dagloop5 commited on
Commit
2070802
·
verified ·
1 Parent(s): 8183acc

Upload film_net.py

Browse files
Files changed (1) hide show
  1. film_net.py +270 -0
film_net.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FILM: Frame Interpolation for Large Motion (ECCV 2022).
2
+
3
+ Vendored verbatim from ComfyUI (`comfy_extras/frame_interpolation_models/film_net.py`,
4
+ https://github.com/comfyanonymous/ComfyUI, GPL-3.0) apart from the two lines below: ComfyUI's
5
+ `comfy.ops.disable_weight_init` is only `torch.nn` with the parameter initialisers turned into no-ops, and this Space
6
+ loads a checkpoint over every parameter anyway, so plain `torch.nn` is a drop-in.
7
+
8
+ This is the `FrameInterpolate` half of the PlagueKind workflow, which runs `film_net_fp16.safetensors`
9
+ (`Comfy-Org/frame_interpolation`) at multiplier 2 to take MiniMax-H3's 24 fps output to 48 fps.
10
+
11
+ Because of this file the Space as a whole is GPL-3.0.
12
+ """
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+
18
+ ops = nn
19
+
20
+
21
+ class FilmConv2d(nn.Module):
22
+ """Conv2d with optional LeakyReLU and FILM-style padding."""
23
+
24
+ def __init__(self, in_channels, out_channels, size, activation=True, device=None, dtype=None, operations=ops):
25
+ super().__init__()
26
+ self.even_pad = not size % 2
27
+ self.conv = operations.Conv2d(in_channels, out_channels, kernel_size=size, padding=size // 2 if size % 2 else 0, device=device, dtype=dtype)
28
+ self.activation = nn.LeakyReLU(0.2) if activation else None
29
+
30
+ def forward(self, x):
31
+ if self.even_pad:
32
+ x = F.pad(x, (0, 1, 0, 1))
33
+ x = self.conv(x)
34
+ if self.activation is not None:
35
+ x = self.activation(x)
36
+ return x
37
+
38
+
39
+ def _warp_core(image, flow, grid_x, grid_y):
40
+ dtype = image.dtype
41
+ H, W = flow.shape[2], flow.shape[3]
42
+ dx = flow[:, 0].float() / (W * 0.5)
43
+ dy = flow[:, 1].float() / (H * 0.5)
44
+ grid = torch.stack([grid_x[None, None, :] + dx, grid_y[None, :, None] + dy], dim=3)
45
+ return F.grid_sample(image.float(), grid, mode="bilinear", padding_mode="border", align_corners=False).to(dtype)
46
+
47
+
48
+ def build_image_pyramid(image, pyramid_levels):
49
+ pyramid = [image]
50
+ for _ in range(1, pyramid_levels):
51
+ image = F.avg_pool2d(image, 2, 2)
52
+ pyramid.append(image)
53
+ return pyramid
54
+
55
+
56
+ def flow_pyramid_synthesis(residual_pyramid):
57
+ flow = residual_pyramid[-1]
58
+ flow_pyramid = [flow]
59
+ for residual_flow in residual_pyramid[:-1][::-1]:
60
+ flow = F.interpolate(flow, size=residual_flow.shape[2:4], mode="bilinear", scale_factor=None).mul_(2).add_(residual_flow)
61
+ flow_pyramid.append(flow)
62
+ flow_pyramid.reverse()
63
+ return flow_pyramid
64
+
65
+
66
+ def multiply_pyramid(pyramid, scalar):
67
+ return [image * scalar[:, None, None, None] for image in pyramid]
68
+
69
+
70
+ def pyramid_warp(feature_pyramid, flow_pyramid, warp_fn):
71
+ return [warp_fn(features, flow) for features, flow in zip(feature_pyramid, flow_pyramid)]
72
+
73
+
74
+ def concatenate_pyramids(pyramid1, pyramid2):
75
+ return [torch.cat([f1, f2], dim=1) for f1, f2 in zip(pyramid1, pyramid2)]
76
+
77
+
78
+ class SubTreeExtractor(nn.Module):
79
+ def __init__(self, in_channels=3, channels=64, n_layers=4, device=None, dtype=None, operations=ops):
80
+ super().__init__()
81
+ convs = []
82
+ for i in range(n_layers):
83
+ out_ch = channels << i
84
+ convs.append(nn.Sequential(
85
+ FilmConv2d(in_channels, out_ch, 3, device=device, dtype=dtype, operations=operations),
86
+ FilmConv2d(out_ch, out_ch, 3, device=device, dtype=dtype, operations=operations)))
87
+ in_channels = out_ch
88
+ self.convs = nn.ModuleList(convs)
89
+
90
+ def forward(self, image, n):
91
+ head = image
92
+ pyramid = []
93
+ for i, layer in enumerate(self.convs):
94
+ head = layer(head)
95
+ pyramid.append(head)
96
+ if i < n - 1:
97
+ head = F.avg_pool2d(head, 2, 2)
98
+ return pyramid
99
+
100
+
101
+ class FeatureExtractor(nn.Module):
102
+ def __init__(self, in_channels=3, channels=64, sub_levels=4, device=None, dtype=None, operations=ops):
103
+ super().__init__()
104
+ self.extract_sublevels = SubTreeExtractor(in_channels, channels, sub_levels, device=device, dtype=dtype, operations=operations)
105
+ self.sub_levels = sub_levels
106
+
107
+ def forward(self, image_pyramid):
108
+ sub_pyramids = [self.extract_sublevels(image_pyramid[i], min(len(image_pyramid) - i, self.sub_levels))
109
+ for i in range(len(image_pyramid))]
110
+ feature_pyramid = []
111
+ for i in range(len(image_pyramid)):
112
+ features = sub_pyramids[i][0]
113
+ for j in range(1, self.sub_levels):
114
+ if j <= i:
115
+ features = torch.cat([features, sub_pyramids[i - j][j]], dim=1)
116
+ feature_pyramid.append(features)
117
+ # Free sub-pyramids no longer needed by future levels
118
+ if i >= self.sub_levels - 1:
119
+ sub_pyramids[i - self.sub_levels + 1] = None
120
+ return feature_pyramid
121
+
122
+
123
+ class FlowEstimator(nn.Module):
124
+ def __init__(self, in_channels, num_convs, num_filters, device=None, dtype=None, operations=ops):
125
+ super().__init__()
126
+ self._convs = nn.ModuleList()
127
+ for _ in range(num_convs):
128
+ self._convs.append(FilmConv2d(in_channels, num_filters, 3, device=device, dtype=dtype, operations=operations))
129
+ in_channels = num_filters
130
+ self._convs.append(FilmConv2d(in_channels, num_filters // 2, 1, device=device, dtype=dtype, operations=operations))
131
+ self._convs.append(FilmConv2d(num_filters // 2, 2, 1, activation=False, device=device, dtype=dtype, operations=operations))
132
+
133
+ def forward(self, features_a, features_b):
134
+ net = torch.cat([features_a, features_b], dim=1)
135
+ for conv in self._convs:
136
+ net = conv(net)
137
+ return net
138
+
139
+
140
+ class PyramidFlowEstimator(nn.Module):
141
+ def __init__(self, filters=64, flow_convs=(3, 3, 3, 3), flow_filters=(32, 64, 128, 256), device=None, dtype=None, operations=ops):
142
+ super().__init__()
143
+ in_channels = filters << 1
144
+ predictors = []
145
+ for i in range(len(flow_convs)):
146
+ predictors.append(FlowEstimator(in_channels, flow_convs[i], flow_filters[i], device=device, dtype=dtype, operations=operations))
147
+ in_channels += filters << (i + 2)
148
+ self._predictor = predictors[-1]
149
+ self._predictors = nn.ModuleList(predictors[:-1][::-1])
150
+
151
+ def forward(self, feature_pyramid_a, feature_pyramid_b, warp_fn):
152
+ levels = len(feature_pyramid_a)
153
+ v = self._predictor(feature_pyramid_a[-1], feature_pyramid_b[-1])
154
+ residuals = [v]
155
+ # Coarse-to-fine: shared predictor for deep levels, then specialized predictors for fine levels
156
+ steps = [(i, self._predictor) for i in range(levels - 2, len(self._predictors) - 1, -1)]
157
+ steps += [(len(self._predictors) - 1 - k, p) for k, p in enumerate(self._predictors)]
158
+ for i, predictor in steps:
159
+ v = F.interpolate(v, size=feature_pyramid_a[i].shape[2:4], mode="bilinear").mul_(2)
160
+ v_residual = predictor(feature_pyramid_a[i], warp_fn(feature_pyramid_b[i], v))
161
+ residuals.append(v_residual)
162
+ v = v.add_(v_residual)
163
+ residuals.reverse()
164
+ return residuals
165
+
166
+
167
+ def _get_fusion_channels(level, filters):
168
+ # Per direction: multi-scale features + RGB image (3ch) + flow (2ch), doubled for both directions
169
+ return (sum(filters << i for i in range(level)) + 3 + 2) * 2
170
+
171
+
172
+ class Fusion(nn.Module):
173
+ def __init__(self, n_layers=4, specialized_layers=3, filters=64, device=None, dtype=None, operations=ops):
174
+ super().__init__()
175
+ self.output_conv = operations.Conv2d(filters, 3, kernel_size=1, device=device, dtype=dtype)
176
+ self.convs = nn.ModuleList()
177
+ in_channels = _get_fusion_channels(n_layers, filters)
178
+ increase = 0
179
+ for i in range(n_layers)[::-1]:
180
+ num_filters = (filters << i) if i < specialized_layers else (filters << specialized_layers)
181
+ self.convs.append(nn.ModuleList([
182
+ FilmConv2d(in_channels, num_filters, 2, activation=False, device=device, dtype=dtype, operations=operations),
183
+ FilmConv2d(in_channels + (increase or num_filters), num_filters, 3, device=device, dtype=dtype, operations=operations),
184
+ FilmConv2d(num_filters, num_filters, 3, device=device, dtype=dtype, operations=operations)]))
185
+ in_channels = num_filters
186
+ increase = _get_fusion_channels(i, filters) - num_filters // 2
187
+
188
+ def forward(self, pyramid):
189
+ net = pyramid[-1]
190
+ for k, layers in enumerate(self.convs):
191
+ i = len(self.convs) - 1 - k
192
+ net = layers[0](F.interpolate(net, size=pyramid[i].shape[2:4], mode="nearest"))
193
+ net = layers[2](layers[1](torch.cat([pyramid[i], net], dim=1)))
194
+ return self.output_conv(net)
195
+
196
+
197
+ class FILMNet(nn.Module):
198
+ def __init__(self, pyramid_levels=7, fusion_pyramid_levels=5, specialized_levels=3, sub_levels=4,
199
+ filters=64, flow_convs=(3, 3, 3, 3), flow_filters=(32, 64, 128, 256), device=None, dtype=None, operations=ops):
200
+ super().__init__()
201
+ self.pyramid_levels = pyramid_levels
202
+ self.fusion_pyramid_levels = fusion_pyramid_levels
203
+ self.extract = FeatureExtractor(3, filters, sub_levels, device=device, dtype=dtype, operations=operations)
204
+ self.predict_flow = PyramidFlowEstimator(filters, flow_convs, flow_filters, device=device, dtype=dtype, operations=operations)
205
+ self.fuse = Fusion(sub_levels, specialized_levels, filters, device=device, dtype=dtype, operations=operations)
206
+ self._warp_grids = {}
207
+
208
+ def get_dtype(self):
209
+ return self.extract.extract_sublevels.convs[0][0].conv.weight.dtype
210
+
211
+ def memory_used_forward(self, shape, dtype):
212
+ return 1700 * shape[1] * shape[2] * dtype.itemsize
213
+
214
+ def _build_warp_grids(self, H, W, device):
215
+ """Pre-compute warp grids for all pyramid levels."""
216
+ if (H, W) in self._warp_grids:
217
+ return
218
+ self._warp_grids = {} # clear old resolution grids to prevent memory leaks
219
+ for _ in range(self.pyramid_levels):
220
+ self._warp_grids[(H, W)] = (
221
+ torch.linspace(-(1 - 1 / W), 1 - 1 / W, W, dtype=torch.float32, device=device),
222
+ torch.linspace(-(1 - 1 / H), 1 - 1 / H, H, dtype=torch.float32, device=device),
223
+ )
224
+ H, W = H // 2, W // 2
225
+
226
+ def warp(self, image, flow):
227
+ grid_x, grid_y = self._warp_grids[(flow.shape[2], flow.shape[3])]
228
+ return _warp_core(image, flow, grid_x, grid_y)
229
+
230
+ def extract_features(self, img):
231
+ """Extract image and feature pyramids for a single frame. Can be cached across pairs."""
232
+ image_pyramid = build_image_pyramid(img, self.pyramid_levels)
233
+ feature_pyramid = self.extract(image_pyramid)
234
+ return image_pyramid, feature_pyramid
235
+
236
+ def forward(self, img0, img1, timestep=0.5, cache=None):
237
+ # FILM uses a scalar timestep per batch element (spatially-varying timesteps not supported)
238
+ t = timestep.mean(dim=(1, 2, 3)).item() if isinstance(timestep, torch.Tensor) else timestep
239
+ return self.forward_multi_timestep(img0, img1, [t], cache=cache)
240
+
241
+ def forward_multi_timestep(self, img0, img1, timesteps, cache=None):
242
+ """Compute flow once, synthesize at multiple timesteps. Expects batch=1 inputs."""
243
+ self._build_warp_grids(img0.shape[2], img0.shape[3], img0.device)
244
+
245
+ image_pyr0, feat_pyr0 = cache["img0"] if cache and "img0" in cache else self.extract_features(img0)
246
+ image_pyr1, feat_pyr1 = cache["img1"] if cache and "img1" in cache else self.extract_features(img1)
247
+
248
+ fwd_flow = flow_pyramid_synthesis(self.predict_flow(feat_pyr0, feat_pyr1, self.warp))[:self.fusion_pyramid_levels]
249
+ bwd_flow = flow_pyramid_synthesis(self.predict_flow(feat_pyr1, feat_pyr0, self.warp))[:self.fusion_pyramid_levels]
250
+
251
+ # Build warp targets and free full pyramids (only first fpl levels needed from here)
252
+ fpl = self.fusion_pyramid_levels
253
+ p2w = [concatenate_pyramids(image_pyr0[:fpl], feat_pyr0[:fpl]),
254
+ concatenate_pyramids(image_pyr1[:fpl], feat_pyr1[:fpl])]
255
+ del image_pyr0, image_pyr1, feat_pyr0, feat_pyr1
256
+
257
+ results = []
258
+ dt_tensors = torch.tensor(timesteps, device=img0.device, dtype=img0.dtype)
259
+ for idx in range(len(timesteps)):
260
+ batch_dt = dt_tensors[idx:idx + 1]
261
+ bwd_scaled = multiply_pyramid(bwd_flow, batch_dt)
262
+ fwd_scaled = multiply_pyramid(fwd_flow, 1 - batch_dt)
263
+ fwd_warped = pyramid_warp(p2w[0], bwd_scaled, self.warp)
264
+ bwd_warped = pyramid_warp(p2w[1], fwd_scaled, self.warp)
265
+ aligned = [torch.cat([fw, bw, bf, ff], dim=1)
266
+ for fw, bw, bf, ff in zip(fwd_warped, bwd_warped, bwd_scaled, fwd_scaled)]
267
+ del fwd_warped, bwd_warped, bwd_scaled, fwd_scaled
268
+ results.append(self.fuse(aligned))
269
+ del aligned
270
+ return torch.cat(results, dim=0)