diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,429 @@
1
+ # Copyright 2024 DeepMind Technologies Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Pytorch neural network definitions."""
17
+
18
+ from typing import Sequence, Union
19
+
20
+ import torch
21
+ from torch import nn
22
+ import torch.nn.functional as F
23
+
24
+ from .utils import Conv2dSamePadding
25
+
26
+
27
+ class ExtraConvBlock(nn.Module):
28
+ """Additional convolution block."""
29
+
30
+ def __init__(
31
+ self,
32
+ channel_dim,
33
+ channel_multiplier,
34
+ ):
35
+ super().__init__()
36
+ self.channel_dim = channel_dim
37
+ self.channel_multiplier = channel_multiplier
38
+
39
+ self.layer_norm = nn.LayerNorm(
40
+ normalized_shape=channel_dim, elementwise_affine=True, bias=True
41
+ )
42
+ self.conv = nn.Conv2d(
43
+ self.channel_dim,
44
+ self.channel_dim * self.channel_multiplier,
45
+ kernel_size=3,
46
+ stride=1,
47
+ padding=1,
48
+ )
49
+ self.conv_1 = nn.Conv2d(
50
+ self.channel_dim * self.channel_multiplier,
51
+ self.channel_dim,
52
+ kernel_size=3,
53
+ stride=1,
54
+ padding=1,
55
+ )
56
+
57
+ def forward(self, x):
58
+ x = self.layer_norm(x)
59
+ x = x.permute(0, 3, 1, 2)
60
+ res = self.conv(x)
61
+ res = F.gelu(res, approximate='tanh')
62
+ x = x + self.conv_1(res)
63
+ x = x.permute(0, 2, 3, 1)
64
+ return x
65
+
66
+
67
+ class ExtraConvs(nn.Module):
68
+ """Additional CNN."""
69
+
70
+ def __init__(
71
+ self,
72
+ num_layers=5,
73
+ channel_dim=256,
74
+ channel_multiplier=4,
75
+ ):
76
+ super().__init__()
77
+ self.num_layers = num_layers
78
+ self.channel_dim = channel_dim
79
+ self.channel_multiplier = channel_multiplier
80
+
81
+ self.blocks = nn.ModuleList()
82
+ for _ in range(self.num_layers):
83
+ self.blocks.append(
84
+ ExtraConvBlock(self.channel_dim, self.channel_multiplier)
85
+ )
86
+
87
+ def forward(self, x):
88
+ for block in self.blocks:
89
+ x = block(x)
90
+
91
+ return x
92
+
93
+
94
+ class ConvChannelsMixer(nn.Module):
95
+ """Linear activation block for PIPs's MLP Mixer."""
96
+
97
+ def __init__(self, in_channels):
98
+ super().__init__()
99
+ self.mlp2_up = nn.Linear(in_channels, in_channels * 4)
100
+ self.mlp2_down = nn.Linear(in_channels * 4, in_channels)
101
+
102
+ def forward(self, x):
103
+ x = self.mlp2_up(x)
104
+ x = F.gelu(x, approximate='tanh')
105
+ x = self.mlp2_down(x)
106
+ return x
107
+
108
+
109
+ class PIPsConvBlock(nn.Module):
110
+ """Convolutional block for PIPs's MLP Mixer."""
111
+
112
+ def __init__(
113
+ self, in_channels, kernel_shape=3, use_causal_conv=False, block_idx=None
114
+ ):
115
+ super().__init__()
116
+ self.use_causal_conv = use_causal_conv
117
+ self.block_name = f'block_{block_idx}'
118
+ self.kernel_shape = kernel_shape
119
+
120
+ self.layer_norm = nn.LayerNorm(
121
+ normalized_shape=in_channels, elementwise_affine=True, bias=False
122
+ )
123
+ self.mlp1_up = nn.Conv1d(
124
+ in_channels,
125
+ in_channels * 4,
126
+ kernel_shape,
127
+ stride=1,
128
+ padding=0 if self.use_causal_conv else 1,
129
+ groups=in_channels,
130
+ )
131
+
132
+ self.mlp1_up_1 = nn.Conv1d(
133
+ in_channels * 4,
134
+ in_channels * 4,
135
+ kernel_shape,
136
+ stride=1,
137
+ padding=0 if self.use_causal_conv else 1,
138
+ groups=in_channels * 4,
139
+ )
140
+ self.layer_norm_1 = nn.LayerNorm(
141
+ normalized_shape=in_channels, elementwise_affine=True, bias=False
142
+ )
143
+ self.conv_channels_mixer = ConvChannelsMixer(in_channels)
144
+
145
+ def forward(self, x, causal_context=None, get_causal_context=False):
146
+ to_skip = x
147
+ x = self.layer_norm(x)
148
+ new_causal_context = {}
149
+ num_extra = 0
150
+
151
+ if causal_context is not None:
152
+ name1 = self.block_name + '_causal_1'
153
+ x = torch.cat([causal_context[name1], x], dim=-2)
154
+ num_extra = causal_context[name1].shape[-2]
155
+ new_causal_context[name1] = x[..., -(self.kernel_shape - 1) :, :]
156
+
157
+ x = x.permute(0, 2, 1)
158
+ if self.use_causal_conv:
159
+ x = F.pad(x, (2, 0))
160
+ x = self.mlp1_up(x)
161
+
162
+ x = F.gelu(x, approximate='tanh')
163
+
164
+ if causal_context is not None:
165
+ x = x.permute(0, 2, 1)
166
+ name2 = self.block_name + '_causal_2'
167
+ num_extra = causal_context[name2].shape[-2]
168
+ x = torch.cat([causal_context[name2], x[..., num_extra:, :]], dim=-2)
169
+ new_causal_context[name2] = x[..., -(self.kernel_shape - 1) :, :]
170
+ x = x.permute(0, 2, 1)
171
+
172
+ if self.use_causal_conv:
173
+ x = F.pad(x, (2, 0))
174
+ x = self.mlp1_up_1(x)
175
+ x = x.permute(0, 2, 1)
176
+
177
+ if causal_context is not None:
178
+ x = x[..., num_extra:, :]
179
+
180
+ x = x[..., 0::4] + x[..., 1::4] + x[..., 2::4] + x[..., 3::4]
181
+
182
+ x = x + to_skip
183
+ to_skip = x
184
+ x = self.layer_norm_1(x)
185
+ x = self.conv_channels_mixer(x)
186
+
187
+ x = x + to_skip
188
+ return x, new_causal_context
189
+
190
+
191
+ class PIPSMLPMixer(nn.Module):
192
+ """Depthwise-conv version of PIPs's MLP Mixer."""
193
+
194
+ def __init__(
195
+ self,
196
+ input_channels: int,
197
+ output_channels: int,
198
+ hidden_dim: int = 512,
199
+ num_blocks: int = 12,
200
+ kernel_shape: int = 3,
201
+ use_causal_conv: bool = False,
202
+ ):
203
+ """Inits Mixer module.
204
+
205
+ A depthwise-convolutional version of a MLP Mixer for processing images.
206
+
207
+ Args:
208
+ input_channels (int): The number of input channels.
209
+ output_channels (int): The number of output channels.
210
+ hidden_dim (int, optional): The dimension of the hidden layer. Defaults
211
+ to 512.
212
+ num_blocks (int, optional): The number of convolution blocks in the
213
+ mixer. Defaults to 12.
214
+ kernel_shape (int, optional): The size of the kernel in the convolution
215
+ blocks. Defaults to 3.
216
+ use_causal_conv (bool, optional): Whether to use causal convolutions.
217
+ Defaults to False.
218
+ """
219
+
220
+ super().__init__()
221
+ self.hidden_dim = hidden_dim
222
+ self.num_blocks = num_blocks
223
+ self.use_causal_conv = use_causal_conv
224
+ self.linear = nn.Linear(input_channels, self.hidden_dim)
225
+ self.layer_norm = nn.LayerNorm(
226
+ normalized_shape=hidden_dim, elementwise_affine=True, bias=False
227
+ )
228
+ self.linear_1 = nn.Linear(hidden_dim, output_channels)
229
+ self.blocks = nn.ModuleList([
230
+ PIPsConvBlock(
231
+ hidden_dim, kernel_shape, self.use_causal_conv, block_idx=i
232
+ )
233
+ for i in range(num_blocks)
234
+ ])
235
+
236
+ def forward(self, x, causal_context=None, get_causal_context=False):
237
+ x = self.linear(x)
238
+ all_causal_context = {}
239
+ for block in self.blocks:
240
+ x, new_causal_context = block(x, causal_context, get_causal_context)
241
+ if get_causal_context:
242
+ all_causal_context.update(new_causal_context)
243
+
244
+ x = self.layer_norm(x)
245
+ x = self.linear_1(x)
246
+ return x, all_causal_context
247
+
248
+
249
+ class BlockV2(nn.Module):
250
+ """ResNet V2 block."""
251
+
252
+ def __init__(
253
+ self,
254
+ channels_in: int,
255
+ channels_out: int,
256
+ stride: Union[int, Sequence[int]],
257
+ use_projection: bool,
258
+ ):
259
+ super().__init__()
260
+ self.padding = (1, 1, 1, 1)
261
+ # Handle assymetric padding created by padding="SAME" in JAX/LAX
262
+ if stride == 1:
263
+ self.padding = (1, 1, 1, 1)
264
+ elif stride == 2:
265
+ self.padding = (0, 2, 0, 2)
266
+ else:
267
+ raise ValueError(
268
+ 'Check correct padding using padtype_to_padsin jax._src.lax.lax'
269
+ )
270
+
271
+ self.use_projection = use_projection
272
+ if self.use_projection:
273
+ self.proj_conv = Conv2dSamePadding(
274
+ in_channels=channels_in,
275
+ out_channels=channels_out,
276
+ kernel_size=1,
277
+ stride=stride,
278
+ padding=0,
279
+ bias=False,
280
+ )
281
+
282
+ self.bn_0 = nn.InstanceNorm2d(
283
+ num_features=channels_in,
284
+ eps=1e-05,
285
+ momentum=0.1,
286
+ affine=True,
287
+ track_running_stats=False,
288
+ )
289
+ self.conv_0 = Conv2dSamePadding(
290
+ in_channels=channels_in,
291
+ out_channels=channels_out,
292
+ kernel_size=3,
293
+ stride=stride,
294
+ padding=0,
295
+ bias=False,
296
+ )
297
+
298
+ self.conv_1 = Conv2dSamePadding(
299
+ in_channels=channels_out,
300
+ out_channels=channels_out,
301
+ kernel_size=3,
302
+ stride=1,
303
+ padding=1,
304
+ bias=False,
305
+ )
306
+ self.bn_1 = nn.InstanceNorm2d(
307
+ num_features=channels_out,
308
+ eps=1e-05,
309
+ momentum=0.1,
310
+ affine=True,
311
+ track_running_stats=False,
312
+ )
313
+
314
+ def forward(self, inputs):
315
+ x = shortcut = inputs
316
+
317
+ x = self.bn_0(x)
318
+ x = torch.relu(x)
319
+ if self.use_projection:
320
+ shortcut = self.proj_conv(x)
321
+
322
+ x = self.conv_0(x)
323
+
324
+ x = self.bn_1(x)
325
+ x = torch.relu(x)
326
+ # no issues with padding here as this layer always has stride 1
327
+ x = self.conv_1(x)
328
+
329
+ return x + shortcut
330
+
331
+
332
+ class BlockGroup(nn.Module):
333
+ """Higher level block for ResNet implementation."""
334
+
335
+ def __init__(
336
+ self,
337
+ channels_in: int,
338
+ channels_out: int,
339
+ num_blocks: int,
340
+ stride: Union[int, Sequence[int]],
341
+ use_projection: bool,
342
+ ):
343
+ super().__init__()
344
+ blocks = []
345
+ for i in range(num_blocks):
346
+ blocks.append(
347
+ BlockV2(
348
+ channels_in=channels_in if i == 0 else channels_out,
349
+ channels_out=channels_out,
350
+ stride=(1 if i else stride),
351
+ use_projection=(i == 0 and use_projection),
352
+ )
353
+ )
354
+ self.blocks = nn.ModuleList(blocks)
355
+
356
+ def forward(self, inputs):
357
+ out = inputs
358
+ for block in self.blocks:
359
+ out = block(out)
360
+ return out
361
+
362
+
363
+ class ResNet(nn.Module):
364
+ """ResNet model."""
365
+
366
+ def __init__(
367
+ self,
368
+ blocks_per_group: Sequence[int],
369
+ channels_per_group: Sequence[int] = (64, 128, 256, 512),
370
+ use_projection: Sequence[bool] = (True, True, True, True),
371
+ strides: Sequence[int] = (1, 2, 2, 2),
372
+ ):
373
+ """Initializes a ResNet model with customizable layers and configurations.
374
+
375
+ This constructor allows defining the architecture of a ResNet model by
376
+ setting the number of blocks, channels, projection usage, and strides for
377
+ each group of blocks within the network. It provides flexibility in
378
+ creating various ResNet configurations.
379
+
380
+ Args:
381
+ blocks_per_group: A sequence of 4 integers, each indicating the number
382
+ of residual blocks in each group.
383
+ channels_per_group: A sequence of 4 integers, each specifying the number
384
+ of output channels for the blocks in each group. Defaults to (64, 128,
385
+ 256, 512).
386
+ use_projection: A sequence of 4 booleans, each indicating whether to use
387
+ a projection shortcut (True) or an identity shortcut (False) in each
388
+ group. Defaults to (True, True, True, True).
389
+ strides: A sequence of 4 integers, each specifying the stride size for
390
+ the convolutions in each group. Defaults to (1, 2, 2, 2).
391
+
392
+ The ResNet model created will have 4 groups, with each group's
393
+ architecture defined by the corresponding elements in these sequences.
394
+ """
395
+ super().__init__()
396
+
397
+ self.initial_conv = Conv2dSamePadding(
398
+ in_channels=3,
399
+ out_channels=channels_per_group[0],
400
+ kernel_size=(7, 7),
401
+ stride=2,
402
+ padding=0,
403
+ bias=False,
404
+ )
405
+
406
+ block_groups = []
407
+ for i, _ in enumerate(strides):
408
+ block_groups.append(
409
+ BlockGroup(
410
+ channels_in=channels_per_group[i - 1] if i > 0 else 64,
411
+ channels_out=channels_per_group[i],
412
+ num_blocks=blocks_per_group[i],
413
+ stride=strides[i],
414
+ use_projection=use_projection[i],
415
+ )
416
+ )
417
+ self.block_groups = nn.ModuleList(block_groups)
418
+
419
+ def forward(self, inputs):
420
+ result = {}
421
+ out = inputs
422
+ out = self.initial_conv(out)
423
+ result['initial_conv'] = out
424
+
425
+ for block_id, block_group in enumerate(self.block_groups):
426
+ out = block_group(out)
427
+ result[f'resnet_unit_{block_id}'] = out
428
+
429
+ return result