Spaces:
Running
on
Zero
Running
on
Zero
page demo
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +1 -0
- __pycache__/attn_ctrl.cpython-310.pyc +0 -0
- __pycache__/inference.cpython-310.pyc +0 -0
- __pycache__/train.cpython-310.pyc +0 -0
- app.py +7 -1
- assets/train/car_turn.mp4 +0 -0
- assets/train/dolly_zoom_out.mp4 +0 -0
- assets/train/orbit_shot.mp4 +0 -0
- assets/train/pan_up.mp4 +0 -0
- assets/train/run_up.mp4 +0 -0
- assets/train/santa_dance.mp4 +0 -0
- assets/train/train_ride.mp4 +0 -0
- assets/train/walk.mp4 +0 -0
- attn_ctrl.py +264 -0
- configs/config.yaml +67 -0
- dataset/__init__.py +5 -0
- dataset/__pycache__/__init__.cpython-310.pyc +0 -0
- dataset/__pycache__/cached_dataset.cpython-310.pyc +0 -0
- dataset/__pycache__/image_dataset.cpython-310.pyc +0 -0
- dataset/__pycache__/single_video_dataset.cpython-310.pyc +0 -0
- dataset/__pycache__/video_folder_dataset.cpython-310.pyc +0 -0
- dataset/__pycache__/video_json_dataset.cpython-310.pyc +0 -0
- dataset/cached_dataset.py +17 -0
- dataset/image_dataset.py +95 -0
- dataset/single_video_dataset.py +106 -0
- dataset/video_folder_dataset.py +90 -0
- dataset/video_json_dataset.py +183 -0
- inference.py +133 -0
- loss/__init__.py +4 -0
- loss/__pycache__/__init__.cpython-310.pyc +0 -0
- loss/__pycache__/base_loss.cpython-310.pyc +0 -0
- loss/__pycache__/debiased_hybrid_loss.cpython-310.pyc +0 -0
- loss/__pycache__/debiased_temporal_loss.cpython-310.pyc +0 -0
- loss/__pycache__/motion_distillation_loss.cpython-310.pyc +0 -0
- loss/base_loss.py +75 -0
- loss/debiased_hybrid_loss.py +149 -0
- loss/debiased_temporal_loss.py +86 -0
- loss/motion_distillation_loss.py +79 -0
- models/dit/latte_t2v.py +990 -0
- models/unet/__pycache__/motion_embeddings.cpython-310.pyc +0 -0
- models/unet/__pycache__/unet_3d_blocks.cpython-310.pyc +0 -0
- models/unet/__pycache__/unet_3d_condition.cpython-310.pyc +0 -0
- models/unet/motion_embeddings.py +283 -0
- models/unet/unet_3d_blocks.py +842 -0
- models/unet/unet_3d_condition.py +500 -0
- noise_init/__init__.py +4 -0
- noise_init/__pycache__/__init__.cpython-310.pyc +0 -0
- noise_init/__pycache__/blend_freq_init.cpython-310.pyc +0 -0
- noise_init/__pycache__/blend_init.cpython-310.pyc +0 -0
- noise_init/__pycache__/fft_init.cpython-310.pyc +0 -0
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
results/*
|
__pycache__/attn_ctrl.cpython-310.pyc
ADDED
Binary file (5.63 kB). View file
|
|
__pycache__/inference.cpython-310.pyc
ADDED
Binary file (3.09 kB). View file
|
|
__pycache__/train.cpython-310.pyc
ADDED
Binary file (11.1 kB). View file
|
|
app.py
CHANGED
@@ -14,7 +14,7 @@ from inference import inference as inference_main
|
|
14 |
def train_model(video, config):
|
15 |
output_dir = 'results'
|
16 |
os.makedirs(output_dir, exist_ok=True)
|
17 |
-
cur_save_dir = os.path.join(output_dir,
|
18 |
|
19 |
config.dataset.single_video_path = video
|
20 |
config.train.output_dir = cur_save_dir
|
@@ -100,6 +100,12 @@ def update_preview_video(checkpoint_dir):
|
|
100 |
|
101 |
|
102 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
inject_motion_embeddings_combinations = ['down 1280','up 1280','down 640','up 640']
|
104 |
default_motion_embeddings_combinations = ['down 1280','up 1280']
|
105 |
|
|
|
14 |
def train_model(video, config):
|
15 |
output_dir = 'results'
|
16 |
os.makedirs(output_dir, exist_ok=True)
|
17 |
+
cur_save_dir = os.path.join(output_dir, 'custom')
|
18 |
|
19 |
config.dataset.single_video_path = video
|
20 |
config.train.output_dir = cur_save_dir
|
|
|
100 |
|
101 |
|
102 |
if __name__ == "__main__":
|
103 |
+
|
104 |
+
if os.path.exists('results/custom'):
|
105 |
+
os.system('rm -rf results/custom')
|
106 |
+
if os.path.exists('outputs'):
|
107 |
+
os.system('rm -rf outputs')
|
108 |
+
|
109 |
inject_motion_embeddings_combinations = ['down 1280','up 1280','down 640','up 640']
|
110 |
default_motion_embeddings_combinations = ['down 1280','up 1280']
|
111 |
|
assets/train/car_turn.mp4
ADDED
Binary file (560 kB). View file
|
|
assets/train/dolly_zoom_out.mp4
ADDED
Binary file (38.5 kB). View file
|
|
assets/train/orbit_shot.mp4
ADDED
Binary file (383 kB). View file
|
|
assets/train/pan_up.mp4
ADDED
Binary file (359 kB). View file
|
|
assets/train/run_up.mp4
ADDED
Binary file (104 kB). View file
|
|
assets/train/santa_dance.mp4
ADDED
Binary file (122 kB). View file
|
|
assets/train/train_ride.mp4
ADDED
Binary file (191 kB). View file
|
|
assets/train/walk.mp4
ADDED
Binary file (62.6 kB). View file
|
|
attn_ctrl.py
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import abc
|
2 |
+
|
3 |
+
LOW_RESOURCE = False
|
4 |
+
import torch
|
5 |
+
import cv2
|
6 |
+
import torch
|
7 |
+
import os
|
8 |
+
import numpy as np
|
9 |
+
from collections import defaultdict
|
10 |
+
from functools import partial
|
11 |
+
from typing import Any, Dict, Optional
|
12 |
+
|
13 |
+
def register_attention_control(unet, config=None):
|
14 |
+
|
15 |
+
def BasicTransformerBlock_forward(
|
16 |
+
self,
|
17 |
+
hidden_states: torch.FloatTensor,
|
18 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
19 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
20 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
21 |
+
timestep: Optional[torch.LongTensor] = None,
|
22 |
+
cross_attention_kwargs: Dict[str, Any] = None,
|
23 |
+
class_labels: Optional[torch.LongTensor] = None,
|
24 |
+
added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
|
25 |
+
) -> torch.FloatTensor:
|
26 |
+
# Notice that normalization is always applied before the real computation in the following blocks.
|
27 |
+
# 0. Self-Attention
|
28 |
+
batch_size = hidden_states.shape[0]
|
29 |
+
|
30 |
+
if self.norm_type == "ada_norm":
|
31 |
+
norm_hidden_states = self.norm1(hidden_states, timestep)
|
32 |
+
elif self.norm_type == "ada_norm_zero":
|
33 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
34 |
+
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
|
35 |
+
)
|
36 |
+
elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
|
37 |
+
norm_hidden_states = self.norm1(hidden_states)
|
38 |
+
elif self.norm_type == "ada_norm_continuous":
|
39 |
+
norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
40 |
+
elif self.norm_type == "ada_norm_single":
|
41 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
42 |
+
self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
|
43 |
+
).chunk(6, dim=1)
|
44 |
+
norm_hidden_states = self.norm1(hidden_states)
|
45 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
|
46 |
+
norm_hidden_states = norm_hidden_states.squeeze(1)
|
47 |
+
else:
|
48 |
+
raise ValueError("Incorrect norm used")
|
49 |
+
|
50 |
+
# save the origin_hidden_states w/o pos_embed, for the use of motion v embedding
|
51 |
+
origin_hidden_states = None
|
52 |
+
if self.pos_embed is not None or hasattr(self.attn1,'vSpatial'):
|
53 |
+
origin_hidden_states = norm_hidden_states.clone()
|
54 |
+
if cross_attention_kwargs is None:
|
55 |
+
cross_attention_kwargs = {}
|
56 |
+
cross_attention_kwargs["origin_hidden_states"] = origin_hidden_states
|
57 |
+
|
58 |
+
if self.pos_embed is not None:
|
59 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
60 |
+
|
61 |
+
|
62 |
+
# 1. Retrieve lora scale.
|
63 |
+
lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
|
64 |
+
|
65 |
+
# 2. Prepare GLIGEN inputs
|
66 |
+
cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
|
67 |
+
gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
|
68 |
+
|
69 |
+
attn_output = self.attn1(
|
70 |
+
norm_hidden_states,
|
71 |
+
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
|
72 |
+
attention_mask=attention_mask,
|
73 |
+
**cross_attention_kwargs,
|
74 |
+
)
|
75 |
+
if self.norm_type == "ada_norm_zero":
|
76 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
77 |
+
elif self.norm_type == "ada_norm_single":
|
78 |
+
attn_output = gate_msa * attn_output
|
79 |
+
|
80 |
+
hidden_states = attn_output + hidden_states
|
81 |
+
if hidden_states.ndim == 4:
|
82 |
+
hidden_states = hidden_states.squeeze(1)
|
83 |
+
|
84 |
+
# 2.5 GLIGEN Control
|
85 |
+
if gligen_kwargs is not None:
|
86 |
+
hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
|
87 |
+
|
88 |
+
# 3. Cross-Attention
|
89 |
+
if self.attn2 is not None:
|
90 |
+
if self.norm_type == "ada_norm":
|
91 |
+
norm_hidden_states = self.norm2(hidden_states, timestep)
|
92 |
+
elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
|
93 |
+
norm_hidden_states = self.norm2(hidden_states)
|
94 |
+
elif self.norm_type == "ada_norm_single":
|
95 |
+
# For PixArt norm2 isn't applied here:
|
96 |
+
# https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
|
97 |
+
norm_hidden_states = hidden_states
|
98 |
+
elif self.norm_type == "ada_norm_continuous":
|
99 |
+
norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
100 |
+
else:
|
101 |
+
raise ValueError("Incorrect norm")
|
102 |
+
|
103 |
+
if self.pos_embed is not None and self.norm_type != "ada_norm_single":
|
104 |
+
# save the origin_hidden_states
|
105 |
+
origin_hidden_states = norm_hidden_states.clone()
|
106 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
107 |
+
cross_attention_kwargs["origin_hidden_states"] = origin_hidden_states
|
108 |
+
|
109 |
+
attn_output = self.attn2(
|
110 |
+
norm_hidden_states,
|
111 |
+
encoder_hidden_states=encoder_hidden_states,
|
112 |
+
attention_mask=encoder_attention_mask,
|
113 |
+
**cross_attention_kwargs,
|
114 |
+
)
|
115 |
+
hidden_states = attn_output + hidden_states
|
116 |
+
# delete the origin_hidden_states
|
117 |
+
if cross_attention_kwargs is not None and "origin_hidden_states" in cross_attention_kwargs:
|
118 |
+
cross_attention_kwargs.pop("origin_hidden_states")
|
119 |
+
|
120 |
+
# 4. Feed-forward
|
121 |
+
# i2vgen doesn't have this norm 🤷♂️
|
122 |
+
if self.norm_type == "ada_norm_continuous":
|
123 |
+
norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
124 |
+
elif not self.norm_type == "ada_norm_single":
|
125 |
+
norm_hidden_states = self.norm3(hidden_states)
|
126 |
+
|
127 |
+
if self.norm_type == "ada_norm_zero":
|
128 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
129 |
+
|
130 |
+
if self.norm_type == "ada_norm_single":
|
131 |
+
norm_hidden_states = self.norm2(hidden_states)
|
132 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
|
133 |
+
|
134 |
+
if self._chunk_size is not None:
|
135 |
+
# "feed_forward_chunk_size" can be used to save memory
|
136 |
+
ff_output = _chunked_feed_forward(
|
137 |
+
self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
|
138 |
+
)
|
139 |
+
else:
|
140 |
+
ff_output = self.ff(norm_hidden_states, scale=lora_scale)
|
141 |
+
|
142 |
+
if self.norm_type == "ada_norm_zero":
|
143 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
144 |
+
elif self.norm_type == "ada_norm_single":
|
145 |
+
ff_output = gate_mlp * ff_output
|
146 |
+
|
147 |
+
hidden_states = ff_output + hidden_states
|
148 |
+
if hidden_states.ndim == 4:
|
149 |
+
hidden_states = hidden_states.squeeze(1)
|
150 |
+
|
151 |
+
return hidden_states
|
152 |
+
|
153 |
+
|
154 |
+
def temp_attn_forward(self, additional_info=None):
|
155 |
+
to_out = self.to_out
|
156 |
+
if type(to_out) is torch.nn.modules.container.ModuleList:
|
157 |
+
to_out = self.to_out[0]
|
158 |
+
else:
|
159 |
+
to_out = self.to_out
|
160 |
+
|
161 |
+
def forward(hidden_states, encoder_hidden_states=None, attention_mask=None,temb=None,origin_hidden_states=None):
|
162 |
+
|
163 |
+
residual = hidden_states
|
164 |
+
|
165 |
+
if self.spatial_norm is not None:
|
166 |
+
hidden_states = self.spatial_norm(hidden_states, temb)
|
167 |
+
|
168 |
+
input_ndim = hidden_states.ndim
|
169 |
+
|
170 |
+
if input_ndim == 4:
|
171 |
+
batch_size, channel, height, width = hidden_states.shape
|
172 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
173 |
+
|
174 |
+
batch_size, sequence_length, _ = (
|
175 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
176 |
+
)
|
177 |
+
|
178 |
+
attention_mask = self.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
179 |
+
|
180 |
+
if self.group_norm is not None:
|
181 |
+
hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
182 |
+
|
183 |
+
if encoder_hidden_states is None:
|
184 |
+
encoder_hidden_states = hidden_states
|
185 |
+
elif self.norm_cross:
|
186 |
+
encoder_hidden_states = self.norm_encoder_hidden_states(encoder_hidden_states)
|
187 |
+
|
188 |
+
query = self.to_q(hidden_states)
|
189 |
+
key = self.to_k(encoder_hidden_states)
|
190 |
+
|
191 |
+
# strategies to manipulate the motion value embedding
|
192 |
+
if additional_info is not None:
|
193 |
+
# empirically, in the inference stage of camera motion
|
194 |
+
# discarding the motion value embedding improves the text similarity of the generated video
|
195 |
+
if additional_info['removeMFromV']:
|
196 |
+
value = self.to_v(origin_hidden_states)
|
197 |
+
elif hasattr(self,'vSpatial'):
|
198 |
+
# during inference, the debiasing operation helps to generate more diverse videos
|
199 |
+
# refer to the 'Figure.3 Right' in the paper for more details
|
200 |
+
if additional_info['vSpatial_frameSubtraction']:
|
201 |
+
value = self.to_v(self.vSpatial.forward_frameSubtraction(origin_hidden_states))
|
202 |
+
# during training, do not apply debias operation for motion learning
|
203 |
+
else:
|
204 |
+
value = self.to_v(self.vSpatial(origin_hidden_states))
|
205 |
+
else:
|
206 |
+
value = self.to_v(origin_hidden_states)
|
207 |
+
else:
|
208 |
+
value = self.to_v(encoder_hidden_states)
|
209 |
+
|
210 |
+
|
211 |
+
query = self.head_to_batch_dim(query)
|
212 |
+
key = self.head_to_batch_dim(key)
|
213 |
+
value = self.head_to_batch_dim(value)
|
214 |
+
|
215 |
+
attention_probs = self.get_attention_scores(query, key, attention_mask)
|
216 |
+
|
217 |
+
hidden_states = torch.bmm(attention_probs, value)
|
218 |
+
hidden_states = self.batch_to_head_dim(hidden_states)
|
219 |
+
|
220 |
+
# linear proj
|
221 |
+
hidden_states = to_out(hidden_states)
|
222 |
+
|
223 |
+
if input_ndim == 4:
|
224 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
225 |
+
|
226 |
+
if self.residual_connection:
|
227 |
+
hidden_states = hidden_states + residual
|
228 |
+
|
229 |
+
hidden_states = hidden_states / self.rescale_output_factor
|
230 |
+
|
231 |
+
return hidden_states
|
232 |
+
return forward
|
233 |
+
|
234 |
+
def register_recr(net_, count, name, config=None):
|
235 |
+
|
236 |
+
if net_.__class__.__name__ == 'BasicTransformerBlock':
|
237 |
+
BasicTransformerBlock_forward_ = partial(BasicTransformerBlock_forward, net_)
|
238 |
+
net_.forward = BasicTransformerBlock_forward_
|
239 |
+
|
240 |
+
if net_.__class__.__name__ == 'Attention':
|
241 |
+
block_name = name.split('.attn')[0]
|
242 |
+
if config is not None and block_name in set([l.split('.attn')[0].split('.pos_embed')[0] for l in config.model.embedding_layers]):
|
243 |
+
additional_info = {}
|
244 |
+
additional_info['layer_name'] = name
|
245 |
+
additional_info['removeMFromV'] = config.strategy.get('removeMFromV', False)
|
246 |
+
additional_info['vSpatial_frameSubtraction'] = config.strategy.get('vSpatial_frameSubtraction', False)
|
247 |
+
net_.forward = temp_attn_forward(net_, additional_info)
|
248 |
+
print('register Motion V embedding at ', block_name)
|
249 |
+
return count + 1
|
250 |
+
else:
|
251 |
+
return count
|
252 |
+
|
253 |
+
elif hasattr(net_, 'children'):
|
254 |
+
for net_name, net__ in dict(net_.named_children()).items():
|
255 |
+
count = register_recr(net__, count, name = name + '.' + net_name, config=config)
|
256 |
+
return count
|
257 |
+
|
258 |
+
sub_nets = unet.named_children()
|
259 |
+
|
260 |
+
for net in sub_nets:
|
261 |
+
register_recr(net[1], 0,name = net[0], config=config)
|
262 |
+
|
263 |
+
|
264 |
+
|
configs/config.yaml
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model:
|
2 |
+
type: unet
|
3 |
+
pretrained_model_path: cerspense/zeroscope_v2_576w
|
4 |
+
motion_embeddings:
|
5 |
+
combinations:
|
6 |
+
- - down
|
7 |
+
- 1280
|
8 |
+
- - up
|
9 |
+
- 1280
|
10 |
+
# unet can be either 'videoCrafter2' or 'zeroscope_v2_576w', the former produces better video quality
|
11 |
+
unet: videoCrafter2
|
12 |
+
|
13 |
+
train:
|
14 |
+
output_dir: ./results
|
15 |
+
validation_steps: 2000
|
16 |
+
checkpointing_steps: 50
|
17 |
+
checkpointing_start: 200
|
18 |
+
train_batch_size: 1
|
19 |
+
max_train_steps: 400
|
20 |
+
gradient_accumulation_steps: 1
|
21 |
+
cache_latents: true
|
22 |
+
cached_latent_dir: null
|
23 |
+
logger_type: tensorboard
|
24 |
+
mixed_precision: fp16
|
25 |
+
use_8bit_adam: false
|
26 |
+
resume_from_checkpoint: null
|
27 |
+
resume_step: null
|
28 |
+
|
29 |
+
dataset:
|
30 |
+
type:
|
31 |
+
- single_video
|
32 |
+
single_video_path: ./assets/car-roundabout-24.mp4
|
33 |
+
single_video_prompt: 'A car turnaround in a city street'
|
34 |
+
width: 576
|
35 |
+
height: 320
|
36 |
+
n_sample_frames: 24
|
37 |
+
fps: 8
|
38 |
+
sample_start_idx: 1
|
39 |
+
frame_step: 1
|
40 |
+
use_bucketing: false
|
41 |
+
use_caption: false
|
42 |
+
|
43 |
+
loss:
|
44 |
+
type: BaseLoss
|
45 |
+
learning_rate: 0.02
|
46 |
+
lr_scheduler: constant
|
47 |
+
lr_warmup_steps: 0
|
48 |
+
|
49 |
+
noise_init:
|
50 |
+
type: BlendInit
|
51 |
+
noise_prior: 0.5
|
52 |
+
|
53 |
+
val:
|
54 |
+
prompt:
|
55 |
+
- "A skateboard slides along a city lane"
|
56 |
+
negative_prompt: ""
|
57 |
+
sample_preview: true
|
58 |
+
width: 576
|
59 |
+
height: 320
|
60 |
+
num_frames: 24
|
61 |
+
num_inference_steps: 30
|
62 |
+
guidance_scale: 12.0
|
63 |
+
seeds: [0]
|
64 |
+
|
65 |
+
strategy:
|
66 |
+
vSpatial_frameSubtraction: false
|
67 |
+
removeMFromV: false
|
dataset/__init__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .cached_dataset import CachedDataset
|
2 |
+
from .image_dataset import ImageDataset
|
3 |
+
from .single_video_dataset import SingleVideoDataset
|
4 |
+
from .video_folder_dataset import VideoFolderDataset
|
5 |
+
from .video_json_dataset import VideoJsonDataset
|
dataset/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (455 Bytes). View file
|
|
dataset/__pycache__/cached_dataset.cpython-310.pyc
ADDED
Binary file (1.33 kB). View file
|
|
dataset/__pycache__/image_dataset.cpython-310.pyc
ADDED
Binary file (2.88 kB). View file
|
|
dataset/__pycache__/single_video_dataset.cpython-310.pyc
ADDED
Binary file (3.63 kB). View file
|
|
dataset/__pycache__/video_folder_dataset.cpython-310.pyc
ADDED
Binary file (2.97 kB). View file
|
|
dataset/__pycache__/video_json_dataset.cpython-310.pyc
ADDED
Binary file (4.59 kB). View file
|
|
dataset/cached_dataset.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.dataset_utils import *
|
2 |
+
|
3 |
+
class CachedDataset(Dataset):
|
4 |
+
def __init__(self,cache_dir: str = ''):
|
5 |
+
self.cache_dir = cache_dir
|
6 |
+
self.cached_data_list = self.get_files_list()
|
7 |
+
|
8 |
+
def get_files_list(self):
|
9 |
+
tensors_list = [f"{self.cache_dir}/{x}" for x in os.listdir(self.cache_dir) if x.endswith('.pt')]
|
10 |
+
return sorted(tensors_list)
|
11 |
+
|
12 |
+
def __len__(self):
|
13 |
+
return len(self.cached_data_list)
|
14 |
+
|
15 |
+
def __getitem__(self, index):
|
16 |
+
cached_latent = torch.load(self.cached_data_list[index], map_location='cuda:0')
|
17 |
+
return cached_latent
|
dataset/image_dataset.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.dataset_utils import *
|
2 |
+
|
3 |
+
class ImageDataset(Dataset):
|
4 |
+
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
tokenizer = None,
|
8 |
+
width: int = 256,
|
9 |
+
height: int = 256,
|
10 |
+
base_width: int = 256,
|
11 |
+
base_height: int = 256,
|
12 |
+
use_caption: bool = False,
|
13 |
+
image_dir: str = '',
|
14 |
+
single_img_prompt: str = '',
|
15 |
+
use_bucketing: bool = False,
|
16 |
+
fallback_prompt: str = '',
|
17 |
+
**kwargs
|
18 |
+
):
|
19 |
+
self.tokenizer = tokenizer
|
20 |
+
self.img_types = (".png", ".jpg", ".jpeg", '.bmp')
|
21 |
+
self.use_bucketing = use_bucketing
|
22 |
+
|
23 |
+
self.image_dir = self.get_images_list(image_dir)
|
24 |
+
self.fallback_prompt = fallback_prompt
|
25 |
+
|
26 |
+
self.use_caption = use_caption
|
27 |
+
self.single_img_prompt = single_img_prompt
|
28 |
+
|
29 |
+
self.width = width
|
30 |
+
self.height = height
|
31 |
+
|
32 |
+
def get_images_list(self, image_dir):
|
33 |
+
if os.path.exists(image_dir):
|
34 |
+
imgs = [x for x in os.listdir(image_dir) if x.endswith(self.img_types)]
|
35 |
+
full_img_dir = []
|
36 |
+
|
37 |
+
for img in imgs:
|
38 |
+
full_img_dir.append(f"{image_dir}/{img}")
|
39 |
+
|
40 |
+
return sorted(full_img_dir)
|
41 |
+
|
42 |
+
return ['']
|
43 |
+
|
44 |
+
def image_batch(self, index):
|
45 |
+
train_data = self.image_dir[index]
|
46 |
+
img = train_data
|
47 |
+
|
48 |
+
try:
|
49 |
+
img = torchvision.io.read_image(img, mode=torchvision.io.ImageReadMode.RGB)
|
50 |
+
except:
|
51 |
+
img = T.transforms.PILToTensor()(Image.open(img).convert("RGB"))
|
52 |
+
|
53 |
+
width = self.width
|
54 |
+
height = self.height
|
55 |
+
|
56 |
+
if self.use_bucketing:
|
57 |
+
_, h, w = img.shape
|
58 |
+
width, height = sensible_buckets(width, height, w, h)
|
59 |
+
|
60 |
+
resize = T.transforms.Resize((height, width), antialias=True)
|
61 |
+
|
62 |
+
img = resize(img)
|
63 |
+
img = repeat(img, 'c h w -> f c h w', f=16)
|
64 |
+
|
65 |
+
prompt = get_text_prompt(
|
66 |
+
file_path=train_data,
|
67 |
+
text_prompt=self.single_img_prompt,
|
68 |
+
fallback_prompt=self.fallback_prompt,
|
69 |
+
ext_types=self.img_types,
|
70 |
+
use_caption=True
|
71 |
+
)
|
72 |
+
prompt_ids = get_prompt_ids(prompt, self.tokenizer)
|
73 |
+
|
74 |
+
return img, prompt, prompt_ids
|
75 |
+
|
76 |
+
@staticmethod
|
77 |
+
def __getname__(): return 'image'
|
78 |
+
|
79 |
+
def __len__(self):
|
80 |
+
# Image directory
|
81 |
+
if os.path.exists(self.image_dir[0]):
|
82 |
+
return len(self.image_dir)
|
83 |
+
else:
|
84 |
+
return 0
|
85 |
+
|
86 |
+
def __getitem__(self, index):
|
87 |
+
img, prompt, prompt_ids = self.image_batch(index)
|
88 |
+
example = {
|
89 |
+
"pixel_values": (img / 127.5 - 1.0),
|
90 |
+
"prompt_ids": prompt_ids[0],
|
91 |
+
"text_prompt": prompt,
|
92 |
+
'dataset': self.__getname__()
|
93 |
+
}
|
94 |
+
|
95 |
+
return example
|
dataset/single_video_dataset.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.dataset_utils import *
|
2 |
+
|
3 |
+
class SingleVideoDataset(Dataset):
|
4 |
+
def __init__(
|
5 |
+
self,
|
6 |
+
tokenizer = None,
|
7 |
+
width: int = 256,
|
8 |
+
height: int = 256,
|
9 |
+
n_sample_frames: int = 4,
|
10 |
+
frame_step: int = 1,
|
11 |
+
single_video_path: str = "",
|
12 |
+
single_video_prompt: str = "",
|
13 |
+
use_caption: bool = False,
|
14 |
+
use_bucketing: bool = False,
|
15 |
+
**kwargs
|
16 |
+
):
|
17 |
+
self.tokenizer = tokenizer
|
18 |
+
self.use_bucketing = use_bucketing
|
19 |
+
self.frames = []
|
20 |
+
self.index = 1
|
21 |
+
|
22 |
+
self.vid_types = (".mp4", ".avi", ".mov", ".webm", ".flv", ".mjpeg")
|
23 |
+
self.n_sample_frames = n_sample_frames
|
24 |
+
self.frame_step = frame_step
|
25 |
+
|
26 |
+
self.single_video_path = single_video_path
|
27 |
+
self.single_video_prompt = single_video_prompt
|
28 |
+
|
29 |
+
self.width = width
|
30 |
+
self.height = height
|
31 |
+
|
32 |
+
def create_video_chunks(self):
|
33 |
+
vr = decord.VideoReader(self.single_video_path)
|
34 |
+
vr_range = range(0, len(vr), self.frame_step)
|
35 |
+
|
36 |
+
self.frames = list(self.chunk(vr_range, self.n_sample_frames))
|
37 |
+
return self.frames
|
38 |
+
|
39 |
+
def chunk(self, it, size):
|
40 |
+
it = iter(it)
|
41 |
+
return iter(lambda: tuple(islice(it, size)), ())
|
42 |
+
|
43 |
+
def get_frame_batch(self, vr, resize=None):
|
44 |
+
index = self.index
|
45 |
+
frames = vr.get_batch(self.frames[self.index])
|
46 |
+
|
47 |
+
if type(frames) == decord.ndarray.NDArray:
|
48 |
+
frames = torch.from_numpy(frames.asnumpy())
|
49 |
+
|
50 |
+
video = rearrange(frames, "f h w c -> f c h w")
|
51 |
+
|
52 |
+
if resize is not None: video = resize(video)
|
53 |
+
return video
|
54 |
+
|
55 |
+
def get_frame_buckets(self, vr):
|
56 |
+
h, w, c = vr[0].shape
|
57 |
+
width, height = sensible_buckets(self.width, self.height, w, h)
|
58 |
+
resize = T.transforms.Resize((height, width), antialias=True)
|
59 |
+
|
60 |
+
return resize
|
61 |
+
|
62 |
+
def process_video_wrapper(self, vid_path):
|
63 |
+
video, vr = process_video(
|
64 |
+
vid_path,
|
65 |
+
self.use_bucketing,
|
66 |
+
self.width,
|
67 |
+
self.height,
|
68 |
+
self.get_frame_buckets,
|
69 |
+
self.get_frame_batch
|
70 |
+
)
|
71 |
+
|
72 |
+
return video, vr
|
73 |
+
|
74 |
+
def single_video_batch(self, index):
|
75 |
+
train_data = self.single_video_path
|
76 |
+
self.index = index
|
77 |
+
|
78 |
+
if train_data.endswith(self.vid_types):
|
79 |
+
video, _ = self.process_video_wrapper(train_data)
|
80 |
+
|
81 |
+
prompt = self.single_video_prompt
|
82 |
+
prompt_ids = get_prompt_ids(prompt, self.tokenizer)
|
83 |
+
|
84 |
+
return video, prompt, prompt_ids
|
85 |
+
else:
|
86 |
+
raise ValueError(f"Single video is not a video type. Types: {self.vid_types}")
|
87 |
+
|
88 |
+
@staticmethod
|
89 |
+
def __getname__(): return 'single_video'
|
90 |
+
|
91 |
+
def __len__(self):
|
92 |
+
|
93 |
+
return len(self.create_video_chunks())
|
94 |
+
|
95 |
+
def __getitem__(self, index):
|
96 |
+
|
97 |
+
video, prompt, prompt_ids = self.single_video_batch(index)
|
98 |
+
|
99 |
+
example = {
|
100 |
+
"pixel_values": (video / 127.5 - 1.0),
|
101 |
+
"prompt_ids": prompt_ids[0],
|
102 |
+
"text_prompt": prompt,
|
103 |
+
'dataset': self.__getname__()
|
104 |
+
}
|
105 |
+
|
106 |
+
return example
|
dataset/video_folder_dataset.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.dataset_utils import *
|
2 |
+
|
3 |
+
class VideoFolderDataset(Dataset):
|
4 |
+
def __init__(
|
5 |
+
self,
|
6 |
+
tokenizer=None,
|
7 |
+
width: int = 256,
|
8 |
+
height: int = 256,
|
9 |
+
n_sample_frames: int = 16,
|
10 |
+
fps: int = 8,
|
11 |
+
path: str = "./data",
|
12 |
+
fallback_prompt: str = "",
|
13 |
+
use_bucketing: bool = False,
|
14 |
+
**kwargs
|
15 |
+
):
|
16 |
+
self.tokenizer = tokenizer
|
17 |
+
self.use_bucketing = use_bucketing
|
18 |
+
|
19 |
+
self.fallback_prompt = fallback_prompt
|
20 |
+
|
21 |
+
self.video_files = glob(f"{path}/*.mp4")
|
22 |
+
|
23 |
+
self.width = width
|
24 |
+
self.height = height
|
25 |
+
|
26 |
+
self.n_sample_frames = n_sample_frames
|
27 |
+
self.fps = fps
|
28 |
+
|
29 |
+
def get_frame_buckets(self, vr):
|
30 |
+
h, w, c = vr[0].shape
|
31 |
+
width, height = sensible_buckets(self.width, self.height, w, h)
|
32 |
+
resize = T.transforms.Resize((height, width), antialias=True)
|
33 |
+
|
34 |
+
return resize
|
35 |
+
|
36 |
+
def get_frame_batch(self, vr, resize=None):
|
37 |
+
n_sample_frames = self.n_sample_frames
|
38 |
+
native_fps = vr.get_avg_fps()
|
39 |
+
|
40 |
+
every_nth_frame = max(1, round(native_fps / self.fps))
|
41 |
+
every_nth_frame = min(len(vr), every_nth_frame)
|
42 |
+
|
43 |
+
effective_length = len(vr) // every_nth_frame
|
44 |
+
if effective_length < n_sample_frames:
|
45 |
+
n_sample_frames = effective_length
|
46 |
+
|
47 |
+
effective_idx = random.randint(0, (effective_length - n_sample_frames))
|
48 |
+
idxs = every_nth_frame * np.arange(effective_idx, effective_idx + n_sample_frames)
|
49 |
+
|
50 |
+
video = vr.get_batch(idxs)
|
51 |
+
video = rearrange(video, "f h w c -> f c h w")
|
52 |
+
|
53 |
+
if resize is not None: video = resize(video)
|
54 |
+
return video, vr
|
55 |
+
|
56 |
+
def process_video_wrapper(self, vid_path):
|
57 |
+
video, vr = process_video(
|
58 |
+
vid_path,
|
59 |
+
self.use_bucketing,
|
60 |
+
self.width,
|
61 |
+
self.height,
|
62 |
+
self.get_frame_buckets,
|
63 |
+
self.get_frame_batch
|
64 |
+
)
|
65 |
+
return video, vr
|
66 |
+
|
67 |
+
def get_prompt_ids(self, prompt):
|
68 |
+
return self.tokenizer(
|
69 |
+
prompt,
|
70 |
+
truncation=True,
|
71 |
+
padding="max_length",
|
72 |
+
max_length=self.tokenizer.model_max_length,
|
73 |
+
return_tensors="pt",
|
74 |
+
).input_ids
|
75 |
+
|
76 |
+
@staticmethod
|
77 |
+
def __getname__(): return 'folder'
|
78 |
+
|
79 |
+
def __len__(self):
|
80 |
+
return len(self.video_files)
|
81 |
+
|
82 |
+
def __getitem__(self, index):
|
83 |
+
|
84 |
+
video, _ = self.process_video_wrapper(self.video_files[index])
|
85 |
+
|
86 |
+
prompt = self.fallback_prompt
|
87 |
+
|
88 |
+
prompt_ids = self.get_prompt_ids(prompt)
|
89 |
+
|
90 |
+
return {"pixel_values": (video[0] / 127.5 - 1.0), "prompt_ids": prompt_ids[0], "text_prompt": prompt, 'dataset': self.__getname__()}
|
dataset/video_json_dataset.py
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.dataset_utils import *
|
2 |
+
|
3 |
+
# https://github.com/ExponentialML/Video-BLIP2-Preprocessor
|
4 |
+
class VideoJsonDataset(Dataset):
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
tokenizer = None,
|
8 |
+
width: int = 256,
|
9 |
+
height: int = 256,
|
10 |
+
n_sample_frames: int = 4,
|
11 |
+
sample_start_idx: int = 1,
|
12 |
+
frame_step: int = 1,
|
13 |
+
json_path: str ="",
|
14 |
+
json_data = None,
|
15 |
+
vid_data_key: str = "video_path",
|
16 |
+
preprocessed: bool = False,
|
17 |
+
use_bucketing: bool = False,
|
18 |
+
**kwargs
|
19 |
+
):
|
20 |
+
self.vid_types = (".mp4", ".avi", ".mov", ".webm", ".flv", ".mjpeg")
|
21 |
+
self.use_bucketing = use_bucketing
|
22 |
+
self.tokenizer = tokenizer
|
23 |
+
self.preprocessed = preprocessed
|
24 |
+
|
25 |
+
self.vid_data_key = vid_data_key
|
26 |
+
self.train_data = self.load_from_json(json_path, json_data)
|
27 |
+
|
28 |
+
self.width = width
|
29 |
+
self.height = height
|
30 |
+
|
31 |
+
self.n_sample_frames = n_sample_frames
|
32 |
+
self.sample_start_idx = sample_start_idx
|
33 |
+
self.frame_step = frame_step
|
34 |
+
|
35 |
+
def build_json(self, json_data):
|
36 |
+
extended_data = []
|
37 |
+
for data in json_data['data']:
|
38 |
+
for nested_data in data['data']:
|
39 |
+
self.build_json_dict(
|
40 |
+
data,
|
41 |
+
nested_data,
|
42 |
+
extended_data
|
43 |
+
)
|
44 |
+
json_data = extended_data
|
45 |
+
return json_data
|
46 |
+
|
47 |
+
def build_json_dict(self, data, nested_data, extended_data):
|
48 |
+
clip_path = nested_data['clip_path'] if 'clip_path' in nested_data else None
|
49 |
+
|
50 |
+
extended_data.append({
|
51 |
+
self.vid_data_key: data[self.vid_data_key],
|
52 |
+
'frame_index': nested_data['frame_index'],
|
53 |
+
'prompt': nested_data['prompt'],
|
54 |
+
'clip_path': clip_path
|
55 |
+
})
|
56 |
+
|
57 |
+
def load_from_json(self, path, json_data):
|
58 |
+
try:
|
59 |
+
with open(path) as jpath:
|
60 |
+
print(f"Loading JSON from {path}")
|
61 |
+
json_data = json.load(jpath)
|
62 |
+
|
63 |
+
return self.build_json(json_data)
|
64 |
+
|
65 |
+
except:
|
66 |
+
self.train_data = []
|
67 |
+
print("Non-existant JSON path. Skipping.")
|
68 |
+
|
69 |
+
def validate_json(self, base_path, path):
|
70 |
+
return os.path.exists(f"{base_path}/{path}")
|
71 |
+
|
72 |
+
def get_frame_range(self, vr):
|
73 |
+
return get_video_frames(
|
74 |
+
vr,
|
75 |
+
self.sample_start_idx,
|
76 |
+
self.frame_step,
|
77 |
+
self.n_sample_frames
|
78 |
+
)
|
79 |
+
|
80 |
+
def get_vid_idx(self, vr, vid_data=None):
|
81 |
+
frames = self.n_sample_frames
|
82 |
+
|
83 |
+
if vid_data is not None:
|
84 |
+
idx = vid_data['frame_index']
|
85 |
+
else:
|
86 |
+
idx = self.sample_start_idx
|
87 |
+
|
88 |
+
return idx
|
89 |
+
|
90 |
+
def get_frame_buckets(self, vr):
|
91 |
+
_, h, w = vr[0].shape
|
92 |
+
width, height = sensible_buckets(self.width, self.height, h, w)
|
93 |
+
# width, height = self.width, self.height
|
94 |
+
resize = T.transforms.Resize((height, width), antialias=True)
|
95 |
+
|
96 |
+
return resize
|
97 |
+
|
98 |
+
def get_frame_batch(self, vr, resize=None):
|
99 |
+
frame_range = self.get_frame_range(vr)
|
100 |
+
frames = vr.get_batch(frame_range)
|
101 |
+
video = rearrange(frames, "f h w c -> f c h w")
|
102 |
+
|
103 |
+
if resize is not None: video = resize(video)
|
104 |
+
return video
|
105 |
+
|
106 |
+
def process_video_wrapper(self, vid_path):
|
107 |
+
video, vr = process_video(
|
108 |
+
vid_path,
|
109 |
+
self.use_bucketing,
|
110 |
+
self.width,
|
111 |
+
self.height,
|
112 |
+
self.get_frame_buckets,
|
113 |
+
self.get_frame_batch
|
114 |
+
)
|
115 |
+
|
116 |
+
return video, vr
|
117 |
+
|
118 |
+
def train_data_batch(self, index):
|
119 |
+
|
120 |
+
# If we are training on individual clips.
|
121 |
+
if 'clip_path' in self.train_data[index] and \
|
122 |
+
self.train_data[index]['clip_path'] is not None:
|
123 |
+
|
124 |
+
vid_data = self.train_data[index]
|
125 |
+
|
126 |
+
clip_path = vid_data['clip_path']
|
127 |
+
|
128 |
+
# Get video prompt
|
129 |
+
prompt = vid_data['prompt']
|
130 |
+
|
131 |
+
video, _ = self.process_video_wrapper(clip_path)
|
132 |
+
|
133 |
+
prompt_ids = get_prompt_ids(prompt, self.tokenizer)
|
134 |
+
|
135 |
+
return video, prompt, prompt_ids
|
136 |
+
|
137 |
+
# Assign train data
|
138 |
+
train_data = self.train_data[index]
|
139 |
+
|
140 |
+
# Get the frame of the current index.
|
141 |
+
self.sample_start_idx = train_data['frame_index']
|
142 |
+
|
143 |
+
# Initialize resize
|
144 |
+
resize = None
|
145 |
+
|
146 |
+
video, vr = self.process_video_wrapper(train_data[self.vid_data_key])
|
147 |
+
|
148 |
+
# Get video prompt
|
149 |
+
prompt = train_data['prompt']
|
150 |
+
vr.seek(0)
|
151 |
+
|
152 |
+
prompt_ids = get_prompt_ids(prompt, self.tokenizer)
|
153 |
+
|
154 |
+
return video, prompt, prompt_ids
|
155 |
+
|
156 |
+
@staticmethod
|
157 |
+
def __getname__(): return 'json'
|
158 |
+
|
159 |
+
def __len__(self):
|
160 |
+
if self.train_data is not None:
|
161 |
+
return len(self.train_data)
|
162 |
+
else:
|
163 |
+
return 0
|
164 |
+
|
165 |
+
def __getitem__(self, index):
|
166 |
+
|
167 |
+
# Initialize variables
|
168 |
+
video = None
|
169 |
+
prompt = None
|
170 |
+
prompt_ids = None
|
171 |
+
|
172 |
+
# Use default JSON training
|
173 |
+
if self.train_data is not None:
|
174 |
+
video, prompt, prompt_ids = self.train_data_batch(index)
|
175 |
+
|
176 |
+
example = {
|
177 |
+
"pixel_values": (video / 127.5 - 1.0),
|
178 |
+
"prompt_ids": prompt_ids[0],
|
179 |
+
"text_prompt": prompt,
|
180 |
+
'dataset': self.__getname__()
|
181 |
+
}
|
182 |
+
|
183 |
+
return example
|
inference.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
|
3 |
+
from train import export_to_video
|
4 |
+
from models.unet.motion_embeddings import load_motion_embeddings
|
5 |
+
from noise_init.blend_init import BlendInit
|
6 |
+
from noise_init.blend_freq_init import BlendFreqInit
|
7 |
+
from noise_init.fft_init import FFTInit
|
8 |
+
from noise_init.freq_init import FreqInit
|
9 |
+
from attn_ctrl import register_attention_control
|
10 |
+
import numpy as np
|
11 |
+
import os
|
12 |
+
from omegaconf import OmegaConf
|
13 |
+
|
14 |
+
def get_pipe(embedding_dir='baseline',config=None,noisy_latent=None, video_round=None):
|
15 |
+
|
16 |
+
# load video generation model
|
17 |
+
pipe = DiffusionPipeline.from_pretrained(config.model.pretrained_model_path,torch_dtype=torch.float16)
|
18 |
+
|
19 |
+
# use videocrafterv2 unet
|
20 |
+
if config.model.unet == 'videoCrafter2':
|
21 |
+
from models.unet.unet_3d_condition import UNet3DConditionModel
|
22 |
+
# unet = UNet3DConditionModel.from_pretrained("adamdad/videocrafterv2_diffusers",subfolder='unet',torch_dtype=torch.float16)
|
23 |
+
unet = UNet3DConditionModel.from_pretrained("adamdad/videocrafterv2_diffusers",torch_dtype=torch.float16)
|
24 |
+
pipe.unet = unet
|
25 |
+
|
26 |
+
# pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
27 |
+
pipe.enable_model_cpu_offload()
|
28 |
+
|
29 |
+
# memory optimization
|
30 |
+
pipe.enable_vae_slicing()
|
31 |
+
|
32 |
+
# if 'vanilla' not in embedding_dir:
|
33 |
+
|
34 |
+
noisy_latent = torch.load(f'{embedding_dir}/cached_latents/cached_0.pt')['inversion_noise'][None,]
|
35 |
+
if video_round is None:
|
36 |
+
motion_embed = torch.load(f'{embedding_dir}/motion_embed.pt')
|
37 |
+
else:
|
38 |
+
motion_embed = torch.load(f'{embedding_dir}/{video_round}/motion_embed.pt')
|
39 |
+
load_motion_embeddings(
|
40 |
+
pipe.unet,
|
41 |
+
motion_embed,
|
42 |
+
)
|
43 |
+
config.model['embedding_layers'] = list(motion_embed.keys())
|
44 |
+
|
45 |
+
return pipe, config, noisy_latent
|
46 |
+
|
47 |
+
def inference(embedding_dir='vanilla',
|
48 |
+
video_round=None,
|
49 |
+
prompt=None,
|
50 |
+
save_dir=None,
|
51 |
+
seed=None,
|
52 |
+
motion_type=None,
|
53 |
+
inference_steps=30
|
54 |
+
):
|
55 |
+
|
56 |
+
# check motion type is valid
|
57 |
+
if motion_type != 'camera' and \
|
58 |
+
motion_type != 'object' and \
|
59 |
+
motion_type != 'hybrid':
|
60 |
+
raise ValueError('Invalid motion type')
|
61 |
+
|
62 |
+
if seed is None:
|
63 |
+
seed = 0
|
64 |
+
|
65 |
+
# load motion embedding
|
66 |
+
noisy_latent = None
|
67 |
+
|
68 |
+
config = OmegaConf.load(f'{embedding_dir}/config.yaml')
|
69 |
+
|
70 |
+
|
71 |
+
# different motion type assigns different strategy
|
72 |
+
if motion_type == 'camera':
|
73 |
+
config['strategy']['removeMFromV'] = True
|
74 |
+
|
75 |
+
elif motion_type == 'object' or motion_type == 'hybrid':
|
76 |
+
config['strategy']['vSpatial_frameSubtraction'] = True
|
77 |
+
|
78 |
+
|
79 |
+
pipe, config, noisy_latent = get_pipe(embedding_dir=embedding_dir,config=config,noisy_latent=noisy_latent,video_round=video_round)
|
80 |
+
n_frames = config.val.num_frames
|
81 |
+
|
82 |
+
shape = (config.val.height,config.val.width)
|
83 |
+
os.makedirs(save_dir,exist_ok=True)
|
84 |
+
|
85 |
+
|
86 |
+
cur_save_dir = f'{save_dir}/{"_".join(prompt.split())}.mp4'
|
87 |
+
|
88 |
+
register_attention_control(pipe.unet,config=config)
|
89 |
+
|
90 |
+
if noisy_latent is not None:
|
91 |
+
torch.manual_seed(seed)
|
92 |
+
noise = torch.randn_like(noisy_latent)
|
93 |
+
init_noise = BlendInit(noisy_latent, noise, noise_prior=0.5)
|
94 |
+
else:
|
95 |
+
init_noise = None
|
96 |
+
|
97 |
+
input_init_noise = init_noise.clone() if not init_noise is None else None
|
98 |
+
video_frames = pipe(
|
99 |
+
prompt=prompt,
|
100 |
+
num_inference_steps=inference_steps,
|
101 |
+
guidance_scale=12,
|
102 |
+
height=shape[0],
|
103 |
+
width=shape[1],
|
104 |
+
num_frames=n_frames,
|
105 |
+
generator=torch.Generator("cuda").manual_seed(seed),
|
106 |
+
latents=input_init_noise,
|
107 |
+
).frames[0]
|
108 |
+
|
109 |
+
video_path = export_to_video(video_frames,output_video_path=cur_save_dir,fps=8)
|
110 |
+
|
111 |
+
return video_path
|
112 |
+
|
113 |
+
|
114 |
+
if __name__ =="__main__":
|
115 |
+
|
116 |
+
prompts = ["A skateboard slides along a city lane",
|
117 |
+
"A tank is running in the desert.",
|
118 |
+
"A toy train chugs around a roundabout tree"]
|
119 |
+
|
120 |
+
|
121 |
+
embedding_dir = './results'
|
122 |
+
video_round = 'checkpoint-250'
|
123 |
+
save_dir = f'outputs'
|
124 |
+
|
125 |
+
inference(
|
126 |
+
embedding_dir=embedding_dir,
|
127 |
+
prompt=prompts,
|
128 |
+
video_round=video_round,
|
129 |
+
save_dir=save_dir,
|
130 |
+
motion_type='hybrid',
|
131 |
+
seed=100
|
132 |
+
)
|
133 |
+
|
loss/__init__.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base_loss import BaseLoss
|
2 |
+
from .debiased_hybrid_loss import DebiasedHybridLoss
|
3 |
+
from .debiased_temporal_loss import DebiasedTemporalLoss
|
4 |
+
from .motion_distillation_loss import MotionDistillationLoss
|
loss/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (408 Bytes). View file
|
|
loss/__pycache__/base_loss.cpython-310.pyc
ADDED
Binary file (1.5 kB). View file
|
|
loss/__pycache__/debiased_hybrid_loss.cpython-310.pyc
ADDED
Binary file (3.13 kB). View file
|
|
loss/__pycache__/debiased_temporal_loss.cpython-310.pyc
ADDED
Binary file (1.83 kB). View file
|
|
loss/__pycache__/motion_distillation_loss.cpython-310.pyc
ADDED
Binary file (1.75 kB). View file
|
|
loss/base_loss.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from utils.func_utils import tensor_to_vae_latent, sample_noise
|
4 |
+
|
5 |
+
def BaseLoss(
|
6 |
+
train_loss_temporal,
|
7 |
+
accelerator,
|
8 |
+
optimizers,
|
9 |
+
lr_schedulers,
|
10 |
+
unet,
|
11 |
+
vae,
|
12 |
+
text_encoder,
|
13 |
+
noise_scheduler,
|
14 |
+
batch,
|
15 |
+
step,
|
16 |
+
config
|
17 |
+
):
|
18 |
+
cache_latents = config.train.cache_latents
|
19 |
+
|
20 |
+
if not cache_latents:
|
21 |
+
latents = tensor_to_vae_latent(batch["pixel_values"], vae)
|
22 |
+
else:
|
23 |
+
latents = batch["latents"]
|
24 |
+
|
25 |
+
# Sample noise that we'll add to the latents
|
26 |
+
# use_offset_noise = use_offset_noise and not rescale_schedule
|
27 |
+
|
28 |
+
noise = sample_noise(latents, 0.1, False)
|
29 |
+
bsz = latents.shape[0]
|
30 |
+
|
31 |
+
# Sample a random timestep for each video
|
32 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
33 |
+
timesteps = timesteps.long()
|
34 |
+
|
35 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
36 |
+
# (this is the forward diffusion process)
|
37 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
38 |
+
|
39 |
+
# *Potentially* Fixes gradient checkpointing training.
|
40 |
+
# See: https://github.com/prigoyal/pytorch_memonger/blob/master/tutorial/Checkpointing_for_PyTorch_models.ipynb
|
41 |
+
# if kwargs.get('eval_train', False):
|
42 |
+
# unet.eval()
|
43 |
+
# text_encoder.eval()
|
44 |
+
|
45 |
+
# Encode text embeddings
|
46 |
+
token_ids = batch['prompt_ids']
|
47 |
+
encoder_hidden_states = text_encoder(token_ids)[0]
|
48 |
+
detached_encoder_state = encoder_hidden_states.clone().detach()
|
49 |
+
|
50 |
+
# Get the target for loss depending on the prediction type
|
51 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
52 |
+
target = noise
|
53 |
+
|
54 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
55 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
56 |
+
|
57 |
+
else:
|
58 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
59 |
+
|
60 |
+
encoder_hidden_states = detached_encoder_state
|
61 |
+
|
62 |
+
|
63 |
+
# optimization
|
64 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states=encoder_hidden_states).sample
|
65 |
+
loss_temporal = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
66 |
+
|
67 |
+
avg_loss_temporal = accelerator.gather(loss_temporal.repeat(config.train.train_batch_size)).mean()
|
68 |
+
train_loss_temporal += avg_loss_temporal.item() / config.train.gradient_accumulation_steps
|
69 |
+
|
70 |
+
accelerator.backward(loss_temporal)
|
71 |
+
optimizers[0].step()
|
72 |
+
lr_schedulers[0].step()
|
73 |
+
|
74 |
+
return loss_temporal, train_loss_temporal
|
75 |
+
|
loss/debiased_hybrid_loss.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torchvision import transforms
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import random
|
5 |
+
|
6 |
+
from utils.lora import extract_lora_child_module
|
7 |
+
from utils.func_utils import tensor_to_vae_latent, sample_noise
|
8 |
+
|
9 |
+
def DebiasedHybridLoss(
|
10 |
+
train_loss_temporal,
|
11 |
+
accelerator,
|
12 |
+
optimizers,
|
13 |
+
lr_schedulers,
|
14 |
+
unet,
|
15 |
+
vae,
|
16 |
+
text_encoder,
|
17 |
+
noise_scheduler,
|
18 |
+
batch,
|
19 |
+
step,
|
20 |
+
config,
|
21 |
+
random_hflip_img=False,
|
22 |
+
spatial_lora_num=1
|
23 |
+
):
|
24 |
+
mask_spatial_lora = random.uniform(0, 1) < 0.2
|
25 |
+
cache_latents = config.train.cache_latents
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
if not cache_latents:
|
30 |
+
latents = tensor_to_vae_latent(batch["pixel_values"], vae)
|
31 |
+
else:
|
32 |
+
latents = batch["latents"]
|
33 |
+
|
34 |
+
# Sample noise that we'll add to the latents
|
35 |
+
# use_offset_noise = use_offset_noise and not rescale_schedule
|
36 |
+
|
37 |
+
noise = sample_noise(latents, 0.1, False)
|
38 |
+
bsz = latents.shape[0]
|
39 |
+
|
40 |
+
# Sample a random timestep for each video
|
41 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
42 |
+
timesteps = timesteps.long()
|
43 |
+
|
44 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
45 |
+
# (this is the forward diffusion process)
|
46 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
47 |
+
|
48 |
+
# *Potentially* Fixes gradient checkpointing training.
|
49 |
+
# See: https://github.com/prigoyal/pytorch_memonger/blob/master/tutorial/Checkpointing_for_PyTorch_models.ipynb
|
50 |
+
# if kwargs.get('eval_train', False):
|
51 |
+
# unet.eval()
|
52 |
+
# text_encoder.eval()
|
53 |
+
|
54 |
+
# Encode text embeddings
|
55 |
+
token_ids = batch['prompt_ids']
|
56 |
+
encoder_hidden_states = text_encoder(token_ids)[0]
|
57 |
+
detached_encoder_state = encoder_hidden_states.clone().detach()
|
58 |
+
|
59 |
+
# Get the target for loss depending on the prediction type
|
60 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
61 |
+
target = noise
|
62 |
+
|
63 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
64 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
65 |
+
|
66 |
+
else:
|
67 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
68 |
+
|
69 |
+
encoder_hidden_states = detached_encoder_state
|
70 |
+
|
71 |
+
|
72 |
+
# optimization
|
73 |
+
if mask_spatial_lora:
|
74 |
+
loras = extract_lora_child_module(unet, target_replace_module=["Transformer2DModel"])
|
75 |
+
for lora_i in loras:
|
76 |
+
lora_i.scale = 0.
|
77 |
+
loss_spatial = None
|
78 |
+
else:
|
79 |
+
loras = extract_lora_child_module(unet, target_replace_module=["Transformer2DModel"])
|
80 |
+
|
81 |
+
if spatial_lora_num == 1:
|
82 |
+
for lora_i in loras:
|
83 |
+
lora_i.scale = 1.
|
84 |
+
else:
|
85 |
+
for lora_i in loras:
|
86 |
+
lora_i.scale = 0.
|
87 |
+
|
88 |
+
for lora_idx in range(0, len(loras), spatial_lora_num):
|
89 |
+
loras[lora_idx + step].scale = 1.
|
90 |
+
|
91 |
+
loras = extract_lora_child_module(unet, target_replace_module=["TransformerTemporalModel"])
|
92 |
+
if len(loras) > 0:
|
93 |
+
for lora_i in loras:
|
94 |
+
lora_i.scale = 0.
|
95 |
+
|
96 |
+
ran_idx = torch.randint(0, noisy_latents.shape[2], (1,)).item()
|
97 |
+
|
98 |
+
if random.uniform(0, 1) < random_hflip_img:
|
99 |
+
pixel_values_spatial = transforms.functional.hflip(
|
100 |
+
batch["pixel_values"][:, ran_idx, :, :, :]).unsqueeze(1)
|
101 |
+
latents_spatial = tensor_to_vae_latent(pixel_values_spatial, vae)
|
102 |
+
noise_spatial = sample_noise(latents_spatial, 0.1, False)
|
103 |
+
noisy_latents_input = noise_scheduler.add_noise(latents_spatial, noise_spatial, timesteps)
|
104 |
+
target_spatial = noise_spatial
|
105 |
+
model_pred_spatial = unet(noisy_latents_input, timesteps,
|
106 |
+
encoder_hidden_states=encoder_hidden_states).sample
|
107 |
+
loss_spatial = F.mse_loss(model_pred_spatial[:, :, 0, :, :].float(),
|
108 |
+
target_spatial[:, :, 0, :, :].float(), reduction="mean")
|
109 |
+
else:
|
110 |
+
noisy_latents_input = noisy_latents[:, :, ran_idx, :, :]
|
111 |
+
target_spatial = target[:, :, ran_idx, :, :]
|
112 |
+
model_pred_spatial = unet(noisy_latents_input.unsqueeze(2), timesteps,
|
113 |
+
encoder_hidden_states=encoder_hidden_states).sample
|
114 |
+
loss_spatial = F.mse_loss(model_pred_spatial[:, :, 0, :, :].float(),
|
115 |
+
target_spatial.float(), reduction="mean")
|
116 |
+
|
117 |
+
|
118 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states=encoder_hidden_states).sample
|
119 |
+
loss_temporal = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
120 |
+
|
121 |
+
beta = 1
|
122 |
+
alpha = (beta ** 2 + 1) ** 0.5
|
123 |
+
ran_idx = torch.randint(0, model_pred.shape[2], (1,)).item()
|
124 |
+
model_pred_decent = alpha * model_pred - beta * model_pred[:, :, ran_idx, :, :].unsqueeze(2)
|
125 |
+
target_decent = alpha * target - beta * target[:, :, ran_idx, :, :].unsqueeze(2)
|
126 |
+
loss_ad_temporal = F.mse_loss(model_pred_decent.float(), target_decent.float(), reduction="mean")
|
127 |
+
loss_temporal = loss_temporal + loss_ad_temporal
|
128 |
+
|
129 |
+
avg_loss_temporal = accelerator.gather(loss_temporal.repeat(config.train.train_batch_size)).mean()
|
130 |
+
train_loss_temporal += avg_loss_temporal.item() / config.train.gradient_accumulation_steps
|
131 |
+
|
132 |
+
if not mask_spatial_lora:
|
133 |
+
accelerator.backward(loss_spatial, retain_graph=True)
|
134 |
+
if spatial_lora_num == 1:
|
135 |
+
optimizers[1].step()
|
136 |
+
else:
|
137 |
+
optimizers[step+1].step()
|
138 |
+
|
139 |
+
accelerator.backward(loss_temporal)
|
140 |
+
optimizers[0].step()
|
141 |
+
|
142 |
+
if spatial_lora_num == 1:
|
143 |
+
lr_schedulers[1].step()
|
144 |
+
else:
|
145 |
+
lr_schedulers[1 + step].step()
|
146 |
+
|
147 |
+
lr_schedulers[0].step()
|
148 |
+
|
149 |
+
return loss_temporal, train_loss_temporal
|
loss/debiased_temporal_loss.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
|
4 |
+
from utils.func_utils import tensor_to_vae_latent, sample_noise
|
5 |
+
|
6 |
+
def DebiasedTemporalLoss(
|
7 |
+
train_loss_temporal,
|
8 |
+
accelerator,
|
9 |
+
optimizers,
|
10 |
+
lr_schedulers,
|
11 |
+
unet,
|
12 |
+
vae,
|
13 |
+
text_encoder,
|
14 |
+
noise_scheduler,
|
15 |
+
batch,
|
16 |
+
step,
|
17 |
+
config
|
18 |
+
):
|
19 |
+
cache_latents = config.train.cache_latents
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
if not cache_latents:
|
24 |
+
latents = tensor_to_vae_latent(batch["pixel_values"], vae)
|
25 |
+
else:
|
26 |
+
latents = batch["latents"]
|
27 |
+
|
28 |
+
# Sample noise that we'll add to the latents
|
29 |
+
# use_offset_noise = use_offset_noise and not rescale_schedule
|
30 |
+
|
31 |
+
noise = sample_noise(latents, 0.1, False)
|
32 |
+
bsz = latents.shape[0]
|
33 |
+
|
34 |
+
# Sample a random timestep for each video
|
35 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
36 |
+
timesteps = timesteps.long()
|
37 |
+
|
38 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
39 |
+
# (this is the forward diffusion process)
|
40 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
41 |
+
|
42 |
+
# *Potentially* Fixes gradient checkpointing training.
|
43 |
+
# See: https://github.com/prigoyal/pytorch_memonger/blob/master/tutorial/Checkpointing_for_PyTorch_models.ipynb
|
44 |
+
# if kwargs.get('eval_train', False):
|
45 |
+
# unet.eval()
|
46 |
+
# text_encoder.eval()
|
47 |
+
|
48 |
+
# Encode text embeddings
|
49 |
+
token_ids = batch['prompt_ids']
|
50 |
+
encoder_hidden_states = text_encoder(token_ids)[0]
|
51 |
+
detached_encoder_state = encoder_hidden_states.clone().detach()
|
52 |
+
|
53 |
+
# Get the target for loss depending on the prediction type
|
54 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
55 |
+
target = noise
|
56 |
+
|
57 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
58 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
59 |
+
|
60 |
+
else:
|
61 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
62 |
+
|
63 |
+
encoder_hidden_states = detached_encoder_state
|
64 |
+
|
65 |
+
|
66 |
+
# optimization
|
67 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states=encoder_hidden_states).sample
|
68 |
+
loss_temporal = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
69 |
+
|
70 |
+
beta = 1
|
71 |
+
alpha = (beta ** 2 + 1) ** 0.5
|
72 |
+
ran_idx = torch.randint(0, model_pred.shape[2], (1,)).item()
|
73 |
+
model_pred_decent = alpha * model_pred - beta * model_pred[:, :, ran_idx, :, :].unsqueeze(2)
|
74 |
+
target_decent = alpha * target - beta * target[:, :, ran_idx, :, :].unsqueeze(2)
|
75 |
+
loss_ad_temporal = F.mse_loss(model_pred_decent.float(), target_decent.float(), reduction="mean")
|
76 |
+
loss_temporal = loss_temporal + loss_ad_temporal
|
77 |
+
|
78 |
+
avg_loss_temporal = accelerator.gather(loss_temporal.repeat(config.train.train_batch_size)).mean()
|
79 |
+
train_loss_temporal += avg_loss_temporal.item() / config.train.gradient_accumulation_steps
|
80 |
+
|
81 |
+
accelerator.backward(loss_temporal)
|
82 |
+
optimizers[0].step()
|
83 |
+
|
84 |
+
lr_schedulers[0].step()
|
85 |
+
|
86 |
+
return loss_temporal, train_loss_temporal
|
loss/motion_distillation_loss.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from utils.func_utils import tensor_to_vae_latent, sample_noise
|
4 |
+
|
5 |
+
def MotionDistillationLoss(
|
6 |
+
train_loss_temporal,
|
7 |
+
accelerator,
|
8 |
+
optimizers,
|
9 |
+
lr_schedulers,
|
10 |
+
unet,
|
11 |
+
vae,
|
12 |
+
text_encoder,
|
13 |
+
noise_scheduler,
|
14 |
+
batch,
|
15 |
+
step,
|
16 |
+
config
|
17 |
+
):
|
18 |
+
cache_latents = config.train.cache_latents
|
19 |
+
|
20 |
+
if not cache_latents:
|
21 |
+
latents = tensor_to_vae_latent(batch["pixel_values"], vae)
|
22 |
+
else:
|
23 |
+
latents = batch["latents"]
|
24 |
+
|
25 |
+
# Sample noise that we'll add to the latents
|
26 |
+
# use_offset_noise = use_offset_noise and not rescale_schedule
|
27 |
+
|
28 |
+
noise = sample_noise(latents, 0.1, False)
|
29 |
+
bsz = latents.shape[0]
|
30 |
+
|
31 |
+
# Sample a random timestep for each video
|
32 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
33 |
+
timesteps = timesteps.long()
|
34 |
+
|
35 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
36 |
+
# (this is the forward diffusion process)
|
37 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
38 |
+
|
39 |
+
# *Potentially* Fixes gradient checkpointing training.
|
40 |
+
# See: https://github.com/prigoyal/pytorch_memonger/blob/master/tutorial/Checkpointing_for_PyTorch_models.ipynb
|
41 |
+
# if kwargs.get('eval_train', False):
|
42 |
+
# unet.eval()
|
43 |
+
# text_encoder.eval()
|
44 |
+
|
45 |
+
# Encode text embeddings
|
46 |
+
token_ids = batch['prompt_ids']
|
47 |
+
encoder_hidden_states = text_encoder(token_ids)[0]
|
48 |
+
detached_encoder_state = encoder_hidden_states.clone().detach()
|
49 |
+
|
50 |
+
# Get the target for loss depending on the prediction type
|
51 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
52 |
+
target = noise
|
53 |
+
|
54 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
55 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
56 |
+
|
57 |
+
else:
|
58 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
59 |
+
|
60 |
+
encoder_hidden_states = detached_encoder_state
|
61 |
+
|
62 |
+
|
63 |
+
# optimization
|
64 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states=encoder_hidden_states).sample
|
65 |
+
|
66 |
+
loss_temporal = 0
|
67 |
+
model_pred_reidual = torch.abs(model_pred[:,:,1:,:,:] - model_pred[:,:,:-1,:,:])
|
68 |
+
target_residual = torch.abs(target[:, :, 1:, :, :] - target[:, :, :-1, :, :])
|
69 |
+
loss_temporal = loss_temporal + (1 - F.cosine_similarity(model_pred_reidual, target_residual, dim=2).mean)
|
70 |
+
|
71 |
+
avg_loss_temporal = accelerator.gather(loss_temporal.repeat(config.train.train_batch_size)).mean()
|
72 |
+
train_loss_temporal += avg_loss_temporal.item() / config.train.gradient_accumulation_steps
|
73 |
+
|
74 |
+
accelerator.backward(loss_temporal)
|
75 |
+
optimizers[0].step()
|
76 |
+
lr_schedulers[0].step()
|
77 |
+
|
78 |
+
return loss_temporal, train_loss_temporal
|
79 |
+
|
models/dit/latte_t2v.py
ADDED
@@ -0,0 +1,990 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
|
6 |
+
from dataclasses import dataclass
|
7 |
+
from einops import rearrange, repeat
|
8 |
+
from typing import Any, Dict, Optional, Tuple
|
9 |
+
from diffusers.models import Transformer2DModel
|
10 |
+
from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate
|
11 |
+
from diffusers.models.embeddings import get_1d_sincos_pos_embed_from_grid, ImagePositionalEmbeddings, CaptionProjection, PatchEmbed, CombinedTimestepSizeEmbeddings
|
12 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
13 |
+
from diffusers.models.modeling_utils import ModelMixin
|
14 |
+
from diffusers.models.attention import BasicTransformerBlock
|
15 |
+
from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
|
16 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
17 |
+
from diffusers.models.embeddings import SinusoidalPositionalEmbedding
|
18 |
+
from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormZero
|
19 |
+
from diffusers.models.attention_processor import Attention
|
20 |
+
from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
|
21 |
+
|
22 |
+
from dataclasses import dataclass
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn.functional as F
|
26 |
+
from torch import nn
|
27 |
+
|
28 |
+
@maybe_allow_in_graph
|
29 |
+
class GatedSelfAttentionDense(nn.Module):
|
30 |
+
r"""
|
31 |
+
A gated self-attention dense layer that combines visual features and object features.
|
32 |
+
|
33 |
+
Parameters:
|
34 |
+
query_dim (`int`): The number of channels in the query.
|
35 |
+
context_dim (`int`): The number of channels in the context.
|
36 |
+
n_heads (`int`): The number of heads to use for attention.
|
37 |
+
d_head (`int`): The number of channels in each head.
|
38 |
+
"""
|
39 |
+
|
40 |
+
def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
|
41 |
+
super().__init__()
|
42 |
+
|
43 |
+
# we need a linear projection since we need cat visual feature and obj feature
|
44 |
+
self.linear = nn.Linear(context_dim, query_dim)
|
45 |
+
|
46 |
+
self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
|
47 |
+
self.ff = FeedForward(query_dim, activation_fn="geglu")
|
48 |
+
|
49 |
+
self.norm1 = nn.LayerNorm(query_dim)
|
50 |
+
self.norm2 = nn.LayerNorm(query_dim)
|
51 |
+
|
52 |
+
self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
|
53 |
+
self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
|
54 |
+
|
55 |
+
self.enabled = True
|
56 |
+
|
57 |
+
def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
|
58 |
+
if not self.enabled:
|
59 |
+
return x
|
60 |
+
|
61 |
+
n_visual = x.shape[1]
|
62 |
+
objs = self.linear(objs)
|
63 |
+
|
64 |
+
x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
|
65 |
+
x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
|
66 |
+
|
67 |
+
return x
|
68 |
+
|
69 |
+
class FeedForward(nn.Module):
|
70 |
+
r"""
|
71 |
+
A feed-forward layer.
|
72 |
+
|
73 |
+
Parameters:
|
74 |
+
dim (`int`): The number of channels in the input.
|
75 |
+
dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
|
76 |
+
mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
|
77 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
78 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
79 |
+
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
|
80 |
+
"""
|
81 |
+
|
82 |
+
def __init__(
|
83 |
+
self,
|
84 |
+
dim: int,
|
85 |
+
dim_out: Optional[int] = None,
|
86 |
+
mult: int = 4,
|
87 |
+
dropout: float = 0.0,
|
88 |
+
activation_fn: str = "geglu",
|
89 |
+
final_dropout: bool = False,
|
90 |
+
):
|
91 |
+
super().__init__()
|
92 |
+
inner_dim = int(dim * mult)
|
93 |
+
dim_out = dim_out if dim_out is not None else dim
|
94 |
+
linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
|
95 |
+
|
96 |
+
if activation_fn == "gelu":
|
97 |
+
act_fn = GELU(dim, inner_dim)
|
98 |
+
if activation_fn == "gelu-approximate":
|
99 |
+
act_fn = GELU(dim, inner_dim, approximate="tanh")
|
100 |
+
elif activation_fn == "geglu":
|
101 |
+
act_fn = GEGLU(dim, inner_dim)
|
102 |
+
elif activation_fn == "geglu-approximate":
|
103 |
+
act_fn = ApproximateGELU(dim, inner_dim)
|
104 |
+
|
105 |
+
self.net = nn.ModuleList([])
|
106 |
+
# project in
|
107 |
+
self.net.append(act_fn)
|
108 |
+
# project dropout
|
109 |
+
self.net.append(nn.Dropout(dropout))
|
110 |
+
# project out
|
111 |
+
self.net.append(linear_cls(inner_dim, dim_out))
|
112 |
+
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
113 |
+
if final_dropout:
|
114 |
+
self.net.append(nn.Dropout(dropout))
|
115 |
+
|
116 |
+
def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
|
117 |
+
compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
|
118 |
+
for module in self.net:
|
119 |
+
if isinstance(module, compatible_cls):
|
120 |
+
hidden_states = module(hidden_states, scale)
|
121 |
+
else:
|
122 |
+
hidden_states = module(hidden_states)
|
123 |
+
return hidden_states
|
124 |
+
|
125 |
+
@maybe_allow_in_graph
|
126 |
+
class BasicTransformerBlock_(nn.Module):
|
127 |
+
r"""
|
128 |
+
A basic Transformer block.
|
129 |
+
|
130 |
+
Parameters:
|
131 |
+
dim (`int`): The number of channels in the input and output.
|
132 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
133 |
+
attention_head_dim (`int`): The number of channels in each head.
|
134 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
135 |
+
cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
|
136 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
137 |
+
num_embeds_ada_norm (:
|
138 |
+
obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
|
139 |
+
attention_bias (:
|
140 |
+
obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
|
141 |
+
only_cross_attention (`bool`, *optional*):
|
142 |
+
Whether to use only cross-attention layers. In this case two cross attention layers are used.
|
143 |
+
double_self_attention (`bool`, *optional*):
|
144 |
+
Whether to use two self-attention layers. In this case no cross attention layers are used.
|
145 |
+
upcast_attention (`bool`, *optional*):
|
146 |
+
Whether to upcast the attention computation to float32. This is useful for mixed precision training.
|
147 |
+
norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
|
148 |
+
Whether to use learnable elementwise affine parameters for normalization.
|
149 |
+
norm_type (`str`, *optional*, defaults to `"layer_norm"`):
|
150 |
+
The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
|
151 |
+
final_dropout (`bool` *optional*, defaults to False):
|
152 |
+
Whether to apply a final dropout after the last feed-forward layer.
|
153 |
+
attention_type (`str`, *optional*, defaults to `"default"`):
|
154 |
+
The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
|
155 |
+
positional_embeddings (`str`, *optional*, defaults to `None`):
|
156 |
+
The type of positional embeddings to apply to.
|
157 |
+
num_positional_embeddings (`int`, *optional*, defaults to `None`):
|
158 |
+
The maximum number of positional embeddings to apply.
|
159 |
+
"""
|
160 |
+
|
161 |
+
def __init__(
|
162 |
+
self,
|
163 |
+
dim: int,
|
164 |
+
num_attention_heads: int,
|
165 |
+
attention_head_dim: int,
|
166 |
+
dropout=0.0,
|
167 |
+
cross_attention_dim: Optional[int] = None,
|
168 |
+
activation_fn: str = "geglu",
|
169 |
+
num_embeds_ada_norm: Optional[int] = None,
|
170 |
+
attention_bias: bool = False,
|
171 |
+
only_cross_attention: bool = False,
|
172 |
+
double_self_attention: bool = False,
|
173 |
+
upcast_attention: bool = False,
|
174 |
+
norm_elementwise_affine: bool = True,
|
175 |
+
norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
|
176 |
+
norm_eps: float = 1e-5,
|
177 |
+
final_dropout: bool = False,
|
178 |
+
attention_type: str = "default",
|
179 |
+
positional_embeddings: Optional[str] = None,
|
180 |
+
num_positional_embeddings: Optional[int] = None,
|
181 |
+
):
|
182 |
+
super().__init__()
|
183 |
+
self.only_cross_attention = only_cross_attention
|
184 |
+
|
185 |
+
self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
|
186 |
+
self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
|
187 |
+
self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
|
188 |
+
self.use_layer_norm = norm_type == "layer_norm"
|
189 |
+
|
190 |
+
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
|
191 |
+
raise ValueError(
|
192 |
+
f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
|
193 |
+
f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
|
194 |
+
)
|
195 |
+
|
196 |
+
if positional_embeddings and (num_positional_embeddings is None):
|
197 |
+
raise ValueError(
|
198 |
+
"If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
|
199 |
+
)
|
200 |
+
|
201 |
+
if positional_embeddings == "sinusoidal":
|
202 |
+
self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
|
203 |
+
else:
|
204 |
+
self.pos_embed = None
|
205 |
+
|
206 |
+
# Define 3 blocks. Each block has its own normalization layer.
|
207 |
+
# 1. Self-Attn
|
208 |
+
if self.use_ada_layer_norm:
|
209 |
+
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
|
210 |
+
elif self.use_ada_layer_norm_zero:
|
211 |
+
self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
|
212 |
+
else:
|
213 |
+
self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
214 |
+
|
215 |
+
self.attn1 = Attention(
|
216 |
+
query_dim=dim,
|
217 |
+
heads=num_attention_heads,
|
218 |
+
dim_head=attention_head_dim,
|
219 |
+
dropout=dropout,
|
220 |
+
bias=attention_bias,
|
221 |
+
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
222 |
+
upcast_attention=upcast_attention,
|
223 |
+
)
|
224 |
+
|
225 |
+
# # 2. Cross-Attn
|
226 |
+
# if cross_attention_dim is not None or double_self_attention:
|
227 |
+
# # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
|
228 |
+
# # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
|
229 |
+
# # the second cross attention block.
|
230 |
+
# self.norm2 = (
|
231 |
+
# AdaLayerNorm(dim, num_embeds_ada_norm)
|
232 |
+
# if self.use_ada_layer_norm
|
233 |
+
# else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
234 |
+
# )
|
235 |
+
# self.attn2 = Attention(
|
236 |
+
# query_dim=dim,
|
237 |
+
# cross_attention_dim=cross_attention_dim if not double_self_attention else None,
|
238 |
+
# heads=num_attention_heads,
|
239 |
+
# dim_head=attention_head_dim,
|
240 |
+
# dropout=dropout,
|
241 |
+
# bias=attention_bias,
|
242 |
+
# upcast_attention=upcast_attention,
|
243 |
+
# ) # is self-attn if encoder_hidden_states is none
|
244 |
+
# else:
|
245 |
+
# self.norm2 = None
|
246 |
+
# self.attn2 = None
|
247 |
+
|
248 |
+
# 3. Feed-forward
|
249 |
+
# if not self.use_ada_layer_norm_single:
|
250 |
+
# self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
251 |
+
self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
252 |
+
|
253 |
+
self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
|
254 |
+
|
255 |
+
# 4. Fuser
|
256 |
+
if attention_type == "gated" or attention_type == "gated-text-image":
|
257 |
+
self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
|
258 |
+
|
259 |
+
# 5. Scale-shift for PixArt-Alpha.
|
260 |
+
if self.use_ada_layer_norm_single:
|
261 |
+
self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
|
262 |
+
|
263 |
+
# let chunk size default to None
|
264 |
+
self._chunk_size = None
|
265 |
+
self._chunk_dim = 0
|
266 |
+
|
267 |
+
def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
|
268 |
+
# Sets chunk feed-forward
|
269 |
+
self._chunk_size = chunk_size
|
270 |
+
self._chunk_dim = dim
|
271 |
+
|
272 |
+
def forward(
|
273 |
+
self,
|
274 |
+
hidden_states: torch.FloatTensor,
|
275 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
276 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
277 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
278 |
+
timestep: Optional[torch.LongTensor] = None,
|
279 |
+
cross_attention_kwargs: Dict[str, Any] = None,
|
280 |
+
class_labels: Optional[torch.LongTensor] = None,
|
281 |
+
) -> torch.FloatTensor:
|
282 |
+
# Notice that normalization is always applied before the real computation in the following blocks.
|
283 |
+
# 0. Self-Attention
|
284 |
+
batch_size = hidden_states.shape[0]
|
285 |
+
|
286 |
+
if self.use_ada_layer_norm:
|
287 |
+
norm_hidden_states = self.norm1(hidden_states, timestep)
|
288 |
+
elif self.use_ada_layer_norm_zero:
|
289 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
290 |
+
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
|
291 |
+
)
|
292 |
+
elif self.use_layer_norm:
|
293 |
+
norm_hidden_states = self.norm1(hidden_states)
|
294 |
+
elif self.use_ada_layer_norm_single:
|
295 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
296 |
+
self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
|
297 |
+
).chunk(6, dim=1)
|
298 |
+
norm_hidden_states = self.norm1(hidden_states)
|
299 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
|
300 |
+
norm_hidden_states = norm_hidden_states.squeeze(1)
|
301 |
+
else:
|
302 |
+
raise ValueError("Incorrect norm used")
|
303 |
+
|
304 |
+
if self.pos_embed is not None:
|
305 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
306 |
+
|
307 |
+
# 1. Retrieve lora scale.
|
308 |
+
lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
|
309 |
+
|
310 |
+
# 2. Prepare GLIGEN inputs
|
311 |
+
cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
|
312 |
+
gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
|
313 |
+
|
314 |
+
attn_output = self.attn1(
|
315 |
+
norm_hidden_states,
|
316 |
+
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
|
317 |
+
attention_mask=attention_mask,
|
318 |
+
**cross_attention_kwargs,
|
319 |
+
)
|
320 |
+
if self.use_ada_layer_norm_zero:
|
321 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
322 |
+
elif self.use_ada_layer_norm_single:
|
323 |
+
attn_output = gate_msa * attn_output
|
324 |
+
|
325 |
+
hidden_states = attn_output + hidden_states
|
326 |
+
if hidden_states.ndim == 4:
|
327 |
+
hidden_states = hidden_states.squeeze(1)
|
328 |
+
|
329 |
+
# 2.5 GLIGEN Control
|
330 |
+
if gligen_kwargs is not None:
|
331 |
+
hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
|
332 |
+
|
333 |
+
# # 3. Cross-Attention
|
334 |
+
# if self.attn2 is not None:
|
335 |
+
# if self.use_ada_layer_norm:
|
336 |
+
# norm_hidden_states = self.norm2(hidden_states, timestep)
|
337 |
+
# elif self.use_ada_layer_norm_zero or self.use_layer_norm:
|
338 |
+
# norm_hidden_states = self.norm2(hidden_states)
|
339 |
+
# elif self.use_ada_layer_norm_single:
|
340 |
+
# # For PixArt norm2 isn't applied here:
|
341 |
+
# # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
|
342 |
+
# norm_hidden_states = hidden_states
|
343 |
+
# else:
|
344 |
+
# raise ValueError("Incorrect norm")
|
345 |
+
|
346 |
+
# if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
|
347 |
+
# norm_hidden_states = self.pos_embed(norm_hidden_states)
|
348 |
+
|
349 |
+
# attn_output = self.attn2(
|
350 |
+
# norm_hidden_states,
|
351 |
+
# encoder_hidden_states=encoder_hidden_states,
|
352 |
+
# attention_mask=encoder_attention_mask,
|
353 |
+
# **cross_attention_kwargs,
|
354 |
+
# )
|
355 |
+
# hidden_states = attn_output + hidden_states
|
356 |
+
|
357 |
+
# 4. Feed-forward
|
358 |
+
# if not self.use_ada_layer_norm_single:
|
359 |
+
# norm_hidden_states = self.norm3(hidden_states)
|
360 |
+
|
361 |
+
if self.use_ada_layer_norm_zero:
|
362 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
363 |
+
|
364 |
+
if self.use_ada_layer_norm_single:
|
365 |
+
# norm_hidden_states = self.norm2(hidden_states)
|
366 |
+
norm_hidden_states = self.norm3(hidden_states)
|
367 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
|
368 |
+
|
369 |
+
if self._chunk_size is not None:
|
370 |
+
# "feed_forward_chunk_size" can be used to save memory
|
371 |
+
if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
|
372 |
+
raise ValueError(
|
373 |
+
f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
|
374 |
+
)
|
375 |
+
|
376 |
+
num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
|
377 |
+
ff_output = torch.cat(
|
378 |
+
[
|
379 |
+
self.ff(hid_slice, scale=lora_scale)
|
380 |
+
for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)
|
381 |
+
],
|
382 |
+
dim=self._chunk_dim,
|
383 |
+
)
|
384 |
+
else:
|
385 |
+
ff_output = self.ff(norm_hidden_states, scale=lora_scale)
|
386 |
+
|
387 |
+
if self.use_ada_layer_norm_zero:
|
388 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
389 |
+
elif self.use_ada_layer_norm_single:
|
390 |
+
ff_output = gate_mlp * ff_output
|
391 |
+
|
392 |
+
hidden_states = ff_output + hidden_states
|
393 |
+
if hidden_states.ndim == 4:
|
394 |
+
hidden_states = hidden_states.squeeze(1)
|
395 |
+
|
396 |
+
return hidden_states
|
397 |
+
|
398 |
+
class AdaLayerNormSingle(nn.Module):
|
399 |
+
r"""
|
400 |
+
Norm layer adaptive layer norm single (adaLN-single).
|
401 |
+
|
402 |
+
As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
|
403 |
+
|
404 |
+
Parameters:
|
405 |
+
embedding_dim (`int`): The size of each embedding vector.
|
406 |
+
use_additional_conditions (`bool`): To use additional conditions for normalization or not.
|
407 |
+
"""
|
408 |
+
|
409 |
+
def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
|
410 |
+
super().__init__()
|
411 |
+
|
412 |
+
self.emb = CombinedTimestepSizeEmbeddings(
|
413 |
+
embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
|
414 |
+
)
|
415 |
+
|
416 |
+
self.silu = nn.SiLU()
|
417 |
+
self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
|
418 |
+
|
419 |
+
def forward(
|
420 |
+
self,
|
421 |
+
timestep: torch.Tensor,
|
422 |
+
added_cond_kwargs: Dict[str, torch.Tensor] = None,
|
423 |
+
batch_size: int = None,
|
424 |
+
hidden_dtype: Optional[torch.dtype] = None,
|
425 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
426 |
+
# No modulation happening here.
|
427 |
+
embedded_timestep = self.emb(timestep, batch_size=batch_size, hidden_dtype=hidden_dtype, resolution=None, aspect_ratio=None)
|
428 |
+
return self.linear(self.silu(embedded_timestep)), embedded_timestep
|
429 |
+
|
430 |
+
@dataclass
|
431 |
+
class Transformer3DModelOutput(BaseOutput):
|
432 |
+
"""
|
433 |
+
The output of [`Transformer2DModel`].
|
434 |
+
|
435 |
+
Args:
|
436 |
+
sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
|
437 |
+
The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
|
438 |
+
distributions for the unnoised latent pixels.
|
439 |
+
"""
|
440 |
+
|
441 |
+
sample: torch.FloatTensor
|
442 |
+
|
443 |
+
|
444 |
+
class LatteT2V(ModelMixin, ConfigMixin):
|
445 |
+
_supports_gradient_checkpointing = True
|
446 |
+
|
447 |
+
"""
|
448 |
+
A 2D Transformer model for image-like data.
|
449 |
+
|
450 |
+
Parameters:
|
451 |
+
num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
|
452 |
+
attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
|
453 |
+
in_channels (`int`, *optional*):
|
454 |
+
The number of channels in the input and output (specify if the input is **continuous**).
|
455 |
+
num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
|
456 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
457 |
+
cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
|
458 |
+
sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
|
459 |
+
This is fixed during training since it is used to learn a number of position embeddings.
|
460 |
+
num_vector_embeds (`int`, *optional*):
|
461 |
+
The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
|
462 |
+
Includes the class for the masked latent pixel.
|
463 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
|
464 |
+
num_embeds_ada_norm ( `int`, *optional*):
|
465 |
+
The number of diffusion steps used during training. Pass if at least one of the norm_layers is
|
466 |
+
`AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
|
467 |
+
added to the hidden states.
|
468 |
+
|
469 |
+
During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
|
470 |
+
attention_bias (`bool`, *optional*):
|
471 |
+
Configure if the `TransformerBlocks` attention should contain a bias parameter.
|
472 |
+
"""
|
473 |
+
|
474 |
+
@register_to_config
|
475 |
+
def __init__(
|
476 |
+
self,
|
477 |
+
num_attention_heads: int = 16,
|
478 |
+
attention_head_dim: int = 88,
|
479 |
+
in_channels: Optional[int] = None,
|
480 |
+
out_channels: Optional[int] = None,
|
481 |
+
num_layers: int = 1,
|
482 |
+
dropout: float = 0.0,
|
483 |
+
norm_num_groups: int = 32,
|
484 |
+
cross_attention_dim: Optional[int] = None,
|
485 |
+
attention_bias: bool = False,
|
486 |
+
sample_size: Optional[int] = None,
|
487 |
+
num_vector_embeds: Optional[int] = None,
|
488 |
+
patch_size: Optional[int] = None,
|
489 |
+
activation_fn: str = "geglu",
|
490 |
+
num_embeds_ada_norm: Optional[int] = None,
|
491 |
+
use_linear_projection: bool = False,
|
492 |
+
only_cross_attention: bool = False,
|
493 |
+
double_self_attention: bool = False,
|
494 |
+
upcast_attention: bool = False,
|
495 |
+
norm_type: str = "layer_norm",
|
496 |
+
norm_elementwise_affine: bool = True,
|
497 |
+
norm_eps: float = 1e-5,
|
498 |
+
attention_type: str = "default",
|
499 |
+
caption_channels: int = None,
|
500 |
+
video_length: int = 16,
|
501 |
+
):
|
502 |
+
super().__init__()
|
503 |
+
self.use_linear_projection = use_linear_projection
|
504 |
+
self.num_attention_heads = num_attention_heads
|
505 |
+
self.attention_head_dim = attention_head_dim
|
506 |
+
inner_dim = num_attention_heads * attention_head_dim
|
507 |
+
self.video_length = video_length
|
508 |
+
|
509 |
+
conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
|
510 |
+
linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
|
511 |
+
|
512 |
+
# 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
|
513 |
+
# Define whether input is continuous or discrete depending on configuration
|
514 |
+
self.is_input_continuous = (in_channels is not None) and (patch_size is None)
|
515 |
+
self.is_input_vectorized = num_vector_embeds is not None
|
516 |
+
self.is_input_patches = in_channels is not None and patch_size is not None
|
517 |
+
|
518 |
+
if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
|
519 |
+
deprecation_message = (
|
520 |
+
f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
|
521 |
+
" incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
|
522 |
+
" Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
|
523 |
+
" results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
|
524 |
+
" would be very nice if you could open a Pull request for the `transformer/config.json` file"
|
525 |
+
)
|
526 |
+
deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
|
527 |
+
norm_type = "ada_norm"
|
528 |
+
|
529 |
+
if self.is_input_continuous and self.is_input_vectorized:
|
530 |
+
raise ValueError(
|
531 |
+
f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
|
532 |
+
" sure that either `in_channels` or `num_vector_embeds` is None."
|
533 |
+
)
|
534 |
+
elif self.is_input_vectorized and self.is_input_patches:
|
535 |
+
raise ValueError(
|
536 |
+
f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
|
537 |
+
" sure that either `num_vector_embeds` or `num_patches` is None."
|
538 |
+
)
|
539 |
+
elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
|
540 |
+
raise ValueError(
|
541 |
+
f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
|
542 |
+
f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
|
543 |
+
)
|
544 |
+
|
545 |
+
# 2. Define input layers
|
546 |
+
if self.is_input_continuous:
|
547 |
+
self.in_channels = in_channels
|
548 |
+
|
549 |
+
self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
550 |
+
if use_linear_projection:
|
551 |
+
self.proj_in = linear_cls(in_channels, inner_dim)
|
552 |
+
else:
|
553 |
+
self.proj_in = conv_cls(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
554 |
+
elif self.is_input_vectorized:
|
555 |
+
assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
|
556 |
+
assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"
|
557 |
+
|
558 |
+
self.height = sample_size
|
559 |
+
self.width = sample_size
|
560 |
+
self.num_vector_embeds = num_vector_embeds
|
561 |
+
self.num_latent_pixels = self.height * self.width
|
562 |
+
|
563 |
+
self.latent_image_embedding = ImagePositionalEmbeddings(
|
564 |
+
num_embed=num_vector_embeds, embed_dim=inner_dim, height=self.height, width=self.width
|
565 |
+
)
|
566 |
+
elif self.is_input_patches:
|
567 |
+
assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
|
568 |
+
|
569 |
+
self.height = sample_size
|
570 |
+
self.width = sample_size
|
571 |
+
|
572 |
+
self.patch_size = patch_size
|
573 |
+
interpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1
|
574 |
+
interpolation_scale = max(interpolation_scale, 1)
|
575 |
+
self.pos_embed = PatchEmbed(
|
576 |
+
height=sample_size,
|
577 |
+
width=sample_size,
|
578 |
+
patch_size=patch_size,
|
579 |
+
in_channels=in_channels,
|
580 |
+
embed_dim=inner_dim,
|
581 |
+
interpolation_scale=interpolation_scale,
|
582 |
+
)
|
583 |
+
|
584 |
+
# 3. Define transformers blocks
|
585 |
+
self.transformer_blocks = nn.ModuleList(
|
586 |
+
[
|
587 |
+
BasicTransformerBlock(
|
588 |
+
inner_dim,
|
589 |
+
num_attention_heads,
|
590 |
+
attention_head_dim,
|
591 |
+
dropout=dropout,
|
592 |
+
cross_attention_dim=cross_attention_dim,
|
593 |
+
activation_fn=activation_fn,
|
594 |
+
num_embeds_ada_norm=num_embeds_ada_norm,
|
595 |
+
attention_bias=attention_bias,
|
596 |
+
only_cross_attention=only_cross_attention,
|
597 |
+
double_self_attention=double_self_attention,
|
598 |
+
upcast_attention=upcast_attention,
|
599 |
+
norm_type=norm_type,
|
600 |
+
norm_elementwise_affine=norm_elementwise_affine,
|
601 |
+
norm_eps=norm_eps,
|
602 |
+
attention_type=attention_type,
|
603 |
+
)
|
604 |
+
for d in range(num_layers)
|
605 |
+
]
|
606 |
+
)
|
607 |
+
|
608 |
+
# Define temporal transformers blocks
|
609 |
+
self.temporal_transformer_blocks = nn.ModuleList(
|
610 |
+
[
|
611 |
+
BasicTransformerBlock_( # one attention
|
612 |
+
inner_dim,
|
613 |
+
num_attention_heads, # num_attention_heads
|
614 |
+
attention_head_dim, # attention_head_dim 72
|
615 |
+
dropout=dropout,
|
616 |
+
cross_attention_dim=None,
|
617 |
+
activation_fn=activation_fn,
|
618 |
+
num_embeds_ada_norm=num_embeds_ada_norm,
|
619 |
+
attention_bias=attention_bias,
|
620 |
+
only_cross_attention=only_cross_attention,
|
621 |
+
double_self_attention=False,
|
622 |
+
upcast_attention=upcast_attention,
|
623 |
+
norm_type=norm_type,
|
624 |
+
norm_elementwise_affine=norm_elementwise_affine,
|
625 |
+
norm_eps=norm_eps,
|
626 |
+
attention_type=attention_type,
|
627 |
+
)
|
628 |
+
for d in range(num_layers)
|
629 |
+
]
|
630 |
+
)
|
631 |
+
|
632 |
+
|
633 |
+
# 4. Define output layers
|
634 |
+
self.out_channels = in_channels if out_channels is None else out_channels
|
635 |
+
if self.is_input_continuous:
|
636 |
+
# TODO: should use out_channels for continuous projections
|
637 |
+
if use_linear_projection:
|
638 |
+
self.proj_out = linear_cls(inner_dim, in_channels)
|
639 |
+
else:
|
640 |
+
self.proj_out = conv_cls(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
|
641 |
+
elif self.is_input_vectorized:
|
642 |
+
self.norm_out = nn.LayerNorm(inner_dim)
|
643 |
+
self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
|
644 |
+
elif self.is_input_patches and norm_type != "ada_norm_single":
|
645 |
+
self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
|
646 |
+
self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
|
647 |
+
self.proj_out_2 = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
|
648 |
+
elif self.is_input_patches and norm_type == "ada_norm_single":
|
649 |
+
self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
|
650 |
+
self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
|
651 |
+
self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
|
652 |
+
|
653 |
+
# 5. PixArt-Alpha blocks.
|
654 |
+
self.adaln_single = None
|
655 |
+
self.use_additional_conditions = False
|
656 |
+
if norm_type == "ada_norm_single":
|
657 |
+
self.use_additional_conditions = self.config.sample_size == 128 # False, 128 -> 1024
|
658 |
+
# TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
|
659 |
+
# additional conditions until we find better name
|
660 |
+
self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=self.use_additional_conditions)
|
661 |
+
|
662 |
+
self.caption_projection = None
|
663 |
+
if caption_channels is not None:
|
664 |
+
self.caption_projection = CaptionProjection(in_features=caption_channels, hidden_size=inner_dim)
|
665 |
+
|
666 |
+
self.gradient_checkpointing = False
|
667 |
+
|
668 |
+
# define temporal positional embedding
|
669 |
+
temp_pos_embed = self.get_1d_sincos_temp_embed(inner_dim, video_length) # 1152 hidden size
|
670 |
+
self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
|
671 |
+
|
672 |
+
|
673 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
674 |
+
self.gradient_checkpointing = value
|
675 |
+
|
676 |
+
|
677 |
+
def forward(
|
678 |
+
self,
|
679 |
+
hidden_states: torch.Tensor,
|
680 |
+
timestep: Optional[torch.LongTensor] = None,
|
681 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
682 |
+
added_cond_kwargs: Dict[str, torch.Tensor] = None,
|
683 |
+
class_labels: Optional[torch.LongTensor] = None,
|
684 |
+
cross_attention_kwargs: Dict[str, Any] = None,
|
685 |
+
attention_mask: Optional[torch.Tensor] = None,
|
686 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
687 |
+
use_image_num: int = 0,
|
688 |
+
enable_temporal_attentions: bool = True,
|
689 |
+
return_dict: bool = True,
|
690 |
+
):
|
691 |
+
"""
|
692 |
+
The [`Transformer2DModel`] forward method.
|
693 |
+
|
694 |
+
Args:
|
695 |
+
hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, frame, channel, height, width)` if continuous):
|
696 |
+
Input `hidden_states`.
|
697 |
+
encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
|
698 |
+
Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
|
699 |
+
self-attention.
|
700 |
+
timestep ( `torch.LongTensor`, *optional*):
|
701 |
+
Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
|
702 |
+
class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
|
703 |
+
Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
|
704 |
+
`AdaLayerZeroNorm`.
|
705 |
+
cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
|
706 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
707 |
+
`self.processor` in
|
708 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
709 |
+
attention_mask ( `torch.Tensor`, *optional*):
|
710 |
+
An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
|
711 |
+
is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
|
712 |
+
negative values to the attention scores corresponding to "discard" tokens.
|
713 |
+
encoder_attention_mask ( `torch.Tensor`, *optional*):
|
714 |
+
Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
|
715 |
+
|
716 |
+
* Mask `(batch, sequence_length)` True = keep, False = discard.
|
717 |
+
* Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
|
718 |
+
|
719 |
+
If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
|
720 |
+
above. This bias will be added to the cross-attention scores.
|
721 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
722 |
+
Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
|
723 |
+
tuple.
|
724 |
+
|
725 |
+
Returns:
|
726 |
+
If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
|
727 |
+
`tuple` where the first element is the sample tensor.
|
728 |
+
"""
|
729 |
+
input_batch_size, c, frame, h, w = hidden_states.shape
|
730 |
+
frame = frame - use_image_num
|
731 |
+
hidden_states = rearrange(hidden_states, 'b c f h w -> (b f) c h w').contiguous()
|
732 |
+
|
733 |
+
# ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
|
734 |
+
# we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
|
735 |
+
# we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
|
736 |
+
# expects mask of shape:
|
737 |
+
# [batch, key_tokens]
|
738 |
+
# adds singleton query_tokens dimension:
|
739 |
+
# [batch, 1, key_tokens]
|
740 |
+
# this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
|
741 |
+
# [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
|
742 |
+
# [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
|
743 |
+
if attention_mask is not None and attention_mask.ndim == 2:
|
744 |
+
# assume that mask is expressed as:
|
745 |
+
# (1 = keep, 0 = discard)
|
746 |
+
# convert mask into a bias that can be added to attention scores:
|
747 |
+
# (keep = +0, discard = -10000.0)
|
748 |
+
attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
|
749 |
+
attention_mask = attention_mask.unsqueeze(1)
|
750 |
+
|
751 |
+
# convert encoder_attention_mask to a bias the same way we do for attention_mask
|
752 |
+
if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2: # ndim == 2 means no image joint
|
753 |
+
encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
|
754 |
+
encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
|
755 |
+
encoder_attention_mask = repeat(encoder_attention_mask, 'b 1 l -> (b f) 1 l', f=frame).contiguous()
|
756 |
+
elif encoder_attention_mask is not None and encoder_attention_mask.ndim == 3: # ndim == 3 means image joint
|
757 |
+
encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
|
758 |
+
encoder_attention_mask_video = encoder_attention_mask[:, :1, ...]
|
759 |
+
encoder_attention_mask_video = repeat(encoder_attention_mask_video, 'b 1 l -> b (1 f) l', f=frame).contiguous()
|
760 |
+
encoder_attention_mask_image = encoder_attention_mask[:, 1:, ...]
|
761 |
+
encoder_attention_mask = torch.cat([encoder_attention_mask_video, encoder_attention_mask_image], dim=1)
|
762 |
+
encoder_attention_mask = rearrange(encoder_attention_mask, 'b n l -> (b n) l').contiguous().unsqueeze(1)
|
763 |
+
|
764 |
+
|
765 |
+
# Retrieve lora scale.
|
766 |
+
lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
|
767 |
+
|
768 |
+
# 1. Input
|
769 |
+
if self.is_input_patches: # here
|
770 |
+
height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
|
771 |
+
num_patches = height * width
|
772 |
+
|
773 |
+
hidden_states = self.pos_embed(hidden_states) # alrady add positional embeddings
|
774 |
+
|
775 |
+
if self.adaln_single is not None:
|
776 |
+
if self.use_additional_conditions and added_cond_kwargs is None:
|
777 |
+
raise ValueError(
|
778 |
+
"`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
|
779 |
+
)
|
780 |
+
# batch_size = hidden_states.shape[0]
|
781 |
+
batch_size = input_batch_size
|
782 |
+
timestep, embedded_timestep = self.adaln_single(
|
783 |
+
timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
|
784 |
+
)
|
785 |
+
|
786 |
+
# 2. Blocks
|
787 |
+
if self.caption_projection is not None:
|
788 |
+
batch_size = hidden_states.shape[0]
|
789 |
+
encoder_hidden_states = self.caption_projection(encoder_hidden_states) # 3 120 1152
|
790 |
+
|
791 |
+
if use_image_num != 0 and self.training:
|
792 |
+
encoder_hidden_states_video = encoder_hidden_states[:, :1, ...]
|
793 |
+
encoder_hidden_states_video = repeat(encoder_hidden_states_video, 'b 1 t d -> b (1 f) t d', f=frame).contiguous()
|
794 |
+
encoder_hidden_states_image = encoder_hidden_states[:, 1:, ...]
|
795 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states_video, encoder_hidden_states_image], dim=1)
|
796 |
+
encoder_hidden_states_spatial = rearrange(encoder_hidden_states, 'b f t d -> (b f) t d').contiguous()
|
797 |
+
else:
|
798 |
+
encoder_hidden_states_spatial = repeat(encoder_hidden_states, 'b t d -> (b f) t d', f=frame).contiguous()
|
799 |
+
|
800 |
+
# prepare timesteps for spatial and temporal block
|
801 |
+
timestep_spatial = repeat(timestep, 'b d -> (b f) d', f=frame + use_image_num).contiguous()
|
802 |
+
timestep_temp = repeat(timestep, 'b d -> (b p) d', p=num_patches).contiguous()
|
803 |
+
|
804 |
+
for i, (spatial_block, temp_block) in enumerate(zip(self.transformer_blocks, self.temporal_transformer_blocks)):
|
805 |
+
|
806 |
+
if self.training and self.gradient_checkpointing:
|
807 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
808 |
+
spatial_block,
|
809 |
+
hidden_states,
|
810 |
+
attention_mask,
|
811 |
+
encoder_hidden_states_spatial,
|
812 |
+
encoder_attention_mask,
|
813 |
+
timestep_spatial,
|
814 |
+
cross_attention_kwargs,
|
815 |
+
class_labels,
|
816 |
+
use_reentrant=False,
|
817 |
+
)
|
818 |
+
|
819 |
+
if enable_temporal_attentions:
|
820 |
+
hidden_states = rearrange(hidden_states, '(b f) t d -> (b t) f d', b=input_batch_size).contiguous()
|
821 |
+
|
822 |
+
if use_image_num != 0: # image-video joitn training
|
823 |
+
hidden_states_video = hidden_states[:, :frame, ...]
|
824 |
+
hidden_states_image = hidden_states[:, frame:, ...]
|
825 |
+
|
826 |
+
if i == 0:
|
827 |
+
hidden_states_video = hidden_states_video + self.temp_pos_embed
|
828 |
+
|
829 |
+
hidden_states_video = torch.utils.checkpoint.checkpoint(
|
830 |
+
temp_block,
|
831 |
+
hidden_states_video,
|
832 |
+
None, # attention_mask
|
833 |
+
None, # encoder_hidden_states
|
834 |
+
None, # encoder_attention_mask
|
835 |
+
timestep_temp,
|
836 |
+
cross_attention_kwargs,
|
837 |
+
class_labels,
|
838 |
+
use_reentrant=False,
|
839 |
+
)
|
840 |
+
|
841 |
+
hidden_states = torch.cat([hidden_states_video, hidden_states_image], dim=1)
|
842 |
+
hidden_states = rearrange(hidden_states, '(b t) f d -> (b f) t d', b=input_batch_size).contiguous()
|
843 |
+
|
844 |
+
else:
|
845 |
+
if i == 0:
|
846 |
+
hidden_states = hidden_states + self.temp_pos_embed
|
847 |
+
|
848 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
849 |
+
temp_block,
|
850 |
+
hidden_states,
|
851 |
+
None, # attention_mask
|
852 |
+
None, # encoder_hidden_states
|
853 |
+
None, # encoder_attention_mask
|
854 |
+
timestep_temp,
|
855 |
+
cross_attention_kwargs,
|
856 |
+
class_labels,
|
857 |
+
use_reentrant=False,
|
858 |
+
)
|
859 |
+
|
860 |
+
hidden_states = rearrange(hidden_states, '(b t) f d -> (b f) t d', b=input_batch_size).contiguous()
|
861 |
+
else:
|
862 |
+
hidden_states = spatial_block(
|
863 |
+
hidden_states,
|
864 |
+
attention_mask,
|
865 |
+
encoder_hidden_states_spatial,
|
866 |
+
encoder_attention_mask,
|
867 |
+
timestep_spatial,
|
868 |
+
cross_attention_kwargs,
|
869 |
+
class_labels,
|
870 |
+
)
|
871 |
+
|
872 |
+
if enable_temporal_attentions:
|
873 |
+
|
874 |
+
hidden_states = rearrange(hidden_states, '(b f) t d -> (b t) f d', b=input_batch_size).contiguous()
|
875 |
+
|
876 |
+
if use_image_num != 0 and self.training:
|
877 |
+
hidden_states_video = hidden_states[:, :frame, ...]
|
878 |
+
hidden_states_image = hidden_states[:, frame:, ...]
|
879 |
+
|
880 |
+
hidden_states_video = temp_block(
|
881 |
+
hidden_states_video,
|
882 |
+
None, # attention_mask
|
883 |
+
None, # encoder_hidden_states
|
884 |
+
None, # encoder_attention_mask
|
885 |
+
timestep_temp,
|
886 |
+
cross_attention_kwargs,
|
887 |
+
class_labels,
|
888 |
+
)
|
889 |
+
|
890 |
+
hidden_states = torch.cat([hidden_states_video, hidden_states_image], dim=1)
|
891 |
+
hidden_states = rearrange(hidden_states, '(b t) f d -> (b f) t d', b=input_batch_size).contiguous()
|
892 |
+
|
893 |
+
else:
|
894 |
+
if i == 0:
|
895 |
+
hidden_states = hidden_states + self.temp_pos_embed
|
896 |
+
|
897 |
+
hidden_states = temp_block(
|
898 |
+
hidden_states,
|
899 |
+
None, # attention_mask
|
900 |
+
None, # encoder_hidden_states
|
901 |
+
None, # encoder_attention_mask
|
902 |
+
timestep_temp,
|
903 |
+
cross_attention_kwargs,
|
904 |
+
class_labels,
|
905 |
+
)
|
906 |
+
|
907 |
+
hidden_states = rearrange(hidden_states, '(b t) f d -> (b f) t d', b=input_batch_size).contiguous()
|
908 |
+
|
909 |
+
|
910 |
+
if self.is_input_patches:
|
911 |
+
if self.config.norm_type != "ada_norm_single":
|
912 |
+
conditioning = self.transformer_blocks[0].norm1.emb(
|
913 |
+
timestep, class_labels, hidden_dtype=hidden_states.dtype
|
914 |
+
)
|
915 |
+
shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
|
916 |
+
hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
|
917 |
+
hidden_states = self.proj_out_2(hidden_states)
|
918 |
+
elif self.config.norm_type == "ada_norm_single":
|
919 |
+
embedded_timestep = repeat(embedded_timestep, 'b d -> (b f) d', f=frame + use_image_num).contiguous()
|
920 |
+
shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
|
921 |
+
hidden_states = self.norm_out(hidden_states)
|
922 |
+
# Modulation
|
923 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
924 |
+
hidden_states = self.proj_out(hidden_states)
|
925 |
+
|
926 |
+
# unpatchify
|
927 |
+
if self.adaln_single is None:
|
928 |
+
height = width = int(hidden_states.shape[1] ** 0.5)
|
929 |
+
hidden_states = hidden_states.reshape(
|
930 |
+
shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
|
931 |
+
)
|
932 |
+
hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
|
933 |
+
output = hidden_states.reshape(
|
934 |
+
shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
|
935 |
+
)
|
936 |
+
output = rearrange(output, '(b f) c h w -> b c f h w', b=input_batch_size).contiguous()
|
937 |
+
|
938 |
+
if not return_dict:
|
939 |
+
return (output,)
|
940 |
+
|
941 |
+
return Transformer3DModelOutput(sample=output)
|
942 |
+
|
943 |
+
def get_1d_sincos_temp_embed(self, embed_dim, length):
|
944 |
+
pos = torch.arange(0, length).unsqueeze(1)
|
945 |
+
return get_1d_sincos_pos_embed_from_grid(embed_dim, pos)
|
946 |
+
|
947 |
+
@classmethod
|
948 |
+
def from_pretrained_2d(cls, pretrained_model_path, subfolder=None, **kwargs):
|
949 |
+
if subfolder is not None:
|
950 |
+
pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
|
951 |
+
|
952 |
+
|
953 |
+
config_file = os.path.join(pretrained_model_path, 'config.json')
|
954 |
+
if not os.path.isfile(config_file):
|
955 |
+
raise RuntimeError(f"{config_file} does not exist")
|
956 |
+
with open(config_file, "r") as f:
|
957 |
+
config = json.load(f)
|
958 |
+
|
959 |
+
model = cls.from_config(config, **kwargs)
|
960 |
+
|
961 |
+
# model_files = [
|
962 |
+
# os.path.join(pretrained_model_path, 'diffusion_pytorch_model.bin'),
|
963 |
+
# os.path.join(pretrained_model_path, 'diffusion_pytorch_model.safetensors')
|
964 |
+
# ]
|
965 |
+
|
966 |
+
# model_file = None
|
967 |
+
|
968 |
+
# for fp in model_files:
|
969 |
+
# if os.path.exists(fp):
|
970 |
+
# model_file = fp
|
971 |
+
|
972 |
+
# if not model_file:
|
973 |
+
# raise RuntimeError(f"{model_file} does not exist")
|
974 |
+
|
975 |
+
# if model_file.split(".")[-1] == "safetensors":
|
976 |
+
# from safetensors import safe_open
|
977 |
+
# state_dict = {}
|
978 |
+
# with safe_open(model_file, framework="pt", device="cpu") as f:
|
979 |
+
# for key in f.keys():
|
980 |
+
# state_dict[key] = f.get_tensor(key)
|
981 |
+
# else:
|
982 |
+
# state_dict = torch.load(model_file, map_location="cpu")
|
983 |
+
|
984 |
+
# for k, v in model.state_dict().items():
|
985 |
+
# if 'temporal_transformer_blocks' in k:
|
986 |
+
# state_dict.update({k: v})
|
987 |
+
|
988 |
+
# model.load_state_dict(state_dict)
|
989 |
+
|
990 |
+
return model
|
models/unet/__pycache__/motion_embeddings.cpython-310.pyc
ADDED
Binary file (7.4 kB). View file
|
|
models/unet/__pycache__/unet_3d_blocks.cpython-310.pyc
ADDED
Binary file (12.9 kB). View file
|
|
models/unet/__pycache__/unet_3d_condition.cpython-310.pyc
ADDED
Binary file (13.9 kB). View file
|
|
models/unet/motion_embeddings.py
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import numpy as np
|
6 |
+
class MotionEmbedding(nn.Module):
|
7 |
+
|
8 |
+
def __init__(self, embed_dim: int = None, max_seq_length: int = 32, wh: int = 1):
|
9 |
+
super().__init__()
|
10 |
+
self.embed = nn.Parameter(torch.zeros(wh, max_seq_length, embed_dim))
|
11 |
+
print('register spatial motion embedding with', wh)
|
12 |
+
|
13 |
+
self.scale = 1.0
|
14 |
+
self.trained_length = -1
|
15 |
+
|
16 |
+
def set_scale(self, scale: float):
|
17 |
+
self.scale = scale
|
18 |
+
|
19 |
+
def set_lengths(self, trained_length: int):
|
20 |
+
if trained_length > self.embed.shape[1] or trained_length <= 0:
|
21 |
+
raise ValueError("Trained length is out of bounds")
|
22 |
+
self.trained_length = trained_length
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
_, seq_length, _ = x.shape # seq_length here is the target sequence length for x
|
26 |
+
# print('seq_length',seq_length)
|
27 |
+
# Assuming self.embed is [batch, frames, dim]
|
28 |
+
embeddings = self.embed[:, :seq_length] # Initial slice, may not be necessary depending on the interpolation logic
|
29 |
+
|
30 |
+
# Check if interpolation is needed
|
31 |
+
if self.trained_length != -1 and seq_length != self.trained_length:
|
32 |
+
# Interpolate embeddings to match x's sequence length
|
33 |
+
# Ensure embeddings is [batch, dim, frames] for 1D interpolation across frames
|
34 |
+
embeddings = embeddings.permute(0, 2, 1) # Now [batch, dim, frames]
|
35 |
+
embeddings = F.interpolate(embeddings, size=(seq_length,), mode='linear', align_corners=False)
|
36 |
+
embeddings = embeddings.permute(0, 2, 1) # Revert to [batch, frames, dim]
|
37 |
+
|
38 |
+
# Ensure the interpolated embeddings match the sequence length of x
|
39 |
+
if embeddings.shape[1] != seq_length:
|
40 |
+
raise ValueError(f"Interpolated embeddings sequence length {embeddings.shape[1]} does not match x's sequence length {seq_length}")
|
41 |
+
|
42 |
+
if x.shape[0] != embeddings.shape[0]:
|
43 |
+
x = x + embeddings.repeat(x.shape[0]//embeddings.shape[0],1,1) * self.scale
|
44 |
+
else:
|
45 |
+
# Now embeddings should have the shape [batch, seq_length, dim] matching x
|
46 |
+
x = x + embeddings * self.scale # Assuming broadcasting is desired over the batch and dim dimensions
|
47 |
+
|
48 |
+
return x
|
49 |
+
|
50 |
+
|
51 |
+
def forward_average(self, x):
|
52 |
+
_, seq_length, _ = x.shape # seq_length here is the target sequence length for x
|
53 |
+
# print('seq_length',seq_length)
|
54 |
+
# Assuming self.embed is [batch, frames, dim]
|
55 |
+
embeddings = self.embed[:, :seq_length] # Initial slice, may not be necessary depending on the interpolation logic
|
56 |
+
|
57 |
+
# Check if interpolation is needed
|
58 |
+
if self.trained_length != -1 and seq_length != self.trained_length:
|
59 |
+
# Interpolate embeddings to match x's sequence length
|
60 |
+
# Ensure embeddings is [batch, dim, frames] for 1D interpolation across frames
|
61 |
+
embeddings = embeddings.permute(0, 2, 1) # Now [batch, dim, frames]
|
62 |
+
embeddings = F.interpolate(embeddings, size=(seq_length,), mode='linear', align_corners=False)
|
63 |
+
embeddings = embeddings.permute(0, 2, 1) # Revert to [batch, frames, dim]
|
64 |
+
|
65 |
+
# Ensure the interpolated embeddings match the sequence length of x
|
66 |
+
if embeddings.shape[1] != seq_length:
|
67 |
+
raise ValueError(f"Interpolated embeddings sequence length {embeddings.shape[1]} does not match x's sequence length {seq_length}")
|
68 |
+
|
69 |
+
embeddings_mean = embeddings.mean(dim=1, keepdim=True)
|
70 |
+
embeddings = embeddings - embeddings_mean
|
71 |
+
if x.shape[0] != embeddings.shape[0]:
|
72 |
+
x = x + embeddings.repeat(x.shape[0]//embeddings.shape[0],1,1) * self.scale
|
73 |
+
else:
|
74 |
+
# Now embeddings should have the shape [batch, seq_length, dim] matching x
|
75 |
+
x = x + embeddings * self.scale # Assuming broadcasting is desired over the batch and dim dimensions
|
76 |
+
|
77 |
+
return x
|
78 |
+
|
79 |
+
def forward_frameSubtraction(self, x):
|
80 |
+
_, seq_length, _ = x.shape # seq_length here is the target sequence length for x
|
81 |
+
# print('seq_length',seq_length)
|
82 |
+
# Assuming self.embed is [batch, frames, dim]
|
83 |
+
embeddings = self.embed[:, :seq_length] # Initial slice, may not be necessary depending on the interpolation logic
|
84 |
+
|
85 |
+
# Check if interpolation is needed
|
86 |
+
if self.trained_length != -1 and seq_length != self.trained_length:
|
87 |
+
# Interpolate embeddings to match x's sequence length
|
88 |
+
# Ensure embeddings is [batch, dim, frames] for 1D interpolation across frames
|
89 |
+
embeddings = embeddings.permute(0, 2, 1) # Now [batch, dim, frames]
|
90 |
+
embeddings = F.interpolate(embeddings, size=(seq_length,), mode='linear', align_corners=False)
|
91 |
+
embeddings = embeddings.permute(0, 2, 1) # Revert to [batch, frames, dim]
|
92 |
+
|
93 |
+
# Ensure the interpolated embeddings match the sequence length of x
|
94 |
+
if embeddings.shape[1] != seq_length:
|
95 |
+
raise ValueError(f"Interpolated embeddings sequence length {embeddings.shape[1]} does not match x's sequence length {seq_length}")
|
96 |
+
|
97 |
+
embeddings_subtraction = embeddings[:,1:] - embeddings[:,:-1]
|
98 |
+
|
99 |
+
embeddings = embeddings.clone().detach()
|
100 |
+
embeddings[:,1:] = embeddings_subtraction
|
101 |
+
|
102 |
+
# first frame minus mean
|
103 |
+
# embeddings[:,0:1] = embeddings[:,0:1] - embeddings.mean(dim=1, keepdim=True)
|
104 |
+
|
105 |
+
if x.shape[0] != embeddings.shape[0]:
|
106 |
+
x = x + embeddings.repeat(x.shape[0]//embeddings.shape[0],1,1) * self.scale
|
107 |
+
else:
|
108 |
+
# Now embeddings should have the shape [batch, seq_length, dim] matching x
|
109 |
+
x = x + embeddings * self.scale # Assuming broadcasting is desired over the batch and dim dimensions
|
110 |
+
|
111 |
+
return x
|
112 |
+
|
113 |
+
class MotionEmbeddingSpatial(nn.Module):
|
114 |
+
|
115 |
+
def __init__(self, h: int = None, w: int = None, embed_dim: int = None, max_seq_length: int = 32):
|
116 |
+
super().__init__()
|
117 |
+
self.embed = nn.Parameter(torch.zeros(h*w, max_seq_length, embed_dim))
|
118 |
+
self.scale = 1.0
|
119 |
+
self.trained_length = -1
|
120 |
+
|
121 |
+
def set_scale(self, scale: float):
|
122 |
+
self.scale = scale
|
123 |
+
|
124 |
+
def set_lengths(self, trained_length: int):
|
125 |
+
if trained_length > self.embed.shape[1] or trained_length <= 0:
|
126 |
+
raise ValueError("Trained length is out of bounds")
|
127 |
+
self.trained_length = trained_length
|
128 |
+
|
129 |
+
def forward(self, x):
|
130 |
+
_, seq_length, _ = x.shape # seq_length here is the target sequence length for x
|
131 |
+
|
132 |
+
# Assuming self.embed is [batch, frames, dim]
|
133 |
+
embeddings = self.embed[:, :seq_length] # Initial slice, may not be necessary depending on the interpolation logic
|
134 |
+
|
135 |
+
# Check if interpolation is needed
|
136 |
+
if self.trained_length != -1 and seq_length != self.trained_length:
|
137 |
+
# Interpolate embeddings to match x's sequence length
|
138 |
+
# Ensure embeddings is [batch, dim, frames] for 1D interpolation across frames
|
139 |
+
embeddings = embeddings.permute(0, 2, 1) # Now [batch, dim, frames]
|
140 |
+
embeddings = F.interpolate(embeddings, size=(seq_length,), mode='linear', align_corners=False)
|
141 |
+
embeddings = embeddings.permute(0, 2, 1) # Revert to [batch, frames, dim]
|
142 |
+
|
143 |
+
# Ensure the interpolated embeddings match the sequence length of x
|
144 |
+
if embeddings.shape[1] != seq_length:
|
145 |
+
raise ValueError(f"Interpolated embeddings sequence length {embeddings.shape[1]} does not match x's sequence length {seq_length}")
|
146 |
+
|
147 |
+
if x.shape[0] != embeddings.shape[0]:
|
148 |
+
x = x + embeddings.repeat(x.shape[0]//embeddings.shape[0],1,1) * self.scale
|
149 |
+
else:
|
150 |
+
# Now embeddings should have the shape [batch, seq_length, dim] matching x
|
151 |
+
x = x + embeddings * self.scale # Assuming broadcasting is desired over the batch and dim dimensions
|
152 |
+
|
153 |
+
return x
|
154 |
+
|
155 |
+
|
156 |
+
def inject_motion_embeddings(model, combinations=None, config=None):
|
157 |
+
spatial_shape=np.array([config.dataset.height,config.dataset.width])
|
158 |
+
shape32 = np.ceil(spatial_shape/32).astype(int)
|
159 |
+
shape16 = np.ceil(spatial_shape/16).astype(int)
|
160 |
+
spatial_name = 'vSpatial'
|
161 |
+
replacement_dict = {}
|
162 |
+
# support for 32 frames
|
163 |
+
max_seq_length = 32
|
164 |
+
inject_layers = []
|
165 |
+
for name, module in model.named_modules():
|
166 |
+
|
167 |
+
# check if the module is temp_attention
|
168 |
+
PETemporal = '.temp_attentions.' in name
|
169 |
+
|
170 |
+
if not(PETemporal and re.search(r'transformer_blocks\.\d+$', name)):
|
171 |
+
continue
|
172 |
+
|
173 |
+
if not ([name.split('_')[0], module.norm1.normalized_shape[0]] in combinations):
|
174 |
+
continue
|
175 |
+
|
176 |
+
replacement_dict[f'{name}.pos_embed'] = MotionEmbedding(max_seq_length=max_seq_length, embed_dim=module.norm1.normalized_shape[0]).to(dtype=model.dtype, device=model.device)
|
177 |
+
|
178 |
+
replacement_keys = list(set(replacement_dict.keys()))
|
179 |
+
temp_attn_list = [name.replace('pos_embed','attn1') for name in replacement_keys] + \
|
180 |
+
[name.replace('pos_embed','attn2') for name in replacement_keys]
|
181 |
+
embed_dims = [replacement_dict[replacement_keys[i]].embed.shape[2] for i in range(len(replacement_keys))]
|
182 |
+
|
183 |
+
for temp_attn_index,temp_attn in enumerate(temp_attn_list):
|
184 |
+
place_in_net = temp_attn.split('_')[0]
|
185 |
+
pattern = r'(\d+)\.temp_attentions'
|
186 |
+
match = re.search(pattern, temp_attn)
|
187 |
+
place_in_net = temp_attn.split('_')[0]
|
188 |
+
index_in_net = match.group(1)
|
189 |
+
h,w = None,None
|
190 |
+
if place_in_net == 'up':
|
191 |
+
if index_in_net == "1":
|
192 |
+
h, w = shape32
|
193 |
+
elif index_in_net == "2":
|
194 |
+
h, w = shape16
|
195 |
+
elif place_in_net == 'down':
|
196 |
+
if index_in_net == "1":
|
197 |
+
h, w = shape16
|
198 |
+
elif index_in_net == "2":
|
199 |
+
h, w = shape32
|
200 |
+
|
201 |
+
replacement_dict[temp_attn+'.'+spatial_name] = \
|
202 |
+
MotionEmbedding(
|
203 |
+
wh=h*w,
|
204 |
+
embed_dim=embed_dims[temp_attn_index%len(replacement_keys)]
|
205 |
+
).to(dtype=model.dtype, device=model.device)
|
206 |
+
|
207 |
+
for name, new_module in replacement_dict.items():
|
208 |
+
parent_name = name.rsplit('.', 1)[0] if '.' in name else ''
|
209 |
+
module_name = name.rsplit('.', 1)[-1]
|
210 |
+
parent_module = model
|
211 |
+
if parent_name:
|
212 |
+
parent_module = dict(model.named_modules())[parent_name]
|
213 |
+
|
214 |
+
if [parent_name.split('_')[0], new_module.embed.shape[-1]] in combinations:
|
215 |
+
inject_layers.append(name)
|
216 |
+
setattr(parent_module, module_name, new_module)
|
217 |
+
|
218 |
+
inject_layers = list(set(inject_layers))
|
219 |
+
for name in inject_layers:
|
220 |
+
print(f"Injecting motion embedding at {name}")
|
221 |
+
|
222 |
+
parameters_list = []
|
223 |
+
for name, para in model.named_parameters():
|
224 |
+
if 'pos_embed' in name or spatial_name in name:
|
225 |
+
parameters_list.append(para)
|
226 |
+
para.requires_grad = True
|
227 |
+
else:
|
228 |
+
para.requires_grad = False
|
229 |
+
|
230 |
+
return parameters_list, inject_layers
|
231 |
+
|
232 |
+
def save_motion_embeddings(model, file_path):
|
233 |
+
# Extract motion embedding from all instances of MotionEmbedding
|
234 |
+
motion_embeddings = {
|
235 |
+
name: module.embed
|
236 |
+
for name, module in model.named_modules()
|
237 |
+
if isinstance(module, MotionEmbedding) or isinstance(module, MotionEmbeddingSpatial)
|
238 |
+
}
|
239 |
+
# Save the motion embeddings to the specified file path
|
240 |
+
torch.save(motion_embeddings, file_path)
|
241 |
+
|
242 |
+
def load_motion_embeddings(model, saved_embeddings):
|
243 |
+
for key, embedding in saved_embeddings.items():
|
244 |
+
# Extract parent module and module name from the key
|
245 |
+
parent_name = key.rsplit('.', 1)[0] if '.' in key else ''
|
246 |
+
module_name = key.rsplit('.', 1)[-1]
|
247 |
+
|
248 |
+
# Retrieve the parent module
|
249 |
+
parent_module = model
|
250 |
+
if parent_name:
|
251 |
+
parent_module = dict(model.named_modules())[parent_name]
|
252 |
+
|
253 |
+
# Create a new MotionEmbedding instance with the correct dimensions
|
254 |
+
|
255 |
+
new_module = MotionEmbedding(wh = embedding.shape[0],embed_dim=embedding.shape[-1], max_seq_length=embedding.shape[-2])
|
256 |
+
|
257 |
+
# Properly assign the loaded embeddings to the 'embed' parameter wrapped in nn.Parameter
|
258 |
+
# Ensure the embedding is on the correct device and has the correct dtype
|
259 |
+
new_module.embed = nn.Parameter(embedding.to(dtype=model.dtype, device=model.device))
|
260 |
+
|
261 |
+
# Replace the corresponding module in the model with the new MotionEmbedding instance
|
262 |
+
setattr(parent_module, module_name, new_module)
|
263 |
+
|
264 |
+
def set_motion_embedding_scale(model, scale_value):
|
265 |
+
# Iterate over all modules in the model
|
266 |
+
for _, module in model.named_modules():
|
267 |
+
# Check if the module is an instance of MotionEmbedding
|
268 |
+
if isinstance(module, MotionEmbedding):
|
269 |
+
# Set the scale attribute to the specified value
|
270 |
+
module.scale = scale_value
|
271 |
+
|
272 |
+
def set_motion_embedding_length(model, trained_length):
|
273 |
+
# Iterate over all modules in the model
|
274 |
+
for _, module in model.named_modules():
|
275 |
+
# Check if the module is an instance of MotionEmbedding
|
276 |
+
if isinstance(module, MotionEmbedding):
|
277 |
+
# Set the length to the specified value
|
278 |
+
module.trained_length = trained_length
|
279 |
+
|
280 |
+
|
281 |
+
|
282 |
+
|
283 |
+
|
models/unet/unet_3d_blocks.py
ADDED
@@ -0,0 +1,842 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
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 |
+
import torch.utils.checkpoint as checkpoint
|
17 |
+
from torch import nn
|
18 |
+
from diffusers.models.resnet import Downsample2D, ResnetBlock2D, TemporalConvLayer, Upsample2D
|
19 |
+
from diffusers.models.transformer_2d import Transformer2DModel
|
20 |
+
from diffusers.models.transformer_temporal import TransformerTemporalModel
|
21 |
+
|
22 |
+
# Assign gradient checkpoint function to simple variable for readability.
|
23 |
+
g_c = checkpoint.checkpoint
|
24 |
+
|
25 |
+
def use_temporal(module, num_frames, x):
|
26 |
+
if num_frames == 1:
|
27 |
+
if isinstance(module, TransformerTemporalModel):
|
28 |
+
return {"sample": x}
|
29 |
+
else:
|
30 |
+
return x
|
31 |
+
|
32 |
+
def custom_checkpoint(module, mode=None):
|
33 |
+
if mode == None: raise ValueError('Mode for gradient checkpointing cannot be none.')
|
34 |
+
custom_forward = None
|
35 |
+
|
36 |
+
if mode == 'resnet':
|
37 |
+
def custom_forward(hidden_states, temb):
|
38 |
+
inputs = module(hidden_states, temb)
|
39 |
+
return inputs
|
40 |
+
|
41 |
+
if mode == 'attn':
|
42 |
+
def custom_forward(
|
43 |
+
hidden_states,
|
44 |
+
encoder_hidden_states=None,
|
45 |
+
cross_attention_kwargs=None
|
46 |
+
):
|
47 |
+
inputs = module(
|
48 |
+
hidden_states,
|
49 |
+
encoder_hidden_states,
|
50 |
+
cross_attention_kwargs
|
51 |
+
)
|
52 |
+
return inputs
|
53 |
+
|
54 |
+
if mode == 'temp':
|
55 |
+
def custom_forward(hidden_states, num_frames=None):
|
56 |
+
inputs = use_temporal(module, num_frames, hidden_states)
|
57 |
+
if inputs is None: inputs = module(
|
58 |
+
hidden_states,
|
59 |
+
num_frames=num_frames
|
60 |
+
)
|
61 |
+
return inputs
|
62 |
+
|
63 |
+
return custom_forward
|
64 |
+
|
65 |
+
def transformer_g_c(transformer, sample, num_frames):
|
66 |
+
sample = g_c(custom_checkpoint(transformer, mode='temp'),
|
67 |
+
sample, num_frames, use_reentrant=False
|
68 |
+
)['sample']
|
69 |
+
|
70 |
+
return sample
|
71 |
+
|
72 |
+
def cross_attn_g_c(
|
73 |
+
attn,
|
74 |
+
temp_attn,
|
75 |
+
resnet,
|
76 |
+
temp_conv,
|
77 |
+
hidden_states,
|
78 |
+
encoder_hidden_states,
|
79 |
+
cross_attention_kwargs,
|
80 |
+
temb,
|
81 |
+
num_frames,
|
82 |
+
inverse_temp=False
|
83 |
+
):
|
84 |
+
|
85 |
+
def ordered_g_c(idx):
|
86 |
+
|
87 |
+
# Self and CrossAttention
|
88 |
+
if idx == 0: return g_c(custom_checkpoint(attn, mode='attn'),
|
89 |
+
hidden_states, encoder_hidden_states,cross_attention_kwargs, use_reentrant=False
|
90 |
+
)['sample']
|
91 |
+
|
92 |
+
# Temporal Self and CrossAttention
|
93 |
+
if idx == 1: return g_c(custom_checkpoint(temp_attn, mode='temp'),
|
94 |
+
hidden_states, num_frames, use_reentrant=False)['sample']
|
95 |
+
|
96 |
+
# Resnets
|
97 |
+
if idx == 2: return g_c(custom_checkpoint(resnet, mode='resnet'),
|
98 |
+
hidden_states, temb, use_reentrant=False)
|
99 |
+
|
100 |
+
# Temporal Convolutions
|
101 |
+
if idx == 3: return g_c(custom_checkpoint(temp_conv, mode='temp'),
|
102 |
+
hidden_states, num_frames, use_reentrant=False
|
103 |
+
)
|
104 |
+
|
105 |
+
# Here we call the function depending on the order in which they are called.
|
106 |
+
# For some layers, the orders are different, so we access the appropriate one by index.
|
107 |
+
|
108 |
+
if not inverse_temp:
|
109 |
+
for idx in [0,1,2,3]: hidden_states = ordered_g_c(idx)
|
110 |
+
else:
|
111 |
+
for idx in [2,3,0,1]: hidden_states = ordered_g_c(idx)
|
112 |
+
|
113 |
+
return hidden_states
|
114 |
+
|
115 |
+
def up_down_g_c(resnet, temp_conv, hidden_states, temb, num_frames):
|
116 |
+
hidden_states = g_c(custom_checkpoint(resnet, mode='resnet'), hidden_states, temb, use_reentrant=False)
|
117 |
+
hidden_states = g_c(custom_checkpoint(temp_conv, mode='temp'),
|
118 |
+
hidden_states, num_frames, use_reentrant=False
|
119 |
+
)
|
120 |
+
return hidden_states
|
121 |
+
|
122 |
+
def get_down_block(
|
123 |
+
down_block_type,
|
124 |
+
num_layers,
|
125 |
+
in_channels,
|
126 |
+
out_channels,
|
127 |
+
temb_channels,
|
128 |
+
add_downsample,
|
129 |
+
resnet_eps,
|
130 |
+
resnet_act_fn,
|
131 |
+
attn_num_head_channels,
|
132 |
+
resnet_groups=None,
|
133 |
+
cross_attention_dim=None,
|
134 |
+
downsample_padding=None,
|
135 |
+
dual_cross_attention=False,
|
136 |
+
use_linear_projection=True,
|
137 |
+
only_cross_attention=False,
|
138 |
+
upcast_attention=False,
|
139 |
+
resnet_time_scale_shift="default",
|
140 |
+
):
|
141 |
+
if down_block_type == "DownBlock3D":
|
142 |
+
return DownBlock3D(
|
143 |
+
num_layers=num_layers,
|
144 |
+
in_channels=in_channels,
|
145 |
+
out_channels=out_channels,
|
146 |
+
temb_channels=temb_channels,
|
147 |
+
add_downsample=add_downsample,
|
148 |
+
resnet_eps=resnet_eps,
|
149 |
+
resnet_act_fn=resnet_act_fn,
|
150 |
+
resnet_groups=resnet_groups,
|
151 |
+
downsample_padding=downsample_padding,
|
152 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
153 |
+
)
|
154 |
+
elif down_block_type == "CrossAttnDownBlock3D":
|
155 |
+
if cross_attention_dim is None:
|
156 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
|
157 |
+
return CrossAttnDownBlock3D(
|
158 |
+
num_layers=num_layers,
|
159 |
+
in_channels=in_channels,
|
160 |
+
out_channels=out_channels,
|
161 |
+
temb_channels=temb_channels,
|
162 |
+
add_downsample=add_downsample,
|
163 |
+
resnet_eps=resnet_eps,
|
164 |
+
resnet_act_fn=resnet_act_fn,
|
165 |
+
resnet_groups=resnet_groups,
|
166 |
+
downsample_padding=downsample_padding,
|
167 |
+
cross_attention_dim=cross_attention_dim,
|
168 |
+
attn_num_head_channels=attn_num_head_channels,
|
169 |
+
dual_cross_attention=dual_cross_attention,
|
170 |
+
use_linear_projection=use_linear_projection,
|
171 |
+
only_cross_attention=only_cross_attention,
|
172 |
+
upcast_attention=upcast_attention,
|
173 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
174 |
+
)
|
175 |
+
raise ValueError(f"{down_block_type} does not exist.")
|
176 |
+
|
177 |
+
|
178 |
+
def get_up_block(
|
179 |
+
up_block_type,
|
180 |
+
num_layers,
|
181 |
+
in_channels,
|
182 |
+
out_channels,
|
183 |
+
prev_output_channel,
|
184 |
+
temb_channels,
|
185 |
+
add_upsample,
|
186 |
+
resnet_eps,
|
187 |
+
resnet_act_fn,
|
188 |
+
attn_num_head_channels,
|
189 |
+
resnet_groups=None,
|
190 |
+
cross_attention_dim=None,
|
191 |
+
dual_cross_attention=False,
|
192 |
+
use_linear_projection=True,
|
193 |
+
only_cross_attention=False,
|
194 |
+
upcast_attention=False,
|
195 |
+
resnet_time_scale_shift="default",
|
196 |
+
):
|
197 |
+
if up_block_type == "UpBlock3D":
|
198 |
+
return UpBlock3D(
|
199 |
+
num_layers=num_layers,
|
200 |
+
in_channels=in_channels,
|
201 |
+
out_channels=out_channels,
|
202 |
+
prev_output_channel=prev_output_channel,
|
203 |
+
temb_channels=temb_channels,
|
204 |
+
add_upsample=add_upsample,
|
205 |
+
resnet_eps=resnet_eps,
|
206 |
+
resnet_act_fn=resnet_act_fn,
|
207 |
+
resnet_groups=resnet_groups,
|
208 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
209 |
+
)
|
210 |
+
elif up_block_type == "CrossAttnUpBlock3D":
|
211 |
+
if cross_attention_dim is None:
|
212 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
|
213 |
+
return CrossAttnUpBlock3D(
|
214 |
+
num_layers=num_layers,
|
215 |
+
in_channels=in_channels,
|
216 |
+
out_channels=out_channels,
|
217 |
+
prev_output_channel=prev_output_channel,
|
218 |
+
temb_channels=temb_channels,
|
219 |
+
add_upsample=add_upsample,
|
220 |
+
resnet_eps=resnet_eps,
|
221 |
+
resnet_act_fn=resnet_act_fn,
|
222 |
+
resnet_groups=resnet_groups,
|
223 |
+
cross_attention_dim=cross_attention_dim,
|
224 |
+
attn_num_head_channels=attn_num_head_channels,
|
225 |
+
dual_cross_attention=dual_cross_attention,
|
226 |
+
use_linear_projection=use_linear_projection,
|
227 |
+
only_cross_attention=only_cross_attention,
|
228 |
+
upcast_attention=upcast_attention,
|
229 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
230 |
+
)
|
231 |
+
raise ValueError(f"{up_block_type} does not exist.")
|
232 |
+
|
233 |
+
|
234 |
+
class UNetMidBlock3DCrossAttn(nn.Module):
|
235 |
+
def __init__(
|
236 |
+
self,
|
237 |
+
in_channels: int,
|
238 |
+
temb_channels: int,
|
239 |
+
dropout: float = 0.0,
|
240 |
+
num_layers: int = 1,
|
241 |
+
resnet_eps: float = 1e-6,
|
242 |
+
resnet_time_scale_shift: str = "default",
|
243 |
+
resnet_act_fn: str = "swish",
|
244 |
+
resnet_groups: int = 32,
|
245 |
+
resnet_pre_norm: bool = True,
|
246 |
+
attn_num_head_channels=1,
|
247 |
+
output_scale_factor=1.0,
|
248 |
+
cross_attention_dim=1280,
|
249 |
+
dual_cross_attention=False,
|
250 |
+
use_linear_projection=True,
|
251 |
+
upcast_attention=False,
|
252 |
+
):
|
253 |
+
super().__init__()
|
254 |
+
|
255 |
+
self.gradient_checkpointing = False
|
256 |
+
self.has_cross_attention = True
|
257 |
+
self.attn_num_head_channels = attn_num_head_channels
|
258 |
+
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
|
259 |
+
|
260 |
+
# there is always at least one resnet
|
261 |
+
resnets = [
|
262 |
+
ResnetBlock2D(
|
263 |
+
in_channels=in_channels,
|
264 |
+
out_channels=in_channels,
|
265 |
+
temb_channels=temb_channels,
|
266 |
+
eps=resnet_eps,
|
267 |
+
groups=resnet_groups,
|
268 |
+
dropout=dropout,
|
269 |
+
time_embedding_norm=resnet_time_scale_shift,
|
270 |
+
non_linearity=resnet_act_fn,
|
271 |
+
output_scale_factor=output_scale_factor,
|
272 |
+
pre_norm=resnet_pre_norm,
|
273 |
+
)
|
274 |
+
]
|
275 |
+
temp_convs = [
|
276 |
+
TemporalConvLayer(
|
277 |
+
in_channels,
|
278 |
+
in_channels,
|
279 |
+
dropout=0.1
|
280 |
+
)
|
281 |
+
]
|
282 |
+
attentions = []
|
283 |
+
temp_attentions = []
|
284 |
+
|
285 |
+
for _ in range(num_layers):
|
286 |
+
attentions.append(
|
287 |
+
Transformer2DModel(
|
288 |
+
in_channels // attn_num_head_channels,
|
289 |
+
attn_num_head_channels,
|
290 |
+
in_channels=in_channels,
|
291 |
+
num_layers=1,
|
292 |
+
cross_attention_dim=cross_attention_dim,
|
293 |
+
norm_num_groups=resnet_groups,
|
294 |
+
use_linear_projection=use_linear_projection,
|
295 |
+
upcast_attention=upcast_attention,
|
296 |
+
)
|
297 |
+
)
|
298 |
+
temp_attentions.append(
|
299 |
+
TransformerTemporalModel(
|
300 |
+
in_channels // attn_num_head_channels,
|
301 |
+
attn_num_head_channels,
|
302 |
+
in_channels=in_channels,
|
303 |
+
num_layers=1,
|
304 |
+
cross_attention_dim=cross_attention_dim,
|
305 |
+
norm_num_groups=resnet_groups,
|
306 |
+
)
|
307 |
+
)
|
308 |
+
resnets.append(
|
309 |
+
ResnetBlock2D(
|
310 |
+
in_channels=in_channels,
|
311 |
+
out_channels=in_channels,
|
312 |
+
temb_channels=temb_channels,
|
313 |
+
eps=resnet_eps,
|
314 |
+
groups=resnet_groups,
|
315 |
+
dropout=dropout,
|
316 |
+
time_embedding_norm=resnet_time_scale_shift,
|
317 |
+
non_linearity=resnet_act_fn,
|
318 |
+
output_scale_factor=output_scale_factor,
|
319 |
+
pre_norm=resnet_pre_norm,
|
320 |
+
)
|
321 |
+
)
|
322 |
+
temp_convs.append(
|
323 |
+
TemporalConvLayer(
|
324 |
+
in_channels,
|
325 |
+
in_channels,
|
326 |
+
dropout=0.1
|
327 |
+
)
|
328 |
+
)
|
329 |
+
|
330 |
+
self.resnets = nn.ModuleList(resnets)
|
331 |
+
self.temp_convs = nn.ModuleList(temp_convs)
|
332 |
+
self.attentions = nn.ModuleList(attentions)
|
333 |
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
334 |
+
|
335 |
+
def forward(
|
336 |
+
self,
|
337 |
+
hidden_states,
|
338 |
+
temb=None,
|
339 |
+
encoder_hidden_states=None,
|
340 |
+
attention_mask=None,
|
341 |
+
num_frames=1,
|
342 |
+
cross_attention_kwargs=None,
|
343 |
+
):
|
344 |
+
if self.gradient_checkpointing:
|
345 |
+
hidden_states = up_down_g_c(
|
346 |
+
self.resnets[0],
|
347 |
+
self.temp_convs[0],
|
348 |
+
hidden_states,
|
349 |
+
temb,
|
350 |
+
num_frames
|
351 |
+
)
|
352 |
+
else:
|
353 |
+
hidden_states = self.resnets[0](hidden_states, temb)
|
354 |
+
hidden_states = self.temp_convs[0](hidden_states, num_frames=num_frames)
|
355 |
+
|
356 |
+
for attn, temp_attn, resnet, temp_conv in zip(
|
357 |
+
self.attentions, self.temp_attentions, self.resnets[1:], self.temp_convs[1:]
|
358 |
+
):
|
359 |
+
if self.gradient_checkpointing:
|
360 |
+
hidden_states = cross_attn_g_c(
|
361 |
+
attn,
|
362 |
+
temp_attn,
|
363 |
+
resnet,
|
364 |
+
temp_conv,
|
365 |
+
hidden_states,
|
366 |
+
encoder_hidden_states,
|
367 |
+
cross_attention_kwargs,
|
368 |
+
temb,
|
369 |
+
num_frames
|
370 |
+
)
|
371 |
+
else:
|
372 |
+
hidden_states = attn(
|
373 |
+
hidden_states,
|
374 |
+
encoder_hidden_states=encoder_hidden_states,
|
375 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
376 |
+
).sample
|
377 |
+
|
378 |
+
if num_frames > 1:
|
379 |
+
hidden_states = temp_attn(hidden_states, num_frames=num_frames).sample
|
380 |
+
|
381 |
+
hidden_states = resnet(hidden_states, temb)
|
382 |
+
|
383 |
+
if num_frames > 1:
|
384 |
+
hidden_states = temp_conv(hidden_states, num_frames=num_frames)
|
385 |
+
|
386 |
+
return hidden_states
|
387 |
+
|
388 |
+
|
389 |
+
class CrossAttnDownBlock3D(nn.Module):
|
390 |
+
def __init__(
|
391 |
+
self,
|
392 |
+
in_channels: int,
|
393 |
+
out_channels: int,
|
394 |
+
temb_channels: int,
|
395 |
+
dropout: float = 0.0,
|
396 |
+
num_layers: int = 1,
|
397 |
+
resnet_eps: float = 1e-6,
|
398 |
+
resnet_time_scale_shift: str = "default",
|
399 |
+
resnet_act_fn: str = "swish",
|
400 |
+
resnet_groups: int = 32,
|
401 |
+
resnet_pre_norm: bool = True,
|
402 |
+
attn_num_head_channels=1,
|
403 |
+
cross_attention_dim=1280,
|
404 |
+
output_scale_factor=1.0,
|
405 |
+
downsample_padding=1,
|
406 |
+
add_downsample=True,
|
407 |
+
dual_cross_attention=False,
|
408 |
+
use_linear_projection=False,
|
409 |
+
only_cross_attention=False,
|
410 |
+
upcast_attention=False,
|
411 |
+
):
|
412 |
+
super().__init__()
|
413 |
+
resnets = []
|
414 |
+
attentions = []
|
415 |
+
temp_attentions = []
|
416 |
+
temp_convs = []
|
417 |
+
|
418 |
+
self.gradient_checkpointing = False
|
419 |
+
self.has_cross_attention = True
|
420 |
+
self.attn_num_head_channels = attn_num_head_channels
|
421 |
+
|
422 |
+
for i in range(num_layers):
|
423 |
+
in_channels = in_channels if i == 0 else out_channels
|
424 |
+
resnets.append(
|
425 |
+
ResnetBlock2D(
|
426 |
+
in_channels=in_channels,
|
427 |
+
out_channels=out_channels,
|
428 |
+
temb_channels=temb_channels,
|
429 |
+
eps=resnet_eps,
|
430 |
+
groups=resnet_groups,
|
431 |
+
dropout=dropout,
|
432 |
+
time_embedding_norm=resnet_time_scale_shift,
|
433 |
+
non_linearity=resnet_act_fn,
|
434 |
+
output_scale_factor=output_scale_factor,
|
435 |
+
pre_norm=resnet_pre_norm,
|
436 |
+
)
|
437 |
+
)
|
438 |
+
temp_convs.append(
|
439 |
+
TemporalConvLayer(
|
440 |
+
out_channels,
|
441 |
+
out_channels,
|
442 |
+
dropout=0.1
|
443 |
+
)
|
444 |
+
)
|
445 |
+
attentions.append(
|
446 |
+
Transformer2DModel(
|
447 |
+
out_channels // attn_num_head_channels,
|
448 |
+
attn_num_head_channels,
|
449 |
+
in_channels=out_channels,
|
450 |
+
num_layers=1,
|
451 |
+
cross_attention_dim=cross_attention_dim,
|
452 |
+
norm_num_groups=resnet_groups,
|
453 |
+
use_linear_projection=use_linear_projection,
|
454 |
+
only_cross_attention=only_cross_attention,
|
455 |
+
upcast_attention=upcast_attention,
|
456 |
+
)
|
457 |
+
)
|
458 |
+
temp_attentions.append(
|
459 |
+
TransformerTemporalModel(
|
460 |
+
out_channels // attn_num_head_channels,
|
461 |
+
attn_num_head_channels,
|
462 |
+
in_channels=out_channels,
|
463 |
+
num_layers=1,
|
464 |
+
cross_attention_dim=cross_attention_dim,
|
465 |
+
norm_num_groups=resnet_groups,
|
466 |
+
)
|
467 |
+
)
|
468 |
+
self.resnets = nn.ModuleList(resnets)
|
469 |
+
self.temp_convs = nn.ModuleList(temp_convs)
|
470 |
+
self.attentions = nn.ModuleList(attentions)
|
471 |
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
472 |
+
|
473 |
+
if add_downsample:
|
474 |
+
self.downsamplers = nn.ModuleList(
|
475 |
+
[
|
476 |
+
Downsample2D(
|
477 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
478 |
+
)
|
479 |
+
]
|
480 |
+
)
|
481 |
+
else:
|
482 |
+
self.downsamplers = None
|
483 |
+
|
484 |
+
def forward(
|
485 |
+
self,
|
486 |
+
hidden_states,
|
487 |
+
temb=None,
|
488 |
+
encoder_hidden_states=None,
|
489 |
+
attention_mask=None,
|
490 |
+
num_frames=1,
|
491 |
+
cross_attention_kwargs=None,
|
492 |
+
):
|
493 |
+
# TODO(Patrick, William) - attention mask is not used
|
494 |
+
output_states = ()
|
495 |
+
|
496 |
+
for resnet, temp_conv, attn, temp_attn in zip(
|
497 |
+
self.resnets, self.temp_convs, self.attentions, self.temp_attentions
|
498 |
+
):
|
499 |
+
|
500 |
+
if self.gradient_checkpointing:
|
501 |
+
hidden_states = cross_attn_g_c(
|
502 |
+
attn,
|
503 |
+
temp_attn,
|
504 |
+
resnet,
|
505 |
+
temp_conv,
|
506 |
+
hidden_states,
|
507 |
+
encoder_hidden_states,
|
508 |
+
cross_attention_kwargs,
|
509 |
+
temb,
|
510 |
+
num_frames,
|
511 |
+
inverse_temp=True
|
512 |
+
)
|
513 |
+
else:
|
514 |
+
hidden_states = resnet(hidden_states, temb)
|
515 |
+
|
516 |
+
if num_frames > 1:
|
517 |
+
hidden_states = temp_conv(hidden_states, num_frames=num_frames)
|
518 |
+
|
519 |
+
hidden_states = attn(
|
520 |
+
hidden_states,
|
521 |
+
encoder_hidden_states=encoder_hidden_states,
|
522 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
523 |
+
).sample
|
524 |
+
|
525 |
+
if num_frames > 1:
|
526 |
+
hidden_states = temp_attn(hidden_states, num_frames=num_frames).sample
|
527 |
+
|
528 |
+
output_states += (hidden_states,)
|
529 |
+
|
530 |
+
if self.downsamplers is not None:
|
531 |
+
for downsampler in self.downsamplers:
|
532 |
+
hidden_states = downsampler(hidden_states)
|
533 |
+
|
534 |
+
output_states += (hidden_states,)
|
535 |
+
|
536 |
+
return hidden_states, output_states
|
537 |
+
|
538 |
+
|
539 |
+
class DownBlock3D(nn.Module):
|
540 |
+
def __init__(
|
541 |
+
self,
|
542 |
+
in_channels: int,
|
543 |
+
out_channels: int,
|
544 |
+
temb_channels: int,
|
545 |
+
dropout: float = 0.0,
|
546 |
+
num_layers: int = 1,
|
547 |
+
resnet_eps: float = 1e-6,
|
548 |
+
resnet_time_scale_shift: str = "default",
|
549 |
+
resnet_act_fn: str = "swish",
|
550 |
+
resnet_groups: int = 32,
|
551 |
+
resnet_pre_norm: bool = True,
|
552 |
+
output_scale_factor=1.0,
|
553 |
+
add_downsample=True,
|
554 |
+
downsample_padding=1,
|
555 |
+
):
|
556 |
+
super().__init__()
|
557 |
+
resnets = []
|
558 |
+
temp_convs = []
|
559 |
+
|
560 |
+
self.gradient_checkpointing = False
|
561 |
+
for i in range(num_layers):
|
562 |
+
in_channels = in_channels if i == 0 else out_channels
|
563 |
+
resnets.append(
|
564 |
+
ResnetBlock2D(
|
565 |
+
in_channels=in_channels,
|
566 |
+
out_channels=out_channels,
|
567 |
+
temb_channels=temb_channels,
|
568 |
+
eps=resnet_eps,
|
569 |
+
groups=resnet_groups,
|
570 |
+
dropout=dropout,
|
571 |
+
time_embedding_norm=resnet_time_scale_shift,
|
572 |
+
non_linearity=resnet_act_fn,
|
573 |
+
output_scale_factor=output_scale_factor,
|
574 |
+
pre_norm=resnet_pre_norm,
|
575 |
+
)
|
576 |
+
)
|
577 |
+
temp_convs.append(
|
578 |
+
TemporalConvLayer(
|
579 |
+
out_channels,
|
580 |
+
out_channels,
|
581 |
+
dropout=0.1
|
582 |
+
)
|
583 |
+
)
|
584 |
+
|
585 |
+
self.resnets = nn.ModuleList(resnets)
|
586 |
+
self.temp_convs = nn.ModuleList(temp_convs)
|
587 |
+
|
588 |
+
if add_downsample:
|
589 |
+
self.downsamplers = nn.ModuleList(
|
590 |
+
[
|
591 |
+
Downsample2D(
|
592 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
593 |
+
)
|
594 |
+
]
|
595 |
+
)
|
596 |
+
else:
|
597 |
+
self.downsamplers = None
|
598 |
+
|
599 |
+
def forward(self, hidden_states, temb=None, num_frames=1):
|
600 |
+
output_states = ()
|
601 |
+
|
602 |
+
for resnet, temp_conv in zip(self.resnets, self.temp_convs):
|
603 |
+
if self.gradient_checkpointing:
|
604 |
+
hidden_states = up_down_g_c(resnet, temp_conv, hidden_states, temb, num_frames)
|
605 |
+
else:
|
606 |
+
hidden_states = resnet(hidden_states, temb)
|
607 |
+
|
608 |
+
if num_frames > 1:
|
609 |
+
hidden_states = temp_conv(hidden_states, num_frames=num_frames)
|
610 |
+
|
611 |
+
output_states += (hidden_states,)
|
612 |
+
|
613 |
+
if self.downsamplers is not None:
|
614 |
+
for downsampler in self.downsamplers:
|
615 |
+
hidden_states = downsampler(hidden_states)
|
616 |
+
|
617 |
+
output_states += (hidden_states,)
|
618 |
+
|
619 |
+
return hidden_states, output_states
|
620 |
+
|
621 |
+
|
622 |
+
class CrossAttnUpBlock3D(nn.Module):
|
623 |
+
def __init__(
|
624 |
+
self,
|
625 |
+
in_channels: int,
|
626 |
+
out_channels: int,
|
627 |
+
prev_output_channel: int,
|
628 |
+
temb_channels: int,
|
629 |
+
dropout: float = 0.0,
|
630 |
+
num_layers: int = 1,
|
631 |
+
resnet_eps: float = 1e-6,
|
632 |
+
resnet_time_scale_shift: str = "default",
|
633 |
+
resnet_act_fn: str = "swish",
|
634 |
+
resnet_groups: int = 32,
|
635 |
+
resnet_pre_norm: bool = True,
|
636 |
+
attn_num_head_channels=1,
|
637 |
+
cross_attention_dim=1280,
|
638 |
+
output_scale_factor=1.0,
|
639 |
+
add_upsample=True,
|
640 |
+
dual_cross_attention=False,
|
641 |
+
use_linear_projection=False,
|
642 |
+
only_cross_attention=False,
|
643 |
+
upcast_attention=False,
|
644 |
+
):
|
645 |
+
super().__init__()
|
646 |
+
resnets = []
|
647 |
+
temp_convs = []
|
648 |
+
attentions = []
|
649 |
+
temp_attentions = []
|
650 |
+
|
651 |
+
self.gradient_checkpointing = False
|
652 |
+
self.has_cross_attention = True
|
653 |
+
self.attn_num_head_channels = attn_num_head_channels
|
654 |
+
|
655 |
+
for i in range(num_layers):
|
656 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
657 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
658 |
+
|
659 |
+
resnets.append(
|
660 |
+
ResnetBlock2D(
|
661 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
662 |
+
out_channels=out_channels,
|
663 |
+
temb_channels=temb_channels,
|
664 |
+
eps=resnet_eps,
|
665 |
+
groups=resnet_groups,
|
666 |
+
dropout=dropout,
|
667 |
+
time_embedding_norm=resnet_time_scale_shift,
|
668 |
+
non_linearity=resnet_act_fn,
|
669 |
+
output_scale_factor=output_scale_factor,
|
670 |
+
pre_norm=resnet_pre_norm,
|
671 |
+
)
|
672 |
+
)
|
673 |
+
temp_convs.append(
|
674 |
+
TemporalConvLayer(
|
675 |
+
out_channels,
|
676 |
+
out_channels,
|
677 |
+
dropout=0.1
|
678 |
+
)
|
679 |
+
)
|
680 |
+
attentions.append(
|
681 |
+
Transformer2DModel(
|
682 |
+
out_channels // attn_num_head_channels,
|
683 |
+
attn_num_head_channels,
|
684 |
+
in_channels=out_channels,
|
685 |
+
num_layers=1,
|
686 |
+
cross_attention_dim=cross_attention_dim,
|
687 |
+
norm_num_groups=resnet_groups,
|
688 |
+
use_linear_projection=use_linear_projection,
|
689 |
+
only_cross_attention=only_cross_attention,
|
690 |
+
upcast_attention=upcast_attention,
|
691 |
+
)
|
692 |
+
)
|
693 |
+
temp_attentions.append(
|
694 |
+
TransformerTemporalModel(
|
695 |
+
out_channels // attn_num_head_channels,
|
696 |
+
attn_num_head_channels,
|
697 |
+
in_channels=out_channels,
|
698 |
+
num_layers=1,
|
699 |
+
cross_attention_dim=cross_attention_dim,
|
700 |
+
norm_num_groups=resnet_groups,
|
701 |
+
)
|
702 |
+
)
|
703 |
+
self.resnets = nn.ModuleList(resnets)
|
704 |
+
self.temp_convs = nn.ModuleList(temp_convs)
|
705 |
+
self.attentions = nn.ModuleList(attentions)
|
706 |
+
self.temp_attentions = nn.ModuleList(temp_attentions)
|
707 |
+
|
708 |
+
if add_upsample:
|
709 |
+
self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
|
710 |
+
else:
|
711 |
+
self.upsamplers = None
|
712 |
+
|
713 |
+
def forward(
|
714 |
+
self,
|
715 |
+
hidden_states,
|
716 |
+
res_hidden_states_tuple,
|
717 |
+
temb=None,
|
718 |
+
encoder_hidden_states=None,
|
719 |
+
upsample_size=None,
|
720 |
+
attention_mask=None,
|
721 |
+
num_frames=1,
|
722 |
+
cross_attention_kwargs=None,
|
723 |
+
):
|
724 |
+
# TODO(Patrick, William) - attention mask is not used
|
725 |
+
for resnet, temp_conv, attn, temp_attn in zip(
|
726 |
+
self.resnets, self.temp_convs, self.attentions, self.temp_attentions
|
727 |
+
):
|
728 |
+
# pop res hidden states
|
729 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
730 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
731 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
732 |
+
|
733 |
+
if self.gradient_checkpointing:
|
734 |
+
hidden_states = cross_attn_g_c(
|
735 |
+
attn,
|
736 |
+
temp_attn,
|
737 |
+
resnet,
|
738 |
+
temp_conv,
|
739 |
+
hidden_states,
|
740 |
+
encoder_hidden_states,
|
741 |
+
cross_attention_kwargs,
|
742 |
+
temb,
|
743 |
+
num_frames,
|
744 |
+
inverse_temp=True
|
745 |
+
)
|
746 |
+
else:
|
747 |
+
hidden_states = resnet(hidden_states, temb)
|
748 |
+
|
749 |
+
if num_frames > 1:
|
750 |
+
hidden_states = temp_conv(hidden_states, num_frames=num_frames)
|
751 |
+
|
752 |
+
hidden_states = attn(
|
753 |
+
hidden_states,
|
754 |
+
encoder_hidden_states=encoder_hidden_states,
|
755 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
756 |
+
).sample
|
757 |
+
|
758 |
+
if num_frames > 1:
|
759 |
+
hidden_states = temp_attn(hidden_states, num_frames=num_frames).sample
|
760 |
+
|
761 |
+
if self.upsamplers is not None:
|
762 |
+
for upsampler in self.upsamplers:
|
763 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
764 |
+
|
765 |
+
return hidden_states
|
766 |
+
|
767 |
+
|
768 |
+
class UpBlock3D(nn.Module):
|
769 |
+
def __init__(
|
770 |
+
self,
|
771 |
+
in_channels: int,
|
772 |
+
prev_output_channel: int,
|
773 |
+
out_channels: int,
|
774 |
+
temb_channels: int,
|
775 |
+
dropout: float = 0.0,
|
776 |
+
num_layers: int = 1,
|
777 |
+
resnet_eps: float = 1e-6,
|
778 |
+
resnet_time_scale_shift: str = "default",
|
779 |
+
resnet_act_fn: str = "swish",
|
780 |
+
resnet_groups: int = 32,
|
781 |
+
resnet_pre_norm: bool = True,
|
782 |
+
output_scale_factor=1.0,
|
783 |
+
add_upsample=True,
|
784 |
+
):
|
785 |
+
super().__init__()
|
786 |
+
resnets = []
|
787 |
+
temp_convs = []
|
788 |
+
self.gradient_checkpointing = False
|
789 |
+
for i in range(num_layers):
|
790 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
791 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
792 |
+
|
793 |
+
resnets.append(
|
794 |
+
ResnetBlock2D(
|
795 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
796 |
+
out_channels=out_channels,
|
797 |
+
temb_channels=temb_channels,
|
798 |
+
eps=resnet_eps,
|
799 |
+
groups=resnet_groups,
|
800 |
+
dropout=dropout,
|
801 |
+
time_embedding_norm=resnet_time_scale_shift,
|
802 |
+
non_linearity=resnet_act_fn,
|
803 |
+
output_scale_factor=output_scale_factor,
|
804 |
+
pre_norm=resnet_pre_norm,
|
805 |
+
)
|
806 |
+
)
|
807 |
+
temp_convs.append(
|
808 |
+
TemporalConvLayer(
|
809 |
+
out_channels,
|
810 |
+
out_channels,
|
811 |
+
dropout=0.1
|
812 |
+
)
|
813 |
+
)
|
814 |
+
|
815 |
+
self.resnets = nn.ModuleList(resnets)
|
816 |
+
self.temp_convs = nn.ModuleList(temp_convs)
|
817 |
+
|
818 |
+
if add_upsample:
|
819 |
+
self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
|
820 |
+
else:
|
821 |
+
self.upsamplers = None
|
822 |
+
|
823 |
+
def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None, num_frames=1):
|
824 |
+
for resnet, temp_conv in zip(self.resnets, self.temp_convs):
|
825 |
+
# pop res hidden states
|
826 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
827 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
828 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
829 |
+
|
830 |
+
if self.gradient_checkpointing:
|
831 |
+
hidden_states = up_down_g_c(resnet, temp_conv, hidden_states, temb, num_frames)
|
832 |
+
else:
|
833 |
+
hidden_states = resnet(hidden_states, temb)
|
834 |
+
|
835 |
+
if num_frames > 1:
|
836 |
+
hidden_states = temp_conv(hidden_states, num_frames=num_frames)
|
837 |
+
|
838 |
+
if self.upsamplers is not None:
|
839 |
+
for upsampler in self.upsamplers:
|
840 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
841 |
+
|
842 |
+
return hidden_states
|
models/unet/unet_3d_condition.py
ADDED
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Alibaba DAMO-VILAB and The HuggingFace Team. All rights reserved.
|
2 |
+
# Copyright 2023 The ModelScope Team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
from dataclasses import dataclass
|
16 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
17 |
+
|
18 |
+
import torch
|
19 |
+
import torch.nn as nn
|
20 |
+
import torch.utils.checkpoint
|
21 |
+
|
22 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
23 |
+
from diffusers.utils import BaseOutput, logging
|
24 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
25 |
+
from diffusers.models.modeling_utils import ModelMixin
|
26 |
+
from diffusers.models.transformer_temporal import TransformerTemporalModel
|
27 |
+
from .unet_3d_blocks import (
|
28 |
+
CrossAttnDownBlock3D,
|
29 |
+
CrossAttnUpBlock3D,
|
30 |
+
DownBlock3D,
|
31 |
+
UNetMidBlock3DCrossAttn,
|
32 |
+
UpBlock3D,
|
33 |
+
get_down_block,
|
34 |
+
get_up_block,
|
35 |
+
transformer_g_c
|
36 |
+
)
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
40 |
+
|
41 |
+
|
42 |
+
@dataclass
|
43 |
+
class UNet3DConditionOutput(BaseOutput):
|
44 |
+
"""
|
45 |
+
Args:
|
46 |
+
sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
47 |
+
Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model.
|
48 |
+
"""
|
49 |
+
|
50 |
+
sample: torch.FloatTensor
|
51 |
+
|
52 |
+
|
53 |
+
class UNet3DConditionModel(ModelMixin, ConfigMixin):
|
54 |
+
r"""
|
55 |
+
UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep
|
56 |
+
and returns sample shaped output.
|
57 |
+
|
58 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
|
59 |
+
implements for all the models (such as downloading or saving, etc.)
|
60 |
+
|
61 |
+
Parameters:
|
62 |
+
sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
|
63 |
+
Height and width of input/output sample.
|
64 |
+
in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
|
65 |
+
out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
|
66 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
|
67 |
+
The tuple of downsample blocks to use.
|
68 |
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`):
|
69 |
+
The tuple of upsample blocks to use.
|
70 |
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
|
71 |
+
The tuple of output channels for each block.
|
72 |
+
layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
|
73 |
+
downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
|
74 |
+
mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
|
75 |
+
act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
|
76 |
+
norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
|
77 |
+
If `None`, it will skip the normalization and activation layers in post-processing
|
78 |
+
norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
|
79 |
+
cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.
|
80 |
+
attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
|
81 |
+
"""
|
82 |
+
|
83 |
+
_supports_gradient_checkpointing = True
|
84 |
+
|
85 |
+
@register_to_config
|
86 |
+
def __init__(
|
87 |
+
self,
|
88 |
+
sample_size: Optional[int] = None,
|
89 |
+
in_channels: int = 4,
|
90 |
+
out_channels: int = 4,
|
91 |
+
down_block_types: Tuple[str] = (
|
92 |
+
"CrossAttnDownBlock3D",
|
93 |
+
"CrossAttnDownBlock3D",
|
94 |
+
"CrossAttnDownBlock3D",
|
95 |
+
"DownBlock3D",
|
96 |
+
),
|
97 |
+
up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"),
|
98 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
99 |
+
layers_per_block: int = 2,
|
100 |
+
downsample_padding: int = 1,
|
101 |
+
mid_block_scale_factor: float = 1,
|
102 |
+
act_fn: str = "silu",
|
103 |
+
norm_num_groups: Optional[int] = 32,
|
104 |
+
norm_eps: float = 1e-5,
|
105 |
+
cross_attention_dim: int = 1024,
|
106 |
+
attention_head_dim: Union[int, Tuple[int]] = 64,
|
107 |
+
):
|
108 |
+
super().__init__()
|
109 |
+
|
110 |
+
self.sample_size = sample_size
|
111 |
+
self.gradient_checkpointing = False
|
112 |
+
# Check inputs
|
113 |
+
if len(down_block_types) != len(up_block_types):
|
114 |
+
raise ValueError(
|
115 |
+
f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
|
116 |
+
)
|
117 |
+
|
118 |
+
if len(block_out_channels) != len(down_block_types):
|
119 |
+
raise ValueError(
|
120 |
+
f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
|
121 |
+
)
|
122 |
+
|
123 |
+
if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
|
124 |
+
raise ValueError(
|
125 |
+
f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
|
126 |
+
)
|
127 |
+
|
128 |
+
# input
|
129 |
+
conv_in_kernel = 3
|
130 |
+
conv_out_kernel = 3
|
131 |
+
conv_in_padding = (conv_in_kernel - 1) // 2
|
132 |
+
self.conv_in = nn.Conv2d(
|
133 |
+
in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
|
134 |
+
)
|
135 |
+
|
136 |
+
# time
|
137 |
+
time_embed_dim = block_out_channels[0] * 4
|
138 |
+
self.time_proj = Timesteps(block_out_channels[0], True, 0)
|
139 |
+
timestep_input_dim = block_out_channels[0]
|
140 |
+
|
141 |
+
self.time_embedding = TimestepEmbedding(
|
142 |
+
timestep_input_dim,
|
143 |
+
time_embed_dim,
|
144 |
+
act_fn=act_fn,
|
145 |
+
)
|
146 |
+
|
147 |
+
self.transformer_in = TransformerTemporalModel(
|
148 |
+
num_attention_heads=8,
|
149 |
+
attention_head_dim=attention_head_dim,
|
150 |
+
in_channels=block_out_channels[0],
|
151 |
+
num_layers=1,
|
152 |
+
)
|
153 |
+
|
154 |
+
# class embedding
|
155 |
+
self.down_blocks = nn.ModuleList([])
|
156 |
+
self.up_blocks = nn.ModuleList([])
|
157 |
+
|
158 |
+
if isinstance(attention_head_dim, int):
|
159 |
+
attention_head_dim = (attention_head_dim,) * len(down_block_types)
|
160 |
+
|
161 |
+
# down
|
162 |
+
output_channel = block_out_channels[0]
|
163 |
+
for i, down_block_type in enumerate(down_block_types):
|
164 |
+
input_channel = output_channel
|
165 |
+
output_channel = block_out_channels[i]
|
166 |
+
is_final_block = i == len(block_out_channels) - 1
|
167 |
+
|
168 |
+
down_block = get_down_block(
|
169 |
+
down_block_type,
|
170 |
+
num_layers=layers_per_block,
|
171 |
+
in_channels=input_channel,
|
172 |
+
out_channels=output_channel,
|
173 |
+
temb_channels=time_embed_dim,
|
174 |
+
add_downsample=not is_final_block,
|
175 |
+
resnet_eps=norm_eps,
|
176 |
+
resnet_act_fn=act_fn,
|
177 |
+
resnet_groups=norm_num_groups,
|
178 |
+
cross_attention_dim=cross_attention_dim,
|
179 |
+
attn_num_head_channels=attention_head_dim[i],
|
180 |
+
downsample_padding=downsample_padding,
|
181 |
+
dual_cross_attention=False,
|
182 |
+
)
|
183 |
+
self.down_blocks.append(down_block)
|
184 |
+
|
185 |
+
# mid
|
186 |
+
self.mid_block = UNetMidBlock3DCrossAttn(
|
187 |
+
in_channels=block_out_channels[-1],
|
188 |
+
temb_channels=time_embed_dim,
|
189 |
+
resnet_eps=norm_eps,
|
190 |
+
resnet_act_fn=act_fn,
|
191 |
+
output_scale_factor=mid_block_scale_factor,
|
192 |
+
cross_attention_dim=cross_attention_dim,
|
193 |
+
attn_num_head_channels=attention_head_dim[-1],
|
194 |
+
resnet_groups=norm_num_groups,
|
195 |
+
dual_cross_attention=False,
|
196 |
+
)
|
197 |
+
|
198 |
+
# count how many layers upsample the images
|
199 |
+
self.num_upsamplers = 0
|
200 |
+
|
201 |
+
# up
|
202 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
203 |
+
reversed_attention_head_dim = list(reversed(attention_head_dim))
|
204 |
+
|
205 |
+
output_channel = reversed_block_out_channels[0]
|
206 |
+
for i, up_block_type in enumerate(up_block_types):
|
207 |
+
is_final_block = i == len(block_out_channels) - 1
|
208 |
+
|
209 |
+
prev_output_channel = output_channel
|
210 |
+
output_channel = reversed_block_out_channels[i]
|
211 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
212 |
+
|
213 |
+
# add upsample block for all BUT final layer
|
214 |
+
if not is_final_block:
|
215 |
+
add_upsample = True
|
216 |
+
self.num_upsamplers += 1
|
217 |
+
else:
|
218 |
+
add_upsample = False
|
219 |
+
|
220 |
+
up_block = get_up_block(
|
221 |
+
up_block_type,
|
222 |
+
num_layers=layers_per_block + 1,
|
223 |
+
in_channels=input_channel,
|
224 |
+
out_channels=output_channel,
|
225 |
+
prev_output_channel=prev_output_channel,
|
226 |
+
temb_channels=time_embed_dim,
|
227 |
+
add_upsample=add_upsample,
|
228 |
+
resnet_eps=norm_eps,
|
229 |
+
resnet_act_fn=act_fn,
|
230 |
+
resnet_groups=norm_num_groups,
|
231 |
+
cross_attention_dim=cross_attention_dim,
|
232 |
+
attn_num_head_channels=reversed_attention_head_dim[i],
|
233 |
+
dual_cross_attention=False,
|
234 |
+
)
|
235 |
+
self.up_blocks.append(up_block)
|
236 |
+
prev_output_channel = output_channel
|
237 |
+
|
238 |
+
# out
|
239 |
+
if norm_num_groups is not None:
|
240 |
+
self.conv_norm_out = nn.GroupNorm(
|
241 |
+
num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
|
242 |
+
)
|
243 |
+
self.conv_act = nn.SiLU()
|
244 |
+
else:
|
245 |
+
self.conv_norm_out = None
|
246 |
+
self.conv_act = None
|
247 |
+
|
248 |
+
conv_out_padding = (conv_out_kernel - 1) // 2
|
249 |
+
self.conv_out = nn.Conv2d(
|
250 |
+
block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
|
251 |
+
)
|
252 |
+
|
253 |
+
def set_attention_slice(self, slice_size):
|
254 |
+
r"""
|
255 |
+
Enable sliced attention computation.
|
256 |
+
|
257 |
+
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
|
258 |
+
in several steps. This is useful to save some memory in exchange for a small speed decrease.
|
259 |
+
|
260 |
+
Args:
|
261 |
+
slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
|
262 |
+
When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
|
263 |
+
`"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
|
264 |
+
provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
|
265 |
+
must be a multiple of `slice_size`.
|
266 |
+
"""
|
267 |
+
sliceable_head_dims = []
|
268 |
+
|
269 |
+
def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
|
270 |
+
if hasattr(module, "set_attention_slice"):
|
271 |
+
sliceable_head_dims.append(module.sliceable_head_dim)
|
272 |
+
|
273 |
+
for child in module.children():
|
274 |
+
fn_recursive_retrieve_slicable_dims(child)
|
275 |
+
|
276 |
+
# retrieve number of attention layers
|
277 |
+
for module in self.children():
|
278 |
+
fn_recursive_retrieve_slicable_dims(module)
|
279 |
+
|
280 |
+
num_slicable_layers = len(sliceable_head_dims)
|
281 |
+
|
282 |
+
if slice_size == "auto":
|
283 |
+
# half the attention head size is usually a good trade-off between
|
284 |
+
# speed and memory
|
285 |
+
slice_size = [dim // 2 for dim in sliceable_head_dims]
|
286 |
+
elif slice_size == "max":
|
287 |
+
# make smallest slice possible
|
288 |
+
slice_size = num_slicable_layers * [1]
|
289 |
+
|
290 |
+
slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
|
291 |
+
|
292 |
+
if len(slice_size) != len(sliceable_head_dims):
|
293 |
+
raise ValueError(
|
294 |
+
f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
|
295 |
+
f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
|
296 |
+
)
|
297 |
+
|
298 |
+
for i in range(len(slice_size)):
|
299 |
+
size = slice_size[i]
|
300 |
+
dim = sliceable_head_dims[i]
|
301 |
+
if size is not None and size > dim:
|
302 |
+
raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
|
303 |
+
|
304 |
+
# Recursively walk through all the children.
|
305 |
+
# Any children which exposes the set_attention_slice method
|
306 |
+
# gets the message
|
307 |
+
def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
|
308 |
+
if hasattr(module, "set_attention_slice"):
|
309 |
+
module.set_attention_slice(slice_size.pop())
|
310 |
+
|
311 |
+
for child in module.children():
|
312 |
+
fn_recursive_set_attention_slice(child, slice_size)
|
313 |
+
|
314 |
+
reversed_slice_size = list(reversed(slice_size))
|
315 |
+
for module in self.children():
|
316 |
+
fn_recursive_set_attention_slice(module, reversed_slice_size)
|
317 |
+
|
318 |
+
def _set_gradient_checkpointing(self, value=False):
|
319 |
+
self.gradient_checkpointing = value
|
320 |
+
self.mid_block.gradient_checkpointing = value
|
321 |
+
for module in self.down_blocks + self.up_blocks:
|
322 |
+
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
|
323 |
+
module.gradient_checkpointing = value
|
324 |
+
|
325 |
+
def forward(
|
326 |
+
self,
|
327 |
+
sample: torch.FloatTensor,
|
328 |
+
timestep: Union[torch.Tensor, float, int],
|
329 |
+
encoder_hidden_states: torch.Tensor,
|
330 |
+
class_labels: Optional[torch.Tensor] = None,
|
331 |
+
timestep_cond: Optional[torch.Tensor] = None,
|
332 |
+
attention_mask: Optional[torch.Tensor] = None,
|
333 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
334 |
+
down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
|
335 |
+
mid_block_additional_residual: Optional[torch.Tensor] = None,
|
336 |
+
return_dict: bool = True,
|
337 |
+
) -> Union[UNet3DConditionOutput, Tuple]:
|
338 |
+
r"""
|
339 |
+
Args:
|
340 |
+
sample (`torch.FloatTensor`): (batch, num_frames, channel, height, width) noisy inputs tensor
|
341 |
+
timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
|
342 |
+
encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
|
343 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
344 |
+
Whether or not to return a [`models.unet_2d_condition.UNet3DConditionOutput`] instead of a plain tuple.
|
345 |
+
cross_attention_kwargs (`dict`, *optional*):
|
346 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
347 |
+
`self.processor` in
|
348 |
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
349 |
+
|
350 |
+
Returns:
|
351 |
+
[`~models.unet_2d_condition.UNet3DConditionOutput`] or `tuple`:
|
352 |
+
[`~models.unet_2d_condition.UNet3DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
353 |
+
returning a tuple, the first element is the sample tensor.
|
354 |
+
"""
|
355 |
+
# By default samples have to be AT least a multiple of the overall upsampling factor.
|
356 |
+
# The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
|
357 |
+
# However, the upsampling interpolation output size can be forced to fit any upsampling size
|
358 |
+
# on the fly if necessary.
|
359 |
+
default_overall_up_factor = 2**self.num_upsamplers
|
360 |
+
|
361 |
+
# upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
|
362 |
+
forward_upsample_size = False
|
363 |
+
upsample_size = None
|
364 |
+
|
365 |
+
if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
|
366 |
+
logger.info("Forward upsample size to force interpolation output size.")
|
367 |
+
forward_upsample_size = True
|
368 |
+
|
369 |
+
# prepare attention_mask
|
370 |
+
if attention_mask is not None:
|
371 |
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
372 |
+
attention_mask = attention_mask.unsqueeze(1)
|
373 |
+
|
374 |
+
# 1. time
|
375 |
+
timesteps = timestep
|
376 |
+
if not torch.is_tensor(timesteps):
|
377 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
378 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
379 |
+
is_mps = sample.device.type == "mps"
|
380 |
+
if isinstance(timestep, float):
|
381 |
+
dtype = torch.float32 if is_mps else torch.float64
|
382 |
+
else:
|
383 |
+
dtype = torch.int32 if is_mps else torch.int64
|
384 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
385 |
+
elif len(timesteps.shape) == 0:
|
386 |
+
timesteps = timesteps[None].to(sample.device)
|
387 |
+
|
388 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
389 |
+
num_frames = sample.shape[2]
|
390 |
+
timesteps = timesteps.expand(sample.shape[0])
|
391 |
+
|
392 |
+
t_emb = self.time_proj(timesteps)
|
393 |
+
|
394 |
+
# timesteps does not contain any weights and will always return f32 tensors
|
395 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
396 |
+
# there might be better ways to encapsulate this.
|
397 |
+
t_emb = t_emb.to(dtype=self.dtype)
|
398 |
+
|
399 |
+
emb = self.time_embedding(t_emb, timestep_cond)
|
400 |
+
emb = emb.repeat_interleave(repeats=num_frames, dim=0)
|
401 |
+
encoder_hidden_states = encoder_hidden_states.repeat_interleave(repeats=num_frames, dim=0)
|
402 |
+
|
403 |
+
# 2. pre-process
|
404 |
+
sample = sample.permute(0, 2, 1, 3, 4).reshape((sample.shape[0] * num_frames, -1) + sample.shape[3:])
|
405 |
+
sample = self.conv_in(sample)
|
406 |
+
|
407 |
+
if num_frames > 1:
|
408 |
+
if self.gradient_checkpointing:
|
409 |
+
sample = transformer_g_c(self.transformer_in, sample, num_frames)
|
410 |
+
else:
|
411 |
+
sample = self.transformer_in(sample, num_frames=num_frames).sample
|
412 |
+
|
413 |
+
# 3. down
|
414 |
+
down_block_res_samples = (sample,)
|
415 |
+
for downsample_block in self.down_blocks:
|
416 |
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
417 |
+
sample, res_samples = downsample_block(
|
418 |
+
hidden_states=sample,
|
419 |
+
temb=emb,
|
420 |
+
encoder_hidden_states=encoder_hidden_states,
|
421 |
+
attention_mask=attention_mask,
|
422 |
+
num_frames=num_frames,
|
423 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
424 |
+
)
|
425 |
+
else:
|
426 |
+
sample, res_samples = downsample_block(hidden_states=sample, temb=emb, num_frames=num_frames)
|
427 |
+
|
428 |
+
down_block_res_samples += res_samples
|
429 |
+
|
430 |
+
if down_block_additional_residuals is not None:
|
431 |
+
new_down_block_res_samples = ()
|
432 |
+
|
433 |
+
for down_block_res_sample, down_block_additional_residual in zip(
|
434 |
+
down_block_res_samples, down_block_additional_residuals
|
435 |
+
):
|
436 |
+
down_block_res_sample = down_block_res_sample + down_block_additional_residual
|
437 |
+
new_down_block_res_samples += (down_block_res_sample,)
|
438 |
+
|
439 |
+
down_block_res_samples = new_down_block_res_samples
|
440 |
+
|
441 |
+
# 4. mid
|
442 |
+
if self.mid_block is not None:
|
443 |
+
sample = self.mid_block(
|
444 |
+
sample,
|
445 |
+
emb,
|
446 |
+
encoder_hidden_states=encoder_hidden_states,
|
447 |
+
attention_mask=attention_mask,
|
448 |
+
num_frames=num_frames,
|
449 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
450 |
+
)
|
451 |
+
|
452 |
+
if mid_block_additional_residual is not None:
|
453 |
+
sample = sample + mid_block_additional_residual
|
454 |
+
|
455 |
+
# 5. up
|
456 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
457 |
+
is_final_block = i == len(self.up_blocks) - 1
|
458 |
+
|
459 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
460 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
461 |
+
|
462 |
+
# if we have not reached the final block and need to forward the
|
463 |
+
# upsample size, we do it here
|
464 |
+
if not is_final_block and forward_upsample_size:
|
465 |
+
upsample_size = down_block_res_samples[-1].shape[2:]
|
466 |
+
|
467 |
+
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
|
468 |
+
sample = upsample_block(
|
469 |
+
hidden_states=sample,
|
470 |
+
temb=emb,
|
471 |
+
res_hidden_states_tuple=res_samples,
|
472 |
+
encoder_hidden_states=encoder_hidden_states,
|
473 |
+
upsample_size=upsample_size,
|
474 |
+
attention_mask=attention_mask,
|
475 |
+
num_frames=num_frames,
|
476 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
477 |
+
)
|
478 |
+
else:
|
479 |
+
sample = upsample_block(
|
480 |
+
hidden_states=sample,
|
481 |
+
temb=emb,
|
482 |
+
res_hidden_states_tuple=res_samples,
|
483 |
+
upsample_size=upsample_size,
|
484 |
+
num_frames=num_frames,
|
485 |
+
)
|
486 |
+
|
487 |
+
# 6. post-process
|
488 |
+
if self.conv_norm_out:
|
489 |
+
sample = self.conv_norm_out(sample)
|
490 |
+
sample = self.conv_act(sample)
|
491 |
+
|
492 |
+
sample = self.conv_out(sample)
|
493 |
+
|
494 |
+
# reshape to (batch, channel, framerate, width, height)
|
495 |
+
sample = sample[None, :].reshape((-1, num_frames) + sample.shape[1:]).permute(0, 2, 1, 3, 4)
|
496 |
+
|
497 |
+
if not return_dict:
|
498 |
+
return (sample,)
|
499 |
+
|
500 |
+
return UNet3DConditionOutput(sample=sample)
|
noise_init/__init__.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .freq_init import FreqInit
|
2 |
+
from .blend_init import BlendInit
|
3 |
+
from .blend_freq_init import BlendFreqInit
|
4 |
+
from .fft_init import FFTInit
|
noise_init/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (350 Bytes). View file
|
|
noise_init/__pycache__/blend_freq_init.cpython-310.pyc
ADDED
Binary file (1.1 kB). View file
|
|
noise_init/__pycache__/blend_init.cpython-310.pyc
ADDED
Binary file (430 Bytes). View file
|
|
noise_init/__pycache__/fft_init.cpython-310.pyc
ADDED
Binary file (5.35 kB). View file
|
|