File size: 94,263 Bytes
7e0b12a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
# modeling_quicksviewer2.py

from __future__ import annotations

import itertools
import os
import csv
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple, Union

import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers.models.glm4v import modeling_glm4v as _glm4v
from transformers.cache_utils import Cache
from transformers.utils import logging
from .configuration_quicksviewer2 import (
    Quicksviewer2Config,
    Quicksviewer2TextConfig,
    Quicksviewer2VisionConfig,
)
from .cubing_quicksviewer2 import Quicksviewer2CubingModule
from .resampler_quicksviewer2 import Quicksviewer2Resampler

logger = logging.get_logger(__name__)

# 全局调试开关:导出 QUICKSVIEWER2_DEBUG=1 才会打印调试信息
DEBUG_ENABLED = os.getenv("QUICKSVIEWER2_DEBUG", "0") == "1"


def debug_print(*args, **kwargs) -> None:
    """Lightweight debug print that prefixes rank when分布式可用。"""
    if not DEBUG_ENABLED:
        return
    prefix = ""
    try:
        import torch.distributed as dist

        if dist.is_available() and dist.is_initialized():
            prefix = f"[Rank {dist.get_rank()}] "
    except Exception:
        prefix = ""

    if prefix:
        if args:
            args = (prefix + str(args[0]), *args[1:])
        else:
            args = (prefix,)
    print(*args, **kwargs)

# =============================================================================
# ==== 元数据工具 ====
# =============================================================================


@dataclass
class Quicksviewer2VideoMetadata:
    original_grid_thw: torch.LongTensor
    temporal_patch_size: int
    mode: str = "native"
    pre_merge: bool = False
    use_thumbnail: bool = True
    thumbnail_num_queries: int = 64
    actual_num_tokens: Optional[int] = None
    tgt_size_range: Optional[List[List[Tuple[int, int]]]] = None
    cube_bounds: Optional[List[List[Tuple[int, int]]]] = None
    z_hard: Optional[List[torch.Tensor]] = None
    z_soft: Optional[List[torch.Tensor]] = None
    gate_logits: Optional[List[torch.Tensor]] = None
    thumbnail: Optional[List[Optional[torch.Tensor]]] = None
    cube_tgt_size_ranges: Optional[List[List[List[List[int]]]]] = None
    video_token_counts: Optional[List[int]] = None
    cube_timestamps: Optional[List[List[str]]] = None  # 逐视频的时间戳字符串
    cube_timestamp_tokens: Optional[List[List[List[int]]]] = None  # 逐视频逐 cube 的时间戳 token ids

    # MRoPE 相关字段
    mrope_positions: Optional[torch.Tensor] = None  # 形状: (3, num_tokens)
    mrope_adjusted: bool = False  # 是否已为 Cubing 调整了 MRoPE
    original_token_count: Optional[int] = None  # 原始 token 数量(用于调试)

    def to_flattened_native(self, device: Optional[torch.device] = None) -> torch.LongTensor:
        """展平为逐帧 Grid,保持 GLM-4.1V 的 native 处理路径。"""
        if self.original_grid_thw.numel() == 0:
            base = self.original_grid_thw.new_zeros((0, 3))
            return base.to(device=device) if device is not None else base

        flattened_chunks: List[torch.LongTensor] = []
        for thw in self.original_grid_thw:
            t, h, w = (int(thw[0].item()), int(thw[1].item()), int(thw[2].item()))
            repeated = thw.new_tensor([1, h, w]).unsqueeze(0).repeat(t, 1)
            flattened_chunks.append(repeated)
        flattened = torch.cat(flattened_chunks, dim=0)
        return flattened.to(device=device) if device is not None else flattened

    def to_temporal_grid(self, device: Optional[torch.device] = None) -> torch.LongTensor:
        """构造 Cubing 需要的 temporal grid(每个条目长度为 temporal_patch_size)。"""
        flattened_chunks: List[torch.LongTensor] = []
        for thw in self.original_grid_thw:
            t = int(thw[0].item())
            h = int(thw[1].item())
            w = int(thw[2].item())
            temporal_patch = max(int(self.temporal_patch_size), 1)
            num_temporal_tokens = max(t // temporal_patch, 1)
            repeated = thw.new_tensor([temporal_patch, h, w]).unsqueeze(0).repeat(num_temporal_tokens, 1)
            flattened_chunks.append(repeated)
        base = torch.cat(flattened_chunks, dim=0) if flattened_chunks else self.original_grid_thw.new_zeros((0, 3))
        return base.to(device=device) if device is not None else base


# ==== 共享组件别名 ====
def rotate_half_llm(x: torch.Tensor) -> torch.Tensor:
    """Rotate half the hidden dims of the input."""
    x1 = x[..., 0::2]
    x2 = x[..., 1::2]
    return torch.stack((-x2, x1), dim=-1).flatten(-2)


def apply_multimodal_rotary_pos_emb(
    q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, mrope_section: Sequence[int], unsqueeze_dim=1
) -> tuple[torch.Tensor, torch.Tensor]:
    """Apply 3D MRoPE to Q/K."""
    mrope_section = [int(x) for x in mrope_section]
    split_sizes = [s * 2 for s in mrope_section]
    cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(split_sizes, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim)
    sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(split_sizes, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim)

    cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
    sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)

    rotary_dim = cos.shape[-1]
    q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
    k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]

    q_embed = (q_rot * cos) + (rotate_half_llm(q_rot) * sin)
    k_embed = (k_rot * cos) + (rotate_half_llm(k_rot) * sin)

    q_embed = torch.cat([q_embed, q_pass], dim=-1)
    k_embed = torch.cat([k_embed, k_pass], dim=-1)
    return q_embed, k_embed


class Quicksviewer2TextAttention(_glm4v.Glm4vTextAttention):
    """MRoPE-aware text attention used by Quicksviewer2."""

    def __init__(self, config: Quicksviewer2TextConfig, layer_idx: Optional[int] = None):
        super().__init__(config, layer_idx)
        self.rope_scaling = getattr(config, "rope_scaling", None)
        self.rope_parameters = getattr(config, "rope_parameters", None) or {}

    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
        attention_mask: Optional[torch.Tensor] = None,
        past_key_values: Optional[_glm4v.Cache] = None,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs,
    ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
        bsz, q_len, _ = hidden_states.size()

        query_states = self.q_proj(hidden_states)
        key_states = self.k_proj(hidden_states)
        value_states = self.v_proj(hidden_states)

        query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
        key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
        value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)

        cos, sin = position_embeddings
        mrope_section = None
        if self.rope_scaling is not None:
            mrope_section = self.rope_scaling.get("mrope_section")
        if mrope_section is None:
            mrope_section = self.rope_parameters.get("mrope_section", [0, 0, 0])
        query_states, key_states = apply_multimodal_rotary_pos_emb(
            query_states, key_states, cos, sin, mrope_section
        )

        if past_key_values is not None:
            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)

        attention_interface = _glm4v.eager_attention_forward
        if self.config._attn_implementation != "eager":
            attention_interface = _glm4v.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]

        attn_output, attn_weights = attention_interface(
            self,
            query_states,
            key_states,
            value_states,
            attention_mask,
            dropout=0.0 if not self.training else self.attention_dropout,
            scaling=self.scaling,
            **kwargs,
        )

        attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
        attn_output = self.o_proj(attn_output)
        return attn_output, attn_weights


class Quicksviewer2TextDecoderLayer(_glm4v.GradientCheckpointingLayer):
    def __init__(self, config: Quicksviewer2TextConfig, layer_idx: int):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.self_attn = Quicksviewer2TextAttention(config, layer_idx)
        self.mlp = _glm4v.Glm4vTextMLP(config)
        self.input_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_attention_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_self_attn_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_mlp_layernorm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)

    @_glm4v.auto_docstring
    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[_glm4v.Cache] = None,
        use_cache: Optional[bool] = False,
        cache_position: Optional[torch.LongTensor] = None,
        **kwargs,
    ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
        residual = hidden_states

        hidden_states = self.input_layernorm(hidden_states)

        # Self Attention
        hidden_states, _ = self.self_attn(
            hidden_states=hidden_states,
            position_embeddings=position_embeddings,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            use_cache=use_cache,
            cache_position=cache_position,
            **kwargs,
        )

        hidden_states = self.post_self_attn_layernorm(hidden_states)
        residual = residual.to(hidden_states.device)
        hidden_states = residual + hidden_states

        # Fully Connected
        residual = hidden_states
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = self.post_mlp_layernorm(hidden_states)
        residual = residual.to(hidden_states.device)
        hidden_states = residual + hidden_states

        return hidden_states


class Quicksviewer2TextModel(_glm4v.Glm4vTextModel):
    """Text backbone that swaps in MRoPE-aware attention layers."""

    config: Quicksviewer2TextConfig
    config_class = Quicksviewer2TextConfig
    input_modalities = "text"

    def __init__(self, config: Quicksviewer2TextConfig):
        _glm4v.Glm4vPreTrainedModel.__init__(self, config)
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size

        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
        self.layers = nn.ModuleList(
            [Quicksviewer2TextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.norm = _glm4v.Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.rotary_emb = _glm4v.Glm4vTextRotaryEmbedding(config=config)

        self.gradient_checkpointing = False
        self.post_init()


# ==== 优化版 Vision Patch Embed(channels_last_3d) ====
class Quicksviewer2VisionPatchEmbed(nn.Module):
    def __init__(self, config: Quicksviewer2VisionConfig) -> None:
        super().__init__()
        self.patch_size = config.patch_size
        self.temporal_patch_size = config.temporal_patch_size
        self.in_channels = config.in_channels
        self.embed_dim = config.hidden_size

        kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
        proj = nn.Conv3d(
            self.in_channels,
            self.embed_dim,
            kernel_size=kernel_size,
            stride=kernel_size,
        )

        self._channels_last_available = False
        if torch.cuda.is_available():
            try:
                proj = proj.to(memory_format=torch.channels_last_3d)
                self._channels_last_available = True
            except Exception:
                # 保持回退路径
                pass

        self.proj = proj

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        target_dtype = self.proj.weight.dtype
        hidden_states = hidden_states.view(
            -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
        )

        if self._channels_last_available and hidden_states.is_cuda:
            hidden_states = hidden_states.to(dtype=target_dtype, memory_format=torch.channels_last_3d)
        else:
            hidden_states = hidden_states.to(dtype=target_dtype)

        hidden_states = self.proj(hidden_states).view(-1, self.embed_dim)
        return hidden_states


Quicksviewer2TextRotaryEmbedding = _glm4v.Glm4vTextRotaryEmbedding
Quicksviewer2TextMLP = _glm4v.Glm4vTextMLP
Quicksviewer2TextDecoderLayer = Quicksviewer2TextDecoderLayer
Quicksviewer2TextAttention = Quicksviewer2TextAttention
Quicksviewer2TextModel = Quicksviewer2TextModel

Quicksviewer2RMSNorm = _glm4v.Glm4vRMSNorm
Quicksviewer2VisionPatchEmbed = Quicksviewer2VisionPatchEmbed
Quicksviewer2VisionRotaryEmbedding = _glm4v.Glm4vVisionRotaryEmbedding
Quicksviewer2VisionPatchMerger = _glm4v.Glm4vVisionPatchMerger
Quicksviewer2VisionEmbeddings = _glm4v.Glm4vVisionEmbeddings
Quicksviewer2VisionAttention = _glm4v.Glm4vVisionAttention
Quicksviewer2VisionBlock = _glm4v.Glm4vVisionBlock
Quicksviewer2ModelOutputWithPast = _glm4v.Glm4vModelOutputWithPast
Quicksviewer2CausalLMOutputWithPast = _glm4v.Glm4vCausalLMOutputWithPast


# ==== 预训练模型包装 ====
class Quicksviewer2PreTrainedModel(_glm4v.Glm4vPreTrainedModel):
    config_class = Quicksviewer2Config


class Quicksviewer2VisionModel(_glm4v.Glm4vVisionModel):
    config_class = Quicksviewer2VisionConfig


class Quicksviewer2Model(_glm4v.Glm4vModel):
    config_class = Quicksviewer2Config

    def __init__(self, config: Quicksviewer2Config):
        super().__init__(config)
        self._latest_video_metadata: Optional[Quicksviewer2VideoMetadata] = None
        self._cubing_module: Optional[Quicksviewer2CubingModule] = None
        self._resampler: Optional[Quicksviewer2Resampler] = None
        # 替换视觉 patch_embed 为 channels_last_3d 优化版
        try:
            old_patch = getattr(self.visual, "patch_embed", None)
            if old_patch is not None:
                new_patch = Quicksviewer2VisionPatchEmbed(config.vision_config)
                new_patch.load_state_dict(old_patch.state_dict(), strict=False)
                self.visual.patch_embed = new_patch
        except Exception:
            # 失败则保留原实现
            pass
        # ==== 替换文本主干以启用 MRoPE ====
        self.language_model = Quicksviewer2TextModel._from_config(config.text_config)
        if getattr(config, "use_cubing", False):
            self.initialize_cubing_modules_if_needed()

    def _debug_logs_enabled(self) -> bool:
        # 允许通过配置开关启用详细调试日志,默认关闭:
        #   config.debug_cubing_logs = True
        return DEBUG_ENABLED and bool(getattr(self.config, "debug_cubing_logs", False))

    # ==== 覆盖父类方法,修复 GLM4V 的 video token ID bug ====
    def get_placeholder_mask(
        self,
        input_ids: Optional[torch.LongTensor],
        inputs_embeds: torch.FloatTensor,
        image_features: Optional[torch.FloatTensor] = None,
        video_features: Optional[torch.FloatTensor] = None,
    ):
        """
        Quicksviewer2 覆盖版本:修复父类 GLM4V 中 video_token_id 错误使用 image_token_id 的 bug。

        父类 GLM4V L1210 有 bug (注释说 "GLM-4.1V and GLM-4.5V special_video_mask is special_image_mask"):
            special_video_mask = input_ids == self.config.image_token_id  # ❌ 错误

        这可能是因为原始 GLM4V 中 image 和 video 使用同一个 token ID (通过 wrapper tokens 区分)。
        但在 Quicksviewer2 配置中:
            - image_token_id = 151343
            - video_token_id = 151344  ← 不同的 ID!

        因此需要修正为:
            special_video_mask = input_ids == self.config.video_token_id  # ✅ 正确
        """
        if input_ids is None:
            base_image_mask = inputs_embeds == self.get_input_embeddings()(
                torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            base_image_mask = base_image_mask.all(-1)
            base_video_mask = inputs_embeds == self.get_input_embeddings()(
                torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            base_video_mask = base_video_mask.all(-1)
        else:
            base_image_mask = input_ids == self.config.image_token_id
            base_video_mask = input_ids == self.config.video_token_id

        n_image_tokens = int(base_image_mask.sum().item())
        if image_features is not None and base_image_mask.sum().item() != image_features.shape[0]:
            raise ValueError(
                f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
            )

        # 对视频占位符做严格匹配,与参考实现一致:占位符数必须等于特征数
        n_video_tokens = int(base_video_mask.sum().item())
        if video_features is not None:
            expected_video_tokens = int(video_features.shape[0])
            if n_video_tokens != expected_video_tokens:
                raise ValueError(
                    f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
                )

        special_image_mask = base_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
        special_video_mask = base_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
        if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
            raise ValueError(
                f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
            )

        return special_image_mask, special_video_mask

    def _debug_log(self, message: str) -> None:
        if self._debug_logs_enabled():
            debug_print(f"[Quicksviewer2][DEBUG] {message}")

    def _log_cubing_metadata_summary(self, metadata: Optional[Quicksviewer2VideoMetadata]) -> None:
        if not self._debug_logs_enabled() or metadata is None:
            return
        counts = metadata.video_token_counts or []
        bounds = metadata.cube_bounds or []
        summary = []
        for idx, grid in enumerate(metadata.original_grid_thw):
            frames = int(grid[0].item())
            token_count = counts[idx] if idx < len(counts) else 0
            cube_ranges = bounds[idx] if idx < len(bounds) else []
            cube_count = len(cube_ranges)
            preview = ", ".join(f"{int(s)}-{int(e)}" for s, e in cube_ranges[:5])
            if cube_count > 5:
                preview += ", ..."
            summary.append(
                f"video{idx}: frames={frames}, cubes={cube_count}, tokens={token_count}"
                + (f", bounds=[{preview}]" if preview else "")
            )
        if summary:
            self._debug_log("Cubing summary -> " + "; ".join(summary))
        else:
            self._debug_log("Cubing enabled but no video metadata available.")

    def _log_cubing_aux_loss(self) -> None:
        if not self._debug_logs_enabled():
            return
        with torch.no_grad():
            aux = self.get_cubing_aux_loss()
        if isinstance(aux, torch.Tensor):
            aux_value = aux.detach().float().cpu().item()
        else:
            aux_value = float(aux)
        debug_print(f"[Quicksviewer2][DEBUG] Cubing aux loss={aux_value:.6f}")

    # =========================================================================
    # ==== 视频特征抽取 (含 metadata) ====
    # =========================================================================
    def get_video_features(
        self,
        pixel_values_videos: torch.FloatTensor,
        video_grid_thw: Optional[torch.LongTensor] = None,
        videos_bound: Optional[Sequence[Tuple[int, int]]] = None,
        return_metadata: bool = False,
        tokenizer=None,
        fps: Optional[float] = None,
    ):
        """
        对齐 Exp modeling_glm4v_withCube.py L2515-2562 的视频特征提取流程。

        Args:
            pixel_values_videos: 视频像素值
            video_grid_thw: 视频网格维度 [num_videos, 3]
            videos_bound: 帧边界列表 [(start, end), ...]
            return_metadata: 是否返回 metadata
            tokenizer: 用于编码时间戳的 tokenizer(cubing 模式必需)
            fps: 视频帧率

        Returns:
            chunks: 视频特征元组
            metadata: (可选) Quicksviewer2VideoMetadata 对象
        """
        import torch.distributed as dist

        if dist.is_initialized():
            rank = dist.get_rank()
            print(
                f"[Rank {rank}] get_video_features: video_shape={tuple(pixel_values_videos.shape)}, "
                f"grid_thw={video_grid_thw.tolist() if isinstance(video_grid_thw, torch.Tensor) else video_grid_thw}",
                flush=True,
            )

        if self._debug_logs_enabled():
            debug_print(
                "[Quicksviewer2][DEBUG get_video_features] pixel_values_videos.shape=%s, video_grid_thw.shape=%s, use_cubing=%s"
                % (
                    tuple(pixel_values_videos.shape),
                    tuple(video_grid_thw.shape) if video_grid_thw is not None else None,
                    bool(getattr(self.config, "use_cubing", False)),
                )
            )

        if video_grid_thw is None:
            raise ValueError("video_grid_thw 必须提供以计算视频特征。")

        use_cubing = bool(getattr(self.config, "use_cubing", False))
        metadata = self._build_video_metadata(
            video_grid_thw=video_grid_thw,
            mode="cubing" if use_cubing else "native",
        )

        if use_cubing:
            # ==== Cubing 模式:对齐 Exp _get_video_features_with_cubing 流程 ====
            self.initialize_cubing_modules_if_needed()

            # Step 1: 获取 pre-merge 特征(对齐 Exp L2627-2631: visual(return_before_merge=True))
            premerge_chunks = self._get_video_features_with_cubing_premerge(pixel_values_videos, metadata)
            metadata.pre_merge = True
            if self._debug_logs_enabled():
                fin = torch.isfinite(premerge_chunks[0]).all().item() if premerge_chunks else True
                nan_count = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0
                debug_print(f"[Quicksviewer2][DEBUG NaNCheck][premerge_chunks] finite={fin} nan_total={nan_count}")

            # Step 2: 调用 cubing 模块获取 cube_bounds 等元数据
            # 对齐 Exp L2670-2676: cubing_module(video_frames, fpq=..., temperature=..., lr_gumbel=...)
            if self._debug_logs_enabled():
                pre_nan = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0
                debug_print(f"[Quicksviewer2][DEBUG NaNCheck][cubing_input] nan_total={pre_nan}")
            _, metadata = self._cubing_module(
                premerge_chunks,
                metadata,
                videos_bound=videos_bound,
            )
            # 缓存 gate_logits 供 aux loss 使用(对齐参考实现 _last_gate_logits)
            valid_logits = [
                logits for logits in (metadata.gate_logits or []) if logits is not None and logits.numel() > 0
            ]
            if valid_logits:
                self._last_gate_logits = torch.cat(valid_logits, dim=0)
            metadata.cube_tgt_size_ranges = self._build_cube_tgt_size_ranges(metadata)

            temporal_patch_size = int(getattr(self.config.vision_config, "temporal_patch_size", 2))
            effective_fps = None
            if fps is not None and fps > 0:
                effective_fps = float(fps) / max(int(temporal_patch_size), 1)
            else:
                base_fps = float(getattr(self.config, "video_fps", -1.0))
                if base_fps > 0:
                    effective_fps = base_fps / max(int(temporal_patch_size), 1)
                elif self._resampler is not None:
                    effective_fps = float(getattr(self._resampler, "effective_video_fps", -1.0))

            # Step 3: 计算时间戳(对齐 Exp L2682-2698)
            # 注意:Exp 在 resampler 之前计算时间戳,我们也按此顺序
            if metadata.cube_bounds:
                if tokenizer is None:
                    raise ValueError("tokenizer must be provided in cubing mode to compute cube timestamps.")

                all_timestamps: List[List[str]] = []
                all_timestamp_tokens: List[List[List[int]]] = []
                for bounds in metadata.cube_bounds:
                    ts = (
                        self._compute_cube_timestamps(
                            cube_bounds=[(int(s), int(e)) for s, e in bounds],
                            video_start_token=0,
                            temporal_patch_size=temporal_patch_size,
                            fps=effective_fps,
                        )
                        if effective_fps and effective_fps > 0
                        else []
                    )
                    all_timestamps.append(ts)

                    # 立即 tokenize 时间戳(对齐 Exp L2692-2698)
                    per_cube_tokens: List[List[int]] = []
                    if tokenizer is not None and ts:
                        for ts_text in ts:
                            try:
                                token_ids = tokenizer.encode(ts_text, add_special_tokens=False)
                            except Exception:
                                token_ids = []
                            per_cube_tokens.append(token_ids)
                    elif ts:
                        per_cube_tokens = [[] for _ in ts]
                    all_timestamp_tokens.append(per_cube_tokens)

                metadata.cube_timestamps = all_timestamps
                metadata.cube_timestamp_tokens = all_timestamp_tokens

            # Step 4: 应用 resampler(对齐 Exp L2700-2727)
            if self._resampler is not None:
                if self._debug_logs_enabled():
                    nan_before = sum(int(torch.isnan(c).sum().item()) for c in premerge_chunks) if premerge_chunks else 0
                    debug_print(f"[Quicksviewer2][DEBUG NaNCheck][resampler_input] nan_total={nan_before}")
                resampler_fps = effective_fps if effective_fps and effective_fps > 0 else None
                chunks = self._apply_cubing_resampler(premerge_chunks, metadata, fps=resampler_fps)
                if self._debug_logs_enabled():
                    nan_after = sum(int(torch.isnan(c).sum().item()) for c in chunks) if chunks else 0
                    debug_print(f"[Quicksviewer2][DEBUG NaNCheck][resampler_output] nan_total={nan_after}")
            else:
                chunks = premerge_chunks

            self._log_cubing_metadata_summary(metadata)
            self._log_cubing_aux_loss()
        else:
            # ==== Native 模式:对齐 Exp _get_video_features_native ====
            chunks = self._get_video_features_native(pixel_values_videos, metadata)
            self._debug_log("use_cubing=False; running native video path.")

        self._latest_video_metadata = metadata

        if return_metadata:
            return chunks, metadata
        return chunks

    def get_rope_index(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        image_grid_thw: Optional[torch.LongTensor] = None,
        video_grid_thw: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        计算 3D rope index,Cubing 模式使用专门的位置编码逻辑
        """
        metadata = self._latest_video_metadata
        use_cubing = bool(getattr(self.config, "use_cubing", False))
        
        if (
            use_cubing
            and metadata is not None
            and getattr(metadata, "mode", "native") == "cubing"
            and metadata.cube_bounds
        ):
            return self._get_rope_index_for_cubing(
                input_ids=input_ids,
                image_grid_thw=image_grid_thw,
                video_grid_thw=video_grid_thw,
                attention_mask=attention_mask,
            )

        return super().get_rope_index(
            input_ids=input_ids,
            image_grid_thw=image_grid_thw,
            video_grid_thw=video_grid_thw,
            attention_mask=attention_mask,
        )


    def _get_rope_index_for_cubing(
        self,
        input_ids: Optional[torch.LongTensor],
        image_grid_thw: Optional[torch.LongTensor],
        video_grid_thw: Optional[torch.LongTensor],
        attention_mask: Optional[torch.Tensor],
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        Cubing 模式的 RoPE 位置编码(支持时间戳和 Thumbnail)
        完全对齐 modeling_glm4v_withCube.py L1095-1321
        
        位置分配策略:
        - text: 连续递增
        - video_start: 单个位置
        - thumbnail: 连续递增(如果启用)
        - timestamp: 连续递增
        - cube: linspace 分布,位置范围按帧数比例分配
        - video_end: 单个位置
        """
        if input_ids is None:
            return super().get_rope_index(
                input_ids=input_ids,
                image_grid_thw=image_grid_thw,
                video_grid_thw=video_grid_thw,
                attention_mask=attention_mask,
            )

        metadata = self._latest_video_metadata
        if metadata is None or not metadata.cube_bounds:
            return super().get_rope_index(
                input_ids=input_ids,
                image_grid_thw=image_grid_thw,
                video_grid_thw=video_grid_thw,
                attention_mask=attention_mask,
            )

        batch_size = input_ids.shape[0]
        seq_len = input_ids.shape[1]
        device = input_ids.device

        video_token_id = getattr(self.config, "video_token_id", self.config.image_token_id)
        video_start_token_id = self.config.video_start_token_id
        video_end_token_id = self.config.video_end_token_id

        # 初始化 position_ids [3, batch_size, seq_len]
        # 3 对应 MRoPE 的 T/H/W 三个维度
        position_ids = torch.ones(
            3, batch_size, seq_len,
            dtype=torch.float32,
            device=device
        )

        mrope_position_deltas = []

        # === 主循环:逐 batch item 处理 ===
        for i in range(batch_size):
            st_idx = 0  # 位置游标(T 维度的当前位置)
            cube_idx = 0  # 当前正在处理的 cube 索引
            cube_video_token_idx = 0  # 当前 cube 内已处理的 video token 数
            in_video_section = False  # 是否在 video_start 和 video_end 之间
            cube_start_pos = None  # 当前 cube 的起始位置

            # Thumbnail 相关状态
            expecting_thumbnail = False
            thumbnail_token_count = 0
            thumbnail_num_queries = int(getattr(metadata, "thumbnail_num_queries", 64))

            # 为当前 batch item 计算每个 cube 的位置分配数量
            cube_position_counts = None
            if metadata.cube_bounds and i < len(metadata.cube_bounds):
                cube_position_counts = self._allocate_cube_position_counts(metadata, batch_idx=i)

            resampler_num_queries = int(getattr(self.config, "resampler_num_queries", 64))

            # === 逐 token 遍历 ===
            for j in range(seq_len):
                # Padding 位置:跳过,保持默认值 1
                if attention_mask is not None and attention_mask[i, j] == 0:
                    position_ids[:, i, j] = 1
                    continue

                token = input_ids[i, j].item()

                # === 处理 <|video_start|> ===
                if token == video_start_token_id:
                    in_video_section = True
                    position_ids[0, i, j] = st_idx
                    position_ids[1, i, j] = 1.0
                    position_ids[2, i, j] = 1.0
                    st_idx += 1

                    # 重置所有 cube 相关计数器
                    cube_idx = 0
                    cube_video_token_idx = 0
                    cube_start_pos = None

                    # 初始化 thumbnail 状态
                    expecting_thumbnail = (
                        metadata is not None and
                        getattr(metadata, "use_thumbnail", False)
                    )
                    thumbnail_token_count = 0
                    continue

                # === 处理 Thumbnail tokens ===
                elif (expecting_thumbnail and
                    in_video_section and
                    token == video_token_id and
                    thumbnail_token_count < thumbnail_num_queries):

                    # Thumbnail token: 使用连续递增位置
                    position_ids[0, i, j] = st_idx
                    position_ids[1, i, j] = 1.0
                    position_ids[2, i, j] = 1.0
                    st_idx += 1
                    thumbnail_token_count += 1

                    # 检查 Thumbnail 是否完成
                    if thumbnail_token_count >= thumbnail_num_queries:
                        expecting_thumbnail = False
                        # 重置 cube 相关计数器,准备处理后续 cubes
                        cube_video_token_idx = 0
                        cube_start_pos = None

                    continue

                # === 处理 <|video_end|> ===
                elif token == video_end_token_id:
                    in_video_section = False
                    position_ids[0, i, j] = st_idx
                    position_ids[1, i, j] = 1.0
                    position_ids[2, i, j] = 1.0
                    st_idx += 1
                    continue

                # === 处理 <|video|> tokens (Cube 内容) ===
                elif token == video_token_id and in_video_section and not expecting_thumbnail:
                    # 检查是否需要切换到下一个 cube(当前 cube 已处理完 64 个 token)
                    if cube_video_token_idx >= resampler_num_queries:
                        cube_idx += 1
                        cube_video_token_idx = 0
                        cube_start_pos = None

                    # 检查当前 cube 是否在有效范围内
                    if cube_position_counts is not None and cube_idx < len(cube_position_counts):
                        num_positions = cube_position_counts[cube_idx]  # 该 cube 分配的位置数量
                        num_tokens = resampler_num_queries  # 64

                        # 初始化新 cube 的起始位置
                        if cube_video_token_idx == 0:
                            cube_start_pos = st_idx

                        # 使用 linspace 计算当前 token 的位置
                        # 64 个 token 均匀分布在 num_positions 个位置中
                        if num_tokens > 1:
                            relative_pos = cube_video_token_idx / (num_tokens - 1)
                        else:
                            relative_pos = 0

                        actual_pos = cube_start_pos + relative_pos * (num_positions - 1)

                        position_ids[0, i, j] = actual_pos
                        position_ids[1, i, j] = 1.0
                        position_ids[2, i, j] = 1.0

                        cube_video_token_idx += 1

                        # 当前 cube 处理完毕,更新 st_idx 到该 cube 位置范围的末尾
                        if cube_video_token_idx >= num_tokens:
                            st_idx = cube_start_pos + num_positions

                    else:
                        # cube 索引超出范围,降级为连续递增位置
                        position_ids[0, i, j] = st_idx
                        position_ids[1, i, j] = 1.0
                        position_ids[2, i, j] = 1.0
                        st_idx += 1

                    continue

                # === 处理其他 tokens(普通文本、时间戳等)===
                else:
                    # 视频段内的非 video_token 视为时间戳
                    # 视频段外的视为普通文本
                    # 两者处理方式相同:连续递增位置
                    position_ids[0, i, j] = st_idx
                    position_ids[1, i, j] = 1.0
                    position_ids[2, i, j] = 1.0
                    st_idx += 1

            # 计算当前样本的 rope delta
            max_pos = position_ids[:, i, :].max()
            delta = max_pos + 1 - seq_len
            mrope_position_deltas.append(delta)

        # 转换 deltas 为 tensor
        mrope_position_deltas = torch.tensor(
            mrope_position_deltas,
            device=device,
            dtype=torch.float32
        ).unsqueeze(1)

        return position_ids, mrope_position_deltas


    def _allocate_cube_position_counts(
        self,
        metadata: Quicksviewer2VideoMetadata,
        batch_idx: int = 0,
    ) -> List[int]:
        """
        计算指定 batch item 的每个 cube 应该占用多少个位置(按帧数比例分配)
        完全对齐 modeling_glm4v_withCube.py L1368-1399

        原理:
        - 每个 cube 包含固定数量的 token(resampler_num_queries,通常是 64)
        - 但每个 cube 对应的原始视频帧数不同
        - 位置编码空间按帧数比例分配,使得时间上更长的 cube 在位置空间中也占据更大范围
        
        例如:3 个 cubes 分别有 5、4、3 帧
        - 总帧数 = 12
        - 总位置数 = 3 × 64 = 192
        - cube0 分配 192 × 5/12 ≈ 80 个位置
        - cube1 分配 192 × 4/12 ≈ 64 个位置  
        - cube2 分配 192 × 3/12 ≈ 48 个位置

        Args:
            metadata: 视频元数据
            batch_idx: 当前 batch 的索引

        Returns:
            List[int]: 每个 cube 的位置分配数量,例如 [80, 64, 48]
        """
        if not metadata.cube_bounds or batch_idx >= len(metadata.cube_bounds):
            return []

        cube_bounds = metadata.cube_bounds[batch_idx]
        num_cubes = len(cube_bounds)
        
        if num_cubes == 0:
            return []
        
        resampler_num_queries = int(getattr(self.config, "resampler_num_queries", 64))
        cube_total_tokens = num_cubes * resampler_num_queries  # 不包括 thumbnail

        # 计算每个 cube 的帧数
        cube_frames = []
        for start_frame, end_frame in cube_bounds:
            num_frames = int(end_frame) - int(start_frame)
            cube_frames.append(max(num_frames, 1))

        total_frames = max(sum(cube_frames), 1)

        # 按帧数比例分配位置数量
        position_counts = []
        for num_frames in cube_frames:
            allocated = int(round(cube_total_tokens * num_frames / total_frames))
            position_counts.append(max(allocated, 1))

        # 调整确保总和 = cube_total_tokens
        diff = cube_total_tokens - sum(position_counts)
        if diff != 0 and position_counts:
            position_counts[-1] += diff

        if self._debug_logs_enabled():
            debug_print(f"\n[Quicksviewer2][DEBUG AllocatePositionCounts] Batch {batch_idx}:")
            debug_print(f"  Cube total tokens: {cube_total_tokens}")
            debug_print(f"  Cube frames: {cube_frames}")
            debug_print(f"  Total frames: {total_frames}")
            debug_print(f"  Position counts: {position_counts}")

        return position_counts

    # ==== Timestamp 工具 ====
    @staticmethod
    def _format_timestamp(seconds: float) -> str:
        """将秒数格式化为固定宽度字符串,例如 0.0 -> 0000.0。"""
        return f"{seconds:06.1f}"

    def _compute_cube_timestamps(
        self,
        cube_bounds: List[Tuple[int, int]],
        video_start_token: int,
        temporal_patch_size: int,
        fps: float,
    ) -> List[str]:
        """
        依据 cube 边界计算每个 cube 的起始时间戳(字符串)。

        Args:
            cube_bounds: [(start, end)] 列表,基于 temporal token 索引。
            video_start_token: 视频在全局帧中的起始索引(当前实现均视为 0)。
            temporal_patch_size: 时间维度 patch 大小。
            fps: 有效帧率(已考虑 temporal_patch_size 的采样)。
        """
        if fps is None or fps <= 0:
            if self._debug_logs_enabled():
                debug_print(
                    "[Quicksviewer2][DEBUG _compute_cube_timestamps] fps<=0, skip. cube_bounds=%s video_start=%d temporal_patch_size=%d"
                    % (cube_bounds, video_start_token, temporal_patch_size)
                )
            return []

        timestamps: List[str] = []
        original_fps = fps * max(int(temporal_patch_size), 1)

        if self._debug_logs_enabled():
            debug_print(
                "[Quicksviewer2][DEBUG _compute_cube_timestamps] cube_bounds=%s video_start_token=%d temporal_patch_size=%d fps=%.4f original_fps=%.4f"
                % (
                    cube_bounds,
                    video_start_token,
                    temporal_patch_size,
                    float(fps),
                    float(original_fps),
                )
            )

        for start_token, _ in cube_bounds:
            abs_frame = video_start_token + start_token * temporal_patch_size
            seconds = abs_frame / float(original_fps)
            ts = self._format_timestamp(seconds)
            timestamps.append(ts)
            if self._debug_logs_enabled():
                debug_print(
                    "  [Quicksviewer2][DEBUG _compute_cube_timestamps] start_token=%d abs_frame=%d seconds=%.1f formatted=%s"
                    % (start_token, abs_frame, float(seconds), ts)
                )
        return timestamps

    @property
    def latest_video_metadata(self) -> Optional[Quicksviewer2VideoMetadata]:
        """返回最近一次调用 `get_video_features` 时生成的 metadata。"""
        return self._latest_video_metadata

    def initialize_cubing_modules_if_needed(self) -> None:
        """
        根据配置初始化 Cubing/Resampler 模块。
        对齐 Exp modeling_glm4v_withCube.py L1502-1505。
        """
        if not getattr(self.config, "use_cubing", False):
            return
        if self._cubing_module is None:
            self._cubing_module = Quicksviewer2CubingModule(self.config)
            # 对齐 Exp L1505: self._current_lr_gumbel = config.cubing_lr_gumbel_start
            lr_gumbel_start = float(getattr(self.config, "cubing_lr_gumbel_start", 1.0))
            setattr(self.config, "_current_lr_gumbel", lr_gumbel_start)
            setattr(self._cubing_module.config, "_current_lr_gumbel", lr_gumbel_start)
            self._debug_log("Initialized Quicksviewer2 cubing module.")
        if self._resampler is None:
            self._resampler = Quicksviewer2Resampler(self.config)
            self._debug_log("Initialized Quicksviewer2 resampler module.")

    @property
    def cubing_module(self) -> Optional[Quicksviewer2CubingModule]:
        return self._cubing_module

    @property
    def resampler(self) -> Optional[Quicksviewer2Resampler]:
        return self._resampler

    def set_gumbel_noise(self, lr_gumbel: float) -> None:
        """Set current Gumbel noise level for cubing (aligns with exp training loop)."""
        setattr(self.config, "_current_lr_gumbel", float(lr_gumbel))
        if self._cubing_module is not None:
            setattr(self._cubing_module.config, "_current_lr_gumbel", float(lr_gumbel))

    def get_cubing_aux_loss(self, alpha: float = 1e-3) -> torch.Tensor:
        """L2 penalty on gate logits, mirroring原版 Quicksviewer2 实现。"""
        if not getattr(self.config, "use_cubing", False):
            device = self.visual.patch_embed.proj.weight.device
            return torch.tensor(0.0, device=device)

        device = self.visual.patch_embed.proj.weight.device
        if hasattr(self, "_last_gate_logits"):
            gate_logits = self._last_gate_logits
            if self._debug_logs_enabled():
                debug_print(
                    "[Quicksviewer2][DEBUG AUX LOSS] Computing aux loss on %d gate logits"
                    % gate_logits.numel()
                )
            aux_loss = alpha * torch.norm(gate_logits, p=2)
            delattr(self, "_last_gate_logits")
            return aux_loss

        if self._debug_logs_enabled():
            debug_print("[Quicksviewer2][DEBUG AUX LOSS] No gate_logits available, returning 0")
        return torch.tensor(0.0, device=device)

    def _build_video_metadata(
        self,
        video_grid_thw: torch.LongTensor,
        mode: str,
    ) -> Quicksviewer2VideoMetadata:
        metadata = Quicksviewer2VideoMetadata(
            original_grid_thw=video_grid_thw.clone(),
            temporal_patch_size=int(getattr(self.config.vision_config, "temporal_patch_size", 2)),
            mode=mode,
            use_thumbnail=bool(getattr(self.config, "cubing_use_thumbnail", True)),
            thumbnail_num_queries=int(getattr(self.config, "thumbnail_num_queries", 64)),
        )
        return metadata

    def _generate_cubing_mrope_positions(
        self,
        num_tokens: int,
        device: torch.device,
        dtype: torch.dtype
    ) -> torch.Tensor:
        """
        为 Cubing 压缩后的 token 生成 MRoPE 位置编码。

        Args:
            num_tokens: 压缩后的 token 数量(通常是 64)
            device: 目标设备
            dtype: 数据类型

        Returns:
            MRoPE 位置编码张量,形状为 (3, num_tokens)
            3 对应 GLM-4.1V MRoPE 的三个部分:Q, K, V
        """
        # 检查是否启用了 MRoPE
        is_mrope_enabled = (
            hasattr(self.config, 'text_config') and
            hasattr(self.config.text_config, 'rope_scaling') and
            'mrope_section' in self.config.text_config.rope_scaling
        )

        if not is_mrope_enabled:
            # 如果没有启用 MRoPE,返回简单的序列位置
            positions = torch.arange(num_tokens, device=device, dtype=torch.long)
            # 扩展为 (3, num_tokens) 格式以保持接口一致性
            return positions.unsqueeze(0).repeat(3, 1)

        # GLM-4.1V MRoPE 配置
        mrope_section = self.config.text_config.rope_scaling.get('mrope_section', [0, 0, 0])

        # 生成基础位置序列 [0, 1, 2, ..., num_tokens-1]
        base_positions = torch.arange(num_tokens, device=device, dtype=torch.long)

        # 为 MRoPE 的三个部分生成位置编码
        # 根据 GLM-4.1V 的实现,三个部分分别对应不同的位置编码策略
        mrope_positions = []

        for i in range(3):  # Q, K, V 三个部分
            if mrope_section[i] == 0:
                # 如果该部分没有专门的配置,使用基础位置
                positions_i = base_positions
            else:
                # 根据配置生成不同的位置编码
                # 这里使用简单的策略,实际可能需要更复杂的逻辑
                positions_i = base_positions * (i + 1) % num_tokens

            mrope_positions.append(positions_i)

        # 堆叠为 (3, num_tokens) 形状
        mrope_tensor = torch.stack(mrope_positions, dim=0)

        return mrope_tensor.to(dtype=torch.long)

    def _get_video_features_native(
        self,
        pixel_values_videos: torch.FloatTensor,
        metadata: Quicksviewer2VideoMetadata,
    ) -> Tuple[torch.Tensor, ...]:
        pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
        flattened_grid = metadata.to_flattened_native(device=pixel_values_videos.device).to(
            dtype=metadata.original_grid_thw.dtype
        )

        video_embeds = self.visual(pixel_values_videos, grid_thw=flattened_grid)

        spatial_merge = getattr(self.visual, "spatial_merge_size", 1)
        split_sizes = (
            metadata.original_grid_thw.prod(-1) // (spatial_merge**2)
        ).tolist()
        metadata.actual_num_tokens = sum(int(size) for size in split_sizes)

        return tuple(torch.split(video_embeds, split_sizes))

    def _get_video_features_with_cubing_premerge(
        self,
        pixel_values_videos: torch.FloatTensor,
        metadata: Quicksviewer2VideoMetadata,
    ) -> Tuple[torch.Tensor, ...]:
        """Compute per-video frame features before spatial merge (aligns with exp: visual(..., return_before_merge=True))."""

        pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
        flattened_grid = metadata.to_flattened_native(device=pixel_values_videos.device).to(
            dtype=metadata.original_grid_thw.dtype
        )

        # 始终使用手动 pre-merge 路径,避免依赖视觉模型签名
        hidden_states = self._run_visual_premerge_manual(pixel_values_videos, flattened_grid)

        frames: List[torch.Tensor] = []
        start_idx = 0
        for thw in metadata.original_grid_thw:
            t = int(thw[0].item())
            h = int(thw[1].item())
            w = int(thw[2].item())
            seq_len = t * h * w
            chunk = hidden_states[start_idx : start_idx + seq_len]
            chunk = chunk.reshape(t, h * w, -1)
            frames.append(chunk)
            start_idx += seq_len

        return tuple(frames)

    def _run_visual_premerge_manual(
        self, pixel_values_videos: torch.FloatTensor, flattened_grid: torch.LongTensor
    ) -> torch.Tensor:
        """手动执行视觉前向,拿到合并前特征(兼容不支持 return_before_merge 的视觉模型)。"""

        hidden_states = self.visual.patch_embed(pixel_values_videos)

        hidden_states = self.visual.post_conv_layernorm(hidden_states)

        rotary_pos_emb, image_type_ids = self.visual.rot_pos_emb(flattened_grid)
        emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
        position_embeddings = (emb.cos(), emb.sin())

        cu_seqlens = torch.repeat_interleave(
            flattened_grid[:, 1] * flattened_grid[:, 2], flattened_grid[:, 0]
        ).cumsum(dim=0, dtype=flattened_grid.dtype if torch.jit.is_tracing() else torch.int32)
        cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
        seqlens = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()

        hidden_states = self.visual.embeddings(
            hidden_states, seqlens, flattened_grid, image_type_ids[:, 0], image_type_ids[:, 1]
        )

        for idx, blk in enumerate(self.visual.blocks):
            hidden_states = blk(
                hidden_states,
                cu_seqlens=cu_seqlens,
                position_embeddings=position_embeddings,
            )

        hidden_states = self.visual.post_layernorm(hidden_states)

        return hidden_states

    def _apply_cubing_resampler(
        self,
        premerge_chunks: Tuple[torch.Tensor, ...],
        metadata: Quicksviewer2VideoMetadata,
        fps: float = None,
    ) -> Tuple[torch.Tensor, ...]:
        if not premerge_chunks or not metadata.cube_bounds:
            return tuple()

        resampled: List[torch.Tensor] = []
        per_video_ranges: List[List[Tuple[int, int]]] = []
        total_tokens = 0
        lm_hidden = int(getattr(self.config.text_config, "hidden_size", premerge_chunks[0].shape[-1]))
        resampler_dtype = self._resampler.query.dtype if hasattr(self._resampler, "query") else premerge_chunks[0].dtype
        per_video_token_counts: List[int] = []

        for video_idx, frames in enumerate(premerge_chunks):
            bounds = metadata.cube_bounds[video_idx] if metadata.cube_bounds else []
            cube_ranges = (
                metadata.cube_tgt_size_ranges[video_idx]
                if metadata.cube_tgt_size_ranges and video_idx < len(metadata.cube_tgt_size_ranges)
                else None
            )
            h = int(metadata.original_grid_thw[video_idx][1].item())
            w = int(metadata.original_grid_thw[video_idx][2].item())

            per_video_tokens: List[torch.Tensor] = []
            per_video_pairs: List[Tuple[int, int]] = []

            for cube_idx, (start, end) in enumerate(bounds):
                start_i, end_i = int(start), int(end)
                if end_i <= start_i:
                    continue
                frame_slice = frames[start_i:end_i]
                if frame_slice.numel() == 0:
                    continue
                cube_flat = frame_slice.reshape(-1, frame_slice.shape[-1])
                tgt_range = (
                    cube_ranges[cube_idx]
                    if cube_ranges and cube_idx < len(cube_ranges)
                    else [[start_i, end_i], [0, h], [0, w]]
                )
                resampled_cube = self._resampler(cube_flat, tgt_range, fps=fps)
                if resampled_cube.dim() == 3:
                    resampled_cube = resampled_cube.squeeze(0)
                resampled_cube = resampled_cube.to(device=frames.device)
                per_video_tokens.append(resampled_cube)
                per_video_pairs.append((start_i, end_i))
                total_tokens += int(resampled_cube.shape[0])

            if metadata.thumbnail and video_idx < len(metadata.thumbnail):
                thumb = metadata.thumbnail[video_idx]
                if thumb is not None:
                    target_dtype = per_video_tokens[0].dtype if per_video_tokens else resampler_dtype
                    # Thumbnail 现在是 [thumbnail_num_queries, language_dim],直接插入无需 unsqueeze
                    per_video_tokens.insert(
                        0, thumb.to(device=frames.device, dtype=target_dtype)
                    )
                    total_tokens += int(thumb.shape[0])  # 添加 thumbnail 的 token 数量 (64)

            if per_video_tokens:
                resampled_video = torch.cat(per_video_tokens, dim=0)
            else:
                resampled_video = torch.empty(0, lm_hidden, device=frames.device, dtype=resampler_dtype)

            resampled.append(resampled_video)
            per_video_ranges.append(per_video_pairs)
            per_video_token_counts.append(int(resampled_video.shape[0]))

        metadata.tgt_size_range = per_video_ranges
        metadata.video_token_counts = per_video_token_counts
        metadata.actual_num_tokens = total_tokens
        if total_tokens > 0:
            reference = resampled[0]
            metadata.mrope_positions = self._generate_cubing_mrope_positions(
                total_tokens, reference.device, reference.dtype
            )
            metadata.mrope_adjusted = True
        else:
            metadata.mrope_positions = None
            metadata.mrope_adjusted = False
        metadata.original_token_count = int(metadata.original_grid_thw.prod(-1).sum().item())
        return tuple(resampled)

    def _build_cube_tgt_size_ranges(
        self, metadata: Quicksviewer2VideoMetadata
    ) -> Optional[List[List[List[List[int]]]]]:
        cube_bounds = metadata.cube_bounds
        if not cube_bounds:
            return None

        ranges: List[List[List[List[int]]]] = []
        for video_idx, bounds in enumerate(cube_bounds):
            per_video: List[List[List[int]]] = []
            h = int(metadata.original_grid_thw[video_idx][1].item())
            w = int(metadata.original_grid_thw[video_idx][2].item())
            frames_total = int(metadata.original_grid_thw[video_idx][0].item())
            covered = 0
            for start, end in bounds:
                start_i = int(start)
                end_i = int(end)
                covered += max(end_i - start_i, 0)
                per_video.append([[start_i, end_i], [0, h], [0, w]])
            if bounds and covered != frames_total:
                raise ValueError(
                    f"Cubing cube_bounds mismatch: covered {covered} vs frames {frames_total}"
                )
            ranges.append(per_video)
        return ranges


class Quicksviewer2ForConditionalGeneration(_glm4v.Glm4vForConditionalGeneration):
    config_class = Quicksviewer2Config

    def __init__(self, config: Quicksviewer2Config):
        # ==== 复用 GLM4V 预训练基类初始化 ====
        _glm4v.Glm4vPreTrainedModel.__init__(self, config)

        # ==== 换上新的主干模型并初始化 lm_head ====
        self.model = Quicksviewer2Model(config)
        self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)

        self.post_init()

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[Cache] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        pixel_values: Optional[torch.Tensor] = None,
        pixel_values_videos: Optional[torch.FloatTensor] = None,
        image_grid_thw: Optional[torch.LongTensor] = None,
        video_grid_thw: Optional[torch.LongTensor] = None,
        videos_bound: Optional[Sequence[Tuple[int, int]]] = None,
        rope_deltas: Optional[torch.LongTensor] = None,
        cache_position: Optional[torch.LongTensor] = None,
        logits_to_keep: Union[int, torch.Tensor] = 0,
        tokenizer=None,
        use_cache: Optional[bool] = None,           # ← 添加
        output_attentions: Optional[bool] = None,   # ← 添加
        output_hidden_states: Optional[bool] = None, # ← 添加
        return_dict: Optional[bool] = None,     
        **kwargs,
    ):
        """
        Forward 方法,对齐 Exp modeling_glm4v_withCube.py L2829-3314。

        核心流程:
        1. 获取初始文本 Embeddings
        2. 插入图像特征(如果存在)
        3. 获取视频特征(含 Cubing)
        4. 在 embedding 层面动态构建最终序列(Exp Step 4)
        5. 重新计算 Position IDs(Exp Step 5)
        6. 调用 language_model(Exp Step 6)
        """
        use_cubing = bool(getattr(self.config, "use_cubing", False))
        debug_print("Using Quicksviewer2")

        # ========== 非 Cubing 模式:走原有基类流程 ==========
        if not use_cubing:
            debug_print("[DEBUG] Using GLM4V native path!")
            return super().forward(
                input_ids=input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                past_key_values=past_key_values,
                inputs_embeds=inputs_embeds,
                labels=labels,
                pixel_values=pixel_values,
                pixel_values_videos=pixel_values_videos,
                image_grid_thw=image_grid_thw,
                video_grid_thw=video_grid_thw,
                rope_deltas=rope_deltas,
                cache_position=cache_position,
                logits_to_keep=logits_to_keep,
                videos_bound=videos_bound,
                **kwargs,
            )
        
        is_decoding = (
        past_key_values is not None and 
        pixel_values_videos is None
    )
    
        if is_decoding:
            # Decode 阶段:轻量级处理,不重新处理视频
            return self._forward_decode_with_cubing(
                input_ids=input_ids,
                attention_mask=attention_mask,
                position_ids=position_ids,
                past_key_values=past_key_values,
                inputs_embeds=inputs_embeds,
                labels=labels,
                use_cache=use_cache,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )

        # ========== Cubing 模式:对齐 Exp Forward 流程 ==========
        device = input_ids.device if input_ids is not None else inputs_embeds.device
        batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
        debug_max_samples = 1
        debug_segments: List[Optional[List[dict]]] = [None for _ in range(batch_size)]

        # ===== Decode 调试:可用于对齐 train/infer 的输入序列 =====
        if DEBUG_ENABLED and tokenizer is not None and input_ids is not None:
            decode_max_len = 512
            for i in range(min(batch_size, debug_max_samples)):
                ids = input_ids[i].detach().cpu()
                decoded = tokenizer.decode(ids[:decode_max_len], skip_special_tokens=False)
                debug_print(f"\n[Quicksviewer2][DEBUG Decode Input] sample {i} len={len(ids)}")
                debug_print(decoded)
            if labels is not None:
                for i in range(min(batch_size, debug_max_samples)):
                    lbl = labels[i].detach().cpu()
                    lbl = lbl[lbl != -100]
                    decoded_lbl = tokenizer.decode(lbl[:decode_max_len], skip_special_tokens=False)
                    debug_print(f"\n[Quicksviewer2][DEBUG Decode Labels] sample {i} len={len(lbl)}")
                    debug_print(decoded_lbl)

        # === Step 1: 获取初始文本 Embeddings (对齐 Exp L2865-2873) ===
        if inputs_embeds is None:
            initial_inputs_embeds = self.get_input_embeddings()(input_ids)
        else:
            initial_inputs_embeds = inputs_embeds
        current_inputs_embeds = initial_inputs_embeds

        # 强制开启前向调试输出,用于检查 position_ids/attention_mask(受全局开关控制)
        debug_enabled = DEBUG_ENABLED

        # === Step 2: 插入图像特征 (对齐 Exp L2881-2902) ===
        if pixel_values is not None:
            image_embeds = self.model.get_image_features(pixel_values, image_grid_thw)
            image_embeds = torch.cat(image_embeds, dim=0).to(current_inputs_embeds.device, current_inputs_embeds.dtype)
            image_mask, _ = self.model.get_placeholder_mask(input_ids, current_inputs_embeds, image_features=image_embeds)
            current_inputs_embeds = current_inputs_embeds.masked_scatter(image_mask, image_embeds)

        # === Step 3: 获取视频特征 (对齐 Exp L2905-2924) ===
        video_embeds_tuple, video_metadata = self.model.get_video_features(
            pixel_values_videos,
            video_grid_thw,
            videos_bound=videos_bound,
            return_metadata=True,
            tokenizer=tokenizer,
        )
        video_embeds_list = [v.to(current_inputs_embeds.device, current_inputs_embeds.dtype) for v in video_embeds_tuple]

        # === Step 4: 动态构建最终 Embeddings 和 Mask (对齐 Exp L2926-3088) ===
        video_start_embed = self.get_input_embeddings()(
            torch.tensor(self.config.video_start_token_id, device=device)
        ).unsqueeze(0)
        video_end_embed = self.get_input_embeddings()(
            torch.tensor(self.config.video_end_token_id, device=device)
        ).unsqueeze(0)

        video_placeholder_id = self.config.video_token_id
        final_inputs_embeds_list = []
        final_attention_mask_list = []
        final_labels_list = [] if labels is not None else None

        for i in range(batch_size):
            video_positions = (input_ids[i] == video_placeholder_id).nonzero(as_tuple=True)[0]

            if len(video_positions) == 0 or i >= len(video_embeds_list):
                # 没有视频占位符,直接使用原始 embeddings
                final_inputs_embeds_list.append(current_inputs_embeds[i])
                if attention_mask is not None:
                    final_attention_mask_list.append(attention_mask[i])
                else:
                    seq_len = current_inputs_embeds[i].shape[0]
                    final_attention_mask_list.append(torch.ones(seq_len, device=device, dtype=torch.long))
                if labels is not None:
                    final_labels_list.append(labels[i])
                continue

            video_pos = video_positions[0].item()
            current_video_embeds = video_embeds_list[i]

            # 获取时间戳和 thumbnail 信息
            cube_timestamps = video_metadata.cube_timestamps[i] if video_metadata.cube_timestamps else []
            cube_timestamp_tokens = video_metadata.cube_timestamp_tokens[i] if video_metadata.cube_timestamp_tokens else []
            num_cubes = len(cube_timestamps)

            has_thumbnail = bool(
                getattr(video_metadata, "use_thumbnail", False)
                or (video_metadata.thumbnail and i < len(video_metadata.thumbnail) and video_metadata.thumbnail[i] is not None)
            )
            thumbnail_num_tokens = int(getattr(self.config, "thumbnail_num_queries", 64)) if has_thumbnail else 0
            cube_offset = thumbnail_num_tokens

            num_cube_tokens = current_video_embeds.shape[0] - cube_offset
            tokens_per_cube = num_cube_tokens // num_cubes if num_cubes > 0 else 0

            segs: List[dict] = []
            cursor = 0

            def _add_seg(name: str, seg_ids: torch.Tensor, seg_type: str) -> None:
                nonlocal cursor
                seg_len = int(seg_ids.shape[0])
                segs.append(
                    {
                        "name": name,
                        "type": seg_type,
                        "start": cursor,
                        "end": cursor + seg_len,
                        "token_ids": seg_ids.detach().cpu(),
                    }
                )
                cursor += seg_len

            # === 构建 embeddings 序列 (对齐 Exp L2996-3017) ===
            parts = [
                current_inputs_embeds[i, :video_pos],
                video_start_embed,
            ]
            _add_seg("text_prefix", input_ids[i, :video_pos], "text")
            _add_seg("video_start", torch.tensor([self.config.video_start_token_id], device=device), "video_start")

            # 插入 Thumbnail
            if has_thumbnail and thumbnail_num_tokens > 0:
                thumbnail_embeds = current_video_embeds[:thumbnail_num_tokens]
                parts.append(thumbnail_embeds)
                _add_seg(
                    "thumbnail",
                    torch.full((thumbnail_num_tokens,), video_placeholder_id, device=device, dtype=torch.long),
                    "thumbnail",
                )

            # 插入 Cubes (timestamp + cube_tokens)
            for cube_idx in range(num_cubes):
                # 时间戳 embeddings
                if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]:
                    ts_embeds = self.get_input_embeddings()(
                        torch.tensor(cube_timestamp_tokens[cube_idx], device=device)
                    )
                    parts.append(ts_embeds)
                    _add_seg(
                        f"cube{cube_idx}_timestamp",
                        torch.tensor(cube_timestamp_tokens[cube_idx], device=device),
                        "timestamp",
                    )

                # Cube embeddings
                cube_start = cube_offset + cube_idx * tokens_per_cube
                cube_end = cube_start + tokens_per_cube
                parts.append(current_video_embeds[cube_start:cube_end])
                _add_seg(
                    f"cube{cube_idx}",
                    torch.full((tokens_per_cube,), video_placeholder_id, device=device, dtype=torch.long),
                    "cube",
                )

            parts.extend([
                video_end_embed,
                current_inputs_embeds[i, video_pos + 1:],
            ])
            _add_seg("video_end", torch.tensor([self.config.video_end_token_id], device=device), "video_end")
            _add_seg("text_suffix", input_ids[i, video_pos + 1:], "text")

            new_embeds = torch.cat(parts, dim=0)
            final_inputs_embeds_list.append(new_embeds)
            debug_segments[i] = segs

            # === 同步构建 attention_mask (对齐 Exp L3022-3059) ===
            if attention_mask is not None:
                current_mask = attention_mask[i]
                mask_parts = [
                    current_mask[:video_pos],
                    torch.ones(1, dtype=current_mask.dtype, device=device),  # video_start
                ]

                if has_thumbnail and thumbnail_num_tokens > 0:
                    mask_parts.append(torch.ones(thumbnail_num_tokens, dtype=current_mask.dtype, device=device))

                for cube_idx in range(num_cubes):
                    if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]:
                        num_ts_tokens = len(cube_timestamp_tokens[cube_idx])
                        mask_parts.append(torch.ones(num_ts_tokens, dtype=current_mask.dtype, device=device))
                    mask_parts.append(torch.ones(tokens_per_cube, dtype=current_mask.dtype, device=device))

                mask_parts.extend([
                    torch.ones(1, dtype=current_mask.dtype, device=device),  # video_end
                    current_mask[video_pos + 1:],
                ])

                new_mask = torch.cat(mask_parts, dim=0)
                final_attention_mask_list.append(new_mask)
            else:
                new_len = new_embeds.shape[0]
                final_attention_mask_list.append(torch.ones(new_len, dtype=torch.long, device=device))

            if labels is not None:
                ignore_index = -100
                label_device = labels.device
                label_dtype = labels.dtype
                label_parts = [
                    labels[i, :video_pos],
                    torch.full((1,), ignore_index, dtype=label_dtype, device=label_device),  # video_start
                ]

                if has_thumbnail and thumbnail_num_tokens > 0:
                    label_parts.append(torch.full((thumbnail_num_tokens,), ignore_index, dtype=label_dtype, device=label_device))

                for cube_idx in range(num_cubes):
                    if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]:
                        num_ts_tokens = len(cube_timestamp_tokens[cube_idx])
                        label_parts.append(torch.full((num_ts_tokens,), ignore_index, dtype=label_dtype, device=label_device))
                    label_parts.append(torch.full((tokens_per_cube,), ignore_index, dtype=label_dtype, device=label_device))

                label_parts.extend([
                    torch.full((1,), ignore_index, dtype=label_dtype, device=label_device),  # video_end
                    labels[i, video_pos + 1:],
                ])

                new_labels = torch.cat(label_parts, dim=0)
                final_labels_list.append(new_labels)

        # === Padding (对齐 Exp L3061-3079) ===
        max_len_new = max(embed.shape[0] for embed in final_inputs_embeds_list)
        final_inputs_embeds = torch.zeros(
            batch_size, max_len_new, current_inputs_embeds.shape[-1],
            dtype=current_inputs_embeds.dtype, device=device
        )
        final_attention_mask = torch.zeros(batch_size, max_len_new, dtype=torch.long, device=device)
        if labels is not None:
            padded_labels = torch.full(
                (batch_size, max_len_new),
                -100,
                dtype=labels.dtype,
                device=labels.device,
            )

        for i in range(batch_size):
            seq_len_i = final_inputs_embeds_list[i].shape[0]
            final_inputs_embeds[i, :seq_len_i] = final_inputs_embeds_list[i]
            final_attention_mask[i, :seq_len_i] = final_attention_mask_list[i]
            if labels is not None:
                label_seq = final_labels_list[i]
                copy_len = min(label_seq.shape[0], max_len_new)
                padded_labels[i, :copy_len] = label_seq[:copy_len]
                # 剩余部分保持 ignore_index

        if labels is not None:
            labels = padded_labels

        # === Step 5: 重新计算 Position IDs (对齐 Exp L3090-3198) ===
        # 构建 temp_input_ids 用于 get_rope_index
        video_start_token_id = self.config.video_start_token_id
        video_end_token_id = self.config.video_end_token_id
        pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else 0

        temp_input_ids = torch.full((batch_size, max_len_new), pad_token_id, dtype=torch.long, device=device)

        for i in range(batch_size):
            video_positions = (input_ids[i] == video_placeholder_id).nonzero(as_tuple=True)[0]

            if len(video_positions) == 0 or i >= len(video_embeds_list):
                original_len = input_ids[i].shape[0]
                temp_input_ids[i, :original_len] = input_ids[i]
                continue

            video_pos_orig = video_positions[0].item()
            cube_timestamp_tokens = video_metadata.cube_timestamp_tokens[i] if video_metadata.cube_timestamp_tokens else []
            num_cubes = len(cube_timestamp_tokens)

            has_thumbnail = bool(
                getattr(video_metadata, "use_thumbnail", False)
                or (video_metadata.thumbnail and i < len(video_metadata.thumbnail) and video_metadata.thumbnail[i] is not None)
            )
            thumbnail_num_tokens = int(getattr(self.config, "thumbnail_num_queries", 64)) if has_thumbnail else 0
            cube_offset = thumbnail_num_tokens

            num_video_tokens = video_embeds_list[i].shape[0]
            num_cube_tokens = num_video_tokens - cube_offset
            tokens_per_cube = num_cube_tokens // num_cubes if num_cubes > 0 else 0

            # 构建 temp_input_ids
            parts = [input_ids[i, :video_pos_orig]]
            parts.append(torch.tensor([video_start_token_id], device=device))

            if has_thumbnail and thumbnail_num_tokens > 0:
                parts.append(torch.full((thumbnail_num_tokens,), video_placeholder_id, device=device))

            for cube_idx in range(num_cubes):
                if cube_idx < len(cube_timestamp_tokens) and cube_timestamp_tokens[cube_idx]:
                    parts.append(torch.tensor(cube_timestamp_tokens[cube_idx], device=device))
                parts.append(torch.full((tokens_per_cube,), video_placeholder_id, device=device))

            parts.append(torch.tensor([video_end_token_id], device=device))
            parts.append(input_ids[i, video_pos_orig + 1:])

            temp_seq = torch.cat(parts)
            actual_len = min(temp_seq.shape[0], max_len_new)
            temp_input_ids[i, :actual_len] = temp_seq[:actual_len]

        # 调用 get_rope_index
        final_position_ids, final_rope_deltas = self.model.get_rope_index(
            input_ids=temp_input_ids,
            image_grid_thw=image_grid_thw,
            video_grid_thw=video_grid_thw,
            attention_mask=final_attention_mask,
        )

        # === 调试:前 5 次 forward 将 embeddings 和 position_ids 全量写入 CSV(默认关闭) ===
        dump_csv_enabled = os.getenv("QUICKSVIEWER2_DUMP_CSV", "0") == "1"
        if dump_csv_enabled:
            if not hasattr(self, "_debug_dump_count"):
                self._debug_dump_count = 0
            if self._debug_dump_count < 5:
                dump_idx = self._debug_dump_count + 1
                self._debug_dump_count += 1
                dump_dir = os.getenv(
                    "QUICKSVIEWER2_DUMP_DIR",
                    os.path.join(os.getcwd(), "logs"),
                )
                os.makedirs(dump_dir, exist_ok=True)
                emb_path = os.path.join(dump_dir, f"llm_embeddings_{dump_idx}.csv")
                pos_path = os.path.join(dump_dir, f"llm_position_ids_{dump_idx}.csv")

                emb_np = final_inputs_embeds.detach().cpu().to(torch.float32).numpy()
                bsz, seq_len, hidden = emb_np.shape
                with open(emb_path, "w", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow(["batch", "position"] + [f"h{i}" for i in range(hidden)])
                    for b in range(bsz):
                        for p in range(seq_len):
                            writer.writerow([b, p] + emb_np[b, p].tolist())

                pos_np = final_position_ids.detach().cpu().to(torch.float32).numpy()  # shape: (3, bsz, seq_len)
                pos_np = pos_np.transpose(1, 2, 0)  # (bsz, seq_len, 3)
                with open(pos_path, "w", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow(["batch", "position", "t", "h", "w"])
                    for b in range(pos_np.shape[0]):
                        for p in range(pos_np.shape[1]):
                            t, h, w = pos_np[b, p].tolist()
                            writer.writerow([b, p, t, h, w])

        if debug_enabled:
            for i in range(min(batch_size, debug_max_samples)):
                segs = debug_segments[i] or []
                seq_len_i = final_inputs_embeds_list[i].shape[0]
                pos_slice = final_position_ids[:, i, :seq_len_i].detach().cpu()
                debug_print(f"\n[Quicksviewer2][DEBUG Forward] Sample {i} seq_len={seq_len_i}")
                debug_print("  attention_mask_sum:", int(final_attention_mask[i, :seq_len_i].sum().item()))
                for seg in segs:
                    s, e = int(seg["start"]), int(seg["end"])
                    seg_pos = pos_slice[:, s:e]
                    t_min = int(seg_pos[0].min().item()) if seg_pos.numel() > 0 else 0
                    t_max = int(seg_pos[0].max().item()) if seg_pos.numel() > 0 else 0
                    h_unique = torch.unique(seg_pos[1]).tolist() if seg_pos.numel() > 0 else []
                    w_unique = torch.unique(seg_pos[2]).tolist() if seg_pos.numel() > 0 else []
                    token_ids = seg.get("token_ids")
                    tok_preview = token_ids[:12].tolist() if token_ids is not None else []
                    debug_print(
                        f"    segment {seg['name']} ({seg['type']}, len={e - s}) "
                        f"pos_t=[{t_min},{t_max}] span={t_max - t_min + 1} "
                        f"h_unique={h_unique} w_unique={w_unique} "
                        f"tokens_head={tok_preview}"
                    )

        # === Step 6: 调用 language_model (对齐 Exp L3231-3290) ===
        outputs = self.model.language_model(
            input_ids=None,
            position_ids=final_position_ids,
            attention_mask=final_attention_mask,
            past_key_values=past_key_values,
            inputs_embeds=final_inputs_embeds,
            cache_position=cache_position,
            **kwargs,
        )

        hidden_states = outputs[0]
        slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
        logits = self.lm_head(hidden_states[:, slice_indices, :])

        loss = None
        if labels is not None:
            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
            if self.training and getattr(self.config, "use_cubing", False):
                aux_loss = self.model.get_cubing_aux_loss()
                loss = loss + aux_loss

        # ===== Decode 输出:只展示有标签位置的预测,避免噪声 =====
        if DEBUG_ENABLED and tokenizer is not None and logits is not None and labels is not None:
            with torch.no_grad():
                # 对齐 cross-entropy,shift 一位
                shift_logits = logits[..., :-1, :].detach().cpu()
                shift_labels = labels[..., 1:].detach().cpu()
                mask = shift_labels != -100
                if mask.any():
                    pred_ids = shift_logits[0].argmax(dim=-1)
                    pred_sel = pred_ids[mask[0]]
                    label_sel = shift_labels[0][mask[0]]
                    # 限制长度,避免过长打印
                    pred_sel = pred_sel[:64]
                    label_sel = label_sel[:64]
                    debug_print("\n[Quicksviewer2][DEBUG Decode Output] preds (masked, first 64):")
                    debug_print(tokenizer.decode(pred_sel, skip_special_tokens=False))
                    debug_print("[Quicksviewer2][DEBUG Decode Output] labels (masked, first 64):")
                    debug_print(tokenizer.decode(label_sel, skip_special_tokens=False))

        return _glm4v.Glm4vCausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            rope_deltas=final_rope_deltas,
        )


    def _forward_decode_with_cubing(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        past_key_values: Optional[List[torch.FloatTensor]] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, _glm4v.Glm4vCausalLMOutputWithPast]:
        """
        Decode 阶段的 forward:不重新处理视频,使用正确的位置编码。
        
        这个方法在生成过程中被调用(第2步及以后),此时:
        - past_key_values 不为 None(有 KV cache)
        - pixel_values_videos 为 None(视频已在 prefill 处理)
        - input_ids 只包含刚生成的 1 个 token
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
        
        # Step 1: 获取 embeddings
        if inputs_embeds is None:
            inputs_embeds = self.get_input_embeddings()(input_ids)
        
        batch_size, seq_length = inputs_embeds.shape[:2]
        device = inputs_embeds.device
        
        # Step 2: 计算 position_ids(关键!)
        # 先计算 cache_length
        cache_length = past_key_values.get_seq_length() if past_key_values is not None else 0
        
        if position_ids is None:
            # 新 token 的位置 = cache_length 开始,连续递增
            new_positions = torch.arange(
                cache_length,
                cache_length + seq_length,
                dtype=torch.long,
                device=device
            )
            
            # MRoPE 格式: (3, batch_size, seq_length)
            # T 维度:连续递增
            # H, W 维度:固定为 1(答案部分不是 2D 图像)
            position_ids = new_positions.unsqueeze(0).repeat(3, 1, 1).float()
            position_ids = position_ids.expand(-1, batch_size, -1)  # 扩展 batch 维度
            position_ids[1:] = 1.0  # H 和 W 维度设置为 1
            
            # 调试输出
            # print(f"\n[Cubing Decode] cache_length={cache_length}, seq_length={seq_length}")
            debug_print(f"[Cubing Decode] position_ids[0,0,:] (T): {position_ids[0, 0, :].tolist()}")
            # print(f"[Cubing Decode] position_ids[1,0,:] (H): {position_ids[1, 0, :].tolist()}")
            # print(f"[Cubing Decode] position_ids[2,0,:] (W): {position_ids[2, 0, :].tolist()}")
        
        # Step 3: 处理 attention_mask
        if attention_mask is None:
            # Decode 阶段:新 token 可以看到所有历史 token
            # attention_mask shape: (batch_size, cache_length + seq_length)
            attention_mask = torch.ones(
                (batch_size, cache_length + seq_length),
                dtype=torch.long,
                device=device
            )
        
        # Step 4: 调用 language_model
        outputs = self.model.language_model(
            input_ids=None,  # 直接用 inputs_embeds
            position_ids=position_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        
        hidden_states = outputs[0]
        
        # Step 5: 计算 logits
        logits = self.lm_head(hidden_states)
        logits = logits.float()
        
        # Step 6: 计算 loss(如果提供了 labels)
        loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            
            loss_fct = torch.nn.CrossEntropyLoss()
            shift_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
            shift_labels = shift_labels.view(-1)
            shift_labels = shift_labels.to(shift_logits.device)
            loss = loss_fct(shift_logits, shift_labels)
        
        # Step 7: 返回结果
        if not return_dict:
            output = (logits,) + outputs[1:]
            return (loss,) + output if loss is not None else output

        max_pos = position_ids[:, :, :].max()
        rope_deltas = (max_pos + 1 - seq_length).unsqueeze(0).to(device)
        
        return _glm4v.Glm4vCausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            rope_deltas=rope_deltas
        )

    def loss_function(
        self,
        logits: torch.Tensor,
        labels: torch.LongTensor,
        vocab_size: int,
        ignore_index: int = -100,
    ) -> torch.Tensor:
        """
        调试友好的 loss 计算:在启用 config.debug_loss 时,输出与
        glm4v_cube_dbg/modeling_glm4v_withCube.py 中相同的详细统计信息。
        """
        # 强制将 labels 与 logits 放在同一设备,避免多 GPU 环境下的 device mismatch
        if labels.device != logits.device:
            labels = labels.to(logits.device)

        debug_loss = DEBUG_ENABLED  # 全局开关控制详细 loss 调试

        # 标准 GLM4V 风格的 loss 计算
        shift_logits = logits[..., :-1, :].contiguous()
        shift_labels = labels[..., 1:].contiguous()

        if not debug_loss:
            return F.cross_entropy(
                shift_logits.view(-1, vocab_size),
                shift_labels.view(-1),
                ignore_index=ignore_index,
            )

        # ====== Debug 分支:打印详细信息,便于对齐/排查 ======
        debug_print("\n[DEBUG LOSS_FUNCTION] === START ===")
        debug_print("  Input shapes:")
        debug_print(f"    logits: {logits.shape}")
        debug_print(f"    labels: {labels.shape}")
        debug_print(f"    vocab_size: {vocab_size}")

        debug_print("  After shift:")
        debug_print(f"    shift_logits: {shift_logits.shape}")
        debug_print(f"    shift_labels: {shift_labels.shape}")

        valid_mask = shift_labels != ignore_index
        num_valid = int(valid_mask.sum().item())
        total = int(shift_labels.numel())

        debug_print("  Label statistics:")
        debug_print(f"    Total positions: {total}")
        debug_print(f"    Valid positions (not {ignore_index}): {num_valid}")
        debug_print(f"    Ignored positions: {total - num_valid}")
        if total > 0:
            debug_print(f"    Valid ratio: {num_valid / total * 100:.2f}%")

        debug_print("  Logits statistics:")
        debug_print(f"    min: {shift_logits.min().item():.4f}")
        debug_print(f"    max: {shift_logits.max().item():.4f}")
        debug_print(f"    mean: {shift_logits.mean().item():.4f}")
        debug_print(f"    has NaN: {shift_logits.isnan().any().item()}")
        debug_print(f"    has Inf: {shift_logits.isinf().any().item()}")

        flat_logits = shift_logits.view(-1, vocab_size)
        flat_labels = shift_labels.view(-1)

        debug_print("  After flatten:")
        debug_print(f"    shift_logits: {flat_logits.shape}")
        debug_print(f"    shift_labels: {flat_labels.shape}")

        debug_print("\n  [Manual loss calculation]")
        loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=ignore_index)
        per_token_loss = loss_fct(flat_logits, flat_labels)

        valid_loss_mask = flat_labels != ignore_index
        valid_losses = per_token_loss[valid_loss_mask]

        if valid_losses.numel() > 0:
            manual_loss = valid_losses.mean()
            debug_print(f"    Per-token loss (first 10): {valid_losses[:10].tolist()}")
            debug_print(f"    Manual loss (mean): {manual_loss.item():.6f}")
        else:
            debug_print("    ⚠️  WARNING: No valid labels!")
            manual_loss = torch.tensor(0.0, device=per_token_loss.device)

        debug_print("\n  [F.cross_entropy]")
        loss = F.cross_entropy(flat_logits, flat_labels, ignore_index=ignore_index)
        debug_print(f"    Returned loss: {loss.item():.6f}")

        if valid_losses.numel() > 0:
            diff = abs(loss.item() - manual_loss.item())
            debug_print("\n  [Comparison]")
            debug_print(f"    Manual:  {manual_loss.item():.6f}")
            debug_print(f"    F.cross: {loss.item():.6f}")
            debug_print(f"    Diff:    {diff:.6f}")
            if diff > 0.01:
                debug_print("    ⚠️  WARNING: Large difference!")

        debug_print("\n  [Valid positions analysis]")
        valid_indices = valid_loss_mask.nonzero(as_tuple=True)[0]
        debug_print(f"    Number of valid positions: {len(valid_indices)}")
        debug_print(f"    Valid position indices: {valid_indices.tolist()}")

        if len(valid_indices) > 0:
            valid_label_values = flat_labels[valid_indices]
            debug_print(f"    Valid label values: {valid_label_values.tolist()}")

        debug_print("\n[DEBUG LABELS DETAIL]")
        if flat_labels.numel() > 0:
            sample_labels = flat_labels  # 展开后的一维 labels
            sample_valid_mask = sample_labels != ignore_index
            sample_valid_positions = sample_valid_mask.nonzero(as_tuple=True)[0]
            debug_print(f"  Valid label positions: {sample_valid_positions.tolist()}")
            if len(sample_valid_positions) > 0:
                debug_print(f"  Valid label IDs: {sample_labels[sample_valid_positions].tolist()}")
        else:
            debug_print("  ⚠️  WARNING: No labels found at all!")

        debug_print("[DEBUG LOSS_FUNCTION] === END ===\n")
        return loss

    def prepare_inputs_for_generation(self, *args, videos_bound: Optional[Sequence[Tuple[int, int]]] = None, **kwargs):
        # `videos_bound` only matters during the initial prefill; discard for decoding
        kwargs.pop("videos_bound", None)
        return super().prepare_inputs_for_generation(*args, **kwargs)

    def get_video_features(
        self,
        pixel_values_videos: torch.FloatTensor,
        video_grid_thw: Optional[torch.LongTensor] = None,
        videos_bound: Optional[Sequence[Tuple[int, int]]] = None,
        return_metadata: bool = False,
    ):
        return self.model.get_video_features(
            pixel_values_videos,
            video_grid_thw,
            videos_bound=videos_bound,
            return_metadata=return_metadata,
        )

    @property
    def latest_video_metadata(self) -> Optional[Quicksviewer2VideoMetadata]:
        return self.model.latest_video_metadata

    def initialize_cubing_modules_if_needed(self) -> None:
        self.model.initialize_cubing_modules_if_needed()

    @property
    def cubing_module(self) -> Optional[Quicksviewer2CubingModule]:
        return self.model.cubing_module

    @property
    def resampler(self) -> Optional[Quicksviewer2Resampler]:
        return self.model.resampler

    def get_cubing_aux_loss(self, alpha: float = 1e-3) -> torch.Tensor:
        return self.model.get_cubing_aux_loss(alpha)


__all__ = [
    "Quicksviewer2VideoMetadata",
    "Quicksviewer2CubingModule",
    "Quicksviewer2Resampler",
    "Quicksviewer2RMSNorm",
    "Quicksviewer2VisionPatchEmbed",
    "Quicksviewer2VisionRotaryEmbedding",
    "Quicksviewer2VisionPatchMerger",
    "Quicksviewer2VisionEmbeddings",
    "Quicksviewer2VisionAttention",
    "Quicksviewer2VisionBlock",
    "Quicksviewer2TextRotaryEmbedding",
    "Quicksviewer2TextAttention",
    "Quicksviewer2TextMLP",
    "Quicksviewer2TextDecoderLayer",
    "Quicksviewer2ModelOutputWithPast",
    "Quicksviewer2CausalLMOutputWithPast",
    "Quicksviewer2PreTrainedModel",
    "Quicksviewer2VisionModel",
    "Quicksviewer2TextModel",
    "Quicksviewer2Model",
    "Quicksviewer2ForConditionalGeneration",
]