-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel.py
1306 lines (1082 loc) · 60.5 KB
/
model.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
import os
import torch
from torch import nn
import transformers
from transformers.utils import logging
from transformers import PreTrainedModel, Blip2QFormerModel, AutoModelForCausalLM
from transformers import CLIPTextConfig, CLIPTextModel
from transformers.modeling_outputs import BaseModelOutputWithPooling
from transformers.models.clip.modeling_clip import CLIPTextTransformer
import sys
from einops import rearrange
from configuration import WorldModelConfig
from typing import Optional, Tuple, Union, List, Dict
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, CLIPTokenizer
from ChatUniVi.constants import DEFAULT_IMAGE_TOKEN
from ChatUniVi.model import ChatUniViLlamaForCausalLM, ChatUniViConfig
sys.path.append('./DynamiCrafter')
from DynamiCrafter.scripts.evaluation.inference import load_model_checkpoint, instantiate_from_config
from DynamiCrafter.lvdm.models.samplers.ddim import DDIMSampler
from DynamiCrafter.lvdm.models.samplers.ddim_multiplecond import DDIMSampler as DDIMSampler_multicond
from omegaconf import OmegaConf
from einops import repeat
from transformers import logging
logging.set_verbosity_error()
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
_make_causal_mask = AttentionMaskConverter._make_causal_mask
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
IMAGE_PREFIX_TOKEN = "[IMG_P]"
logger = logging.get_logger(__name__)
def freeze_sub_models(function):
def wrapper(*args, **kwargs):
model = function(*args, **kwargs)
if model.config.freeze_video_model:
for param in model.video_model.parameters():
param.requires_grad = False
if model.config.use_diffusion_text_encoder and model.config.freeze_diffusion_text_encoder:
for param in model.diffusion_text_encoder.parameters():
param.requires_grad = False
if model.config.use_image_callbacks:
for param in model.diffusion_original_text_encoder.parameters():
param.requires_grad = False
if model.config.freeze_diffusion_qformer:
for param in model.diffusion_qformer.parameters():
param.requires_grad = False
for param in model.diffusion_qformer_proj.parameters():
param.requires_grad = False
model.diffusion_query_tokens.requires_grad = False
for param in model.diffusion_proj.parameters():
param.requires_grad = False
return model
return wrapper
class WorldModel(PreTrainedModel):
config_class = WorldModelConfig
sub_models = ['video_model']
supports_gradient_checkpointing = True
_supports_flash_attn_2 = True
def __init__(self, config: WorldModelConfig):
super().__init__(config)
if config.use_image_prefix:
self.image_prefix = nn.Linear(config.video_model_config.hidden_size, config.image_prefix_length, bias=False)
if config.use_flash_attn:
video_model_config = self._check_and_enable_flash_attn_2(config=config.video_model_config)
else:
video_model_config = config.video_model_config
video_model_config._flash_attn_2_enabled = False
if config.use_image_tokenizer:
self.image_embeddings = nn.Embedding(config.image_vocab_size, config.video_model_config.hidden_size)
self.diffusion_qformer_proj = nn.Linear(config.video_model_config.hidden_size, config.diffusion_qformer_config.hidden_size)
self.diffusion_qformer = Blip2QFormerModel(config.diffusion_qformer_config)
self.diffusion_query_tokens = nn.Parameter(torch.zeros(config.diffusion_text_encoder_config.max_position_embeddings, config.diffusion_qformer_config.hidden_size))
self.diffusion_proj = nn.Linear(config.diffusion_qformer_config.hidden_size, config.diffusion_proj_out_dim)
if config.use_image_callbacks:
self.diffusion_original_text_encoder = CLIPTextModel.from_pretrained(config.diffusion_model_name_or_path, subfolder="text_encoder")
self.diffusion_tokenizer = CLIPTokenizer.from_pretrained(config.diffusion_model_name_or_path,subfolder='tokenizer')
if config.use_diffusion_text_encoder:
self.diffusion_text_encoder = CLIPTextEmbeddingModel(config.diffusion_text_encoder_config)
self.post_init()
self.video_model = AutoModelForCausalLM.from_pretrained(config.video_model_name_or_path, config=video_model_config)
for module in self.video_model.modules():
module._is_hf_initialized = True
if not config.do_alignment:
model_config = OmegaConf.load(config.dynamicrafter)
model_config = model_config.pop("model", OmegaConf.create())
model_config['params']['unet_config']['params']['use_checkpoint'] = False
self.diffusion_model = instantiate_from_config(model_config)
self.diffusion_model.perframe_ae = True
# load_model_checkpoint(self.diffusion_model, config.dynamicrafter_ckpt)
for module in self.diffusion_model.modules():
module._is_hf_initialized = True
if config.use_image_tokenizer:
self.image_embeddings.weight.data.normal_(mean=0.0, std=0.5)
@classmethod
@freeze_sub_models
def from_pretrained(cls, *args, **kwargs):
return super(WorldModel, cls).from_pretrained(*args, **kwargs)
def get_diffusion_conditioning(
self,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = True,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
diffusion_tgt_mask: Optional[torch.LongTensor] = None,
):
# print(f'11 normal {pixel_values.shape=}', flush=True)
# Copy and modify from ChatUniVi forward function ------------------------------------------------------------------------------------------------------------------
video_model = self.video_model
output_attentions = output_attentions if output_attentions is not None else video_model.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else video_model.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else video_model.config.use_return_dict
# Use labels to keep track of the location of image prefix tokens since image features will change the length of the sequence
image_prefix_token_id = self.video_model.config.vocab_size + 1 # ugly hardcode here
labels = input_ids.clone()
input_ids[input_ids.eq(image_prefix_token_id)] = 0
input_ids, attention_mask, past_key_values, inputs_embeds, labels = video_model.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, None, labels, pixel_values)
# print('11 normal', flush=True)
if self.config.use_image_prefix:
bs, seq_len = labels.shape
labels = labels.reshape(-1)
image_prefix_mask = labels.eq(image_prefix_token_id)
inputs_embeds = inputs_embeds.reshape(bs * seq_len, -1)
image_num = image_prefix_mask.sum().item() / self.config.image_prefix_length
assert int(image_num) == image_num
image_prefix_embeddings = self.image_prefix.weight.repeat(int(image_num), 1)
inputs_embeds[image_prefix_mask] = image_prefix_embeddings
inputs_embeds = inputs_embeds.reshape(bs, seq_len, -1)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
# print(f'12 normal {inputs_embeds.shape=}', flush=True)
outputs = video_model.model(
input_ids=input_ids,
attention_mask=attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict
)
# print(f'13 normal {outputs[0].shape}', flush=True)
output_hidden_states = outputs[0]
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------
output_hidden_states = output_hidden_states.reshape(bs * seq_len, -1)
image_outputs_embeds = output_hidden_states[image_prefix_mask][diffusion_tgt_mask]
diffusion_loss = None
img_feat_num = self.config.image_prefix_length # if self.config.use_image_prefix else self.config.num_query_tokens
diffusion_conditioning = image_outputs_embeds.view(-1, img_feat_num, self.config.video_model_config.hidden_size)
diffusion_conditioning = self.diffusion_qformer_proj(diffusion_conditioning)
diffusion_query_tokens = self.diffusion_query_tokens.expand(diffusion_conditioning.shape[0], -1, -1)
diffusion_conditioning = self.diffusion_qformer(
query_embeds=diffusion_query_tokens,
encoder_hidden_states=diffusion_conditioning,
)[0]
diffusion_conditioning = self.diffusion_proj(diffusion_conditioning)
return diffusion_conditioning
@staticmethod
def get_latent_z(model, videos):
b, c, t, h, w = videos.shape
x = rearrange(videos, 'b c t h w -> (b t) c h w')
z = model.encode_first_stage(x)
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
if t == 1:
zero_pad = repeat(torch.zeros_like(z), 'b c t h w -> b c (repeat t) h w', repeat=3)
z = torch.cat([z, zero_pad], dim=2)
z = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=4)
return z
def image_guided_synthesis(self, diffusion_conditioning, videos, diffusion_cond_image, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \
unconditional_guidance_scale=1.0, cfg_img=None, fs=None, multiple_cond_cfg=False, loop=False, gfi=False, timestep_spacing='uniform', guidance_rescale=0.0, **kwargs):
ddim_sampler = DDIMSampler(self.diffusion_model) if not multiple_cond_cfg else DDIMSampler_multicond(self.diffusion_model)
batch_size = noise_shape[0]
fs = torch.tensor([fs] * batch_size, dtype=torch.long, device=self.diffusion_model.device)
# img = videos[:,:,0] #bchw
img = diffusion_cond_image
img_emb = self.diffusion_model.embedder(img) ## blc
img_emb = self.diffusion_model.image_proj_model(img_emb)
# cond_emb = self.diffusion_model.get_learned_conditioning(prompts)
cond_emb = diffusion_conditioning
cond = {"c_crossattn": [torch.cat([cond_emb,img_emb], dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
z = self.get_latent_z(self.diffusion_model, videos) # b c t h w
img_cat_cond = z
cond["c_concat"] = [img_cat_cond] # b c 1 h w
if unconditional_guidance_scale != 1.0:
if self.diffusion_model.uncond_type == "empty_seq":
prompts = batch_size * [""]
uc_emb = self.diffusion_model.get_learned_conditioning(prompts)
elif self.diffusion_model.uncond_type == "zero_embed":
uc_emb = torch.zeros_like(cond_emb)
uc_img_emb = self.diffusion_model.embedder(torch.zeros_like(img)) ## b l c
uc_img_emb = self.diffusion_model.image_proj_model(uc_img_emb)
uc = {"c_crossattn": [torch.cat([uc_emb,uc_img_emb],dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
uc["c_concat"] = [img_cat_cond]
else:
uc = None
## we need one more unconditioning image=yes, text=""
if multiple_cond_cfg and cfg_img != 1.0:
uc_2 = {"c_crossattn": [torch.cat([uc_emb,img_emb],dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
uc_2["c_concat"] = [img_cat_cond]
kwargs.update({"unconditional_conditioning_img_nonetext": uc_2})
else:
kwargs.update({"unconditional_conditioning_img_nonetext": None})
z0 = None
cond_mask = None
batch_variants = []
for _ in range(n_samples):
if z0 is not None:
cond_z0 = z0.clone()
kwargs.update({"clean_cond": True})
else:
cond_z0 = None
if ddim_sampler is not None:
samples, _ = ddim_sampler.sample(S=ddim_steps,
conditioning=cond,
batch_size=batch_size,
shape=noise_shape[1:],
verbose=True,
unconditional_guidance_scale=unconditional_guidance_scale,
unconditional_conditioning=uc,
eta=ddim_eta,
cfg_img=cfg_img,
mask=cond_mask,
x0=cond_z0,
fs=fs,
timestep_spacing=timestep_spacing,
guidance_rescale=guidance_rescale,
precision=diffusion_conditioning.dtype,
**kwargs
)
## reconstruct from latent to pixel space
batch_images = self.diffusion_model.decode_first_stage(samples)
batch_variants.append(batch_images)
## variants, batch, c, t, h, w
batch_variants = torch.stack(batch_variants)
return batch_variants.permute(1, 0, 2, 3, 4, 5)
@torch.no_grad()
def generate(
self,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
diffusion_pixel_values: torch.FloatTensor = None,
diffusion_cond_image: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
tokenizer: Optional[transformers.PreTrainedTokenizer] = None,
**generate_kwargs, # max_new_tokens, guidance_scale
):
assert input_ids.size(0) == 1, "Currently only support batch size 1"
past_key_values = None
output_sequence = input_ids
gen_images = []
img_feat_num = self.config.image_prefix_length if self.config.use_image_prefix else self.config.num_query_tokens
assert input_ids[0][-1] == tokenizer.image_prefix_token_id
diffusion_conditioning = self.get_diffusion_conditioning(input_ids, pixel_values, attention_mask, True, None, None)
diffusion_conditioning = diffusion_conditioning[-1:] # Only generate last video
h, w = diffusion_pixel_values.shape[-2:]
samples = self.image_guided_synthesis(diffusion_conditioning=diffusion_conditioning,
videos=diffusion_pixel_values[None, ...],
diffusion_cond_image=diffusion_cond_image,
noise_shape=[1, 4, self.diffusion_model.temporal_length, h//8, w//8],
**generate_kwargs)
return samples
class CLIPTextEmbeddingTransformer(CLIPTextTransformer):
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
r"""
Returns:
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None:
# raise ValueError("You have to specify input_ids")
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
else:
assert inputs_embeds is not None
input_shape = inputs_embeds.size()[:-1]
hidden_states = inputs_embeds
# CLIP's text model uses causal mask, prepare it here.
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
causal_attention_mask = _make_causal_mask(input_shape, hidden_states.dtype, device=hidden_states.device)
# expand attention_mask
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
encoder_outputs = self.encoder(
inputs_embeds=hidden_states,
attention_mask=attention_mask,
causal_attention_mask=causal_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = encoder_outputs[0]
last_hidden_state = self.final_layer_norm(last_hidden_state)
if not return_dict:
return (last_hidden_state) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
class CLIPTextEmbeddingModel(CLIPTextModel):
def __init__(self, config: CLIPTextConfig):
super().__init__(config)
self.text_model = CLIPTextEmbeddingTransformer(config)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
return self.text_model(
input_ids=input_ids,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
import torch
import uuid
import numpy as np
import torchvision
from PIL import Image
from torch import nn
import transformers
from transformers.utils import logging
from transformers import PreTrainedModel, Blip2QFormerModel, AutoModelForCausalLM
from transformers import CLIPTextConfig, CLIPTextModel
from transformers.modeling_outputs import BaseModelOutputWithPooling
import torch.nn.functional as F
from torch.nn import MSELoss
from transformers.models.clip.modeling_clip import CLIPTextTransformer
import sys
from einops import rearrange
from configuration import WorldModelConfig
from typing import Optional, Tuple, Union, List, Dict
from transformers import AutoTokenizer, AutoConfig
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, CLIPTokenizer
from pytorch_lightning.utilities import grad_norm
from ChatUniVi.constants import DEFAULT_IMAGE_TOKEN
from ChatUniVi.model import ChatUniViLlamaForCausalLM, ChatUniViConfig
import pytorch_lightning as pl
import gradio as gr
import torchvision.transforms as transforms
sys.path.append('./DynamiCrafter')
from DynamiCrafter.scripts.evaluation.inference import load_model_checkpoint, instantiate_from_config
from DynamiCrafter.lvdm.models.samplers.ddim import DDIMSampler
from DynamiCrafter.lvdm.models.samplers.ddim_multiplecond import DDIMSampler as DDIMSampler_multicond
from omegaconf import OmegaConf
from einops import repeat
from transformers import logging
logging.set_verbosity_error()
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
from functools import partial
from pytorch_lightning.utilities import rank_zero_only
ckpt = torch.utils.checkpoint.checkpoint
_make_causal_mask = AttentionMaskConverter._make_causal_mask
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
IMAGE_PREFIX_TOKEN = "[IMG_P]"
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
logger = logging.get_logger(__name__)
logger.setLevel(logging.INFO)
def load_wm(repo_id,training_args=None, model=None):
'''load model, image processor and tokenizer'''
ckpt_name = repo_id.split('/')[-1]
print(f"Start to load model, current ckpt is: {repo_id}")
config = WorldModelConfig.from_pretrained(repo_id)
if training_args is not None:
config.reset_training_args(
do_alignment=training_args.do_alignment,
learning_rate=training_args.learning_rate
)
else:
config.reset_training_args(
do_alignment=False,
)
if model == None:
model = WorldModel.from_pretrained(repo_id, config=config, ignore_mismatched_sizes=True)
# load image processors
image_processor = model.video_model.get_vision_tower().image_processor
diffusion_image_processor= transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])
# load tokenizer
tokenizer = AutoTokenizer.from_pretrained(repo_id)
tokenizer.image_start_token_id = tokenizer.convert_tokens_to_ids("<img_s>")
tokenizer.image_token_id = tokenizer.convert_tokens_to_ids("<image>")
tokenizer.image_prefix_token_id = tokenizer.convert_tokens_to_ids("[IMG_P]")
processor = {
'image_processor':image_processor,
'diffusion_image_processor':diffusion_image_processor,
'tokenizer':tokenizer
}
return model, processor
def dynamic_resize(img):
'''resize frames'''
trans = transforms.Compose([
transforms.Resize(min((576, 1024))),
transforms.CenterCrop((576, 1024))
])
return trans(img)
def freeze_sub_models(function):
def wrapper(*args, **kwargs):
model = function(*args, **kwargs)
model.train()
if model.config.freeze_video_model:
model.video_model.eval()
for param in model.video_model.parameters():
param.requires_grad = False
if model.config.do_alignment:
model.diffusion_text_encoder.eval()
for param in model.diffusion_text_encoder.parameters():
param.requires_grad = False
if model.config.use_image_callbacks:
for param in model.diffusion_original_text_encoder.parameters():
param.requires_grad = False
if model.config.freeze_diffusion_qformer:
model.diffusion_qformer.eval()
model.diffusion_qformer_proj.eval()
model.diffusion_query_tokens.eval()
model.diffusion_proj.eval()
for param in model.diffusion_qformer.parameters():
param.requires_grad = False
for param in model.diffusion_qformer_proj.parameters():
param.requires_grad = False
model.diffusion_query_tokens.requires_grad = False
for param in model.diffusion_proj.parameters():
param.requires_grad = False
return model
return wrapper
class WorldModel(PreTrainedModel, pl.LightningModule):
config_class = WorldModelConfig
sub_models = ['video_model']
supports_gradient_checkpointing = True
_supports_flash_attn_2 = True
def __init__(self, config: WorldModelConfig):
super().__init__(config)
if config.use_image_prefix:
self.image_prefix = nn.Linear(config.video_model_config.hidden_size, config.image_prefix_length, bias=False)
if config.use_flash_attn:
video_model_config = self._check_and_enable_flash_attn_2(config=config.video_model_config)
else:
video_model_config = config.video_model_config
video_model_config._flash_attn_2_enabled = False
if config.use_image_tokenizer:
self.image_embeddings = nn.Embedding(config.image_vocab_size, config.video_model_config.hidden_size)
self.diffusion_qformer_proj = nn.Linear(config.video_model_config.hidden_size, config.diffusion_qformer_config.hidden_size)
self.diffusion_qformer = Blip2QFormerModel(config.diffusion_qformer_config)
self.diffusion_query_tokens = nn.Parameter(torch.zeros(config.diffusion_text_encoder_config.max_position_embeddings, config.diffusion_qformer_config.hidden_size))
self.diffusion_proj = nn.Linear(config.diffusion_qformer_config.hidden_size, config.diffusion_proj_out_dim)
if config.use_image_callbacks:
self.diffusion_original_text_encoder = CLIPTextModel.from_pretrained(config.diffusion_model_name_or_path, subfolder="text_encoder")
self.diffusion_tokenizer = CLIPTokenizer.from_pretrained(config.diffusion_model_name_or_path,subfolder='tokenizer')
if config.do_alignment:
from lvdm.modules.encoders.condition import FrozenOpenCLIPEmbedder
self.diffusion_text_encoder = FrozenOpenCLIPEmbedder(layer="penultimate", freeze=True)
self.post_init()
self.video_model = AutoModelForCausalLM.from_pretrained(config.video_model_name_or_path, config=video_model_config)
for module in self.video_model.modules():
module._is_hf_initialized = True
if not config.do_alignment:
model_config = OmegaConf.load(config.dynamicrafter)
model_config = model_config.pop("model", OmegaConf.create())
self.diffusion_model = instantiate_from_config(model_config)
self.diffusion_model.perframe_ae = True
# load_model_checkpoint(self.diffusion_model, config.dynamicrafter_ckpt)
for module in self.diffusion_model.modules():
module._is_hf_initialized = True
if config.use_image_tokenizer:
self.image_embeddings.weight.data.normal_(mean=0.0, std=0.5)
@classmethod
@freeze_sub_models
def from_pretrained(cls, *args, **kwargs):
return super(WorldModel, cls).from_pretrained(*args, **kwargs)
def get_diffusion_conditioning(
self,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = True,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
diffusion_tgt_mask: Optional[torch.LongTensor] = None,
):
# print(f'11 normal {pixel_values.shape=}', flush=True)
# Copy and modify from ChatUniVi forward function ------------------------------------------------------------------------------------------------------------------
video_model = self.video_model
output_attentions = output_attentions if output_attentions is not None else video_model.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else video_model.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else video_model.config.use_return_dict
# Use labels to keep track of the location of image prefix tokens since image features will change the length of the sequence
image_prefix_token_id = self.video_model.config.vocab_size + 1 # ugly hardcode here
labels = input_ids.clone()
input_ids[input_ids.eq(image_prefix_token_id)] = 0
input_ids, attention_mask, past_key_values, inputs_embeds, labels = video_model.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, None, labels, pixel_values)
# print('11 normal', flush=True)
if self.config.use_image_prefix:
bs, seq_len = labels.shape
labels = labels.reshape(-1)
image_prefix_mask = labels.eq(image_prefix_token_id)
inputs_embeds = inputs_embeds.reshape(bs * seq_len, -1)
image_num = image_prefix_mask.sum().item() / self.config.image_prefix_length
assert int(image_num) == image_num
image_prefix_embeddings = self.image_prefix.weight.repeat(int(image_num), 1)
inputs_embeds[image_prefix_mask] = image_prefix_embeddings
inputs_embeds = inputs_embeds.reshape(bs, seq_len, -1)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
# print(f'12 normal {inputs_embeds.shape=}', flush=True)
outputs = video_model.model(
input_ids=input_ids,
attention_mask=attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict
)
# print(f'13 normal {outputs[0].shape}', flush=True)
output_hidden_states = outputs[0]
#--------------------------------------------------------------------------------------------------------------------------------------------------------------------
output_hidden_states = output_hidden_states.reshape(bs * seq_len, -1)
image_outputs_embeds = output_hidden_states[image_prefix_mask][diffusion_tgt_mask]
diffusion_loss = None
img_feat_num = self.config.image_prefix_length # if self.config.use_image_prefix else self.config.num_query_tokens
diffusion_conditioning = image_outputs_embeds.view(-1, img_feat_num, self.config.video_model_config.hidden_size)
diffusion_conditioning = self.diffusion_qformer_proj(diffusion_conditioning)
diffusion_query_tokens = self.diffusion_query_tokens.expand(diffusion_conditioning.shape[0], -1, -1)
diffusion_conditioning = self.diffusion_qformer(
query_embeds=diffusion_query_tokens,
encoder_hidden_states=diffusion_conditioning,
)[0]
diffusion_conditioning = self.diffusion_proj(diffusion_conditioning)
return diffusion_conditioning
@staticmethod
def get_latent_z(model, videos):
b, c, t, h, w = videos.shape
x = rearrange(videos, 'b c t h w -> (b t) c h w')
z = model.encode_first_stage(x)
z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
if t == 1:
# zero_pad = repeat(torch.zeros_like(z), 'b c t h w -> b c (repeat t) h w', repeat=3)
# z = torch.cat([z, zero_pad], dim=2)
z = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=4)
z = repeat(z, 'b c t h w -> b c (repeat t) h w', repeat=4)
return z
def image_guided_synthesis(self, diffusion_conditioning, videos, diffusion_cond_image, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1., \
unconditional_guidance_scale=1.0, cfg_img=None, fs=None, multiple_cond_cfg=False, loop=False, gfi=False, timestep_spacing='uniform', guidance_rescale=0.0, **kwargs):
ddim_sampler = DDIMSampler(self.diffusion_model) if not multiple_cond_cfg else DDIMSampler_multicond(self.diffusion_model)
batch_size = noise_shape[0]
fs = torch.tensor([fs] * batch_size, dtype=torch.long, device=self.diffusion_model.device)
# img = videos[:,:,0] #bchw
img = diffusion_cond_image
img_emb = self.diffusion_model.embedder(img) ## blc
img_emb = self.diffusion_model.image_proj_model(img_emb)
# cond_emb = self.diffusion_model.get_learned_conditioning(prompts)
cond_emb = diffusion_conditioning
cond = {"c_crossattn": [torch.cat([cond_emb,img_emb], dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
z = self.get_latent_z(self.diffusion_model, videos) # b c t h w
img_cat_cond = z
cond["c_concat"] = [img_cat_cond] # b c 1 h w
if unconditional_guidance_scale != 1.0:
if self.diffusion_model.uncond_type == "empty_seq":
prompts = batch_size * [""]
uc_emb = self.diffusion_model.get_learned_conditioning(prompts)
elif self.diffusion_model.uncond_type == "zero_embed":
uc_emb = torch.zeros_like(cond_emb)
uc_img_emb = self.diffusion_model.embedder(torch.zeros_like(img)) ## b l c
uc_img_emb = self.diffusion_model.image_proj_model(uc_img_emb)
uc = {"c_crossattn": [torch.cat([uc_emb,uc_img_emb],dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
uc["c_concat"] = [img_cat_cond]
else:
uc = None
## we need one more unconditioning image=yes, text=""
if multiple_cond_cfg and cfg_img != 1.0:
uc_2 = {"c_crossattn": [torch.cat([uc_emb,img_emb],dim=1)]}
if self.diffusion_model.model.conditioning_key == 'hybrid':
uc_2["c_concat"] = [img_cat_cond]
kwargs.update({"unconditional_conditioning_img_nonetext": uc_2})
else:
kwargs.update({"unconditional_conditioning_img_nonetext": None})
z0 = None
cond_mask = None
batch_variants = []
for _ in range(n_samples):
if z0 is not None:
cond_z0 = z0.clone()
kwargs.update({"clean_cond": True})
else:
cond_z0 = None
if ddim_sampler is not None:
samples, _ = ddim_sampler.sample(S=ddim_steps,
conditioning=cond,
batch_size=batch_size,
shape=noise_shape[1:],
verbose=True,
unconditional_guidance_scale=unconditional_guidance_scale,
unconditional_conditioning=uc,
eta=ddim_eta,
cfg_img=cfg_img,
mask=cond_mask,
x0=cond_z0,
fs=fs,
timestep_spacing=timestep_spacing,
guidance_rescale=guidance_rescale,
precision=diffusion_conditioning.dtype,
**kwargs
)
## reconstruct from latent to pixel space
batch_images = self.diffusion_model.decode_first_stage(samples)
batch_variants.append(batch_images)
## variants, batch, c, t, h, w
batch_variants = torch.stack(batch_variants)
return batch_variants.permute(1, 0, 2, 3, 4, 5)
@torch.no_grad()
def generate(
self,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
diffusion_pixel_values: torch.FloatTensor = None,
diffusion_cond_image: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
tokenizer: Optional[transformers.PreTrainedTokenizer] = None,
**generate_kwargs, # max_new_tokens, guidance_scale
):
assert input_ids.size(0) == 1, "Currently only support batch size 1"
past_key_values = None
output_sequence = input_ids
gen_images = []
img_feat_num = self.config.image_prefix_length if self.config.use_image_prefix else self.config.num_query_tokens
assert input_ids[0][-1] == tokenizer.image_prefix_token_id
# print("use FrozenOpenCLIPEmbedder")
# caption = tokenizer.decode(input_ids[0],skip_special_tokens=True)
# diffusion_conditioning = self.diffusion_model.cond_stage_model(caption)
diffusion_conditioning = self.get_diffusion_conditioning(input_ids, pixel_values, attention_mask, True, None, None)
diffusion_conditioning = diffusion_conditioning[-1:] # Only generate last video
h, w = diffusion_pixel_values.shape[-2:]
samples = self.image_guided_synthesis(diffusion_conditioning=diffusion_conditioning,
videos=diffusion_pixel_values[None, ...],
diffusion_cond_image=diffusion_cond_image,
noise_shape=[1, 4, self.diffusion_model.temporal_length, h//8, w//8],
**generate_kwargs)
return samples
def get_input(self, x):
'''
if len(x.shape) == 3:
x = x[..., None]
x = rearrange(x, 'b h w c -> b c h w')
'''
x = x.to(memory_format=torch.contiguous_format).float()
return x
def get_batch_input(
self,
video,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
diffusion_pixel_values: torch.FloatTensor = None,
diffusion_cond_image: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
fps=None,
frame_stride=None,
random_uncond=True,
**kwargs
):
## x: b c t h w
assert input_ids.size(0) == 1, "Currently only support batch size 1"
pixel_values = pixel_values[0]
diffusion_cond_image = diffusion_cond_image[0]
try:
assert input_ids[0][-1] == 32001
except AssertionError:
print("Assertion failed. The value of input_ids[0] is:")
print(input_ids[0])
## x: b c t h w
x = self.get_input(video)
z = self.diffusion_model.encode_first_stage(x)
diffusion_conditioning = self.get_diffusion_conditioning(input_ids, pixel_values, attention_mask, True, None, None)
cond_emb = diffusion_conditioning[-1:]
cond = {}
## to support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
if random_uncond:
random_num = torch.rand(x.size(0), device=x.device)
else:
random_num = torch.ones(x.size(0), device=x.device) ## by doning so, we can get text embedding and complete img emb for inference
prompt_mask = rearrange(random_num < 2 * self.diffusion_model.uncond_prob, "n -> n 1 1")
input_mask = 1 - rearrange((random_num >= self.diffusion_model.uncond_prob).float() * (random_num < 3 * self.diffusion_model.uncond_prob).float(), "n -> n 1 1 1")
null_prompt = self.diffusion_model.get_learned_conditioning([""])
prompt_emb = torch.where(prompt_mask, null_prompt, cond_emb)
img = diffusion_cond_image[0]
img = input_mask * img
## img: b c h w
img_emb = self.diffusion_model.embedder(img)
img_emb = self.diffusion_model.image_proj_model(img_emb)
if self.diffusion_model.model.conditioning_key == 'hybrid':
## encode video frames x to z via a 2D encoder
img_cat_cond = self.get_latent_z(self.diffusion_model, diffusion_pixel_values)
cond["c_concat"] = [img_cat_cond] # b c t h w
cond["c_crossattn"] = [torch.cat([prompt_emb, img_emb], dim=1)] ## concat in the seq_len dim
out = [z, cond, fps]
return out
def alignment_forward(
self,
video,
caption,
input_ids: torch.FloatTensor,
pixel_values: torch.FloatTensor = None,
diffusion_pixel_values: torch.FloatTensor = None,
diffusion_cond_image: torch.FloatTensor = None,
attention_mask: Optional[torch.LongTensor] = None,
frame_stride=None,
random_uncond=True,
**kwargs
):
## x: b c t h w
assert input_ids.size(0) == 1, "Currently only support batch size 1"
pixel_values = pixel_values[0]
diffusion_cond_image = diffusion_cond_image[0]
caption = caption[0]
assert input_ids[0][-1] == 32001
## x: b c t h w
diffusion_conditioning = self.get_diffusion_conditioning(input_ids, pixel_values, attention_mask, True, None, None)
llm_cond_emb = diffusion_conditioning[-1:]
clip_cond_emb = self.diffusion_text_encoder(caption)
# KLDivLoss
log_llm_cond_emb = torch.log_softmax(llm_cond_emb, dim=-1)
clip_cond_emb_probs = torch.softmax(clip_cond_emb, dim=-1)
kl_loss = nn.KLDivLoss(reduction='batchmean')
loss = kl_loss(log_llm_cond_emb, clip_cond_emb_probs)
# MSELoss
# mse_loss = torch.nn.MSELoss()
# loss = mse_loss(llm_cond_emb, clip_cond_emb)
return loss, {"loss":loss}
def training_step(self, batch, batch_idx):
# if batch_idx%200==0:
# print(self.image_prefix.weight)
if not self.config.do_alignment:
x, c, fs = self.get_batch_input(**batch, random_uncond=False)
kwargs= {"fs": fs.long()}
loss, loss_dict = self.diffusion_model(x, c, **kwargs)
else:
loss, loss_dict = self.alignment_forward(**batch)
## sync_dist | rank_zero_only
# loss_dict.update({"global_step": int(self.global_step)})
self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=False)
return loss
# def on_before_optimizer_step(self, optimizer):
# # Compute the 2-norm for each layer
# # If using mixed precision, the gradients are already unscaled here
# import deepspeed
# norms = deepspeed.utils.safe_get_full_grad(self.image_prefix, norm_type=2)
# self.log_dict(norms)
def configure_optimizers(self):
lr = self.config.learning_rate
params = list()
if not self.config.do_alignment:
params = list(self.diffusion_model.model.parameters())
params.append(self.diffusion_query_tokens)
params.extend(list(self.image_prefix.parameters()))
params.extend(list(self.diffusion_proj.parameters()))
params.extend(list(self.diffusion_qformer.parameters()))
params.extend(list(self.diffusion_qformer_proj.parameters()))
## optimizer
optimizer = torch.optim.AdamW(params, lr=lr)
if self.config.do_alignment:
logger.info("Setting up scheduler...")
T_max = self.trainer.max_steps # 根据训练的最大epochs设置T_max
lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=T_max, eta_min=1e-6)
return [optimizer], [{'scheduler': lr_scheduler, 'interval': 'step', 'frequency': 1}]
return optimizer
@torch.no_grad()
def log_images(self, batch, sample=True, ddim_steps=50, ddim_eta=1., plot_denoise_rows=False, \
unconditional_guidance_scale=1.0, mask=None, **kwargs):
""" log images for LatentVisualDiffusion """
return {"image":batch["pixel_values"]}
class ChatWM():
def __init__(self, model, processor, training_args=None, video_path=None):
self.model = model
self.image_processor = processor['image_processor']
self.diffusion_image_processor = processor['diffusion_image_processor']
self.tokenizer = processor['tokenizer']
self.generate_kwargs = {
"unconditional_guidance_scale": 4,
"ddim_steps": 50,
"ddim_eta": 1.0,
"fs": 15,
"timestep_spacing": "uniform_trailing",
"n_samples": 4,
}
self.cat_videos = []
self.text = ''
self.pixel_values = None
self.diffusion_cond_image = None