forked from neggles/animatediff-cli
-
Notifications
You must be signed in to change notification settings - Fork 104
/
animation.py
3487 lines (2831 loc) · 149 KB
/
animation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py
import inspect
import itertools
import logging
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers import LCMScheduler
from diffusers.configuration_utils import FrozenDict
from diffusers.image_processor import VaeImageProcessor
from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin
from diffusers.models import AutoencoderKL, ControlNetModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.schedulers import (DDIMScheduler, DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler, LMSDiscreteScheduler,
PNDMScheduler)
from diffusers.utils import (BaseOutput, deprecate, is_accelerate_available,
is_accelerate_version)
from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
from einops import rearrange
from packaging import version
from tqdm.rich import tqdm
from transformers import CLIPImageProcessor, CLIPTokenizer
from animatediff.ip_adapter import IPAdapter, IPAdapterFull, IPAdapterPlus
from animatediff.models.attention import BasicTransformerBlock
from animatediff.models.clip import CLIPSkipTextModel
from animatediff.models.unet import (UNet3DConditionModel,
UNetMidBlock3DCrossAttn)
from animatediff.models.unet_blocks import (CrossAttnDownBlock3D,
CrossAttnUpBlock3D, DownBlock3D,
UpBlock3D)
from animatediff.pipelines.context import (get_context_scheduler,
get_total_steps)
from animatediff.utils.model import nop_train
from animatediff.utils.pipeline import get_memory_format
from animatediff.utils.util import (end_profile,
get_tensor_interpolation_method, show_gpu,
start_profile, stopwatch_record,
stopwatch_start, stopwatch_stop)
logger = logging.getLogger(__name__)
C_REF_MODE = "write"
def torch_dfs(model: torch.nn.Module):
result = [model]
for child in model.children():
result += torch_dfs(child)
return result
class PromptEncoder:
def __init__(
self,
pipe,
device,
latents_device,
num_videos_per_prompt,
do_classifier_free_guidance,
region_condi_list,
negative_prompt,
is_signle_prompt_mode,
clip_skip,
multi_uncond_mode
):
self.pipe = pipe
self.is_single_prompt_mode=is_signle_prompt_mode
self.do_classifier_free_guidance = do_classifier_free_guidance
uncond_num = 0
if do_classifier_free_guidance:
if multi_uncond_mode:
uncond_num = len(region_condi_list)
else:
uncond_num = 1
### text
prompt_nums = []
prompt_map_list = []
prompt_list = []
for condi in region_condi_list:
_prompt_map = condi["prompt_map"]
prompt_map_list.append(_prompt_map)
_prompt_map = dict(sorted(_prompt_map.items()))
_prompt_list = [_prompt_map[key_frame] for key_frame in _prompt_map.keys()]
prompt_nums.append( len(_prompt_list) )
prompt_list += _prompt_list
prompt_embeds = pipe._encode_prompt(
prompt_list,
device,
num_videos_per_prompt,
do_classifier_free_guidance,
negative_prompt,
prompt_embeds=None,
negative_prompt_embeds=None,
clip_skip=clip_skip,
).to(device = latents_device)
self.prompt_embeds_dtype = prompt_embeds.dtype
if do_classifier_free_guidance:
negative, positive = prompt_embeds.chunk(2, 0)
negative = negative.chunk(negative.shape[0], 0)
positive = positive.chunk(positive.shape[0], 0)
else:
positive = prompt_embeds
positive = positive.chunk(positive.shape[0], 0)
if pipe.ip_adapter:
pipe.ip_adapter.set_text_length(positive[0].shape[1])
prompt_embeds_region_list = []
if do_classifier_free_guidance:
prompt_embeds_region_list = [
{
0:negative[0]
}
] * uncond_num + prompt_embeds_region_list
pos_index = 0
for prompt_map, num in zip(prompt_map_list, prompt_nums):
prompt_embeds_map={}
pos = positive[pos_index:pos_index+num]
for i, key_frame in enumerate(prompt_map):
prompt_embeds_map[key_frame] = pos[i]
prompt_embeds_region_list.append( prompt_embeds_map )
pos_index += num
if do_classifier_free_guidance:
prompt_map_list = [
{
0:negative_prompt
}
] * uncond_num + prompt_map_list
self.prompt_map_list = prompt_map_list
self.prompt_embeds_region_list = prompt_embeds_region_list
### image
if pipe.ip_adapter:
ip_im_nums = []
ip_im_map_list = []
ip_im_list = []
for condi in region_condi_list:
_ip_im_map = condi["ip_adapter_map"]["images"]
ip_im_map_list.append(_ip_im_map)
_ip_im_map = dict(sorted(_ip_im_map.items()))
_ip_im_list = [_ip_im_map[key_frame] for key_frame in _ip_im_map.keys()]
ip_im_nums.append( len(_ip_im_list) )
ip_im_list += _ip_im_list
positive, negative = pipe.ip_adapter.get_image_embeds(ip_im_list)
positive = positive.to(device=latents_device)
negative = negative.to(device=latents_device)
bs_embed, seq_len, _ = positive.shape
positive = positive.repeat(1, 1, 1)
positive = positive.view(bs_embed * 1, seq_len, -1)
bs_embed, seq_len, _ = negative.shape
negative = negative.repeat(1, 1, 1)
negative = negative.view(bs_embed * 1, seq_len, -1)
if do_classifier_free_guidance:
negative = negative.chunk(negative.shape[0], 0)
positive = positive.chunk(positive.shape[0], 0)
else:
positive = positive.chunk(positive.shape[0], 0)
im_prompt_embeds_region_list = []
if do_classifier_free_guidance:
im_prompt_embeds_region_list = [
{
0:negative[0]
}
] * uncond_num + im_prompt_embeds_region_list
pos_index = 0
for ip_im_map, num in zip(ip_im_map_list, ip_im_nums):
im_prompt_embeds_map={}
pos = positive[pos_index:pos_index+num]
for i, key_frame in enumerate(ip_im_map):
im_prompt_embeds_map[key_frame] = pos[i]
im_prompt_embeds_region_list.append( im_prompt_embeds_map )
pos_index += num
if do_classifier_free_guidance:
ip_im_map_list = [
{
0:None
}
] * uncond_num + ip_im_map_list
self.ip_im_map_list = ip_im_map_list
self.im_prompt_embeds_region_list = im_prompt_embeds_region_list
def _get_current_prompt_embeds_from_text(
self,
prompt_map,
prompt_embeds_map,
center_frame = None,
video_length : int = 0
):
key_prev = list(prompt_map.keys())[-1]
key_next = list(prompt_map.keys())[0]
for p in prompt_map.keys():
if p > center_frame:
key_next = p
break
key_prev = p
dist_prev = center_frame - key_prev
if dist_prev < 0:
dist_prev += video_length
dist_next = key_next - center_frame
if dist_next < 0:
dist_next += video_length
if key_prev == key_next or dist_prev + dist_next == 0:
return prompt_embeds_map[key_prev]
rate = dist_prev / (dist_prev + dist_next)
return get_tensor_interpolation_method()( prompt_embeds_map[key_prev], prompt_embeds_map[key_next], rate )
def get_current_prompt_embeds_from_text(
self,
center_frame = None,
video_length : int = 0
):
outputs = ()
for prompt_map, prompt_embeds_map in zip(self.prompt_map_list, self.prompt_embeds_region_list):
embs = self._get_current_prompt_embeds_from_text(
prompt_map,
prompt_embeds_map,
center_frame,
video_length)
outputs += (embs,)
return outputs
def _get_current_prompt_embeds_from_image(
self,
ip_im_map,
im_prompt_embeds_map,
center_frame = None,
video_length : int = 0
):
key_prev = list(ip_im_map.keys())[-1]
key_next = list(ip_im_map.keys())[0]
for p in ip_im_map.keys():
if p > center_frame:
key_next = p
break
key_prev = p
dist_prev = center_frame - key_prev
if dist_prev < 0:
dist_prev += video_length
dist_next = key_next - center_frame
if dist_next < 0:
dist_next += video_length
if key_prev == key_next or dist_prev + dist_next == 0:
return im_prompt_embeds_map[key_prev]
rate = dist_prev / (dist_prev + dist_next)
return get_tensor_interpolation_method()( im_prompt_embeds_map[key_prev], im_prompt_embeds_map[key_next], rate)
def get_current_prompt_embeds_from_image(
self,
center_frame = None,
video_length : int = 0
):
outputs=()
for prompt_map, prompt_embeds_map in zip(self.ip_im_map_list, self.im_prompt_embeds_region_list):
embs = self._get_current_prompt_embeds_from_image(
prompt_map,
prompt_embeds_map,
center_frame,
video_length)
outputs += (embs,)
return outputs
def get_current_prompt_embeds_single(
self,
context: List[int] = None,
video_length : int = 0
):
center_frame = context[len(context)//2]
text_emb = self.get_current_prompt_embeds_from_text(center_frame, video_length)
text_emb = torch.cat(text_emb)
if self.pipe.ip_adapter:
image_emb = self.get_current_prompt_embeds_from_image(center_frame, video_length)
image_emb = torch.cat(image_emb)
return torch.cat([text_emb,image_emb], dim=1)
else:
return text_emb
def get_current_prompt_embeds_multi(
self,
context: List[int] = None,
video_length : int = 0
):
emb_list = []
for c in context:
t = self.get_current_prompt_embeds_from_text(c, video_length)
for i, emb in enumerate(t):
if i >= len(emb_list):
emb_list.append([])
emb_list[i].append(emb)
text_emb = []
for emb in emb_list:
emb = torch.cat(emb)
text_emb.append(emb)
text_emb = torch.cat(text_emb)
if self.pipe.ip_adapter == None:
return text_emb
emb_list = []
for c in context:
t = self.get_current_prompt_embeds_from_image(c, video_length)
for i, emb in enumerate(t):
if i >= len(emb_list):
emb_list.append([])
emb_list[i].append(emb)
image_emb = []
for emb in emb_list:
emb = torch.cat(emb)
image_emb.append(emb)
image_emb = torch.cat(image_emb)
return torch.cat([text_emb,image_emb], dim=1)
def get_current_prompt_embeds(
self,
context: List[int] = None,
video_length : int = 0
):
return self.get_current_prompt_embeds_single(context,video_length) if self.is_single_prompt_mode else self.get_current_prompt_embeds_multi(context,video_length)
def get_prompt_embeds_dtype(self):
return self.prompt_embeds_dtype
def get_condi_size(self):
return len(self.prompt_embeds_region_list)
class RegionMask:
def __init__(
self,
region_list,
batch_size,
num_channels_latents,
video_length,
height,
width,
vae_scale_factor,
dtype,
device,
multi_uncond_mode
):
shape = (
batch_size,
num_channels_latents,
video_length,
height // vae_scale_factor,
width // vae_scale_factor,
)
def get_area(m:torch.Tensor):
area = torch.where(m == 1)
if len(area[0]) == 0 or len(area[1]) == 0:
return (0,0,0,0)
ymin = min(area[0])
ymax = max(area[0])
xmin = min(area[1])
xmax = max(area[1])
h = ymax+1 - ymin
w = xmax+1 - xmin
mod_h = (h + 7) // 8 * 8
diff_h = mod_h - h
ymin -= diff_h
if ymin < 0:
ymin = 0
h = mod_h
mod_w = (w + 7) // 8 * 8
diff_w = mod_w - w
xmin -= diff_w
if xmin < 0:
xmin = 0
w = mod_w
return (int(xmin), int(ymin), int(w), int(h))
for r in region_list:
mask_latents = torch.zeros(shape)
cur = r["mask_images"]
area_info = None
if cur:
area_info = [ (0,0,0,0) for l in range(video_length)]
for frame_no in cur:
mask = cur[frame_no]
mask = np.array(mask.convert("L"))[None, None, :]
mask = mask.astype(np.float32) / 255.0
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1
mask = torch.from_numpy(mask)
mask = torch.nn.functional.interpolate(
mask, size=(height // vae_scale_factor, width // vae_scale_factor)
)
area_info[frame_no] = get_area(mask[0][0])
mask_latents[:,:,frame_no,:,:] = mask
else:
mask_latents = torch.ones(shape)
w = mask_latents.shape[4]
h = mask_latents.shape[3]
r["mask_latents"] = mask_latents.to(device=device, dtype=dtype, non_blocking=True)
r["mask_images"] = None
r["area"] = area_info
r["latent_size"] = (w, h)
self.region_list = region_list
self.multi_uncond_mode = multi_uncond_mode
self.cond2region = {}
for i,r in enumerate(self.region_list):
if r["src"] != -1:
self.cond2region[r["src"]] = i
def get_mask(
self,
region_index,
):
return self.region_list[region_index]["mask_latents"]
def get_region_from_layer(
self,
cond_layer,
cond_nums,
):
if self.multi_uncond_mode:
cond_layer = cond_layer if cond_layer < cond_nums//2 else cond_layer - cond_nums//2
else:
if cond_layer == 0:
return -1 #uncond for all layer
cond_layer -= 1
if cond_layer not in self.cond2region:
logger.warn(f"unknown {cond_layer=}")
return -1
return self.cond2region[cond_layer]
def get_area(
self,
cond_layer,
cond_nums,
context,
):
if self.multi_uncond_mode:
cond_layer = cond_layer if cond_layer < cond_nums//2 else cond_layer - cond_nums//2
else:
if cond_layer == 0:
return None,None
cond_layer -= 1
if cond_layer not in self.cond2region:
return None,None
region_index = self.cond2region[cond_layer]
if region_index == -1:
return None,None
_,_,w,h = self.region_list[region_index]["area"][context[0]]
l_w, l_h = self.region_list[region_index]["latent_size"]
xy_list = []
for c in context:
x,y,_,_ = self.region_list[region_index]["area"][c]
if x + w > l_w:
x -= (x+w - l_w)
if y + h > l_h:
y -= (y+h - l_h)
xy_list.append( (x,y) )
if self.region_list[region_index]["area"]:
return (w,h), xy_list
else:
return None,None
def get_crop_generation_rate(
self,
cond_layer,
cond_nums,
):
if self.multi_uncond_mode:
cond_layer = cond_layer if cond_layer < cond_nums//2 else cond_layer - cond_nums//2
else:
if cond_layer == 0:
return 0
cond_layer -= 1
if cond_layer not in self.cond2region:
return 0
region_index = self.cond2region[cond_layer]
if region_index == -1:
return 0
return self.region_list[region_index]["crop_generation_rate"]
@dataclass
class AnimationPipelineOutput(BaseOutput):
videos: Union[torch.Tensor, np.ndarray]
class AnimationPipeline(DiffusionPipeline, TextualInversionLoaderMixin):
_optional_components = ["feature_extractor"]
vae: AutoencoderKL
text_encoder: CLIPSkipTextModel
tokenizer: CLIPTokenizer
unet: UNet3DConditionModel
feature_extractor: CLIPImageProcessor
scheduler: Union[
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
]
controlnet_map: Dict[ str , ControlNetModel ]
ip_adapter: IPAdapter = None
model_cpu_offload_seq = "text_encoder->unet->vae"
def __init__(
self,
vae: AutoencoderKL,
text_encoder: CLIPSkipTextModel,
tokenizer: CLIPTokenizer,
unet: UNet3DConditionModel,
scheduler: Union[
DDIMScheduler,
PNDMScheduler,
LMSDiscreteScheduler,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
DPMSolverMultistepScheduler,
],
feature_extractor: CLIPImageProcessor,
controlnet_map: Dict[ str , ControlNetModel ]=None,
):
super().__init__()
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
deprecation_message = (
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
" file"
)
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
new_config = dict(scheduler.config)
new_config["steps_offset"] = 1
scheduler._internal_dict = FrozenDict(new_config)
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
deprecation_message = (
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
)
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
new_config = dict(scheduler.config)
new_config["clip_sample"] = False
scheduler._internal_dict = FrozenDict(new_config)
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
version.parse(unet.config._diffusers_version).base_version
) < version.parse("0.9.0.dev0")
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
deprecation_message = (
"The configuration file of the unet has set the default `sample_size` to smaller than"
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
" in the config might lead to incorrect results in future versions. If you have downloaded this"
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
" the `unet/config.json` file"
)
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
new_config = dict(unet.config)
new_config["sample_size"] = 64
unet._internal_dict = FrozenDict(new_config)
self.register_modules(
vae=vae,
text_encoder=text_encoder,
tokenizer=tokenizer,
unet=unet,
scheduler=scheduler,
feature_extractor=feature_extractor,
)
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
self.control_image_processor = VaeImageProcessor(
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
)
self.controlnet_map = controlnet_map
def enable_vae_slicing(self):
r"""
Enable sliced VAE decoding.
When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
steps. This is useful to save some memory and allow larger batch sizes.
"""
self.vae.enable_slicing()
def disable_vae_slicing(self):
r"""
Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
computing decoding in one step.
"""
self.vae.disable_slicing()
def enable_vae_tiling(self):
r"""
Enable tiled VAE decoding.
When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
"""
self.vae.enable_tiling()
def disable_vae_tiling(self):
r"""
Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
computing decoding in one step.
"""
self.vae.disable_tiling()
def __enable_model_cpu_offload(self, gpu_id=0):
r"""
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
"""
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
from accelerate import cpu_offload_with_hook
else:
raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
device = torch.device(f"cuda:{gpu_id}")
if self.device.type != "cpu":
self.to("cpu", silence_dtype_warnings=True)
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
hook = None
for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
if self.safety_checker is not None:
_, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
# control net hook has be manually offloaded as it alternates with unet
cpu_offload_with_hook(self.controlnet, device)
# We'll offload the last model manually.
self.final_offload_hook = hook
@property
def _execution_device(self):
r"""
Returns the device on which the pipeline's models will be executed. After calling
`pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
hooks.
"""
if not hasattr(self.unet, "_hf_hook"):
return self.device
for module in self.unet.modules():
if (
hasattr(module, "_hf_hook")
and hasattr(module._hf_hook, "execution_device")
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device)
return self.device
def _encode_prompt(
self,
prompt,
device,
num_videos_per_prompt: int = 1,
do_classifier_free_guidance: bool = False,
negative_prompt=None,
max_embeddings_multiples=3,
prompt_embeds: Optional[torch.FloatTensor] = None,
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
clip_skip: int = 1,
):
r"""
Encodes the prompt into text encoder hidden states.
Args:
prompt (`str` or `list(int)`):
prompt to be encoded
device: (`torch.device`):
torch device
num_videos_per_prompt (`int`):
number of videos that should be generated per prompt
do_classifier_free_guidance (`bool`):
whether to use classifier free guidance or not
negative_prompt (`str` or `List[str]`):
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
if `guidance_scale` is less than `1`).
max_embeddings_multiples (`int`, *optional*, defaults to `3`):
The max multiple length of prompt embeddings compared to the max output length of text encoder.
"""
from ..utils.lpw_stable_diffusion import get_weighted_text_embeddings
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None and isinstance(prompt, list):
batch_size = len(prompt)
else:
batch_size = prompt_embeds.shape[0]
if negative_prompt_embeds is None:
if negative_prompt is None:
negative_prompt = [""] * batch_size
elif isinstance(negative_prompt, str):
negative_prompt = [negative_prompt] * batch_size
if batch_size != len(negative_prompt):
raise ValueError(
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
" the batch size of `prompt`."
)
if prompt_embeds is None or negative_prompt_embeds is None:
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
if do_classifier_free_guidance and negative_prompt_embeds is None:
negative_prompt = self.maybe_convert_prompt(negative_prompt, self.tokenizer)
prompt_embeds1, negative_prompt_embeds1 = get_weighted_text_embeddings(
pipe=self,
prompt=prompt,
uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
max_embeddings_multiples=max_embeddings_multiples,
clip_skip=clip_skip
)
if prompt_embeds is None:
prompt_embeds = prompt_embeds1
if negative_prompt_embeds is None:
negative_prompt_embeds = negative_prompt_embeds1
bs_embed, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, seq_len, -1)
if do_classifier_free_guidance:
bs_embed, seq_len, _ = negative_prompt_embeds.shape
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(bs_embed * num_videos_per_prompt, seq_len, -1)
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
return prompt_embeds
def __encode_prompt(
self,
prompt,
device,
num_videos_per_prompt: int = 1,
do_classifier_free_guidance: bool = False,
negative_prompt=None,
prompt_embeds: Optional[torch.FloatTensor] = None,
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
lora_scale: Optional[float] = None,
clip_skip: int = 1,
):
# set lora scale so that monkey patched LoRA
# function of text encoder can correctly access it
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
self._lora_scale = lora_scale
batch_size = len(prompt) if isinstance(prompt, list) else 1
if prompt_embeds is None:
# textual inversion: procecss multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
text_inputs = self.tokenizer(
prompt,
padding="max_length",
max_length=self.tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
text_input_ids, untruncated_ids
):
removed_text = self.tokenizer.batch_decode(
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
)
logger.warning(
"The following part of your input was truncated because CLIP can only handle sequences up to"
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
)
if (
hasattr(self.text_encoder.config, "use_attention_mask")
and self.text_encoder.config.use_attention_mask
):
attention_mask = text_inputs.attention_mask.to(device)
else:
attention_mask = None
prompt_embeds = self.text_encoder(
text_input_ids.to(device),
attention_mask=attention_mask,
clip_skip=clip_skip,
)
prompt_embeds = prompt_embeds[0]
bs_embed, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, seq_len, -1)
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance and negative_prompt_embeds is None:
uncond_tokens: List[str]
if negative_prompt is None:
uncond_tokens = [""] * batch_size
elif prompt is not None and type(prompt) is not type(negative_prompt):
raise TypeError(
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
f" {type(prompt)}."
)
elif isinstance(negative_prompt, str):
uncond_tokens = [negative_prompt]
elif batch_size != len(negative_prompt):
raise ValueError(
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
" the batch size of `prompt`."
)
else:
uncond_tokens = negative_prompt
# textual inversion: procecss multi-vector tokens if necessary
if isinstance(self, TextualInversionLoaderMixin):
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
max_length = prompt_embeds.shape[1]
uncond_input = self.tokenizer(
uncond_tokens,
padding="max_length",
max_length=max_length,
truncation=True,
return_tensors="pt",
)
uncond_input_ids = uncond_input.input_ids
if (
hasattr(self.text_encoder.config, "use_attention_mask")
and self.text_encoder.config.use_attention_mask
):
attention_mask = uncond_input.attention_mask.to(device)
else:
attention_mask = None
negative_prompt_embeds = self.text_encoder(
uncond_input_ids.to(device),
attention_mask=attention_mask,
clip_skip=clip_skip,
)
negative_prompt_embeds = negative_prompt_embeds[0]
if do_classifier_free_guidance:
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
seq_len = negative_prompt_embeds.shape[1]
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(
batch_size * num_videos_per_prompt, seq_len, -1
)
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
return prompt_embeds
def interpolate_latents(self, latents: torch.Tensor, interpolation_factor:int, device ):
if interpolation_factor < 2:
return latents
new_latents = torch.zeros(
(latents.shape[0],latents.shape[1],((latents.shape[2]-1) * interpolation_factor)+1, latents.shape[3],latents.shape[4]),
device=latents.device,
dtype=latents.dtype,
)
org_video_length = latents.shape[2]
rate = [i/interpolation_factor for i in range(interpolation_factor)][1:]
new_index = 0
v0 = None
v1 = None
for i0,i1 in zip( range( org_video_length ),range( org_video_length )[1:] ):
v0 = latents[:,:,i0,:,:]
v1 = latents[:,:,i1,:,:]
new_latents[:,:,new_index,:,:] = v0
new_index += 1