-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmodel.py
More file actions
1670 lines (1398 loc) · 91.7 KB
/
model.py
File metadata and controls
1670 lines (1398 loc) · 91.7 KB
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 math
import random
import types
import time
from collections import defaultdict
from contextlib import nullcontext
from functools import cached_property, partial
from contextlib import ExitStack
from numpy import mask_indices
from unidisc.utils.tensor_utils import get_contiguous_blocks, get_contiguous_blocks_per_sample, get_interleaved_indices
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint
from accelerate.utils import gather, gather_object
from einops import rearrange
from tensordict import TensorDict
from torch import Tensor, nn
from tqdm.auto import tqdm
import model_eval
import model_setup
import model_utils
import utils
from decoupled_utils import (Profiler, barrier, dprint, get_rank, get_world_size, gprint,
is_local_main_process, is_main_process,
is_torch_cuda_available, is_torch_xla_available,
print_memory, rprint, save_memory_profile,
synchronize_device, try_except, use_dist)
from unidisc.tokenizers.image_tokenizers import (decode_latents, get_image_batch,
get_vae, vae_encode_image)
from unidisc.utils.cuda_utils import sync_times
from unidisc.utils.xla_utils import shard_output
from model_utils import (Loss, ddprint, ema_update, empty_device_cache, get_chameleon_txt_indices, get_interleaved_block_mask, log,
replace_nan_dict, update_histogram, update_logs, get_block_mask)
from unidisc.utils.trainer_utils import TrainingState, incremental_dict_update, linear_warmup
is_xla_available = is_torch_xla_available()
if is_xla_available:
import torch_xla
from torch_xla.distributed.spmd import XLAShardedTensor
def maybe_unwrap(t: torch.Tensor) -> torch.Tensor:
return t.global_tensor if isinstance(t, XLAShardedTensor) else t
class Diffusion:
def __init__(self, config, tokenizer, device, disable_init=False):
super().__init__()
setup_methods = [
'init', 'to', 'get_params', 'get_vae', 'get_cond_vae', 'configure_optimizers',
'_validate_configuration', 'register_signal_handler', 'on_train_start',
'optimizer_step', 'init_dataloader', 'set_accelerator', 'set_callbacks',
'on_train_step_end', 'init_optimizer_lr_scheduler', 'after_backward', 'checkpoint',
'print_hashes', 'shortcut_return', 'reset_validation_metrics', 'unwrap_model'
]
for method_name in setup_methods:
setattr(self, method_name, types.MethodType(getattr(model_setup, method_name), self))
utils_methods = [
'get_coord_plot', '_score_entropy', 'sample_subs_guidance',
'restore_model_and_semi_ar_sample', '_reconstruction_loss',
'restore_model_and_sample', 'get_score', '_staggered_score',
'_analytic_update', '_denoiser_update', '_transp_transition',
'eval_retokenize', 'compute_generative_perplexity', '_d3pm_loss',
'_d3pm_parameterization', '_sedd_parameterization',
'get_base_shapes_for_mup', 'update_histogram', '_maybe_sub_sample',
'viz_images_from_dataloader', 'compute_cider'
]
for method_name in utils_methods:
setattr(self, method_name, types.MethodType(getattr(model_utils, method_name), self))
eval_methods = [
'get_every_n_evals', 'on_validation_epoch_start', 'sample',
'predict_step', 'validation_step', 'on_validation_epoch_end',
'on_validation_epoch_cleanup', '_sample_prior', '_ddpm_forward',
'_ddpm_update', '_ddpm_caching_update', '_sample', '_ar_sampler',
'decode_batch', 'sample_transfusion', 'sample_continuous_image',
'decode_sampling', '_ddpm_update_finetune_controlled_tweedie',
'sample_masking', 'log_flops', "visualize_samples", "_maskgit_update",
"_first_hitting_update", "update_inline_fid", "compute_inline_fid",
"update_clean_fid", "compute_clean_fid_eval", "sample_for_fid",
"compute_clip_score", "mauve_store_references", "zero_shot_eval_step",
"zero_shot_eval_epoch_end", "get_cfg_weight", "cleanup_fid_output",
"calculate_chameleon_perplexity", "get_anole_data",
"update_img_to_txt_mauve_clip", "compute_mauve_entropy",
"get_top_k", "compute_entropy", "get_mauve_score", "get_valid_seq", "gather_tokens",
"count_valid_tokens", "compute_val_metrics_standalone", "_maskgit_nucleus_update",
"get_img_text_saturation_batch", "handle_interleaved_decode", "get_interleaved_image",
"auto_enhance", "get_clip_score", "get_dfn_score", "get_hpsv2_score", "get_model_likelihood_score",
"get_laion_aesthetic_score", "get_rewards", "get_chameleon_score", "clear_reward_models",
"get_text_likelihood_score", "get_text_reward_model_score", "save_image_text_pair"
]
for method_name in eval_methods:
setattr(self, method_name, types.MethodType(getattr(model_eval, method_name), self))
if disable_init:
pass
else:
model_setup.init(self, config, tokenizer, device)
@cached_property
def xla_mesh(self):
import torch_xla.distributed.spmd as xs
return xs.get_global_mesh()
def on_train_resume(self):
if not is_torch_xla_available():
empty_device_cache()
if self.ema is not None and not self.config.trainer.use_custom_ema:
self.ema.restore(self.get_params(), raise_error_if_already_restored=False)
self.backbone.train()
def zero_shot_update_batch(self, batch):
dataset = self.config.data.train
if dataset is None:
return batch
def get_attr(attr_name):
return getattr(self.config.model, attr_name, None)
if dataset == "nlphuji/flickr30k":
# image captioning dataset
# above thing but order is [txt, img]
batch['gt_input_ids'] = batch['input_ids']
image_input_ids = get_image_batch(self.config, self.get_vae(), batch, self.device)
image_input_ids += self.text_vocab_size
batch["input_ids"] = torch.cat([torch.zeros_like(batch['gt_input_ids'], dtype=torch.int64), image_input_ids], dim=-1).to(self.device)
batch['attention_mask'] = torch.cat([torch.zeros_like(batch['gt_input_ids'], dtype=torch.bool), torch.ones_like(image_input_ids, dtype=torch.bool)], dim=-1).to(self.device)
batch["modality"] = torch.cat([torch.zeros_like(batch['gt_input_ids'], dtype=torch.int64), torch.ones_like(image_input_ids, dtype=torch.int64)], dim=-1).to(self.device)
elif dataset == "facebook/winoground":
# get image and text input ids
caption_0_input_ids = batch['caption_0_input_ids']
caption_1_input_ids = batch['caption_1_input_ids']
image_0 = batch['img_0']
image_1 = batch['img_1']
# tokenize and store captions separately
image_0_input_ids = vae_encode_image(self.config, self.get_vae(), image_0, self.device, get_attr("vae_type")) + self.text_vocab_size
image_1_input_ids = vae_encode_image(self.config, self.get_vae(), image_1, self.device, get_attr("vae_type")) + self.text_vocab_size
# make 4 combinat ions of image and text
batch['input_ids_0_0'] = torch.cat([caption_0_input_ids, image_0_input_ids], dim=-1).to(self.device)
batch['input_ids_0_1'] = torch.cat([caption_0_input_ids, image_1_input_ids], dim=-1).to(self.device)
batch['input_ids_1_0'] = torch.cat([caption_1_input_ids, image_0_input_ids], dim=-1).to(self.device)
batch['input_ids_1_1'] = torch.cat([caption_1_input_ids, image_1_input_ids], dim=-1).to(self.device)
batch['attention_mask'] = torch.cat([torch.zeros_like(caption_0_input_ids, dtype=torch.bool), torch.ones_like(image_0_input_ids, dtype=torch.bool)], dim=-1).to(self.device)
batch['modality'] = torch.cat([torch.zeros_like(caption_0_input_ids, dtype=torch.int64), torch.ones_like(image_0_input_ids, dtype=torch.int64)], dim=-1).to(self.device)
# elif dataset == "facebook/winoground":
batch["modality_mask"] = F.one_hot(batch["modality"], num_classes=2).to(torch.bool)
return batch
def update_batch(self, batch):
if getattr(self.config.eval, 'big_seq_len_eval', False):
# new batch of 8192 seq length with txt length 4096 and img length 4096s
N = self.config.model.length
new_batch = dict()
new_batch['input_ids'] = torch.zeros(batch['input_ids'].shape[0], N, device=self.device, dtype=batch['input_ids'].dtype)
new_batch['attention_mask'] = torch.ones(batch['attention_mask'].shape[0], N, device=self.device, dtype=batch['attention_mask'].dtype)
new_batch['modality'] = torch.zeros(batch['modality'].shape[0], N, device=self.device, dtype=batch['modality'].dtype)
new_batch['modality'][:, N//2:] = 1
new_batch['modality_mask'] = F.one_hot(new_batch['modality'], num_classes=2).to(torch.bool)
batch = new_batch
return batch
continuous_mode = self.config.trainer.image_mode == "continuous"
if batch is None:
gprint(f"Warning! Batch is None")
return batch
if isinstance(batch, TensorDict):
batch.batch_size = (batch.batch_size[0],)
if self.image_model or getattr(self.config.data, "force_image_dataset", False):
text_input_ids = None
if isinstance(batch, TensorDict) and (self.is_compiled or getattr(self.config.trainer, "force_convert_to_dict", False)):
batch = dict(batch.items())
if "txt_input_ids" in batch or "img_input_ids" in batch:
index_keys = ["img_input_ids", "txt_input_ids", "sample_ids"]
for key in index_keys:
if key in batch:
if isinstance(batch[key], list):
batch[key] = torch.stack(batch[key], dim=0)
batch[key] = batch[key].to(torch.int64)
index_keys = ["img_label"]
for key in index_keys:
if key in batch:
batch[key] = batch[key].squeeze(-1)
img_input_ids = batch.pop("img_input_ids")
batch["input_ids"] = img_input_ids
batch["attention_mask"] = torch.ones_like(img_input_ids).to(torch.bool)
if "txt_input_ids" in batch:
batch["input_ids"] = torch.cat([batch["txt_input_ids"], batch["input_ids"] + self.text_vocab_size], dim=-1)
batch["attention_mask"] = torch.cat([batch["txt_attention_mask"], batch["attention_mask"]], dim=-1)
batch["input_ids"] = batch["input_ids"].to(torch.int64)
if "modality" not in batch:
if getattr(self.config.trainer, "ignore_text_in_unified", False):
modality = torch.ones_like(batch["input_ids"], dtype=torch.int64)
else:
assert self.config.model.txt_length > 0 and self.config.model.img_length > 0
modality = torch.zeros_like(batch["input_ids"], dtype=torch.int64)
modality[:, -img_input_ids.shape[-1]:] = 1
batch["modality"] = modality
elif (self.config.trainer.multimodal_batches or continuous_mode) and \
not getattr(self.config.trainer, "use_legacy_update_batch_fn", False):
if "img" in batch:
is_image_batch = (batch["modality"] == 1).all(dim=-1)
image_input_ids = get_image_batch(self.config, self.get_vae(), batch, self.device)
assert ((batch["modality"].sum(dim=-1) == 0) | (batch["modality"].sum(dim=-1) >= image_input_ids.shape[1])).all()
if getattr(self.config.trainer, "add_label", False):
assert (batch["modality"] == 1).all()
batch["input_ids"][:, 1:] = torch.where(is_image_batch[:, None], image_input_ids, batch["input_ids"][:, 1:])
elif image_input_ids.ndim == 3:
batch["img_emb"] = torch.where((batch["modality"] == 1)[:, :, None], image_input_ids, torch.nan)
elif (batch["input_ids"][batch["modality"] == 1] == -1).all():
batch["input_ids"].masked_scatter_(batch["modality"] == 1, image_input_ids)
else:
batch["input_ids"] = torch.where(is_image_batch[:, None], image_input_ids, batch["input_ids"])
if getattr(self.config.trainer, "force_shift_raw_image_batches", False):
assert not getattr(self.config.trainer, "force_shift_image_batches", False)
batch["input_ids"] = torch.where(batch["modality"] == 1, batch["input_ids"] + self.text_vocab_size, batch["input_ids"])
else:
if getattr(self.config.trainer, "add_label", False):
shift_index = self.vocab_size - self.config.model.add_labels
batch["input_ids"] = torch.cat([batch["label"] + shift_index, batch["input_ids"]], dim=-1)
batch["attention_mask"] = torch.cat([torch.zeros_like(batch["label"], dtype=torch.bool), batch["attention_mask"]], dim=-1)
batch["modality"] = torch.cat([torch.ones_like(batch["label"], dtype=torch.int64), batch["modality"]], dim=-1)
assert (batch["modality"] == 1).all()
batch["input_ids"] = batch["input_ids"].to(torch.int64)
if "sample_ids" in batch:
batch["sample_ids"] = batch["sample_ids"].to(torch.int64)
if getattr(self.config.trainer, "force_shift_image_batches", False):
batch["input_ids"] = torch.where(batch["modality"] == 1, batch["input_ids"] + self.text_vocab_size, batch["input_ids"])
else:
if continuous_mode:
assert False
else:
if "input_ids" in batch and not self.config.trainer.ignore_text_in_unified:
assert self.config.model.unified_model
assert "attention_mask" in batch
text_input_ids = batch["input_ids"]
image_ids = get_image_batch(self.config, self.get_vae(), batch, self.device)
image_attention_mask = torch.ones_like(image_ids).to(torch.bool)
if "cond_img" in batch:
cond_image_ids = get_image_batch(self.config, self.get_cond_vae(), batch, self.device, use_cond=True)
batch["cond_input_ids"] = cond_image_ids
if text_input_ids is not None:
assert batch["input_ids"].shape[1] == self.config.model.txt_length
assert image_ids.shape[1] == self.config.model.img_length
image_ids = image_ids + self.text_vocab_size
batch["input_ids"] = torch.cat([batch["input_ids"].to(self.device), image_ids], dim=-1)
batch["attention_mask"] = torch.cat([batch["attention_mask"].to(self.device), image_attention_mask], dim=-1).to(torch.bool)
assert batch["input_ids"].shape[1] == batch["attention_mask"].shape[1] == self.config.model.length
batch["modality"] = torch.zeros_like(batch["input_ids"], dtype=torch.int64)
batch["modality"][:, -image_ids.shape[-1]:] = 1
else:
assert self.unified_model is False
batch["input_ids"] = image_ids
batch["attention_mask"] = image_attention_mask
batch["modality"] = torch.ones_like(batch["input_ids"], dtype=torch.int64)
if "txt_x0_unmask" in batch and "img_x0_unmask" in batch:
assert not continuous_mode
batch["gt_img_input_ids"] = image_ids
batch["x0_unmask"] = torch.cat([batch["txt_x0_unmask"], batch["img_x0_unmask"]], dim=-1)
batch["input_ids"][~batch["x0_unmask"]] = self.mask_index
if (batch["input_ids"].shape[1] != self.config.model.length) and not self.config.trainer.ar_inpainting:
gprint(f"Warning! Input ids shape: {batch['input_ids'].shape}, model length: {self.config.model.length}")
batch["input_ids"] = batch["input_ids"][:, : self.config.model.length]
assert False, f"input ids are not the correct length input ids shape: {batch['input_ids'].shape}, model length: {self.config.model.length}"
if getattr(self.config.model, "img_cond", False):
assert "cond_input_ids" in batch
assert not continuous_mode
if "modality" in batch:
batch["modality"] = batch["modality"].to(torch.int64)
if self.config.trainer.multimodal_batches and batch["modality"].ndim == 2 and batch["modality"].shape[-1] == 1:
batch["modality"] = batch["modality"].repeat(1, self.config.model.length)
else:
if self.image_model and not self.config.trainer.multimodal_batches:
assert self.config.model.txt_length > 0 and self.config.model.img_length > 0
modality = torch.zeros_like(batch["input_ids"], dtype=torch.int64)
modality[:, self.static_img_sl] = 1
batch["modality"] = modality
elif self.config.data.txt_only:
batch["modality"] = torch.zeros_like(batch["input_ids"], dtype=torch.int64)
if "modality" in batch:
batch["modality"][batch["modality"] == -1] = 0
assert batch["modality"].min() == 0 and batch["modality"].max() == 1
batch["modality_mask"] = F.one_hot(batch["modality"], num_classes=2).to(torch.bool)
batch["batch_contains_img"] = (batch["modality"] == 1).any(dim=-1)
batch['txt_sl'] = self.txt_sl(batch)
batch['img_sl'] = self.img_sl(batch)
if getattr(self.config.trainer, "force_remove_img_tokens", False):
assert not continuous_mode
batch["input_ids"] = batch["input_ids"][batch['txt_sl']]
batch["attention_mask"] = batch["attention_mask"][batch['txt_sl']]
if getattr(self.config.trainer, "add_label", False):
assert getattr(self.config.model, "add_labels", False)
assert "label" in batch
batch["label"] = batch["label"].to(torch.int64)
assert 0 <= batch["label"].min() and batch["label"].max() < self.config.model.add_labels
shift_index = self.vocab_size - self.config.model.add_labels
assert batch["input_ids"].shape[-1] == self.config.model.length
if batch["label"].ndim == 1:
batch["input_ids"][:, [0]] = (batch["label"] + shift_index).unsqueeze(-1)
else:
batch["input_ids"][:, [0]] = batch["label"] + shift_index
batch["attention_mask"][:, 0] = False
if isinstance(batch, dict):
for key in batch.keys():
if isinstance(batch[key], torch.Tensor):
batch[key] = batch[key].to(self.device)
elif isinstance(batch, TensorDict):
assert self.config.backbone != "gemma"
batch = batch.to(self.device)
if getattr(self.config.trainer, "force_full_attention_mask", False):
batch["attention_mask"] = torch.ones_like(batch["attention_mask"], dtype=torch.bool)
batch["attention_mask"] = batch["attention_mask"].to(torch.bool)
if self.config.data.require_sample_ids:
assert "sample_ids" in batch
batch["sample_ids"][~(batch["attention_mask"].bool())] = -1
batch["attention_mask"][batch["sample_ids"] == -1] = False
# Flip [txt, img] -> [img, txt]
# TODO: Flip by sample not batch. As we train w/~8 batches, it's for now
if (self.training or getattr(self.config.trainer, "force_flip_ar_val", False)) and self.config.parameterization == "ar" and getattr(self.config.trainer, "rand_flip_ar_prob", None) is not None:
assert (batch["modality"][:, :self.config.model.txt_length] == 0).all() and (batch["modality"][:, self.config.model.txt_length:] == 1).all(), "Modality does not match img_before_txt configuration"
batch_flip_mask = torch.rand(batch["modality"].shape[0], device=self.device) < self.config.trainer.rand_flip_ar_prob
img_slice = slice(-self.config.model.img_length, None)
txt_slice = slice(None, self.config.model.txt_length)
for key in ["modality", "attention_mask", "input_ids"]:
batch[key][batch_flip_mask] = torch.cat([batch[key][batch_flip_mask][:, img_slice], batch[key][batch_flip_mask][:, txt_slice]], dim=1)
if "modality_mask" in batch:
batch["modality_mask"] = F.one_hot(batch["modality"], num_classes=2).to(torch.bool)
batch['txt_sl'] = None
batch['img_sl'] = None
batch["batch_flip_mask"] = batch_flip_mask
if self.config.trainer.interleaved and "sample_ids" not in batch:
batch["sample_ids"] = torch.zeros_like(batch["modality"], dtype=torch.int64)
if self.config.trainer.interleaved:
batch_indices, start_positions, end_positions = get_contiguous_blocks(batch["modality"])
interleaved_metadata = TensorDict({
"batch_indices": batch_indices,
"start_positions": start_positions,
"end_positions": end_positions
}, batch_size=[])
allowed_image_sizes = (64, 256, 1024, 2304, 4096)
block_sizes = (end_positions - start_positions).to(torch.int32)
is_txt_block = batch["modality"][batch_indices, start_positions] == 0
is_valid_img_size = torch.isin(block_sizes, torch.tensor(allowed_image_sizes, dtype=torch.int32, device=self.device))
if not ((is_txt_block | is_valid_img_size).all()):
gprint(f"WARNING: Found non-text block of size {block_sizes[~(is_txt_block | is_valid_img_size)]} in interleaved batch")
if isinstance(batch, TensorDict):
batch.batch_size = []
batch["interleaved_metadata"] = interleaved_metadata
return batch
def get_cond_dict(self, batch):
ret_dict = dict()
if "cond_input_ids" in batch:
ret_dict["x_cond"] = batch["cond_input_ids"]
if "img_label" in batch:
ret_dict["label"] = batch["img_label"]
if self.config.model.use_attention_mask:
ret_dict["attention_mask"] = batch["attention_mask"]
if self.config.trainer.multimodal_batches:
ret_dict["modality"] = batch["modality"]
if self.config.trainer.image_mode == "continuous":
ret_dict["continuous_mode"] = True
ret_dict["modality"] = batch["modality"]
if self.parameterization == "ar" and "modality" in batch:
ret_dict["modality"] = batch["modality"]
return ret_dict
def training_step(self, batch, batch_idx):
batch = self.update_batch(batch)
return self.compute_loss(batch, prefix="train", batch_idx=batch_idx)
def q_xt(self, x, move_chance, allow_move_mask=None, return_ignore_batch_mask_for_metrics=False, mask_image_square=False, mask_text_region=False, batch=None):
"""Computes the noisy sample xt.
Args:
x: int torch.Tensor with shape (batch_size,
diffusion_model_input_length), input.
move_chance: float torch.Tensor with shape (batch_size, 1).
"""
if self.config.backbone == "maskdit" and getattr(self.config.trainer, "force_single_timestep_per_batch", False):
num_to_mask = int(x.shape[1] * move_chance[0].item())
batch_size, seq_len = x.shape
random_indices = torch.rand(batch_size, seq_len, device=x.device).argsort(dim=1)[:, :num_to_mask]
xt = x.scatter(1, random_indices, self.mask_index)
return xt
move_indices = torch.rand(*x.shape, device=x.device) < move_chance
if mask_image_square:
latent_dim = int(math.sqrt(self.config.model.img_length))
img_move_indices = move_indices[:, self.static_img_sl].clone().reshape(move_indices.shape[0], latent_dim, latent_dim)
max_d = int(math.sqrt(self.config.model.img_length))
for b in range(move_indices.shape[0]):
if move_chance[b] == 1:
continue
h, w = img_move_indices[b].shape
d = random.randint(max_d // 2, max_d - 2)
i = random.randint(0, h - d)
j = random.randint(0, w - d)
mask = torch.zeros_like(img_move_indices[b], dtype=torch.bool)
mask[i:i+d, j:j+d] = True
move_indices[b, self.static_img_sl] = mask.reshape(-1)
if mask_text_region:
for b in range(x.shape[0]):
if move_chance[b] == 1:
continue
should_mask = torch.zeros_like(move_indices[b, self.static_txt_sl], dtype=torch.bool)
max_valid = (x[b] == self.tokenizer.eos_token_id).nonzero()[0, 0] if self.tokenizer.eos_token_id in x[b] else x.shape[1]
d = random.randint(max_valid//3, max_valid-1)
start = random.randint(0, max_valid - d)
should_mask[start:start+d] = True
move_indices[b, self.static_txt_sl] = should_mask
ignore_batch_mask_for_metrics = None
should_mask_txt, should_mask_img = None, None
if (mask_prob := getattr(self.config.trainer, "mask_entire_modality", None)) is not None \
and (mask_image_square is False and mask_text_region is False) and self.backbone.training:
assert batch is not None
batch_size, seq_len = x.shape
if getattr(self.config.trainer, "mask_txt_only", False):
should_mask_txt = torch.rand(batch_size, 1, device=x.device) < mask_prob
should_mask_img = torch.zeros_like(should_mask_txt, device=x.device)
else:
should_mask_txt = torch.rand(batch_size, 1, device=x.device) < mask_prob/2
should_mask_img = torch.rand(batch_size, 1, device=x.device) < mask_prob/2
if self.config.trainer.multimodal_batches:
if self.config.trainer.interleaved:
batch_indices, start_positions, end_positions = get_contiguous_blocks_per_sample(batch["modality"], batch["sample_ids"])
block_size = end_positions - start_positions
size_mask = block_size > 4
batch_indices, start_positions, end_positions = batch_indices[size_mask], start_positions[size_mask], end_positions[size_mask]
block_counts = torch.zeros_like(batch_indices)
max_num_sample_ids = torch.zeros_like(batch_indices)
for i in range(len(batch_indices)):
curr_sample_id = batch["sample_ids"][batch_indices[i], start_positions[i]]
# Find blocks before this one with same batch index and sample_id
prev_blocks_mask = (batch_indices[:i] == batch_indices[i]) & \
(batch["sample_ids"][batch_indices[:i], start_positions[:i]] == curr_sample_id)
total_in_sample = ((batch_indices == batch_indices[i]) & (batch["sample_ids"][batch_indices, start_positions] == curr_sample_id)).sum()
block_counts[i] = prev_blocks_mask.sum()
max_num_sample_ids[i] = total_in_sample
block_prob = (block_counts + 1) / max_num_sample_ids
positions = torch.arange(move_indices.shape[-1], device=move_indices.device).unsqueeze(0) # Shape: [1, N]
mask = (positions >= start_positions.unsqueeze(1)) & (positions < end_positions.unsqueeze(1)) # Shape: [M, N]
mask = mask & (torch.rand(batch_indices.shape[0], 1, device=x.device) < (mask_prob * block_prob * 2)[..., None])
expanded_batch_indices = batch_indices.unsqueeze(1).expand(-1, move_indices.shape[1]) # Shape: [M, N]
# True if we should manually mask the part of the sequence
accum = torch.zeros_like(move_indices, dtype=torch.int32) # Shape: [B, N]
accum.scatter_add_(0, expanded_batch_indices, mask.int()) # Accumulate counts
accum = accum.to(torch.bool)
move_indices = move_indices | accum
# We ignore the entire sequence if any of the blocks are fully masked
ignore_batch_mask_for_metrics = torch.zeros((move_indices.shape[0],), device=x.device, dtype=torch.bool)
ignore_batch_mask_for_metrics.scatter_add_(0, batch_indices, mask.any(dim=-1))
else:
# TODO: Be smarter about masking for interleaved
# To make sure that we have even masking prob, we prefer to mask less but equally
both_mask = should_mask_txt & should_mask_img
should_mask_txt = torch.where(both_mask, False, should_mask_txt)
should_mask_img = torch.where(both_mask, False, should_mask_img)
move_indices = torch.where(should_mask_txt, batch["modality_mask"][..., 0], move_indices)
move_indices = torch.where(should_mask_img, batch["modality_mask"][..., 1], move_indices)
ignore_batch_mask_for_metrics = should_mask_img | should_mask_txt
else:
both_mask = should_mask_txt & should_mask_img
should_mask_txt[both_mask] = False
should_mask_img[both_mask] = False
should_mask_img[batch["txt_sl"].all(dim=-1)] = False
move_indices[:, self.static_txt_sl] = torch.where(should_mask_txt, True, move_indices[:, self.static_txt_sl])
move_indices[:, self.static_img_sl] = torch.where(should_mask_img, True, move_indices[:, self.static_img_sl])
ignore_batch_mask_for_metrics = should_mask_img | should_mask_txt
joint_ar_nar_mask = None
if self.config.trainer.joint_ar_nar_prob is not None and self.training:
batch_size = x.shape[0]
current_prob = linear_warmup(
current_step=self.global_step,
warmup_steps=self.config.trainer.joint_ar_nar_prob_warmup_steps,
final_value=self.config.trainer.joint_ar_nar_prob,
initial_value=1.0
)
joint_ar_nar_mask = torch.rand(batch_size, device=x.device) < current_prob
move_indices = torch.where(joint_ar_nar_mask[:, None], False, move_indices)
if self.config.trainer.add_label:
move_indices[:, 0] = False
if self.config.trainer.first_token_dropout is not None and self.training:
_initial_mask = torch.rand(x.shape[0], device=x.device) < self.config.trainer.first_token_dropout
move_indices[:, 0] = torch.where(_initial_mask, True, move_indices[:, 0])
if ignore_batch_mask_for_metrics is None:
ignore_batch_mask_for_metrics = _initial_mask
else:
ignore_batch_mask_for_metrics = ignore_batch_mask_for_metrics | _initial_mask
if allow_move_mask is not None:
move_indices = move_indices & allow_move_mask
if getattr(self.config.trainer, "discrete_diffusion_mode", "absorbing") == "uniform":
if getattr(self.config.model, "force_argmax_valid_indices", False):
assert self.mask_index == self.text_vocab_size - 1
text_random_tokens = torch.randint(0, self.text_vocab_size - 1, size=x.shape, device=x.device)
img_random_tokens = torch.randint(self.text_vocab_size, self.vocab_size, size=x.shape, device=x.device)
random_tokens = torch.where(batch["modality_mask"][..., 0], text_random_tokens, img_random_tokens)
assert not torch.any(random_tokens == self.mask_index)
else:
random_tokens = torch.randint(0, vocab_size, size=x.shape, device=x.device)
random_tokens = torch.where(random_tokens == self.mask_index, random_tokens + 1, random_tokens) # avoid mask index
xt = torch.where(move_indices, random_tokens, x)
else:
xt = torch.where(move_indices, self.mask_index, x)
if self.parameterization == "ar":
xt = x.clone()
if return_ignore_batch_mask_for_metrics:
return xt, ignore_batch_mask_for_metrics, joint_ar_nar_mask, should_mask_txt, should_mask_img, move_indices
else:
return xt
def _sample_t(self, n, device):
if self.config.backbone == "maskdit" and getattr(self.config.trainer, "force_single_timestep_per_batch", False):
_eps_t = torch.rand(1, device=device).repeat(n)
else:
_eps_t = torch.rand(n, device=device)
if self.config.trainer.joint_ar_nar_timestep_warmup_steps is not None:
max_t = linear_warmup(
current_step=self.global_step,
warmup_steps=self.config.trainer.joint_ar_nar_timestep_warmup_steps,
final_value=1,
initial_value=0,
start_step=0
)
_eps_t = _eps_t * max_t
if max_t == 1:
offset = torch.arange(n, device=device) / n
_eps_t = (_eps_t / n + offset) % 1
elif self.antithetic_sampling:
offset = torch.arange(n, device=device) / n
_eps_t = (_eps_t / n + offset) % 1
if getattr(self.config.trainer, "force_timestep", None) is not None:
_eps_t[:] = self.config.trainer.force_timestep
elif getattr(self.config.eval, "ar_inpainting_force_val", None) is not None:
_eps_t[:] = self.config.eval.ar_inpainting_force_val
t = (1 - self.sampling_eps) * _eps_t + self.sampling_eps
if self.importance_sampling:
return self.noise.importance_sampling_transformation(t)
return t.to(torch.float32)
def _subs_parameterization(self, logits, xt, batch=None, modality=None, **kwargs):
# log prob at the mask index = - infinity
if not self.allow_slicing:
logits = logits.clone()
logits[..., self.mask_index] += self.neg_infinity
if getattr(self.config.model, "force_argmax_valid_indices", False):
if self.config.trainer.multimodal_batches:
_txt_sl = batch["txt_sl"] if modality is None else modality == 0
_img_sl = batch["img_sl"] if modality is None else modality == 1
logits[..., self.text_vocab_size:] = torch.where(_txt_sl[..., None], self.neg_infinity, logits[..., self.text_vocab_size:])
logits[..., :self.text_vocab_size] = torch.where(_img_sl[..., None], self.neg_infinity, logits[..., :self.text_vocab_size])
else:
logits[..., self.static_txt_sl, self.text_vocab_size:] = self.neg_infinity
logits[..., self.static_img_sl, :self.text_vocab_size] = self.neg_infinity
# Normalize the logits such that x.exp() is
# a probability distribution over vocab_size.
logits = logits - torch.logsumexp(logits, dim=-1, keepdim=True)
if self.parameterization != "ar" and xt is not None:
# Apply updates directly in the logits matrix.
# For the logits of the unmasked tokens, set all values
# to -infinity except for the indices corresponding to
# the unmasked tokens.
unmasked_indices = xt != self.mask_index
if not self.allow_slicing:
logits = torch.where(unmasked_indices.unsqueeze(-1), torch.full_like(logits, self.neg_infinity), logits)
logits = torch.where(
unmasked_indices.unsqueeze(-1) & (torch.arange(logits.size(-1)).to(logits.device) == xt.unsqueeze(-1)),
torch.zeros_like(logits),
logits
)
else:
logits[unmasked_indices] = self.neg_infinity
logits[unmasked_indices, xt[unmasked_indices]] = 0
return logits
def _process_sigma(self, sigma):
if sigma is None:
assert (self.parameterization == "ar" or self.config.trainer.ar_llm_loss) or self.config.trainer.allow_null_sigma
return sigma
if sigma.ndim > 1 and not self.config.trainer.image_mode == "continuous":
sigma = sigma.squeeze(-1)
assert sigma.ndim == 1, sigma.shape
if not self.time_conditioning and getattr(self.config.model, "force_time_conditioning", False):
sigma = torch.zeros_like(sigma)
return sigma
def forward(
self,
x,
sigma,
batch=None,
forward_attention_mask=None,
return_additional_loss=False,
x_img_emb=None,
disable_ar_shift=False,
continuous_mode=False,
joint_ar_nar_mask=None,
return_logits=False,
block_mask=None,
update_cache_slice=None,
**kwargs,
):
"""Returns log score."""
sigma = self._process_sigma(sigma)
if self.config.trainer.image_mode == "continuous": assert "modality" in kwargs
should_autocast = (((self.config.trainer.disable_forward_autocast_during_eval and self.backbone.training) is False) and (self.dtype != torch.float32))
with ExitStack() as stack:
if should_autocast:
stack.enter_context(torch.autocast(device_type=self.device.type, dtype=self.dtype))
orig_modality = None
if self.config.backbone == "elm":
if getattr(self.config.trainer, "print_llm_ppl", False):
_labels = x.clone()
_labels[~forward_attention_mask] = -100
kwargs['labels'] = _labels
if "modality" in kwargs:
if self.config.mode == "eval": orig_modality = kwargs.pop("modality")
else: kwargs.pop("modality")
if "modality_mask" in kwargs: kwargs.pop("modality_mask")
if "x0" in kwargs: kwargs.pop("x0")
if "start_pos" in kwargs: kwargs.pop("start_pos")
if "sample_ids" in kwargs: kwargs.pop("sample_ids")
output = self.backbone(input_ids=x, **kwargs)
if self.config.mode == "eval": kwargs["modality"] = orig_modality
if isinstance(output, Tensor):
logits = output
else:
logits = output.logits
if getattr(self.config.trainer, "print_llm_ppl", False):
rprint(f"AR PPL: {torch.exp(output.loss)}")
else:
if self.config.trainer.compile == 'max-autotune' and not is_xla_available:
torch.compiler.cudagraph_mark_step_begin()
logits = self.backbone(x, sigma, continuous_mode=continuous_mode, x_img_emb=x_img_emb, block_mask=block_mask, update_cache_slice=update_cache_slice, **kwargs)
if self.config.trainer.force_bf16_eval:
logits = logits.to(torch.bfloat16)
if continuous_mode:
assert self.parameterization == "ar"
logits, logits_img = logits
if self.config.trainer.ar_shift and not disable_ar_shift:
# config trainer ar shift is for training
# disable ar shift is for sampling at inference
logits = logits[:, :-1]
xt = x[:, 1:]
if orig_modality is not None and self.config.mode == 'eval':
orig_modality = orig_modality[:, 1:]
else:
xt = x
if self.config.trainer.low_precision_loss:
logits = logits.to(self.dtype)
if continuous_mode:
logits_img = logits_img.to(self.dtype)
if self.parameterization == "planner":
return logits
elif self.config.trainer.ar_llm_loss:
assert not self.parameterization == "ar"
model_output = self._subs_parameterization(logits, xt=xt, modality=orig_modality), logits
if is_xla_available: shard_output(model_output[0], self.xla_mesh)
if is_xla_available: shard_output(model_output[1], self.xla_mesh)
return model_output if return_additional_loss else model_output[0]
elif self.parameterization == "ar":
if not getattr(self.config.trainer, "use_orig_unidisc_dit", False):
logits = torch.where(
torch.arange(logits.shape[-1], device=logits.device)[None, None, :] == self.mask_index, self.neg_infinity, logits
)
_modality = kwargs.get("modality") if batch is None else batch.get("modality")
# During eval, we let the sampler handle this part.
if getattr(self.config.model, "force_argmax_valid_indices", False) and _modality.shape[1] == (logits.shape[1] + 1):
if not self.allow_slicing:
logits = logits.clone()
logits[..., self.text_vocab_size:] = torch.where(
(kwargs.get("modality") == 0)[..., 1:, None], torch.finfo(logits.dtype).min, logits[..., self.text_vocab_size:]
)
logits[..., :self.text_vocab_size] = torch.where(
(kwargs.get("modality") == 1)[..., 1:, None], torch.finfo(logits.dtype).min, logits[..., :self.text_vocab_size]
)
logits = logits.log_softmax(-1)
if continuous_mode:
return (logits, logits_img)
elif self.parameterization == "subs":
if return_logits:
return logits
model_output = self._subs_parameterization(logits, xt=xt, batch=batch, **kwargs)
if is_xla_available: shard_output(model_output, self.xla_mesh)
return model_output
elif self.parameterization == "sedd":
return self._sedd_parameterization(logits=logits, xt=x, sigma=sigma)
elif self.parameterization == "d3pm":
return self._d3pm_parameterization(logits=logits)
return logits
def compute_loss(self, batch, prefix, batch_idx=-1):
if not is_xla_available and ((self.current_run_fwd_bwd_pass == 0 and self.config.mode == 'train') or batch_idx == 0):
self.visualize_samples(batch, batch_idx, split=prefix)
if getattr(self.config.trainer, 'overfit_on_first_batch', False):
if batch_idx <= 0:
# store it
self.overfit_batch = batch.copy()
else:
batch = self.overfit_batch
kwargs = self.get_cond_dict(batch)
modality_mask = batch.get("modality_mask", None)
(input_tokens, output_tokens, attention_mask) = self._maybe_sub_sample(batch["input_ids"], batch.get("attention_mask", None))
continuous_mode = self.config.trainer.image_mode == "continuous"
joint_ar_nar_mask, modality = None, None
if continuous_mode:
assert 'modality' in batch
x0, img_emb, attention_mask, modality = (
batch["input_ids"],
batch["img_emb"],
batch["attention_mask"],
batch["modality"],
) # img_emb has [0.] * txt_len + img_emb
xt = x0
B, N_tot, C = img_emb.shape
noise_scheduler = self.get_vae().scheduler
noise = torch.randn_like(img_emb)
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (B,), device=img_emb.device).long()
img_timesteps = timesteps.unsqueeze(-1).expand(-1, N_tot).to(self.dtype)
zero_timesteps = torch.zeros_like(img_timesteps)
unet_conditioning = torch.where(modality == 1, img_timesteps, zero_timesteps)
# unet_conditioning = timesteps.to(self.dtype)
# unet_conditioning = torch.where(modality_mask==1, timesteps.to(self.dtype), torch.zeros_like(timesteps.to(self.dtype)))
x_img_emb = noise_scheduler.add_noise(img_emb, noise, timesteps).to(self.dtype)
if noise_scheduler.config.prediction_type == "epsilon":
target = noise
elif noise_scheduler.config.prediction_type == "v_prediction":
target = noise_scheduler.get_velocity(img_emb, noise, timesteps) # todo, might break
elif noise_scheduler.config.prediction_type:
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
target = target.to(self.dtype)
else:
unet_conditioning, xt, x0, x_img_emb, modality_mask = None, None, input_tokens, None, batch.get("modality_mask", None)
if self.parameterization != "ar":
t = self._sample_t(x0.shape[0], x0.device)
if self.T > 0:
t = (t * self.T).to(torch.int)
t = t / self.T
t += 1 / self.T # t \in {1/T, 2/T, ..., 1}
if self.change_of_variables:
unet_conditioning = t[:, None]
f_T = torch.log1p(-torch.exp(-self.noise.sigma_max))
f_0 = torch.log1p(-torch.exp(-self.noise.sigma_min))
move_chance = torch.exp(f_0 + t * (f_T - f_0))
move_chance = move_chance[:, None]
else:
# total, rate
sigma, dsigma = self.noise(t)
unet_conditioning = sigma[:, None]
move_chance = 1 - torch.exp(-sigma[:, None])
xt, ignore_batch_mask_for_metrics, joint_ar_nar_mask, should_mask_txt, should_mask_img, move_indices = self.q_xt(x0, move_chance, return_ignore_batch_mask_for_metrics=True, batch=batch)
if (self.config.model.flex_attention_img_masking_prob is not None or self.config.model.flex_attention_txt_masking_prob is not None) and self.backbone.training:
assert xt.shape[1] == (self.config.model.img_length + self.config.model.txt_length)
txt_batch_attn_dropout = torch.rand(xt.shape[0], device=xt.device) < self.config.model.flex_attention_txt_masking_prob
img_batch_attn_dropout = torch.rand(xt.shape[0], device=xt.device) < self.config.model.flex_attention_img_masking_prob
# If we mask out a modality, we cannot let it only see itself
txt_batch_attn_dropout = txt_batch_attn_dropout & ~should_mask_txt.squeeze(-1)
img_batch_attn_dropout = img_batch_attn_dropout & ~should_mask_img.squeeze(-1)
kwargs['block_mask'] = get_block_mask(txt_batch_attn_dropout, img_batch_attn_dropout, self.config.model.txt_length, xt.shape[0], xt.shape[1], xt.device)
# TODO: Somehow report these metrics so we know what's going on
ignore_batch_mask_for_metrics = ignore_batch_mask_for_metrics | (txt_batch_attn_dropout | img_batch_attn_dropout).unsqueeze(-1)
if getattr(self.config.trainer, "interleaved_training_flex_attention", False):
kwargs['block_mask'] = get_interleaved_block_mask(batch["sample_ids"], batch_size=xt.shape[0], seq_len=xt.shape[1], device=xt.device)
kwargs['sample_ids'] = batch["sample_ids"]
elif self.config.trainer.ar_inpainting:
x0 = torch.cat([x0, x0], dim=1)
kwargs['modality'] = torch.cat([kwargs['modality'], kwargs['modality']], dim=1)
attention_mask = torch.cat([torch.zeros_like(attention_mask, dtype=attention_mask.dtype), torch.ones_like(attention_mask, dtype=attention_mask.dtype)], dim=1)
modality_mask = torch.cat([modality_mask, modality_mask], dim=1)
min_val, max_val = 0.0, 1.0
n = x0.shape[0]
_eps_t = torch.rand(n, device=self.device)
offset = torch.arange(n, device=self.device) / n
_eps_t = (_eps_t / n + offset) % 1
t = (max_val - min_val) * _eps_t + min_val
if getattr(self.config.eval, "ar_inpainting_force_val", None) is not None:
t = torch.full_like(t, getattr(self.config.eval, "ar_inpainting_force_val"), dtype=t.dtype, device=t.device)
move_indices = torch.rand(*x0.shape, device=x0.device) < t[:, None]
move_indices[:, x0.shape[1] // 2:] = False
x0 = torch.where(move_indices, self.mask_index, x0)
xt = x0
else:
xt = x0
if (self.training or getattr(self.config.trainer, "force_flip_ar_val", False)) and self.config.trainer.rand_ar_modality_dropout is not None:
assert not is_xla_available
xt = xt.clone()
batch_modality_dropout = torch.rand(xt.shape[0], device=xt.device) < self.config.trainer.rand_ar_modality_dropout
first_modality = batch["modality"][:, 0]
first_modality_mask = batch["modality"] == first_modality[:, None]
xt = torch.where(first_modality_mask & batch_modality_dropout[:, None], self.mask_index, xt)
attention_mask = torch.where(first_modality_mask & batch_modality_dropout[:, None], False, attention_mask)
true_logits = None
model_output = self.forward(
xt, unet_conditioning, return_additional_loss=True, batch=batch, x_img_emb=x_img_emb, joint_ar_nar_mask=joint_ar_nar_mask, **kwargs
)
if isinstance(model_output, tuple):
if continuous_mode:
model_output, img_output = model_output # model_output is for text, img_output is for image although both will have N_total length (zeroed out according to modality mask)
B, _, C = img_output.shape
# use modality mask to get the correct logits
x0 = x0[modality==0].reshape(B, -1)
xt = xt[modality==0].reshape(B, -1)
attention_mask = torch.ones_like(x0, dtype=torch.bool) # since we separate text, we don't need to mask it out
img_output = img_output[modality==1].reshape(B, -1, C)
target = target[modality==1].reshape(B, -1, C)
else:
model_output, true_logits = model_output
to_dtype = self.dtype if self.config.trainer.low_precision_loss else torch.float32
model_output = model_output.to(to_dtype)
if true_logits is not None:
true_logits = true_logits.to(self.dtype)
if continuous_mode:
img_output = img_output.to(to_dtype)
target = target.to(to_dtype)
# if prefix != 'train':
# breakpoint()
if self.config.trainer.ar_shift:
x0 = x0[:, 1:]
xt = xt[:, 1:]
attention_mask = attention_mask[:, 1:]
if modality_mask is not None: modality_mask = modality_mask[:, 1:]
if modality is not None: modality = modality[:, 1:]
if not self.is_compiled:
utils.print_nans(model_output, "model_output")
if self.parameterization == "sedd":
return dsigma[:, None] * self._score_entropy(model_output, sigma[:, None], xt, x0)
elif self.parameterization == "planner":
return F.binary_cross_entropy_with_logits(model_output.squeeze(-1), move_indices.float()).mean()
diffusion_loss = None
if self.T > 0:
diffusion_loss = self._d3pm_loss(model_output=model_output, xt=xt, x0=x0, t=t)
if self.parameterization == "d3pm":
reconstruction_loss = self._reconstruction_loss(x0)
elif self.parameterization == "subs" or self.parameterization == "ar":
reconstruction_loss = 0
# return reconstruction_loss + diffusion_loss
if self.parameterization == "ar":
if getattr(self.config.trainer, "use_orig_unidisc_dit", False):
return self.shortcut_return(model_output, x0, attention_mask, prefix)
else:
log_p_theta = model_output.gather(-1, x0[:, :, None])[:, :, 0]
else:
# SUBS parameterization, continuous time
log_p_theta = torch.gather(input=model_output, dim=-1, index=x0[:, :, None]).squeeze(-1)
if self.change_of_variables or self.importance_sampling:
return log_p_theta * torch.log1p(-torch.exp(-self.noise.sigma_min))
if self.parameterization == "ar" or getattr(self.config.trainer, "no_ce_weighting", False):
std_weighting = 1
else:
std_weighting = (dsigma / torch.expm1(sigma))[:, None]
# ddprint(f"self.current_run_fwd_bwd_pass: {self.current_run_fwd_bwd_pass}, log_p_theta: {torch.isnan(log_p_theta).any()}")
# if torch.isnan(log_p_theta).any() or self.current_run_fwd_bwd_pass > 15473:
# import pickle
# import time
# rank = get_rank()
# timestamp = int(time.time() * 1e9) # nanosecond timestep
# filename = f'batch_datastep_{self.current_run_fwd_bwd_pass}_rank{rank}_{timestamp}.pkl'
# with open(filename, 'wb') as f:
# pickle.dump(log_p_theta, f)
# ddprint(f"Saved batch to {filename}")
loss = -log_p_theta * std_weighting
if not (self.parameterization == "ar" or (self.config.trainer.ar_llm_loss and joint_ar_nar_mask is None) or getattr(self.config.trainer, "no_ce_weighting", False)):
gamma = getattr(self.config.trainer, "softmin_snr", None)
if gamma is not None:
softmin_weighting = (dsigma / (torch.expm1(sigma) + (1 / gamma)))[:, None]
loss = -log_p_theta * softmin_weighting
if diffusion_loss is not None:
assert self.T > 0
loss = diffusion_loss
std_loss = -log_p_theta * std_weighting
loss_dict = dict(std_loss=std_loss.detach(), extra_losses=dict())