Spaces:
Running
on
Zero
Running
on
Zero
Init
Browse files- .gitignore +2 -0
- README.md +2 -0
- app.py +502 -0
- ckpts/model.safetensors +3 -0
- ckpts/sam_vit_h_4b8939.pth +3 -0
- network_utils.py +104 -0
- package-lock.json +6 -0
- requirements.txt +154 -0
- svd.py +1316 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
__pycache__
|
2 |
+
outputs
|
README.md
CHANGED
@@ -11,3 +11,5 @@ license: cc-by-nc-sa-4.0
|
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
14 |
+
|
15 |
+
arxiv.org/abs/2408.04631
|
app.py
ADDED
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from PIL import Image, ImageOps
|
3 |
+
import random
|
4 |
+
|
5 |
+
import cv2
|
6 |
+
from diffusers import StableVideoDiffusionPipeline
|
7 |
+
from diffusers.image_processor import VaeImageProcessor
|
8 |
+
from diffusers.models.attention_processor import XFormersAttnProcessor
|
9 |
+
from diffusers.utils import export_to_gif
|
10 |
+
import gradio as gr
|
11 |
+
import numpy as np
|
12 |
+
from safetensors import safe_open
|
13 |
+
from segment_anything import build_sam, SamPredictor
|
14 |
+
import spaces
|
15 |
+
from tqdm import tqdm
|
16 |
+
import torch
|
17 |
+
|
18 |
+
from svd import (
|
19 |
+
UNetDragSpatioTemporalConditionModel,
|
20 |
+
AllToFirstXFormersAttnProcessor,
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
TITLE = '''Puppet-Master: Scaling Interactive Video Generation as a Motion Prior for Part-Level Dynamics'''
|
25 |
+
DESCRIPTION = """
|
26 |
+
<div>
|
27 |
+
Try <a href='https://vgg-puppetmaster.github.io/'><b>Puppet-Master</b></a> yourself to animate your favorite objects in seconds!
|
28 |
+
</div>
|
29 |
+
<div>
|
30 |
+
Please give us a 🌟 on <a href='https://github.com/RuiningLi/puppet-master'>Github</a> if you like our work!
|
31 |
+
</div>
|
32 |
+
"""
|
33 |
+
INSTRUCTION = '''
|
34 |
+
2 steps to get started:
|
35 |
+
- Upload an image of a dynamic object.
|
36 |
+
- Add one or more drags on the object to specify the part-level interactions.
|
37 |
+
How to add drags:
|
38 |
+
- To add a drag, first click on the starting point of the drag, then click on the ending point of the drag, on the Input Image (leftmost).
|
39 |
+
- You can add up to 5 drags.
|
40 |
+
- After every click, the drags will be visualized on the Image with Drags (second from left).
|
41 |
+
- If the last drag is not completed (you specified the starting point but not the ending point), it will simply be ignored.
|
42 |
+
- To retry, click the [x] button on the top-right corner of the input image to start over, even if you just want to try a different set of drags.
|
43 |
+
- Have fun dragging!
|
44 |
+
|
45 |
+
Then, you will be prompted to verify the object segmentation. Once you confirm that the segmentation is decent, the output image will be generated in seconds!
|
46 |
+
|
47 |
+
Tips:
|
48 |
+
- We found having classifier-free guidance weight ~5.0 works best.
|
49 |
+
- Try changing the random seed to get different results.
|
50 |
+
'''
|
51 |
+
PREPROCESS_INSTRUCTION = '''
|
52 |
+
Segmentation is needed if it is not already provided through an alpha channel in the input image.
|
53 |
+
You don't need to tick this box if you have chosen one of the example images.
|
54 |
+
If you have uploaded one of your own images, it is very likely that you will need to tick this box.
|
55 |
+
You should verify that the preprocessed image is object-centric (i.e., clearly contains a single object) and has white background.
|
56 |
+
'''
|
57 |
+
|
58 |
+
|
59 |
+
def tensor2vid(video: torch.Tensor, processor: VaeImageProcessor, output_type: str = "np"):
|
60 |
+
batch_size = video.shape[0]
|
61 |
+
outputs = []
|
62 |
+
for batch_idx in range(batch_size):
|
63 |
+
batch_vid = video[batch_idx].permute(1, 0, 2, 3)
|
64 |
+
batch_output = processor.postprocess(batch_vid, output_type)
|
65 |
+
|
66 |
+
outputs.append(batch_output)
|
67 |
+
|
68 |
+
if output_type == "np":
|
69 |
+
outputs = np.stack(outputs)
|
70 |
+
|
71 |
+
elif output_type == "pt":
|
72 |
+
outputs = torch.stack(outputs)
|
73 |
+
|
74 |
+
elif not output_type == "pil":
|
75 |
+
raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
|
76 |
+
|
77 |
+
return outputs
|
78 |
+
|
79 |
+
|
80 |
+
def center_and_square_image(pil_image_rgba, drags, scale_factor):
|
81 |
+
image = pil_image_rgba
|
82 |
+
alpha = np.array(image)[:, :, 3] # Extract the alpha channel
|
83 |
+
|
84 |
+
foreground_coords = np.argwhere(alpha > 0)
|
85 |
+
y_min, x_min = foreground_coords.min(axis=0)
|
86 |
+
y_max, x_max = foreground_coords.max(axis=0)
|
87 |
+
cy, cx = (y_min + y_max) // 2, (x_min + x_max) // 2
|
88 |
+
crop_height, crop_width = y_max - y_min + 1, x_max - x_min + 1
|
89 |
+
side_length = int(max(crop_height, crop_width) * scale_factor)
|
90 |
+
padded_image = ImageOps.expand(
|
91 |
+
image,
|
92 |
+
(side_length // 2, side_length // 2, side_length // 2, side_length // 2),
|
93 |
+
fill=(255, 255, 255, 255)
|
94 |
+
)
|
95 |
+
left, top = cx, cy
|
96 |
+
new_drags = []
|
97 |
+
for d in drags:
|
98 |
+
x, y = d
|
99 |
+
new_x, new_y = (x + side_length // 2 - cx) / side_length, (y + side_length // 2 - cy) / side_length
|
100 |
+
new_drags.append((new_x, new_y))
|
101 |
+
|
102 |
+
# Crop or pad the image as needed to make it centered around (cx, cy)
|
103 |
+
image = padded_image.crop((left, top, left + side_length, top + side_length))
|
104 |
+
# Resize the image to 256x256
|
105 |
+
image = image.resize((256, 256), Image.Resampling.LANCZOS)
|
106 |
+
return image, new_drags
|
107 |
+
|
108 |
+
|
109 |
+
def sam_init():
|
110 |
+
sam_checkpoint = os.path.join(os.path.dirname(__file__), "ckpts", "sam_vit_h_4b8939.pth")
|
111 |
+
predictor = SamPredictor(build_sam(checkpoint=sam_checkpoint).to("cuda"))
|
112 |
+
return predictor
|
113 |
+
|
114 |
+
|
115 |
+
def model_init():
|
116 |
+
model_checkpoint = os.path.join(os.path.dirname(__file__), "ckpts", "model.safetensors")
|
117 |
+
state_dict = {}
|
118 |
+
with safe_open(model_checkpoint, framework="pt", device="cpu") as f:
|
119 |
+
for k in f.keys():
|
120 |
+
state_dict[k] = f.get_tensor(k)
|
121 |
+
model = UNetDragSpatioTemporalConditionModel(num_drags=5)
|
122 |
+
attn_processors_dict={
|
123 |
+
"down_blocks.0.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
124 |
+
"down_blocks.0.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
125 |
+
"down_blocks.0.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
126 |
+
"down_blocks.0.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
127 |
+
"down_blocks.1.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
128 |
+
"down_blocks.1.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
129 |
+
"down_blocks.1.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
130 |
+
"down_blocks.1.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
131 |
+
"down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
132 |
+
"down_blocks.2.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
133 |
+
"down_blocks.2.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
134 |
+
"down_blocks.2.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
135 |
+
|
136 |
+
"down_blocks.0.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
137 |
+
"down_blocks.0.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
138 |
+
"down_blocks.0.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
139 |
+
"down_blocks.0.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
140 |
+
"down_blocks.1.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
141 |
+
"down_blocks.1.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
142 |
+
"down_blocks.1.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
143 |
+
"down_blocks.1.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
144 |
+
"down_blocks.2.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
145 |
+
"down_blocks.2.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
146 |
+
"down_blocks.2.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
147 |
+
"down_blocks.2.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
148 |
+
|
149 |
+
"up_blocks.1.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
150 |
+
"up_blocks.1.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
151 |
+
"up_blocks.1.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
152 |
+
"up_blocks.1.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
153 |
+
"up_blocks.1.attentions.2.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
154 |
+
"up_blocks.1.attentions.2.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
155 |
+
"up_blocks.2.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
156 |
+
"up_blocks.2.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
157 |
+
"up_blocks.2.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
158 |
+
"up_blocks.2.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
159 |
+
"up_blocks.2.attentions.2.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
160 |
+
"up_blocks.2.attentions.2.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
161 |
+
"up_blocks.3.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
162 |
+
"up_blocks.3.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
163 |
+
"up_blocks.3.attentions.1.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
164 |
+
"up_blocks.3.attentions.1.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
165 |
+
"up_blocks.3.attentions.2.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
166 |
+
"up_blocks.3.attentions.2.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
167 |
+
|
168 |
+
"up_blocks.1.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
169 |
+
"up_blocks.1.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
170 |
+
"up_blocks.1.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
171 |
+
"up_blocks.1.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
172 |
+
"up_blocks.1.attentions.2.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
173 |
+
"up_blocks.1.attentions.2.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
174 |
+
"up_blocks.2.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
175 |
+
"up_blocks.2.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
176 |
+
"up_blocks.2.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
177 |
+
"up_blocks.2.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
178 |
+
"up_blocks.2.attentions.2.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
179 |
+
"up_blocks.2.attentions.2.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
180 |
+
"up_blocks.3.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
181 |
+
"up_blocks.3.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
182 |
+
"up_blocks.3.attentions.1.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
183 |
+
"up_blocks.3.attentions.1.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
184 |
+
"up_blocks.3.attentions.2.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
185 |
+
"up_blocks.3.attentions.2.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
186 |
+
|
187 |
+
"mid_block.attentions.0.transformer_blocks.0.attn1.processor": AllToFirstXFormersAttnProcessor(),
|
188 |
+
"mid_block.attentions.0.transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
189 |
+
"mid_block.attentions.0.temporal_transformer_blocks.0.attn1.processor": XFormersAttnProcessor(),
|
190 |
+
"mid_block.attentions.0.temporal_transformer_blocks.0.attn2.processor": XFormersAttnProcessor(),
|
191 |
+
}
|
192 |
+
model.set_attn_processor(attn_processors_dict)
|
193 |
+
model.load_state_dict(state_dict, strict=True)
|
194 |
+
return model.to("cuda")
|
195 |
+
|
196 |
+
|
197 |
+
sam_predictor = sam_init()
|
198 |
+
model = model_init()
|
199 |
+
pipe = StableVideoDiffusionPipeline.from_pretrained(
|
200 |
+
"/scratch/shared/beegfs/ruining/projects/generative-models/stable-video-diffusion-img2vid",
|
201 |
+
torch_dtype=torch.float16, variant="fp16"
|
202 |
+
)
|
203 |
+
pipe.vae.to(dtype=torch.float16, device="cuda")
|
204 |
+
pipe.image_encoder = pipe.image_encoder.to("cuda")
|
205 |
+
|
206 |
+
|
207 |
+
@spaces.GPU(duration=10)
|
208 |
+
def sam_segment(input_image, drags, foreground_points=None, scale_factor=2.2):
|
209 |
+
image = np.asarray(input_image)
|
210 |
+
sam_predictor.set_image(image)
|
211 |
+
|
212 |
+
with torch.no_grad():
|
213 |
+
masks_bbox, _, _ = sam_predictor.predict(
|
214 |
+
point_coords=foreground_points if foreground_points is not None else None,
|
215 |
+
point_labels=np.ones(len(foreground_points)) if foreground_points is not None else None,
|
216 |
+
multimask_output=True
|
217 |
+
)
|
218 |
+
|
219 |
+
out_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
|
220 |
+
out_image[:, :, :3] = image
|
221 |
+
out_image[:, :, 3] = masks_bbox[-1].astype(np.uint8) * 255
|
222 |
+
torch.cuda.empty_cache()
|
223 |
+
out_image, new_drags = center_and_square_image(Image.fromarray(out_image, mode="RGBA"), drags, scale_factor)
|
224 |
+
|
225 |
+
return out_image, new_drags
|
226 |
+
|
227 |
+
|
228 |
+
def get_point(img, sel_pix, evt: gr.SelectData):
|
229 |
+
sel_pix.append(evt.index)
|
230 |
+
points = []
|
231 |
+
img = np.array(img)
|
232 |
+
height = img.shape[0]
|
233 |
+
arrow_width_large = 7 * height // 256
|
234 |
+
arrow_width_small = 3 * height // 256
|
235 |
+
circle_size = 5 * height // 256
|
236 |
+
|
237 |
+
with_alpha = img.shape[2] == 4
|
238 |
+
for idx, point in enumerate(sel_pix):
|
239 |
+
if idx % 2 == 1:
|
240 |
+
cv2.circle(img, tuple(point), circle_size, (0, 0, 255, 255) if with_alpha else (0, 0, 255), -1)
|
241 |
+
else:
|
242 |
+
cv2.circle(img, tuple(point), circle_size, (255, 0, 0, 255) if with_alpha else (255, 0, 0), -1)
|
243 |
+
points.append(tuple(point))
|
244 |
+
if len(points) == 2:
|
245 |
+
cv2.arrowedLine(img, points[0], points[1], (0, 0, 0, 255) if with_alpha else (0, 0, 0), arrow_width_large)
|
246 |
+
cv2.arrowedLine(img, points[0], points[1], (255, 255, 0, 255) if with_alpha else (0, 0, 0), arrow_width_small)
|
247 |
+
points = []
|
248 |
+
return img if isinstance(img, np.ndarray) else np.array(img)
|
249 |
+
|
250 |
+
|
251 |
+
def clear_drag():
|
252 |
+
return []
|
253 |
+
|
254 |
+
|
255 |
+
def preprocess_image(img, chk_group, drags):
|
256 |
+
if img is None:
|
257 |
+
gr.Warning("No image is specified. Please specify an image before preprocessing.")
|
258 |
+
return None, drags
|
259 |
+
|
260 |
+
if drags is None or len(drags) == 0:
|
261 |
+
foreground_points = None
|
262 |
+
else:
|
263 |
+
foreground_points = np.array([drags[i] for i in range(0, len(drags), 2)])
|
264 |
+
|
265 |
+
if len(drags) == 0:
|
266 |
+
gr.Warning("No drags are specified. We recommend first specifying the drags before preprocessing.")
|
267 |
+
|
268 |
+
new_drags = drags
|
269 |
+
if "Preprocess with Segmentation" in chk_group:
|
270 |
+
img_np = np.array(img)
|
271 |
+
rgb_img = img_np[..., :3]
|
272 |
+
img, new_drags = sam_segment(
|
273 |
+
rgb_img,
|
274 |
+
drags,
|
275 |
+
foreground_points=foreground_points,
|
276 |
+
)
|
277 |
+
else:
|
278 |
+
new_drags = [(d[0] / img.width, d[1] / img.height) for d in drags]
|
279 |
+
|
280 |
+
img = np.array(img).astype(np.float32)
|
281 |
+
processed_img = img[..., :3] * img[..., 3:] / 255. + 255. * (1 - img[..., 3:] / 255.)
|
282 |
+
image_pil = Image.fromarray(processed_img.astype(np.uint8), mode="RGB")
|
283 |
+
processed_img = image_pil.resize((256, 256), Image.LANCZOS)
|
284 |
+
return processed_img, new_drags
|
285 |
+
|
286 |
+
|
287 |
+
def sample_from_noise(model, scheduler, cond_latent, cond_embedding, drags,
|
288 |
+
min_guidance=1.0, max_guidance=3.0, num_inference_steps=50):
|
289 |
+
model.eval()
|
290 |
+
|
291 |
+
scheduler.set_timesteps(num_inference_steps, device=cond_latent.device)
|
292 |
+
timesteps = scheduler.timesteps.to(cond_latent.device)
|
293 |
+
|
294 |
+
do_classifier_free_guidance = max_guidance > 1.0
|
295 |
+
latents = torch.randn((1, 14, 4, 32, 32)).to(cond_latent) * scheduler.init_noise_sigma
|
296 |
+
guidance_scale = torch.linspace(min_guidance, max_guidance, 14).unsqueeze(0).to(cond_latent)[..., None, None, None]
|
297 |
+
|
298 |
+
for i, t in tqdm(enumerate(timesteps)):
|
299 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
300 |
+
|
301 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
302 |
+
|
303 |
+
with torch.no_grad():
|
304 |
+
noise_pred = model(
|
305 |
+
latent_model_input,
|
306 |
+
t,
|
307 |
+
image_latents=torch.cat([cond_latent, torch.zeros_like(cond_latent)]) if do_classifier_free_guidance else cond_latent,
|
308 |
+
encoder_hidden_states=torch.cat([cond_embedding, torch.zeros_like(cond_embedding)]) if do_classifier_free_guidance else cond_embedding,
|
309 |
+
added_time_ids=None, # dummy
|
310 |
+
drags=torch.cat([drags, torch.zeros_like(drags)]) if do_classifier_free_guidance else drags,
|
311 |
+
)
|
312 |
+
|
313 |
+
if do_classifier_free_guidance:
|
314 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
315 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
316 |
+
|
317 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
318 |
+
|
319 |
+
return latents
|
320 |
+
|
321 |
+
|
322 |
+
@spaces.GPU(duration=40)
|
323 |
+
def generate_image(img_cond, seed, cfg_scale, drags_list):
|
324 |
+
if img_cond is None:
|
325 |
+
gr.Warning("Please preprocess the image first.")
|
326 |
+
return None
|
327 |
+
|
328 |
+
torch.manual_seed(seed)
|
329 |
+
np.random.seed(seed)
|
330 |
+
random.seed(seed)
|
331 |
+
|
332 |
+
img_cond_pil = Image.fromarray(img_cond)
|
333 |
+
img_cond_preprocessed = pipe.video_processor.preprocess(img_cond_pil, height=256, width=256)
|
334 |
+
img_cond_preprocessed = img_cond_preprocessed.to(device="cuda", dtype=torch.float16)
|
335 |
+
latent_dist = pipe.vae.encode(img_cond_preprocessed).latent_dist
|
336 |
+
embeddings = pipe._encode_image(img_cond_pil, device="cuda", num_videos_per_prompt=1, do_classifier_free_guidance=False)
|
337 |
+
|
338 |
+
drags = torch.zeros(14, 5, 4)
|
339 |
+
for i in range(0, len(drags_list), 2):
|
340 |
+
start_point, end_point = drags_list[i:i+2]
|
341 |
+
drag_idx = i // 2
|
342 |
+
drags[:, drag_idx, :2] = torch.Tensor(start_point)
|
343 |
+
drags[0, drag_idx, 2:] = torch.Tensor(start_point)
|
344 |
+
drags[-1, drag_idx, 2:] = torch.Tensor(end_point)
|
345 |
+
|
346 |
+
if drag_idx == 4:
|
347 |
+
break
|
348 |
+
|
349 |
+
frame_indices = torch.arange(1, 13).unsqueeze(-1).unsqueeze(-1)
|
350 |
+
t = frame_indices.float() / 13.0 # Normalize time to [0, 1]
|
351 |
+
drags[1:-1, :, 2:] = drags[0, :, 2:] * (1 - t) + drags[-1, :, 2:] * t
|
352 |
+
drags = drags[None].to(device="cuda")
|
353 |
+
|
354 |
+
batch = dict(
|
355 |
+
drags=drags,
|
356 |
+
cond_embedding=embeddings.to(dtype=torch.float32),
|
357 |
+
cond_latent=latent_dist.mean.to(dtype=torch.float32),
|
358 |
+
)
|
359 |
+
|
360 |
+
with torch.no_grad():
|
361 |
+
latents = sample_from_noise(
|
362 |
+
model,
|
363 |
+
pipe.scheduler,
|
364 |
+
**batch,
|
365 |
+
max_guidance=cfg_scale,
|
366 |
+
num_inference_steps=50,
|
367 |
+
)
|
368 |
+
|
369 |
+
frames = pipe.vae.decode(latents.flatten(0, 1).to(torch.float16) / 0.18215, num_frames=14).sample.float()
|
370 |
+
frames = tensor2vid(frames.view(-1, 14, 3, 256, 256).permute(0, 2, 1, 3, 4), pipe.video_processor, output_type="pil")[0]
|
371 |
+
|
372 |
+
# Add drags
|
373 |
+
frame_with_drag = np.ascontiguousarray(np.array(frames[0]))
|
374 |
+
for i in range(0, len(drags_list), 2):
|
375 |
+
drag_idx = i // 2
|
376 |
+
start_point, end_point = drags_list[i:i+2]
|
377 |
+
start_point = (int(start_point[0] * 256), int(start_point[1] * 256))
|
378 |
+
end_point = (int(end_point[0] * 256), int(end_point[1] * 256))
|
379 |
+
frame_with_drag = cv2.arrowedLine(frame_with_drag, start_point, end_point, (0, 0, 0), 4)
|
380 |
+
frame_with_drag = cv2.arrowedLine(frame_with_drag, start_point, end_point, (255, 255, 0), 2)
|
381 |
+
|
382 |
+
if drag_idx == 4:
|
383 |
+
break
|
384 |
+
|
385 |
+
frames = [Image.fromarray(frame_with_drag)] * 5 + frames
|
386 |
+
save_dir = os.path.join(os.path.dirname(__file__), "outputs")
|
387 |
+
if not os.path.exists(save_dir):
|
388 |
+
os.makedirs(save_dir)
|
389 |
+
save_id = len(os.listdir(save_dir))
|
390 |
+
save_path = os.path.join(save_dir, f"{save_id:05d}.gif")
|
391 |
+
export_to_gif(frames, save_path)
|
392 |
+
return save_path
|
393 |
+
|
394 |
+
|
395 |
+
with gr.Blocks(title=TITLE) as demo:
|
396 |
+
gr.Markdown("# " + DESCRIPTION)
|
397 |
+
|
398 |
+
with gr.Row():
|
399 |
+
gr.Markdown(INSTRUCTION)
|
400 |
+
|
401 |
+
drags = gr.State(value=[])
|
402 |
+
|
403 |
+
with gr.Row(variant="panel"):
|
404 |
+
with gr.Column(scale=1):
|
405 |
+
input_image = gr.Image(
|
406 |
+
interactive=True,
|
407 |
+
type='pil',
|
408 |
+
image_mode="RGBA",
|
409 |
+
width=256,
|
410 |
+
show_label=True,
|
411 |
+
label="Input Image",
|
412 |
+
)
|
413 |
+
|
414 |
+
example_folder = os.path.join(os.path.dirname(__file__), "./example_images")
|
415 |
+
example_fns = [os.path.join(example_folder, example) for example in sorted(os.listdir(example_folder))]
|
416 |
+
gr.Examples(
|
417 |
+
examples=example_fns,
|
418 |
+
inputs=[input_image],
|
419 |
+
cache_examples=False,
|
420 |
+
label='Feel free to use one of our provided examples!',
|
421 |
+
examples_per_page=30
|
422 |
+
)
|
423 |
+
|
424 |
+
input_image.change(
|
425 |
+
fn=clear_drag,
|
426 |
+
outputs=[drags],
|
427 |
+
)
|
428 |
+
|
429 |
+
with gr.Column(scale=1):
|
430 |
+
drag_image = gr.Image(
|
431 |
+
type="numpy",
|
432 |
+
label="Image with Drags",
|
433 |
+
interactive=False,
|
434 |
+
width=256,
|
435 |
+
image_mode="RGB",
|
436 |
+
)
|
437 |
+
|
438 |
+
input_image.select(
|
439 |
+
fn=get_point,
|
440 |
+
inputs=[input_image, drags],
|
441 |
+
outputs=[drag_image],
|
442 |
+
)
|
443 |
+
|
444 |
+
with gr.Column(scale=1):
|
445 |
+
processed_image = gr.Image(
|
446 |
+
type='numpy',
|
447 |
+
label="Processed Image",
|
448 |
+
interactive=False,
|
449 |
+
width=256,
|
450 |
+
height=256,
|
451 |
+
image_mode='RGB',
|
452 |
+
)
|
453 |
+
processed_image_highres = gr.Image(type='pil', image_mode='RGB', visible=False)
|
454 |
+
|
455 |
+
with gr.Accordion('Advanced preprocessing options', open=True):
|
456 |
+
with gr.Row():
|
457 |
+
with gr.Column():
|
458 |
+
preprocess_chk_group = gr.CheckboxGroup(
|
459 |
+
['Preprocess with Segmentation'],
|
460 |
+
label='Segment',
|
461 |
+
info=PREPROCESS_INSTRUCTION
|
462 |
+
)
|
463 |
+
|
464 |
+
preprocess_button = gr.Button(
|
465 |
+
value="Preprocess Input Image",
|
466 |
+
)
|
467 |
+
preprocess_button.click(
|
468 |
+
fn=preprocess_image,
|
469 |
+
inputs=[input_image, preprocess_chk_group, drags],
|
470 |
+
outputs=[processed_image, drags],
|
471 |
+
queue=True,
|
472 |
+
)
|
473 |
+
|
474 |
+
with gr.Column(scale=1):
|
475 |
+
generated_gif = gr.Image(
|
476 |
+
type="filepath",
|
477 |
+
label="Generated GIF",
|
478 |
+
interactive=False,
|
479 |
+
height=256,
|
480 |
+
width=256,
|
481 |
+
image_mode="RGB",
|
482 |
+
)
|
483 |
+
|
484 |
+
with gr.Accordion('Advanced generation options', open=True):
|
485 |
+
with gr.Row():
|
486 |
+
with gr.Column():
|
487 |
+
seed = gr.Slider(label="seed", value=0, minimum=0, maximum=10000, step=1, randomize=False)
|
488 |
+
cfg_scale = gr.Slider(
|
489 |
+
label="classifier-free guidance weight",
|
490 |
+
value=5, minimum=1, maximum=10, step=0.1
|
491 |
+
)
|
492 |
+
|
493 |
+
generate_button = gr.Button(
|
494 |
+
value="Generate Image",
|
495 |
+
)
|
496 |
+
generate_button.click(
|
497 |
+
fn=generate_image,
|
498 |
+
inputs=[processed_image, seed, cfg_scale, drags],
|
499 |
+
outputs=[generated_gif],
|
500 |
+
)
|
501 |
+
|
502 |
+
demo.launch(share=True)
|
ckpts/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7aa29ca634d8ec0f84fb8b090c1cda73d99f77d7a8cfaca3b051687a21a7f4c8
|
3 |
+
size 6703457048
|
ckpts/sam_vit_h_4b8939.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a7bf3b02f3ebf1267aba913ff637d9a2d5c33d3173bb679e46d9f338c26f262e
|
3 |
+
size 2564550879
|
network_utils.py
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple
|
2 |
+
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
class DragEmbedding(nn.Module):
|
9 |
+
def __init__(
|
10 |
+
self,
|
11 |
+
conditioning_embedding_channels: int, # out channel
|
12 |
+
conditioning_channels: int = 3,
|
13 |
+
block_out_channels: Tuple[int, ...] = (16, 32, 96),
|
14 |
+
):
|
15 |
+
super().__init__()
|
16 |
+
|
17 |
+
self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
|
18 |
+
|
19 |
+
self.blocks = nn.ModuleList([])
|
20 |
+
|
21 |
+
for i in range(len(block_out_channels) - 1):
|
22 |
+
channel_in = block_out_channels[i]
|
23 |
+
channel_out = block_out_channels[i + 1]
|
24 |
+
self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
|
25 |
+
self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1))
|
26 |
+
|
27 |
+
self.conv_out = zero_module(
|
28 |
+
nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
|
29 |
+
)
|
30 |
+
|
31 |
+
def forward(self, conditioning):
|
32 |
+
conditioning_ndims = len(conditioning.shape)
|
33 |
+
if conditioning_ndims == 5:
|
34 |
+
batch_size, num_frames, num_channels, h, w = conditioning.shape
|
35 |
+
conditioning = conditioning.flatten(0, 1)
|
36 |
+
|
37 |
+
embedding = self.conv_in(conditioning)
|
38 |
+
embedding = F.silu(embedding)
|
39 |
+
|
40 |
+
for block in self.blocks:
|
41 |
+
embedding = block(embedding)
|
42 |
+
embedding = F.silu(embedding)
|
43 |
+
|
44 |
+
embedding = self.conv_out(embedding)
|
45 |
+
if conditioning_ndims == 5:
|
46 |
+
embedding = embedding.view(batch_size, num_frames, *embedding.shape[1:])
|
47 |
+
|
48 |
+
return embedding
|
49 |
+
|
50 |
+
|
51 |
+
def zero_module(module):
|
52 |
+
for p in module.parameters():
|
53 |
+
nn.init.zeros_(p)
|
54 |
+
return module
|
55 |
+
|
56 |
+
|
57 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
|
58 |
+
"""
|
59 |
+
grid_size: int of the grid height and width
|
60 |
+
return:
|
61 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
62 |
+
"""
|
63 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
64 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
65 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
66 |
+
grid = np.stack(grid, axis=0)
|
67 |
+
|
68 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
69 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
70 |
+
if cls_token and extra_tokens > 0:
|
71 |
+
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
|
72 |
+
return pos_embed
|
73 |
+
|
74 |
+
|
75 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
76 |
+
assert embed_dim % 2 == 0
|
77 |
+
|
78 |
+
# use half of dimensions to encode grid_h
|
79 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
80 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
81 |
+
|
82 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
83 |
+
return emb
|
84 |
+
|
85 |
+
|
86 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
87 |
+
"""
|
88 |
+
embed_dim: output dimension for each position
|
89 |
+
pos: a list of positions to be encoded: size (M,)
|
90 |
+
out: (M, D)
|
91 |
+
"""
|
92 |
+
assert embed_dim % 2 == 0
|
93 |
+
omega = np.arange(embed_dim // 2, dtype=np.float64)
|
94 |
+
omega /= embed_dim / 2.
|
95 |
+
omega = 1. / 10000**omega # (D/2,)
|
96 |
+
|
97 |
+
pos = pos.reshape(-1) # (M,)
|
98 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
99 |
+
|
100 |
+
emb_sin = np.sin(out) # (M, D/2)
|
101 |
+
emb_cos = np.cos(out) # (M, D/2)
|
102 |
+
|
103 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
104 |
+
return emb
|
package-lock.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "puppet-master",
|
3 |
+
"lockfileVersion": 2,
|
4 |
+
"requires": true,
|
5 |
+
"packages": {}
|
6 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
accelerate==0.31.0
|
2 |
+
aiofiles==23.2.1
|
3 |
+
aiohttp==3.9.5
|
4 |
+
aiosignal==1.3.1
|
5 |
+
aiostream==0.5.2
|
6 |
+
altair==5.3.0
|
7 |
+
annotated-types==0.7.0
|
8 |
+
antlr4-python3-runtime==4.9.3
|
9 |
+
anyio==4.4.0
|
10 |
+
async-timeout==4.0.3
|
11 |
+
attrs==23.2.0
|
12 |
+
beautifulsoup4==4.12.3
|
13 |
+
Brotli==1.1.0
|
14 |
+
certifi==2024.6.2
|
15 |
+
charset-normalizer==3.3.2
|
16 |
+
click==8.1.7
|
17 |
+
cloudpickle==3.0.0
|
18 |
+
contourpy==1.2.1
|
19 |
+
cycler==0.12.1
|
20 |
+
diffusers @ git+https://github.com/huggingface/diffusers@8e1b7a084addc4711b8d9be2738441dfad680ce0
|
21 |
+
dnspython==2.6.1
|
22 |
+
docker-pycreds==0.4.0
|
23 |
+
email_validator==2.2.0
|
24 |
+
exceptiongroup==1.2.1
|
25 |
+
fastapi==0.111.0
|
26 |
+
fastapi-cli==0.0.4
|
27 |
+
ffmpy==0.3.2
|
28 |
+
filelock==3.13.1
|
29 |
+
fonttools==4.53.0
|
30 |
+
frozenlist==1.4.1
|
31 |
+
fsspec==2024.2.0
|
32 |
+
gdown==5.2.0
|
33 |
+
gitdb==4.0.11
|
34 |
+
GitPython==3.1.43
|
35 |
+
gradio
|
36 |
+
gradio_client
|
37 |
+
grpclib==0.4.7
|
38 |
+
h11==0.14.0
|
39 |
+
h2==4.1.0
|
40 |
+
h5py==3.11.0
|
41 |
+
hpack==4.0.0
|
42 |
+
httpcore==1.0.5
|
43 |
+
httptools==0.6.1
|
44 |
+
httpx==0.27.0
|
45 |
+
huggingface-hub==0.23.4
|
46 |
+
hydra-core==1.3.1
|
47 |
+
hyperframe==6.0.1
|
48 |
+
idna==3.7
|
49 |
+
imageio==2.34.1
|
50 |
+
importlib_metadata==7.1.0
|
51 |
+
importlib_resources==6.4.0
|
52 |
+
Jinja2==3.1.3
|
53 |
+
jsonschema==4.22.0
|
54 |
+
jsonschema-specifications==2023.12.1
|
55 |
+
kiwisolver==1.4.5
|
56 |
+
lazy_loader==0.4
|
57 |
+
lightning-utilities==0.11.2
|
58 |
+
markdown-it-py==3.0.0
|
59 |
+
MarkupSafe==2.1.5
|
60 |
+
matplotlib==3.9.0
|
61 |
+
mdurl==0.1.2
|
62 |
+
modal==0.63.2
|
63 |
+
mpmath==1.3.0
|
64 |
+
multidict==6.0.5
|
65 |
+
mutagen==1.47.0
|
66 |
+
networkx==3.2.1
|
67 |
+
numpy==1.26.3
|
68 |
+
nvidia-cublas-cu11==11.11.3.6
|
69 |
+
nvidia-cuda-cupti-cu11==11.8.87
|
70 |
+
nvidia-cuda-nvrtc-cu11==11.8.89
|
71 |
+
nvidia-cuda-runtime-cu11==11.8.89
|
72 |
+
nvidia-cudnn-cu11==8.7.0.84
|
73 |
+
nvidia-cufft-cu11==10.9.0.58
|
74 |
+
nvidia-curand-cu11==10.3.0.86
|
75 |
+
nvidia-cusolver-cu11==11.4.1.48
|
76 |
+
nvidia-cusparse-cu11==11.7.5.86
|
77 |
+
nvidia-nccl-cu11==2.20.5
|
78 |
+
nvidia-nvtx-cu11==11.8.86
|
79 |
+
omegaconf==2.3.0
|
80 |
+
opencv-python==4.10.0.82
|
81 |
+
orjson==3.10.5
|
82 |
+
packaging==24.1
|
83 |
+
pandas==2.2.2
|
84 |
+
pillow==10.2.0
|
85 |
+
platformdirs==4.2.2
|
86 |
+
protobuf==4.25.3
|
87 |
+
psutil==5.9.8
|
88 |
+
pycryptodomex==3.20.0
|
89 |
+
pydantic==2.7.4
|
90 |
+
pydantic_core==2.18.4
|
91 |
+
pydub==0.25.1
|
92 |
+
Pygments==2.18.0
|
93 |
+
pyparsing==3.1.2
|
94 |
+
PySocks==1.7.1
|
95 |
+
python-dateutil==2.9.0.post0
|
96 |
+
python-dotenv==1.0.1
|
97 |
+
python-multipart==0.0.9
|
98 |
+
pytube==15.0.0
|
99 |
+
pytube3==9.6.4
|
100 |
+
pytz==2024.1
|
101 |
+
PyYAML==6.0.1
|
102 |
+
referencing==0.35.1
|
103 |
+
regex==2024.5.15
|
104 |
+
requests==2.32.3
|
105 |
+
rich==13.7.1
|
106 |
+
rpds-py==0.18.1
|
107 |
+
ruff==0.5.0
|
108 |
+
safetensors==0.4.3
|
109 |
+
scikit-image==0.24.0
|
110 |
+
scipy==1.13.1
|
111 |
+
segment-anything==1.0
|
112 |
+
semantic-version==2.10.0
|
113 |
+
sentry-sdk==2.5.1
|
114 |
+
setproctitle==1.3.3
|
115 |
+
shellingham==1.5.4
|
116 |
+
sigtools==4.0.1
|
117 |
+
six==1.16.0
|
118 |
+
smmap==5.0.1
|
119 |
+
sniffio==1.3.1
|
120 |
+
soupsieve==2.5
|
121 |
+
spaces==0.29.3
|
122 |
+
starlette==0.37.2
|
123 |
+
submitit==1.5.1
|
124 |
+
sympy==1.12
|
125 |
+
synchronicity==0.6.7
|
126 |
+
tifffile==2024.6.18
|
127 |
+
tokenizers==0.19.1
|
128 |
+
toml==0.10.2
|
129 |
+
tomlkit==0.12.0
|
130 |
+
toolz==0.12.1
|
131 |
+
torch==2.3.0+cu118
|
132 |
+
torchaudio==2.3.1+cu118
|
133 |
+
torchmetrics==1.4.0.post0
|
134 |
+
torchvision==0.18.1+cu118
|
135 |
+
tqdm==4.66.4
|
136 |
+
transformers==4.41.2
|
137 |
+
triton==2.3.0
|
138 |
+
typer==0.12.3
|
139 |
+
types-certifi==2021.10.8.3
|
140 |
+
types-toml==0.10.8.20240310
|
141 |
+
typing_extensions==4.9.0
|
142 |
+
tzdata==2024.1
|
143 |
+
ujson==5.10.0
|
144 |
+
urllib3==2.2.1
|
145 |
+
uvicorn==0.30.1
|
146 |
+
uvloop==0.19.0
|
147 |
+
wandb==0.17.1
|
148 |
+
watchfiles==0.22.0
|
149 |
+
websockets==11.0.3
|
150 |
+
xformers==0.0.26.post1+cu118
|
151 |
+
yarl==1.9.4
|
152 |
+
youtube-dl==2021.12.17
|
153 |
+
yt-dlp==2024.5.27
|
154 |
+
zipp==3.19.2
|
svd.py
ADDED
@@ -0,0 +1,1316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
from typing import Dict, Optional, Tuple, Union, Any, Callable
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
9 |
+
from diffusers.loaders import UNet2DConditionLoadersMixin
|
10 |
+
from diffusers.utils import BaseOutput, logging
|
11 |
+
from diffusers.utils.torch_utils import is_torch_version
|
12 |
+
from diffusers.models.attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
|
13 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
14 |
+
from diffusers.models.modeling_utils import ModelMixin
|
15 |
+
from diffusers.models.unets.unet_3d_blocks import (
|
16 |
+
UNetMidBlockSpatioTemporal,
|
17 |
+
get_down_block as gdb,
|
18 |
+
get_up_block as gub,
|
19 |
+
)
|
20 |
+
from diffusers.models.resnet import (
|
21 |
+
Downsample2D,
|
22 |
+
SpatioTemporalResBlock,
|
23 |
+
Upsample2D,
|
24 |
+
)
|
25 |
+
from diffusers.models.transformers.transformer_temporal import TransformerSpatioTemporalModel
|
26 |
+
from diffusers.models.attention_processor import Attention
|
27 |
+
from diffusers.utils import deprecate
|
28 |
+
from diffusers.utils.import_utils import is_xformers_available
|
29 |
+
|
30 |
+
from network_utils import DragEmbedding, get_2d_sincos_pos_embed
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
33 |
+
|
34 |
+
|
35 |
+
if is_xformers_available():
|
36 |
+
import xformers
|
37 |
+
import xformers.ops
|
38 |
+
|
39 |
+
|
40 |
+
class AllToFirstXFormersAttnProcessor:
|
41 |
+
r"""
|
42 |
+
Processor for implementing memory efficient attention using xFormers.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
attention_op (`Callable`, *optional*, defaults to `None`):
|
46 |
+
The base
|
47 |
+
[operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
|
48 |
+
use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
|
49 |
+
operator.
|
50 |
+
"""
|
51 |
+
|
52 |
+
def __init__(self, attention_op: Optional[Callable] = None):
|
53 |
+
self.attention_op = attention_op
|
54 |
+
|
55 |
+
def __call__(
|
56 |
+
self,
|
57 |
+
attn: Attention,
|
58 |
+
hidden_states: torch.FloatTensor,
|
59 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
60 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
61 |
+
temb: Optional[torch.FloatTensor] = None,
|
62 |
+
*args,
|
63 |
+
**kwargs,
|
64 |
+
) -> torch.FloatTensor:
|
65 |
+
if len(args) > 0 or kwargs.get("scale", None) is not None:
|
66 |
+
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
|
67 |
+
deprecate("scale", "1.0.0", deprecation_message)
|
68 |
+
|
69 |
+
residual = hidden_states
|
70 |
+
|
71 |
+
if attn.spatial_norm is not None:
|
72 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
73 |
+
|
74 |
+
input_ndim = hidden_states.ndim
|
75 |
+
|
76 |
+
if input_ndim == 4:
|
77 |
+
batch_size, channel, height, width = hidden_states.shape
|
78 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
79 |
+
|
80 |
+
batch_size, key_tokens, _ = (
|
81 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
82 |
+
)
|
83 |
+
|
84 |
+
assert encoder_hidden_states is None
|
85 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, key_tokens, batch_size)
|
86 |
+
if attention_mask is not None:
|
87 |
+
# expand our mask's singleton query_tokens dimension:
|
88 |
+
# [batch*heads, 1, key_tokens] ->
|
89 |
+
# [batch*heads, query_tokens, key_tokens]
|
90 |
+
# so that it can be added as a bias onto the attention scores that xformers computes:
|
91 |
+
# [batch*heads, query_tokens, key_tokens]
|
92 |
+
# we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
|
93 |
+
_, query_tokens, _ = hidden_states.shape
|
94 |
+
attention_mask = attention_mask.expand(-1, query_tokens, -1)
|
95 |
+
|
96 |
+
if attn.group_norm is not None:
|
97 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
98 |
+
|
99 |
+
query = attn.to_q(hidden_states)
|
100 |
+
key = attn.to_k(hidden_states.view(-1, 14, *hidden_states.shape[1:])[:, 0])[:, None].expand(-1, 14, -1, -1).flatten(0, 1)
|
101 |
+
value = attn.to_v(hidden_states.view(-1, 14, *hidden_states.shape[1:])[:, 0])[:, None].expand(-1, 14, -1, -1).flatten(0, 1)
|
102 |
+
|
103 |
+
query = attn.head_to_batch_dim(query).contiguous()
|
104 |
+
key = attn.head_to_batch_dim(key).contiguous()
|
105 |
+
value = attn.head_to_batch_dim(value).contiguous()
|
106 |
+
|
107 |
+
hidden_states = xformers.ops.memory_efficient_attention(
|
108 |
+
query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
|
109 |
+
)
|
110 |
+
hidden_states = hidden_states.to(query.dtype)
|
111 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
112 |
+
|
113 |
+
# linear proj
|
114 |
+
hidden_states = attn.to_out[0](hidden_states)
|
115 |
+
# dropout
|
116 |
+
hidden_states = attn.to_out[1](hidden_states)
|
117 |
+
|
118 |
+
if input_ndim == 4:
|
119 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
120 |
+
|
121 |
+
if attn.residual_connection:
|
122 |
+
hidden_states = hidden_states + residual
|
123 |
+
|
124 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
125 |
+
|
126 |
+
return hidden_states
|
127 |
+
|
128 |
+
|
129 |
+
class CrossAttnDownBlockSpatioTemporalWithFlow(nn.Module):
|
130 |
+
def __init__(
|
131 |
+
self,
|
132 |
+
in_channels: int,
|
133 |
+
out_channels: int,
|
134 |
+
temb_channels: int,
|
135 |
+
flow_channels: int,
|
136 |
+
num_layers: int = 1,
|
137 |
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
138 |
+
num_attention_heads: int = 1,
|
139 |
+
cross_attention_dim: int = 1280,
|
140 |
+
add_downsample: bool = True,
|
141 |
+
num_frames: int = 14,
|
142 |
+
pos_embed_dim: int = 64,
|
143 |
+
drag_token_cross_attn: bool = True,
|
144 |
+
use_modulate: bool = True,
|
145 |
+
drag_embedder_out_channels = (256, 320, 320),
|
146 |
+
num_max_drags: int = 5,
|
147 |
+
):
|
148 |
+
super().__init__()
|
149 |
+
resnets = []
|
150 |
+
attentions = []
|
151 |
+
flow_convs = []
|
152 |
+
if drag_token_cross_attn:
|
153 |
+
drag_token_mlps = []
|
154 |
+
self.num_max_drags = num_max_drags
|
155 |
+
self.num_frames = num_frames
|
156 |
+
self.pos_embed_dim = pos_embed_dim
|
157 |
+
self.drag_token_cross_attn = drag_token_cross_attn
|
158 |
+
|
159 |
+
self.has_cross_attention = True
|
160 |
+
self.num_attention_heads = num_attention_heads
|
161 |
+
self.use_modulate = use_modulate
|
162 |
+
if isinstance(transformer_layers_per_block, int):
|
163 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
164 |
+
|
165 |
+
for i in range(num_layers):
|
166 |
+
in_channels = in_channels if i == 0 else out_channels
|
167 |
+
resnets.append(
|
168 |
+
SpatioTemporalResBlock(
|
169 |
+
in_channels=in_channels,
|
170 |
+
out_channels=out_channels,
|
171 |
+
temb_channels=temb_channels,
|
172 |
+
eps=1e-6,
|
173 |
+
)
|
174 |
+
)
|
175 |
+
attentions.append(
|
176 |
+
TransformerSpatioTemporalModel(
|
177 |
+
num_attention_heads,
|
178 |
+
out_channels // num_attention_heads,
|
179 |
+
in_channels=out_channels,
|
180 |
+
num_layers=transformer_layers_per_block[i],
|
181 |
+
cross_attention_dim=cross_attention_dim,
|
182 |
+
)
|
183 |
+
)
|
184 |
+
flow_convs.append(
|
185 |
+
DragEmbedding(
|
186 |
+
conditioning_channels=flow_channels,
|
187 |
+
conditioning_embedding_channels=out_channels * 2 if use_modulate else out_channels,
|
188 |
+
block_out_channels = drag_embedder_out_channels,
|
189 |
+
)
|
190 |
+
)
|
191 |
+
if drag_token_cross_attn:
|
192 |
+
drag_token_mlps.append(
|
193 |
+
nn.Sequential(
|
194 |
+
nn.Linear(pos_embed_dim * 2 + out_channels * 2, cross_attention_dim),
|
195 |
+
nn.SiLU(),
|
196 |
+
nn.Linear(cross_attention_dim, cross_attention_dim),
|
197 |
+
)
|
198 |
+
)
|
199 |
+
self.attentions = nn.ModuleList(attentions)
|
200 |
+
self.resnets = nn.ModuleList(resnets)
|
201 |
+
self.flow_convs = nn.ModuleList(flow_convs)
|
202 |
+
if drag_token_cross_attn:
|
203 |
+
self.drag_token_mlps = nn.ModuleList(drag_token_mlps)
|
204 |
+
if add_downsample:
|
205 |
+
self.downsamplers = nn.ModuleList(
|
206 |
+
[
|
207 |
+
Downsample2D(
|
208 |
+
out_channels,
|
209 |
+
use_conv=True,
|
210 |
+
out_channels=out_channels,
|
211 |
+
padding=1,
|
212 |
+
name="op",
|
213 |
+
)
|
214 |
+
]
|
215 |
+
)
|
216 |
+
else:
|
217 |
+
self.downsamplers = None
|
218 |
+
|
219 |
+
self.pos_embedding = {res: torch.tensor(get_2d_sincos_pos_embed(self.pos_embed_dim, res)) for res in [32, 16, 8, 4, 2]}
|
220 |
+
self.pos_embedding_prepared = False
|
221 |
+
|
222 |
+
self.gradient_checkpointing = False
|
223 |
+
|
224 |
+
def forward(
|
225 |
+
self,
|
226 |
+
hidden_states: torch.FloatTensor,
|
227 |
+
temb: Optional[torch.FloatTensor] = None,
|
228 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
229 |
+
image_only_indicator: Optional[torch.Tensor] = None,
|
230 |
+
flow: Optional[torch.Tensor] = None,
|
231 |
+
drag_original: Optional[torch.Tensor] = None, # (batch_frame, num_points, 4)
|
232 |
+
) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
|
233 |
+
output_states = ()
|
234 |
+
|
235 |
+
batch_frame = hidden_states.shape[0]
|
236 |
+
|
237 |
+
if self.drag_token_cross_attn:
|
238 |
+
encoder_hidden_states_ori = encoder_hidden_states
|
239 |
+
|
240 |
+
if not self.pos_embedding_prepared:
|
241 |
+
for res in self.pos_embedding:
|
242 |
+
self.pos_embedding[res] = self.pos_embedding[res].to(hidden_states)
|
243 |
+
self.pos_embedding_prepared = True
|
244 |
+
|
245 |
+
blocks = list(zip(self.resnets, self.attentions, self.flow_convs))
|
246 |
+
for bid, (resnet, attn, flow_conv) in enumerate(blocks):
|
247 |
+
if self.training and self.gradient_checkpointing: # TODO
|
248 |
+
|
249 |
+
def create_custom_forward(module, return_dict=None):
|
250 |
+
def custom_forward(*inputs):
|
251 |
+
if return_dict is not None:
|
252 |
+
return module(*inputs, return_dict=return_dict)
|
253 |
+
else:
|
254 |
+
return module(*inputs)
|
255 |
+
|
256 |
+
return custom_forward
|
257 |
+
|
258 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
259 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
260 |
+
create_custom_forward(resnet),
|
261 |
+
hidden_states,
|
262 |
+
temb,
|
263 |
+
image_only_indicator,
|
264 |
+
**ckpt_kwargs,
|
265 |
+
)
|
266 |
+
|
267 |
+
if flow is not None:
|
268 |
+
# flow shape is (batch_frame, 40, h, w)
|
269 |
+
drags = flow.view(-1, self.num_frames, *flow.shape[1:])
|
270 |
+
drags = drags.chunk(self.num_max_drags, dim=2) # (batch, frame, 4, h, w) x 10
|
271 |
+
drags = torch.stack(drags, dim=0) # 10, batch, frame, 4, h, w
|
272 |
+
invalid_flag = torch.all(drags == -1, dim=(2, 3, 4, 5))
|
273 |
+
if self.use_modulate:
|
274 |
+
scale, shift = flow_conv(flow).chunk(2, dim=1)
|
275 |
+
else:
|
276 |
+
scale = 0
|
277 |
+
shift = flow_conv(flow)
|
278 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
279 |
+
# print(self.drag_token_cross_attn)
|
280 |
+
if self.drag_token_cross_attn:
|
281 |
+
drag_token_mlp = self.drag_token_mlps[bid]
|
282 |
+
pos_embed = self.pos_embedding[scale.shape[-1]]
|
283 |
+
pos_embed = pos_embed.reshape(1, scale.shape[-1], scale.shape[-1], -1).permute(0, 3, 1, 2)
|
284 |
+
grid = (drag_original[..., :2] * 2 - 1)[:, None]
|
285 |
+
grid_end = (drag_original[..., 2:] * 2 - 1)[:, None]
|
286 |
+
drags_pos_start = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
287 |
+
drags_pos_end = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
288 |
+
features = F.grid_sample(hidden_states.detach(), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
289 |
+
features_end = F.grid_sample(hidden_states.detach(), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
290 |
+
|
291 |
+
drag_token_in = torch.cat([features, features_end, drags_pos_start, drags_pos_end], dim=1).permute(0, 2, 1)
|
292 |
+
drag_token_out = drag_token_mlp(drag_token_in)
|
293 |
+
# Mask the invalid drags
|
294 |
+
drag_token_out = drag_token_out.view(batch_frame // self.num_frames, self.num_frames, self.num_max_drags, -1)
|
295 |
+
drag_token_out = drag_token_out.permute(2, 0, 1, 3)
|
296 |
+
drag_token_out = drag_token_out.masked_fill(invalid_flag[..., None, None].expand_as(drag_token_out), 0)
|
297 |
+
drag_token_out = drag_token_out.permute(1, 2, 0, 3).flatten(0, 1)
|
298 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states_ori, drag_token_out], dim=1)
|
299 |
+
|
300 |
+
hidden_states = attn(
|
301 |
+
hidden_states,
|
302 |
+
encoder_hidden_states=encoder_hidden_states,
|
303 |
+
image_only_indicator=image_only_indicator,
|
304 |
+
return_dict=False,
|
305 |
+
)[0]
|
306 |
+
else:
|
307 |
+
hidden_states = resnet(
|
308 |
+
hidden_states,
|
309 |
+
temb,
|
310 |
+
image_only_indicator=image_only_indicator,
|
311 |
+
)
|
312 |
+
if flow is not None:
|
313 |
+
# flow shape is (batch_frame, 40, h, w)
|
314 |
+
drags = flow.view(-1, self.num_frames, *flow.shape[1:])
|
315 |
+
drags = drags.chunk(self.num_max_drags, dim=2) # (batch, frame, 4, h, w) x 10
|
316 |
+
drags = torch.stack(drags, dim=0) # 10, batch, frame, 4, h, w
|
317 |
+
invalid_flag = torch.all(drags == -1, dim=(2, 3, 4, 5))
|
318 |
+
if self.use_modulate:
|
319 |
+
scale, shift = flow_conv(flow).chunk(2, dim=1)
|
320 |
+
else:
|
321 |
+
scale = 0
|
322 |
+
shift = flow_conv(flow)
|
323 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
324 |
+
if self.drag_token_cross_attn:
|
325 |
+
drag_token_mlp = self.drag_token_mlps[bid]
|
326 |
+
pos_embed = self.pos_embedding[scale.shape[-1]]
|
327 |
+
pos_embed = pos_embed.reshape(1, scale.shape[-1], scale.shape[-1], -1).permute(0, 3, 1, 2)
|
328 |
+
grid = (drag_original[..., :2] * 2 - 1)[:, None]
|
329 |
+
grid_end = (drag_original[..., 2:] * 2 - 1)[:, None]
|
330 |
+
drags_pos_start = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
331 |
+
drags_pos_end = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
332 |
+
features = F.grid_sample(hidden_states.detach(), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
333 |
+
features_end = F.grid_sample(hidden_states.detach(), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
334 |
+
|
335 |
+
drag_token_in = torch.cat([features, features_end, drags_pos_start, drags_pos_end], dim=1).permute(0, 2, 1)
|
336 |
+
drag_token_out = drag_token_mlp(drag_token_in)
|
337 |
+
# Mask the invalid drags
|
338 |
+
drag_token_out = drag_token_out.view(batch_frame // self.num_frames, self.num_frames, self.num_max_drags, -1)
|
339 |
+
drag_token_out = drag_token_out.permute(2, 0, 1, 3)
|
340 |
+
drag_token_out = drag_token_out.masked_fill(invalid_flag[..., None, None].expand_as(drag_token_out), 0)
|
341 |
+
drag_token_out = drag_token_out.permute(1, 2, 0, 3).flatten(0, 1)
|
342 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states_ori, drag_token_out], dim=1)
|
343 |
+
hidden_states = attn(
|
344 |
+
hidden_states,
|
345 |
+
encoder_hidden_states=encoder_hidden_states,
|
346 |
+
image_only_indicator=image_only_indicator,
|
347 |
+
return_dict=False,
|
348 |
+
)[0]
|
349 |
+
|
350 |
+
output_states = output_states + (hidden_states,)
|
351 |
+
|
352 |
+
if self.downsamplers is not None:
|
353 |
+
for downsampler in self.downsamplers:
|
354 |
+
hidden_states = downsampler(hidden_states)
|
355 |
+
|
356 |
+
output_states = output_states + (hidden_states,)
|
357 |
+
|
358 |
+
return hidden_states, output_states
|
359 |
+
|
360 |
+
|
361 |
+
class CrossAttnUpBlockSpatioTemporalWithFlow(nn.Module):
|
362 |
+
def __init__(
|
363 |
+
self,
|
364 |
+
in_channels: int,
|
365 |
+
out_channels: int,
|
366 |
+
prev_output_channel: int,
|
367 |
+
temb_channels: int,
|
368 |
+
flow_channels: int,
|
369 |
+
resolution_idx: Optional[int] = None,
|
370 |
+
num_layers: int = 1,
|
371 |
+
transformer_layers_per_block: Union[int, Tuple[int]] = 1,
|
372 |
+
resnet_eps: float = 1e-6,
|
373 |
+
num_attention_heads: int = 1,
|
374 |
+
cross_attention_dim: int = 1280,
|
375 |
+
add_upsample: bool = True,
|
376 |
+
num_frames: int = 14,
|
377 |
+
pos_embed_dim: int = 64,
|
378 |
+
drag_token_cross_attn: bool = True,
|
379 |
+
use_modulate: bool = True,
|
380 |
+
drag_embedder_out_channels = (256, 320, 320),
|
381 |
+
num_max_drags: int = 5,
|
382 |
+
):
|
383 |
+
super().__init__()
|
384 |
+
resnets = []
|
385 |
+
attentions = []
|
386 |
+
flow_convs = []
|
387 |
+
if drag_token_cross_attn:
|
388 |
+
drag_token_mlps = []
|
389 |
+
self.num_max_drags = num_max_drags
|
390 |
+
|
391 |
+
self.drag_token_cross_attn = drag_token_cross_attn
|
392 |
+
|
393 |
+
self.num_frames = num_frames
|
394 |
+
self.pos_embed_dim = pos_embed_dim
|
395 |
+
|
396 |
+
self.has_cross_attention = True
|
397 |
+
self.num_attention_heads = num_attention_heads
|
398 |
+
self.use_modulate = use_modulate
|
399 |
+
|
400 |
+
if isinstance(transformer_layers_per_block, int):
|
401 |
+
transformer_layers_per_block = [transformer_layers_per_block] * num_layers
|
402 |
+
|
403 |
+
for i in range(num_layers):
|
404 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
405 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
406 |
+
|
407 |
+
resnets.append(
|
408 |
+
SpatioTemporalResBlock(
|
409 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
410 |
+
out_channels=out_channels,
|
411 |
+
temb_channels=temb_channels,
|
412 |
+
eps=resnet_eps,
|
413 |
+
)
|
414 |
+
)
|
415 |
+
attentions.append(
|
416 |
+
TransformerSpatioTemporalModel(
|
417 |
+
num_attention_heads,
|
418 |
+
out_channels // num_attention_heads,
|
419 |
+
in_channels=out_channels,
|
420 |
+
num_layers=transformer_layers_per_block[i],
|
421 |
+
cross_attention_dim=cross_attention_dim,
|
422 |
+
)
|
423 |
+
)
|
424 |
+
flow_convs.append(
|
425 |
+
DragEmbedding(
|
426 |
+
conditioning_channels=flow_channels,
|
427 |
+
conditioning_embedding_channels=out_channels * 2 if use_modulate else out_channels,
|
428 |
+
block_out_channels = drag_embedder_out_channels,
|
429 |
+
)
|
430 |
+
)
|
431 |
+
if drag_token_cross_attn:
|
432 |
+
drag_token_mlps.append(
|
433 |
+
nn.Sequential(
|
434 |
+
nn.Linear(pos_embed_dim * 2 + out_channels * 2, cross_attention_dim),
|
435 |
+
nn.SiLU(),
|
436 |
+
nn.Linear(cross_attention_dim, cross_attention_dim),
|
437 |
+
)
|
438 |
+
)
|
439 |
+
self.attentions = nn.ModuleList(attentions)
|
440 |
+
self.resnets = nn.ModuleList(resnets)
|
441 |
+
self.flow_convs = nn.ModuleList(flow_convs)
|
442 |
+
|
443 |
+
if drag_token_cross_attn:
|
444 |
+
self.drag_token_mlps = nn.ModuleList(drag_token_mlps)
|
445 |
+
if add_upsample:
|
446 |
+
self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
|
447 |
+
else:
|
448 |
+
self.upsamplers = None
|
449 |
+
|
450 |
+
self.pos_embedding = {res: torch.tensor(get_2d_sincos_pos_embed(pos_embed_dim, res)) for res in [32, 16, 8, 4, 2]}
|
451 |
+
self.pos_embedding_prepared = False
|
452 |
+
|
453 |
+
self.gradient_checkpointing = False
|
454 |
+
self.resolution_idx = resolution_idx
|
455 |
+
|
456 |
+
def forward(
|
457 |
+
self,
|
458 |
+
hidden_states: torch.FloatTensor,
|
459 |
+
res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
|
460 |
+
temb: Optional[torch.FloatTensor] = None,
|
461 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
462 |
+
image_only_indicator: Optional[torch.Tensor] = None,
|
463 |
+
flow: Optional[torch.Tensor] = None,
|
464 |
+
drag_original: Optional[torch.Tensor] = None, # (batch_frame, num_points, 4)
|
465 |
+
) -> torch.FloatTensor:
|
466 |
+
batch_frame = hidden_states.shape[0]
|
467 |
+
|
468 |
+
if self.drag_token_cross_attn:
|
469 |
+
encoder_hidden_states_ori = encoder_hidden_states
|
470 |
+
|
471 |
+
if not self.pos_embedding_prepared:
|
472 |
+
for res in self.pos_embedding:
|
473 |
+
self.pos_embedding[res] = self.pos_embedding[res].to(hidden_states)
|
474 |
+
self.pos_embedding_prepared = True
|
475 |
+
|
476 |
+
for bid, (resnet, attn, flow_conv) in enumerate(zip(self.resnets, self.attentions, self.flow_convs)):
|
477 |
+
# pop res hidden states
|
478 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
479 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
480 |
+
|
481 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
482 |
+
|
483 |
+
if self.training and self.gradient_checkpointing: # TODO
|
484 |
+
def create_custom_forward(module, return_dict=None):
|
485 |
+
def custom_forward(*inputs):
|
486 |
+
if return_dict is not None:
|
487 |
+
return module(*inputs, return_dict=return_dict)
|
488 |
+
else:
|
489 |
+
return module(*inputs)
|
490 |
+
|
491 |
+
return custom_forward
|
492 |
+
|
493 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
494 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
495 |
+
create_custom_forward(resnet),
|
496 |
+
hidden_states,
|
497 |
+
temb,
|
498 |
+
image_only_indicator,
|
499 |
+
**ckpt_kwargs,
|
500 |
+
)
|
501 |
+
if flow is not None:
|
502 |
+
# flow shape is (batch_frame, 40, h, w)
|
503 |
+
drags = flow.view(-1, self.num_frames, *flow.shape[1:])
|
504 |
+
drags = drags.chunk(self.num_max_drags, dim=2) # (batch, frame, 4, h, w) x 10
|
505 |
+
drags = torch.stack(drags, dim=0) # 10, batch, frame, 4, h, w
|
506 |
+
invalid_flag = torch.all(drags == -1, dim=(2, 3, 4, 5))
|
507 |
+
if self.use_modulate:
|
508 |
+
scale, shift = flow_conv(flow).chunk(2, dim=1)
|
509 |
+
else:
|
510 |
+
scale = 0
|
511 |
+
shift = flow_conv(flow)
|
512 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
513 |
+
if self.drag_token_cross_attn:
|
514 |
+
drag_token_mlp = self.drag_token_mlps[bid]
|
515 |
+
pos_embed = self.pos_embedding[scale.shape[-1]]
|
516 |
+
pos_embed = pos_embed.reshape(1, scale.shape[-1], scale.shape[-1], -1).permute(0, 3, 1, 2)
|
517 |
+
grid = (drag_original[..., :2] * 2 - 1)[:, None]
|
518 |
+
grid_end = (drag_original[..., 2:] * 2 - 1)[:, None]
|
519 |
+
drags_pos_start = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
520 |
+
drags_pos_end = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
521 |
+
features = F.grid_sample(hidden_states.detach(), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
522 |
+
features_end = F.grid_sample(hidden_states.detach(), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
523 |
+
|
524 |
+
drag_token_in = torch.cat([features, features_end, drags_pos_start, drags_pos_end], dim=1).permute(0, 2, 1)
|
525 |
+
drag_token_out = drag_token_mlp(drag_token_in)
|
526 |
+
# Mask the invalid drags
|
527 |
+
drag_token_out = drag_token_out.view(batch_frame // self.num_frames, self.num_frames, self.num_max_drags, -1)
|
528 |
+
drag_token_out = drag_token_out.permute(2, 0, 1, 3)
|
529 |
+
drag_token_out = drag_token_out.masked_fill(invalid_flag[..., None, None].expand_as(drag_token_out), 0)
|
530 |
+
drag_token_out = drag_token_out.permute(1, 2, 0, 3).flatten(0, 1)
|
531 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states_ori, drag_token_out], dim=1)
|
532 |
+
|
533 |
+
hidden_states = attn(
|
534 |
+
hidden_states,
|
535 |
+
encoder_hidden_states=encoder_hidden_states,
|
536 |
+
image_only_indicator=image_only_indicator,
|
537 |
+
return_dict=False,
|
538 |
+
)[0]
|
539 |
+
else:
|
540 |
+
hidden_states = resnet(
|
541 |
+
hidden_states,
|
542 |
+
temb,
|
543 |
+
image_only_indicator=image_only_indicator,
|
544 |
+
)
|
545 |
+
if flow is not None:
|
546 |
+
# flow shape is (batch_frame, 40, h, w)
|
547 |
+
drags = flow.view(-1, self.num_frames, *flow.shape[1:])
|
548 |
+
drags = drags.chunk(self.num_max_drags, dim=2) # (batch, frame, 4, h, w) x 10
|
549 |
+
drags = torch.stack(drags, dim=0) # 10, batch, frame, 4, h, w
|
550 |
+
invalid_flag = torch.all(drags == -1, dim=(2, 3, 4, 5))
|
551 |
+
if self.use_modulate:
|
552 |
+
scale, shift = flow_conv(flow).chunk(2, dim=1)
|
553 |
+
else:
|
554 |
+
scale = 0
|
555 |
+
shift = flow_conv(flow)
|
556 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
557 |
+
if self.drag_token_cross_attn:
|
558 |
+
drag_token_mlp = self.drag_token_mlps[bid]
|
559 |
+
pos_embed = self.pos_embedding[scale.shape[-1]]
|
560 |
+
pos_embed = pos_embed.reshape(1, scale.shape[-1], scale.shape[-1], -1).permute(0, 3, 1, 2)
|
561 |
+
grid = (drag_original[..., :2] * 2 - 1)[:, None]
|
562 |
+
grid_end = (drag_original[..., 2:] * 2 - 1)[:, None]
|
563 |
+
drags_pos_start = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
564 |
+
drags_pos_end = F.grid_sample(pos_embed.repeat(batch_frame, 1, 1, 1), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
565 |
+
features = F.grid_sample(hidden_states.detach(), grid, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
566 |
+
features_end = F.grid_sample(hidden_states.detach(), grid_end, padding_mode="border", mode="bilinear", align_corners=False).squeeze(dim=2)
|
567 |
+
|
568 |
+
drag_token_in = torch.cat([features, features_end, drags_pos_start, drags_pos_end], dim=1).permute(0, 2, 1)
|
569 |
+
drag_token_out = drag_token_mlp(drag_token_in)
|
570 |
+
# Mask the invalid drags
|
571 |
+
drag_token_out = drag_token_out.view(batch_frame // self.num_frames, self.num_frames, self.num_max_drags, -1)
|
572 |
+
drag_token_out = drag_token_out.permute(2, 0, 1, 3)
|
573 |
+
drag_token_out = drag_token_out.masked_fill(invalid_flag[..., None, None].expand_as(drag_token_out), 0)
|
574 |
+
drag_token_out = drag_token_out.permute(1, 2, 0, 3).flatten(0, 1)
|
575 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states_ori, drag_token_out], dim=1)
|
576 |
+
|
577 |
+
hidden_states = attn(
|
578 |
+
hidden_states,
|
579 |
+
encoder_hidden_states=encoder_hidden_states,
|
580 |
+
image_only_indicator=image_only_indicator,
|
581 |
+
return_dict=False,
|
582 |
+
)[0]
|
583 |
+
|
584 |
+
if self.upsamplers is not None:
|
585 |
+
for upsampler in self.upsamplers:
|
586 |
+
hidden_states = upsampler(hidden_states)
|
587 |
+
|
588 |
+
return hidden_states
|
589 |
+
|
590 |
+
|
591 |
+
def get_down_block(
|
592 |
+
with_concatenated_flow: bool = False,
|
593 |
+
*args,
|
594 |
+
**kwargs,
|
595 |
+
):
|
596 |
+
NEEDED_KEYS = [
|
597 |
+
"in_channels",
|
598 |
+
"out_channels",
|
599 |
+
"temb_channels",
|
600 |
+
"flow_channels",
|
601 |
+
"num_layers",
|
602 |
+
"transformer_layers_per_block",
|
603 |
+
"num_attention_heads",
|
604 |
+
"cross_attention_dim",
|
605 |
+
"add_downsample",
|
606 |
+
"pos_embed_dim",
|
607 |
+
'use_modulate',
|
608 |
+
"drag_token_cross_attn",
|
609 |
+
"drag_embedder_out_channels",
|
610 |
+
"num_max_drags",
|
611 |
+
]
|
612 |
+
if not with_concatenated_flow or args[0] == "DownBlockSpatioTemporal":
|
613 |
+
kwargs.pop("flow_channels", None)
|
614 |
+
kwargs.pop("pos_embed_dim", None)
|
615 |
+
kwargs.pop("use_modulate", None)
|
616 |
+
kwargs.pop("drag_token_cross_attn", None)
|
617 |
+
kwargs.pop("drag_embedder_out_channels", None)
|
618 |
+
kwargs.pop("num_max_drags", None)
|
619 |
+
return gdb(*args, **kwargs)
|
620 |
+
elif args[0] == "CrossAttnDownBlockSpatioTemporal":
|
621 |
+
for key in list(kwargs.keys()):
|
622 |
+
if key not in NEEDED_KEYS:
|
623 |
+
kwargs.pop(key, None)
|
624 |
+
return CrossAttnDownBlockSpatioTemporalWithFlow(*args[1:], **kwargs)
|
625 |
+
else:
|
626 |
+
raise ValueError(f"Unknown block type {args[0]}")
|
627 |
+
|
628 |
+
|
629 |
+
def get_up_block(
|
630 |
+
with_concatenated_flow: bool = False,
|
631 |
+
*args,
|
632 |
+
**kwargs,
|
633 |
+
):
|
634 |
+
NEEDED_KEYS = [
|
635 |
+
"in_channels",
|
636 |
+
"out_channels",
|
637 |
+
"prev_output_channel",
|
638 |
+
"temb_channels",
|
639 |
+
"flow_channels",
|
640 |
+
"resolution_idx",
|
641 |
+
"num_layers",
|
642 |
+
"transformer_layers_per_block",
|
643 |
+
"resnet_eps",
|
644 |
+
"num_attention_heads",
|
645 |
+
"cross_attention_dim",
|
646 |
+
"add_upsample",
|
647 |
+
"pos_embed_dim",
|
648 |
+
"use_modulate",
|
649 |
+
"drag_token_cross_attn",
|
650 |
+
"drag_embedder_out_channels",
|
651 |
+
"num_max_drags",
|
652 |
+
]
|
653 |
+
if not with_concatenated_flow or args[0] == "UpBlockSpatioTemporal":
|
654 |
+
kwargs.pop("flow_channels", None)
|
655 |
+
kwargs.pop("pos_embed_dim", None)
|
656 |
+
kwargs.pop("use_modulate", None)
|
657 |
+
kwargs.pop("drag_token_cross_attn", None)
|
658 |
+
kwargs.pop("drag_embedder_out_channels", None)
|
659 |
+
kwargs.pop("num_max_drags", None)
|
660 |
+
return gub(*args, **kwargs)
|
661 |
+
elif args[0] == "CrossAttnUpBlockSpatioTemporal":
|
662 |
+
for key in list(kwargs.keys()):
|
663 |
+
if key not in NEEDED_KEYS:
|
664 |
+
kwargs.pop(key, None)
|
665 |
+
return CrossAttnUpBlockSpatioTemporalWithFlow(*args[1:], **kwargs)
|
666 |
+
else:
|
667 |
+
raise ValueError(f"Unknown block type {args[0]}")
|
668 |
+
|
669 |
+
|
670 |
+
@dataclass
|
671 |
+
class UNetSpatioTemporalConditionOutput(BaseOutput):
|
672 |
+
"""
|
673 |
+
The output of [`UNetSpatioTemporalConditionModel`].
|
674 |
+
|
675 |
+
Args:
|
676 |
+
sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
677 |
+
The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
|
678 |
+
"""
|
679 |
+
|
680 |
+
sample: torch.FloatTensor = None
|
681 |
+
|
682 |
+
|
683 |
+
class UNetDragSpatioTemporalConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
684 |
+
r"""
|
685 |
+
A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and
|
686 |
+
returns a sample shaped output.
|
687 |
+
|
688 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
689 |
+
for all models (such as downloading or saving).
|
690 |
+
|
691 |
+
Parameters:
|
692 |
+
sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
|
693 |
+
Height and width of input/output sample.
|
694 |
+
in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample.
|
695 |
+
out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
|
696 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`):
|
697 |
+
The tuple of downsample blocks to use.
|
698 |
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`):
|
699 |
+
The tuple of upsample blocks to use.
|
700 |
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
|
701 |
+
The tuple of output channels for each block.
|
702 |
+
addition_time_embed_dim: (`int`, defaults to 256):
|
703 |
+
Dimension to to encode the additional time ids.
|
704 |
+
projection_class_embeddings_input_dim (`int`, defaults to 768):
|
705 |
+
The dimension of the projection of encoded `added_time_ids`.
|
706 |
+
layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
|
707 |
+
cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
|
708 |
+
The dimension of the cross attention features.
|
709 |
+
transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
|
710 |
+
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
|
711 |
+
[`~models.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`],
|
712 |
+
[`~models.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`],
|
713 |
+
[`~models.unet_3d_blocks.UNetMidBlockSpatioTemporal`].
|
714 |
+
num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`):
|
715 |
+
The number of attention heads.
|
716 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
717 |
+
"""
|
718 |
+
|
719 |
+
_supports_gradient_checkpointing = True
|
720 |
+
|
721 |
+
@register_to_config
|
722 |
+
def __init__(
|
723 |
+
self,
|
724 |
+
sample_size: Optional[int] = None,
|
725 |
+
in_channels: int = 8,
|
726 |
+
out_channels: int = 4,
|
727 |
+
down_block_types: Tuple[str] = (
|
728 |
+
"CrossAttnDownBlockSpatioTemporal",
|
729 |
+
"CrossAttnDownBlockSpatioTemporal",
|
730 |
+
"CrossAttnDownBlockSpatioTemporal",
|
731 |
+
"DownBlockSpatioTemporal",
|
732 |
+
),
|
733 |
+
up_block_types: Tuple[str] = (
|
734 |
+
"UpBlockSpatioTemporal",
|
735 |
+
"CrossAttnUpBlockSpatioTemporal",
|
736 |
+
"CrossAttnUpBlockSpatioTemporal",
|
737 |
+
"CrossAttnUpBlockSpatioTemporal",
|
738 |
+
),
|
739 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
740 |
+
addition_time_embed_dim: int = 256,
|
741 |
+
projection_class_embeddings_input_dim: int = 768,
|
742 |
+
layers_per_block: Union[int, Tuple[int]] = 2,
|
743 |
+
cross_attention_dim: Union[int, Tuple[int]] = 1024,
|
744 |
+
transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
|
745 |
+
num_attention_heads: Union[int, Tuple[int]] = (5, 10, 20, 20),
|
746 |
+
num_frames: int = 25,
|
747 |
+
num_drags: int = 10,
|
748 |
+
cond_dropout_prob: float = 0.1,
|
749 |
+
pos_embed_dim: int = 64,
|
750 |
+
drag_token_cross_attn: bool = True,
|
751 |
+
|
752 |
+
use_modulate: bool = True,
|
753 |
+
|
754 |
+
drag_embedder_out_channels = (256, 320, 320),
|
755 |
+
|
756 |
+
cross_attn_with_ref: bool = True,
|
757 |
+
double_batch: bool = False,
|
758 |
+
):
|
759 |
+
super().__init__()
|
760 |
+
|
761 |
+
self.sample_size = sample_size
|
762 |
+
self.cond_dropout_prob = cond_dropout_prob
|
763 |
+
self.drag_token_cross_attn = drag_token_cross_attn
|
764 |
+
|
765 |
+
self.pos_embed_dim = pos_embed_dim
|
766 |
+
|
767 |
+
self.use_modulate = use_modulate
|
768 |
+
|
769 |
+
self.cross_attn_with_ref = cross_attn_with_ref
|
770 |
+
self.double_batch = double_batch
|
771 |
+
|
772 |
+
flow_channels = 6 * num_drags
|
773 |
+
|
774 |
+
# Check inputs
|
775 |
+
if len(down_block_types) != len(up_block_types):
|
776 |
+
raise ValueError(
|
777 |
+
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}."
|
778 |
+
)
|
779 |
+
|
780 |
+
if len(block_out_channels) != len(down_block_types):
|
781 |
+
raise ValueError(
|
782 |
+
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}."
|
783 |
+
)
|
784 |
+
|
785 |
+
if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
|
786 |
+
raise ValueError(
|
787 |
+
f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
|
788 |
+
)
|
789 |
+
|
790 |
+
if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
|
791 |
+
raise ValueError(
|
792 |
+
f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
|
793 |
+
)
|
794 |
+
|
795 |
+
if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
|
796 |
+
raise ValueError(
|
797 |
+
f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
|
798 |
+
)
|
799 |
+
|
800 |
+
# input
|
801 |
+
self.conv_in = nn.Conv2d(
|
802 |
+
in_channels,
|
803 |
+
block_out_channels[0],
|
804 |
+
kernel_size=3,
|
805 |
+
padding=1,
|
806 |
+
)
|
807 |
+
|
808 |
+
# time
|
809 |
+
time_embed_dim = block_out_channels[0] * 4
|
810 |
+
|
811 |
+
self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0)
|
812 |
+
timestep_input_dim = block_out_channels[0]
|
813 |
+
|
814 |
+
self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
815 |
+
|
816 |
+
self.down_blocks = nn.ModuleList([])
|
817 |
+
self.up_blocks = nn.ModuleList([])
|
818 |
+
|
819 |
+
if isinstance(num_attention_heads, int):
|
820 |
+
num_attention_heads = (num_attention_heads,) * len(down_block_types)
|
821 |
+
|
822 |
+
if isinstance(cross_attention_dim, int):
|
823 |
+
cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
|
824 |
+
|
825 |
+
if isinstance(layers_per_block, int):
|
826 |
+
layers_per_block = [layers_per_block] * len(down_block_types)
|
827 |
+
|
828 |
+
if isinstance(transformer_layers_per_block, int):
|
829 |
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
830 |
+
|
831 |
+
blocks_time_embed_dim = time_embed_dim
|
832 |
+
|
833 |
+
# down
|
834 |
+
output_channel = block_out_channels[0]
|
835 |
+
for i, down_block_type in enumerate(down_block_types):
|
836 |
+
input_channel = output_channel
|
837 |
+
output_channel = block_out_channels[i]
|
838 |
+
is_final_block = i == len(block_out_channels) - 1
|
839 |
+
|
840 |
+
down_block = get_down_block(
|
841 |
+
True,
|
842 |
+
down_block_type,
|
843 |
+
num_layers=layers_per_block[i],
|
844 |
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
845 |
+
in_channels=input_channel,
|
846 |
+
out_channels=output_channel,
|
847 |
+
temb_channels=blocks_time_embed_dim,
|
848 |
+
add_downsample=not is_final_block,
|
849 |
+
resnet_eps=1e-5,
|
850 |
+
cross_attention_dim=cross_attention_dim[i],
|
851 |
+
num_attention_heads=num_attention_heads[i],
|
852 |
+
resnet_act_fn="silu",
|
853 |
+
flow_channels=flow_channels,
|
854 |
+
pos_embed_dim=pos_embed_dim,
|
855 |
+
use_modulate=use_modulate,
|
856 |
+
drag_token_cross_attn=drag_token_cross_attn,
|
857 |
+
drag_embedder_out_channels=drag_embedder_out_channels,
|
858 |
+
num_max_drags=num_drags,
|
859 |
+
)
|
860 |
+
self.down_blocks.append(down_block)
|
861 |
+
|
862 |
+
# mid
|
863 |
+
self.mid_block = UNetMidBlockSpatioTemporal(
|
864 |
+
block_out_channels[-1],
|
865 |
+
temb_channels=blocks_time_embed_dim,
|
866 |
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
867 |
+
cross_attention_dim=cross_attention_dim[-1],
|
868 |
+
num_attention_heads=num_attention_heads[-1],
|
869 |
+
)
|
870 |
+
|
871 |
+
# count how many layers upsample the images
|
872 |
+
self.num_upsamplers = 0
|
873 |
+
|
874 |
+
# up
|
875 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
876 |
+
reversed_num_attention_heads = list(reversed(num_attention_heads))
|
877 |
+
reversed_layers_per_block = list(reversed(layers_per_block))
|
878 |
+
reversed_cross_attention_dim = list(reversed(cross_attention_dim))
|
879 |
+
reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
|
880 |
+
|
881 |
+
output_channel = reversed_block_out_channels[0]
|
882 |
+
for i, up_block_type in enumerate(up_block_types):
|
883 |
+
is_final_block = i == len(block_out_channels) - 1
|
884 |
+
|
885 |
+
prev_output_channel = output_channel
|
886 |
+
output_channel = reversed_block_out_channels[i]
|
887 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
888 |
+
|
889 |
+
# add upsample block for all BUT final layer
|
890 |
+
if not is_final_block:
|
891 |
+
add_upsample = True
|
892 |
+
self.num_upsamplers += 1
|
893 |
+
else:
|
894 |
+
add_upsample = False
|
895 |
+
|
896 |
+
up_block = get_up_block(
|
897 |
+
True,
|
898 |
+
up_block_type,
|
899 |
+
num_layers=reversed_layers_per_block[i] + 1,
|
900 |
+
transformer_layers_per_block=reversed_transformer_layers_per_block[i],
|
901 |
+
in_channels=input_channel,
|
902 |
+
out_channels=output_channel,
|
903 |
+
prev_output_channel=prev_output_channel,
|
904 |
+
temb_channels=blocks_time_embed_dim,
|
905 |
+
add_upsample=add_upsample,
|
906 |
+
resnet_eps=1e-5,
|
907 |
+
resolution_idx=i,
|
908 |
+
cross_attention_dim=reversed_cross_attention_dim[i],
|
909 |
+
num_attention_heads=reversed_num_attention_heads[i],
|
910 |
+
resnet_act_fn="silu",
|
911 |
+
flow_channels=flow_channels,
|
912 |
+
pos_embed_dim=pos_embed_dim,
|
913 |
+
use_modulate=use_modulate,
|
914 |
+
drag_token_cross_attn=drag_token_cross_attn,
|
915 |
+
drag_embedder_out_channels=drag_embedder_out_channels,
|
916 |
+
num_max_drags=num_drags,
|
917 |
+
)
|
918 |
+
self.up_blocks.append(up_block)
|
919 |
+
prev_output_channel = output_channel
|
920 |
+
|
921 |
+
# out
|
922 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-5)
|
923 |
+
self.conv_act = nn.SiLU()
|
924 |
+
|
925 |
+
self.conv_out = nn.Conv2d(
|
926 |
+
block_out_channels[0],
|
927 |
+
out_channels,
|
928 |
+
kernel_size=3,
|
929 |
+
padding=1,
|
930 |
+
)
|
931 |
+
|
932 |
+
self.num_drags = num_drags
|
933 |
+
|
934 |
+
self.pos_embedding = {res: torch.tensor(get_2d_sincos_pos_embed(self.pos_embed_dim, res)) for res in [32, 16, 8, 4, 2]}
|
935 |
+
self.pos_embedding_prepared = False
|
936 |
+
|
937 |
+
@property
|
938 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
939 |
+
r"""
|
940 |
+
Returns:
|
941 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
942 |
+
indexed by its weight name.
|
943 |
+
"""
|
944 |
+
# set recursively
|
945 |
+
processors = {}
|
946 |
+
|
947 |
+
def fn_recursive_add_processors(
|
948 |
+
name: str,
|
949 |
+
module: torch.nn.Module,
|
950 |
+
processors: Dict[str, AttentionProcessor],
|
951 |
+
):
|
952 |
+
if hasattr(module, "get_processor"):
|
953 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
954 |
+
|
955 |
+
for sub_name, child in module.named_children():
|
956 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
957 |
+
|
958 |
+
return processors
|
959 |
+
|
960 |
+
for name, module in self.named_children():
|
961 |
+
fn_recursive_add_processors(name, module, processors)
|
962 |
+
|
963 |
+
return processors
|
964 |
+
|
965 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
966 |
+
r"""
|
967 |
+
Sets the attention processor to use to compute attention.
|
968 |
+
|
969 |
+
Parameters:
|
970 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
971 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
972 |
+
for **all** `Attention` layers.
|
973 |
+
|
974 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
975 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
976 |
+
|
977 |
+
"""
|
978 |
+
count = len(self.attn_processors.keys())
|
979 |
+
|
980 |
+
if isinstance(processor, dict) and len(processor) != count:
|
981 |
+
raise ValueError(
|
982 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
983 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
984 |
+
)
|
985 |
+
|
986 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
987 |
+
if hasattr(module, "set_processor"):
|
988 |
+
if not isinstance(processor, dict):
|
989 |
+
module.set_processor(processor)
|
990 |
+
else:
|
991 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
992 |
+
|
993 |
+
for sub_name, child in module.named_children():
|
994 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
995 |
+
|
996 |
+
for name, module in self.named_children():
|
997 |
+
fn_recursive_attn_processor(name, module, processor)
|
998 |
+
|
999 |
+
def set_default_attn_processor(self):
|
1000 |
+
"""
|
1001 |
+
Disables custom attention processors and sets the default attention implementation.
|
1002 |
+
"""
|
1003 |
+
if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
1004 |
+
processor = AttnProcessor()
|
1005 |
+
else:
|
1006 |
+
raise ValueError(
|
1007 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
1008 |
+
)
|
1009 |
+
|
1010 |
+
self.set_attn_processor(processor)
|
1011 |
+
|
1012 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
1013 |
+
if hasattr(module, "gradient_checkpointing"):
|
1014 |
+
module.gradient_checkpointing = value
|
1015 |
+
|
1016 |
+
# Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
|
1017 |
+
def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
|
1018 |
+
"""
|
1019 |
+
Sets the attention processor to use [feed forward
|
1020 |
+
chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
|
1021 |
+
|
1022 |
+
Parameters:
|
1023 |
+
chunk_size (`int`, *optional*):
|
1024 |
+
The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
|
1025 |
+
over each tensor of dim=`dim`.
|
1026 |
+
dim (`int`, *optional*, defaults to `0`):
|
1027 |
+
The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
|
1028 |
+
or dim=1 (sequence length).
|
1029 |
+
"""
|
1030 |
+
if dim not in [0, 1]:
|
1031 |
+
raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
|
1032 |
+
|
1033 |
+
# By default chunk size is 1
|
1034 |
+
chunk_size = chunk_size or 1
|
1035 |
+
|
1036 |
+
def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
|
1037 |
+
if hasattr(module, "set_chunk_feed_forward"):
|
1038 |
+
module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
|
1039 |
+
|
1040 |
+
for child in module.children():
|
1041 |
+
fn_recursive_feed_forward(child, chunk_size, dim)
|
1042 |
+
|
1043 |
+
for module in self.children():
|
1044 |
+
fn_recursive_feed_forward(module, chunk_size, dim)
|
1045 |
+
|
1046 |
+
def _convert_drag_to_concatting_image(self, drags: torch.Tensor, current_resolution: int) -> torch.Tensor:
|
1047 |
+
batch_size, num_frames, num_points, _ = drags.shape
|
1048 |
+
num_channels = 6
|
1049 |
+
concatting_image = -torch.ones(
|
1050 |
+
batch_size, num_frames, num_channels * num_points, current_resolution, current_resolution
|
1051 |
+
).to(drags)
|
1052 |
+
|
1053 |
+
not_all_zeros = drags.any(dim=-1).repeat_interleave(num_channels, dim=-1)[..., None, None]
|
1054 |
+
y_grid, x_grid = torch.meshgrid(torch.arange(current_resolution), torch.arange(current_resolution), indexing='ij')
|
1055 |
+
y_grid = y_grid.to(drags)[None, None, None] # (1, 1, 1, res, res)
|
1056 |
+
x_grid = x_grid.to(drags)[None, None, None] # (1, 1, 1, res, res)
|
1057 |
+
x0 = (drags[..., 0] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1058 |
+
x_src = (drags[..., 0] * current_resolution - x0)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1059 |
+
x0 = x0[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1060 |
+
x0 = torch.stack([
|
1061 |
+
x0, x0,
|
1062 |
+
torch.zeros_like(x0) - 1, torch.zeros_like(x0) - 1,
|
1063 |
+
torch.zeros_like(x0) - 1, torch.zeros_like(x0) - 1,
|
1064 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1065 |
+
|
1066 |
+
y0 = (drags[..., 1] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1067 |
+
y_src = (drags[..., 1] * current_resolution - y0)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1068 |
+
y0 = y0[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1069 |
+
y0 = torch.stack([
|
1070 |
+
y0, y0,
|
1071 |
+
torch.zeros_like(y0) - 1, torch.zeros_like(y0) - 1,
|
1072 |
+
torch.zeros_like(y0) - 1, torch.zeros_like(y0) - 1,
|
1073 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1074 |
+
|
1075 |
+
x1 = (drags[..., 2] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1076 |
+
x_tgt = (drags[..., 2] * current_resolution - x1)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1077 |
+
x1 = x1[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1078 |
+
x1 = torch.stack([
|
1079 |
+
torch.zeros_like(x1) - 1, torch.zeros_like(x1) - 1,
|
1080 |
+
x1, x1,
|
1081 |
+
torch.zeros_like(x1) - 1, torch.zeros_like(x1) - 1
|
1082 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1083 |
+
|
1084 |
+
y1 = (drags[..., 3] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1085 |
+
y_tgt = (drags[..., 3] * current_resolution - y1)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1086 |
+
y1 = y1[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1087 |
+
y1 = torch.stack([
|
1088 |
+
torch.zeros_like(y1) - 1, torch.zeros_like(y1) - 1,
|
1089 |
+
y1, y1,
|
1090 |
+
torch.zeros_like(y1) - 1, torch.zeros_like(y1) - 1
|
1091 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1092 |
+
|
1093 |
+
drags_final = drags[:, -1:, :, :].expand_as(drags)
|
1094 |
+
x_final = (drags_final[..., 2] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1095 |
+
x_final_tgt = (drags_final[..., 2] * current_resolution - x_final)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1096 |
+
x_final = x_final[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1097 |
+
x_final = torch.stack([
|
1098 |
+
torch.zeros_like(x_final) - 1, torch.zeros_like(x_final) - 1,
|
1099 |
+
torch.zeros_like(x_final) - 1, torch.zeros_like(x_final) - 1,
|
1100 |
+
x_final, x_final
|
1101 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1102 |
+
|
1103 |
+
y_final = (drags_final[..., 3] * current_resolution - 0.5).round().clip(0, current_resolution - 1)
|
1104 |
+
y_final_tgt = (drags_final[..., 3] * current_resolution - y_final)[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1105 |
+
y_final = y_final[..., None, None] # (batch, num_frames, num_points, 1, 1)
|
1106 |
+
y_final = torch.stack([
|
1107 |
+
torch.zeros_like(y_final) - 1, torch.zeros_like(y_final) - 1,
|
1108 |
+
torch.zeros_like(y_final) - 1, torch.zeros_like(y_final) - 1,
|
1109 |
+
y_final, y_final
|
1110 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1111 |
+
|
1112 |
+
value_image = torch.stack([
|
1113 |
+
x_src, y_src,
|
1114 |
+
x_tgt, y_tgt,
|
1115 |
+
x_final_tgt, y_final_tgt
|
1116 |
+
], dim=3).view(batch_size, num_frames, num_channels * num_points, 1, 1)
|
1117 |
+
value_image = value_image.expand_as(concatting_image)
|
1118 |
+
start_mask = (x_grid == x0) & (y_grid == y0) & not_all_zeros
|
1119 |
+
end_mask = (x_grid == x1) & (y_grid == y1) & not_all_zeros
|
1120 |
+
final_mask = (x_grid == x_final) & (y_grid == y_final) & not_all_zeros
|
1121 |
+
concatting_image[start_mask] = value_image[start_mask]
|
1122 |
+
concatting_image[end_mask] = value_image[end_mask]
|
1123 |
+
concatting_image[final_mask] = value_image[final_mask]
|
1124 |
+
return concatting_image
|
1125 |
+
|
1126 |
+
def zero_init(self):
|
1127 |
+
for block in self.down_blocks:
|
1128 |
+
if hasattr(block, "flow_convs"):
|
1129 |
+
for flow_conv in block.flow_convs:
|
1130 |
+
try:
|
1131 |
+
nn.init.constant_(flow_conv.conv_out.weight, 0)
|
1132 |
+
nn.init.constant_(flow_conv.conv_out.bias, 0)
|
1133 |
+
except:
|
1134 |
+
nn.init.constant_(flow_conv.weight, 0)
|
1135 |
+
|
1136 |
+
for block in self.up_blocks:
|
1137 |
+
if hasattr(block, "flow_convs"):
|
1138 |
+
for flow_conv in block.flow_convs:
|
1139 |
+
try:
|
1140 |
+
nn.init.constant_(flow_conv.conv_out.weight, 0)
|
1141 |
+
nn.init.constant_(flow_conv.conv_out.bias, 0)
|
1142 |
+
except:
|
1143 |
+
nn.init.constant_(flow_conv.weight, 0)
|
1144 |
+
|
1145 |
+
def forward(
|
1146 |
+
self,
|
1147 |
+
sample: torch.FloatTensor,
|
1148 |
+
timestep: Union[torch.Tensor, float, int],
|
1149 |
+
image_latents: torch.FloatTensor,
|
1150 |
+
encoder_hidden_states: torch.Tensor,
|
1151 |
+
added_time_ids: torch.Tensor,
|
1152 |
+
drags: torch.Tensor,
|
1153 |
+
|
1154 |
+
force_drop_ids: Optional[torch.Tensor] = None,
|
1155 |
+
) -> Union[UNetSpatioTemporalConditionOutput, Tuple]:
|
1156 |
+
r"""
|
1157 |
+
The [`UNetSpatioTemporalConditionModel`] forward method.
|
1158 |
+
|
1159 |
+
Args:
|
1160 |
+
sample (`torch.FloatTensor`):
|
1161 |
+
The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
|
1162 |
+
image_latents (`torch.FloatTensor`):
|
1163 |
+
The clean conditioning tensor of the first frame of the image with shape `(batch, num_channels, height, width)`.
|
1164 |
+
timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
|
1165 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
1166 |
+
The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`.
|
1167 |
+
added_time_ids: (`torch.FloatTensor`):
|
1168 |
+
The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
|
1169 |
+
embeddings and added to the time embeddings.
|
1170 |
+
drags (`torch.Tensor`):
|
1171 |
+
The drags tensor with shape `(batch, num_frames, num_points, 4)`.
|
1172 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1173 |
+
Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead
|
1174 |
+
of a plain tuple.
|
1175 |
+
Returns:
|
1176 |
+
[`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
|
1177 |
+
If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is
|
1178 |
+
returned, otherwise a `tuple` is returned where the first element is the sample tensor.
|
1179 |
+
"""
|
1180 |
+
batch_size, num_frames = sample.shape[:2]
|
1181 |
+
|
1182 |
+
if not self.pos_embedding_prepared:
|
1183 |
+
for res in self.pos_embedding:
|
1184 |
+
self.pos_embedding[res] = self.pos_embedding[res].to(drags)
|
1185 |
+
self.pos_embedding_prepared = True
|
1186 |
+
|
1187 |
+
# 0. prepare for cfg
|
1188 |
+
drag_drop_ids = None
|
1189 |
+
if (self.training and self.cond_dropout_prob > 0) or force_drop_ids is not None:
|
1190 |
+
if force_drop_ids is None:
|
1191 |
+
drag_drop_ids = torch.rand(batch_size, device=sample.device) < self.cond_dropout_prob
|
1192 |
+
else:
|
1193 |
+
drag_drop_ids = (force_drop_ids == 1)
|
1194 |
+
drags = drags * ~drag_drop_ids[:, None, None, None]
|
1195 |
+
|
1196 |
+
sample = torch.cat([sample, image_latents[:, None].repeat(1, num_frames, 1, 1, 1)], dim=2)
|
1197 |
+
# 1. time
|
1198 |
+
timesteps = timestep
|
1199 |
+
if not torch.is_tensor(timesteps):
|
1200 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
1201 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
1202 |
+
is_mps = sample.device.type == "mps"
|
1203 |
+
if isinstance(timestep, float):
|
1204 |
+
dtype = torch.float32 if is_mps else torch.float64
|
1205 |
+
else:
|
1206 |
+
dtype = torch.int32 if is_mps else torch.int64
|
1207 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
1208 |
+
elif len(timesteps.shape) == 0:
|
1209 |
+
timesteps = timesteps[None].to(sample.device)
|
1210 |
+
|
1211 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1212 |
+
timesteps = timesteps.expand(batch_size)
|
1213 |
+
|
1214 |
+
if self.cross_attn_with_ref and self.double_batch:
|
1215 |
+
sample_ref = image_latents[:, None].repeat(1, num_frames, 2, 1, 1)
|
1216 |
+
sample_ref[:, :, :4] = sample_ref[:, :, :4] * 0.18215
|
1217 |
+
sample = torch.cat([sample_ref, sample], dim=0)
|
1218 |
+
|
1219 |
+
drags = torch.cat([torch.zeros_like(drags), drags], dim=0)
|
1220 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states], dim=0)
|
1221 |
+
timesteps = torch.cat([timesteps, timesteps], dim=0)
|
1222 |
+
batch_size *= 2
|
1223 |
+
|
1224 |
+
drag_encodings = {res: self._convert_drag_to_concatting_image(drags, res) for res in [32, 16, 8]}
|
1225 |
+
|
1226 |
+
t_emb = self.time_proj(timesteps)
|
1227 |
+
|
1228 |
+
# `Timesteps` does not contain any weights and will always return f32 tensors
|
1229 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
1230 |
+
# there might be better ways to encapsulate this.
|
1231 |
+
t_emb = t_emb.to(dtype=sample.dtype)
|
1232 |
+
emb = self.time_embedding(t_emb)
|
1233 |
+
|
1234 |
+
# Flatten the batch and frames dimensions
|
1235 |
+
# sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
|
1236 |
+
sample = sample.flatten(0, 1)
|
1237 |
+
# Repeat the embeddings num_video_frames times
|
1238 |
+
# emb: [batch, channels] -> [batch * frames, channels]
|
1239 |
+
emb = emb.repeat_interleave(num_frames, dim=0)
|
1240 |
+
# encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
|
1241 |
+
encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)
|
1242 |
+
|
1243 |
+
# 2. pre-process
|
1244 |
+
sample = self.conv_in(sample)
|
1245 |
+
|
1246 |
+
image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)
|
1247 |
+
|
1248 |
+
down_block_res_samples = (sample,)
|
1249 |
+
for downsample_block in self.down_blocks:
|
1250 |
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
1251 |
+
flow = drag_encodings[sample.shape[-1]]
|
1252 |
+
|
1253 |
+
sample, res_samples = downsample_block(
|
1254 |
+
hidden_states=sample,
|
1255 |
+
temb=emb,
|
1256 |
+
encoder_hidden_states=encoder_hidden_states,
|
1257 |
+
image_only_indicator=image_only_indicator,
|
1258 |
+
flow=flow.flatten(0, 1),
|
1259 |
+
drag_original=drags.flatten(0, 1),
|
1260 |
+
)
|
1261 |
+
else:
|
1262 |
+
sample, res_samples = downsample_block(
|
1263 |
+
hidden_states=sample,
|
1264 |
+
temb=emb,
|
1265 |
+
image_only_indicator=image_only_indicator,
|
1266 |
+
)
|
1267 |
+
|
1268 |
+
down_block_res_samples += res_samples
|
1269 |
+
|
1270 |
+
# 4. mid
|
1271 |
+
sample = self.mid_block(
|
1272 |
+
hidden_states=sample,
|
1273 |
+
temb=emb,
|
1274 |
+
encoder_hidden_states=encoder_hidden_states,
|
1275 |
+
image_only_indicator=image_only_indicator,
|
1276 |
+
)
|
1277 |
+
# 5. up
|
1278 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
1279 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
1280 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
1281 |
+
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
|
1282 |
+
flow = drag_encodings[sample.shape[-1]]
|
1283 |
+
sample = upsample_block(
|
1284 |
+
hidden_states=sample,
|
1285 |
+
temb=emb,
|
1286 |
+
res_hidden_states_tuple=res_samples,
|
1287 |
+
encoder_hidden_states=encoder_hidden_states,
|
1288 |
+
image_only_indicator=image_only_indicator,
|
1289 |
+
flow=flow.flatten(0, 1),
|
1290 |
+
drag_original=drags.flatten(0, 1),
|
1291 |
+
)
|
1292 |
+
else:
|
1293 |
+
sample = upsample_block(
|
1294 |
+
hidden_states=sample,
|
1295 |
+
temb=emb,
|
1296 |
+
res_hidden_states_tuple=res_samples,
|
1297 |
+
image_only_indicator=image_only_indicator,
|
1298 |
+
)
|
1299 |
+
|
1300 |
+
# 6. post-process
|
1301 |
+
sample = self.conv_norm_out(sample)
|
1302 |
+
sample = self.conv_act(sample)
|
1303 |
+
sample = self.conv_out(sample)
|
1304 |
+
|
1305 |
+
# 7. Reshape back to original shape
|
1306 |
+
sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
|
1307 |
+
if self.cross_attn_with_ref and self.double_batch:
|
1308 |
+
sample = sample[batch_size // 2:]
|
1309 |
+
|
1310 |
+
return sample
|
1311 |
+
|
1312 |
+
|
1313 |
+
if __name__ == "__main__":
|
1314 |
+
puppet_master = UNetDragSpatioTemporalConditionModel(num_drags=5)
|
1315 |
+
state_dict = torch.load("ckpts/0800000-ema.pt", map_location="cpu")
|
1316 |
+
puppet_master.load_state_dict(state_dict, strict=True)
|