File size: 70,627 Bytes
0b06187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
import math
import copy
import torch
from torch import nn, einsum
import torch.nn.functional as F
from functools import partial
from pathlib import Path
from torch.optim import Adam
from torch.cuda.amp import autocast, GradScaler
from tqdm import tqdm
from einops import rearrange
from einops_exts import check_shape, rearrange_many
from rotary_embedding_torch import RotaryEmbedding
from ddpm.text import tokenize, bert_embed, BERT_MODEL_DIM
from torch.utils.data import DataLoader
# from vq_gan_3d.model.vqgan import VQGAN

from collections import defaultdict

# 检查x是否不为None
def exists(x):
    return x is not None
# 无操作函数,用作占位符
def noop(*args, **kwargs):
    pass
# 判断数字n是否为奇数
def is_odd(n):
    return (n % 2) == 1
# 如果val存在,则返回val;否则返回d()(如果d是可调用的)或d
def default(val, d):
    if exists(val):
        return val
    return d() if callable(d) else d
# 创建一个无限生成器,循环遍历数据加载器dl
def cycle(dl):
    while True:
        for data in dl:
            yield data
# 将num分成大小为divisor的组,处理余数
def num_to_groups(num, divisor):
    groups = num // divisor
    remainder = num % divisor
    arr = [divisor] * groups
    if remainder > 0:
        arr.append(remainder)
    return arr
# 根据概率prob生成一个掩码张量
def prob_mask_like(shape, prob, device):
    if prob == 1:
        return torch.ones(shape, device=device, dtype=torch.bool)
    elif prob == 0:
        return torch.zeros(shape, device=device, dtype=torch.bool)
    else:
        return torch.zeros(shape, device=device).float().uniform_(0, 1) < prob
# 检查x是否为字符串列表或元组
def is_list_str(x):
    if not isinstance(x, (list, tuple)):
        return False
    return all([type(el) == str for el in x])

class RelativePositionBias(nn.Module):
    def __init__(
        self,
        heads=8,
        num_buckets=32,
        max_distance=128
    ):
        super().__init__()
        self.num_buckets = num_buckets
        self.max_distance = max_distance
        self.relative_attention_bias = nn.Embedding(num_buckets, heads)

    @staticmethod
    def _relative_position_bucket(relative_position, num_buckets=32, max_distance=128):
        ret = 0
        n = -relative_position
        num_buckets //= 2
        ret += (n < 0).long() * num_buckets
        n = torch.abs(n)
        max_exact = num_buckets // 2
        is_small = n < max_exact
        val_if_large = max_exact + (
            torch.log(n.float() / max_exact) / math.log(max_distance /
                                                        max_exact) * (num_buckets - max_exact)
        ).long()
        val_if_large = torch.min(
            val_if_large, torch.full_like(val_if_large, num_buckets - 1))
        ret += torch.where(is_small, n, val_if_large)
        return ret

    def forward(self, n, device):
        q_pos = torch.arange(n, dtype=torch.long, device=device)
        k_pos = torch.arange(n, dtype=torch.long, device=device)
        rel_pos = rearrange(k_pos, 'j -> 1 j') - rearrange(q_pos, 'i -> i 1')
        rp_bucket = self._relative_position_bucket(
            rel_pos, num_buckets=self.num_buckets, max_distance=self.max_distance)
        values = self.relative_attention_bias(rp_bucket)
        return rearrange(values, 'i j h -> h i j')

class EMA():
    def __init__(self, beta):
        super().__init__()
        self.beta = beta

    def update_model_average(self, ma_model, current_model):
        for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()):
            old_weight, up_weight = ma_params.data, current_params.data
            ma_params.data = self.update_average(old_weight, up_weight)

    def update_average(self, old, new):
        if old is None:
            return new
        return old * self.beta + (1 - self.beta) * new


class Residual(nn.Module):
    def __init__(self, fn):
        super().__init__()
        self.fn = fn

    def forward(self, x, *args, **kwargs):
        return self.fn(x, *args, **kwargs) + x


class SinusoidalPosEmb(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim

    def forward(self, x):
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
        emb = x[:, None] * emb[None, :]
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb


def Upsample(dim):
    return nn.ConvTranspose3d(dim, dim, (1, 4, 4), (1, 2, 2), (0, 1, 1))


def Downsample(dim):
    return nn.Conv3d(dim, dim, (1, 4, 4), (1, 2, 2), (0, 1, 1))


class LayerNorm(nn.Module):
    def __init__(self, dim, eps=1e-5):
        super().__init__()
        self.eps = eps
        self.gamma = nn.Parameter(torch.ones(1, dim, 1, 1, 1))

    def forward(self, x):
        var = torch.var(x, dim=1, unbiased=False, keepdim=True)
        mean = torch.mean(x, dim=1, keepdim=True)
        return (x - mean) / (var + self.eps).sqrt() * self.gamma


class PreNorm(nn.Module):
    def __init__(self, dim, fn):
        super().__init__()
        self.fn = fn
        self.norm = LayerNorm(dim)

    def forward(self, x, **kwargs):
        x = self.norm(x)
        return self.fn(x, **kwargs)



class Block(nn.Module):
    def __init__(self, dim, dim_out, groups=8):
        super().__init__()
        self.proj = nn.Conv3d(dim, dim_out, (1, 3, 3), padding=(0, 1, 1))
        self.norm = nn.GroupNorm(groups, dim_out)
        self.act = nn.SiLU()

    def forward(self, x, scale_shift=None):
        x = self.proj(x)
        x = self.norm(x)
        if exists(scale_shift):
            scale, shift = scale_shift
            x = x * (scale + 1) + shift
        return self.act(x)


class ResnetBlock(nn.Module):
    def __init__(self, dim, dim_out, *, time_emb_dim=None, groups=8):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.SiLU(),
            nn.Linear(time_emb_dim, dim_out * 2)
        ) if exists(time_emb_dim) else None
        self.block1 = Block(dim, dim_out, groups=groups)
        self.block2 = Block(dim_out, dim_out, groups=groups)
        self.res_conv = nn.Conv3d(
            dim, dim_out, 1) if dim != dim_out else nn.Identity()

    def forward(self, x, time_emb=None):
        scale_shift = None
        if exists(self.mlp):
            assert exists(time_emb), 'time emb must be passed in'
            time_emb = self.mlp(time_emb)
            time_emb = rearrange(time_emb, 'b c -> b c 1 1 1')
            scale_shift = time_emb.chunk(2, dim=1)
        h = self.block1(x, scale_shift=scale_shift)
        h = self.block2(h)
        return h + self.res_conv(x)


class SpatialLinearAttention(nn.Module):
    def __init__(self, dim, heads=4, dim_head=32):
        super().__init__()
        self.scale = dim_head ** -0.5
        self.heads = heads
        hidden_dim = dim_head * heads
        self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
        self.to_out = nn.Conv2d(hidden_dim, dim, 1)

    def forward(self, x):
        b, c, f, h, w = x.shape
        x = rearrange(x, 'b c f h w -> (b f) c h w')
        qkv = self.to_qkv(x).chunk(3, dim=1)
        q, k, v = rearrange_many(
            qkv, 'b (h c) x y -> b h c (x y)', h=self.heads)
        q = q.softmax(dim=-2)
        k = k.softmax(dim=-1)
        q = q * self.scale
        context = torch.einsum('b h d n, b h e n -> b h d e', k, v)

        out = torch.einsum('b h d e, b h d n -> b h e n', context, q)
        out = rearrange(out, 'b h c (x y) -> b (h c) x y',
                        h=self.heads, x=h, y=w)
        out = self.to_out(out)
        return rearrange(out, '(b f) c h w -> b c f h w', b=b)


class EinopsToAndFrom(nn.Module):
    def __init__(self, from_einops, to_einops, fn):
        super().__init__()
        self.from_einops = from_einops
        self.to_einops = to_einops
        self.fn = fn

    def forward(self, x, **kwargs):
        shape = x.shape
        reconstitute_kwargs = dict(
            tuple(zip(self.from_einops.split(' '), shape)))
        x = rearrange(x, f'{self.from_einops} -> {self.to_einops}')
        x = self.fn(x, **kwargs)
        x = rearrange(
            x, f'{self.to_einops} -> {self.from_einops}', **reconstitute_kwargs)
        return x


class Attention(nn.Module):
    def __init__(
        self,
        dim,
        heads=4,
        dim_head=32,
        rotary_emb=None
    ):
        super().__init__()
        self.scale = dim_head ** -0.5
        self.heads = heads
        hidden_dim = dim_head * heads
        self.rotary_emb = rotary_emb
        self.to_qkv = nn.Linear(dim, hidden_dim * 3, bias=False)
        self.to_out = nn.Linear(hidden_dim, dim, bias=False)

    def forward(
        self,
        x,
        pos_bias=None,
        focus_present_mask=None
    ):
        n, device = x.shape[-2], x.device
        qkv = self.to_qkv(x).chunk(3, dim=-1)
        if exists(focus_present_mask) and focus_present_mask.all():
            values = qkv[-1]
            return self.to_out(values)
        q, k, v = rearrange_many(qkv, '... n (h d) -> ... h n d', h=self.heads)
        q = q * self.scale
        if exists(self.rotary_emb):
            q = self.rotary_emb.rotate_queries_or_keys(q)
            k = self.rotary_emb.rotate_queries_or_keys(k)
        sim = einsum('... h i d, ... h j d -> ... h i j', q, k)
        if exists(pos_bias):
            sim = sim + pos_bias

        if exists(focus_present_mask) and not (~focus_present_mask).all():
            attend_all_mask = torch.ones(
                (n, n), device=device, dtype=torch.bool)
            attend_self_mask = torch.eye(n, device=device, dtype=torch.bool)

            mask = torch.where(
                rearrange(focus_present_mask, 'b -> b 1 1 1 1'),
                rearrange(attend_self_mask, 'i j -> 1 1 1 i j'),
                rearrange(attend_all_mask, 'i j -> 1 1 1 i j'),
            )
            sim = sim.masked_fill(~mask, -torch.finfo(sim.dtype).max)
        sim = sim - sim.amax(dim=-1, keepdim=True).detach()
        attn = sim.softmax(dim=-1)
        out = einsum('... h i j, ... h j d -> ... h i d', attn, v)
        out = rearrange(out, '... h n d -> ... n (h d)')
        return self.to_out(out)


class Unet3D(nn.Module):
    def __init__(
        self,
        dim,
        cond_dim=None,
        out_dim=None,
        dim_mults=(1, 2, 4, 8),
        channels=3,
        attn_heads=8,
        attn_dim_head=32,
        use_bert_text_cond=False,
        init_dim=None,
        init_kernel_size=7,
        use_sparse_linear_attn=True,
        resnet_groups=8
    ):
        super().__init__()
        self.channels = channels
        rotary_emb = RotaryEmbedding(min(32, attn_dim_head))
        def temporal_attn(dim): return EinopsToAndFrom('b c f h w', 'b (h w) f c', Attention(
            dim, heads=attn_heads, dim_head=attn_dim_head, rotary_emb=rotary_emb))
        self.time_rel_pos_bias = RelativePositionBias(
            heads=attn_heads, max_distance=32)
        init_dim = default(init_dim, dim)
        assert is_odd(init_kernel_size)
        init_padding = init_kernel_size // 2
        self.init_conv = nn.Conv3d(channels, init_dim, (1, init_kernel_size,
                                   init_kernel_size), padding=(0, init_padding, init_padding))
        self.init_temporal_attn = Residual(
            PreNorm(init_dim, temporal_attn(init_dim)))
        dims = [init_dim, *map(lambda m: dim * m, dim_mults)]
        in_out = list(zip(dims[:-1], dims[1:]))
        time_dim = dim * 4
        self.time_mlp = nn.Sequential(
            SinusoidalPosEmb(dim),
            nn.Linear(dim, time_dim),
            nn.GELU(),
            nn.Linear(time_dim, time_dim)
        )
        self.has_cond = exists(cond_dim) or use_bert_text_cond
        cond_dim = BERT_MODEL_DIM if use_bert_text_cond else cond_dim
        self.null_cond_emb = nn.Parameter(
            torch.randn(1, cond_dim)) if self.has_cond else None
        cond_dim = time_dim + int(cond_dim or 0)
        self.downs = nn.ModuleList([])
        self.ups = nn.ModuleList([])
        num_resolutions = len(in_out)
        block_klass = partial(ResnetBlock, groups=resnet_groups)
        block_klass_cond = partial(block_klass, time_emb_dim=cond_dim)
        for ind, (dim_in, dim_out) in enumerate(in_out):
            is_last = ind >= (num_resolutions - 1)
            self.downs.append(nn.ModuleList([
                block_klass_cond(dim_in, dim_out),
                block_klass_cond(dim_out, dim_out),
                Residual(PreNorm(dim_out, SpatialLinearAttention(
                    dim_out, heads=attn_heads))) if use_sparse_linear_attn else nn.Identity(),
                Residual(PreNorm(dim_out, temporal_attn(dim_out))),
                Downsample(dim_out) if not is_last else nn.Identity()
            ]))
        mid_dim = dims[-1]
        self.mid_block1 = block_klass_cond(mid_dim, mid_dim)
        spatial_attn = EinopsToAndFrom(
            'b c f h w', 'b f (h w) c', Attention(mid_dim, heads=attn_heads))
        self.mid_spatial_attn = Residual(PreNorm(mid_dim, spatial_attn))
        self.mid_temporal_attn = Residual(
            PreNorm(mid_dim, temporal_attn(mid_dim)))
        self.mid_block2 = block_klass_cond(mid_dim, mid_dim)
        for ind, (dim_in, dim_out) in enumerate(reversed(in_out)):
            is_last = ind >= (num_resolutions - 1)
            self.ups.append(nn.ModuleList([
                block_klass_cond(dim_out * 2, dim_in),
                block_klass_cond(dim_in, dim_in),
                Residual(PreNorm(dim_in, SpatialLinearAttention(
                    dim_in, heads=attn_heads))) if use_sparse_linear_attn else nn.Identity(),
                Residual(PreNorm(dim_in, temporal_attn(dim_in))),
                Upsample(dim_in) if not is_last else nn.Identity()
            ]))
        out_dim = default(out_dim, channels)
        self.final_conv = nn.Sequential(
            block_klass(dim * 2, dim),
            nn.Conv3d(dim, out_dim, 1)
        )

    def forward_with_cond_scale(
        self,
        *args,
        cond_scale=2.,
        **kwargs
    ): 
        logits = self.forward(*args, null_cond_prob=0., **kwargs)
        if cond_scale == 1 or not self.has_cond:
            return logits
        null_logits = self.forward(*args, null_cond_prob=1., **kwargs)
        return null_logits + (logits - null_logits) * cond_scale

    def forward(
        self,
        x,
        time,
        cond=None,
        null_cond_prob=0.,
        focus_present_mask=None,
        prob_focus_present=0.
    ):
        if cond is None:                    
            cond = torch.zeros((1, 16))
            cond[0, -1] = 1.0
        assert not (self.has_cond and not exists(cond)
                    ), 'cond must be passed in if cond_dim specified'
        batch, device = x.shape[0], x.device
        focus_present_mask = default(focus_present_mask, lambda: prob_mask_like(
            (batch,), prob_focus_present, device=device))
        time_rel_pos_bias = self.time_rel_pos_bias(x.shape[2], device=x.device)
        x = self.init_conv(x)
        r = x.clone()
        x = self.init_temporal_attn(x, pos_bias=time_rel_pos_bias)
        t = self.time_mlp(time) if exists(self.time_mlp) else None
        if self.has_cond:
            batch, device = x.shape[0], x.device
            mask = prob_mask_like((batch,), null_cond_prob, device=device)
            cond = cond.to(device)
            cond = torch.where(rearrange(mask, 'b -> b 1'),
                               self.null_cond_emb, cond)

            t = torch.cat((t, cond), dim=-1)
        h = []
        for block1, block2, spatial_attn, temporal_attn, downsample in self.downs:
            x = block1(x, t)
            x = block2(x, t)
            x = spatial_attn(x)
            x = temporal_attn(x, pos_bias=time_rel_pos_bias,
                              focus_present_mask=focus_present_mask)
            h.append(x)
            x = downsample(x)
        x = self.mid_block1(x, t)
        x = self.mid_spatial_attn(x)
        x = self.mid_temporal_attn(
            x, pos_bias=time_rel_pos_bias, focus_present_mask=focus_present_mask)
        x = self.mid_block2(x, t)
        for block1, block2, spatial_attn, temporal_attn, upsample in self.ups:
            x = torch.cat((x, h.pop()), dim=1)
            x = block1(x, t)
            x = block2(x, t)
            x = spatial_attn(x)
            x = temporal_attn(x, pos_bias=time_rel_pos_bias,
                              focus_present_mask=focus_present_mask)
            x = upsample(x)

        x = torch.cat((x, r), dim=1)
        return self.final_conv(x)



def extract(a, t, x_shape):
    b, *_ = t.shape
    out = a.gather(-1, t)
    return out.reshape(b, *((1,) * (len(x_shape) - 1)))


def cosine_beta_schedule(timesteps, s=0.008):

    steps = timesteps + 1
    x = torch.linspace(0, timesteps, steps, dtype=torch.float64)
    alphas_cumprod = torch.cos(
        ((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
    alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
    betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
    return torch.clip(betas, 0, 0.9999)


class GaussianDiffusion_Nolatent(nn.Module):
    def __init__(
        self,
        denoise_fn,
        *,
        image_size,
        num_frames,
        text_use_bert_cls=False,
        channels=2,
        timesteps=1000,
        loss_type='l1',
        use_dynamic_thres=False, 
        dynamic_thres_percentile=0.9,
        device=None,
        use_guide=True,
        # vqgan_ckpt=None,
    ):
        super().__init__()
        self.channels = channels
        self.image_size = image_size
        self.num_frames = num_frames
        self.denoise_fn = denoise_fn
        # if vqgan_ckpt:
        #     self.vqgan = VQGAN.load_from_checkpoint(vqgan_ckpt).cuda()
        #     self.vqgan.eval()
        # else:
        #     self.vqgan = None
        self.device=device
        betas = cosine_beta_schedule(timesteps)
        alphas = 1. - betas
        alphas_cumprod = torch.cumprod(alphas, axis=0)
        alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.)
        timesteps, = betas.shape
        self.num_timesteps = int(timesteps)
        print("timesteps : ", timesteps)
        self.loss_type = loss_type
        self.use_guide = use_guide


        def register_buffer(name, val): return self.register_buffer(
            name, val.to(torch.float32))
        register_buffer('betas', betas)
        register_buffer('alphas_cumprod', alphas_cumprod)
        register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
        register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
        register_buffer('sqrt_one_minus_alphas_cumprod',
                        torch.sqrt(1. - alphas_cumprod))
        register_buffer('log_one_minus_alphas_cumprod',
                        torch.log(1. - alphas_cumprod))
        register_buffer('sqrt_recip_alphas_cumprod',
                        torch.sqrt(1. / alphas_cumprod))
        register_buffer('sqrt_recipm1_alphas_cumprod',
                        torch.sqrt(1. / alphas_cumprod - 1))


        posterior_variance = betas * \
            (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)
        register_buffer('posterior_variance', posterior_variance)

        register_buffer('posterior_log_variance_clipped',
                        torch.log(posterior_variance.clamp(min=1e-20)))
        register_buffer('posterior_mean_coef1', betas *
                        torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))
        register_buffer('posterior_mean_coef2', (1. - alphas_cumprod_prev)
                        * torch.sqrt(alphas) / (1. - alphas_cumprod))


        self.text_use_bert_cls = text_use_bert_cls


        self.use_dynamic_thres = use_dynamic_thres
        self.dynamic_thres_percentile = dynamic_thres_percentile

    # 计算扩散过程中的均值和方差,用于定义 q(x_t|x_0) 分布
    # x_start:原始数据 x_0 
    def q_mean_variance(self, x_start, t):
        mean = extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
        variance = extract(1. - self.alphas_cumprod, t, x_start.shape)
        log_variance = extract(
            self.log_one_minus_alphas_cumprod, t, x_start.shape)
        return mean, variance, log_variance
    
    # 从带噪声的样本 x_t 和噪声 epsilon 预测 原始数据 x_0
    # 输出:预测的原始数据 x_0
    def predict_start_from_noise(self, x_t, t, noise):
        return (
            extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
            extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
        )

    # 计算后验分布 q(x_{t-1}|x_t, x_0) 的均值和方差
    def q_posterior(self, x_start, x_t, t):
        posterior_mean = (
            extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
            extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
        )
        posterior_variance = extract(self.posterior_variance, t, x_t.shape)
        posterior_log_variance_clipped = extract(
            self.posterior_log_variance_clipped, t, x_t.shape)
        return posterior_mean, posterior_variance, posterior_log_variance_clipped

    # 根据去噪函数的预测,计算后验分布 p(x_{t-1}|x_t)
    def p_mean_variance(self, x, t, clip_denoised: bool, cond=None, cond_scale=1.):
        if isinstance(self.denoise_fn, torch.nn.DataParallel):
            noise = self.denoise_fn.module.forward_with_cond_scale(x, t, cond=cond, cond_scale=cond_scale)
        else:
            noise = self.denoise_fn.forward_with_cond_scale(x, t, cond=cond, cond_scale=cond_scale)
        x_recon = self.predict_start_from_noise(
            x, t=t, noise=noise)
        if clip_denoised:
            s = 1.
            if self.use_dynamic_thres:
                s = torch.quantile(
                    rearrange(x_recon, 'b ... -> b (...)').abs(),
                    self.dynamic_thres_percentile,
                    dim=-1
                )
                s.clamp_(min=1.)
                s = s.view(-1, *((1,) * (x_recon.ndim - 1)))

            x_recon = x_recon.clamp(-s, s) / s
        model_mean, posterior_variance, posterior_log_variance = self.q_posterior(
            x_start=x_recon, x_t=x, t=t)
        return model_mean, posterior_variance, posterior_log_variance


    # 从后验分布 p(x_{t-1}|x_t) 采样 x_{t-1}
    #@torch.inference_mode()
    def p_sample_v2(self, x, t, cond=None, cond_scale=1., clip_denoised=True):
        b, *_ = x.shape
        model_mean, _, model_log_variance = self.p_mean_variance(
            x=x, t=t, clip_denoised=clip_denoised, cond=cond, cond_scale=cond_scale)
        noise = torch.randn_like(x)
        nonzero_mask = (1 - (t == 0).float()).reshape(b,
                                                      *((1,) * (len(x.shape) - 1)))
        return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
    
    @torch.inference_mode()
    def p_sample(self, x, t, cond=None, cond_scale=1., clip_denoised=True):
        b, *_ = x.shape
        model_mean, _, model_log_variance = self.p_mean_variance(
            x=x, t=t, clip_denoised=clip_denoised, cond=cond, cond_scale=cond_scale)
        noise = torch.randn_like(x)
        nonzero_mask = (1 - (t == 0).float()).reshape(b,
                                                      *((1,) * (len(x.shape) - 1)))
        return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
    
    # @torch.inference_mode()
    def p_sample_loop_v2(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None):
        b = shape_image[0]
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        input = torch.cat((img, mask), dim=1)
        real_img = image
        input_guided = input
        N = 2 
        R = 3
        B = 1
        recurrent = [0] * self.num_timesteps
        for i in range(self.num_timesteps):
            if i % R == 0:
                recurrent[i] = R
        i = self.num_timesteps - 1
        while i >= 0:
            # print(i)
            if self.use_guide is not None and i < 250:
            # if self.use_guide is not None:
                input_with_grad = input_guided.clone().detach().requires_grad_(True)
                loss = 0
                t = torch.full((b,), i, dtype=torch.long, device=device)
                real_noisy_image = self.q_sample(x_start=real_img, t=t)
                for _ in range(N):
                    input_sampled = input_with_grad
                    input_sampled = self.p_sample_v2(input_sampled, torch.full(
                        (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
                    # print(torch.split(input_sampled, 1, dim=1).shape)
                    loss+=F.mse_loss(torch.split(input_sampled, 1, dim=1)[0], real_noisy_image)
                loss /= N
                loss.backward()
                update = torch.clamp(input_with_grad.grad * 10000.0, -1.5, 1.5)
                # input_guided= input_guided- update
                # print(update[:, 0, :, :, :])
                input_guided[:, 0, :, :, :] = input_guided[:, 0, :, :, :] - update[:, 0, :, :, :]
                # input_guided[:, 1:6, :, :, :] = input_guided[:, 1:6, :, :, :] - 0.01*update[:, 0, :, :, :]
                input_with_grad.grad.zero_()
            
            # else:
            #     input_guided = input

            with torch.no_grad():
                    # input = self.p_sample_v2(input, torch.full(
                    # (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
                    input_guided = self.p_sample_v2(input_guided, torch.full(
                    (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)

            # if i % R == 0 and recurrent[i]!=0 :
            #     recurrent[i] -= 1
            #     with torch.no_grad():
            #         for _ in range(B):
            #             input_guided=self.q_sample_one_step(input_guided, torch.full((b,), i, device=device, dtype=torch.long))
            #             i += 1
            
            i -= 1
        
        return input_guided 
    
    @torch.inference_mode()
    def p_sample_loop(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None):
        b = shape_image[0]
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        input = torch.cat((img, mask), dim=1)
        real_img = image
        R = 2
        recurrent = [0] * self.num_timesteps
        for i in range(self.num_timesteps):
            if i % R == 0:
                recurrent[i] = R
        
        i = self.num_timesteps - 1
        while i >= 0:
            # print(i)
            # if self.use_guide is not None and i < 250:
            # if self.use_guide is not None and i > 200:
            if self.use_guide is not None:
                t = torch.full((b,), i, dtype=torch.long, device=device)
                real_noisy_image = self.q_sample(x_start=real_img, t=t)
                input[:, 0, :, :, :] = real_noisy_image[:, 0, :, :, :].clone()
            # with torch.no_grad():
                input = self.p_sample(input, torch.full(
                (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)

            # if i % 5 == 0 and recurrent[i]!=0 :
            #     recurrent[i] -= 1
            #     with torch.no_grad():
            #         for _ in range(5):
            #             input=self.q_sample_one_step(input, torch.full((b,), i, device=device, dtype=torch.long))
            #             i += 1
            
            i -= 1
        
        return input

    @torch.inference_mode()
    def p_sample_loop_v4(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None):
        b = shape_image[0]
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        input = torch.cat((img, mask), dim=1)
        real_img = image
        R = 2
        recurrent = [0] * self.num_timesteps
        for i in range(self.num_timesteps):
            if i % R == 0:
                recurrent[i] = R
        
        i = self.num_timesteps - 1
        while i >= 0:
            print(i)
            # if self.use_guide is not None and i < 250:
            if self.use_guide is not None and i > 100:
            # if self.use_guide is not None:
                t = torch.full((b,), i, dtype=torch.long, device=device)
                real_noisy_image = self.q_sample(x_start=real_img, t=t)
                input[:, 0, :, :, :] = real_noisy_image[:, 0, :, :, :].clone()
            # with torch.no_grad():
                input = self.p_sample(input, torch.full(
                (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
            else:
                input = self.p_sample(input, torch.full(
                (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)

            # if i % 5 == 0 and recurrent[i]!=0 :
            #     recurrent[i] -= 1
            #     with torch.no_grad():
            #         for _ in range(5):
            #             input=self.q_sample_one_step(input, torch.full((b,), i, device=device, dtype=torch.long))
            #             i += 1
            
            i -= 1
        
        return input
    

    @torch.inference_mode()
    def p_sample_loop_v3(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None):
        b = shape_image[0]
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        input = torch.cat((img, mask), dim=1)

        i = self.num_timesteps - 1
        while i >= 0:
            input = self.p_sample(input, torch.full(
            (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
            i -= 1
        
        return input
    
    @torch.inference_mode()
    def p_sample_loop_v3_image_only(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None):
        b = shape_image[0]
        img = torch.randn(shape_image, device=device)
        input = img

        i = self.num_timesteps - 1
        while i >= 0:
            input = self.p_sample(input, torch.full(
            (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
            i -= 1
        
        return input
        # for i in reversed(range(0, self.num_timesteps)):
            
        #     t = torch.full((b,), i, dtype=torch.long, device=device)
        #     real_noisy_image = self.q_sample(x_start=real_img, t=t)
        #     input[:, 0, :, :, :] = real_noisy_image[:, 0, :, :, :].clone()


        #     with torch.no_grad():
        #         input = self.p_sample_v2(input, torch.full(
        #         (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
            
        # return input


    # @torch.inference_mode()
    # def p_sample_loop(self, shape, cond=None, cond_scale=1., device=None):
    #     b = shape[0]
    #     img = torch.randn(shape, device=device)
    #     mask = torch.randn(shape, device=device)
    #     input = torch.cat((img, mask), dim=1)
    #     for i in tqdm(reversed(range(0, self.num_timesteps)), desc='sampling loop time step', total=self.num_timesteps):
    #         input = self.p_sample(input, torch.full(
    #             (b,), i, device=device, dtype=torch.long), cond=cond, cond_scale=cond_scale)
    #     return input
    
    # 向原始数据 x_0 添加噪声,生成 x_t 
    def q_sample(self, x_start, t, noise=None):
        noise = default(noise, lambda: torch.randn_like(x_start))
        return (
            extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
            extract(self.sqrt_one_minus_alphas_cumprod,
                    t, x_start.shape) * noise
        )

    # 对当前样本 x_{t-1} 添加一步噪声,生成 x_t
    # t 是目标时间步
    def q_sample_one_step(self, x_prev, t):
        beta_t = extract(self.betas, t, x_prev.shape)
        alpha_t = 1.0 - beta_t
        sqrt_alpha_t = torch.sqrt(alpha_t)
        sqrt_beta_t = torch.sqrt(beta_t)
        noise = torch.randn_like(x_prev)
        x_t = sqrt_alpha_t * x_prev + sqrt_beta_t * noise
        return x_t
    
    def p_losses(self, x_start, t, mask_start, cond=None, noise_x=None, noise_m=None, **kwargs):
        device = x_start.device
        x_start = x_start.to(device=device, dtype=torch.float32)

        mask_start = mask_start.to(device=device, dtype=torch.float32)

        noise_x = default(noise_x, lambda: torch.randn_like(x_start))
        noise_m = default(noise_m, lambda: torch.randn_like(mask_start))

        x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise_x)
        m_noisy = self.q_sample(x_start=mask_start, t=t, noise=noise_m)
        
        input = torch.cat((x_noisy, m_noisy), dim=1)

        if is_list_str(cond):
            cond = bert_embed(
                tokenize(cond), return_cls_repr=self.text_use_bert_cls)
            cond = cond.to(device)

        recon = self.denoise_fn(**dict(x=input, time=t, cond=cond, **kwargs))
        # print(recon.size())


        
        x_recon = recon[:,0,:,:,:]
        x_recon = x_recon.unsqueeze(1)
        #x_recon = x_recon.squeeze(1)
        m_recon = recon[:,1:(recon.size()[1]),:,:,:]
        #x_recon, m_recon = torch.split(recon, 1, dim=1)
        m_recon = m_recon.squeeze(1)
        # noise_x = noise_x.squeeze(1)
        noise_m = noise_m.squeeze(1)
        # print(noise_x.size())
        # print(x_recon.size())
        # print(noise_m.size())
        # print(m_recon.size())
        # print(m_recon.shape)
        # print(noise_m.shape)
        if self.loss_type == 'l1':
            loss = F.l1_loss(noise_x, x_recon) + F.l1_loss(noise_m, m_recon)
        elif self.loss_type == 'l2':
            loss = F.mse_loss(noise_x, x_recon) + F.mse_loss(noise_m, m_recon)
        else:
            raise NotImplementedError()
        return loss
    
    def p_losses_image_only(self, x_start, t, cond=None, noise_x=None,**kwargs):
        device = x_start.device
        x_start = x_start.to(device=device, dtype=torch.float32)

        noise_x = default(noise_x, lambda: torch.randn_like(x_start))

        x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise_x)
        
        input = x_noisy

        if is_list_str(cond):
            cond = bert_embed(
                tokenize(cond), return_cls_repr=self.text_use_bert_cls)
            cond = cond.to(device)

        recon = self.denoise_fn(**dict(x=input, time=t, cond=cond, **kwargs))

        x_recon = recon
        # x_recon = recon[:,0,:,:,:]
        #x_recon = x_recon.squeeze(1)
        #x_recon, m_recon = torch.split(recon, 1, dim=1)
        # noise_x = noise_x.squeeze(1)
        # print(m_recon.shape)
        # print(noise_m.shape)
        if self.loss_type == 'l1':
            loss = F.l1_loss(noise_x, x_recon)
        elif self.loss_type == 'l2':
            loss = F.mse_loss(noise_x, x_recon)
        else:
            raise NotImplementedError()
        return loss

    def forward(self, x, mask, *args, **kwargs):
        b, device, img_size, = x.shape[0], x.device, self.image_size
        # check_shape(x, 'b c f h w', c=self.channels,
        #             f=self.num_frames, h=img_size, w=img_size)
        t = torch.randint(0, self.num_timesteps, (b,), device=device).long().to(self.device)
        return self.p_losses(**dict(x_start=x, t=t, mask_start=mask, *args, **kwargs))
    
    # def forward(self, x, mask, *args, **kwargs):
    #     b, device, img_size, = x.shape[0], x.device, self.image_size
    #     # check_shape(x, 'b c f h w', c=self.channels,
    #     #             f=self.num_frames, h=img_size, w=img_size)
    #     t = torch.randint(0, self.num_timesteps, (b,), device=device).long().to(self.device)
    #     return self.p_losses_image_only(**dict(x_start=x, t=t, *args, **kwargs))

    # @torch.inference_mode()
    def p_sample_loop_guidance(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, image=None, degrade_mask=None, delta=1.5):
        if degrade_mask is None: # default is all 1
            degrade_mask = torch.ones(shape_image, device=device)
        degrade_mask = degrade_mask.to(device=device, dtype=torch.float32)
        device = self.betas.device
        b = shape_image[0]
        init_noise = torch.randn_like(image)
        step_noise_list = []
        for step in range(self.num_timesteps):
            t = torch.full((image.shape[0],), step, device=device, dtype=torch.long)
            step_noise = self.q_sample(image, t, noise=init_noise)
            step_noise_list.append(step_noise)
        img_noisy = torch.stack(step_noise_list)  # [T, B, C, D, H, W]
        
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        pair = torch.cat((img, mask), dim=1)

        TCOUNT = 2 # 2
        RSTEP = 1  # 10
        GRAD_STEP = 3 # 7
        print(f'TCOUNT: {TCOUNT}, RSTEP: {RSTEP}, GRAD_STEP: {GRAD_STEP}')
        recurrent = [0] * self.num_timesteps
        for i in range(self.num_timesteps):
            if i % RSTEP == 0:
                recurrent[i] = TCOUNT
        i = self.num_timesteps - 1

        print('degrade_mask_sum_check:', degrade_mask.sum().item())
        while i >= 0:
            # real_noisy_image = self.q_sample(x_start=image, t=t)
            pair[:, :1] = img_noisy[i] * degrade_mask + pair[:, :1] * (1 - degrade_mask)
            # pair[:, :1] = img_noisy[i]
            pair = pair.clone().detach()
            for g in range(GRAD_STEP):
                # break
                if i > 150:
                    break
                with torch.enable_grad():
                    pair_with_grad = pair.detach().clone().requires_grad_(True)
                    t = torch.full((b,), i, device=device, dtype=torch.long)
                    self.loss_type = 'l1'
                    loss = self.p_losses_guidance(pair_with_grad, t, init_noise, degrade_mask=degrade_mask)
                    print('t:', i, 'g', g, 'loss:', loss.item())
                    grad = torch.autograd.grad(loss, pair_with_grad)[0]
                    grad[:, :1] = grad[:, :1] * (1 - degrade_mask) 
                    grad_norm = grad.flatten(start_dim=1).norm( dim=1, keepdim=True).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
                    grad = grad / (grad_norm + 1e-8)
                    pair = pair - grad * delta

            t = torch.full((b,), i, device=device, dtype=torch.long)
            pair = self.p_sample(pair, t, cond=cond, cond_scale=cond_scale).clone()

            # if recurrent[i] > 0 and i % RSTEP == 0:
            #     recurrent[i] -= 1
            #     for _ in range(RSTEP):
            #         with torch.no_grad():
            #             t = torch.full((b,), i, device=device, dtype=torch.long)
            #             pair = self.q_sample_one_step(pair, t)
            #         i += 1
            #         if i >= self.num_timesteps:
            #             break
            
            
            
            i -= 1

        return pair


    def p_losses_guidance(self, pair_noisy, t, noise, cond=None, degrade_mask=None, **kwargs):
        device = pair_noisy.device

        if is_list_str(cond):
            cond = bert_embed(
                tokenize(cond), return_cls_repr=self.text_use_bert_cls)
            cond = cond.to(device)

        x_recon = self.denoise_fn(pair_noisy, t, cond=cond, **kwargs)[:, :1]

        if degrade_mask is not None:
            x_recon = x_recon * degrade_mask
            noise = noise * degrade_mask
        
        if self.loss_type == 'l1':
            loss = F.l1_loss(noise, x_recon, reduction='sum')
        elif self.loss_type == 'l2':
            loss = F.mse_loss(noise, x_recon, reduction='sum')
        else:
            raise NotImplementedError()

        if degrade_mask is not None:
            loss = loss / degrade_mask.sum()
        else:
            loss = loss / noise.numel()

        return loss


    def p_sample_loop_universal_guidance(
        self,
        shape_image,
        shape_mask,
        cond=None,
        cond_scale=1.,
        device=None,
        image=None,
        degrade_mask=None,
        num_guidance_steps=3,
        guidance_scale=1.5,
        guidance_start_t=-1,
        recurrent_steps=1,
        loss_type='l1',
        use_ddim=True,
        ddim_steps=50,
        ddim_eta=0.0,
        guidance_strategy='equal_distance',
        proc=True,
    ):
        """
        Universal guidance for continuous diffusion model supporting both DDPM and DDIM.
        
        This function performs gradient-based guidance to match the degraded region of the
        predicted clean image with the real clean image.
        
        Args:
            shape_image: Shape of image to generate
            shape_mask: Shape of mask to generate
            cond: Optional conditioning
            cond_scale: Conditioning scale
            device: Device to use
            image: Real clean image (ground truth for degraded region)
            degrade_mask: Binary mask indicating degraded region (1=degraded, 0=clean)
            num_guidance_steps: Number of gradient descent iterations per guided timestep
            guidance_scale: Step size for gradient descent (delta)
            guidance_start_t: Number of timesteps/steps to apply guidance
            recurrent_steps: Number of denoise-renoise cycles per timestep (DDPM and DDIM)
            loss_type: 'l1' or 'l2' for guidance loss
            use_ddim: Whether to use DDIM sampling instead of DDPM
            ddim_steps: Number of steps for DDIM sampling
            ddim_eta: Stochasticity parameter for DDIM (0=deterministic, 1=DDPM-like)
            guidance_strategy: 'last_n' or 'equal_distance' - how to distribute guidance steps
            proc: Whether to show progress bar
            
        Returns:
            Generated pair (image + mask concatenated)
        """
        if degrade_mask is None:
            degrade_mask = torch.ones(shape_image, device=device)
        degrade_mask = degrade_mask.to(device=device, dtype=torch.float32)
        device = self.betas.device
        b = shape_image[0]
        
        # Pre-compute noisy versions of input image at all timesteps (for replacement strategy)
        init_noise = torch.randn_like(image)
        step_noise_list = []
        for step in range(self.num_timesteps):
            t = torch.full((image.shape[0],), step, device=device, dtype=torch.long)
            step_noise = self.q_sample(image, t, noise=init_noise)
            step_noise_list.append(step_noise)
        img_noisy = torch.stack(step_noise_list)  # [T, B, C, D, H, W]
        
        # Initialize random samples
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        pair = torch.cat((img, mask), dim=1)
        
        if use_ddim:
            # DDIM sampling with universal guidance
            return self._ddim_sample_universal_guidance(
                pair=pair,
                img_noisy=img_noisy,
                real_image=image,
                degrade_mask=degrade_mask,
                cond=cond,
                cond_scale=cond_scale,
                num_guidance_steps=num_guidance_steps,
                guidance_scale=guidance_scale,
                guidance_start_t=guidance_start_t,
                recurrent_steps=recurrent_steps,
                loss_type=loss_type,
                ddim_steps=ddim_steps,
                ddim_eta=ddim_eta,
                guidance_strategy=guidance_strategy,
                proc=proc,
            )
        else:
            # DDPM sampling with universal guidance
            return self._ddpm_sample_universal_guidance(
                pair=pair,
                img_noisy=img_noisy,
                real_image=image,
                degrade_mask=degrade_mask,
                cond=cond,
                cond_scale=cond_scale,
                num_guidance_steps=num_guidance_steps,
                guidance_scale=guidance_scale,
                guidance_start_t=guidance_start_t,
                recurrent_steps=recurrent_steps,
                loss_type=loss_type,
                guidance_strategy=guidance_strategy,
                proc=proc,
            )


    def _ddpm_sample_universal_guidance(
        self,
        pair,
        img_noisy,
        real_image,
        degrade_mask,
        cond,
        cond_scale,
        num_guidance_steps,
        guidance_scale,
        guidance_start_t,
        recurrent_steps,
        loss_type,
        guidance_strategy,
        proc,
    ):
        """DDPM sampling with universal guidance."""
        device = pair.device
        b = pair.shape[0]
        
        # Build guidance schedule
        guidance_schedule = self._build_guidance_schedule(
            total_steps=self.num_timesteps,
            num_guidance=guidance_start_t,
            strategy=guidance_strategy,
        )
        
        print(f'DDPM Universal Guidance Config:')
        print(f'  num_guidance_steps: {num_guidance_steps}')
        print(f'  recurrent_steps: {recurrent_steps}')
        print(f'  guidance_scale: {guidance_scale}')
        print(f'  guidance_start_t: {guidance_start_t}')
        print(f'  guidance_strategy: {guidance_strategy}')
        print(f'  loss_type: {loss_type}')
        print(f'  degrade_mask sum: {degrade_mask.sum().item()}')
        print(f'  guidance at {len(guidance_schedule)} timesteps: {sorted(list(guidance_schedule))[:10]}{"..." if len(guidance_schedule) > 10 else ""}')
        
        iterator = range(self.num_timesteps - 1, -1, -1)
        if proc:
            from tqdm import tqdm
            iterator = tqdm(iterator, desc='DDPM + Universal Guidance', leave=False)
        
        for i in iterator:
            t = torch.full((b,), i, device=device, dtype=torch.long)
            
            # Replace degraded region with noisy ground truth
            pair[:, :1] = img_noisy[i] * degrade_mask + pair[:, :1] * (1 - degrade_mask)
            
            # Apply guidance if this timestep is in the schedule
            if i in guidance_schedule:
                pair = pair.clone().detach()
                
                for recurrent_idx in range(recurrent_steps):
                    # Gradient descent iterations
                    for g in range(num_guidance_steps):
                        with torch.enable_grad():
                            pair_with_grad = pair.detach().clone().requires_grad_(True)
                            
                            # Compute guidance loss
                            loss = self._compute_guidance_loss(
                                pair_with_grad,
                                t,
                                real_image,
                                degrade_mask,
                                loss_type,
                                cond,
                            )
                            
                            if (i % 10 == 0 or i < 3) and g == 0 and recurrent_idx == 0:
                                print(f'  t={i}: loss={loss.item():.6f}')
                            
                            # Compute gradient
                            grad = torch.autograd.grad(loss, pair_with_grad)[0]
                            
                            # Only apply gradient to non-degraded region of image channel
                            grad[:, :1] = grad[:, :1] * (1 - degrade_mask)
                            
                            # Normalize gradient
                            grad_norm = grad.flatten(start_dim=1).norm(dim=1, keepdim=True)
                            grad_norm = grad_norm.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
                            grad = grad / (grad_norm + 1e-8)
                            
                            # Update pair
                            pair = pair - grad * guidance_scale
                    
                    # Recurrent refinement: denoise one step and add noise back
                    # (Only if not the last recurrent step)
                    if recurrent_idx < recurrent_steps - 1 and i > 0:
                        with torch.no_grad():
                            # Denoise one step
                            pair = self.p_sample(pair, t, cond=cond, cond_scale=cond_scale)
                            
                            # Add noise back: x_{t-1} → x_t
                            pair = self.q_sample_one_step(pair, t)
            
            # Standard denoising step
            with torch.no_grad():
                pair = self.p_sample(pair, t, cond=cond, cond_scale=cond_scale).clone()
        
        return pair


    def _ddim_sample_universal_guidance(
        self,
        pair,
        img_noisy,
        real_image,
        degrade_mask,
        cond,
        cond_scale,
        num_guidance_steps,
        guidance_scale,
        guidance_start_t,
        recurrent_steps,
        loss_type,
        ddim_steps,
        ddim_eta,
        guidance_strategy,
        proc,
    ):
        """DDIM sampling with universal guidance."""
        device = pair.device
        b = pair.shape[0]
        
        # Build DDIM timestep schedule
        step = self.num_timesteps // ddim_steps
        timesteps = torch.arange(0, self.num_timesteps, step, device=device).long()
        timesteps = torch.flip(timesteps, dims=[0])  # Reverse for denoising
        
        # Build guidance schedule based on DDIM steps
        guidance_schedule = self._build_guidance_schedule(
            total_steps=len(timesteps),
            num_guidance=guidance_start_t,
            strategy=guidance_strategy,
        )
        
        print(f'DDIM Universal Guidance Config:')
        print(f'  ddim_steps: {ddim_steps}')
        print(f'  num_guidance_steps: {num_guidance_steps}')
        print(f'  recurrent_steps: {recurrent_steps}')
        print(f'  guidance_scale: {guidance_scale}')
        print(f'  guidance_start_t: {guidance_start_t}')
        print(f'  guidance_strategy: {guidance_strategy}')
        print(f'  ddim_eta: {ddim_eta}')
        print(f'  loss_type: {loss_type}')
        print(f'  degrade_mask sum: {degrade_mask.sum().item()}')
        print(f'  guidance at {len(guidance_schedule)} DDIM steps (indices): {sorted(list(guidance_schedule))[:10]}{"..." if len(guidance_schedule) > 10 else ""}')
        
        iterator = enumerate(timesteps.tolist())
        if proc:
            from tqdm import tqdm
            iterator = enumerate(tqdm(timesteps.tolist(), desc='DDIM + Universal Guidance', leave=False))
        
        for idx, t_val in iterator:
            t = torch.full((b,), t_val, device=device, dtype=torch.long)
            
            # Determine next timestep
            if idx + 1 < len(timesteps):
                t_next = timesteps[idx + 1]
            else:
                t_next = torch.tensor(-1, device=device)
            
            # Replace degraded region with noisy ground truth before guidance
            pair[:, :1] = img_noisy[t_val] * degrade_mask + pair[:, :1] * (1 - degrade_mask)
            
            # Apply guidance if this DDIM step index is in the schedule
            if idx in guidance_schedule:
                pair = pair.clone().detach()
                
                for recurrent_idx in range(recurrent_steps):
                    # Gradient descent iterations
                    for g in range(num_guidance_steps):
                        with torch.enable_grad():
                            pair_with_grad = pair.detach().clone().requires_grad_(True)
                            
                            # Compute guidance loss
                            loss = self._compute_guidance_loss(
                                pair_with_grad,
                                t,
                                real_image,
                                degrade_mask,
                                loss_type,
                                cond,
                            )
                            
                            if (idx % 5 == 0 or idx < 3) and g == 0 and recurrent_idx == 0:
                                print(f'  DDIM step {idx} (t={t_val}): loss={loss.item():.6f}')
                            
                            # Compute gradient
                            grad = torch.autograd.grad(loss, pair_with_grad)[0]
                            
                            # Only apply gradient to non-degraded region of image channel
                            grad[:, :1] = grad[:, :1] * (1 - degrade_mask)
                            
                            # Normalize gradient
                            grad_norm = grad.flatten(start_dim=1).norm(dim=1, keepdim=True)
                            grad_norm = grad_norm.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
                            grad = grad / (grad_norm + 1e-8)
                            
                            # Update pair
                            pair = pair - grad * guidance_scale
                    
                    # Recurrent refinement: DDIM step and add noise back
                    # (Only if not the last recurrent step and not the final timestep)
                    if recurrent_idx < recurrent_steps - 1 and t_next >= 0:
                        with torch.no_grad():
                            # Apply one DDIM denoising step
                            pair_denoised = self._ddim_step(
                                pair,
                                t,
                                t_next,
                                cond=cond,
                                cond_scale=cond_scale,
                                eta=ddim_eta,
                            )
                            
                            # Re-noise back to current timestep t using DDIM forward process
                            # q(x_t | x_{t-1}) for DDIM: deterministically add noise back
                            alpha_t = extract(self.alphas_cumprod, t, pair.shape)
                            alpha_t_next = extract(self.alphas_cumprod, t_next.expand(pair.shape[0]), pair.shape)
                            
                            # Predict x0 from denoised sample at t_next
                            noise_pred = self.denoise_fn(pair_denoised, t_next.expand(b), cond=cond)[:, :pair.shape[1]]
                            x0_from_denoised = (pair_denoised - torch.sqrt(1 - alpha_t_next) * noise_pred) / torch.sqrt(alpha_t_next)
                            
                            # Re-noise to timestep t: x_t = sqrt(alpha_t) * x0 + sqrt(1-alpha_t) * noise
                            noise = torch.randn_like(pair)
                            pair = torch.sqrt(alpha_t) * x0_from_denoised + torch.sqrt(1 - alpha_t) * noise
            
            # Replace degraded region with noisy ground truth after guidance
            pair[:, :1] = img_noisy[t_val] * degrade_mask + pair[:, :1] * (1 - degrade_mask)
            
            # DDIM denoising step
            with torch.no_grad():
                pair = self._ddim_step(
                    pair,
                    t,
                    t_next,
                    cond=cond,
                    cond_scale=cond_scale,
                    eta=ddim_eta,
                )
        
        return pair


    def _compute_guidance_loss(
        self,
        pair_noisy,
        t,
        real_image,
        degrade_mask,
        loss_type,
        cond,
    ):
        """
        Compute guidance loss for universal guidance.
        
        The loss is the L1/L2 distance between:
        - degrade_mask * predicted clean image
        - degrade_mask * real clean image
        """
        device = pair_noisy.device
        
        # Predict noise from the noisy pair
        noise_pred = self.denoise_fn(pair_noisy, t, cond=cond)[:, :1]
        
        # Predict clean image (x_0) from noise prediction
        # x_0 = (x_t - sqrt(1-alpha_t) * noise) / sqrt(alpha_t)
        x0_pred = self.predict_start_from_noise(pair_noisy[:, :1], t, noise_pred)
        
        # Apply mask to both predicted and real clean images
        if degrade_mask is not None:
            x0_pred_masked = x0_pred * degrade_mask
            real_image_masked = real_image * degrade_mask
        else:
            x0_pred_masked = x0_pred
            real_image_masked = real_image
        
        # Compute loss between masked regions
        if loss_type == 'l1':
            loss = F.l1_loss(x0_pred_masked, real_image_masked, reduction='sum')
        elif loss_type == 'l2':
            loss = F.mse_loss(x0_pred_masked, real_image_masked, reduction='sum')
        else:
            raise NotImplementedError(f'Unknown loss type: {loss_type}')
        
        # Normalize by mask size
        if degrade_mask is not None:
            loss = loss / degrade_mask.sum().clamp(min=1.0)
        else:
            loss = loss / real_image_masked.numel()
        
        return loss


    def _ddim_step(self, x, t, t_next, cond=None, cond_scale=1., eta=0.0):
        """
        Single DDIM denoising step.
        
        Args:
            x: Current noisy sample
            t: Current timestep tensor
            t_next: Next timestep (scalar tensor or -1 for final step)
            cond: Optional conditioning
            cond_scale: Conditioning scale
            eta: Stochasticity parameter (0=deterministic, 1=DDPM-like)
        """
        # Predict noise
        noise_pred = self.denoise_fn(x, t, cond=cond)
        
        # Apply classifier-free guidance if cond_scale != 1
        if cond is not None and cond_scale != 1.:
            noise_pred_uncond = self.denoise_fn(x, t, cond=None)
            noise_pred = noise_pred_uncond + cond_scale * (noise_pred - noise_pred_uncond)
        
        # Extract coefficients
        alpha_t = extract(self.alphas_cumprod, t, x.shape)
        
        if t_next >= 0:
            alpha_t_next = extract(self.alphas_cumprod, t_next.expand(x.shape[0]), x.shape)
        else:
            alpha_t_next = torch.ones_like(alpha_t)
        
        # Predict x0
        pred_x0 = (x - torch.sqrt(1 - alpha_t) * noise_pred) / torch.sqrt(alpha_t)
        
        # Compute direction pointing to x_t
        sigma_t = eta * torch.sqrt((1 - alpha_t_next) / (1 - alpha_t) * (1 - alpha_t / alpha_t_next))
        
        # Compute x_{t-1}
        dir_xt = torch.sqrt(1 - alpha_t_next - sigma_t ** 2) * noise_pred
        
        if t_next >= 0:
            noise = torch.randn_like(x)
            x_next = torch.sqrt(alpha_t_next) * pred_x0 + dir_xt + sigma_t * noise
        else:
            x_next = torch.sqrt(alpha_t_next) * pred_x0 + dir_xt
        
        return x_next


    def _build_guidance_schedule(self, total_steps, num_guidance, strategy='last_n'):
        """
        Build a set of step indices where guidance should be applied.
        
        Args:
            total_steps: Total number of denoising steps
            num_guidance: Number of steps to apply guidance
            strategy: 'last_n' or 'equal_distance'
                - 'last_n': Apply guidance at the last N steps (smallest timesteps)
                - 'equal_distance': Distribute N guidance steps evenly across all steps
        
        Returns:
            Set of step indices where guidance should be applied
        """
        num_guidance = min(num_guidance, total_steps)
        
        if strategy == 'last_n':
            # For DDPM iterating t from (total_steps-1) down to 0:
            # Last N steps means the smallest timestep values: {0, 1, ..., N-1}
            return set(range(num_guidance))
        
        elif strategy == 'equal_distance':
            # Distribute guidance steps evenly across the timeline
            if num_guidance == 0:
                return set()
            if num_guidance >= total_steps:
                return set(range(total_steps))
            
            # Calculate spacing
            spacing = total_steps / num_guidance
            indices = []
            for i in range(num_guidance):
                idx = int(i * spacing)
                indices.append(idx)
            
            return set(indices)
        
        else:
            raise ValueError(f"Unknown guidance strategy: {strategy}. Use 'last_n' or 'equal_distance'")


    def p_sample_loop_gen(self, shape_image, shape_mask, cond=None, cond_scale=1., device=None, mask=None, degrade_mask=None):
        if degrade_mask is None: # default is all 1
            degrade_mask = torch.ones(shape_image, device=device)
        degrade_mask = degrade_mask.to(device=device, dtype=torch.float32)
        device = self.betas.device
        b = shape_image[0]
        init_noise = torch.randn_like(mask)
        step_noise_list = []
        for step in range(self.num_timesteps):
            t = torch.full((mask.shape[0],), step, device=device, dtype=torch.long)
            step_noise = self.q_sample(mask, t, noise=init_noise)
            step_noise_list.append(step_noise)
        mask_noisy = torch.stack(step_noise_list)  # [T, B, C, D, H, W]
        
        img = torch.randn(shape_image, device=device)
        mask = torch.randn(shape_mask, device=device)
        pair = torch.cat((img, mask), dim=1)
        # print(shape_mask)

        TCOUNT = 2 # 2
        RSTEP = 1  # 10
        GRAD_STEP = 0 # 7
        print(f'TCOUNT: {TCOUNT}, RSTEP: {RSTEP}, GRAD_STEP: {GRAD_STEP}')
        recurrent = [0] * self.num_timesteps
        for i in range(self.num_timesteps):
            if i % RSTEP == 0:
                recurrent[i] = TCOUNT
        i = self.num_timesteps - 1

        while i >= 0:
            # real_noisy_mask = self.q_sample(x_start=mask, t=t)
            pair[:, 1:] = mask_noisy[i] * degrade_mask + pair[:, 1:] * (1 - degrade_mask)
            pair = pair.clone().detach()
            for g in range(GRAD_STEP):
                if i > 10:
                    break
                with torch.enable_grad():
                    pair_with_grad = pair.detach().clone().requires_grad_(True)
                    t = torch.full((b,), i, device=device, dtype=torch.long)
                    self.loss_type = 'l1'
                    loss = self.p_losses_guidance_gen(pair_with_grad, t, init_noise, degrade_mask=degrade_mask)
                    print('t:', i, 'g', g, 'loss:', loss.item())
                    grad = torch.autograd.grad(loss, pair_with_grad)[0][:, :1]
                    grad_norm = grad.flatten(start_dim=1).norm( dim=1, keepdim=True).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
                    grad = grad / (grad_norm + 1e-8)
                    pair[:, :1]  = pair[:, :1] - grad * 0.5

            t = torch.full((b,), i, device=device, dtype=torch.long)
            pair = self.p_sample(pair, t, cond=cond, cond_scale=cond_scale).clone()

            # if recurrent[i] > 0 and i % RSTEP == 0:
            #     recurrent[i] -= 1
            #     for _ in range(RSTEP):
            #         with torch.no_grad():
            #             t = torch.full((b,), i, device=device, dtype=torch.long)
            #             pair = self.q_sample_one_step(pair, t)
            #         i += 1
            #         if i >= self.num_timesteps:
            #             break
            
            
            
            i -= 1

        return pair

    def p_losses_guidance_gen(self, pair_noisy, t, noise, cond=None, degrade_mask=None, **kwargs):
        device = pair_noisy.device

        if is_list_str(cond):
            cond = bert_embed(
                tokenize(cond), return_cls_repr=self.text_use_bert_cls)
            cond = cond.to(device)

        x_recon = self.denoise_fn(pair_noisy, t, cond=cond, **kwargs)[:, 1:]
        
        if self.loss_type == 'l1':
            loss = F.l1_loss(noise, x_recon, reduction='sum')
        elif self.loss_type == 'l2':
            loss = F.mse_loss(noise, x_recon, reduction='sum')
        else:
            raise NotImplementedError()

        if degrade_mask is not None:
            loss = loss / degrade_mask.sum()
        else:
            loss = loss / noise.numel()

        return loss




class Trainer(object):
    def __init__(
        self,
        diffusion_model,
        cfg,
        dataset=None,
        *,
        ema_decay=0.995,
        train_batch_size=32,
        train_lr=1e-4,
        train_num_steps=100000,
        gradient_accumulate_every=2,
        amp=False,
        step_start_ema=2000,
        update_ema_every=10,
        save_and_sample_every=1000,
        results_folder='./results',
        max_grad_norm=None,
        num_workers=4,
        device=None,
    ):
        super().__init__()
        self.model = diffusion_model
        self.ema = EMA(ema_decay)
        self.ema_model = copy.deepcopy(self.model)
        self.update_ema_every = update_ema_every

        self.step_start_ema = step_start_ema
        self.save_and_sample_every = save_and_sample_every

        self.batch_size = train_batch_size
        self.image_size = diffusion_model.image_size
        self.gradient_accumulate_every = gradient_accumulate_every
        self.train_num_steps = train_num_steps
        self.device = device

        self.cfg = cfg

        self.ds = dataset
        dl = DataLoader(self.ds, batch_size=train_batch_size,
                        shuffle=True, pin_memory=True, num_workers=num_workers)

        self.len_dataloader = len(dl)
        print("len_dl ", len(dl))
        self.dl = cycle(dl)

        print(f'found {len(self.ds)} videos as gif files')
        assert len(
            self.ds) > 0, 'need to have at least 1 video to start training (although 1 is not great, try 100k)'

        self.opt = Adam(diffusion_model.parameters(), lr=train_lr)

        self.step = 0

        self.amp = amp
        self.scaler = GradScaler(enabled=amp)
        self.max_grad_norm = max_grad_norm

        self.results_folder = Path(results_folder)
        self.results_folder.mkdir(exist_ok=True, parents=True)

        self.reset_parameters()

    def reset_parameters(self):
        self.ema_model.load_state_dict(self.model.state_dict())

    def step_ema(self):
        if self.step < self.step_start_ema:
            self.reset_parameters()
            return
        self.ema.update_model_average(self.ema_model, self.model)

    def save(self, milestone):
        data = {
            'step': self.step,
            'model': self.model.state_dict(),
            'ema': self.ema_model.state_dict(),
            'scaler': self.scaler.state_dict(),
            'optimizer': self.opt.state_dict()  # 保存优化器状态
        }
        torch.save(data, str(self.results_folder / f'model-{milestone}.pt'))

    def load(self, milestone, map_location=None, **kwargs):
        if milestone == -1:
            all_milestones = [int(p.stem.split('-')[-1])
                              for p in Path(self.results_folder).glob('**/*.pt')]
            assert len(
                all_milestones) > 0, 'need to have at least one milestone to load from latest checkpoint (milestone == -1)'
            milestone = max(all_milestones)
        
        if map_location:
            data = torch.load(milestone, map_location=map_location)
        else:
            import os
            data = torch.load(os.path.join(self.results_folder, f'model-{milestone}.pt'))

        self.step = data['step']
        self.model.load_state_dict(data['model'], **kwargs)
        self.ema_model.load_state_dict(data['ema'], **kwargs)
        self.scaler.load_state_dict(data['scaler'])
        self.opt.load_state_dict(data['optimizer'])

    def train(
        self,
        prob_focus_present=0.,
        focus_present_mask=None,
        log_fn=noop
    ):
        assert callable(log_fn)

        while self.step < self.train_num_steps:
            for i in range(self.gradient_accumulate_every):

                data_frame = next(self.dl)
                data = data_frame['img'].to(self.device)
                mask_sdf = data_frame['mask_sdf'].to(self.device)
                # print("Mask Sum: ", mask.sum())
                # print(data_frame['name'])

                with autocast(enabled=self.amp):

                    loss = self.model(**dict(
                        x=data,
                        mask=mask_sdf,
                        prob_focus_present=prob_focus_present,
                        focus_present_mask=focus_present_mask)
                    )

                    self.scaler.scale(
                            loss / self.gradient_accumulate_every).backward()

                print(f'{self.step}: {loss.item()}')

            log = {'loss': loss.item()}

            if exists(self.max_grad_norm):
                self.scaler.unscale_(self.opt)
                nn.utils.clip_grad_norm_(
                    self.model.parameters(), self.max_grad_norm)

            self.scaler.step(self.opt)
            self.scaler.update()
            self.opt.zero_grad()

            if self.step % self.update_ema_every == 0:
                self.step_ema()

            if self.step != 0 and self.step % self.save_and_sample_every == 0:
                self.ema_model.eval()
                with torch.no_grad():
                    milestone = self.step // self.save_and_sample_every
                self.save(milestone)

            log_fn(log)
            self.step += 1
            
            

        print('training completed')


# _extract_into_tensor 函数的作用是从一个给定的数组(arr)中提取与时间步(timesteps)相对应的值,
# 并将这些值广播成指定的形状(broadcast_shape)。
# 该函数主要用于处理扩散模型中的参数提取和广播操作,确保不同时间步的参数能够与图像数据进行匹配
def _extract_into_tensor(arr, timesteps, broadcast_shape):
 
    res = arr[timesteps].float()

    while len(res.shape) < len(broadcast_shape):
        res = res[..., None]
    return res.expand(broadcast_shape)