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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import time
|
3 |
+
from typing import Type, Dict, Any, Tuple, Callable
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
from einops import rearrange
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
|
10 |
+
from . import merge
|
11 |
+
from .utils import isinstance_str, init_generator, join_frame, split_frame, func_warper, join_warper, split_warper
|
12 |
+
|
13 |
+
|
14 |
+
def compute_merge(module: torch.nn.Module, x: torch.Tensor, tome_info: Dict[str, Any]) -> Tuple[Callable, ...]:
|
15 |
+
original_h, original_w = tome_info["size"]
|
16 |
+
original_tokens = original_h * original_w
|
17 |
+
downsample = int(math.ceil(math.sqrt(original_tokens // x.shape[1])))
|
18 |
+
|
19 |
+
args = tome_info["args"]
|
20 |
+
generator = module.generator
|
21 |
+
|
22 |
+
# Frame Number and Token Number
|
23 |
+
fsize = x.shape[0] // args["batch_size"]
|
24 |
+
tsize = x.shape[1]
|
25 |
+
|
26 |
+
# Merge tokens in high resolution layers
|
27 |
+
if downsample <= args["max_downsample"]:
|
28 |
+
|
29 |
+
if args["generator"] is None:
|
30 |
+
args["generator"] = init_generator(x.device)
|
31 |
+
# module.generator = module.generator.manual_seed(123)
|
32 |
+
elif args["generator"].device != x.device:
|
33 |
+
args["generator"] = init_generator(x.device, fallback=args["generator"])
|
34 |
+
|
35 |
+
# Local Token Merging!
|
36 |
+
|
37 |
+
local_tokens = join_frame(x, fsize)
|
38 |
+
m_ls = [join_warper(fsize)]
|
39 |
+
u_ls = [split_warper(fsize)]
|
40 |
+
unm = 0
|
41 |
+
curF = fsize
|
42 |
+
|
43 |
+
# Recursive merge multi-frame tokens into one set. Such as 4->1 for 4 frames and 8->2->1 for 8 frames when target stride is 4.
|
44 |
+
while curF > 1:
|
45 |
+
m, u, ret_dict = merge.bipartite_soft_matching_randframe(
|
46 |
+
local_tokens, curF, args["local_merge_ratio"], unm, generator, args["target_stride"], args["align_batch"])
|
47 |
+
unm += ret_dict["unm_num"]
|
48 |
+
m_ls.append(m)
|
49 |
+
u_ls.append(u)
|
50 |
+
local_tokens = m(local_tokens)
|
51 |
+
|
52 |
+
# assert (x.shape[1] - unm) % tsize == 0
|
53 |
+
# Total token number = current frame number * per-frame token number + unmerged token number
|
54 |
+
curF = (local_tokens.shape[1] - unm) // tsize
|
55 |
+
|
56 |
+
merged_tokens = local_tokens
|
57 |
+
|
58 |
+
# Global Token Merging!
|
59 |
+
if args["merge_global"]:
|
60 |
+
if hasattr(module, "global_tokens") and module.global_tokens is not None:
|
61 |
+
# Merge local tokens with global tokens. Randomly determine merging destination.
|
62 |
+
if torch.rand(1, generator=generator, device=generator.device) > args["global_rand"]:
|
63 |
+
src_len = local_tokens.shape[1]
|
64 |
+
tokens = torch.cat(
|
65 |
+
[local_tokens, module.global_tokens.to(local_tokens)], dim=1)
|
66 |
+
local_chunk = 0
|
67 |
+
else:
|
68 |
+
src_len = module.global_tokens.shape[1]
|
69 |
+
tokens = torch.cat(
|
70 |
+
[module.global_tokens.to(local_tokens), local_tokens], dim=1)
|
71 |
+
local_chunk = 1
|
72 |
+
|
73 |
+
m, u, _ = merge.bipartite_soft_matching_2s(
|
74 |
+
tokens, src_len, args["global_merge_ratio"], args["align_batch"], unmerge_chunk=local_chunk)
|
75 |
+
merged_tokens = m(tokens)
|
76 |
+
m_ls.append(m)
|
77 |
+
u_ls.append(u)
|
78 |
+
|
79 |
+
# Update global tokens with unmerged local tokens. There should be a better way to do this.
|
80 |
+
module.global_tokens = u(merged_tokens).detach().clone().cpu()
|
81 |
+
else:
|
82 |
+
module.global_tokens = local_tokens.detach().clone().cpu()
|
83 |
+
|
84 |
+
m = func_warper(m_ls)
|
85 |
+
u = func_warper(u_ls[::-1])
|
86 |
+
else:
|
87 |
+
m, u = (merge.do_nothing, merge.do_nothing)
|
88 |
+
merged_tokens = x
|
89 |
+
|
90 |
+
# Return merge op, unmerge op, and merged tokens.
|
91 |
+
return m, u, merged_tokens
|
92 |
+
|
93 |
+
|
94 |
+
def make_tome_block(block_class: Type[torch.nn.Module]) -> Type[torch.nn.Module]:
|
95 |
+
"""
|
96 |
+
Make a patched class on the fly so we don't have to import any specific modules.
|
97 |
+
This patch applies ToMe to the forward function of the block.
|
98 |
+
"""
|
99 |
+
|
100 |
+
class ToMeBlock(block_class):
|
101 |
+
# Save for unpatching later
|
102 |
+
_parent = block_class
|
103 |
+
|
104 |
+
def _forward(self, x: torch.Tensor, context: torch.Tensor = None) -> torch.Tensor:
|
105 |
+
m_a, m_c, m_m, u_a, u_c, u_m = compute_merge(
|
106 |
+
self, x, self._tome_info)
|
107 |
+
|
108 |
+
# This is where the meat of the computation happens
|
109 |
+
x = u_a(self.attn1(m_a(self.norm1(x)),
|
110 |
+
context=context if self.disable_self_attn else None)) + x
|
111 |
+
x = u_c(self.attn2(m_c(self.norm2(x)), context=context)) + x
|
112 |
+
x = u_m(self.ff(m_m(self.norm3(x)))) + x
|
113 |
+
|
114 |
+
return x
|
115 |
+
|
116 |
+
return ToMeBlock
|
117 |
+
|
118 |
+
|
119 |
+
def make_diffusers_tome_block(block_class: Type[torch.nn.Module]) -> Type[torch.nn.Module]:
|
120 |
+
"""
|
121 |
+
Make a patched class for a diffusers model.
|
122 |
+
This patch applies ToMe to the forward function of the block.
|
123 |
+
"""
|
124 |
+
class ToMeBlock(block_class):
|
125 |
+
# Save for unpatching later
|
126 |
+
_parent = block_class
|
127 |
+
|
128 |
+
def forward(
|
129 |
+
self,
|
130 |
+
hidden_states,
|
131 |
+
attention_mask=None,
|
132 |
+
encoder_hidden_states=None,
|
133 |
+
encoder_attention_mask=None,
|
134 |
+
timestep=None,
|
135 |
+
cross_attention_kwargs=None,
|
136 |
+
class_labels=None,
|
137 |
+
) -> torch.Tensor:
|
138 |
+
|
139 |
+
if self.use_ada_layer_norm:
|
140 |
+
norm_hidden_states = self.norm1(hidden_states, timestep)
|
141 |
+
elif self.use_ada_layer_norm_zero:
|
142 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
143 |
+
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
|
144 |
+
)
|
145 |
+
else:
|
146 |
+
norm_hidden_states = self.norm1(hidden_states)
|
147 |
+
|
148 |
+
# Merge input tokens
|
149 |
+
m_a, u_a, merged_tokens = compute_merge(
|
150 |
+
self, norm_hidden_states, self._tome_info)
|
151 |
+
|
152 |
+
norm_hidden_states = merged_tokens
|
153 |
+
|
154 |
+
# 1. Self-Attention
|
155 |
+
cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
|
156 |
+
# tt = time.time()
|
157 |
+
attn_output = self.attn1(
|
158 |
+
norm_hidden_states,
|
159 |
+
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
|
160 |
+
attention_mask=attention_mask,
|
161 |
+
**cross_attention_kwargs,
|
162 |
+
)
|
163 |
+
# print(time.time() - tt)
|
164 |
+
if self.use_ada_layer_norm_zero:
|
165 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
166 |
+
|
167 |
+
# Unmerge output tokens
|
168 |
+
attn_output = u_a(attn_output)
|
169 |
+
hidden_states = attn_output + hidden_states
|
170 |
+
|
171 |
+
if self.attn2 is not None:
|
172 |
+
norm_hidden_states = (
|
173 |
+
self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(
|
174 |
+
hidden_states)
|
175 |
+
)
|
176 |
+
|
177 |
+
# 2. Cross-Attention
|
178 |
+
attn_output = self.attn2(
|
179 |
+
norm_hidden_states,
|
180 |
+
encoder_hidden_states=encoder_hidden_states,
|
181 |
+
attention_mask=encoder_attention_mask,
|
182 |
+
**cross_attention_kwargs,
|
183 |
+
)
|
184 |
+
|
185 |
+
hidden_states = attn_output + hidden_states
|
186 |
+
|
187 |
+
# 3. Feed-forward
|
188 |
+
norm_hidden_states = self.norm3(hidden_states)
|
189 |
+
|
190 |
+
if self.use_ada_layer_norm_zero:
|
191 |
+
norm_hidden_states = norm_hidden_states * \
|
192 |
+
(1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
193 |
+
|
194 |
+
ff_output = self.ff(norm_hidden_states)
|
195 |
+
|
196 |
+
if self.use_ada_layer_norm_zero:
|
197 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
198 |
+
|
199 |
+
hidden_states = ff_output + hidden_states
|
200 |
+
|
201 |
+
return hidden_states
|
202 |
+
|
203 |
+
return ToMeBlock
|
204 |
+
|
205 |
+
|
206 |
+
def hook_tome_model(model: torch.nn.Module):
|
207 |
+
""" Adds a forward pre hook to get the image size. This hook can be removed with remove_patch. """
|
208 |
+
def hook(module, args):
|
209 |
+
module._tome_info["size"] = (args[0].shape[2], args[0].shape[3])
|
210 |
+
return None
|
211 |
+
|
212 |
+
model._tome_info["hooks"].append(model.register_forward_pre_hook(hook))
|
213 |
+
|
214 |
+
|
215 |
+
def hook_tome_module(module: torch.nn.Module):
|
216 |
+
""" Adds a forward pre hook to initialize random number generator.
|
217 |
+
All modules share the same generator state to keep their randomness in VidToMe consistent in one pass.
|
218 |
+
This hook can be removed with remove_patch. """
|
219 |
+
def hook(module, args):
|
220 |
+
if not hasattr(module, "generator"):
|
221 |
+
module.generator = init_generator(args[0].device)
|
222 |
+
elif module.generator.device != args[0].device:
|
223 |
+
module.generator = init_generator(
|
224 |
+
args[0].device, fallback=module.generator)
|
225 |
+
else:
|
226 |
+
return None
|
227 |
+
|
228 |
+
# module.generator = module.generator.manual_seed(module._tome_info["args"]["seed"])
|
229 |
+
return None
|
230 |
+
|
231 |
+
module._tome_info["hooks"].append(module.register_forward_pre_hook(hook))
|
232 |
+
|
233 |
+
|
234 |
+
def apply_patch(
|
235 |
+
model: torch.nn.Module,
|
236 |
+
local_merge_ratio: float = 0.9,
|
237 |
+
merge_global: bool = False,
|
238 |
+
global_merge_ratio=0.8,
|
239 |
+
max_downsample: int = 2,
|
240 |
+
seed: int = 123,
|
241 |
+
batch_size: int = 2,
|
242 |
+
include_control: bool = False,
|
243 |
+
align_batch: bool = False,
|
244 |
+
target_stride: int = 4,
|
245 |
+
global_rand=0.5):
|
246 |
+
"""
|
247 |
+
Patches a stable diffusion model with VidToMe.
|
248 |
+
Apply this to the highest level stable diffusion object (i.e., it should have a .model.diffusion_model).
|
249 |
+
|
250 |
+
Important Args:
|
251 |
+
- model: A top level Stable Diffusion module to patch in place. Should have a ".model.diffusion_model"
|
252 |
+
- local_merge_ratio: The ratio of tokens to merge locally. I.e., 0.9 would merge 90% src tokens.
|
253 |
+
If there are 4 frames in a chunk (3 src, 1 dst), the compression ratio will be 1.3 / 4.0.
|
254 |
+
And the largest compression ratio is 0.25 (when local_merge_ratio = 1.0).
|
255 |
+
Higher values result in more consistency, but with more visual quality loss.
|
256 |
+
- merge_global: Whether or not to include global token merging.
|
257 |
+
- global_merge_ratio: The ratio of tokens to merge locally. I.e., 0.8 would merge 80% src tokens.
|
258 |
+
When find significant degradation in video quality. Try to lower the value.
|
259 |
+
|
260 |
+
Args to tinker with if you want:
|
261 |
+
- max_downsample [1, 2, 4, or 8]: Apply VidToMe to layers with at most this amount of downsampling.
|
262 |
+
E.g., 1 only applies to layers with no downsampling (4/15) while
|
263 |
+
8 applies to all layers (15/15). I recommend a value of 1 or 2.
|
264 |
+
- seed: Manual random seed.
|
265 |
+
- batch_size: Video batch size. Number of video chunks in one pass. When processing one video, it
|
266 |
+
should be 2 (cond + uncond) or 3 (when using PnP, source + cond + uncond).
|
267 |
+
- include_control: Whether or not to patch ControlNet model.
|
268 |
+
- align_batch: Whether or not to align similarity matching maps of samples in the batch. It should
|
269 |
+
be True when using PnP as control.
|
270 |
+
- target_stride: Stride between target frames. I.e., when target_stride = 4, there is 1 target frame
|
271 |
+
in any 4 consecutive frames.
|
272 |
+
- global_rand: Probability in global token merging src/dst split. Global tokens are always src when
|
273 |
+
global_rand = 1.0 and always dst when global_rand = 0.0 .
|
274 |
+
"""
|
275 |
+
|
276 |
+
# Make sure the module is not currently patched
|
277 |
+
remove_patch(model)
|
278 |
+
|
279 |
+
is_diffusers = isinstance_str(
|
280 |
+
model, "DiffusionPipeline") or isinstance_str(model, "ModelMixin")
|
281 |
+
|
282 |
+
if not is_diffusers:
|
283 |
+
if not hasattr(model, "model") or not hasattr(model.model, "diffusion_model"):
|
284 |
+
# Provided model not supported
|
285 |
+
raise RuntimeError(
|
286 |
+
"Provided model was not a Stable Diffusion / Latent Diffusion model, as expected.")
|
287 |
+
diffusion_model = model.model.diffusion_model
|
288 |
+
else:
|
289 |
+
# Supports "pipe.unet" and "unet"
|
290 |
+
diffusion_model = model.unet if hasattr(model, "unet") else model
|
291 |
+
|
292 |
+
if isinstance_str(model, "StableDiffusionControlNetPipeline") and include_control:
|
293 |
+
diffusion_models = [diffusion_model, model.controlnet]
|
294 |
+
else:
|
295 |
+
diffusion_models = [diffusion_model]
|
296 |
+
|
297 |
+
for diffusion_model in diffusion_models:
|
298 |
+
diffusion_model._tome_info = {
|
299 |
+
"size": None,
|
300 |
+
"hooks": [],
|
301 |
+
"args": {
|
302 |
+
"max_downsample": max_downsample,
|
303 |
+
"generator": None,
|
304 |
+
"seed": seed,
|
305 |
+
"batch_size": batch_size,
|
306 |
+
"align_batch": align_batch,
|
307 |
+
"merge_global": merge_global,
|
308 |
+
"global_merge_ratio": global_merge_ratio,
|
309 |
+
"local_merge_ratio": local_merge_ratio,
|
310 |
+
"global_rand": global_rand,
|
311 |
+
"target_stride": target_stride
|
312 |
+
}
|
313 |
+
}
|
314 |
+
hook_tome_model(diffusion_model)
|
315 |
+
|
316 |
+
for name, module in diffusion_model.named_modules():
|
317 |
+
# If for some reason this has a different name, create an issue and I'll fix it
|
318 |
+
# if isinstance_str(module, "BasicTransformerBlock") and "down_blocks" not in name:
|
319 |
+
if isinstance_str(module, "BasicTransformerBlock"):
|
320 |
+
make_tome_block_fn = make_diffusers_tome_block if is_diffusers else make_tome_block
|
321 |
+
module.__class__ = make_tome_block_fn(module.__class__)
|
322 |
+
module._tome_info = diffusion_model._tome_info
|
323 |
+
hook_tome_module(module)
|
324 |
+
|
325 |
+
# Something introduced in SD 2.0 (LDM only)
|
326 |
+
if not hasattr(module, "disable_self_attn") and not is_diffusers:
|
327 |
+
module.disable_self_attn = False
|
328 |
+
|
329 |
+
# Something needed for older versions of diffusers
|
330 |
+
if not hasattr(module, "use_ada_layer_norm_zero") and is_diffusers:
|
331 |
+
module.use_ada_layer_norm = False
|
332 |
+
module.use_ada_layer_norm_zero = False
|
333 |
+
|
334 |
+
return model
|
335 |
+
|
336 |
+
|
337 |
+
def remove_patch(model: torch.nn.Module):
|
338 |
+
""" Removes a patch from a ToMe Diffusion module if it was already patched. """
|
339 |
+
# For diffusers
|
340 |
+
|
341 |
+
model = model.unet if hasattr(model, "unet") else model
|
342 |
+
model_ls = [model]
|
343 |
+
if hasattr(model, "controlnet"):
|
344 |
+
model_ls.append(model.controlnet)
|
345 |
+
for model in model_ls:
|
346 |
+
for _, module in model.named_modules():
|
347 |
+
if hasattr(module, "_tome_info"):
|
348 |
+
for hook in module._tome_info["hooks"]:
|
349 |
+
hook.remove()
|
350 |
+
module._tome_info["hooks"].clear()
|
351 |
+
|
352 |
+
if module.__class__.__name__ == "ToMeBlock":
|
353 |
+
module.__class__ = module._parent
|
354 |
+
|
355 |
+
return model
|
356 |
+
|
357 |
+
|
358 |
+
def update_patch(model: torch.nn.Module, **kwargs):
|
359 |
+
""" Update arguments in patched modules """
|
360 |
+
# For diffusers
|
361 |
+
model0 = model.unet if hasattr(model, "unet") else model
|
362 |
+
model_ls = [model0]
|
363 |
+
if hasattr(model, "controlnet"):
|
364 |
+
model_ls.append(model.controlnet)
|
365 |
+
for model in model_ls:
|
366 |
+
for _, module in model.named_modules():
|
367 |
+
if hasattr(module, "_tome_info"):
|
368 |
+
for k, v in kwargs.items():
|
369 |
+
setattr(module, k, v)
|
370 |
+
return model
|
371 |
+
|
372 |
+
|
373 |
+
def collect_from_patch(model: torch.nn.Module, attr="tome"):
|
374 |
+
""" Collect attributes in patched modules """
|
375 |
+
# For diffusers
|
376 |
+
model0 = model.unet if hasattr(model, "unet") else model
|
377 |
+
model_ls = [model0]
|
378 |
+
if hasattr(model, "controlnet"):
|
379 |
+
model_ls.append(model.controlnet)
|
380 |
+
ret_dict = dict()
|
381 |
+
for model in model_ls:
|
382 |
+
for name, module in model.named_modules():
|
383 |
+
if hasattr(module, attr):
|
384 |
+
res = getattr(module, attr)
|
385 |
+
ret_dict[name] = res
|
386 |
+
|
387 |
+
return ret_dict
|