samarth-ht commited on
Commit
ac37772
Β·
1 Parent(s): 5e8dc4f

files rearranged

Browse files
Files changed (49) hide show
  1. {data β†’ latentsync/data}/syncnet_dataset.py +0 -0
  2. {data β†’ latentsync/data}/unet_dataset.py +0 -0
  3. latentsync/models/attention.py +492 -0
  4. latentsync/models/motion_module.py +332 -0
  5. latentsync/models/resnet.py +234 -0
  6. latentsync/models/syncnet.py +233 -0
  7. latentsync/models/syncnet_wav2lip.py +90 -0
  8. latentsync/models/unet.py +528 -0
  9. latentsync/models/unet_blocks.py +903 -0
  10. latentsync/models/utils.py +19 -0
  11. {pipelines β†’ latentsync/pipelines}/lipsync_pipeline.py +0 -0
  12. {trepa β†’ latentsync/trepa}/__init__.py +0 -0
  13. {trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/__init__.py +0 -0
  14. {trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/utils.py +0 -0
  15. {trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/videomaev2_finetune.py +0 -0
  16. {trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/videomaev2_pretrain.py +0 -0
  17. {trepa β†’ latentsync/trepa}/third_party/__init__.py +0 -0
  18. {trepa β†’ latentsync/trepa}/utils/__init__.py +0 -0
  19. {trepa β†’ latentsync/trepa}/utils/data_utils.py +0 -0
  20. {trepa β†’ latentsync/trepa}/utils/metric_utils.py +0 -0
  21. {utils β†’ latentsync/utils}/affine_transform.py +0 -0
  22. {utils β†’ latentsync/utils}/audio.py +0 -0
  23. {utils β†’ latentsync/utils}/av_reader.py +0 -0
  24. {utils β†’ latentsync/utils}/image_processor.py +0 -0
  25. latentsync/utils/mask.png +0 -0
  26. {utils β†’ latentsync/utils}/util.py +0 -0
  27. {whisper β†’ latentsync/whisper}/audio2feature.py +0 -0
  28. {whisper β†’ latentsync/whisper}/whisper/__init__.py +0 -0
  29. {whisper β†’ latentsync/whisper}/whisper/__main__.py +0 -0
  30. {whisper β†’ latentsync/whisper}/whisper/assets/gpt2/merges.txt +0 -0
  31. {whisper β†’ latentsync/whisper}/whisper/assets/gpt2/special_tokens_map.json +0 -0
  32. {whisper β†’ latentsync/whisper}/whisper/assets/gpt2/tokenizer_config.json +0 -0
  33. {whisper β†’ latentsync/whisper}/whisper/assets/gpt2/vocab.json +0 -0
  34. {whisper β†’ latentsync/whisper}/whisper/assets/mel_filters.npz +0 -0
  35. {whisper β†’ latentsync/whisper}/whisper/assets/multilingual/added_tokens.json +0 -0
  36. {whisper β†’ latentsync/whisper}/whisper/assets/multilingual/merges.txt +0 -0
  37. {whisper β†’ latentsync/whisper}/whisper/assets/multilingual/special_tokens_map.json +0 -0
  38. {whisper β†’ latentsync/whisper}/whisper/assets/multilingual/tokenizer_config.json +0 -0
  39. {whisper β†’ latentsync/whisper}/whisper/assets/multilingual/vocab.json +0 -0
  40. {whisper β†’ latentsync/whisper}/whisper/audio.py +0 -0
  41. {whisper β†’ latentsync/whisper}/whisper/decoding.py +0 -0
  42. {whisper β†’ latentsync/whisper}/whisper/model.py +0 -0
  43. {whisper β†’ latentsync/whisper}/whisper/normalizers/__init__.py +0 -0
  44. {whisper β†’ latentsync/whisper}/whisper/normalizers/basic.py +0 -0
  45. {whisper β†’ latentsync/whisper}/whisper/normalizers/english.json +0 -0
  46. {whisper β†’ latentsync/whisper}/whisper/normalizers/english.py +0 -0
  47. {whisper β†’ latentsync/whisper}/whisper/tokenizer.py +0 -0
  48. {whisper β†’ latentsync/whisper}/whisper/transcribe.py +0 -0
  49. {whisper β†’ latentsync/whisper}/whisper/utils.py +0 -0
{data β†’ latentsync/data}/syncnet_dataset.py RENAMED
File without changes
{data β†’ latentsync/data}/unet_dataset.py RENAMED
File without changes
latentsync/models/attention.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
2
+
3
+ from dataclasses import dataclass
4
+ from turtle import forward
5
+ from typing import Optional
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.modeling_utils import ModelMixin
13
+ from diffusers.utils import BaseOutput
14
+ from diffusers.utils.import_utils import is_xformers_available
15
+ from diffusers.models.attention import CrossAttention, FeedForward, AdaLayerNorm
16
+
17
+ from einops import rearrange, repeat
18
+ from .utils import zero_module
19
+
20
+
21
+ @dataclass
22
+ class Transformer3DModelOutput(BaseOutput):
23
+ sample: torch.FloatTensor
24
+
25
+
26
+ if is_xformers_available():
27
+ import xformers
28
+ import xformers.ops
29
+ else:
30
+ xformers = None
31
+
32
+
33
+ class Transformer3DModel(ModelMixin, ConfigMixin):
34
+ @register_to_config
35
+ def __init__(
36
+ self,
37
+ num_attention_heads: int = 16,
38
+ attention_head_dim: int = 88,
39
+ in_channels: Optional[int] = None,
40
+ num_layers: int = 1,
41
+ dropout: float = 0.0,
42
+ norm_num_groups: int = 32,
43
+ cross_attention_dim: Optional[int] = None,
44
+ attention_bias: bool = False,
45
+ activation_fn: str = "geglu",
46
+ num_embeds_ada_norm: Optional[int] = None,
47
+ use_linear_projection: bool = False,
48
+ only_cross_attention: bool = False,
49
+ upcast_attention: bool = False,
50
+ use_motion_module: bool = False,
51
+ unet_use_cross_frame_attention=None,
52
+ unet_use_temporal_attention=None,
53
+ add_audio_layer=False,
54
+ audio_condition_method="cross_attn",
55
+ custom_audio_layer: bool = False,
56
+ ):
57
+ super().__init__()
58
+ self.use_linear_projection = use_linear_projection
59
+ self.num_attention_heads = num_attention_heads
60
+ self.attention_head_dim = attention_head_dim
61
+ inner_dim = num_attention_heads * attention_head_dim
62
+
63
+ # Define input layers
64
+ self.in_channels = in_channels
65
+
66
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
67
+ if use_linear_projection:
68
+ self.proj_in = nn.Linear(in_channels, inner_dim)
69
+ else:
70
+ self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
71
+
72
+ if not custom_audio_layer:
73
+ # Define transformers blocks
74
+ self.transformer_blocks = nn.ModuleList(
75
+ [
76
+ BasicTransformerBlock(
77
+ inner_dim,
78
+ num_attention_heads,
79
+ attention_head_dim,
80
+ dropout=dropout,
81
+ cross_attention_dim=cross_attention_dim,
82
+ activation_fn=activation_fn,
83
+ num_embeds_ada_norm=num_embeds_ada_norm,
84
+ attention_bias=attention_bias,
85
+ only_cross_attention=only_cross_attention,
86
+ upcast_attention=upcast_attention,
87
+ use_motion_module=use_motion_module,
88
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
89
+ unet_use_temporal_attention=unet_use_temporal_attention,
90
+ add_audio_layer=add_audio_layer,
91
+ custom_audio_layer=custom_audio_layer,
92
+ audio_condition_method=audio_condition_method,
93
+ )
94
+ for d in range(num_layers)
95
+ ]
96
+ )
97
+ else:
98
+ self.transformer_blocks = nn.ModuleList(
99
+ [
100
+ AudioTransformerBlock(
101
+ inner_dim,
102
+ num_attention_heads,
103
+ attention_head_dim,
104
+ dropout=dropout,
105
+ cross_attention_dim=cross_attention_dim,
106
+ activation_fn=activation_fn,
107
+ num_embeds_ada_norm=num_embeds_ada_norm,
108
+ attention_bias=attention_bias,
109
+ only_cross_attention=only_cross_attention,
110
+ upcast_attention=upcast_attention,
111
+ use_motion_module=use_motion_module,
112
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
113
+ unet_use_temporal_attention=unet_use_temporal_attention,
114
+ add_audio_layer=add_audio_layer,
115
+ )
116
+ for d in range(num_layers)
117
+ ]
118
+ )
119
+
120
+ # 4. Define output layers
121
+ if use_linear_projection:
122
+ self.proj_out = nn.Linear(in_channels, inner_dim)
123
+ else:
124
+ self.proj_out = nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
125
+
126
+ if custom_audio_layer:
127
+ self.proj_out = zero_module(self.proj_out)
128
+
129
+ def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, return_dict: bool = True):
130
+ # Input
131
+ assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
132
+ video_length = hidden_states.shape[2]
133
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
134
+
135
+ # No need to do this for audio input, because different audio samples are independent
136
+ # encoder_hidden_states = repeat(encoder_hidden_states, 'b n c -> (b f) n c', f=video_length)
137
+
138
+ batch, channel, height, weight = hidden_states.shape
139
+ residual = hidden_states
140
+
141
+ hidden_states = self.norm(hidden_states)
142
+ if not self.use_linear_projection:
143
+ hidden_states = self.proj_in(hidden_states)
144
+ inner_dim = hidden_states.shape[1]
145
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
146
+ else:
147
+ inner_dim = hidden_states.shape[1]
148
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
149
+ hidden_states = self.proj_in(hidden_states)
150
+
151
+ # Blocks
152
+ for block in self.transformer_blocks:
153
+ hidden_states = block(
154
+ hidden_states,
155
+ encoder_hidden_states=encoder_hidden_states,
156
+ timestep=timestep,
157
+ video_length=video_length,
158
+ )
159
+
160
+ # Output
161
+ if not self.use_linear_projection:
162
+ hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
163
+ hidden_states = self.proj_out(hidden_states)
164
+ else:
165
+ hidden_states = self.proj_out(hidden_states)
166
+ hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
167
+
168
+ output = hidden_states + residual
169
+
170
+ output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
171
+ if not return_dict:
172
+ return (output,)
173
+
174
+ return Transformer3DModelOutput(sample=output)
175
+
176
+
177
+ class BasicTransformerBlock(nn.Module):
178
+ def __init__(
179
+ self,
180
+ dim: int,
181
+ num_attention_heads: int,
182
+ attention_head_dim: int,
183
+ dropout=0.0,
184
+ cross_attention_dim: Optional[int] = None,
185
+ activation_fn: str = "geglu",
186
+ num_embeds_ada_norm: Optional[int] = None,
187
+ attention_bias: bool = False,
188
+ only_cross_attention: bool = False,
189
+ upcast_attention: bool = False,
190
+ use_motion_module: bool = False,
191
+ unet_use_cross_frame_attention=None,
192
+ unet_use_temporal_attention=None,
193
+ add_audio_layer=False,
194
+ custom_audio_layer=False,
195
+ audio_condition_method="cross_attn",
196
+ ):
197
+ super().__init__()
198
+ self.only_cross_attention = only_cross_attention
199
+ self.use_ada_layer_norm = num_embeds_ada_norm is not None
200
+ self.unet_use_cross_frame_attention = unet_use_cross_frame_attention
201
+ self.unet_use_temporal_attention = unet_use_temporal_attention
202
+ self.use_motion_module = use_motion_module
203
+ self.add_audio_layer = add_audio_layer
204
+
205
+ # SC-Attn
206
+ assert unet_use_cross_frame_attention is not None
207
+ if unet_use_cross_frame_attention:
208
+ raise NotImplementedError("SparseCausalAttention2D not implemented yet.")
209
+ else:
210
+ self.attn1 = CrossAttention(
211
+ query_dim=dim,
212
+ heads=num_attention_heads,
213
+ dim_head=attention_head_dim,
214
+ dropout=dropout,
215
+ bias=attention_bias,
216
+ upcast_attention=upcast_attention,
217
+ )
218
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
219
+
220
+ # Cross-Attn
221
+ if add_audio_layer and audio_condition_method == "cross_attn" and not custom_audio_layer:
222
+ self.audio_cross_attn = AudioCrossAttn(
223
+ dim=dim,
224
+ cross_attention_dim=cross_attention_dim,
225
+ num_attention_heads=num_attention_heads,
226
+ attention_head_dim=attention_head_dim,
227
+ dropout=dropout,
228
+ attention_bias=attention_bias,
229
+ upcast_attention=upcast_attention,
230
+ num_embeds_ada_norm=num_embeds_ada_norm,
231
+ use_ada_layer_norm=self.use_ada_layer_norm,
232
+ zero_proj_out=False,
233
+ )
234
+ else:
235
+ self.audio_cross_attn = None
236
+
237
+ # Feed-forward
238
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
239
+ self.norm3 = nn.LayerNorm(dim)
240
+
241
+ # Temp-Attn
242
+ assert unet_use_temporal_attention is not None
243
+ if unet_use_temporal_attention:
244
+ self.attn_temp = CrossAttention(
245
+ query_dim=dim,
246
+ heads=num_attention_heads,
247
+ dim_head=attention_head_dim,
248
+ dropout=dropout,
249
+ bias=attention_bias,
250
+ upcast_attention=upcast_attention,
251
+ )
252
+ nn.init.zeros_(self.attn_temp.to_out[0].weight.data)
253
+ self.norm_temp = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
254
+
255
+ def set_use_memory_efficient_attention_xformers(self, use_memory_efficient_attention_xformers: bool):
256
+ if not is_xformers_available():
257
+ print("Here is how to install it")
258
+ raise ModuleNotFoundError(
259
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
260
+ " xformers",
261
+ name="xformers",
262
+ )
263
+ elif not torch.cuda.is_available():
264
+ raise ValueError(
265
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is only"
266
+ " available for GPU "
267
+ )
268
+ else:
269
+ try:
270
+ # Make sure we can run the memory efficient attention
271
+ _ = xformers.ops.memory_efficient_attention(
272
+ torch.randn((1, 2, 40), device="cuda"),
273
+ torch.randn((1, 2, 40), device="cuda"),
274
+ torch.randn((1, 2, 40), device="cuda"),
275
+ )
276
+ except Exception as e:
277
+ raise e
278
+ self.attn1._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
279
+ if self.audio_cross_attn is not None:
280
+ self.audio_cross_attn.attn._use_memory_efficient_attention_xformers = (
281
+ use_memory_efficient_attention_xformers
282
+ )
283
+ # self.attn_temp._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
284
+
285
+ def forward(
286
+ self, hidden_states, encoder_hidden_states=None, timestep=None, attention_mask=None, video_length=None
287
+ ):
288
+ # SparseCausal-Attention
289
+ norm_hidden_states = (
290
+ self.norm1(hidden_states, timestep) if self.use_ada_layer_norm else self.norm1(hidden_states)
291
+ )
292
+
293
+ # if self.only_cross_attention:
294
+ # hidden_states = (
295
+ # self.attn1(norm_hidden_states, encoder_hidden_states, attention_mask=attention_mask) + hidden_states
296
+ # )
297
+ # else:
298
+ # hidden_states = self.attn1(norm_hidden_states, attention_mask=attention_mask, video_length=video_length) + hidden_states
299
+
300
+ # pdb.set_trace()
301
+ if self.unet_use_cross_frame_attention:
302
+ hidden_states = (
303
+ self.attn1(norm_hidden_states, attention_mask=attention_mask, video_length=video_length)
304
+ + hidden_states
305
+ )
306
+ else:
307
+ hidden_states = self.attn1(norm_hidden_states, attention_mask=attention_mask) + hidden_states
308
+
309
+ if self.audio_cross_attn is not None and encoder_hidden_states is not None:
310
+ hidden_states = self.audio_cross_attn(
311
+ hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
312
+ )
313
+
314
+ # Feed-forward
315
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
316
+
317
+ # Temporal-Attention
318
+ if self.unet_use_temporal_attention:
319
+ d = hidden_states.shape[1]
320
+ hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
321
+ norm_hidden_states = (
322
+ self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)
323
+ )
324
+ hidden_states = self.attn_temp(norm_hidden_states) + hidden_states
325
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
326
+
327
+ return hidden_states
328
+
329
+
330
+ class AudioTransformerBlock(nn.Module):
331
+ def __init__(
332
+ self,
333
+ dim: int,
334
+ num_attention_heads: int,
335
+ attention_head_dim: int,
336
+ dropout=0.0,
337
+ cross_attention_dim: Optional[int] = None,
338
+ activation_fn: str = "geglu",
339
+ num_embeds_ada_norm: Optional[int] = None,
340
+ attention_bias: bool = False,
341
+ only_cross_attention: bool = False,
342
+ upcast_attention: bool = False,
343
+ use_motion_module: bool = False,
344
+ unet_use_cross_frame_attention=None,
345
+ unet_use_temporal_attention=None,
346
+ add_audio_layer=False,
347
+ ):
348
+ super().__init__()
349
+ self.only_cross_attention = only_cross_attention
350
+ self.use_ada_layer_norm = num_embeds_ada_norm is not None
351
+ self.unet_use_cross_frame_attention = unet_use_cross_frame_attention
352
+ self.unet_use_temporal_attention = unet_use_temporal_attention
353
+ self.use_motion_module = use_motion_module
354
+ self.add_audio_layer = add_audio_layer
355
+
356
+ # SC-Attn
357
+ assert unet_use_cross_frame_attention is not None
358
+ if unet_use_cross_frame_attention:
359
+ raise NotImplementedError("SparseCausalAttention2D not implemented yet.")
360
+ else:
361
+ self.attn1 = CrossAttention(
362
+ query_dim=dim,
363
+ heads=num_attention_heads,
364
+ dim_head=attention_head_dim,
365
+ dropout=dropout,
366
+ bias=attention_bias,
367
+ upcast_attention=upcast_attention,
368
+ )
369
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
370
+
371
+ self.audio_cross_attn = AudioCrossAttn(
372
+ dim=dim,
373
+ cross_attention_dim=cross_attention_dim,
374
+ num_attention_heads=num_attention_heads,
375
+ attention_head_dim=attention_head_dim,
376
+ dropout=dropout,
377
+ attention_bias=attention_bias,
378
+ upcast_attention=upcast_attention,
379
+ num_embeds_ada_norm=num_embeds_ada_norm,
380
+ use_ada_layer_norm=self.use_ada_layer_norm,
381
+ zero_proj_out=False,
382
+ )
383
+
384
+ # Feed-forward
385
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
386
+ self.norm3 = nn.LayerNorm(dim)
387
+
388
+ def set_use_memory_efficient_attention_xformers(self, use_memory_efficient_attention_xformers: bool):
389
+ if not is_xformers_available():
390
+ print("Here is how to install it")
391
+ raise ModuleNotFoundError(
392
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
393
+ " xformers",
394
+ name="xformers",
395
+ )
396
+ elif not torch.cuda.is_available():
397
+ raise ValueError(
398
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is only"
399
+ " available for GPU "
400
+ )
401
+ else:
402
+ try:
403
+ # Make sure we can run the memory efficient attention
404
+ _ = xformers.ops.memory_efficient_attention(
405
+ torch.randn((1, 2, 40), device="cuda"),
406
+ torch.randn((1, 2, 40), device="cuda"),
407
+ torch.randn((1, 2, 40), device="cuda"),
408
+ )
409
+ except Exception as e:
410
+ raise e
411
+ self.attn1._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
412
+ if self.audio_cross_attn is not None:
413
+ self.audio_cross_attn.attn._use_memory_efficient_attention_xformers = (
414
+ use_memory_efficient_attention_xformers
415
+ )
416
+ # self.attn_temp._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
417
+
418
+ def forward(
419
+ self, hidden_states, encoder_hidden_states=None, timestep=None, attention_mask=None, video_length=None
420
+ ):
421
+ # SparseCausal-Attention
422
+ norm_hidden_states = (
423
+ self.norm1(hidden_states, timestep) if self.use_ada_layer_norm else self.norm1(hidden_states)
424
+ )
425
+
426
+ # pdb.set_trace()
427
+ if self.unet_use_cross_frame_attention:
428
+ hidden_states = (
429
+ self.attn1(norm_hidden_states, attention_mask=attention_mask, video_length=video_length)
430
+ + hidden_states
431
+ )
432
+ else:
433
+ hidden_states = self.attn1(norm_hidden_states, attention_mask=attention_mask) + hidden_states
434
+
435
+ if self.audio_cross_attn is not None and encoder_hidden_states is not None:
436
+ hidden_states = self.audio_cross_attn(
437
+ hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
438
+ )
439
+
440
+ # Feed-forward
441
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
442
+
443
+ return hidden_states
444
+
445
+
446
+ class AudioCrossAttn(nn.Module):
447
+ def __init__(
448
+ self,
449
+ dim,
450
+ cross_attention_dim,
451
+ num_attention_heads,
452
+ attention_head_dim,
453
+ dropout,
454
+ attention_bias,
455
+ upcast_attention,
456
+ num_embeds_ada_norm,
457
+ use_ada_layer_norm,
458
+ zero_proj_out=False,
459
+ ):
460
+ super().__init__()
461
+
462
+ self.norm = AdaLayerNorm(dim, num_embeds_ada_norm) if use_ada_layer_norm else nn.LayerNorm(dim)
463
+ self.attn = CrossAttention(
464
+ query_dim=dim,
465
+ cross_attention_dim=cross_attention_dim,
466
+ heads=num_attention_heads,
467
+ dim_head=attention_head_dim,
468
+ dropout=dropout,
469
+ bias=attention_bias,
470
+ upcast_attention=upcast_attention,
471
+ )
472
+
473
+ if zero_proj_out:
474
+ self.proj_out = zero_module(nn.Linear(dim, dim))
475
+
476
+ self.zero_proj_out = zero_proj_out
477
+ self.use_ada_layer_norm = use_ada_layer_norm
478
+
479
+ def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, attention_mask=None):
480
+ previous_hidden_states = hidden_states
481
+ hidden_states = self.norm(hidden_states, timestep) if self.use_ada_layer_norm else self.norm(hidden_states)
482
+
483
+ if encoder_hidden_states.dim() == 4:
484
+ encoder_hidden_states = rearrange(encoder_hidden_states, "b f n d -> (b f) n d")
485
+
486
+ hidden_states = self.attn(
487
+ hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
488
+ )
489
+
490
+ if self.zero_proj_out:
491
+ hidden_states = self.proj_out(hidden_states)
492
+ return hidden_states + previous_hidden_states
latentsync/models/motion_module.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/guoyww/AnimateDiff/blob/main/animatediff/models/motion_module.py
2
+
3
+ # Actually we don't use the motion module in the final version of LatentSync
4
+ # When we started the project, we used the codebase of AnimateDiff and tried motion module
5
+ # But the results are poor, and we decied to leave the code here for possible future usage
6
+
7
+ from dataclasses import dataclass
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+
13
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
14
+ from diffusers.modeling_utils import ModelMixin
15
+ from diffusers.utils import BaseOutput
16
+ from diffusers.utils.import_utils import is_xformers_available
17
+ from diffusers.models.attention import CrossAttention, FeedForward
18
+
19
+ from einops import rearrange, repeat
20
+ import math
21
+ from .utils import zero_module
22
+
23
+
24
+ @dataclass
25
+ class TemporalTransformer3DModelOutput(BaseOutput):
26
+ sample: torch.FloatTensor
27
+
28
+
29
+ if is_xformers_available():
30
+ import xformers
31
+ import xformers.ops
32
+ else:
33
+ xformers = None
34
+
35
+
36
+ def get_motion_module(in_channels, motion_module_type: str, motion_module_kwargs: dict):
37
+ if motion_module_type == "Vanilla":
38
+ return VanillaTemporalModule(
39
+ in_channels=in_channels,
40
+ **motion_module_kwargs,
41
+ )
42
+ else:
43
+ raise ValueError
44
+
45
+
46
+ class VanillaTemporalModule(nn.Module):
47
+ def __init__(
48
+ self,
49
+ in_channels,
50
+ num_attention_heads=8,
51
+ num_transformer_block=2,
52
+ attention_block_types=("Temporal_Self", "Temporal_Self"),
53
+ cross_frame_attention_mode=None,
54
+ temporal_position_encoding=False,
55
+ temporal_position_encoding_max_len=24,
56
+ temporal_attention_dim_div=1,
57
+ zero_initialize=True,
58
+ ):
59
+ super().__init__()
60
+
61
+ self.temporal_transformer = TemporalTransformer3DModel(
62
+ in_channels=in_channels,
63
+ num_attention_heads=num_attention_heads,
64
+ attention_head_dim=in_channels // num_attention_heads // temporal_attention_dim_div,
65
+ num_layers=num_transformer_block,
66
+ attention_block_types=attention_block_types,
67
+ cross_frame_attention_mode=cross_frame_attention_mode,
68
+ temporal_position_encoding=temporal_position_encoding,
69
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
70
+ )
71
+
72
+ if zero_initialize:
73
+ self.temporal_transformer.proj_out = zero_module(self.temporal_transformer.proj_out)
74
+
75
+ def forward(self, input_tensor, temb, encoder_hidden_states, attention_mask=None, anchor_frame_idx=None):
76
+ hidden_states = input_tensor
77
+ hidden_states = self.temporal_transformer(hidden_states, encoder_hidden_states, attention_mask)
78
+
79
+ output = hidden_states
80
+ return output
81
+
82
+
83
+ class TemporalTransformer3DModel(nn.Module):
84
+ def __init__(
85
+ self,
86
+ in_channels,
87
+ num_attention_heads,
88
+ attention_head_dim,
89
+ num_layers,
90
+ attention_block_types=(
91
+ "Temporal_Self",
92
+ "Temporal_Self",
93
+ ),
94
+ dropout=0.0,
95
+ norm_num_groups=32,
96
+ cross_attention_dim=768,
97
+ activation_fn="geglu",
98
+ attention_bias=False,
99
+ upcast_attention=False,
100
+ cross_frame_attention_mode=None,
101
+ temporal_position_encoding=False,
102
+ temporal_position_encoding_max_len=24,
103
+ ):
104
+ super().__init__()
105
+
106
+ inner_dim = num_attention_heads * attention_head_dim
107
+
108
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
109
+ self.proj_in = nn.Linear(in_channels, inner_dim)
110
+
111
+ self.transformer_blocks = nn.ModuleList(
112
+ [
113
+ TemporalTransformerBlock(
114
+ dim=inner_dim,
115
+ num_attention_heads=num_attention_heads,
116
+ attention_head_dim=attention_head_dim,
117
+ attention_block_types=attention_block_types,
118
+ dropout=dropout,
119
+ norm_num_groups=norm_num_groups,
120
+ cross_attention_dim=cross_attention_dim,
121
+ activation_fn=activation_fn,
122
+ attention_bias=attention_bias,
123
+ upcast_attention=upcast_attention,
124
+ cross_frame_attention_mode=cross_frame_attention_mode,
125
+ temporal_position_encoding=temporal_position_encoding,
126
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
127
+ )
128
+ for d in range(num_layers)
129
+ ]
130
+ )
131
+ self.proj_out = nn.Linear(inner_dim, in_channels)
132
+
133
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
134
+ assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
135
+ video_length = hidden_states.shape[2]
136
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
137
+
138
+ batch, channel, height, weight = hidden_states.shape
139
+ residual = hidden_states
140
+
141
+ hidden_states = self.norm(hidden_states)
142
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, channel)
143
+ hidden_states = self.proj_in(hidden_states)
144
+
145
+ # Transformer Blocks
146
+ for block in self.transformer_blocks:
147
+ hidden_states = block(
148
+ hidden_states, encoder_hidden_states=encoder_hidden_states, video_length=video_length
149
+ )
150
+
151
+ # output
152
+ hidden_states = self.proj_out(hidden_states)
153
+ hidden_states = hidden_states.reshape(batch, height, weight, channel).permute(0, 3, 1, 2).contiguous()
154
+
155
+ output = hidden_states + residual
156
+ output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
157
+
158
+ return output
159
+
160
+
161
+ class TemporalTransformerBlock(nn.Module):
162
+ def __init__(
163
+ self,
164
+ dim,
165
+ num_attention_heads,
166
+ attention_head_dim,
167
+ attention_block_types=(
168
+ "Temporal_Self",
169
+ "Temporal_Self",
170
+ ),
171
+ dropout=0.0,
172
+ norm_num_groups=32,
173
+ cross_attention_dim=768,
174
+ activation_fn="geglu",
175
+ attention_bias=False,
176
+ upcast_attention=False,
177
+ cross_frame_attention_mode=None,
178
+ temporal_position_encoding=False,
179
+ temporal_position_encoding_max_len=24,
180
+ ):
181
+ super().__init__()
182
+
183
+ attention_blocks = []
184
+ norms = []
185
+
186
+ for block_name in attention_block_types:
187
+ attention_blocks.append(
188
+ VersatileAttention(
189
+ attention_mode=block_name.split("_")[0],
190
+ cross_attention_dim=cross_attention_dim if block_name.endswith("_Cross") else None,
191
+ query_dim=dim,
192
+ heads=num_attention_heads,
193
+ dim_head=attention_head_dim,
194
+ dropout=dropout,
195
+ bias=attention_bias,
196
+ upcast_attention=upcast_attention,
197
+ cross_frame_attention_mode=cross_frame_attention_mode,
198
+ temporal_position_encoding=temporal_position_encoding,
199
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
200
+ )
201
+ )
202
+ norms.append(nn.LayerNorm(dim))
203
+
204
+ self.attention_blocks = nn.ModuleList(attention_blocks)
205
+ self.norms = nn.ModuleList(norms)
206
+
207
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
208
+ self.ff_norm = nn.LayerNorm(dim)
209
+
210
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
211
+ for attention_block, norm in zip(self.attention_blocks, self.norms):
212
+ norm_hidden_states = norm(hidden_states)
213
+ hidden_states = (
214
+ attention_block(
215
+ norm_hidden_states,
216
+ encoder_hidden_states=encoder_hidden_states if attention_block.is_cross_attention else None,
217
+ video_length=video_length,
218
+ )
219
+ + hidden_states
220
+ )
221
+
222
+ hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
223
+
224
+ output = hidden_states
225
+ return output
226
+
227
+
228
+ class PositionalEncoding(nn.Module):
229
+ def __init__(self, d_model, dropout=0.0, max_len=24):
230
+ super().__init__()
231
+ self.dropout = nn.Dropout(p=dropout)
232
+ position = torch.arange(max_len).unsqueeze(1)
233
+ div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
234
+ pe = torch.zeros(1, max_len, d_model)
235
+ pe[0, :, 0::2] = torch.sin(position * div_term)
236
+ pe[0, :, 1::2] = torch.cos(position * div_term)
237
+ self.register_buffer("pe", pe)
238
+
239
+ def forward(self, x):
240
+ x = x + self.pe[:, : x.size(1)]
241
+ return self.dropout(x)
242
+
243
+
244
+ class VersatileAttention(CrossAttention):
245
+ def __init__(
246
+ self,
247
+ attention_mode=None,
248
+ cross_frame_attention_mode=None,
249
+ temporal_position_encoding=False,
250
+ temporal_position_encoding_max_len=24,
251
+ *args,
252
+ **kwargs,
253
+ ):
254
+ super().__init__(*args, **kwargs)
255
+ assert attention_mode == "Temporal"
256
+
257
+ self.attention_mode = attention_mode
258
+ self.is_cross_attention = kwargs["cross_attention_dim"] is not None
259
+
260
+ self.pos_encoder = (
261
+ PositionalEncoding(kwargs["query_dim"], dropout=0.0, max_len=temporal_position_encoding_max_len)
262
+ if (temporal_position_encoding and attention_mode == "Temporal")
263
+ else None
264
+ )
265
+
266
+ def extra_repr(self):
267
+ return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
268
+
269
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
270
+ batch_size, sequence_length, _ = hidden_states.shape
271
+
272
+ if self.attention_mode == "Temporal":
273
+ d = hidden_states.shape[1]
274
+ hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
275
+
276
+ if self.pos_encoder is not None:
277
+ hidden_states = self.pos_encoder(hidden_states)
278
+
279
+ encoder_hidden_states = (
280
+ repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d)
281
+ if encoder_hidden_states is not None
282
+ else encoder_hidden_states
283
+ )
284
+ else:
285
+ raise NotImplementedError
286
+
287
+ # encoder_hidden_states = encoder_hidden_states
288
+
289
+ if self.group_norm is not None:
290
+ hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
291
+
292
+ query = self.to_q(hidden_states)
293
+ dim = query.shape[-1]
294
+ query = self.reshape_heads_to_batch_dim(query)
295
+
296
+ if self.added_kv_proj_dim is not None:
297
+ raise NotImplementedError
298
+
299
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
300
+ key = self.to_k(encoder_hidden_states)
301
+ value = self.to_v(encoder_hidden_states)
302
+
303
+ key = self.reshape_heads_to_batch_dim(key)
304
+ value = self.reshape_heads_to_batch_dim(value)
305
+
306
+ if attention_mask is not None:
307
+ if attention_mask.shape[-1] != query.shape[1]:
308
+ target_length = query.shape[1]
309
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
310
+ attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
311
+
312
+ # attention, what we cannot get enough of
313
+ if self._use_memory_efficient_attention_xformers:
314
+ hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
315
+ # Some versions of xformers return output in fp32, cast it back to the dtype of the input
316
+ hidden_states = hidden_states.to(query.dtype)
317
+ else:
318
+ if self._slice_size is None or query.shape[0] // self._slice_size == 1:
319
+ hidden_states = self._attention(query, key, value, attention_mask)
320
+ else:
321
+ hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
322
+
323
+ # linear proj
324
+ hidden_states = self.to_out[0](hidden_states)
325
+
326
+ # dropout
327
+ hidden_states = self.to_out[1](hidden_states)
328
+
329
+ if self.attention_mode == "Temporal":
330
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
331
+
332
+ return hidden_states
latentsync/models/resnet.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from einops import rearrange
8
+
9
+
10
+ class InflatedConv3d(nn.Conv2d):
11
+ def forward(self, x):
12
+ video_length = x.shape[2]
13
+
14
+ x = rearrange(x, "b c f h w -> (b f) c h w")
15
+ x = super().forward(x)
16
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
17
+
18
+ return x
19
+
20
+
21
+ class InflatedGroupNorm(nn.GroupNorm):
22
+ def forward(self, x):
23
+ video_length = x.shape[2]
24
+
25
+ x = rearrange(x, "b c f h w -> (b f) c h w")
26
+ x = super().forward(x)
27
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
28
+
29
+ return x
30
+
31
+
32
+ class Upsample3D(nn.Module):
33
+ def __init__(self, channels, use_conv=False, use_conv_transpose=False, out_channels=None, name="conv"):
34
+ super().__init__()
35
+ self.channels = channels
36
+ self.out_channels = out_channels or channels
37
+ self.use_conv = use_conv
38
+ self.use_conv_transpose = use_conv_transpose
39
+ self.name = name
40
+
41
+ conv = None
42
+ if use_conv_transpose:
43
+ raise NotImplementedError
44
+ elif use_conv:
45
+ self.conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
46
+
47
+ def forward(self, hidden_states, output_size=None):
48
+ assert hidden_states.shape[1] == self.channels
49
+
50
+ if self.use_conv_transpose:
51
+ raise NotImplementedError
52
+
53
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
54
+ dtype = hidden_states.dtype
55
+ if dtype == torch.bfloat16:
56
+ hidden_states = hidden_states.to(torch.float32)
57
+
58
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
59
+ if hidden_states.shape[0] >= 64:
60
+ hidden_states = hidden_states.contiguous()
61
+
62
+ # if `output_size` is passed we force the interpolation output
63
+ # size and do not make use of `scale_factor=2`
64
+ if output_size is None:
65
+ hidden_states = F.interpolate(hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest")
66
+ else:
67
+ hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
68
+
69
+ # If the input is bfloat16, we cast back to bfloat16
70
+ if dtype == torch.bfloat16:
71
+ hidden_states = hidden_states.to(dtype)
72
+
73
+ # if self.use_conv:
74
+ # if self.name == "conv":
75
+ # hidden_states = self.conv(hidden_states)
76
+ # else:
77
+ # hidden_states = self.Conv2d_0(hidden_states)
78
+ hidden_states = self.conv(hidden_states)
79
+
80
+ return hidden_states
81
+
82
+
83
+ class Downsample3D(nn.Module):
84
+ def __init__(self, channels, use_conv=False, out_channels=None, padding=1, name="conv"):
85
+ super().__init__()
86
+ self.channels = channels
87
+ self.out_channels = out_channels or channels
88
+ self.use_conv = use_conv
89
+ self.padding = padding
90
+ stride = 2
91
+ self.name = name
92
+
93
+ if use_conv:
94
+ self.conv = InflatedConv3d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
95
+ else:
96
+ raise NotImplementedError
97
+
98
+ def forward(self, hidden_states):
99
+ assert hidden_states.shape[1] == self.channels
100
+ if self.use_conv and self.padding == 0:
101
+ raise NotImplementedError
102
+
103
+ assert hidden_states.shape[1] == self.channels
104
+ hidden_states = self.conv(hidden_states)
105
+
106
+ return hidden_states
107
+
108
+
109
+ class ResnetBlock3D(nn.Module):
110
+ def __init__(
111
+ self,
112
+ *,
113
+ in_channels,
114
+ out_channels=None,
115
+ conv_shortcut=False,
116
+ dropout=0.0,
117
+ temb_channels=512,
118
+ groups=32,
119
+ groups_out=None,
120
+ pre_norm=True,
121
+ eps=1e-6,
122
+ non_linearity="swish",
123
+ time_embedding_norm="default",
124
+ output_scale_factor=1.0,
125
+ use_in_shortcut=None,
126
+ use_inflated_groupnorm=False,
127
+ ):
128
+ super().__init__()
129
+ self.pre_norm = pre_norm
130
+ self.pre_norm = True
131
+ self.in_channels = in_channels
132
+ out_channels = in_channels if out_channels is None else out_channels
133
+ self.out_channels = out_channels
134
+ self.use_conv_shortcut = conv_shortcut
135
+ self.time_embedding_norm = time_embedding_norm
136
+ self.output_scale_factor = output_scale_factor
137
+
138
+ if groups_out is None:
139
+ groups_out = groups
140
+
141
+ assert use_inflated_groupnorm != None
142
+ if use_inflated_groupnorm:
143
+ self.norm1 = InflatedGroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
144
+ else:
145
+ self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
146
+
147
+ self.conv1 = InflatedConv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
148
+
149
+ if temb_channels is not None:
150
+ time_emb_proj_out_channels = out_channels
151
+ # if self.time_embedding_norm == "default":
152
+ # time_emb_proj_out_channels = out_channels
153
+ # elif self.time_embedding_norm == "scale_shift":
154
+ # time_emb_proj_out_channels = out_channels * 2
155
+ # else:
156
+ # raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
157
+
158
+ self.time_emb_proj = torch.nn.Linear(temb_channels, time_emb_proj_out_channels)
159
+ else:
160
+ self.time_emb_proj = None
161
+
162
+ if self.time_embedding_norm == "scale_shift":
163
+ self.double_len_linear = torch.nn.Linear(time_emb_proj_out_channels, 2 * time_emb_proj_out_channels)
164
+ else:
165
+ self.double_len_linear = None
166
+
167
+ if use_inflated_groupnorm:
168
+ self.norm2 = InflatedGroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
169
+ else:
170
+ self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
171
+
172
+ self.dropout = torch.nn.Dropout(dropout)
173
+ self.conv2 = InflatedConv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
174
+
175
+ if non_linearity == "swish":
176
+ self.nonlinearity = lambda x: F.silu(x)
177
+ elif non_linearity == "mish":
178
+ self.nonlinearity = Mish()
179
+ elif non_linearity == "silu":
180
+ self.nonlinearity = nn.SiLU()
181
+
182
+ self.use_in_shortcut = self.in_channels != self.out_channels if use_in_shortcut is None else use_in_shortcut
183
+
184
+ self.conv_shortcut = None
185
+ if self.use_in_shortcut:
186
+ self.conv_shortcut = InflatedConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
187
+
188
+ def forward(self, input_tensor, temb):
189
+ hidden_states = input_tensor
190
+
191
+ hidden_states = self.norm1(hidden_states)
192
+ hidden_states = self.nonlinearity(hidden_states)
193
+
194
+ hidden_states = self.conv1(hidden_states)
195
+
196
+ if temb is not None:
197
+ if temb.dim() == 2:
198
+ # input (1, 1280)
199
+ temb = self.time_emb_proj(self.nonlinearity(temb))
200
+ temb = temb[:, :, None, None, None] # unsqueeze
201
+ else:
202
+ # input (1, 1280, 16)
203
+ temb = temb.permute(0, 2, 1)
204
+ temb = self.time_emb_proj(self.nonlinearity(temb))
205
+ if self.double_len_linear is not None:
206
+ temb = self.double_len_linear(self.nonlinearity(temb))
207
+ temb = temb.permute(0, 2, 1)
208
+ temb = temb[:, :, :, None, None]
209
+
210
+ if temb is not None and self.time_embedding_norm == "default":
211
+ hidden_states = hidden_states + temb
212
+
213
+ hidden_states = self.norm2(hidden_states)
214
+
215
+ if temb is not None and self.time_embedding_norm == "scale_shift":
216
+ scale, shift = torch.chunk(temb, 2, dim=1)
217
+ hidden_states = hidden_states * (1 + scale) + shift
218
+
219
+ hidden_states = self.nonlinearity(hidden_states)
220
+
221
+ hidden_states = self.dropout(hidden_states)
222
+ hidden_states = self.conv2(hidden_states)
223
+
224
+ if self.conv_shortcut is not None:
225
+ input_tensor = self.conv_shortcut(input_tensor)
226
+
227
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
228
+
229
+ return output_tensor
230
+
231
+
232
+ class Mish(torch.nn.Module):
233
+ def forward(self, hidden_states):
234
+ return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))
latentsync/models/syncnet.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Bytedance Ltd. and/or its affiliates
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
+ import torch
16
+ from torch import nn
17
+ from einops import rearrange
18
+ from torch.nn import functional as F
19
+ from ..utils.util import cosine_loss
20
+
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from diffusers.models.attention import CrossAttention, FeedForward
25
+ from diffusers.utils.import_utils import is_xformers_available
26
+ from einops import rearrange
27
+
28
+
29
+ class SyncNet(nn.Module):
30
+ def __init__(self, config):
31
+ super().__init__()
32
+ self.audio_encoder = DownEncoder2D(
33
+ in_channels=config["audio_encoder"]["in_channels"],
34
+ block_out_channels=config["audio_encoder"]["block_out_channels"],
35
+ downsample_factors=config["audio_encoder"]["downsample_factors"],
36
+ dropout=config["audio_encoder"]["dropout"],
37
+ attn_blocks=config["audio_encoder"]["attn_blocks"],
38
+ )
39
+
40
+ self.visual_encoder = DownEncoder2D(
41
+ in_channels=config["visual_encoder"]["in_channels"],
42
+ block_out_channels=config["visual_encoder"]["block_out_channels"],
43
+ downsample_factors=config["visual_encoder"]["downsample_factors"],
44
+ dropout=config["visual_encoder"]["dropout"],
45
+ attn_blocks=config["visual_encoder"]["attn_blocks"],
46
+ )
47
+
48
+ self.eval()
49
+
50
+ def forward(self, image_sequences, audio_sequences):
51
+ vision_embeds = self.visual_encoder(image_sequences) # (b, c, 1, 1)
52
+ audio_embeds = self.audio_encoder(audio_sequences) # (b, c, 1, 1)
53
+
54
+ vision_embeds = vision_embeds.reshape(vision_embeds.shape[0], -1) # (b, c)
55
+ audio_embeds = audio_embeds.reshape(audio_embeds.shape[0], -1) # (b, c)
56
+
57
+ # Make them unit vectors
58
+ vision_embeds = F.normalize(vision_embeds, p=2, dim=1)
59
+ audio_embeds = F.normalize(audio_embeds, p=2, dim=1)
60
+
61
+ return vision_embeds, audio_embeds
62
+
63
+
64
+ class ResnetBlock2D(nn.Module):
65
+ def __init__(
66
+ self,
67
+ in_channels: int,
68
+ out_channels: int,
69
+ dropout: float = 0.0,
70
+ norm_num_groups: int = 32,
71
+ eps: float = 1e-6,
72
+ act_fn: str = "silu",
73
+ downsample_factor=2,
74
+ ):
75
+ super().__init__()
76
+
77
+ self.norm1 = nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=eps, affine=True)
78
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
79
+
80
+ self.norm2 = nn.GroupNorm(num_groups=norm_num_groups, num_channels=out_channels, eps=eps, affine=True)
81
+ self.dropout = nn.Dropout(dropout)
82
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
83
+
84
+ if act_fn == "relu":
85
+ self.act_fn = nn.ReLU()
86
+ elif act_fn == "silu":
87
+ self.act_fn = nn.SiLU()
88
+
89
+ if in_channels != out_channels:
90
+ self.conv_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
91
+ else:
92
+ self.conv_shortcut = None
93
+
94
+ if isinstance(downsample_factor, list):
95
+ downsample_factor = tuple(downsample_factor)
96
+
97
+ if downsample_factor == 1:
98
+ self.downsample_conv = None
99
+ else:
100
+ self.downsample_conv = nn.Conv2d(
101
+ out_channels, out_channels, kernel_size=3, stride=downsample_factor, padding=0
102
+ )
103
+ self.pad = (0, 1, 0, 1)
104
+ if isinstance(downsample_factor, tuple):
105
+ if downsample_factor[0] == 1:
106
+ self.pad = (0, 1, 1, 1) # The padding order is from back to front
107
+ elif downsample_factor[1] == 1:
108
+ self.pad = (1, 1, 0, 1)
109
+
110
+ def forward(self, input_tensor):
111
+ hidden_states = input_tensor
112
+
113
+ hidden_states = self.norm1(hidden_states)
114
+ hidden_states = self.act_fn(hidden_states)
115
+
116
+ hidden_states = self.conv1(hidden_states)
117
+ hidden_states = self.norm2(hidden_states)
118
+ hidden_states = self.act_fn(hidden_states)
119
+
120
+ hidden_states = self.dropout(hidden_states)
121
+ hidden_states = self.conv2(hidden_states)
122
+
123
+ if self.conv_shortcut is not None:
124
+ input_tensor = self.conv_shortcut(input_tensor)
125
+
126
+ hidden_states += input_tensor
127
+
128
+ if self.downsample_conv is not None:
129
+ hidden_states = F.pad(hidden_states, self.pad, mode="constant", value=0)
130
+ hidden_states = self.downsample_conv(hidden_states)
131
+
132
+ return hidden_states
133
+
134
+
135
+ class AttentionBlock2D(nn.Module):
136
+ def __init__(self, query_dim, norm_num_groups=32, dropout=0.0):
137
+ super().__init__()
138
+ if not is_xformers_available():
139
+ raise ModuleNotFoundError(
140
+ "You have to install xformers to enable memory efficient attetion", name="xformers"
141
+ )
142
+ # inner_dim = dim_head * heads
143
+ self.norm1 = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=query_dim, eps=1e-6, affine=True)
144
+ self.norm2 = nn.LayerNorm(query_dim)
145
+ self.norm3 = nn.LayerNorm(query_dim)
146
+
147
+ self.ff = FeedForward(query_dim, dropout=dropout, activation_fn="geglu")
148
+
149
+ self.conv_in = nn.Conv2d(query_dim, query_dim, kernel_size=1, stride=1, padding=0)
150
+ self.conv_out = nn.Conv2d(query_dim, query_dim, kernel_size=1, stride=1, padding=0)
151
+
152
+ self.attn = CrossAttention(query_dim=query_dim, heads=8, dim_head=query_dim // 8, dropout=dropout, bias=True)
153
+ self.attn._use_memory_efficient_attention_xformers = True
154
+
155
+ def forward(self, hidden_states):
156
+ assert hidden_states.dim() == 4, f"Expected hidden_states to have ndim=4, but got ndim={hidden_states.dim()}."
157
+
158
+ batch, channel, height, width = hidden_states.shape
159
+ residual = hidden_states
160
+
161
+ hidden_states = self.norm1(hidden_states)
162
+ hidden_states = self.conv_in(hidden_states)
163
+ hidden_states = rearrange(hidden_states, "b c h w -> b (h w) c")
164
+
165
+ norm_hidden_states = self.norm2(hidden_states)
166
+ hidden_states = self.attn(norm_hidden_states, attention_mask=None) + hidden_states
167
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
168
+
169
+ hidden_states = rearrange(hidden_states, "b (h w) c -> b c h w", h=height, w=width)
170
+ hidden_states = self.conv_out(hidden_states)
171
+
172
+ hidden_states = hidden_states + residual
173
+ return hidden_states
174
+
175
+
176
+ class DownEncoder2D(nn.Module):
177
+ def __init__(
178
+ self,
179
+ in_channels=4 * 16,
180
+ block_out_channels=[64, 128, 256, 256],
181
+ downsample_factors=[2, 2, 2, 2],
182
+ layers_per_block=2,
183
+ norm_num_groups=32,
184
+ attn_blocks=[1, 1, 1, 1],
185
+ dropout: float = 0.0,
186
+ act_fn="silu",
187
+ ):
188
+ super().__init__()
189
+ self.layers_per_block = layers_per_block
190
+
191
+ # in
192
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, stride=1, padding=1)
193
+
194
+ # down
195
+ self.down_blocks = nn.ModuleList([])
196
+
197
+ output_channels = block_out_channels[0]
198
+ for i, block_out_channel in enumerate(block_out_channels):
199
+ input_channels = output_channels
200
+ output_channels = block_out_channel
201
+ # is_final_block = i == len(block_out_channels) - 1
202
+
203
+ down_block = ResnetBlock2D(
204
+ in_channels=input_channels,
205
+ out_channels=output_channels,
206
+ downsample_factor=downsample_factors[i],
207
+ norm_num_groups=norm_num_groups,
208
+ dropout=dropout,
209
+ act_fn=act_fn,
210
+ )
211
+
212
+ self.down_blocks.append(down_block)
213
+
214
+ if attn_blocks[i] == 1:
215
+ attention_block = AttentionBlock2D(query_dim=output_channels, dropout=dropout)
216
+ self.down_blocks.append(attention_block)
217
+
218
+ # out
219
+ self.norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6)
220
+ self.act_fn_out = nn.ReLU()
221
+
222
+ def forward(self, hidden_states):
223
+ hidden_states = self.conv_in(hidden_states)
224
+
225
+ # down
226
+ for down_block in self.down_blocks:
227
+ hidden_states = down_block(hidden_states)
228
+
229
+ # post-process
230
+ hidden_states = self.norm_out(hidden_states)
231
+ hidden_states = self.act_fn_out(hidden_states)
232
+
233
+ return hidden_states
latentsync/models/syncnet_wav2lip.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/primepake/wav2lip_288x288/blob/master/models/syncnetv2.py
2
+ # The code here is for ablation study.
3
+
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ class SyncNetWav2Lip(nn.Module):
9
+ def __init__(self, act_fn="leaky"):
10
+ super().__init__()
11
+
12
+ # input image sequences: (15, 128, 256)
13
+ self.visual_encoder = nn.Sequential(
14
+ Conv2d(15, 32, kernel_size=(7, 7), stride=1, padding=3, act_fn=act_fn), # (128, 256)
15
+ Conv2d(32, 64, kernel_size=5, stride=(1, 2), padding=1, act_fn=act_fn), # (126, 127)
16
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
17
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
18
+ Conv2d(64, 128, kernel_size=3, stride=2, padding=1, act_fn=act_fn), # (63, 64)
19
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
20
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
21
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
22
+ Conv2d(128, 256, kernel_size=3, stride=3, padding=1, act_fn=act_fn), # (21, 22)
23
+ Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
24
+ Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
25
+ Conv2d(256, 512, kernel_size=3, stride=2, padding=1, act_fn=act_fn), # (11, 11)
26
+ Conv2d(512, 512, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
27
+ Conv2d(512, 512, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
28
+ Conv2d(512, 1024, kernel_size=3, stride=2, padding=1, act_fn=act_fn), # (6, 6)
29
+ Conv2d(1024, 1024, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
30
+ Conv2d(1024, 1024, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
31
+ Conv2d(1024, 1024, kernel_size=3, stride=2, padding=1, act_fn="relu"), # (3, 3)
32
+ Conv2d(1024, 1024, kernel_size=3, stride=1, padding=0, act_fn="relu"), # (1, 1)
33
+ Conv2d(1024, 1024, kernel_size=1, stride=1, padding=0, act_fn="relu"),
34
+ )
35
+
36
+ # input audio sequences: (1, 80, 16)
37
+ self.audio_encoder = nn.Sequential(
38
+ Conv2d(1, 32, kernel_size=3, stride=1, padding=1, act_fn=act_fn),
39
+ Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
40
+ Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
41
+ Conv2d(32, 64, kernel_size=3, stride=(3, 1), padding=1, act_fn=act_fn), # (27, 16)
42
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
43
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
44
+ Conv2d(64, 128, kernel_size=3, stride=3, padding=1, act_fn=act_fn), # (9, 6)
45
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
46
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
47
+ Conv2d(128, 256, kernel_size=3, stride=(3, 2), padding=1, act_fn=act_fn), # (3, 3)
48
+ Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
49
+ Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
50
+ Conv2d(256, 512, kernel_size=3, stride=1, padding=1, act_fn=act_fn),
51
+ Conv2d(512, 512, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
52
+ Conv2d(512, 512, kernel_size=3, stride=1, padding=1, residual=True, act_fn=act_fn),
53
+ Conv2d(512, 1024, kernel_size=3, stride=1, padding=0, act_fn="relu"), # (1, 1)
54
+ Conv2d(1024, 1024, kernel_size=1, stride=1, padding=0, act_fn="relu"),
55
+ )
56
+
57
+ def forward(self, image_sequences, audio_sequences):
58
+ vision_embeds = self.visual_encoder(image_sequences) # (b, c, 1, 1)
59
+ audio_embeds = self.audio_encoder(audio_sequences) # (b, c, 1, 1)
60
+
61
+ vision_embeds = vision_embeds.reshape(vision_embeds.shape[0], -1) # (b, c)
62
+ audio_embeds = audio_embeds.reshape(audio_embeds.shape[0], -1) # (b, c)
63
+
64
+ # Make them unit vectors
65
+ vision_embeds = F.normalize(vision_embeds, p=2, dim=1)
66
+ audio_embeds = F.normalize(audio_embeds, p=2, dim=1)
67
+
68
+ return vision_embeds, audio_embeds
69
+
70
+
71
+ class Conv2d(nn.Module):
72
+ def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, act_fn="relu", *args, **kwargs):
73
+ super().__init__(*args, **kwargs)
74
+ self.conv_block = nn.Sequential(nn.Conv2d(cin, cout, kernel_size, stride, padding), nn.BatchNorm2d(cout))
75
+ if act_fn == "relu":
76
+ self.act_fn = nn.ReLU()
77
+ elif act_fn == "tanh":
78
+ self.act_fn = nn.Tanh()
79
+ elif act_fn == "silu":
80
+ self.act_fn = nn.SiLU()
81
+ elif act_fn == "leaky":
82
+ self.act_fn = nn.LeakyReLU(0.2, inplace=True)
83
+
84
+ self.residual = residual
85
+
86
+ def forward(self, x):
87
+ out = self.conv_block(x)
88
+ if self.residual:
89
+ out += x
90
+ return self.act_fn(out)
latentsync/models/unet.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/guoyww/AnimateDiff/blob/main/animatediff/models/unet.py
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional, Tuple, Union
5
+ import copy
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.utils.checkpoint
10
+
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.modeling_utils import ModelMixin
13
+ from diffusers import UNet2DConditionModel
14
+ from diffusers.utils import BaseOutput, logging
15
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
16
+ from .unet_blocks import (
17
+ CrossAttnDownBlock3D,
18
+ CrossAttnUpBlock3D,
19
+ DownBlock3D,
20
+ UNetMidBlock3DCrossAttn,
21
+ UpBlock3D,
22
+ get_down_block,
23
+ get_up_block,
24
+ )
25
+ from .resnet import InflatedConv3d, InflatedGroupNorm
26
+
27
+ from ..utils.util import zero_rank_log
28
+ from einops import rearrange
29
+ from .utils import zero_module
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ @dataclass
36
+ class UNet3DConditionOutput(BaseOutput):
37
+ sample: torch.FloatTensor
38
+
39
+
40
+ class UNet3DConditionModel(ModelMixin, ConfigMixin):
41
+ _supports_gradient_checkpointing = True
42
+
43
+ @register_to_config
44
+ def __init__(
45
+ self,
46
+ sample_size: Optional[int] = None,
47
+ in_channels: int = 4,
48
+ out_channels: int = 4,
49
+ center_input_sample: bool = False,
50
+ flip_sin_to_cos: bool = True,
51
+ freq_shift: int = 0,
52
+ down_block_types: Tuple[str] = (
53
+ "CrossAttnDownBlock3D",
54
+ "CrossAttnDownBlock3D",
55
+ "CrossAttnDownBlock3D",
56
+ "DownBlock3D",
57
+ ),
58
+ mid_block_type: str = "UNetMidBlock3DCrossAttn",
59
+ up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"),
60
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
61
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
62
+ layers_per_block: int = 2,
63
+ downsample_padding: int = 1,
64
+ mid_block_scale_factor: float = 1,
65
+ act_fn: str = "silu",
66
+ norm_num_groups: int = 32,
67
+ norm_eps: float = 1e-5,
68
+ cross_attention_dim: int = 1280,
69
+ attention_head_dim: Union[int, Tuple[int]] = 8,
70
+ dual_cross_attention: bool = False,
71
+ use_linear_projection: bool = False,
72
+ class_embed_type: Optional[str] = None,
73
+ num_class_embeds: Optional[int] = None,
74
+ upcast_attention: bool = False,
75
+ resnet_time_scale_shift: str = "default",
76
+ use_inflated_groupnorm=False,
77
+ # Additional
78
+ use_motion_module=False,
79
+ motion_module_resolutions=(1, 2, 4, 8),
80
+ motion_module_mid_block=False,
81
+ motion_module_decoder_only=False,
82
+ motion_module_type=None,
83
+ motion_module_kwargs={},
84
+ unet_use_cross_frame_attention=False,
85
+ unet_use_temporal_attention=False,
86
+ add_audio_layer=False,
87
+ audio_condition_method: str = "cross_attn",
88
+ custom_audio_layer=False,
89
+ ):
90
+ super().__init__()
91
+
92
+ self.sample_size = sample_size
93
+ time_embed_dim = block_out_channels[0] * 4
94
+ self.use_motion_module = use_motion_module
95
+ self.add_audio_layer = add_audio_layer
96
+
97
+ self.conv_in = zero_module(InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)))
98
+
99
+ # time
100
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
101
+ timestep_input_dim = block_out_channels[0]
102
+
103
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
104
+
105
+ # class embedding
106
+ if class_embed_type is None and num_class_embeds is not None:
107
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
108
+ elif class_embed_type == "timestep":
109
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
110
+ elif class_embed_type == "identity":
111
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
112
+ else:
113
+ self.class_embedding = None
114
+
115
+ self.down_blocks = nn.ModuleList([])
116
+ self.mid_block = None
117
+ self.up_blocks = nn.ModuleList([])
118
+
119
+ if isinstance(only_cross_attention, bool):
120
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
121
+
122
+ if isinstance(attention_head_dim, int):
123
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
124
+
125
+ # down
126
+ output_channel = block_out_channels[0]
127
+ for i, down_block_type in enumerate(down_block_types):
128
+ res = 2**i
129
+ input_channel = output_channel
130
+ output_channel = block_out_channels[i]
131
+ is_final_block = i == len(block_out_channels) - 1
132
+
133
+ down_block = get_down_block(
134
+ down_block_type,
135
+ num_layers=layers_per_block,
136
+ in_channels=input_channel,
137
+ out_channels=output_channel,
138
+ temb_channels=time_embed_dim,
139
+ add_downsample=not is_final_block,
140
+ resnet_eps=norm_eps,
141
+ resnet_act_fn=act_fn,
142
+ resnet_groups=norm_num_groups,
143
+ cross_attention_dim=cross_attention_dim,
144
+ attn_num_head_channels=attention_head_dim[i],
145
+ downsample_padding=downsample_padding,
146
+ dual_cross_attention=dual_cross_attention,
147
+ use_linear_projection=use_linear_projection,
148
+ only_cross_attention=only_cross_attention[i],
149
+ upcast_attention=upcast_attention,
150
+ resnet_time_scale_shift=resnet_time_scale_shift,
151
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
152
+ unet_use_temporal_attention=unet_use_temporal_attention,
153
+ use_inflated_groupnorm=use_inflated_groupnorm,
154
+ use_motion_module=use_motion_module
155
+ and (res in motion_module_resolutions)
156
+ and (not motion_module_decoder_only),
157
+ motion_module_type=motion_module_type,
158
+ motion_module_kwargs=motion_module_kwargs,
159
+ add_audio_layer=add_audio_layer,
160
+ audio_condition_method=audio_condition_method,
161
+ custom_audio_layer=custom_audio_layer,
162
+ )
163
+ self.down_blocks.append(down_block)
164
+
165
+ # mid
166
+ if mid_block_type == "UNetMidBlock3DCrossAttn":
167
+ self.mid_block = UNetMidBlock3DCrossAttn(
168
+ in_channels=block_out_channels[-1],
169
+ temb_channels=time_embed_dim,
170
+ resnet_eps=norm_eps,
171
+ resnet_act_fn=act_fn,
172
+ output_scale_factor=mid_block_scale_factor,
173
+ resnet_time_scale_shift=resnet_time_scale_shift,
174
+ cross_attention_dim=cross_attention_dim,
175
+ attn_num_head_channels=attention_head_dim[-1],
176
+ resnet_groups=norm_num_groups,
177
+ dual_cross_attention=dual_cross_attention,
178
+ use_linear_projection=use_linear_projection,
179
+ upcast_attention=upcast_attention,
180
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
181
+ unet_use_temporal_attention=unet_use_temporal_attention,
182
+ use_inflated_groupnorm=use_inflated_groupnorm,
183
+ use_motion_module=use_motion_module and motion_module_mid_block,
184
+ motion_module_type=motion_module_type,
185
+ motion_module_kwargs=motion_module_kwargs,
186
+ add_audio_layer=add_audio_layer,
187
+ audio_condition_method=audio_condition_method,
188
+ custom_audio_layer=custom_audio_layer,
189
+ )
190
+ else:
191
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
192
+
193
+ # count how many layers upsample the videos
194
+ self.num_upsamplers = 0
195
+
196
+ # up
197
+ reversed_block_out_channels = list(reversed(block_out_channels))
198
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
199
+ only_cross_attention = list(reversed(only_cross_attention))
200
+ output_channel = reversed_block_out_channels[0]
201
+ for i, up_block_type in enumerate(up_block_types):
202
+ res = 2 ** (3 - i)
203
+ is_final_block = i == len(block_out_channels) - 1
204
+
205
+ prev_output_channel = output_channel
206
+ output_channel = reversed_block_out_channels[i]
207
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
208
+
209
+ # add upsample block for all BUT final layer
210
+ if not is_final_block:
211
+ add_upsample = True
212
+ self.num_upsamplers += 1
213
+ else:
214
+ add_upsample = False
215
+
216
+ up_block = get_up_block(
217
+ up_block_type,
218
+ num_layers=layers_per_block + 1,
219
+ in_channels=input_channel,
220
+ out_channels=output_channel,
221
+ prev_output_channel=prev_output_channel,
222
+ temb_channels=time_embed_dim,
223
+ add_upsample=add_upsample,
224
+ resnet_eps=norm_eps,
225
+ resnet_act_fn=act_fn,
226
+ resnet_groups=norm_num_groups,
227
+ cross_attention_dim=cross_attention_dim,
228
+ attn_num_head_channels=reversed_attention_head_dim[i],
229
+ dual_cross_attention=dual_cross_attention,
230
+ use_linear_projection=use_linear_projection,
231
+ only_cross_attention=only_cross_attention[i],
232
+ upcast_attention=upcast_attention,
233
+ resnet_time_scale_shift=resnet_time_scale_shift,
234
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
235
+ unet_use_temporal_attention=unet_use_temporal_attention,
236
+ use_inflated_groupnorm=use_inflated_groupnorm,
237
+ use_motion_module=use_motion_module and (res in motion_module_resolutions),
238
+ motion_module_type=motion_module_type,
239
+ motion_module_kwargs=motion_module_kwargs,
240
+ add_audio_layer=add_audio_layer,
241
+ audio_condition_method=audio_condition_method,
242
+ custom_audio_layer=custom_audio_layer,
243
+ )
244
+ self.up_blocks.append(up_block)
245
+ prev_output_channel = output_channel
246
+
247
+ # out
248
+ if use_inflated_groupnorm:
249
+ self.conv_norm_out = InflatedGroupNorm(
250
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
251
+ )
252
+ else:
253
+ self.conv_norm_out = nn.GroupNorm(
254
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
255
+ )
256
+ self.conv_act = nn.SiLU()
257
+
258
+ self.conv_out = zero_module(InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1))
259
+
260
+ def set_attention_slice(self, slice_size):
261
+ r"""
262
+ Enable sliced attention computation.
263
+
264
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
265
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
266
+
267
+ Args:
268
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
269
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
270
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
271
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
272
+ must be a multiple of `slice_size`.
273
+ """
274
+ sliceable_head_dims = []
275
+
276
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
277
+ if hasattr(module, "set_attention_slice"):
278
+ sliceable_head_dims.append(module.sliceable_head_dim)
279
+
280
+ for child in module.children():
281
+ fn_recursive_retrieve_slicable_dims(child)
282
+
283
+ # retrieve number of attention layers
284
+ for module in self.children():
285
+ fn_recursive_retrieve_slicable_dims(module)
286
+
287
+ num_slicable_layers = len(sliceable_head_dims)
288
+
289
+ if slice_size == "auto":
290
+ # half the attention head size is usually a good trade-off between
291
+ # speed and memory
292
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
293
+ elif slice_size == "max":
294
+ # make smallest slice possible
295
+ slice_size = num_slicable_layers * [1]
296
+
297
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
298
+
299
+ if len(slice_size) != len(sliceable_head_dims):
300
+ raise ValueError(
301
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
302
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
303
+ )
304
+
305
+ for i in range(len(slice_size)):
306
+ size = slice_size[i]
307
+ dim = sliceable_head_dims[i]
308
+ if size is not None and size > dim:
309
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
310
+
311
+ # Recursively walk through all the children.
312
+ # Any children which exposes the set_attention_slice method
313
+ # gets the message
314
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
315
+ if hasattr(module, "set_attention_slice"):
316
+ module.set_attention_slice(slice_size.pop())
317
+
318
+ for child in module.children():
319
+ fn_recursive_set_attention_slice(child, slice_size)
320
+
321
+ reversed_slice_size = list(reversed(slice_size))
322
+ for module in self.children():
323
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
324
+
325
+ def _set_gradient_checkpointing(self, module, value=False):
326
+ if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
327
+ module.gradient_checkpointing = value
328
+
329
+ def forward(
330
+ self,
331
+ sample: torch.FloatTensor,
332
+ timestep: Union[torch.Tensor, float, int],
333
+ encoder_hidden_states: torch.Tensor,
334
+ class_labels: Optional[torch.Tensor] = None,
335
+ attention_mask: Optional[torch.Tensor] = None,
336
+ # support controlnet
337
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
338
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
339
+ return_dict: bool = True,
340
+ ) -> Union[UNet3DConditionOutput, Tuple]:
341
+ r"""
342
+ Args:
343
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
344
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
345
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
346
+ return_dict (`bool`, *optional*, defaults to `True`):
347
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
348
+
349
+ Returns:
350
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
351
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
352
+ returning a tuple, the first element is the sample tensor.
353
+ """
354
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
355
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
356
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
357
+ # on the fly if necessary.
358
+ default_overall_up_factor = 2**self.num_upsamplers
359
+
360
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
361
+ forward_upsample_size = False
362
+ upsample_size = None
363
+
364
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
365
+ logger.info("Forward upsample size to force interpolation output size.")
366
+ forward_upsample_size = True
367
+
368
+ # prepare attention_mask
369
+ if attention_mask is not None:
370
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
371
+ attention_mask = attention_mask.unsqueeze(1)
372
+
373
+ # center input if necessary
374
+ if self.config.center_input_sample:
375
+ sample = 2 * sample - 1.0
376
+
377
+ # time
378
+ timesteps = timestep
379
+ if not torch.is_tensor(timesteps):
380
+ # This would be a good case for the `match` statement (Python 3.10+)
381
+ is_mps = sample.device.type == "mps"
382
+ if isinstance(timestep, float):
383
+ dtype = torch.float32 if is_mps else torch.float64
384
+ else:
385
+ dtype = torch.int32 if is_mps else torch.int64
386
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
387
+ elif len(timesteps.shape) == 0:
388
+ timesteps = timesteps[None].to(sample.device)
389
+
390
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
391
+ timesteps = timesteps.expand(sample.shape[0])
392
+
393
+ t_emb = self.time_proj(timesteps)
394
+
395
+ # timesteps does not contain any weights and will always return f32 tensors
396
+ # but time_embedding might actually be running in fp16. so we need to cast here.
397
+ # there might be better ways to encapsulate this.
398
+ t_emb = t_emb.to(dtype=self.dtype)
399
+ emb = self.time_embedding(t_emb)
400
+
401
+ if self.class_embedding is not None:
402
+ if class_labels is None:
403
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
404
+
405
+ if self.config.class_embed_type == "timestep":
406
+ class_labels = self.time_proj(class_labels)
407
+
408
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
409
+ emb = emb + class_emb
410
+
411
+ # pre-process
412
+ sample = self.conv_in(sample)
413
+
414
+ # down
415
+ down_block_res_samples = (sample,)
416
+ for downsample_block in self.down_blocks:
417
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
418
+ sample, res_samples = downsample_block(
419
+ hidden_states=sample,
420
+ temb=emb,
421
+ encoder_hidden_states=encoder_hidden_states,
422
+ attention_mask=attention_mask,
423
+ )
424
+ else:
425
+ sample, res_samples = downsample_block(
426
+ hidden_states=sample, temb=emb, encoder_hidden_states=encoder_hidden_states
427
+ )
428
+
429
+ down_block_res_samples += res_samples
430
+
431
+ # support controlnet
432
+ down_block_res_samples = list(down_block_res_samples)
433
+ if down_block_additional_residuals is not None:
434
+ for i, down_block_additional_residual in enumerate(down_block_additional_residuals):
435
+ if down_block_additional_residual.dim() == 4: # boardcast
436
+ down_block_additional_residual = down_block_additional_residual.unsqueeze(2)
437
+ down_block_res_samples[i] = down_block_res_samples[i] + down_block_additional_residual
438
+
439
+ # mid
440
+ sample = self.mid_block(
441
+ sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
442
+ )
443
+
444
+ # support controlnet
445
+ if mid_block_additional_residual is not None:
446
+ if mid_block_additional_residual.dim() == 4: # boardcast
447
+ mid_block_additional_residual = mid_block_additional_residual.unsqueeze(2)
448
+ sample = sample + mid_block_additional_residual
449
+
450
+ # up
451
+ for i, upsample_block in enumerate(self.up_blocks):
452
+ is_final_block = i == len(self.up_blocks) - 1
453
+
454
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
455
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
456
+
457
+ # if we have not reached the final block and need to forward the
458
+ # upsample size, we do it here
459
+ if not is_final_block and forward_upsample_size:
460
+ upsample_size = down_block_res_samples[-1].shape[2:]
461
+
462
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
463
+ sample = upsample_block(
464
+ hidden_states=sample,
465
+ temb=emb,
466
+ res_hidden_states_tuple=res_samples,
467
+ encoder_hidden_states=encoder_hidden_states,
468
+ upsample_size=upsample_size,
469
+ attention_mask=attention_mask,
470
+ )
471
+ else:
472
+ sample = upsample_block(
473
+ hidden_states=sample,
474
+ temb=emb,
475
+ res_hidden_states_tuple=res_samples,
476
+ upsample_size=upsample_size,
477
+ encoder_hidden_states=encoder_hidden_states,
478
+ )
479
+
480
+ # post-process
481
+ sample = self.conv_norm_out(sample)
482
+ sample = self.conv_act(sample)
483
+ sample = self.conv_out(sample)
484
+
485
+ if not return_dict:
486
+ return (sample,)
487
+
488
+ return UNet3DConditionOutput(sample=sample)
489
+
490
+ def load_state_dict(self, state_dict, strict=True):
491
+ # If the loaded checkpoint's in_channels or out_channels are different from config
492
+ temp_state_dict = copy.deepcopy(state_dict)
493
+ if temp_state_dict["conv_in.weight"].shape[1] != self.config.in_channels:
494
+ del temp_state_dict["conv_in.weight"]
495
+ del temp_state_dict["conv_in.bias"]
496
+ if temp_state_dict["conv_out.weight"].shape[0] != self.config.out_channels:
497
+ del temp_state_dict["conv_out.weight"]
498
+ del temp_state_dict["conv_out.bias"]
499
+
500
+ # If the loaded checkpoint's cross_attention_dim is different from config
501
+ keys_to_remove = []
502
+ for key in temp_state_dict:
503
+ if "audio_cross_attn.attn.to_k." in key or "audio_cross_attn.attn.to_v." in key:
504
+ if temp_state_dict[key].shape[1] != self.config.cross_attention_dim:
505
+ keys_to_remove.append(key)
506
+
507
+ for key in keys_to_remove:
508
+ del temp_state_dict[key]
509
+
510
+ return super().load_state_dict(state_dict=temp_state_dict, strict=strict)
511
+
512
+ @classmethod
513
+ def from_pretrained(cls, model_config: dict, ckpt_path: str, device="cpu"):
514
+ unet = cls.from_config(model_config).to(device)
515
+ if ckpt_path != "":
516
+ zero_rank_log(logger, f"Load from checkpoint: {ckpt_path}")
517
+ ckpt = torch.load(ckpt_path, map_location=device)
518
+ if "global_step" in ckpt:
519
+ zero_rank_log(logger, f"resume from global_step: {ckpt['global_step']}")
520
+ resume_global_step = ckpt["global_step"]
521
+ else:
522
+ resume_global_step = 0
523
+ state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt
524
+ unet.load_state_dict(state_dict, strict=False)
525
+ else:
526
+ resume_global_step = 0
527
+
528
+ return unet, resume_global_step
latentsync/models/unet_blocks.py ADDED
@@ -0,0 +1,903 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/guoyww/AnimateDiff/blob/main/animatediff/models/unet_blocks.py
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from .attention import Transformer3DModel
7
+ from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
8
+ from .motion_module import get_motion_module
9
+
10
+
11
+ def get_down_block(
12
+ down_block_type,
13
+ num_layers,
14
+ in_channels,
15
+ out_channels,
16
+ temb_channels,
17
+ add_downsample,
18
+ resnet_eps,
19
+ resnet_act_fn,
20
+ attn_num_head_channels,
21
+ resnet_groups=None,
22
+ cross_attention_dim=None,
23
+ downsample_padding=None,
24
+ dual_cross_attention=False,
25
+ use_linear_projection=False,
26
+ only_cross_attention=False,
27
+ upcast_attention=False,
28
+ resnet_time_scale_shift="default",
29
+ unet_use_cross_frame_attention=False,
30
+ unet_use_temporal_attention=False,
31
+ use_inflated_groupnorm=False,
32
+ use_motion_module=None,
33
+ motion_module_type=None,
34
+ motion_module_kwargs=None,
35
+ add_audio_layer=False,
36
+ audio_condition_method="cross_attn",
37
+ custom_audio_layer=False,
38
+ ):
39
+ down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
40
+ if down_block_type == "DownBlock3D":
41
+ return DownBlock3D(
42
+ num_layers=num_layers,
43
+ in_channels=in_channels,
44
+ out_channels=out_channels,
45
+ temb_channels=temb_channels,
46
+ add_downsample=add_downsample,
47
+ resnet_eps=resnet_eps,
48
+ resnet_act_fn=resnet_act_fn,
49
+ resnet_groups=resnet_groups,
50
+ downsample_padding=downsample_padding,
51
+ resnet_time_scale_shift=resnet_time_scale_shift,
52
+ use_inflated_groupnorm=use_inflated_groupnorm,
53
+ use_motion_module=use_motion_module,
54
+ motion_module_type=motion_module_type,
55
+ motion_module_kwargs=motion_module_kwargs,
56
+ )
57
+ elif down_block_type == "CrossAttnDownBlock3D":
58
+ if cross_attention_dim is None:
59
+ raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
60
+ return CrossAttnDownBlock3D(
61
+ num_layers=num_layers,
62
+ in_channels=in_channels,
63
+ out_channels=out_channels,
64
+ temb_channels=temb_channels,
65
+ add_downsample=add_downsample,
66
+ resnet_eps=resnet_eps,
67
+ resnet_act_fn=resnet_act_fn,
68
+ resnet_groups=resnet_groups,
69
+ downsample_padding=downsample_padding,
70
+ cross_attention_dim=cross_attention_dim,
71
+ attn_num_head_channels=attn_num_head_channels,
72
+ dual_cross_attention=dual_cross_attention,
73
+ use_linear_projection=use_linear_projection,
74
+ only_cross_attention=only_cross_attention,
75
+ upcast_attention=upcast_attention,
76
+ resnet_time_scale_shift=resnet_time_scale_shift,
77
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
78
+ unet_use_temporal_attention=unet_use_temporal_attention,
79
+ use_inflated_groupnorm=use_inflated_groupnorm,
80
+ use_motion_module=use_motion_module,
81
+ motion_module_type=motion_module_type,
82
+ motion_module_kwargs=motion_module_kwargs,
83
+ add_audio_layer=add_audio_layer,
84
+ audio_condition_method=audio_condition_method,
85
+ custom_audio_layer=custom_audio_layer,
86
+ )
87
+ raise ValueError(f"{down_block_type} does not exist.")
88
+
89
+
90
+ def get_up_block(
91
+ up_block_type,
92
+ num_layers,
93
+ in_channels,
94
+ out_channels,
95
+ prev_output_channel,
96
+ temb_channels,
97
+ add_upsample,
98
+ resnet_eps,
99
+ resnet_act_fn,
100
+ attn_num_head_channels,
101
+ resnet_groups=None,
102
+ cross_attention_dim=None,
103
+ dual_cross_attention=False,
104
+ use_linear_projection=False,
105
+ only_cross_attention=False,
106
+ upcast_attention=False,
107
+ resnet_time_scale_shift="default",
108
+ unet_use_cross_frame_attention=False,
109
+ unet_use_temporal_attention=False,
110
+ use_inflated_groupnorm=False,
111
+ use_motion_module=None,
112
+ motion_module_type=None,
113
+ motion_module_kwargs=None,
114
+ add_audio_layer=False,
115
+ audio_condition_method="cross_attn",
116
+ custom_audio_layer=False,
117
+ ):
118
+ up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
119
+ if up_block_type == "UpBlock3D":
120
+ return UpBlock3D(
121
+ num_layers=num_layers,
122
+ in_channels=in_channels,
123
+ out_channels=out_channels,
124
+ prev_output_channel=prev_output_channel,
125
+ temb_channels=temb_channels,
126
+ add_upsample=add_upsample,
127
+ resnet_eps=resnet_eps,
128
+ resnet_act_fn=resnet_act_fn,
129
+ resnet_groups=resnet_groups,
130
+ resnet_time_scale_shift=resnet_time_scale_shift,
131
+ use_inflated_groupnorm=use_inflated_groupnorm,
132
+ use_motion_module=use_motion_module,
133
+ motion_module_type=motion_module_type,
134
+ motion_module_kwargs=motion_module_kwargs,
135
+ )
136
+ elif up_block_type == "CrossAttnUpBlock3D":
137
+ if cross_attention_dim is None:
138
+ raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
139
+ return CrossAttnUpBlock3D(
140
+ num_layers=num_layers,
141
+ in_channels=in_channels,
142
+ out_channels=out_channels,
143
+ prev_output_channel=prev_output_channel,
144
+ temb_channels=temb_channels,
145
+ add_upsample=add_upsample,
146
+ resnet_eps=resnet_eps,
147
+ resnet_act_fn=resnet_act_fn,
148
+ resnet_groups=resnet_groups,
149
+ cross_attention_dim=cross_attention_dim,
150
+ attn_num_head_channels=attn_num_head_channels,
151
+ dual_cross_attention=dual_cross_attention,
152
+ use_linear_projection=use_linear_projection,
153
+ only_cross_attention=only_cross_attention,
154
+ upcast_attention=upcast_attention,
155
+ resnet_time_scale_shift=resnet_time_scale_shift,
156
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
157
+ unet_use_temporal_attention=unet_use_temporal_attention,
158
+ use_inflated_groupnorm=use_inflated_groupnorm,
159
+ use_motion_module=use_motion_module,
160
+ motion_module_type=motion_module_type,
161
+ motion_module_kwargs=motion_module_kwargs,
162
+ add_audio_layer=add_audio_layer,
163
+ audio_condition_method=audio_condition_method,
164
+ custom_audio_layer=custom_audio_layer,
165
+ )
166
+ raise ValueError(f"{up_block_type} does not exist.")
167
+
168
+
169
+ class UNetMidBlock3DCrossAttn(nn.Module):
170
+ def __init__(
171
+ self,
172
+ in_channels: int,
173
+ temb_channels: int,
174
+ dropout: float = 0.0,
175
+ num_layers: int = 1,
176
+ resnet_eps: float = 1e-6,
177
+ resnet_time_scale_shift: str = "default",
178
+ resnet_act_fn: str = "swish",
179
+ resnet_groups: int = 32,
180
+ resnet_pre_norm: bool = True,
181
+ attn_num_head_channels=1,
182
+ output_scale_factor=1.0,
183
+ cross_attention_dim=1280,
184
+ dual_cross_attention=False,
185
+ use_linear_projection=False,
186
+ upcast_attention=False,
187
+ unet_use_cross_frame_attention=False,
188
+ unet_use_temporal_attention=False,
189
+ use_inflated_groupnorm=False,
190
+ use_motion_module=None,
191
+ motion_module_type=None,
192
+ motion_module_kwargs=None,
193
+ add_audio_layer=False,
194
+ audio_condition_method="cross_attn",
195
+ custom_audio_layer: bool = False,
196
+ ):
197
+ super().__init__()
198
+
199
+ self.has_cross_attention = True
200
+ self.attn_num_head_channels = attn_num_head_channels
201
+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
202
+
203
+ # there is always at least one resnet
204
+ resnets = [
205
+ ResnetBlock3D(
206
+ in_channels=in_channels,
207
+ out_channels=in_channels,
208
+ temb_channels=temb_channels,
209
+ eps=resnet_eps,
210
+ groups=resnet_groups,
211
+ dropout=dropout,
212
+ time_embedding_norm=resnet_time_scale_shift,
213
+ non_linearity=resnet_act_fn,
214
+ output_scale_factor=output_scale_factor,
215
+ pre_norm=resnet_pre_norm,
216
+ use_inflated_groupnorm=use_inflated_groupnorm,
217
+ )
218
+ ]
219
+ attentions = []
220
+ audio_attentions = []
221
+ motion_modules = []
222
+
223
+ for _ in range(num_layers):
224
+ if dual_cross_attention:
225
+ raise NotImplementedError
226
+ attentions.append(
227
+ Transformer3DModel(
228
+ attn_num_head_channels,
229
+ in_channels // attn_num_head_channels,
230
+ in_channels=in_channels,
231
+ num_layers=1,
232
+ cross_attention_dim=cross_attention_dim,
233
+ norm_num_groups=resnet_groups,
234
+ use_linear_projection=use_linear_projection,
235
+ upcast_attention=upcast_attention,
236
+ use_motion_module=use_motion_module,
237
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
238
+ unet_use_temporal_attention=unet_use_temporal_attention,
239
+ add_audio_layer=add_audio_layer,
240
+ audio_condition_method=audio_condition_method,
241
+ )
242
+ )
243
+ audio_attentions.append(
244
+ Transformer3DModel(
245
+ attn_num_head_channels,
246
+ in_channels // attn_num_head_channels,
247
+ in_channels=in_channels,
248
+ num_layers=1,
249
+ cross_attention_dim=cross_attention_dim,
250
+ norm_num_groups=resnet_groups,
251
+ use_linear_projection=use_linear_projection,
252
+ upcast_attention=upcast_attention,
253
+ use_motion_module=use_motion_module,
254
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
255
+ unet_use_temporal_attention=unet_use_temporal_attention,
256
+ add_audio_layer=add_audio_layer,
257
+ audio_condition_method=audio_condition_method,
258
+ custom_audio_layer=True,
259
+ )
260
+ if custom_audio_layer
261
+ else None
262
+ )
263
+ motion_modules.append(
264
+ get_motion_module(
265
+ in_channels=in_channels,
266
+ motion_module_type=motion_module_type,
267
+ motion_module_kwargs=motion_module_kwargs,
268
+ )
269
+ if use_motion_module
270
+ else None
271
+ )
272
+ resnets.append(
273
+ ResnetBlock3D(
274
+ in_channels=in_channels,
275
+ out_channels=in_channels,
276
+ temb_channels=temb_channels,
277
+ eps=resnet_eps,
278
+ groups=resnet_groups,
279
+ dropout=dropout,
280
+ time_embedding_norm=resnet_time_scale_shift,
281
+ non_linearity=resnet_act_fn,
282
+ output_scale_factor=output_scale_factor,
283
+ pre_norm=resnet_pre_norm,
284
+ use_inflated_groupnorm=use_inflated_groupnorm,
285
+ )
286
+ )
287
+
288
+ self.attentions = nn.ModuleList(attentions)
289
+ self.audio_attentions = nn.ModuleList(audio_attentions)
290
+ self.resnets = nn.ModuleList(resnets)
291
+ self.motion_modules = nn.ModuleList(motion_modules)
292
+
293
+ def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None):
294
+ hidden_states = self.resnets[0](hidden_states, temb)
295
+ for attn, audio_attn, resnet, motion_module in zip(
296
+ self.attentions, self.audio_attentions, self.resnets[1:], self.motion_modules
297
+ ):
298
+ hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
299
+ hidden_states = (
300
+ audio_attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
301
+ if audio_attn is not None
302
+ else hidden_states
303
+ )
304
+ hidden_states = (
305
+ motion_module(hidden_states, temb, encoder_hidden_states=encoder_hidden_states)
306
+ if motion_module is not None
307
+ else hidden_states
308
+ )
309
+ hidden_states = resnet(hidden_states, temb)
310
+
311
+ return hidden_states
312
+
313
+
314
+ class CrossAttnDownBlock3D(nn.Module):
315
+ def __init__(
316
+ self,
317
+ in_channels: int,
318
+ out_channels: int,
319
+ temb_channels: int,
320
+ dropout: float = 0.0,
321
+ num_layers: int = 1,
322
+ resnet_eps: float = 1e-6,
323
+ resnet_time_scale_shift: str = "default",
324
+ resnet_act_fn: str = "swish",
325
+ resnet_groups: int = 32,
326
+ resnet_pre_norm: bool = True,
327
+ attn_num_head_channels=1,
328
+ cross_attention_dim=1280,
329
+ output_scale_factor=1.0,
330
+ downsample_padding=1,
331
+ add_downsample=True,
332
+ dual_cross_attention=False,
333
+ use_linear_projection=False,
334
+ only_cross_attention=False,
335
+ upcast_attention=False,
336
+ unet_use_cross_frame_attention=False,
337
+ unet_use_temporal_attention=False,
338
+ use_inflated_groupnorm=False,
339
+ use_motion_module=None,
340
+ motion_module_type=None,
341
+ motion_module_kwargs=None,
342
+ add_audio_layer=False,
343
+ audio_condition_method="cross_attn",
344
+ custom_audio_layer: bool = False,
345
+ ):
346
+ super().__init__()
347
+ resnets = []
348
+ attentions = []
349
+ audio_attentions = []
350
+ motion_modules = []
351
+
352
+ self.has_cross_attention = True
353
+ self.attn_num_head_channels = attn_num_head_channels
354
+
355
+ for i in range(num_layers):
356
+ in_channels = in_channels if i == 0 else out_channels
357
+ resnets.append(
358
+ ResnetBlock3D(
359
+ in_channels=in_channels,
360
+ out_channels=out_channels,
361
+ temb_channels=temb_channels,
362
+ eps=resnet_eps,
363
+ groups=resnet_groups,
364
+ dropout=dropout,
365
+ time_embedding_norm=resnet_time_scale_shift,
366
+ non_linearity=resnet_act_fn,
367
+ output_scale_factor=output_scale_factor,
368
+ pre_norm=resnet_pre_norm,
369
+ use_inflated_groupnorm=use_inflated_groupnorm,
370
+ )
371
+ )
372
+ if dual_cross_attention:
373
+ raise NotImplementedError
374
+ attentions.append(
375
+ Transformer3DModel(
376
+ attn_num_head_channels,
377
+ out_channels // attn_num_head_channels,
378
+ in_channels=out_channels,
379
+ num_layers=1,
380
+ cross_attention_dim=cross_attention_dim,
381
+ norm_num_groups=resnet_groups,
382
+ use_linear_projection=use_linear_projection,
383
+ only_cross_attention=only_cross_attention,
384
+ upcast_attention=upcast_attention,
385
+ use_motion_module=use_motion_module,
386
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
387
+ unet_use_temporal_attention=unet_use_temporal_attention,
388
+ add_audio_layer=add_audio_layer,
389
+ audio_condition_method=audio_condition_method,
390
+ )
391
+ )
392
+ audio_attentions.append(
393
+ Transformer3DModel(
394
+ attn_num_head_channels,
395
+ out_channels // attn_num_head_channels,
396
+ in_channels=out_channels,
397
+ num_layers=1,
398
+ cross_attention_dim=cross_attention_dim,
399
+ norm_num_groups=resnet_groups,
400
+ use_linear_projection=use_linear_projection,
401
+ only_cross_attention=only_cross_attention,
402
+ upcast_attention=upcast_attention,
403
+ use_motion_module=use_motion_module,
404
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
405
+ unet_use_temporal_attention=unet_use_temporal_attention,
406
+ add_audio_layer=add_audio_layer,
407
+ audio_condition_method=audio_condition_method,
408
+ custom_audio_layer=True,
409
+ )
410
+ if custom_audio_layer
411
+ else None
412
+ )
413
+ motion_modules.append(
414
+ get_motion_module(
415
+ in_channels=out_channels,
416
+ motion_module_type=motion_module_type,
417
+ motion_module_kwargs=motion_module_kwargs,
418
+ )
419
+ if use_motion_module
420
+ else None
421
+ )
422
+
423
+ self.attentions = nn.ModuleList(attentions)
424
+ self.audio_attentions = nn.ModuleList(audio_attentions)
425
+ self.resnets = nn.ModuleList(resnets)
426
+ self.motion_modules = nn.ModuleList(motion_modules)
427
+
428
+ if add_downsample:
429
+ self.downsamplers = nn.ModuleList(
430
+ [
431
+ Downsample3D(
432
+ out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
433
+ )
434
+ ]
435
+ )
436
+ else:
437
+ self.downsamplers = None
438
+
439
+ self.gradient_checkpointing = False
440
+
441
+ def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None):
442
+ output_states = ()
443
+
444
+ for resnet, attn, audio_attn, motion_module in zip(
445
+ self.resnets, self.attentions, self.audio_attentions, self.motion_modules
446
+ ):
447
+ if self.training and self.gradient_checkpointing:
448
+
449
+ def create_custom_forward(module, return_dict=None):
450
+ def custom_forward(*inputs):
451
+ if return_dict is not None:
452
+ return module(*inputs, return_dict=return_dict)
453
+ else:
454
+ return module(*inputs)
455
+
456
+ return custom_forward
457
+
458
+ hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
459
+ hidden_states = torch.utils.checkpoint.checkpoint(
460
+ create_custom_forward(attn, return_dict=False),
461
+ hidden_states,
462
+ encoder_hidden_states,
463
+ )[0]
464
+ if motion_module is not None:
465
+ hidden_states = torch.utils.checkpoint.checkpoint(
466
+ create_custom_forward(motion_module),
467
+ hidden_states.requires_grad_(),
468
+ temb,
469
+ encoder_hidden_states,
470
+ )
471
+
472
+ else:
473
+ hidden_states = resnet(hidden_states, temb)
474
+ hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
475
+
476
+ hidden_states = (
477
+ audio_attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
478
+ if audio_attn is not None
479
+ else hidden_states
480
+ )
481
+
482
+ # add motion module
483
+ hidden_states = (
484
+ motion_module(hidden_states, temb, encoder_hidden_states=encoder_hidden_states)
485
+ if motion_module is not None
486
+ else hidden_states
487
+ )
488
+
489
+ output_states += (hidden_states,)
490
+
491
+ if self.downsamplers is not None:
492
+ for downsampler in self.downsamplers:
493
+ hidden_states = downsampler(hidden_states)
494
+
495
+ output_states += (hidden_states,)
496
+
497
+ return hidden_states, output_states
498
+
499
+
500
+ class DownBlock3D(nn.Module):
501
+ def __init__(
502
+ self,
503
+ in_channels: int,
504
+ out_channels: int,
505
+ temb_channels: int,
506
+ dropout: float = 0.0,
507
+ num_layers: int = 1,
508
+ resnet_eps: float = 1e-6,
509
+ resnet_time_scale_shift: str = "default",
510
+ resnet_act_fn: str = "swish",
511
+ resnet_groups: int = 32,
512
+ resnet_pre_norm: bool = True,
513
+ output_scale_factor=1.0,
514
+ add_downsample=True,
515
+ downsample_padding=1,
516
+ use_inflated_groupnorm=False,
517
+ use_motion_module=None,
518
+ motion_module_type=None,
519
+ motion_module_kwargs=None,
520
+ ):
521
+ super().__init__()
522
+ resnets = []
523
+ motion_modules = []
524
+
525
+ for i in range(num_layers):
526
+ in_channels = in_channels if i == 0 else out_channels
527
+ resnets.append(
528
+ ResnetBlock3D(
529
+ in_channels=in_channels,
530
+ out_channels=out_channels,
531
+ temb_channels=temb_channels,
532
+ eps=resnet_eps,
533
+ groups=resnet_groups,
534
+ dropout=dropout,
535
+ time_embedding_norm=resnet_time_scale_shift,
536
+ non_linearity=resnet_act_fn,
537
+ output_scale_factor=output_scale_factor,
538
+ pre_norm=resnet_pre_norm,
539
+ use_inflated_groupnorm=use_inflated_groupnorm,
540
+ )
541
+ )
542
+ motion_modules.append(
543
+ get_motion_module(
544
+ in_channels=out_channels,
545
+ motion_module_type=motion_module_type,
546
+ motion_module_kwargs=motion_module_kwargs,
547
+ )
548
+ if use_motion_module
549
+ else None
550
+ )
551
+
552
+ self.resnets = nn.ModuleList(resnets)
553
+ self.motion_modules = nn.ModuleList(motion_modules)
554
+
555
+ if add_downsample:
556
+ self.downsamplers = nn.ModuleList(
557
+ [
558
+ Downsample3D(
559
+ out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
560
+ )
561
+ ]
562
+ )
563
+ else:
564
+ self.downsamplers = None
565
+
566
+ self.gradient_checkpointing = False
567
+
568
+ def forward(self, hidden_states, temb=None, encoder_hidden_states=None):
569
+ output_states = ()
570
+
571
+ for resnet, motion_module in zip(self.resnets, self.motion_modules):
572
+ if self.training and self.gradient_checkpointing:
573
+
574
+ def create_custom_forward(module):
575
+ def custom_forward(*inputs):
576
+ return module(*inputs)
577
+
578
+ return custom_forward
579
+
580
+ hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
581
+ if motion_module is not None:
582
+ hidden_states = torch.utils.checkpoint.checkpoint(
583
+ create_custom_forward(motion_module),
584
+ hidden_states.requires_grad_(),
585
+ temb,
586
+ encoder_hidden_states,
587
+ )
588
+ else:
589
+ hidden_states = resnet(hidden_states, temb)
590
+
591
+ # add motion module
592
+ hidden_states = (
593
+ motion_module(hidden_states, temb, encoder_hidden_states=encoder_hidden_states)
594
+ if motion_module is not None
595
+ else hidden_states
596
+ )
597
+
598
+ output_states += (hidden_states,)
599
+
600
+ if self.downsamplers is not None:
601
+ for downsampler in self.downsamplers:
602
+ hidden_states = downsampler(hidden_states)
603
+
604
+ output_states += (hidden_states,)
605
+
606
+ return hidden_states, output_states
607
+
608
+
609
+ class CrossAttnUpBlock3D(nn.Module):
610
+ def __init__(
611
+ self,
612
+ in_channels: int,
613
+ out_channels: int,
614
+ prev_output_channel: int,
615
+ temb_channels: int,
616
+ dropout: float = 0.0,
617
+ num_layers: int = 1,
618
+ resnet_eps: float = 1e-6,
619
+ resnet_time_scale_shift: str = "default",
620
+ resnet_act_fn: str = "swish",
621
+ resnet_groups: int = 32,
622
+ resnet_pre_norm: bool = True,
623
+ attn_num_head_channels=1,
624
+ cross_attention_dim=1280,
625
+ output_scale_factor=1.0,
626
+ add_upsample=True,
627
+ dual_cross_attention=False,
628
+ use_linear_projection=False,
629
+ only_cross_attention=False,
630
+ upcast_attention=False,
631
+ unet_use_cross_frame_attention=False,
632
+ unet_use_temporal_attention=False,
633
+ use_inflated_groupnorm=False,
634
+ use_motion_module=None,
635
+ motion_module_type=None,
636
+ motion_module_kwargs=None,
637
+ add_audio_layer=False,
638
+ audio_condition_method="cross_attn",
639
+ custom_audio_layer=False,
640
+ ):
641
+ super().__init__()
642
+ resnets = []
643
+ attentions = []
644
+ audio_attentions = []
645
+ motion_modules = []
646
+
647
+ self.has_cross_attention = True
648
+ self.attn_num_head_channels = attn_num_head_channels
649
+
650
+ for i in range(num_layers):
651
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
652
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
653
+
654
+ resnets.append(
655
+ ResnetBlock3D(
656
+ in_channels=resnet_in_channels + res_skip_channels,
657
+ out_channels=out_channels,
658
+ temb_channels=temb_channels,
659
+ eps=resnet_eps,
660
+ groups=resnet_groups,
661
+ dropout=dropout,
662
+ time_embedding_norm=resnet_time_scale_shift,
663
+ non_linearity=resnet_act_fn,
664
+ output_scale_factor=output_scale_factor,
665
+ pre_norm=resnet_pre_norm,
666
+ use_inflated_groupnorm=use_inflated_groupnorm,
667
+ )
668
+ )
669
+ if dual_cross_attention:
670
+ raise NotImplementedError
671
+ attentions.append(
672
+ Transformer3DModel(
673
+ attn_num_head_channels,
674
+ out_channels // attn_num_head_channels,
675
+ in_channels=out_channels,
676
+ num_layers=1,
677
+ cross_attention_dim=cross_attention_dim,
678
+ norm_num_groups=resnet_groups,
679
+ use_linear_projection=use_linear_projection,
680
+ only_cross_attention=only_cross_attention,
681
+ upcast_attention=upcast_attention,
682
+ use_motion_module=use_motion_module,
683
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
684
+ unet_use_temporal_attention=unet_use_temporal_attention,
685
+ add_audio_layer=add_audio_layer,
686
+ audio_condition_method=audio_condition_method,
687
+ )
688
+ )
689
+ audio_attentions.append(
690
+ Transformer3DModel(
691
+ attn_num_head_channels,
692
+ out_channels // attn_num_head_channels,
693
+ in_channels=out_channels,
694
+ num_layers=1,
695
+ cross_attention_dim=cross_attention_dim,
696
+ norm_num_groups=resnet_groups,
697
+ use_linear_projection=use_linear_projection,
698
+ only_cross_attention=only_cross_attention,
699
+ upcast_attention=upcast_attention,
700
+ use_motion_module=use_motion_module,
701
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
702
+ unet_use_temporal_attention=unet_use_temporal_attention,
703
+ add_audio_layer=add_audio_layer,
704
+ audio_condition_method=audio_condition_method,
705
+ custom_audio_layer=True,
706
+ )
707
+ if custom_audio_layer
708
+ else None
709
+ )
710
+ motion_modules.append(
711
+ get_motion_module(
712
+ in_channels=out_channels,
713
+ motion_module_type=motion_module_type,
714
+ motion_module_kwargs=motion_module_kwargs,
715
+ )
716
+ if use_motion_module
717
+ else None
718
+ )
719
+
720
+ self.attentions = nn.ModuleList(attentions)
721
+ self.audio_attentions = nn.ModuleList(audio_attentions)
722
+ self.resnets = nn.ModuleList(resnets)
723
+ self.motion_modules = nn.ModuleList(motion_modules)
724
+
725
+ if add_upsample:
726
+ self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
727
+ else:
728
+ self.upsamplers = None
729
+
730
+ self.gradient_checkpointing = False
731
+
732
+ def forward(
733
+ self,
734
+ hidden_states,
735
+ res_hidden_states_tuple,
736
+ temb=None,
737
+ encoder_hidden_states=None,
738
+ upsample_size=None,
739
+ attention_mask=None,
740
+ ):
741
+ for resnet, attn, audio_attn, motion_module in zip(
742
+ self.resnets, self.attentions, self.audio_attentions, self.motion_modules
743
+ ):
744
+ # pop res hidden states
745
+ res_hidden_states = res_hidden_states_tuple[-1]
746
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
747
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
748
+
749
+ if self.training and self.gradient_checkpointing:
750
+
751
+ def create_custom_forward(module, return_dict=None):
752
+ def custom_forward(*inputs):
753
+ if return_dict is not None:
754
+ return module(*inputs, return_dict=return_dict)
755
+ else:
756
+ return module(*inputs)
757
+
758
+ return custom_forward
759
+
760
+ hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
761
+ hidden_states = torch.utils.checkpoint.checkpoint(
762
+ create_custom_forward(attn, return_dict=False),
763
+ hidden_states,
764
+ encoder_hidden_states,
765
+ )[0]
766
+ if motion_module is not None:
767
+ hidden_states = torch.utils.checkpoint.checkpoint(
768
+ create_custom_forward(motion_module),
769
+ hidden_states.requires_grad_(),
770
+ temb,
771
+ encoder_hidden_states,
772
+ )
773
+
774
+ else:
775
+ hidden_states = resnet(hidden_states, temb)
776
+ hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
777
+ hidden_states = (
778
+ audio_attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
779
+ if audio_attn is not None
780
+ else hidden_states
781
+ )
782
+
783
+ # add motion module
784
+ hidden_states = (
785
+ motion_module(hidden_states, temb, encoder_hidden_states=encoder_hidden_states)
786
+ if motion_module is not None
787
+ else hidden_states
788
+ )
789
+
790
+ if self.upsamplers is not None:
791
+ for upsampler in self.upsamplers:
792
+ hidden_states = upsampler(hidden_states, upsample_size)
793
+
794
+ return hidden_states
795
+
796
+
797
+ class UpBlock3D(nn.Module):
798
+ def __init__(
799
+ self,
800
+ in_channels: int,
801
+ prev_output_channel: int,
802
+ out_channels: int,
803
+ temb_channels: int,
804
+ dropout: float = 0.0,
805
+ num_layers: int = 1,
806
+ resnet_eps: float = 1e-6,
807
+ resnet_time_scale_shift: str = "default",
808
+ resnet_act_fn: str = "swish",
809
+ resnet_groups: int = 32,
810
+ resnet_pre_norm: bool = True,
811
+ output_scale_factor=1.0,
812
+ add_upsample=True,
813
+ use_inflated_groupnorm=False,
814
+ use_motion_module=None,
815
+ motion_module_type=None,
816
+ motion_module_kwargs=None,
817
+ ):
818
+ super().__init__()
819
+ resnets = []
820
+ motion_modules = []
821
+
822
+ for i in range(num_layers):
823
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
824
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
825
+
826
+ resnets.append(
827
+ ResnetBlock3D(
828
+ in_channels=resnet_in_channels + res_skip_channels,
829
+ out_channels=out_channels,
830
+ temb_channels=temb_channels,
831
+ eps=resnet_eps,
832
+ groups=resnet_groups,
833
+ dropout=dropout,
834
+ time_embedding_norm=resnet_time_scale_shift,
835
+ non_linearity=resnet_act_fn,
836
+ output_scale_factor=output_scale_factor,
837
+ pre_norm=resnet_pre_norm,
838
+ use_inflated_groupnorm=use_inflated_groupnorm,
839
+ )
840
+ )
841
+ motion_modules.append(
842
+ get_motion_module(
843
+ in_channels=out_channels,
844
+ motion_module_type=motion_module_type,
845
+ motion_module_kwargs=motion_module_kwargs,
846
+ )
847
+ if use_motion_module
848
+ else None
849
+ )
850
+
851
+ self.resnets = nn.ModuleList(resnets)
852
+ self.motion_modules = nn.ModuleList(motion_modules)
853
+
854
+ if add_upsample:
855
+ self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
856
+ else:
857
+ self.upsamplers = None
858
+
859
+ self.gradient_checkpointing = False
860
+
861
+ def forward(
862
+ self,
863
+ hidden_states,
864
+ res_hidden_states_tuple,
865
+ temb=None,
866
+ upsample_size=None,
867
+ encoder_hidden_states=None,
868
+ ):
869
+ for resnet, motion_module in zip(self.resnets, self.motion_modules):
870
+ # pop res hidden states
871
+ res_hidden_states = res_hidden_states_tuple[-1]
872
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
873
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
874
+
875
+ if self.training and self.gradient_checkpointing:
876
+
877
+ def create_custom_forward(module):
878
+ def custom_forward(*inputs):
879
+ return module(*inputs)
880
+
881
+ return custom_forward
882
+
883
+ hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
884
+ if motion_module is not None:
885
+ hidden_states = torch.utils.checkpoint.checkpoint(
886
+ create_custom_forward(motion_module),
887
+ hidden_states.requires_grad_(),
888
+ temb,
889
+ encoder_hidden_states,
890
+ )
891
+ else:
892
+ hidden_states = resnet(hidden_states, temb)
893
+ hidden_states = (
894
+ motion_module(hidden_states, temb, encoder_hidden_states=encoder_hidden_states)
895
+ if motion_module is not None
896
+ else hidden_states
897
+ )
898
+
899
+ if self.upsamplers is not None:
900
+ for upsampler in self.upsamplers:
901
+ hidden_states = upsampler(hidden_states, upsample_size)
902
+
903
+ return hidden_states
latentsync/models/utils.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024 Bytedance Ltd. and/or its affiliates
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
+ def zero_module(module):
16
+ # Zero out the parameters of a module and return it.
17
+ for p in module.parameters():
18
+ p.detach().zero_()
19
+ return module
{pipelines β†’ latentsync/pipelines}/lipsync_pipeline.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/__init__.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/__init__.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/utils.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/videomaev2_finetune.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/third_party/VideoMAEv2/videomaev2_pretrain.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/third_party/__init__.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/utils/__init__.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/utils/data_utils.py RENAMED
File without changes
{trepa β†’ latentsync/trepa}/utils/metric_utils.py RENAMED
File without changes
{utils β†’ latentsync/utils}/affine_transform.py RENAMED
File without changes
{utils β†’ latentsync/utils}/audio.py RENAMED
File without changes
{utils β†’ latentsync/utils}/av_reader.py RENAMED
File without changes
{utils β†’ latentsync/utils}/image_processor.py RENAMED
File without changes
latentsync/utils/mask.png ADDED
{utils β†’ latentsync/utils}/util.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/audio2feature.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/__init__.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/__main__.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/gpt2/merges.txt RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/gpt2/special_tokens_map.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/gpt2/tokenizer_config.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/gpt2/vocab.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/mel_filters.npz RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/multilingual/added_tokens.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/multilingual/merges.txt RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/multilingual/special_tokens_map.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/multilingual/tokenizer_config.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/assets/multilingual/vocab.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/audio.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/decoding.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/model.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/normalizers/__init__.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/normalizers/basic.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/normalizers/english.json RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/normalizers/english.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/tokenizer.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/transcribe.py RENAMED
File without changes
{whisper β†’ latentsync/whisper}/whisper/utils.py RENAMED
File without changes