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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9835792
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
import math
import os
import random
import glob
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.optim import Adam
from torchvision.utils import make_grid
from PIL import Image
from transformers import (
    DistilBertModel,
    DistilBertTokenizer,
    CLIPTokenizer,
    CLIPTextModel,
)

dataset_params = {
    "image_path": "data/CelebAMask-HQ",
    "image_channels": 3,
    "image_size": 256,
    "name": "celebhq",
}

diffusion_params = {
    "num_timesteps": 1000,
    "beta_start": 0.00085,
    "beta_end": 0.012,
}

ldm_params = {
    "down_channels": [256, 384, 512, 768],
    "mid_channels": [768, 512],
    "down_sample": [True, True, True],
    "attn_down": [True, True, True],  # Attention in the DownBlock and UpBlock of VQ-VAE
    "time_emb_dim": 512,
    "norm_channels": 32,
    "num_heads": 16,
    "conv_out_channels": 128,
    "num_down_layers": 2,
    "num_mid_layers": 2,
    "num_up_layers": 2,
    "condition_config": {
        "condition_types": ["text", "image"],
        "text_condition_config": {
            "text_embed_model": "clip",
            "train_text_embed_model": False,
            "text_embed_dim": 512,  # Each token should map to text_embed_dim sized vector
            "cond_drop_prob": 0.1,  # Probability of dropping conditioning during training to allow the model to generate images without conditioning as well
        },
        "image_condition_config": {
            "image_condition_input_channels": 18,  # CelebA has 18 classes excluding background
            "image_condition_output_channels": 3,
            "image_condition_h": 512,  # Mask height
            "image_condition_w": 512,  # Mask width
            "cond_drop_prob": 0.1,  # Probability of dropping conditioning during training to allow the model to generate images without conditioning as well
        },
    },
}

autoencoder_params = {
    "z_channels": 4,
    "codebook_size": 8192,
    "down_channels": [64, 128, 256, 256],
    "mid_channels": [256, 256],
    "down_sample": [True, True, True],
    "attn_down": [
        False,
        False,
        False,
    ],  # No attention in the DownBlock and UpBlock of VQ-VAE
    "norm_channels": 32,
    "num_heads": 4,
    "num_down_layers": 2,
    "num_mid_layers": 2,
    "num_up_layers": 2,
}

train_params = {
    "seed": 1111,
    "task_name": "celebhq",  # Folder to save models and images to
    "ldm_batch_size": 16,
    "autoencoder_batch_size": 4,
    "disc_start": 15000,
    "disc_weight": 0.5,
    "codebook_weight": 1,
    "commitment_beta": 0.2,
    "perceptual_weight": 1,
    "kl_weight": 0.000005,
    "ldm_epochs": 100,
    "autoencoder_epochs": 20,
    "num_samples": 1,
    "num_grid_rows": 1,
    "ldm_lr": 0.000005,
    "autoencoder_lr": 0.00001,
    "autoencoder_acc_steps": 4,
    "autoencoder_img_save_steps": 64,
    "save_latents": True,
    "cf_guidance_scale": 1.0,
    "vqvae_latent_dir_name": "vqvae_latents",
    "ldm_ckpt_name": "ddpm_ckpt_class_cond.pth",
    "vqvae_autoencoder_ckpt_name": "vqvae_autoencoder_ckpt.pth",
}


def get_config_value(config, key, default_value):
    return config[key] if key in config else default_value


def spatial_average(in_tens, keepdim=True):
    return in_tens.mean([2, 3], keepdim=keepdim)


class LinearNoiseScheduler:
    def __init__(self, num_timesteps, beta_start, beta_end):
        self.num_timesteps = num_timesteps
        self.beta_start = beta_start
        self.beta_end = beta_end
        self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_timesteps) ** 2
        self.alphas = 1.0 - self.betas
        self.alpha_cum_prod = torch.cumprod(self.alphas, dim=0)
        self.sqrt_alpha_cum_prod = torch.sqrt(self.alpha_cum_prod)
        self.sqrt_one_minus_alpha_cum_prod = torch.sqrt(1 - self.alpha_cum_prod)

    def add_noise(self, original, noise, t):
        # original: (batch_size, c, h, w), t: tensor of timesteps (batch_size,)
        batch_size = original.shape[0]
        sqrt_alpha_cum_prod = self.sqrt_alpha_cum_prod.to(original.device)[t].view(
            batch_size, 1, 1, 1
        )
        sqrt_one_minus_alpha_cum_prod = self.sqrt_one_minus_alpha_cum_prod.to(
            original.device
        )[t].view(batch_size, 1, 1, 1)
        return sqrt_alpha_cum_prod * original + sqrt_one_minus_alpha_cum_prod * noise

    def sample_prev_timestep(self, xt, noise_pred, t):
        batch_size = xt.shape[0]
        alpha_cum_prod_t = self.alpha_cum_prod.to(xt.device)[t].view(
            batch_size, 1, 1, 1
        )
        sqrt_one_minus_alpha_cum_prod_t = self.sqrt_one_minus_alpha_cum_prod.to(
            xt.device
        )[t].view(batch_size, 1, 1, 1)
        x0 = (xt - sqrt_one_minus_alpha_cum_prod_t * noise_pred) / torch.sqrt(
            alpha_cum_prod_t
        )
        x0 = torch.clamp(x0, -1.0, 1.0)
        betas_t = self.betas.to(xt.device)[t].view(batch_size, 1, 1, 1)
        mean = (
            xt - betas_t / sqrt_one_minus_alpha_cum_prod_t * noise_pred
        ) / torch.sqrt(self.alphas.to(xt.device)[t].view(batch_size, 1, 1, 1))
        if t[0] == 0:
            return mean, x0
        else:
            prev_alpha_cum_prod = self.alpha_cum_prod.to(xt.device)[
                (t - 1).clamp(min=0)
            ].view(batch_size, 1, 1, 1)
            variance = (1 - prev_alpha_cum_prod) / (1 - alpha_cum_prod_t) * betas_t
            sigma = variance.sqrt()
            z = torch.randn_like(xt)
            return mean + sigma * z, x0


def get_tokenizer_and_model(model_type, device, eval_mode=True):
    assert model_type in (
        "bert",
        "clip",
    ), "Text model can only be one of 'clip' or 'bert'"
    if model_type == "bert":
        text_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
        text_model = DistilBertModel.from_pretrained("distilbert-base-uncased").to(
            device
        )
    else:
        text_tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch16")
        text_model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch16").to(
            device
        )
    if eval_mode:
        text_model.eval()
    return text_tokenizer, text_model


def get_text_representation(text, text_tokenizer, text_model, device, max_length=77):
    token_output = text_tokenizer(
        text,
        truncation=True,
        padding="max_length",
        return_attention_mask=True,
        max_length=max_length,
    )
    tokens_tensor = torch.tensor(token_output["input_ids"]).to(device)
    mask_tensor = torch.tensor(token_output["attention_mask"]).to(device)
    text_embed = text_model(tokens_tensor, attention_mask=mask_tensor).last_hidden_state
    return text_embed


def get_time_embedding(time_steps, temb_dim):
    """
    Convert time steps tensor into an embedding using the sinusoidal time embedding formula
    time_steps: 1D tensor of length batch size
    temb_dim: Dimension of the embedding
    """
    assert temb_dim % 2 == 0, "time embedding dimension must be divisible by 2"

    # factor = 10000^(2i/d_model)
    factor = 10000 ** (
        (
            torch.arange(
                start=0,
                end=temb_dim // 2,
                dtype=torch.float32,
                device=time_steps.device,
            )
            / (temb_dim // 2)
        )
    )

    t_emb = time_steps.unsqueeze(dim=-1).repeat(1, temb_dim // 2) / factor
    t_emb = torch.cat([torch.sin(t_emb), torch.cos(t_emb)], dim=-1)

    return t_emb  # (batch_size, temb_dim)


class DownBlock(nn.Module):
    """
    Down conv block with attention.
    1. Resnet block with time embedding
    2. Attention block
    3. Downsample

    in_channels: Number of channels in the input feature map.
    out_channels: Number of channels produced by this block.
    t_emb_dim: Dimension of the time embedding. Only use for UNet for Diffusion. In an AutoEncoder, set it to None.
    down_sample: Whether to apply downsampling at the end.
    num_heads: Number of attention heads (used if attention is enabled).
    num_layers: How many sub-blocks to apply in sequence.
    attn: Whether to apply self-attention
    norm_channels: Number of groups for GroupNorm.
    cross_attn: Whether to apply cross-attention.
    context_dim: If performing cross-attention, provide a context_dim for extra conditioning context.
    """

    def __init__(
        self,
        in_channels,
        out_channels,
        t_emb_dim,
        down_sample,
        num_heads,
        num_layers,
        attn,
        norm_channels,
        cross_attn=False,
        context_dim=None,
    ):
        super().__init__()

        self.num_layers = num_layers
        self.down_sample = down_sample
        self.attn = attn
        self.context_dim = context_dim
        self.cross_attn = cross_attn
        self.t_emb_dim = t_emb_dim

        self.resnet_conv_first = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(
                        norm_channels, in_channels if i == 0 else out_channels
                    ),  # Normalizes over channels. For the first sub-block, the in_channels=in_channels, else out_channels
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=(in_channels if i == 0 else out_channels),
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, c, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers)
            ]
        )

        # Only add the time embedding for diffusion and not AutoEncoder
        if self.t_emb_dim is not None:
            self.t_emb_layers = nn.ModuleList(
                [
                    nn.Sequential(
                        nn.SiLU(),
                        nn.Linear(
                            in_features=self.t_emb_dim, out_features=out_channels
                        ),  # (batch_size, t_emb_dim) -> (batch_size, out_channels)
                    )
                    for i in range(num_layers)
                ]
            )

        self.resnet_conv_second = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(norm_channels, out_channels),
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, out_channels, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers)
            ]
        )

        self.residual_input_conv = nn.ModuleList(
            [
                nn.Conv2d(
                    in_channels=(in_channels if i == 0 else out_channels),
                    out_channels=out_channels,
                    kernel_size=1,
                    stride=1,
                    padding=0,
                )  # (batch_size, in_channels, h, w) -> (batch_size, out_channels, h, w)
                for i in range(num_layers)
            ]
        )

        if self.attn:
            self.attention_norms = nn.ModuleList(
                [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
            )

            self.attentions = nn.ModuleList(
                [
                    nn.MultiheadAttention(
                        embed_dim=out_channels, num_heads=num_heads, batch_first=True
                    )
                    for i in range(num_layers)
                ]
            )

        # Cross attention for text conditioning
        if self.cross_attn:
            assert (
                context_dim is not None
            ), "Context Dimension must be passed for cross attention"

            self.cross_attention_norms = nn.ModuleList(
                [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
            )

            self.cross_attentions = nn.ModuleList(
                [
                    nn.MultiheadAttention(
                        embed_dim=out_channels, num_heads=num_heads, batch_first=True
                    )
                    for i in range(num_layers)
                ]
            )

            self.context_proj = nn.ModuleList(
                [
                    nn.Linear(in_features=context_dim, out_features=out_channels)
                    for i in range(num_layers)
                ]
            )

        # Down sample by a factor of 2
        self.down_sample_conv = (
            nn.Conv2d(
                in_channels=out_channels,
                out_channels=out_channels,
                kernel_size=4,
                stride=2,
                padding=1,
            )
            if self.down_sample
            else nn.Identity()
        )  # (batch_size, out_channels, h / 2, w / 2)

    def forward(self, x, t_emb=None, context=None):
        out = x
        for i in range(self.num_layers):
            # Resnet block of UNET
            resnet_input = out  # (batch_size, c, h, w)

            out = self.resnet_conv_first[i](out)  # (batch_size, out_channels, h, w)

            # Only add the time embedding for diffusion and not AutoEncoder
            if self.t_emb_dim is not None:
                # Add the embeddings for timesteps - (batch_size, t_emb_dim) -> (batch_size, out_channels, 1, 1)
                out = out + self.t_emb_layers[i](t_emb).unsqueeze(dim=-1).unsqueeze(
                    dim=-1
                )  # (batch_size, out_channels, h, w)

            out = self.resnet_conv_second[i](
                out
            )  # (batch_size, out_channels, h, w) -> (batch_size, out_channels, h, w)

            # Residual Connection
            out = out + self.residual_input_conv[i](
                resnet_input
            )  # (batch_size, out_channels, h, w)

            # Only do for Diffusion and not for AutoEncoder
            if self.attn:
                # Attention block of UNET
                batch_size, channels, h, w = (
                    out.shape
                )  # (batch_size, out_channels, h, w)

                in_attn = out.reshape(
                    batch_size, channels, h * w
                )  # (batch_size, out_channels, h * w)
                in_attn = self.attention_norms[i](in_attn)
                in_attn = in_attn.transpose(1, 2)  # (batch_size, h * w, out_channels)

                # Self-Attention
                out_attn, attn_weights = self.attentions[i](in_attn, in_attn, in_attn)
                out_attn = out_attn.transpose(1, 2).reshape(
                    batch_size, channels, h, w
                )  # (batch_size, out_channels h, w)

                # Skip connection
                out = out + out_attn  # (batch_size, out_channels h, w)

            if self.cross_attn:
                assert (
                    context is not None
                ), "context cannot be None if cross attention layers are used"

                batch_size, channels, h, w = (
                    out.shape
                )  # (batch_size, out_channels, h, w)

                in_attn = out.reshape(
                    batch_size, channels, h * w
                )  # (batch_size, out_channels, h * w)
                in_attn = self.cross_attention_norms[i](in_attn)
                in_attn = in_attn.transpose(1, 2)  # (batch_size, h * w, out_channels)

                assert (
                    context.shape[0] == x.shape[0]
                    and context.shape[-1] == self.context_dim
                )  # Make sure the batch_size and context_dim match with the model's parameters
                context_proj = self.context_proj[i](
                    context
                )  # (batch_size, seq_len, context_dim) -> (batch_size, seq_len, out_channels)

                # Cross-Attention
                out_attn, attn_weights = self.cross_attentions[i](
                    in_attn, context_proj, context_proj
                )  # (batch_size, h * w, out_channels)
                out_attn = out_attn.transpose(1, 2).reshape(
                    batch_size, channels, h, w
                )  # (batch_size, out_channels, h, w)

                # Skip Connection
                out = out + out_attn  # (batch_size, out_channels, h, w)

        # Downsampling
        out = self.down_sample_conv(out)  # (batch_size, out_channels, h / 2, w / 2)
        return out


class MidBlock(nn.Module):
    """
    Mid conv block with attention.
    1. Resnet block with time embedding
    2. Attention block
    3. Resnet block with time embedding

    in_channels: Number of channels in the input feature map.
    out_channels: Number of channels produced by this block.
    t_emb_dim: Dimension of the time embedding. Only use for UNet for Diffusion. In an AutoEncoder, set it to None.
    num_heads: Number of attention heads (used if attention is enabled).
    num_layers: How many sub-blocks to apply in sequence.
    norm_channels: Number of groups for GroupNorm.
    cross_attn: Whether to apply cross-attention.
    context_dim: If performing cross-attention, provide a context_dim for extra conditioning context.
    """

    def __init__(
        self,
        in_channels,
        out_channels,
        t_emb_dim,
        num_heads,
        num_layers,
        norm_channels,
        cross_attn=None,
        context_dim=None,
    ):
        super().__init__()

        self.num_layers = num_layers
        self.t_emb_dim = t_emb_dim
        self.context_dim = context_dim
        self.cross_attn = cross_attn

        self.resnet_conv_first = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(
                        norm_channels, in_channels if i == 0 else out_channels
                    ),  # Normalizes over channels. For the first sub-block, the in_channels=in_channels, else out_channels
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=(in_channels if i == 0 else out_channels),
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, c, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers + 1)
            ]
        )

        # Only add the time embedding for diffusion and not AutoEncoder
        if self.t_emb_dim is not None:
            self.t_emb_layers = nn.ModuleList(
                [
                    nn.Sequential(
                        nn.SiLU(),
                        nn.Linear(
                            in_features=self.t_emb_dim, out_features=out_channels
                        ),  # (batch_size, t_emb_dim) -> (batch_size, out_channels)
                    )
                    for i in range(num_layers + 1)
                ]
            )

        self.resnet_conv_second = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(norm_channels, out_channels),
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, out_channels, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers + 1)
            ]
        )

        self.residual_input_conv = nn.ModuleList(
            [
                nn.Conv2d(
                    in_channels=(in_channels if i == 0 else out_channels),
                    out_channels=out_channels,
                    kernel_size=1,
                    stride=1,
                    padding=0,
                )  # (batch_size, in_channels, h, w) -> (batch_size, out_channels, h, w)
                for i in range(num_layers + 1)
            ]
        )

        self.attention_norms = nn.ModuleList(
            [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
        )

        self.attentions = nn.ModuleList(
            [
                nn.MultiheadAttention(
                    embed_dim=out_channels, num_heads=num_heads, batch_first=True
                )
                for i in range(num_layers)
            ]
        )

        # Cross attention for text conditioning
        if self.cross_attn:
            assert (
                context_dim is not None
            ), "Context Dimension must be passed for cross attention"

            self.cross_attention_norms = nn.ModuleList(
                [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
            )

            self.cross_attentions = nn.ModuleList(
                [
                    nn.MultiheadAttention(
                        embed_dim=out_channels, num_heads=num_heads, batch_first=True
                    )
                    for i in range(num_layers)
                ]
            )

            self.context_proj = nn.ModuleList(
                [
                    nn.Linear(in_features=context_dim, out_features=out_channels)
                    for i in range(num_layers)
                ]
            )

    def forward(self, x, t_emb=None, context=None):
        out = x

        # First ResNet block
        resnet_input = out  # (batch_size, c, h, w)
        out = self.resnet_conv_first[0](out)  # (batch_size, out_channels, h, w)

        # Only add the time embedding for diffusion and not AutoEncoder
        if self.t_emb_dim is not None:
            # Add the embeddings for timesteps - (batch_size, t_emb_dim) -> (batch_size, out_channels, 1, 1)
            out = out + self.t_emb_layers[0](t_emb).unsqueeze(dim=-1).unsqueeze(
                dim=-1
            )  # (batch_size, out_channels, h, w)

        out = self.resnet_conv_second[0](
            out
        )  # (batch_size, out_channels, h, w) -> (batch_size, out_channels, h, w)

        # Residual Connection
        out = out + self.residual_input_conv[0](
            resnet_input
        )  # (batch_size, out_channels, h, w)

        for i in range(self.num_layers):
            # Attention Block
            batch_size, channels, h, w = out.shape  # (batch_size, out_channels, h, w)

            # Do for both Diffusion and AutoEncoder
            in_attn = out.reshape(
                batch_size, channels, h * w
            )  # (batch_size, out_channels, h * w)
            in_attn = self.attention_norms[i](in_attn)
            in_attn = in_attn.transpose(1, 2)  # (batch_size, h * w, out_channels)

            # Self-Attention
            out_attn, attn_weights = self.attentions[i](in_attn, in_attn, in_attn)
            out_attn = out_attn.transpose(1, 2).reshape(batch_size, channels, h, w)

            # Skip connection
            out = out + out_attn  # (batch_size, out_channels h, w)

            if self.cross_attn:
                assert (
                    context is not None
                ), "context cannot be None if cross attention layers are used"
                batch_size, channels, h, w = out.shape

                in_attn = out.reshape(
                    batch_size, channels, h * w
                )  # (batch_size, out_channels, h * w)
                in_attn = self.cross_attention_norms[i](in_attn)
                in_attn = in_attn.transpose(1, 2)  # (batch_size, h * w, out_channels)

                assert (
                    context.shape[0] == x.shape[0]
                    and context.shape[-1] == self.context_dim
                )  # Make sure the batch_size and context_dim match with the model's parameters
                context_proj = self.context_proj[i](
                    context
                )  # (batch_size, seq_len, context_dim) -> (batch_size, seq_len, context_dim)

                # Cross-Attention
                out_attn, attn_weights = self.cross_attentions[i](
                    in_attn, context_proj, context_proj
                )
                out_attn = out_attn.transpose(1, 2).reshape(
                    batch_size, channels, h, w
                )  # (batch_size, out_channels, h, w)

                # Skip Connection
                out = out + out_attn  # (batch_size, out_channels h, w)

            # Resnet Block
            resnet_input = out
            out = self.resnet_conv_first[i + 1](
                out
            )  # (batch_size, out_channels h, w) -> (batch_size, out_channels h, w)

            # Only add the time embedding for diffusion and not AutoEncoder
            if self.t_emb_dim is not None:
                # Add the embeddings for timesteps - (batch_size, t_emb_dim) -> (batch_size, out_channels, 1, 1)
                out = out + self.t_emb_layers[i + 1](t_emb).unsqueeze(dim=-1).unsqueeze(
                    dim=-1
                )  # (batch_size, out_channels h, w)

            out = self.resnet_conv_second[i + 1](
                out
            )  # (batch_size, out_channels h, w) -> (batch_size, out_channels h, w)

            # Residual Connection
            out = out + self.residual_input_conv[i + 1](
                resnet_input
            )  # (batch_size, out_channels, h, w)

        return out


class UpBlock(nn.Module):
    """
    Up conv block with attention.
    1. Upsample
    1. Concatenate Down block output
    2. Resnet block with time embedding
    3. Attention Block

    in_channels: Number of channels in the input feature map.
    out_channels: Number of channels produced by this block.
    t_emb_dim: Dimension of the time embedding. Only use for UNet for Diffusion. In an AutoEncoder, set it to None.
    up_sample: Whether to apply upsampling at the end.
    num_heads: Number of attention heads (used if attention is enabled).
    num_layers: How many sub-blocks to apply in sequence.
    attn: Whether to apply self-attention
    norm_channels: Number of groups for GroupNorm.
    """

    def __init__(
        self,
        in_channels,
        out_channels,
        t_emb_dim,
        up_sample,
        num_heads,
        num_layers,
        attn,
        norm_channels,
    ):
        super().__init__()

        self.num_layers = num_layers
        self.up_sample = up_sample
        self.t_emb_dim = t_emb_dim
        self.attn = attn

        # Upsample by a factor of 2
        self.up_sample_conv = (
            nn.ConvTranspose2d(
                in_channels=in_channels,
                out_channels=in_channels,
                kernel_size=4,
                stride=2,
                padding=1,
            )
            if self.up_sample
            else nn.Identity()
        )  # (batch_size, c, h * 2, w * 2)

        self.resnet_conv_first = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(
                        norm_channels, in_channels if i == 0 else out_channels
                    ),  # Normalizes over channels. For the first sub-block, the in_channels=in_channels, else out_channels
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=(in_channels if i == 0 else out_channels),
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, c, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers)
            ]
        )

        # Only add the time embedding for diffusion and not AutoEncoder
        if self.t_emb_dim is not None:
            self.t_emb_layers = nn.ModuleList(
                [
                    nn.Sequential(
                        nn.SiLU(),
                        nn.Linear(
                            in_features=self.t_emb_dim, out_features=out_channels
                        ),  # (batch_size, t_emb_dim) -> (batch_size, out_channels)
                    )
                    for i in range(num_layers)
                ]
            )

        self.resnet_conv_second = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(norm_channels, out_channels),
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, out_channels, h, w) -> (batch_size, out_channels, h, w)
                )
                for i in range(num_layers)
            ]
        )

        self.residual_input_conv = nn.ModuleList(
            [
                nn.Conv2d(
                    in_channels=(in_channels if i == 0 else out_channels),
                    out_channels=out_channels,
                    kernel_size=1,
                    stride=1,
                    padding=0,
                )  # (batch_size, in_channels, h, w) -> (batch_size, out_channels, h, w)
                for i in range(num_layers)
            ]
        )

        if self.attn:
            self.attention_norms = nn.ModuleList(
                [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
            )

            self.attentions = nn.ModuleList(
                [
                    nn.MultiheadAttention(
                        embed_dim=out_channels, num_heads=num_heads, batch_first=True
                    )
                    for i in range(num_layers)
                ]
            )

    def forward(self, x, out_down=None, t_emb=None):
        # x shape: (batch_size, c, h, w)

        # Upsample
        x = self.up_sample_conv(
            x
        )  # (batch_size, c, h, w) -> (batch_size, c, h * 2, w * 2)

        # *Only do for diffusion
        # Concatenate with the output of respective DownBlock
        if out_down is not None:
            x = torch.cat(
                [x, out_down], dim=1
            )  # (batch_size, c, h * 2, w * 2) -> (batch_size, c * 2, h * 2, w * 2)

        out = x  # (batch_size, c, h * 2, w * 2)

        for i in range(self.num_layers):
            # Resnet block
            resnet_input = out
            out = self.resnet_conv_first[i](
                out
            )  # (batch_size, in_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)

            # Only add the time embedding for diffusion and not AutoEncoder
            if self.t_emb_dim is not None:
                # Add the embeddings for timesteps - (batch_size, t_emb_dim) -> (batch_size, out_channels, 1, 1)
                out = out + self.t_emb_layers[i](t_emb).unsqueeze(dim=-1).unsqueeze(
                    dim=-1
                )  # (batch_size, out_channels, h * 2, w * 2)

            out = self.resnet_conv_second[i](
                out
            )  # (batch_size, out_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)

            # Residual Connection
            out = out + self.residual_input_conv[i](
                resnet_input
            )  # (batch_size, out_channels, h * 2, w * 2)

            # Only do for Diffusion and not for AutoEncoder
            if self.attn:
                # Attention block of UNET
                batch_size, channels, h, w = out.shape

                in_attn = out.reshape(
                    batch_size, channels, h * w
                )  # (batch_size, out_channels, h * w * 4)
                in_attn = self.attention_norms[i](in_attn)
                in_attn = in_attn.transpose(
                    1, 2
                )  # (batch_size, h * w * 4, out_channels)

                # Self-Attention
                out_attn, attn_weights = self.attentions[i](in_attn, in_attn, in_attn)
                out_attn = out_attn.transpose(1, 2).reshape(
                    batch_size, channels, h, w
                )  # (batch_size, out_channels h * 2, w * 2)

                # Skip connection
                out = out + out_attn  # (batch_size, out_channels h * 2, w * 2)

        return out  # (batch_size, out_channels h * 2, w * 2)


class UpBlockUNet(nn.Module):
    """
    Up conv block with attention.
    1. Upsample
    1. Concatenate Down block output
    2. Resnet block with time embedding
    3. Attention Block

    in_channels: Number of channels in the input feature map. (It is passed in multiplied by 2 for concatenation with DownBlock output)
    out_channels: Number of channels produced by this block.
    t_emb_dim: Dimension of the time embedding. Only use for UNet for Diffusion. In an AutoEncoder, set it to None.
    up_sample: Whether to apply upsampling at the end.
    num_heads: Number of attention heads (used if attention is enabled).
    num_layers: How many sub-blocks to apply in sequence.
    norm_channels: Number of groups for GroupNorm.
    cross_attn: Whether to apply cross-attention.
    context_dim: If performing cross-attention, provide a context_dim for extra conditioning context.
    """

    def __init__(
        self,
        in_channels,
        out_channels,
        t_emb_dim,
        up_sample,
        num_heads,
        num_layers,
        norm_channels,
        cross_attn=False,
        context_dim=None,
    ):
        super().__init__()

        self.num_layers = num_layers
        self.up_sample = up_sample
        self.t_emb_dim = t_emb_dim
        self.cross_attn = cross_attn
        self.context_dim = context_dim

        self.up_sample_conv = (
            nn.ConvTranspose2d(
                in_channels=(in_channels // 2),
                out_channels=(in_channels // 2),
                kernel_size=4,
                stride=2,
                padding=1,
            )
            if self.up_sample
            else nn.Identity()
        )  # (batch_size, in_channels // 2, h * 2, w * 2)

        self.resnet_conv_first = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(
                        norm_channels, in_channels if i == 0 else out_channels
                    ),  # Normalizes over channels. For the first sub-block, the in_channels=in_channels, else out_channels
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=(in_channels if i == 0 else out_channels),
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, in_channels, h * 2, w. * 2) -> (batch_size, out_channels, h * 2, w * 2) - Starts at in_channels and not in_channels // 2 because of concatenation
                )
                for i in range(num_layers)
            ]
        )

        # Only add the time embedding if needed for UNET in diffusion
        # Do not add the time embedding in the AutoEncoder
        if self.t_emb_dim is not None:
            self.t_emb_layers = nn.ModuleList(
                [
                    nn.Sequential(
                        nn.SiLU(),
                        nn.Linear(
                            in_features=self.t_emb_dim, out_features=out_channels
                        ),  # (batch_size, t_emb_dim) -> (batch_size, out_channels)
                    )
                    for i in range(num_layers)
                ]
            )

        self.resnet_conv_second = nn.ModuleList(
            [
                nn.Sequential(
                    nn.GroupNorm(norm_channels, out_channels),
                    nn.SiLU(),
                    nn.Conv2d(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        kernel_size=3,
                        stride=1,
                        padding=1,
                    ),  # (batch_size, out_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)
                )
                for i in range(num_layers)
            ]
        )

        self.residual_input_conv = nn.ModuleList(
            [
                nn.Conv2d(
                    in_channels=(in_channels if i == 0 else out_channels),
                    out_channels=out_channels,
                    kernel_size=1,
                    stride=1,
                    padding=0,
                )
                for i in range(
                    num_layers
                )  # (batch_size, in_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)
            ]
        )

        self.attention_norms = nn.ModuleList(
            [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
        )

        self.attentions = nn.ModuleList(
            [
                nn.MultiheadAttention(
                    embed_dim=out_channels, num_heads=num_heads, batch_first=True
                )
                for i in range(num_layers)
            ]
        )

        # Cross attention for text conditioning
        if self.cross_attn:
            assert (
                context_dim is not None
            ), "Context Dimension must be passed for cross attention"

            self.cross_attention_norms = nn.ModuleList(
                [nn.GroupNorm(norm_channels, out_channels) for i in range(num_layers)]
            )

            self.cross_attentions = nn.ModuleList(
                [
                    nn.MultiheadAttention(
                        embed_dim=out_channels, num_heads=num_heads, batch_first=True
                    )
                    for i in range(num_layers)
                ]
            )

            self.context_proj = nn.ModuleList(
                [
                    nn.Linear(in_features=context_dim, out_features=out_channels)
                    for i in range(num_layers)
                ]
            )

    def forward(self, x, out_down=None, t_emb=None, context=None):
        # x shape: (batch_size, in_channels // 2, h, w)

        # Upsample
        x = self.up_sample_conv(
            x
        )  # (batch_size, in_channels // 2, h, w) -> (batch_size, in_channels // 2, h * 2, w * 2)

        # Concatenate with the output of respective DownBlock
        if out_down is not None:
            x = torch.cat(
                [x, out_down], dim=1
            )  # (batch_size, in_channels // 2, h * 2, w * 2) -> (batch_size, in_channels, h * 2, w * 2)

        out = x  # (batch_size, in_channels, h * 2, w * 2)
        for i in range(self.num_layers):
            # Resnet block
            resnet_input = out

            out = self.resnet_conv_first[i](
                out
            )  # (batch_size, in_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)

            if self.t_emb_dim is not None:
                # Add the embeddings for timesteps - (batch_size, t_emb_dim) -> (batch_size, out_channels, 1, 1)
                out = out + self.t_emb_layers[i](t_emb).unsqueeze(dim=-1).unsqueeze(
                    dim=-1
                )  # (batch_size, out_channels, h * 2, w * 2)

            out = self.resnet_conv_second[i](
                out
            )  # (batch_size, out_channels, h * 2, w * 2) -> (batch_size, out_channels, h * 2, w * 2)

            # Residual Connection
            out = out + self.residual_input_conv[i](
                resnet_input
            )  # (batch_size, out_channels, h * 2, w * 2)

            # Attention block of UNET
            batch_size, channels, h, w = (
                out.shape
            )  # (batch_size, out_channels, h * 2, w * 2)

            in_attn = out.reshape(
                batch_size, channels, h * w
            )  # (batch_size, out_channels, h * w * 4)
            in_attn = self.attention_norms[i](in_attn)
            in_attn = in_attn.transpose(1, 2)  # (batch_size, h * w * 4, out_channels)

            # Self-Attention
            out_attn, attn_weights = self.attentions[i](in_attn, in_attn, in_attn)
            out_attn = out_attn.transpose(1, 2).reshape(
                batch_size, channels, h, w
            )  # (batch_size, out_channels h * 2, w * 2)

            # Skip connection
            out = out + out_attn  # (batch_size, out_channels h * 2, w * 2)

            if self.cross_attn:
                assert (
                    context is not None
                ), "context cannot be None if cross attention layers are used"
                batch_size, channels, h, w = out.shape

                in_attn = out.reshape(
                    batch_size, channels, h * w
                )  # (batch_size, out_channels, h * w * 4)
                in_attn = self.cross_attention_norms[i](in_attn)
                in_attn = in_attn.transpose(
                    1, 2
                )  # (batch_size, h * w * 4, out_channels)

                assert (
                    len(context.shape) == 3
                ), "Context shape does not match batch_size, _, context_dim"

                assert (
                    context.shape[0] == x.shape[0]
                    and context.shape[-1] == self.context_dim
                ), "Context shape does not match batch_size, _, context_dim"  # Make sure the batch_size and context_dim match with the model's parameters
                context_proj = self.context_proj[i](
                    context
                )  # (batch_size, seq_len, context_dim) -> (batch_size, seq_len, context_dim)

                # Cross-Attention
                out_attn, attn_weights = self.cross_attentions[i](
                    in_attn, context_proj, context_proj
                )
                out_attn = out_attn.transpose(1, 2).reshape(
                    batch_size, channels, h, w
                )  # (batch_size, out_channels, h * 2, w * 2)

                # Skip Connection
                out = out + out_attn  # (batch_size, out_channels h * 2, w * 2)

        return out  # (batch_size, out_channels h * 2, w * 2)


class VQVAE(nn.Module):
    def __init__(self, image_channels, model_config):
        super().__init__()

        self.down_channels = model_config["down_channels"]
        self.mid_channels = model_config["mid_channels"]
        self.down_sample = model_config["down_sample"]
        self.num_down_layers = model_config["num_down_layers"]
        self.num_mid_layers = model_config["num_mid_layers"]
        self.num_up_layers = model_config["num_up_layers"]

        # To disable attention in Downblock of Encoder and Upblock of Decoder
        self.attns = model_config["attn_down"]

        # Latent Dimension
        self.z_channels = model_config[
            "z_channels"
        ]  # number of channels in the latent representation
        self.codebook_size = model_config[
            "codebook_size"
        ]  # number of discrete code vectors available
        self.norm_channels = model_config["norm_channels"]
        self.num_heads = model_config["num_heads"]

        assert self.mid_channels[0] == self.down_channels[-1]
        assert self.mid_channels[-1] == self.down_channels[-1]
        assert len(self.down_sample) == len(self.down_channels) - 1
        assert len(self.attns) == len(self.down_channels) - 1

        # Wherever we downsample in the encoder, use upsampling in the decoder at the corresponding location
        self.up_sample = list(reversed(self.down_sample))

        # Encoder
        self.encoder_conv_in = nn.Conv2d(
            in_channels=image_channels,
            out_channels=self.down_channels[0],
            kernel_size=3,
            stride=1,
            padding=1,
        )  # (batch_size, 3, h, w) -> (batch_size, c, h, w)

        # Downblock + Midblock
        self.encoder_layers = nn.ModuleList([])
        for i in range(len(self.down_channels) - 1):
            self.encoder_layers.append(
                DownBlock(
                    in_channels=self.down_channels[i],
                    out_channels=self.down_channels[i + 1],
                    t_emb_dim=None,
                    down_sample=self.down_sample[i],
                    num_heads=self.num_heads,
                    num_layers=self.num_down_layers,
                    attn=self.attns[i],
                    norm_channels=self.norm_channels,
                )
            )

        self.encoder_mids = nn.ModuleList([])
        for i in range(len(self.mid_channels) - 1):
            self.encoder_mids.append(
                MidBlock(
                    in_channels=self.mid_channels[i],
                    out_channels=self.mid_channels[i + 1],
                    t_emb_dim=None,
                    num_heads=self.num_heads,
                    num_layers=self.num_mid_layers,
                    norm_channels=self.norm_channels,
                )
            )

        self.encoder_norm_out = nn.GroupNorm(self.norm_channels, self.down_channels[-1])

        self.encoder_conv_out = nn.Conv2d(
            in_channels=self.down_channels[-1],
            out_channels=self.z_channels,
            kernel_size=3,
            stride=1,
            padding=1,
        )  # (batch_size, z_channels, h', w')

        # Pre Quantization Convolution
        self.pre_quant_conv = nn.Conv2d(
            in_channels=self.z_channels,
            out_channels=self.z_channels,
            kernel_size=1,
            stride=1,
            padding=0,
        )  # (batch_size, z_channels, h', w')

        # Codebook Vectors
        self.embedding = nn.Embedding(
            self.codebook_size, self.z_channels
        )  # (codebook_size, z_channels)

        # Decoder

        # Post Quantization Convolution
        self.post_quant_conv = nn.Conv2d(
            in_channels=self.z_channels,
            out_channels=self.z_channels,
            kernel_size=1,
            stride=1,
            padding=0,
        )  # (batch_size, z_channels, h', w')

        self.decoder_conv_in = nn.Conv2d(
            in_channels=self.z_channels,
            out_channels=self.mid_channels[-1],
            kernel_size=3,
            stride=1,
            padding=1,
        )  # (batch_size, c, h', w')

        # Midblock + Upblock
        self.decoder_mids = nn.ModuleList([])
        for i in reversed(range(1, len(self.mid_channels))):
            self.decoder_mids.append(
                MidBlock(
                    in_channels=self.mid_channels[i],
                    out_channels=self.mid_channels[i - 1],
                    t_emb_dim=None,
                    num_heads=self.num_heads,
                    num_layers=self.num_mid_layers,
                    norm_channels=self.norm_channels,
                )
            )

        self.decoder_layers = nn.ModuleList([])
        for i in reversed(range(1, len(self.down_channels))):
            self.decoder_layers.append(
                UpBlock(
                    in_channels=self.down_channels[i],
                    out_channels=self.down_channels[i - 1],
                    t_emb_dim=None,
                    up_sample=self.down_sample[i - 1],
                    num_heads=self.num_heads,
                    num_layers=self.num_up_layers,
                    attn=self.attns[i - 1],
                    norm_channels=self.norm_channels,
                )
            )

        self.decoder_norm_out = nn.GroupNorm(self.norm_channels, self.down_channels[0])

        self.decoder_conv_out = nn.Conv2d(
            in_channels=self.down_channels[0],
            out_channels=image_channels,
            kernel_size=3,
            stride=1,
            padding=1,
        )  # (batch_size, c, h, w)

    def quantize(self, x):
        batch_size, c, h, w = x.shape  # (batch_size, z_channels, h, w)

        x = x.permute(
            0, 2, 3, 1
        )  # (batch_size, z_channels, h, w) -> (batch_size, h, w, z_channels)
        x = x.reshape(
            batch_size, -1, c
        )  # (batch_size, h, w, z_channels) -> (batch_size, h * w, z_channels)

        # Find the nearest codebook vector with distance between (batch_size, h * w, z_channels) and (batch_size, code_book_size, z_channels) -> (batch_size, h * w, code_book_size)
        dist = torch.cdist(
            x, self.embedding.weight.unsqueeze(dim=0).repeat((batch_size, 1, 1))
        )  # cdist calculates the batched p-norm distance

        # (batch_size, h * w) Get the index of the closet codebook vector
        min_encoding_indices = torch.argmin(dist, dim=-1)

        # Replace the encoder output with the nearest codebook
        quant_out = torch.index_select(
            self.embedding.weight, 0, min_encoding_indices.view(-1)
        )  # (batch_size, h * w, z_channels)

        x = x.reshape((-1, c))  # (batch_size * h * w, z_channels)

        # Commitment and Codebook Loss using mSE
        commitment_loss = torch.mean((quant_out.detach() - x) ** 2)
        codebook_loss = torch.mean((quant_out - x.detach()) ** 2)

        quantize_losses = {
            "codebook_loss": codebook_loss,
            "commitment_loss": commitment_loss,
        }

        # Straight through estimation
        quant_out = x + (quant_out - x).detach()

        quant_out = quant_out.reshape(batch_size, h, w, c).permute(
            0, 3, 1, 2
        )  # (batch_size, z_channels, h, w)
        min_encoding_indices = min_encoding_indices.reshape(
            (-1, h, w)
        )  # (batch_size, h, w)

        return quant_out, quantize_losses, min_encoding_indices

    def encode(self, x):
        out = self.encoder_conv_in(x)  # (batch_size, self.down_channels[0], h, w)

        # (batch_size, self.down_channels[0], h, w) -> (batch_size, self.down_channels[-1], h', w')
        for idx, down in enumerate(self.encoder_layers):
            out = down(out)

        # (batch_size, self.down_channels[-1], h', w') -> (batch_size, self.mid_channels[-1], h', w')
        for mid in self.encoder_mids:
            out = mid(out)

        out = self.encoder_norm_out(out)
        out = F.silu(out)

        out = self.encoder_conv_out(
            out
        )  # (batch_size, self.mid_channels[-1], h', w') -> (batch_size, self.z_channels, h', w')
        out = self.pre_quant_conv(
            out
        )  # (batch_size, self.z_channels, h', w') -> (batch_size, self.z_channels, h', w')

        out, quant_losses, min_encoding_indices = self.quantize(
            out
        )  # (batch_size, self.z_channels, h', w'), (codebook_loss, commitment_loss), (batch_size, h, w)
        return out, quant_losses

    def decode(self, z):
        out = z
        out = self.post_quant_conv(
            out
        )  # (batch_size, self.z_channels, h', w') -> (batch_size, self.z_channels, h', w')
        out = self.decoder_conv_in(
            out
        )  # (batch_size, self.z_channels, h', w') -> (batch_size, self.mid_channels[-1], h', w')

        # (batch_size, self.mid_channels[-1], h', w') -> (batch_size, self.down_channels[-1], h', w')
        for mid in self.decoder_mids:
            out = mid(out)

        # (batch_size, self.down_channels[-1], h', w') -> (batch_size, self.down_channels[0], h, w)
        for idx, up in enumerate(self.decoder_layers):
            out = up(out)

        out = self.decoder_norm_out(out)
        out = F.silu(out)

        out = self.decoder_conv_out(
            out
        )  # (batch_size, self.down_channels[0], h, w) -> (batch_size, c, h, w)
        return out

    def forward(self, x):
        # x shape: (batch_size, c, h, w)

        z, quant_losses = self.encode(
            x
        )  # (batch_size, self.z_channels, h', w'), (codebook_loss, commitment_loss)
        out = self.decode(z)  # (batch_size, c, h, w)

        return out, z, quant_losses


def validate_image_conditional_input(cond_input, x):
    assert (
        "image" in cond_input
    ), "Model initialized with image conditioning but cond_input has no image information"
    assert (
        cond_input["image"].shape[0] == x.shape[0]
    ), "Batch size mismatch of image condition and input"
    assert (
        cond_input["image"].shape[2] % x.shape[2] == 0
    ), "Height/Width of image condition must be divisible by latent input"


def validate_class_conditional_input(cond_input, x, num_classes):
    assert (
        "class" in cond_input
    ), "Model initialized with class conditioning but cond_input has no class information"
    assert cond_input["class"].shape == (
        x.shape[0],
        num_classes,
    ), "Shape of class condition input must match (Batch Size, )"


def get_config_value(config, key, default_value):
    return config[key] if key in config else default_value


class UNet(nn.Module):
    """
    Unet model comprising
    Down blocks, Midblocks and Uplocks
    """

    def __init__(self, image_channels, model_config):
        super().__init__()

        self.down_channels = model_config["down_channels"]
        self.mid_channels = model_config["mid_channels"]
        self.t_emb_dim = model_config["time_emb_dim"]
        self.down_sample = model_config["down_sample"]
        self.num_down_layers = model_config["num_down_layers"]
        self.num_mid_layers = model_config["num_mid_layers"]
        self.num_up_layers = model_config["num_up_layers"]
        self.attns = model_config["attn_down"]
        self.norm_channels = model_config["norm_channels"]
        self.num_heads = model_config["num_heads"]
        self.conv_out_channels = model_config["conv_out_channels"]

        assert self.mid_channels[0] == self.down_channels[-1]
        assert self.mid_channels[-1] == self.down_channels[-2]
        assert len(self.down_sample) == len(self.down_channels) - 1
        assert len(self.attns) == len(self.down_channels) - 1

        # Class, Mask, and Text Conditioning Config
        self.class_cond = False
        self.text_cond = False
        self.image_cond = False
        self.text_embed_dim = None
        self.condition_config = get_config_value(
            model_config, "condition_config", None
        )  # Get the dictionary containing conditional information

        if self.condition_config is not None:
            assert (
                "condition_types" in self.condition_config
            ), "Condition Type not provided in model config"
            condition_types = self.condition_config["condition_types"]

            # For class, text, and image, get necessary parameters
            if "class" in condition_types:
                self.class_cond = True
                self.num_classes = self.condition_config["class_condition_config"][
                    "num_classes"
                ]

            if "text" in condition_types:
                self.text_cond = True
                self.text_embed_dim = self.condition_config["text_condition_config"][
                    "text_embed_dim"
                ]

            if "image" in condition_types:
                self.image_cond = True
                self.image_cond_input_channels = self.condition_config[
                    "image_condition_config"
                ]["image_condition_input_channels"]
                self.image_cond_output_channels = self.condition_config[
                    "image_condition_config"
                ]["image_condition_output_channels"]

        if self.class_cond:
            # For class conditioning, do not add the class embedding information for unconditional generation
            self.class_emb = nn.Embedding(
                self.num_classes, self.t_emb_dim
            )  # (num_classes, t_emb_dim)

        if self.image_cond:
            # Map the mask image to a image_cond_output_channels channel image, and concat with input across the channel dimension
            self.cond_conv_in = nn.Conv2d(
                in_channels=self.image_cond_input_channels,
                out_channels=self.image_cond_output_channels,
                kernel_size=1,
                stride=1,
                padding=0,
                bias=False,
            )

            self.conv_in_concat = nn.Conv2d(
                in_channels=(image_channels + self.image_cond_output_channels),
                out_channels=self.down_channels[0],
                kernel_size=3,
                stride=1,
                padding=1,
            )
        else:
            self.conv_in = nn.Conv2d(
                in_channels=image_channels,
                out_channels=self.down_channels[0],
                kernel_size=3,
                stride=1,
                padding=1,
            )  # (batch_size, image_channels, h, w) -> (batch_size, self.down_channels[0], h, w)

        self.cond = self.text_cond or self.image_cond or self.class_cond

        # Initial projection from sinusoidal time embedding
        self.t_proj = nn.Sequential(
            nn.Linear(in_features=self.t_emb_dim, out_features=self.t_emb_dim),
            nn.SiLU(),
            nn.Linear(in_features=self.t_emb_dim, out_features=self.t_emb_dim),
        )  # (batch_size, t_emb_dim)

        self.up_sample = list(reversed(self.down_sample))

        self.downs = nn.ModuleList([])
        for i in range(len(self.down_channels) - 1):
            # Cross attention and Context Dim are only used for text conditioning
            self.downs.append(
                DownBlock(
                    in_channels=self.down_channels[i],
                    out_channels=self.down_channels[i + 1],
                    t_emb_dim=self.t_emb_dim,
                    down_sample=self.down_sample[i],
                    num_heads=self.num_heads,
                    num_layers=self.num_down_layers,
                    attn=self.attns[i],
                    norm_channels=self.norm_channels,
                    cross_attn=self.text_cond,
                    context_dim=self.text_embed_dim,
                )
            )

        self.mids = nn.ModuleList([])
        for i in range(len(self.mid_channels) - 1):
            # Cross attention and Context Dim are only used for text conditioning
            self.mids.append(
                MidBlock(
                    in_channels=self.mid_channels[i],
                    out_channels=self.mid_channels[i + 1],
                    t_emb_dim=self.t_emb_dim,
                    num_heads=self.num_heads,
                    num_layers=self.num_mid_layers,
                    norm_channels=self.norm_channels,
                    cross_attn=self.text_cond,
                    context_dim=self.text_embed_dim,
                )
            )

        self.ups = nn.ModuleList([])
        for i in reversed(range(len(self.down_channels) - 1)):
            # Cross attention and Context Dim are only used for text conditioning
            self.ups.append(
                UpBlockUNet(
                    in_channels=(self.down_channels[i] * 2),
                    out_channels=(
                        self.down_channels[i - 1] if i != 0 else self.conv_out_channels
                    ),
                    t_emb_dim=self.t_emb_dim,
                    up_sample=self.down_sample[i],
                    num_heads=self.num_heads,
                    num_layers=self.num_up_layers,
                    norm_channels=self.norm_channels,
                    cross_attn=self.text_cond,
                    context_dim=self.text_embed_dim,
                )
            )

        self.norm_out = nn.GroupNorm(self.norm_channels, self.conv_out_channels)

        self.conv_out = nn.Conv2d(
            in_channels=self.conv_out_channels,
            out_channels=image_channels,
            kernel_size=3,
            stride=1,
            padding=1,
        )  # (batch_size, conv_out_channels, h, w) -> (batch_size, image_channels, h, w)

    def forward(self, x, t, cond_input=None):
        # x shape: (batch_size, c, h, w)
        # cond_input is the conditioning vector
        # For class conditioning, it will be a one-hot vector of size # (batch_size, num_classes)

        if self.cond:
            assert (
                cond_input is not None
            ), "Model initialized with conditioning so cond_input cannot be None"

        if self.image_cond:
            # Mask Conditioning
            validate_image_conditional_input(cond_input, x)
            image_cond = cond_input["image"]
            image_cond = F.interpolate(image_cond, size=x.shape[-2:])
            image_cond = self.cond_conv_in(image_cond)
            assert image_cond.shape[-2:] == x.shape[-2:]

            x = torch.cat(
                [x, image_cond], dim=1
            )  # (batch_size, image_channels + image_cond_output_channels, h, w)
            out = self.conv_in_concat(x)  # (batch_size, down_channels[0], h, w)
        else:
            out = self.conv_in(x)  # (batch_size, down_channels[0], h, w)

        t_emb = get_time_embedding(
            torch.as_tensor(t).long(), self.t_emb_dim
        )  # (batch_size, t_emb_dim)
        t_emb = self.t_proj(t_emb)  # (batch_size, t_emb_dim)

        # Class Conditioning
        if self.class_cond:
            validate_class_conditional_input(cond_input, x, self.num_classes)

            # Take the matrix for class embedding vectors and matrix multiply it with the embedding matrix to get the class embedding for all images in a batch
            class_embed = torch.matmul(
                cond_input["class"].float(), self.class_emb.weight
            )  # (batch_size, t_emb_dim)
            t_emb += class_embed  # Add the class embedding to the time embedding

        context_hidden_states = None

        # Only use context hidden states in cross-attention for text conditioning
        if self.text_cond:
            assert (
                "text" in cond_input
            ), "Model initialized with text conditioning but cond_input has no text information"
            context_hidden_states = cond_input["text"]

        down_outs = []
        for idx, down in enumerate(self.downs):
            down_outs.append(out)
            out = down(
                out, t_emb, context_hidden_states
            )  # Use context_hidden_states for cross-attention
        # out = (batch_size, c4, h / 4, w / 4)

        for mid in self.mids:
            out = mid(out, t_emb, context_hidden_states)
        # out = (batch_size, c3, h / 4, w / 4)

        for up in self.ups:
            down_out = down_outs.pop()
            out = up(out, down_out, t_emb, context_hidden_states)
        # out = (batch_size, self.conv_out_channels, h, w)

        out = F.silu(self.norm_out(out))
        out = self.conv_out(
            out
        )  # (batch_size, self.conv_out_channels, h, w) -> (batch_size, image_channels, h, w)

        return out  # (batch_size, image_channels, h, w)