File size: 135,916 Bytes
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae7e2d
 
 
 
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae7e2d
 
9e6e56b
 
 
 
 
9ae7e2d
 
 
 
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae7e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae7e2d
9e6e56b
 
 
9ae7e2d
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
9ae7e2d
 
 
 
9e6e56b
 
 
 
 
 
9ae7e2d
 
 
 
 
 
 
 
9e6e56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
# Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

from typing import Any
import copy
import torch
import torch.utils.checkpoint
import time
import os
import random
import logging
import wandb
import numpy as np
import pandas as pd
import shutil
import json
from datetime import datetime
from pytorch_lightning.utilities import rank_zero_only
import torch.distributed as dist
import matplotlib
import mdtraj
import warnings

from gafl.analysis import metrics 
from gafl.models.flow_module import FlowModule
from gafl.data import utils as du
from gafl.models import utils as mu
import gafl.experiment_utils as eu

from bbflow.data.alignment import require_alignment_version
from bbflow.models.bbflow_model import BBFlowModel
from bbflow.models.latent import LatentEncoder
from bbflow.models.collective import collective_measure_dynamics_loss
from bbflow.analysis import utils as au
from bbflow.analysis.analyse_bbflow import calc_metrics
from bbflow.data.interpolant_bbflow import InterpolantBBFlow

# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals:
from omegaconf import DictConfig, OmegaConf
from omegaconf.base import ContainerMetadata
if hasattr(torch.serialization, 'add_safe_globals'):
    torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True

WARMUP_EPOCH_SUMMARY_KEYS = [
    "train_loss",
    "official_loss",
    "enm_warmup_loss",
    "enm_warmup_subspace_overlap",
    "enm_warmup_cross_cov_far_top10_sign_agree",
    "enm_warmup_cross_cov_far_corr",
    "enm_warmup_active",
    "latent_effective_modes",
    "condition_scaled_pred_trans_delta_rel",
]

MD_EPOCH_SUMMARY_KEYS = [
    "train_loss",
    "official_loss",
    "motion_loss",
    "mode_orth_loss",
    "mode_recon_loss",
    "q_nll_loss",
    "q_nll_per_dim",
    "mode_coeff_abs",
    "mode_coeff_std",
    "mode_recon_centered_rel_error",
    "mode_recon_uncentered_rel_error",
    "mode_gram_min_eig",
    "mode_gram_condition",
    "mode_max_cosine_abs",
    "local_cov_loss",
    "cross_cov_loss",
    "cross_cov_near_loss",
    "cross_cov_far_loss",
    "cross_cov_far_corr",
    "cross_cov_far_top10_sign_agree",
    "cross_cov_near_top10_sign_agree",
    "rmsf_loss",
    "gen_cov_loss",
    "gen_local_shape_loss",
    "gen_cross_shape_loss",
    "gen_oracle_shape_loss",
    "gen_oracle_weighted_loss",
    "gen_oracle_active_frac",
    "gen_oracle_rank_used",
    "gen_trace_anchor_loss",
    "gen_response_abs_mean",
    "gen_response_trace_mean",
    "gen_trace_ratio_to_teacher",
    "gen_trace_ratio_to_anchor",
    "gen_trace_anchor_mean",
    "gen_rollout_trace_ratio",
    "gen_rollout_trace_ratio_ema",
    "gen_rollout_trace_target_scale",
    "gen_rollout_trace_measured",
    "gen_rollout_trace_steps",
    "gen_rollout_batch",
    "gen_rollout_num_res",
    "gen_response_active_frac",
    "pca_align_loss",
    "pca_align_weighted_overlap",
    "pca_align_best_overlap",
    "pca_align_top_energy_overlap",
    "pca_align_top_energy_subspace_overlap",
    "condition_cycle_loss",
    "condition_cycle_rel_error",
    "condition_cycle_cosine",
    "enm_warmup_active",
    "latent_effective_modes",
    "condition_scaled_pred_trans_delta_rel",
    "collective_measure_loss",
    "collective_mean_dynamics_abs_error",
    "collective_cov_dynamics_loss",
    "collective_update_abs",
    "collective_retained_fraction",
]


def epoch_summary_stage(metrics):
    warmup_active = float(metrics.get("enm_warmup_active", 0.0) or 0.0) > 0.5
    return "enm-init" if warmup_active else "md"


def epoch_summary_keys(metrics):
    """Return the concise console summary for the current training stage."""
    return WARMUP_EPOCH_SUMMARY_KEYS if epoch_summary_stage(metrics) == "enm-init" else MD_EPOCH_SUMMARY_KEYS


class BBFlowModule(FlowModule):

    def __init__(self, cfg, folding_cfg=None):
        self._latent_cfg_raw = cfg.latent if hasattr(cfg, "latent") else None
        super().__init__(cfg, folding_cfg)
        self._print_logger = eu.get_pylogger(__name__)
        if hasattr(self._exp_cfg, 'reset_epoch'):
            self.reset_epoch = self._exp_cfg.reset_epoch
        else:
            self.reset_epoch = False
        if hasattr(self._exp_cfg, 'reset_optimizer_on_load'):
            self.reset_optimizer_on_load = self._exp_cfg.reset_optimizer_on_load
        else:
            self.reset_optimizer_on_load = False

        # set samples per valid protein:
        num_ranks = cfg.experiment.num_devices
        total_samples_per_valid_prot = self._data_cfg.validation.samples_per_valid_protein
        self.samples_per_valid_protein_per_rank = total_samples_per_valid_prot // num_ranks

        assert total_samples_per_valid_prot % num_ranks == 0, f"Samples per valid protein ({self.samples_per_valid_protein_per_rank}) must be divisible by the number of ranks ({num_ranks}), set by the coinfig parameter experiment.num_devices."
        assert self.samples_per_valid_protein_per_rank > 0

    def create_model(self):
        latent_enabled = bool(self._latent_cfg_raw is not None and getattr(self._latent_cfg_raw, "enable", False))
        self.model = BBFlowModel(self._model_cfg, latent_cfg=self._latent_cfg_raw)
        self.interpolant = InterpolantBBFlow(self._interpolant_cfg)
        self.latent_enabled = latent_enabled
        training_cfg = self._exp_cfg.training
        self.motion_loss_enabled = bool(
            latent_enabled and float(getattr(training_cfg, "lambda_shape", 1.0)) != 0.0
        )
        self.condition_enabled = bool(
            latent_enabled and (
                getattr(self._latent_cfg_raw, "inject_embedder", True)
                or getattr(self._latent_cfg_raw, "inject_film", True)
            )
        )
        self.collective_enabled = bool(
            latent_enabled and getattr(self._latent_cfg_raw, "collective_enable", False)
        )
        self.collective_rank = int(
            getattr(self._latent_cfg_raw, "collective_rank", 0)
        ) if self.collective_enabled else 0
        # Take the collective basis from the data instead of from the model's own
        # implied covariance. The self-referential version measures the model's
        # error in a basis the model chooses, which has two measured
        # consequences: the basis walks (its spectrum is nearly flat, so the
        # eigenvectors are unstable), and directions where nothing happens are
        # free to inflate until they reach the model's own rank-R eigenvalue --
        # observed at 10^-0.15 of that level on 39 of 82 systems. Anchoring to
        # the cached MD principal directions removes both. It also raises the
        # fraction of the reference variance the objective can reach at all,
        # from ~18% (a random 4-plane inside the mode span) to the top-R share.
        self.collective_basis_from_data = bool(
            self.collective_enabled
            and getattr(self._latent_cfg_raw, "collective_basis_from_data", False)
        )
        # Keep the 1/tau in the velocities. Default True only to leave the
        # existing configuration alone; see the loss docstring for why False is
        # the better choice.
        self.collective_rate_weighted = bool(
            getattr(self._latent_cfg_raw, "collective_rate_weighted", True)
        )
        if self.collective_enabled:
            if bool(getattr(self._latent_cfg_raw, "freeze_foundation", False)):
                raise ValueError("CMFM requires the full BBFlow foundation to be unfrozen")
            # freeze_mode_head is allowed here. It used to be rejected because the
            # blanket requires_grad_(True) below silently undid it; that unfreeze
            # now respects the flag. With a stage-1 warm start the mode head
            # arrives aligned (mode_max_cosine 0.871, cross_cov_far_corr 0.236)
            # and one epoch of CMFM training destroys it -- the template head
            # takes a gradient norm ~24x the backbone's on 54x fewer tensors.
            group_size = int(getattr(training_cfg, "ensemble_group_size", 0))
            if group_size <= self.collective_rank:
                raise ValueError(
                    f"CMFM ensemble_group_size must exceed collective_rank="
                    f"{self.collective_rank}, got {group_size}"
                )
        self.training_epoch_metrics = []
        self._grad_flow_reported = False
        self._condition_probe_epoch = None
        self._gen_cov_rollout_trace_ratio_ema = None
        self.freeze_foundation = bool(
            latent_enabled and getattr(self._latent_cfg_raw, "freeze_foundation", True)
        )
        if latent_enabled:
            self.latent_encoder = LatentEncoder(self._latent_cfg_raw)
            self.motion_target_cache = None
            self.motion_target_device_cache = {}
            self.equilibrium_distance_cache = {}
            self.motion_target_cache_path = getattr(
                self._latent_cfg_raw,
                "motion_target_cache_path",
                getattr(self._latent_cfg_raw, "shape_fingerprint_cache_path", None),
            )
            if not self.motion_loss_enabled and not self.condition_enabled:
                for param in self.latent_encoder.parameters():
                    param.requires_grad = False
            if self.freeze_foundation:
                self._freeze_foundation_model()
            # Stage-2 switch: freeze U (trunk + template heads) so c* = Proj_U(D) is
            # a stable target and q/generator train against a fixed representation.
            # Orthogonal to freeze_foundation (that freezes the GENERATOR; this
            # freezes the LATENT mode pathway). Load a stage-1 checkpoint's weights
            # via experiment.warm_start before relying on this -- freezing does not
            # by itself give you a trained U, it just stops a loaded one from moving.
            self.freeze_mode_head = bool(
                latent_enabled and getattr(self._latent_cfg_raw, "freeze_mode_head", False)
            )
            if self.freeze_mode_head:
                self.latent_encoder.freeze_prior_backbone()
                if int(getattr(self, "global_rank", 0)) == 0:
                    check = self.latent_encoder.prior_backbone_grad_check()
                    logging.info(
                        "[freeze-mode-head] u_pathway_params=%d u_pathway_trainable=%d "
                        "(want 0) q_head_trainable=%d (want >0)",
                        check["u_pathway_params"],
                        check["u_pathway_trainable"],
                        check["q_head_trainable"],
                    )
        else:
            self.freeze_mode_head = False
        if self.collective_enabled:
            for param in self.model.parameters():
                param.requires_grad_(True)
            for param in self.latent_encoder.parameters():
                param.requires_grad_(True)
            # CMFM needs the generator and q trainable; U is optional. Re-apply
            # the stage-2 freeze here, after the blanket unfreeze, or it is a
            # no-op -- q and the collective controller then train against a
            # fixed U instead of dragging it along.
            if self.freeze_mode_head:
                self.latent_encoder.freeze_prior_backbone()
                if int(getattr(self, "global_rank", 0)) == 0:
                    check = self.latent_encoder.prior_backbone_grad_check()
                    print(
                        "[freeze-mode-head] after collective unfreeze: "
                        f"u_pathway_params={check['u_pathway_params']} "
                        f"u_pathway_trainable={check['u_pathway_trainable']} (want 0) "
                        f"q_head_trainable={check['q_head_trainable']} (want >0)",
                        flush=True,
                    )

    def _freeze_foundation_model(self):
        for param in self.model.parameters():
            param.requires_grad = False
        trainable_modules = [
            self.model.embedder.z_node_adapter,
            self.model.embedder.z_edge_adapter,
            self.model.embedder.disp_node_adapter,
            self.model.embedder.disp_edge_adapter,
            self.model.film_mlp,
        ]
        for module in trainable_modules:
            if module is not None:
                for param in module.parameters():
                    param.requires_grad = True

    def _set_frozen_foundation_eval(self):
        if not getattr(self, "freeze_foundation", False):
            return
        self.model.eval()
        for module in [
            self.model.embedder.z_node_adapter,
            self.model.embedder.z_edge_adapter,
            self.model.embedder.disp_node_adapter,
            self.model.embedder.disp_edge_adapter,
            self.model.film_mlp,
        ]:
            if module is not None:
                module.train()

    def on_train_start(self):
        parent_hook = getattr(super(), "on_train_start", None)
        if parent_hook is not None:
            parent_hook()
        if int(getattr(self, "global_rank", 0)) == 0:
            lrs = [
                float(group["lr"])
                for optimizer in self.trainer.optimizers
                for group in optimizer.param_groups
            ]
            print(f"[train-start-lr] lrs={lrs}", flush=True)

    def on_train_epoch_start(self):
        self._set_frozen_foundation_eval()
        if getattr(self, "freeze_mode_head", False):
            self.latent_encoder.set_frozen_prior_backbone_eval()
        parent_hook = getattr(super(), "on_train_epoch_start", None)
        if parent_hook is not None:
            return parent_hook()
        return None

    def _get_motion_target_cache(self):
        if self.motion_target_cache is not None:
            return self.motion_target_cache
        cache_path = self.motion_target_cache_path
        if cache_path in (None, "null", ""):
            return None
        cache_path = os.path.expanduser(str(cache_path))
        if not os.path.exists(cache_path):
            raise FileNotFoundError(f"Missing motion target cache: {cache_path}")
        cache = torch.load(cache_path, map_location="cpu", weights_only=False)
        require_alignment_version(cache, source=str(cache_path))
        if isinstance(cache, dict) and "motion_targets" in cache:
            targets = cache["motion_targets"]
        else:
            raise ValueError(
                f"Unsupported motion target cache format: {cache_path}. "
                "Run scripts/extract_shape_fingerprints.py again to create motion_targets."
            )
        out = {}
        for key, value in targets.items():
            target = {
                "local_cov": torch.as_tensor(value["local_cov"], dtype=torch.float32),
                "cross_cov": torch.as_tensor(value["cross_cov"], dtype=torch.float32),
                "dccm": torch.as_tensor(value.get("dccm", value["cross_cov"]), dtype=torch.float32),
                "rmsf": torch.as_tensor(value["rmsf"], dtype=torch.float32),
                "res_mask": torch.as_tensor(value.get("res_mask", torch.ones_like(torch.as_tensor(value["rmsf"]))), dtype=torch.float32),
            }
            for optional_field in [
                "oracle_modes",
                "oracle_energy",
                "oracle_mean_disp",
                "gen_response_trace_anchor",
            ]:
                if optional_field in value:
                    target[optional_field] = torch.as_tensor(value[optional_field], dtype=torch.float32)
            for name in self._pdb_name_variants(str(key)):
                out[name] = target
        if len(out) == 0:
            raise ValueError(f"Motion target cache is empty: {cache_path}")
        self.motion_target_cache = out
        return self.motion_target_cache

    @staticmethod
    def _pdb_name_variants(name):
        variants = {name}
        if "_" in name:
            variants.add(name.replace("_", ""))
        elif len(name) == 5:
            variants.add(f"{name[:4]}_{name[4]}")
        return variants

    def _lookup_motion_targets(self, pdb_names, device, dtype, num_res):
        cache = self._get_motion_target_cache()
        if cache is None:
            raise ValueError(
                "latent.motion_target_cache_path is required for motion-prior training; "
                "run base_stages/00_extract_shape_fingerprints.sh first."
            )
        rows = []
        missing = []
        required_fields = ["local_cov", "cross_cov", "rmsf"]
        optional_fields = ["oracle_mean_disp", "gen_response_trace_anchor"]
        needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or (
            float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0
        ) or bool(getattr(self, "collective_basis_from_data", False)) or (
            int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0)) > 0
        ) or (
            float(getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)) > 0.0
        ) or (
            float(getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)) > 0.0
        )
        if needs_oracle_modes:
            # Append rather than replace. The previous reassignment dropped
            # `gen_response_trace_anchor`, which silently switched the generator
            # trace anchor from the cached value to constructing a frozen teacher.
            optional_fields = optional_fields + ["oracle_modes", "oracle_energy"]
        for name in pdb_names:
            key = str(name)
            value = None
            resolved_name = None
            for variant in self._pdb_name_variants(key):
                value = cache.get(variant)
                if value is not None:
                    resolved_name = variant
                    break
            if value is None:
                missing.append(key)
                continue
            if needs_oracle_modes:
                missing_oracle = [field for field in ["oracle_modes", "oracle_energy"] if field not in value]
                if missing_oracle:
                    raise ValueError(
                        f"Motion target cache entry {key} lacks {missing_oracle}; "
                        "regenerate it with scripts/extract_shape_fingerprints.py before using lambda_pca_align."
                    )
            if int(value["rmsf"].shape[0]) != int(num_res):
                raise ValueError(
                    f"Motion target length mismatch for {key}: cache {value['rmsf'].shape[0]} vs batch {num_res}"
                )
            device_key = (resolved_name, str(device), str(dtype))
            device_value = self.motion_target_device_cache.get(device_key)
            if device_value is None:
                fields = required_fields + [
                    field for field in optional_fields if field in value
                ]
                device_value = {
                    field: value[field].to(device=device, dtype=dtype)
                    for field in fields
                }
                self.motion_target_device_cache[device_key] = device_value
            rows.append(device_value)
        if missing:
            preview = ", ".join(missing[:10])
            raise KeyError(f"Missing motion targets for {len(missing)} proteins: {preview}")
        out = {
            field: torch.stack([row[field] for row in rows], dim=0)
            for field in required_fields
        }
        for field in optional_fields:
            if all(field in row for row in rows):
                out[field] = torch.stack([row[field] for row in rows], dim=0)
        return out

    def _equilibrium_spatial_dists(self, pdb_names, trans_equilibrium):
        rows = []
        num_res = int(trans_equilibrium.shape[1])
        for name, coords in zip(pdb_names, trans_equilibrium):
            key = (
                str(name),
                num_res,
                str(coords.device),
                str(coords.dtype),
            )
            distances = self.equilibrium_distance_cache.get(key)
            if distances is None:
                distances = torch.cdist(
                    coords.detach().float()[None], coords.detach().float()[None]
                )[0]
                self.equilibrium_distance_cache[key] = distances
            rows.append(distances)
        return torch.stack(rows, dim=0)

    def validation_step(self, batch: Any, batch_idx: int, dataloader_idx: int=0):
        pdb_name = batch["pdb_name"][0]

        epoch_dir = os.path.join(self._sample_write_dir, f'epoch_{self.current_epoch}')
        os.makedirs(epoch_dir, exist_ok=True)
        pdb_dir = os.path.join(epoch_dir, pdb_name)
        os.makedirs(pdb_dir, exist_ok=True)
        
        N = batch['seq'].shape[1]
        batch_size = self._data_cfg.validation.max_valid_num_res_squared / N**2
        batch_size = max(
            1,
            min(
                self._data_cfg.validation.max_valid_batch_size,
                int(batch_size/5)*5
            )
        )
        self.interpolant.set_device(batch["trans_equilibrium"].device)
        # print(self.interpolant._cfg)
        sampled_conformations = self._sample_multiple(
            batch["trans_equilibrium"],
            batch["rotmats_equilibrium"],
            batch["seq"],
            self.samples_per_valid_protein_per_rank,
            batch_size,
            self.interpolant,
        )


        rank = dist.get_rank()
        if dist.get_world_size() > 1:
            # if multi-gpu, only save npy files and combine in on_validation_epoch_end
            # into one pdb file.
            samples_path = os.path.join(pdb_dir, f'rank_{rank}_sampled_conformations.npy')
            np.save(samples_path, sampled_conformations)
        else:
            # if single-gpu, save pdb file directly
            samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb')
            au.write_prot_to_pdb(
                sampled_conformations,
                samples_path,
                no_indexing=True
            )


    def on_validation_epoch_end(self):
        # wait until all ranks finished validation_step
        if dist.is_initialized() and dist.get_world_size() > 1:
            dist.barrier()  # wait until all ranks wrote their .npy

        if dist.is_initialized() and dist.get_rank() != 0:
            return  # only rank 0 continues

        # make image saving faster:
        matplotlib.use("Agg")   # non-interactive, fast, no GUI needed
        import matplotlib.pyplot as plt 

        folder = os.path.join(
            self._sample_write_dir,
            f'epoch_{self.current_epoch}',
        )
        valid_csv_path = os.path.join(self._sample_write_dir, 'valid.csv')
        valid_csv = pd.read_csv(valid_csv_path)
        all_pdb_names = valid_csv['name'].values if 'name' in valid_csv else valid_csv['pdb_name'].values
        pdb_names = []
        if dist.get_world_size() > 1:
            # combine samples that are saved in npy files into one pdb file
            for pdb_name in all_pdb_names:
                pdb_folder = os.path.join(folder, pdb_name)
                if self.trainer.sanity_checking and not os.path.exists(pdb_folder):
                    continue
                pdb_names.append(pdb_name)

                coords = []
                for rank in range(dist.get_world_size()):
                    samples_path = os.path.join(pdb_folder, f'rank_{rank}_sampled_conformations.npy')
                    coords.append(np.load(samples_path))
                    os.remove(samples_path)
                coords = np.concatenate(coords, axis=0)
                
                samples_path = os.path.join(pdb_folder, f'sampled_conformations.pdb')
                au.write_prot_to_pdb(
                    coords,
                    samples_path,
                    no_indexing=True
                )
        else:
            for pdb_name in all_pdb_names:
                pdb_folder = os.path.join(folder, pdb_name)
                if self.trainer.sanity_checking and not os.path.exists(pdb_folder):
                    continue
                pdb_names.append(pdb_name)



        if self.trainer.sanity_checking or not self._exp_cfg.use_wandb:
            return

        metrics_subset = self._data_cfg.validation.metrics_subset
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=UserWarning)
            data, metrics_dict, _ = calc_metrics(
                pdb_names,
                self._data_cfg.validation.valid_xtc_paths,
                folder,
                137,
                self._data_cfg.loader.num_workers,
                metrics_subset=metrics_subset,
                use_tqdm=self._exp_cfg.use_tqdm
            )
        for key, value in metrics_dict.items():
            self._log_scalar(
                f'valid_bbf_metrics/{key}', value,
                on_step=False, on_epoch=True, prog_bar=False,
            )


        af_rmsfs = None
        if self._data_cfg.validation.alphaflow_valid_rmsf_path is not None and os.path.exists(self._data_cfg.validation.alphaflow_valid_rmsf_path):
            with open(self._data_cfg.validation.alphaflow_valid_rmsf_path, 'r') as f:
                af_rmsfs = json.load(f)
        else:
            af_rmsfs = None

        def _plot_rmsf(pdb_name, ax, md, bbf, af=None, rmsf_type="RMSF"):
            rmse = np.sqrt(np.mean((bbf[0] - md[0])**2))
            xs = np.arange(len(md[0]))
            ax.plot(xs, md[0], label="MD", c="C0")
            ax.fill_between(xs, md[1], md[2], color="C0", alpha=0.5)
            ax.plot(xs, bbf[0], label="BBFlow", c="C1")
            ax.fill_between(xs, bbf[1], bbf[2], color="C1", alpha=0.5)
            if af is not None:
                ax.plot(xs, af["rmsf"], label="AlphaFlow", c="C2")
                ax.fill_between(xs, af["low"], af["high"], color="C2", alpha=0.5)
            ax.set_xlabel("Residue")
            ax.set_ylabel(f"{rmsf_type} "+r"[$\AA$]")
            ax.legend()
            ax.set_title(f"{rmsf_type} {pdb_name}, Epoch {self.current_epoch}, RMSE={rmse:.3f}")

        if self._exp_cfg.use_wandb and "RMSF" in metrics_subset:
            SMALL_SIZE = 20
            MEDIUM_SIZE = 24
            BIGGER_SIZE = 28
            plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
            plt.rc('axes', titlesize=BIGGER_SIZE)    # fontsize of the axes title
            plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
            plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
            plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
            plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
            plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

            for pdb_name in pdb_names:
                fig = plt.figure(figsize=(10, 5))
                _plot_rmsf(
                    pdb_name, plt.gca(),
                    (data[pdb_name]["CA_ref_rmsf"], data[pdb_name]["CA_ref_rmsf_low"], data[pdb_name]["CA_ref_rmsf_high"]),
                    (data[pdb_name]["CA_model_rmsf"], data[pdb_name]["CA_model_rmsf_low"], data[pdb_name]["CA_model_rmsf_high"]),
                    af_rmsfs[pdb_name] if af_rmsfs is not None else None,
                    "RMSF"
                )
                wandb.log({f"rmsf_plots/{pdb_name}": wandb.Image(fig)})
                plt.close(fig)


        if "RMSF" in metrics_subset:
            rmses = []
            for pdb_name in pdb_names:
                rmse = np.sqrt(np.mean((data[pdb_name]["model_rmsf"] - data[pdb_name]["ref_rmsf"])**2))
                rmses.append(rmse)
                self._log_scalar(
                    f'valid_all/{pdb_name}_rmsf_rmse', rmse,
                    on_step=False, on_epoch=True, prog_bar=False,
                )

            rmses = np.array(rmses)
            self._log_scalar(
                f'valid/rmsf_rmse', np.mean(rmses),
                on_step=False, on_epoch=True, prog_bar=False,
            )

    

    def _sample_multiple(self, 
        trans_eq, rotmats_eq, seq, 
        num_samples, batch_size,
        interpolant,
        pdb_dir=None
    ):
        _, N = trans_eq.shape[:2]
        diffuse_mask = torch.ones(1, N)

        sample_ids_batches = np.split(
            np.arange(num_samples),
            np.arange(batch_size, num_samples, batch_size)
        )

        sampled_conformations = []
        
        for sample_ids in sample_ids_batches:
            B = len(sample_ids)
            z = self._sample_prior_z(trans_eq, rotmats_eq, seq, B)
            atom37_traj, pred_traj, _ = interpolant.sample(
                B,
                N,
                self.model,
                trans_eq.repeat(B, 1, 1),
                rotmats_eq.repeat(B, 1, 1, 1),
                seq.repeat(B, 1, 1),
                z=z,
                return_trajectory=not bool(
                    getattr(self._infer_cfg, "final_only", True)
                ) or pdb_dir is not None,
                cache_static_features=bool(
                    getattr(self._infer_cfg, "cache_static_features", True)
                ),
            )

            atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1))
            pred_traj = du.to_numpy(torch.stack(pred_traj, dim=1))
            # B, T, N, 37, 3

            # remove the c betas. they are not predicted by the network but rule based and have no real meaning
            # Masking CB atoms
            # atom37 bb order = ['N', 'CA', 'C', 'CB', 'O']
            atom37_traj[..., 3, :] = 0
            pred_traj[..., 3, :] = 0

            for i, sample_id in enumerate(sample_ids):
                sampled_conformations.append(atom37_traj[i, -1])

                if pdb_dir is not None:
                    sample_dir = os.path.join(pdb_dir, f'conf_{sample_id}')
                    os.makedirs(sample_dir, exist_ok=True)
                    eu.save_traj(
                        atom37_traj[i, -1],
                        np.flip(atom37_traj[i], axis=0),
                        np.flip(pred_traj[i], axis=0),
                        du.to_numpy(diffuse_mask)[0],
                        output_dir=sample_dir,
                    )

        sampled_conformations = np.stack(sampled_conformations, axis=0)
        return sampled_conformations

    def _zero_condition(self, condition):
        if condition is None:
            return None
        out = {}
        for key, value in condition.items():
            if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
                out[key] = torch.zeros_like(value)
            else:
                out[key] = value
        return out

    def _scale_condition(self, condition, scale):
        if condition is None or float(scale) == 1.0:
            return condition
        out = {}
        for key, value in condition.items():
            if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
                out[key] = value * float(scale)
            else:
                out[key] = value
        return out

    def _shuffle_condition(self, condition, num_res):
        if condition is None:
            return None
        device = next(
            (value.device for value in condition.values() if torch.is_tensor(value)),
            torch.device("cpu"),
        )
        perm = torch.randperm(int(num_res), device=device)
        out = {}
        for key, value in condition.items():
            if not torch.is_tensor(value):
                out[key] = value
            elif key in {"node_cond", "disp_node_cond"} and value.ndim >= 3 and value.shape[1] == num_res:
                out[key] = value[:, perm, ...]
            elif key in {"edge_cond", "disp_edge_cond"} and value.ndim >= 4 and value.shape[1] == num_res and value.shape[2] == num_res:
                out[key] = value[:, perm, ...][:, :, perm, ...]
            else:
                out[key] = value
        return out

    def _sample_prior_z(self, trans_eq, rotmats_eq, seq, batch_size):
        if not getattr(self, "latent_enabled", False):
            return None
        device = trans_eq.device
        _, num_res = trans_eq.shape[:2]
        res_mask = torch.ones(1, num_res, device=device)
        infer_cfg = getattr(self, "_infer_cfg", None)
        z_per_sample = bool(getattr(infer_cfg, "z_per_sample", False)) if infer_cfg is not None else False
        z_per_sample = z_per_sample or bool(getattr(self.latent_encoder, "sample_coefficients", False))
        condition_mode = str(getattr(infer_cfg, "condition_mode", "real")) if infer_cfg is not None else "real"
        condition_scale = float(getattr(infer_cfg, "condition_scale", 1.0)) if infer_cfg is not None else 1.0
        # Per-mode tilt, read from the same place as condition_scale. The gain vector is
        # fixed per protein from that protein's coefficient covariance, so it has to be
        # set after the prior is computed -- see below. Zero leaves the gain unset and
        # reproduces every existing result bit for bit.
        tilt_alpha = (float(getattr(infer_cfg, "coefficient_tilt_alpha", 0.0) or 0.0)
                      if infer_cfg is not None else 0.0)
        self.latent_encoder._tilt_gain = None
        with torch.no_grad():
            # Fix the tilt gain for THIS protein before any sample is drawn: it is derived
            # from the protein's own coefficient covariance and must be identical across
            # its samples, or the transformed covariance is not G Gamma G and the
            # linearised gate no longer describes what the sampler does.
            if tilt_alpha != 0.0:
                from bbflow.models.collective import mixture_mean_and_covariance
                prior_for_tilt, _ = self.latent_encoder.forward_prior(
                    trans_eq, rotmats_eq, seq, res_mask)
                _, cov_for_tilt = mixture_mean_and_covariance(
                    prior_for_tilt["mixture_logits"], prior_for_tilt["mixture_mu"],
                    prior_for_tilt["mixture_scale_tril"])
                self.latent_encoder.set_tilt(tilt_alpha, cov_for_tilt)
            if z_per_sample:
                trans_in = trans_eq.repeat(batch_size, 1, 1)
                rot_in = rotmats_eq.repeat(batch_size, 1, 1, 1)
                seq_in = seq.repeat(batch_size, 1, 1)
                mask_in = res_mask.repeat(batch_size, 1)
                z = self.latent_encoder.sample_prior_z(trans_in, rot_in, seq_in, mask_in)
            else:
                z = self.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask)
                z = self.latent_encoder.repeat_condition(z, batch_size)
            if condition_mode == "real":
                pass
            elif condition_mode == "zero":
                z = self._zero_condition(z)
            elif condition_mode == "shuffled":
                z = self._shuffle_condition(z, num_res)
            elif condition_mode in ("disp_only", "mode_only"):
                # Channel ablation. The conditioning splits into two groups with
                # different gauge behaviour: `node_cond` and `edge_cond` are indexed by
                # mode, so they change under U -> U R and carry no consistent meaning
                # across proteins, while `disp_node_cond` and `disp_edge_cond` are built
                # from the displacement field sum_k c_k u_k and are gauge-invariant.
                # Every trained objective constrains U Gamma U^T, which is also
                # gauge-invariant -- so an objective can shape it well while the
                # generator faces per-mode coordinates whose meaning varies per protein.
                # If zeroing the gauge-dependent pair changes nothing, the generator was
                # already ignoring them and all four objective failures share one cause.
                drop = (("node_cond", "edge_cond") if condition_mode == "disp_only"
                        else ("disp_node_cond", "disp_edge_cond"))
                z = {k: (torch.zeros_like(v) if k in drop and torch.is_tensor(v) else v)
                     for k, v in z.items()}
            else:
                raise ValueError(f"Unknown inference.condition_mode={condition_mode}")
            z = self._scale_condition(z, condition_scale)
            if self.collective_enabled:
                z = dict(z)
                z["collective_group_index"] = torch.zeros(
                    batch_size, device=device, dtype=torch.long
                )
            return z
    
    def on_load_checkpoint(self, checkpoint):
        super().on_load_checkpoint(checkpoint)
        # If using a Gafl checkpoint, don't use weights of node_embedder and edge_embedder
        new_state_dict = {}
        current_state = self.state_dict()
        for k,v in checkpoint["state_dict"].items():
            if 'node_embedder' in k:
                continue
            if 'edge_embedder' in k:
                continue
            if k not in current_state:
                continue
            if current_state[k].shape != v.shape:
                continue
            new_state_dict[k] = v
        for k,v in self.model.state_dict().items():
            if f"model.{k}" not in new_state_dict:
                new_state_dict[f"model.{k}"] = v
        for k, v in current_state.items():
            if k not in new_state_dict:
                new_state_dict[k] = v
        checkpoint['state_dict'] = new_state_dict
            
        if self.reset_optimizer_on_load:
            optimizers = self.configure_optimizers()
            if isinstance(optimizers, tuple):
                optimizers = optimizers[0]
                lr_schedulers = optimizers[1]
                checkpoint['optimizer_states'] = [o.state_dict() for o in optimizers]
                checkpoint['lr_schedulers'] = [s.state_dict() for s in lr_schedulers]
            else:
                checkpoint['optimizer_states'] = [optimizers.state_dict()]

        if self.reset_epoch:
            checkpoint["epoch"] = 0
            checkpoint["global_step"] = 0
            del checkpoint["loops"]

    def _oracle_group_z(self, noisy_batch):
        device = noisy_batch["res_mask"].device
        num_batch, num_res = noisy_batch["res_mask"].shape[:2]
        oracle_targets = self._lookup_motion_targets(
            noisy_batch["pdb_name"],
            device=device,
            dtype=torch.float32,
            num_res=num_res,
        )
        missing = [field for field in ["oracle_modes", "oracle_energy", "oracle_mean_disp"] if field not in oracle_targets]
        if missing:
            raise ValueError(
                f"Oracle condition training requires {missing} in latent.motion_target_cache_path; "
                "rerun base_stages/00_extract_shape_fingerprints.sh with the updated code."
            )
        condition = self.latent_encoder.oracle_condition_from_targets(
            noisy_batch["trans_1"],
            noisy_batch["trans_equilibrium"],
            noisy_batch["rotmats_equilibrium"],
            noisy_batch["res_mask"],
            oracle_targets,
        )
        latent_metrics = {}
        if self._diagnostic_step():
            latent_metrics.update(self.latent_encoder.motion_metrics(condition, noisy_batch["res_mask"]))
        coeff = condition["mode_coefficients"].detach().float()
        centered = condition["oracle_centered_disp"].detach().float()
        recon = condition["oracle_recon_disp"].detach().float()
        mask = noisy_batch["res_mask"].float()[:, :, None]
        recon_error = ((centered - recon).square() * mask).sum().sqrt()
        recon_denom = (centered.square() * mask).sum().sqrt().clamp_min(1e-8)
        latent_metrics.update({
            "oracle_condition_active": noisy_batch["res_mask"].new_ones(()),
            "oracle_coeff_abs": coeff.abs().mean(),
            "oracle_coeff_std": coeff.std(),
            "oracle_recon_rel_error": (recon_error / recon_denom).detach(),
            "enm_warmup_active": noisy_batch["res_mask"].new_zeros(()),
        })
        motion_loss = noisy_batch["res_mask"].new_zeros(())
        shape_baseline_error = noisy_batch["res_mask"].new_zeros(())
        return (
            condition,
            torch.arange(num_batch, device=device, dtype=torch.long),
            latent_metrics,
            motion_loss,
            shape_baseline_error,
        )

    def _motion_loss_weights(self):
        training_cfg = self._exp_cfg.training
        weights = {
            "local_cov_loss": float(getattr(training_cfg, "lambda_local_cov", 1.0)),
            "cross_cov_loss": float(getattr(training_cfg, "lambda_cross_cov", 1.0)),
            "rmsf_loss": float(getattr(training_cfg, "lambda_rmsf", 0.25)),
        }
        lambda_pca_align = float(getattr(training_cfg, "lambda_pca_align", 0.0))
        if lambda_pca_align > 0.0:
            weights["pca_align_loss"] = lambda_pca_align
        return weights

    def _diagnostic_step(self):
        interval = int(getattr(
            self._exp_cfg.training, "diagnostic_interval_steps", 1
        ))
        return interval > 0 and int(self.global_step) % interval == 0

    def _collective_shared_time(self, batch):
        if "group_index" not in batch:
            raise ValueError("CMFM training requires grouped batches with group_index")
        group_index = batch["group_index"].long()
        groups, counts = torch.unique(group_index, sorted=True, return_counts=True)
        if torch.any(counts <= self.collective_rank):
            raise ValueError(
                f"every CMFM group must contain more than rank={self.collective_rank} "
                f"particles; observed sizes={counts.detach().cpu().tolist()}"
            )
        group_time = self.interpolant.sample_t(int(groups.numel())).float()
        time = torch.empty(
            group_index.shape[0], 1, device=group_index.device, dtype=torch.float32
        )
        for index, group in enumerate(groups):
            time[group_index == group] = group_time[index]
        return time

    def _collective_group_prior_condition(self, noisy_batch):
        """Evaluate the equilibrium-only prior once per group and broadcast it."""
        if "group_index" not in noisy_batch:
            raise ValueError("CMFM training requires group_index in every batch")
        group_index = noisy_batch["group_index"].long()
        groups, inverse, counts = torch.unique(
            group_index,
            sorted=True,
            return_inverse=True,
            return_counts=True,
        )
        if torch.any(counts <= self.collective_rank):
            raise ValueError(
                f"every CMFM group must contain more than rank={self.collective_rank} "
                f"particles; observed sizes={counts.detach().cpu().tolist()}"
            )

        pdb_names = noisy_batch.get("pdb_name")
        if pdb_names is not None:
            group_ids = group_index.detach().cpu().tolist()
            if len(pdb_names) != len(group_ids):
                raise ValueError("pdb_name must have one entry per CMFM particle")
            group_names = {}
            for group_id, pdb_name in zip(group_ids, pdb_names):
                previous = group_names.setdefault(group_id, pdb_name)
                if pdb_name != previous:
                    raise ValueError(
                        "every CMFM group must contain particles from one protein; "
                        f"group={group_id} contains {previous!r} and {pdb_name!r}"
                    )

        representative_indices = torch.stack([
            torch.nonzero(group_index == group, as_tuple=False)[0, 0]
            for group in groups
        ])
        representative_condition, _ = self.latent_encoder.forward_prior(
            noisy_batch["trans_equilibrium"].index_select(
                0,
                representative_indices,
            ),
            noisy_batch["rotmats_equilibrium"].index_select(
                0,
                representative_indices,
            ),
            noisy_batch["seq"].index_select(0, representative_indices),
            noisy_batch["res_mask"].index_select(0, representative_indices),
        )

        condition = {}
        num_groups = int(groups.numel())
        for name, value in representative_condition.items():
            if not torch.is_tensor(value) or value.ndim == 0:
                condition[name] = value
                continue
            if value.shape[0] != num_groups:
                raise ValueError(
                    f"prior condition {name} must have leading group dimension "
                    f"{num_groups}, got shape={tuple(value.shape)}"
                )
            condition[name] = value.index_select(0, inverse)

        if self.collective_basis_from_data:
            if pdb_names is None:
                raise ValueError(
                    "collective_basis_from_data needs pdb_name in the batch to "
                    "look up the cached principal directions"
                )
            representative_names = [
                pdb_names[int(index)] for index in representative_indices
            ]
            targets = self._lookup_motion_targets(
                representative_names,
                device=group_index.device,
                dtype=torch.float32,
                num_res=int(noisy_batch["res_mask"].shape[1]),
            )
            if "oracle_modes" not in targets or "oracle_energy" not in targets:
                raise ValueError(
                    "collective_basis_from_data requires oracle_modes and "
                    "oracle_energy in the motion target cache; regenerate it with "
                    "scripts/extract_shape_fingerprints.py"
                )
            rank = self.collective_rank
            # oracle_modes are the right singular vectors of the centred MD
            # displacements, so each is already unit norm in the flattened 3N
            # space and they are sorted by variance -- the same convention the
            # q-derived basis used, which makes this a drop-in replacement.
            # oracle_energy holds the variances along them, so the target
            # covariance is exactly diagonal and needs no estimation from the
            # group at all.
            basis = targets["oracle_modes"][:, :, :rank, :].contiguous()
            energy = targets["oracle_energy"][:, :rank].contiguous()
            if basis.shape[2] != rank or energy.shape[1] != rank:
                raise ValueError(
                    f"cached oracle modes provide fewer than collective_rank={rank} "
                    f"directions: modes={tuple(basis.shape)} energy={tuple(energy.shape)}"
                )
            dtype = condition["collective_basis_global"].dtype
            condition["collective_basis_global"] = basis.index_select(
                0, inverse
            ).to(dtype=dtype)
            condition["collective_target_variance"] = energy.index_select(
                0, inverse
            ).to(dtype=dtype)
            condition["collective_target_covariance"] = torch.diag_embed(
                energy
            ).index_select(0, inverse).to(dtype=dtype)
            # The retained fraction is a property of the q-implied spectrum and
            # is meaningless once the basis comes from the data. Report the
            # share of MD variance the retained directions carry instead.
            total = targets["oracle_energy"].sum(dim=-1).clamp_min(1e-8)
            condition["collective_retained_fraction"] = (
                energy.sum(dim=-1) / total
            ).index_select(0, inverse).to(dtype=dtype)
        return condition

    def _collective_population_covariance(self, condition):
        """Second moment in the collective basis, when it is a data quantity.

        Only returned for the data-anchored basis. With the q-derived basis
        ``collective_target_covariance`` is the model's own implied variance --
        measured at 2 to 800 times the observed variance along the same
        directions -- so normalising by it would put the model's belief on both
        sides of the comparison.
        """
        if not self.collective_basis_from_data:
            return None
        return condition.get("collective_target_covariance")

    def _latent_group_z(self, noisy_batch):
        self._gen_cov_targets = None
        if bool(getattr(self._exp_cfg.training, "oracle_condition", False)):
            return self._oracle_group_z(noisy_batch)
        device = noisy_batch["res_mask"].device
        num_batch, num_res = noisy_batch["res_mask"].shape[:2]
        if self.collective_enabled:
            prior_condition = self._collective_group_prior_condition(noisy_batch)
        else:
            prior_condition, _ = self.latent_encoder.forward_prior(
                noisy_batch["trans_equilibrium"],
                noisy_batch["rotmats_equilibrium"],
                noisy_batch["seq"],
                noisy_batch["res_mask"],
            )
        condition = prior_condition
        latent_metrics = {}
        if self.collective_enabled:
            latent_metrics["collective_retained_fraction"] = prior_condition[
                "collective_retained_fraction"
            ].detach().float().mean()
            latent_metrics.update({
                "prior_hidden_abs_max": prior_condition[
                    "prior_hidden_abs_max"
                ].detach().float().amax(),
                "prior_raw_mode_abs_max": prior_condition[
                    "prior_raw_mode_abs_max"
                ].detach().float().amax(),
                "prior_raw_mode_rms_min": prior_condition[
                    "prior_raw_mode_rms_min"
                ].detach().float().amin(),
                "prior_raw_mode_rms_max": prior_condition[
                    "prior_raw_mode_rms_max"
                ].detach().float().amax(),
                "prior_mode_norm_min": prior_condition[
                    "mode_norm"
                ].detach().float().amin(),
                "prior_mode_norm_max": prior_condition[
                    "mode_norm"
                ].detach().float().amax(),
                "prior_q_mu_abs_max": prior_condition[
                    "mixture_mu"
                ].detach().float().abs().amax(),
                "prior_q_scale_abs_max": prior_condition[
                    "mixture_scale_tril"
                ].detach().float().abs().amax(),
                "collective_target_variance_min": prior_condition[
                    "collective_target_variance"
                ].detach().float().amin(),
                "collective_target_variance_max": prior_condition[
                    "collective_target_variance"
                ].detach().float().amax(),
                # QR backward is the second suspect: the gauge fixing can stay
                # finite in the forward while its Jacobian blows up.
                "prior_qr_diag_abs_min": prior_condition[
                    "prior_qr_diag_abs_min"
                ].detach().float().amin(),
                "prior_qr_rel_diag_min": prior_condition[
                    "prior_qr_rel_diag_min"
                ].detach().float().amin(),
                "prior_qr_condition_max": prior_condition[
                    "prior_qr_condition"
                ].detach().float().amax(),
            })
        if self._diagnostic_step():
            latent_metrics.update(self.latent_encoder.motion_metrics(prior_condition, noisy_batch["res_mask"]))
        shape_baseline_error = noisy_batch["res_mask"].new_zeros(())
        motion_loss = noisy_batch["res_mask"].new_zeros(())
        q_fit_loss = noisy_batch["res_mask"].new_zeros(())
        mode_recon_loss = noisy_batch["res_mask"].new_zeros(())
        # Must be the pre-gauge modes: u_global is orthonormal by construction, so
        # penalising it reports ~0 and leaves the mode head free to collapse --
        # which is exactly what makes the gauge factorisation ill-conditioned.
        mode_orth_loss = self.latent_encoder.mode_orthogonality_loss(
            prior_condition.get("raw_modes_global", prior_condition["u_global"]),
            noisy_batch["res_mask"],
        )
        motion_targets = None

        enm_warmup_epochs = int(getattr(self._exp_cfg.training, "enm_warmup_epochs", 0))
        in_enm_warmup = bool(self.motion_loss_enabled and int(self.current_epoch) < enm_warmup_epochs)
        if in_enm_warmup:
            loss_parts = self.latent_encoder.enm_initialization_loss(
                prior_condition,
                noisy_batch["trans_equilibrium"],
                noisy_batch["res_mask"],
            )
            warmup_weight = float(getattr(self._exp_cfg.training, "lambda_enm_warmup", 1.0))
            motion_loss = warmup_weight * loss_parts["enm_warmup_loss"]
            latent_metrics.update(loss_parts)
            latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_ones(())
        else:
            if self.motion_loss_enabled:
                motion_targets = self._lookup_motion_targets(
                    noisy_batch["pdb_name"],
                    device=device,
                    dtype=prior_condition["local_cov_pred"].dtype,
                    num_res=num_res,
                )
                self._gen_cov_targets = motion_targets
                with torch.autocast(device_type=device.type, enabled=False):
                    spatial_dists = self._equilibrium_spatial_dists(
                        noisy_batch["pdb_name"],
                        noisy_batch["trans_equilibrium"].float(),
                    )
                loss_parts = self.latent_encoder.motion_recon_loss(
                    prior_condition,
                    motion_targets,
                    noisy_batch["res_mask"],
                    spatial_dists=spatial_dists,
                )
                weights = self._motion_loss_weights()
                motion_loss = sum(weight * loss_parts[name] for name, weight in weights.items())
                latent_metrics.update(loss_parts)
                if self._diagnostic_step():
                    latent_metrics.update(self.latent_encoder.motion_alignment_metrics(
                        prior_condition,
                        motion_targets,
                        noisy_batch["res_mask"],
                        spatial_dists,
                    ))
            latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_zeros(())

            if bool(getattr(self._exp_cfg.training, "per_frame_coeff_condition", False)):
                mean_disp = None if motion_targets is None else motion_targets.get("oracle_mean_disp")
                with torch.autocast(device_type=device.type, enabled=False):
                    condition, coeff_target = self.latent_encoder.frame_condition_from_projection(
                        noisy_batch["trans_1"].float(),
                        noisy_batch["trans_equilibrium"].float(),
                        noisy_batch["rotmats_equilibrium"],
                        noisy_batch["res_mask"],
                        prior_condition,
                        mean_disp=mean_disp,
                    )
                    q_fit_loss = self.latent_encoder.mixture_nll(
                        prior_condition, coeff_target.detach()
                    )
                    mode_recon_loss = condition["projection_recon_loss"].float().mean()
                centered_recon = condition["projection_recon_rel_error"].detach().float().mean()
                latent_metrics.update({
                    "mode_recon_loss": mode_recon_loss.detach(),
                    "q_nll_loss": q_fit_loss.detach(),
                    "q_nll_per_dim": q_fit_loss.detach() / float(self.latent_encoder.num_modes),
                    "mode_coeff_abs": coeff_target.detach().float().abs().mean(),
                    "mode_coeff_std": coeff_target.detach().float().std(),
                    "mode_recon_rel_error": centered_recon,
                    "mode_recon_centered_rel_error": centered_recon,
                    "mode_recon_uncentered_rel_error": condition[
                        "projection_uncentered_recon_rel_error"
                    ].detach().float().mean(),
                })
                if self._diagnostic_step():
                    # Same reason as mode_orth_loss: measured on u_global these
                    # collinearity metrics are constant-by-construction.
                    gram_metrics = self.latent_encoder.mode_gram_diagnostics(
                        prior_condition.get(
                            "raw_modes_global", prior_condition["u_global"]
                        ),
                        noisy_batch["res_mask"],
                    )
                    latent_metrics.update({
                        "mode_gram_min_eig": gram_metrics["mode_gram_min_eig"].detach().float().mean(),
                        "mode_gram_condition": gram_metrics["mode_gram_condition"].detach().float().mean(),
                        "mode_max_cosine_abs": gram_metrics["mode_max_cosine_abs"].detach().float().mean(),
                    })

        lambda_motion = float(getattr(self._exp_cfg.training, "lambda_motion", 1.0))
        lambda_q = float(getattr(self._exp_cfg.training, "lambda_q", 1.0))
        lambda_mode_orth = float(getattr(self._exp_cfg.training, "lambda_mode_orth", 0.0))
        lambda_mode_recon = float(getattr(self._exp_cfg.training, "lambda_mode_recon", 0.0))
        lambda_md_subspace = float(
            getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)
        )
        lambda_md_subspace_trace = float(
            getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)
        )
        md_subspace_loss = noisy_batch["res_mask"].new_zeros(())
        if lambda_md_subspace > 0.0 or lambda_md_subspace_trace > 0.0:
            # Targets carry the reference eigenbasis; `motion_targets` is already the
            # cache row when the motion prior is on, otherwise fetch it here.
            subspace_targets = motion_targets
            if subspace_targets is None or "oracle_modes" not in subspace_targets:
                subspace_targets = self._lookup_motion_targets(
                    noisy_batch["pdb_name"],
                    device=device,
                    dtype=prior_condition["u_global"].dtype,
                    num_res=num_res,
                )
            with torch.autocast(device_type=device.type, enabled=False):
                # prior_condition, not the per-frame condition: the quantity to align
                # with the reference covariance is q(c | x_eq), which is what inference
                # samples from. The per-frame condition carries coefficients read off
                # the target frame and is only available during training.
                subspace_parts = self.latent_encoder.md_subspace_shape_loss(
                    prior_condition,
                    subspace_targets,
                    noisy_batch["res_mask"],
                    weight_exp=float(
                        getattr(self._exp_cfg.training, "md_subspace_weight_exp", 0.0)
                    ),
                )
            md_subspace_loss = (
                lambda_md_subspace * subspace_parts["md_subspace_shape_loss"]
                + lambda_md_subspace_trace * subspace_parts["md_subspace_trace_loss"]
            )
            latent_metrics.update({
                key: value.detach() for key, value in subspace_parts.items()
            })
        latent_regularizer = (
            lambda_motion * motion_loss
            + lambda_q * q_fit_loss
            + lambda_mode_orth * mode_orth_loss
            + lambda_mode_recon * mode_recon_loss
            + md_subspace_loss
        )
        latent_metrics["motion_loss"] = motion_loss.detach()
        latent_metrics["mode_orth_loss"] = mode_orth_loss.detach()
        latent_metrics["mode_recon_loss"] = mode_recon_loss.detach()
        latent_metrics["latent_regularizer_loss"] = latent_regularizer.detach()
        if self.collective_enabled:
            if "group_index" not in noisy_batch:
                raise ValueError("CMFM training requires group_index in every batch")
            group_index = noisy_batch["group_index"].long()
            condition = dict(condition)
            condition["collective_group_index"] = group_index
        else:
            group_index = torch.arange(num_batch, device=device, dtype=torch.long)
        return (
            condition,
            group_index,
            latent_metrics,
            latent_regularizer,
            shape_baseline_error,
        )

    @staticmethod
    def _condition_with_scale(condition, scale):
        if not isinstance(condition, dict):
            return condition * scale
        out = {}
        for key, value in condition.items():
            if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
                out[key] = value * scale
            else:
                out[key] = value
        return out

    def _condition_cycle_loss(self, noisy_batch, model_output, condition):
        lambda_cycle = float(getattr(self._exp_cfg.training, "lambda_condition_cycle", 0.0))
        zero = model_output["pred_trans"].new_zeros(())
        if lambda_cycle == 0.0 or condition is None or not isinstance(condition, dict):
            return zero, {}
        required = {"mode_coefficients", "u_global", "projection_mean_disp"}
        if any(key not in condition for key in required):
            return zero, {}

        device = model_output["pred_trans"].device
        with torch.autocast(device_type=device.type, enabled=False):
            pred_trans = model_output["pred_trans"].float()
            trans_eq = noisy_batch["trans_equilibrium"].to(device=device, dtype=torch.float32)
            res_mask = noisy_batch["res_mask"].to(device=device, dtype=torch.float32)
            mean_disp = condition["projection_mean_disp"].to(device=device, dtype=torch.float32).detach()
            modes = condition["u_global"].to(device=device, dtype=torch.float32).detach()
            target_coeff = condition["mode_coefficients"].to(device=device, dtype=torch.float32).detach()

            pred_disp = self.latent_encoder.relative_displacement(
                pred_trans,
                trans_eq,
                res_mask,
            )
            pred_centered = pred_disp - mean_disp
            pred_coeff = self.latent_encoder.project_displacement_lstsq(
                pred_centered,
                modes,
                res_mask,
                ridge=float(getattr(self.latent_encoder, "q_lstsq_ridge", 1e-4)),
                detach_modes=True,
            )
            diff = pred_coeff - target_coeff
            denom = target_coeff.norm(dim=-1).clamp_min(1e-8)
            rel_error = diff.norm(dim=-1) / denom
            raw_loss = rel_error.mean()
            cosine = torch.nn.functional.cosine_similarity(
                pred_coeff,
                target_coeff,
                dim=-1,
                eps=1e-8,
            ).mean()

        weighted_loss = lambda_cycle * raw_loss
        metrics = {
            "condition_cycle_loss": raw_loss.detach(),
            "condition_cycle_weighted_loss": weighted_loss.detach(),
            "condition_cycle_rel_error": rel_error.detach().mean(),
            "condition_cycle_cosine": cosine.detach(),
        }
        return weighted_loss, metrics

    def _initial_generator_response_teacher(self):
        if not hasattr(self, "_gen_response_teacher_model"):
            self._gen_response_teacher_model = None
        if self._gen_response_teacher_model is None:
            teacher = copy.deepcopy(self.model)
            teacher.eval()
            for param in teacher.parameters():
                param.requires_grad_(False)
            self._gen_response_teacher_model = teacher
        return self._gen_response_teacher_model

    def _generator_response_cov_loss(self, noisy_batch, condition):
        """Train generator response shape without rewarding global expansion.

        v2 samples multiple antithetic coefficient perturbations, computes the
        generator's central-difference responses, and matches only the
        trace-normalized response covariance shape to MD targets. A weak optional
        frozen-initial teacher trace anchor keeps response amplitude near the
        A30/start checkpoint under the same ``t`` and coefficient perturbations.
        """
        lambda_gen = float(getattr(self._exp_cfg.training, "lambda_generator_cov", 0.0))
        zero = noisy_batch["res_mask"].new_zeros(())
        if lambda_gen == 0.0 or condition is None or not isinstance(condition, dict):
            return zero, {}
        targets = getattr(self, "_gen_cov_targets", None)
        if targets is None or "local_cov" not in targets or "rmsf" not in targets:
            return zero, {}
        required = ("u_global", "mixture_logits", "mixture_mu", "mixture_scale_tril")
        if any(key not in condition for key in required):
            return zero, {}
        use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False))
        if use_cross and "cross_cov" not in targets:
            use_cross = False
        # Projection onto the cached MD principal directions. Fails closed: if it is
        # requested and the cache cannot supply the basis, raise rather than train a
        # silently different objective. Rank is capped at the number of antithetic
        # perturbations, since the response covariance cannot exceed that rank.
        oracle_rank = int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0))
        oracle_weight = float(
            getattr(self._exp_cfg.training, "lambda_gen_oracle_shape", 0.0)
        )
        # Rank and weight must agree. Either alone is a configuration that looks
        # enabled and trains nothing: a positive weight with rank 0 never builds the
        # term, a positive rank with weight 0 builds it and discards it.
        if (oracle_rank > 0) != (oracle_weight > 0.0):
            raise ValueError(
                "generator_cov_oracle_rank and lambda_gen_oracle_shape must be both "
                f"zero or both positive; got rank={oracle_rank}, weight={oracle_weight}"
            )
        if oracle_rank > 0:
            missing = [
                field for field in ("oracle_modes", "oracle_energy")
                if field not in targets
            ]
            if missing:
                raise KeyError(
                    f"generator_cov_oracle_rank={oracle_rank} requires {missing} in the "
                    "motion target cache"
                )

        # t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t.
        t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1))
        t_max = float(getattr(self._exp_cfg.training, "generator_cov_t_max", 0.6))
        t_vec = torch.squeeze(noisy_batch["t"]).reshape(-1).float()
        sample_weight = ((t_vec >= t_min) & (t_vec <= t_max)).to(dtype=t_vec.dtype)

        scale = float(getattr(self._exp_cfg.training, "generator_cov_delta_scale", 1.0))
        num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_num_deltas", 2))
        num_deltas = max(num_deltas, 2)
        student_chunk_deltas = int(
            getattr(self._exp_cfg.training, "generator_cov_student_chunk_deltas", 1)
        )
        student_chunk_deltas = max(1, min(student_chunk_deltas, num_deltas))
        teacher_anchor = bool(getattr(self._exp_cfg.training, "generator_cov_initial_trace_anchor", True))
        teacher_num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_teacher_num_deltas", 1))
        teacher_num_deltas = max(1, min(teacher_num_deltas, num_deltas))
        teacher_reuse_student_delta = bool(
            getattr(self._exp_cfg.training, "generator_cov_teacher_reuse_student_delta", True)
        )
        teacher_trace_denominator = str(
            getattr(self._exp_cfg.training, "generator_cov_teacher_trace_denominator", "teacher")
        )
        # "md_trace" (default) anchors the response magnitude to the cached MD trace.
        # "teacher_trace" is retained only for reproducing the old runs: the frozen teacher
        # is copied at step 0 with zero-initialized condition adapters, so its response to c
        # is identically zero and the anchor collapses the student's response to zero.
        amplitude_anchor = str(
            getattr(self._exp_cfg.training, "generator_cov_amplitude_anchor", "md_trace")
        )
        rollout_enabled = bool(
            getattr(self._exp_cfg.training, "generator_cov_rollout_calibration", False)
        )
        if rollout_enabled and amplitude_anchor == "md_trace":
            amplitude_anchor = "rollout_trace"
        if not teacher_anchor:
            amplitude_anchor = "none"
        use_teacher = amplitude_anchor == "teacher_trace"
        cached_teacher_trace = targets.get("gen_response_trace_anchor") if use_teacher else None
        teacher_model = (
            self._initial_generator_response_teacher()
            if use_teacher and cached_teacher_trace is None
            else None
        )
        with torch.autocast(device_type=noisy_batch["res_mask"].device.type, enabled=False):
            logits = condition["mixture_logits"].detach().float()
            mu = condition["mixture_mu"].detach().float()
            probs = torch.softmax(logits, dim=-1)
            mu_bar = torch.einsum("bm,bmk->bk", probs, mu)

        u_global = condition["u_global"].detach()
        rotmats_eq = noisy_batch["rotmats_equilibrium"]
        res_mask = noisy_batch["res_mask"]
        def _concat_conditions(conditions):
            out = {}
            keys = conditions[0].keys()
            local_batch_size = None
            for value in conditions[0].values():
                if torch.is_tensor(value) and value.dim() > 0:
                    local_batch_size = value.shape[0]
                    break
            for key in keys:
                value = conditions[0][key]
                if (
                    local_batch_size is not None
                    and torch.is_tensor(value)
                    and value.shape[:1] == (local_batch_size,)
                ):
                    out[key] = torch.cat([cond[key] for cond in conditions], dim=0)
                else:
                    out[key] = value
            return out

        def _expand_batch(batch, repeats):
            out = {}
            local_batch_size = batch["res_mask"].shape[0]
            for key, value in batch.items():
                if key == "z":
                    continue
                if torch.is_tensor(value) and value.shape[:1] == (local_batch_size,):
                    out[key] = torch.cat([value for _ in range(repeats)], dim=0)
                elif isinstance(value, (list, tuple)) and len(value) == local_batch_size:
                    out[key] = list(value) * repeats
                else:
                    out[key] = value
            return out

        use_checkpoint = bool(getattr(self._exp_cfg.training, "generator_cov_checkpoint", True))
        trans_eq = noisy_batch["trans_equilibrium"]
        conditions = []
        for _ in range(num_deltas):
            c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition)
            c_sample = c_sample.detach().float()
            delta = (c_sample - mu_bar) * scale
            c_plus = mu_bar + delta
            c_minus = mu_bar - delta
            cond_plus = self.latent_encoder.condition_from_mode_coefficients(
                u_global, c_plus, rotmats_eq, res_mask, include_statistics=False
            )
            cond_minus = self.latent_encoder.condition_from_mode_coefficients(
                u_global, c_minus, rotmats_eq, res_mask, include_statistics=False
            )
            conditions.extend([cond_plus, cond_minus])

        batch_size = res_mask.shape[0]
        response_chunks = []
        for start_delta in range(0, num_deltas, student_chunk_deltas):
            end_delta = min(num_deltas, start_delta + student_chunk_deltas)
            chunk_conditions = conditions[2 * start_delta : 2 * end_delta]
            chunk_num_deltas = end_delta - start_delta
            merged_condition = _concat_conditions(chunk_conditions)
            merged_batch = _expand_batch(noisy_batch, repeats=len(chunk_conditions))
            merged_batch["z"] = merged_condition

            def _pred_trans_merged(z_cond):
                probe_batch = dict(merged_batch)
                probe_batch["z"] = z_cond
                return self.model(probe_batch)["pred_trans"]

            if use_checkpoint:
                pred_merged = torch.utils.checkpoint.checkpoint(
                    _pred_trans_merged, merged_condition, use_reentrant=False
                )
            else:
                pred_merged = _pred_trans_merged(merged_condition)

            pred_merged = pred_merged.reshape(
                chunk_num_deltas, 2, batch_size, *pred_merged.shape[1:]
            )
            pred_plus = pred_merged[:, 0].reshape(
                chunk_num_deltas * batch_size, *pred_merged.shape[3:]
            )
            pred_minus = pred_merged[:, 1].reshape(
                chunk_num_deltas * batch_size, *pred_merged.shape[3:]
            )
            trans_eq_rep = trans_eq[None].expand(
                chunk_num_deltas, -1, -1, -1
            ).reshape(chunk_num_deltas * batch_size, *trans_eq.shape[1:])
            res_mask_rep = res_mask[None].expand(
                chunk_num_deltas, -1, -1
            ).reshape(chunk_num_deltas * batch_size, *res_mask.shape[1:])
            disp_plus = self.latent_encoder.relative_displacement(
                pred_plus.float(), trans_eq_rep.float(), res_mask_rep
            )
            disp_minus = self.latent_encoder.relative_displacement(
                pred_minus.float(), trans_eq_rep.float(), res_mask_rep
            )
            chunk_response = 0.5 * (disp_plus - disp_minus)
            chunk_response = chunk_response.reshape(
                chunk_num_deltas, batch_size, *chunk_response.shape[1:]
            )
            response_chunks.append(chunk_response)
        response_deltas = torch.cat(response_chunks, dim=0)

        def _response_trace(response, mask_value):
            resp = response.float()
            if resp.dim() == 3:
                resp = resp[None]
            resp = resp * mask_value[None, :, :, None].float()
            local = torch.einsum("sbni,sbnj->bnij", resp, resp) / float(resp.shape[0])
            return (
                torch.diagonal(local, dim1=-2, dim2=-1).sum(dim=-1)
                * mask_value.float()
            ).sum(dim=-1).clamp_min(1e-8)

        def _trim_residue_dims(value, max_res):
            if not torch.is_tensor(value):
                return value
            if value.dim() >= 2 and value.shape[1] == res_mask.shape[1]:
                value = value[:, :max_res, ...]
            if value.dim() >= 3 and value.shape[2] == res_mask.shape[1]:
                value = value[:, :, :max_res, ...]
            return value

        def _index_first_dim(value, example_idx, max_res=None):
            if torch.is_tensor(value) and value.shape[:1] == (batch_size,):
                value = value.index_select(0, example_idx)
                if max_res is not None:
                    value = _trim_residue_dims(value, max_res)
                return value
            if isinstance(value, (list, tuple)) and len(value) == batch_size:
                return [value[int(i)] for i in example_idx.detach().cpu().tolist()]
            return value

        def _slice_condition(cond, example_idx, max_res=None):
            out = {}
            for key, value in cond.items():
                out[key] = _index_first_dim(value, example_idx, max_res=max_res)
            return out

        def _slice_batch(batch, example_idx, max_res=None):
            out = {}
            for key, value in batch.items():
                if key == "z":
                    continue
                out[key] = _index_first_dim(value, example_idx, max_res=max_res)
            return out

        def _rollout_final_pred_trans(probe_batch, steps):
            # Faithful mirror of the real inference sampler (interpolant_bbflow.sample):
            # the caller has already placed the SHARED prior-noise x0 into
            # trans_t/rotmats_t. Integrate the full linspace(min_t, 1, steps+1) grid
            # with the exact euler steps inference uses (scalar t_1/d_t), then return
            # the final clean pred_trans. This is what makes T_full the real-sampler
            # c-response instead of a coarse t->1 continuation of the training state.
            rollout_batch = dict(probe_batch)
            rollout_batch.pop("trans_sc", None)
            rollout_batch["_embedder_static"] = self.model.prepare_inference_static(rollout_batch)
            trans_current = rollout_batch["trans_t"]
            rotmats_current = rollout_batch["rotmats_t"]
            n = trans_current.shape[0]
            device = trans_current.device
            min_t = float(getattr(self._interpolant_cfg, "min_t", 1e-2))
            ts = torch.linspace(min_t, 1.0, int(steps) + 1, device=device)
            was_training = self.model.training
            self.model.eval()
            try:
                t_1 = ts[0]
                for t_2 in ts[1:]:
                    rollout_batch["trans_t"] = trans_current
                    rollout_batch["rotmats_t"] = rotmats_current
                    rollout_batch["t"] = torch.ones((n, 1), device=device) * t_1
                    model_out = self.model(rollout_batch)
                    pred_trans_1 = model_out["pred_trans"]
                    pred_rotmats_1 = model_out["pred_rotmats"]
                    if self._interpolant_cfg.self_condition:
                        rollout_batch["trans_sc"] = pred_trans_1.detach()
                    d_t = t_2 - t_1
                    trans_current = self.interpolant._trans_euler_step(
                        d_t, t_1, pred_trans_1, trans_current
                    )
                    rotmats_current = self.interpolant._rots_euler_step(
                        d_t, t_1, pred_rotmats_1, rotmats_current
                    )
                    t_1 = t_2
                rollout_batch["trans_t"] = trans_current
                rollout_batch["rotmats_t"] = rotmats_current
                rollout_batch["t"] = torch.ones((n, 1), device=device) * ts[-1]
                model_out = self.model(rollout_batch)
                return model_out["pred_trans"]
            finally:
                self.model.train(was_training)

        rollout_metrics = {}
        trace_target_scale = None
        if rollout_enabled:
            rollout_interval = int(
                getattr(self._exp_cfg.training, "generator_cov_rollout_interval_steps", 200)
            )
            rollout_interval = max(1, rollout_interval)
            should_measure = (
                self._gen_cov_rollout_trace_ratio_ema is None
                or int(getattr(self, "global_step", 0)) % rollout_interval == 0
            )
            if should_measure:
                # Default matches inference resolution (num_timesteps=20). This is a
                # no_grad forward-only measurement on a few proteins once per interval,
                # so there is no reason to under-resolve it; a coarse 2-step rollout
                # gives a systematically wrong amplification G.
                rollout_steps = int(
                    getattr(self._exp_cfg.training, "generator_cov_rollout_steps", 20)
                )
                rollout_steps = max(1, rollout_steps)
                rollout_num_deltas = int(
                    getattr(self._exp_cfg.training, "generator_cov_rollout_num_deltas", 1)
                )
                rollout_num_deltas = max(1, min(rollout_num_deltas, num_deltas))
                rollout_max_examples = int(
                    getattr(self._exp_cfg.training, "generator_cov_rollout_max_examples", 4)
                )
                rollout_max_examples = max(1, min(rollout_max_examples, batch_size))
                example_idx = torch.arange(
                    rollout_max_examples,
                    device=res_mask.device,
                    dtype=torch.long,
                )
                selected_mask = res_mask.index_select(0, example_idx)
                selected_lengths = selected_mask.float().sum(dim=-1)
                rollout_max_res = int(selected_lengths.max().detach().cpu().item())
                rollout_max_res = max(1, min(rollout_max_res, res_mask.shape[1]))
                with torch.inference_mode():
                    rollout_conditions = [
                        _slice_condition(cond, example_idx, max_res=rollout_max_res)
                        for cond in conditions[: 2 * rollout_num_deltas]
                    ]
                    rollout_condition = _concat_conditions(rollout_conditions)
                    rollout_base_batch = _slice_batch(
                        noisy_batch,
                        example_idx,
                        max_res=rollout_max_res,
                    )
                    # Start T_full from SHARED prior noise x0 (the real inference
                    # start), NOT from the training-time trans_t. trans_t is anchored
                    # to the ground-truth frame (corrupt_batch interpolates noise<->x_1),
                    # so rolling from it measures the c-response near the true frame,
                    # not the free-sampling response inference actually produces.
                    # Sampling x0 on the sliced base (before expand) makes +delta and
                    # -delta of the same example share the same x0 (supplement 1).
                    r_trans0, r_rotmats0 = self.interpolant.sample_from_prior(
                        rollout_max_examples,
                        rollout_max_res,
                        rollout_base_batch["trans_equilibrium"],
                        rollout_base_batch["rotmats_equilibrium"],
                    )
                    rollout_base_batch = dict(rollout_base_batch)
                    rollout_base_batch["trans_t"] = r_trans0
                    rollout_base_batch["rotmats_t"] = r_rotmats0
                    rollout_batch = _expand_batch(
                        rollout_base_batch,
                        repeats=len(rollout_conditions),
                    )
                    rollout_batch["z"] = rollout_condition
                    rollout_pred = _rollout_final_pred_trans(rollout_batch, rollout_steps)
                    rollout_pred = rollout_pred.reshape(
                        rollout_num_deltas, 2, rollout_max_examples, *rollout_pred.shape[1:]
                    )
                    rollout_plus = rollout_pred[:, 0].reshape(
                        rollout_num_deltas * rollout_max_examples,
                        *rollout_pred.shape[3:],
                    )
                    rollout_minus = rollout_pred[:, 1].reshape(
                        rollout_num_deltas * rollout_max_examples,
                        *rollout_pred.shape[3:],
                    )
                    rollout_trans_eq = trans_eq.index_select(0, example_idx)
                    rollout_trans_eq = rollout_trans_eq[:, :rollout_max_res, :]
                    rollout_res_mask = res_mask.index_select(0, example_idx)[:, :rollout_max_res]
                    rollout_trans_eq_rep = rollout_trans_eq[None].expand(
                        rollout_num_deltas, -1, -1, -1
                    ).reshape(
                        rollout_num_deltas * rollout_max_examples,
                        *rollout_trans_eq.shape[1:],
                    )
                    rollout_res_mask_rep = rollout_res_mask[None].expand(
                        rollout_num_deltas, -1, -1
                    ).reshape(
                        rollout_num_deltas * rollout_max_examples,
                        *rollout_res_mask.shape[1:],
                    )
                    rollout_disp_plus = self.latent_encoder.relative_displacement(
                        rollout_plus.float(),
                        rollout_trans_eq_rep.float(),
                        rollout_res_mask_rep,
                    )
                    rollout_disp_minus = self.latent_encoder.relative_displacement(
                        rollout_minus.float(),
                        rollout_trans_eq_rep.float(),
                        rollout_res_mask_rep,
                    )
                    rollout_response = 0.5 * (rollout_disp_plus - rollout_disp_minus)
                    rollout_response = rollout_response.reshape(
                        rollout_num_deltas,
                        rollout_max_examples,
                        *rollout_response.shape[1:],
                    )
                    rollout_weight = sample_weight.index_select(0, example_idx)
                    rollout_mask = rollout_res_mask.float() * rollout_weight[:, None].float()
                    one_step_trace = _response_trace(
                        response_deltas[:rollout_num_deltas].index_select(1, example_idx),
                        rollout_mask,
                    )
                    rollout_trace = _response_trace(rollout_response, rollout_mask)
                    valid = (rollout_mask.sum(dim=-1) > 0).float()
                    trace_ratio = (rollout_trace / one_step_trace).clamp_min(1e-8)
                    ratio_num = (trace_ratio * valid).sum()
                    ratio_den = valid.sum()
                    if dist.is_available() and dist.is_initialized():
                        ratio_num = ratio_num.detach().clone()
                        ratio_den = ratio_den.detach().clone()
                        dist.all_reduce(ratio_num, op=dist.ReduceOp.SUM)
                        dist.all_reduce(ratio_den, op=dist.ReduceOp.SUM)
                    if ratio_den.detach().item() > 0:
                        ratio_value = ratio_num / ratio_den.clamp_min(1.0)
                        ema_decay = float(
                            getattr(self._exp_cfg.training, "generator_cov_rollout_ema_decay", 0.9)
                        )
                        ema_decay = min(max(ema_decay, 0.0), 0.999)
                        if self._gen_cov_rollout_trace_ratio_ema is None:
                            self._gen_cov_rollout_trace_ratio_ema = ratio_value.detach()
                        else:
                            self._gen_cov_rollout_trace_ratio_ema = (
                                ema_decay * self._gen_cov_rollout_trace_ratio_ema.to(ratio_value.device)
                                + (1.0 - ema_decay) * ratio_value.detach()
                            )
                        rollout_metrics["gen_rollout_trace_ratio"] = ratio_value.detach()
                        rollout_metrics["gen_rollout_trace_measured"] = ratio_value.new_tensor(1.0)
                        rollout_metrics["gen_rollout_trace_steps"] = ratio_value.new_tensor(
                            float(rollout_steps)
                        )
                        rollout_metrics["gen_rollout_batch"] = ratio_value.new_tensor(
                            float(2 * rollout_num_deltas * rollout_max_examples)
                        )
                        rollout_metrics["gen_rollout_num_res"] = ratio_value.new_tensor(
                            float(rollout_max_res)
                        )
            if self._gen_cov_rollout_trace_ratio_ema is not None:
                ema_ratio = self._gen_cov_rollout_trace_ratio_ema.to(res_mask.device).clamp_min(1e-8)
                trace_target_scale = (1.0 / ema_ratio).detach().reshape(1)
                rollout_metrics["gen_rollout_trace_ratio_ema"] = ema_ratio.detach()
                rollout_metrics["gen_rollout_trace_target_scale"] = trace_target_scale.detach()[0]
            else:
                trace_target_scale = res_mask.new_tensor([1.0])
                rollout_metrics["gen_rollout_trace_ratio_ema"] = res_mask.new_tensor(1.0)
                rollout_metrics["gen_rollout_trace_target_scale"] = res_mask.new_tensor(1.0)
            if "gen_rollout_trace_measured" not in rollout_metrics:
                rollout_metrics["gen_rollout_trace_measured"] = res_mask.new_tensor(0.0)

        teacher_response_deltas = None
        if teacher_model is not None:
            with torch.no_grad():
                if teacher_reuse_student_delta:
                    teacher_conditions = conditions[: 2 * teacher_num_deltas]
                else:
                    teacher_conditions = []
                    for _ in range(teacher_num_deltas):
                        c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition)
                        c_sample = c_sample.detach().float()
                        delta = (c_sample - mu_bar) * scale
                        c_plus = mu_bar + delta
                        c_minus = mu_bar - delta
                        teacher_conditions.append(
                            self.latent_encoder.condition_from_mode_coefficients(
                                u_global, c_plus, rotmats_eq, res_mask, include_statistics=False
                            )
                        )
                        teacher_conditions.append(
                            self.latent_encoder.condition_from_mode_coefficients(
                                u_global, c_minus, rotmats_eq, res_mask, include_statistics=False
                            )
                        )
                teacher_condition = _concat_conditions(teacher_conditions)
                teacher_batch = _expand_batch(noisy_batch, repeats=len(teacher_conditions))
                teacher_batch["z"] = teacher_condition
                teacher_pred = teacher_model(teacher_batch)["pred_trans"]
                teacher_pred = teacher_pred.reshape(
                    teacher_num_deltas, 2, batch_size, *teacher_pred.shape[1:]
                )
                teacher_plus = teacher_pred[:, 0].reshape(
                    teacher_num_deltas * batch_size, *teacher_pred.shape[3:]
                )
                teacher_minus = teacher_pred[:, 1].reshape(
                    teacher_num_deltas * batch_size, *teacher_pred.shape[3:]
                )
                teacher_trans_eq_rep = trans_eq[None].expand(
                    teacher_num_deltas, -1, -1, -1
                ).reshape(teacher_num_deltas * batch_size, *trans_eq.shape[1:])
                teacher_res_mask_rep = res_mask[None].expand(
                    teacher_num_deltas, -1, -1
                ).reshape(teacher_num_deltas * batch_size, *res_mask.shape[1:])
                teacher_disp_plus = self.latent_encoder.relative_displacement(
                    teacher_plus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep
                )
                teacher_disp_minus = self.latent_encoder.relative_displacement(
                    teacher_minus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep
                )
                teacher_response_deltas = 0.5 * (teacher_disp_plus - teacher_disp_minus)
                teacher_response_deltas = teacher_response_deltas.reshape(
                    teacher_num_deltas, batch_size, *teacher_response_deltas.shape[1:]
                )

        losses, metrics = self.latent_encoder.generator_response_cov_loss(
            response_deltas,
            res_mask=res_mask,
            targets=targets,
            use_cross=use_cross,
            sample_weight=sample_weight,
            teacher_response_deltas=teacher_response_deltas,
            teacher_trace_anchor=cached_teacher_trace,
            teacher_trace_denominator=teacher_trace_denominator,
            amplitude_anchor=amplitude_anchor,
            trace_target_scale=trace_target_scale,
            oracle_rank=oracle_rank,
        )
        w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0))
        w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0))
        w_oracle = oracle_weight
        w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05))
        # Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs.
        # Slamming the calibrated anchor to full on epoch 0 drove the condition to MD
        # amplitude too fast and collapsed the latent mode geometry (max_cos -> 0.99,
        # gram_condition -> 1e13) into a NaN q-head by epoch 3. Ramping lets the latent
        # settle before the amplitude drive reaches full. 0 disables the ramp.
        anchor_warmup = int(getattr(self._exp_cfg.training, "gen_trace_anchor_warmup_epochs", 0))
        if anchor_warmup > 0:
            w_anchor = w_anchor * min(
                1.0, float(getattr(self, "current_epoch", 0)) / float(anchor_warmup)
            )
        total = w_local * losses["gen_local_shape_loss"]
        if use_cross and "gen_cross_shape_loss" in losses:
            total = total + w_cross * losses["gen_cross_shape_loss"]
        oracle_weighted = None
        if "gen_oracle_shape_loss" in losses:
            oracle_weighted = w_oracle * losses["gen_oracle_shape_loss"]
            total = total + oracle_weighted
        if "gen_trace_anchor_loss" in losses:
            total = total + w_anchor * losses["gen_trace_anchor_loss"]
        weighted = lambda_gen * total
        out_metrics = {key: value.detach() for key, value in losses.items()}
        out_metrics.update(metrics)
        out_metrics.update(rollout_metrics)
        # The only number that proves the oracle term reached the backward. The
        # unweighted loss says nothing about its weight, `gen_oracle_active_frac`
        # says nothing about either, and `gen_cov_loss` may be entirely the local
        # term.
        if oracle_weighted is not None:
            out_metrics["gen_oracle_weighted_loss"] = (
                lambda_gen * oracle_weighted
            ).detach()
        out_metrics["gen_cov_loss"] = weighted.detach()
        return weighted, out_metrics

    def _condition_probe_metrics(self, noisy_batch, model_output, condition):
        if condition is None or not isinstance(condition, dict):
            return {}
        enabled = bool(getattr(self._exp_cfg.training, "epoch_condition_probe", True))
        if not enabled or self._condition_probe_epoch == int(self.current_epoch):
            return {}
        self._condition_probe_epoch = int(self.current_epoch)
        scale = float(getattr(self._exp_cfg.training, "condition_probe_scale", 2.0))
        with torch.no_grad():
            zero_batch = dict(noisy_batch)
            zero_batch["z"] = self._condition_with_scale(condition, 0.0)
            zero_output = self.model(zero_batch)
            scaled_batch = dict(noisy_batch)
            scaled_batch["z"] = self._condition_with_scale(condition, scale)
            scaled_output = self.model(scaled_batch)
            pred = model_output["pred_trans"].detach().float()
            denom = pred.abs().mean().clamp_min(1e-8)
            zero_delta = (pred - zero_output["pred_trans"].detach().float()).abs().mean()
            scaled_delta = (scaled_output["pred_trans"].detach().float() - pred).abs().mean()
        return {
            "condition_zero_pred_trans_delta": zero_delta.detach(),
            "condition_zero_pred_trans_delta_rel": (zero_delta / denom).detach(),
            "condition_scaled_pred_trans_delta": scaled_delta.detach(),
            "condition_scaled_pred_trans_delta_rel": (scaled_delta / denom).detach(),
        }

    def _z_separability(self, z_sample, group_index, groups):
        with torch.no_grad():
            z_group, _ = self.latent_encoder._group_mean(z_sample, group_index)
            if z_group.shape[0] < 2:
                return None
            between = torch.pdist(z_group.float(), p=2)
            if between.numel() == 0:
                return None
            within = []
            for group in groups:
                members = z_sample[group_index == group]
                if members.shape[0] > 1:
                    within.append(torch.pdist(members.float(), p=2).mean())
            if not within:
                return None
            within_mean = torch.stack(within).mean().clamp_min(1e-8)
            return between.mean() / within_mean

    def on_train_epoch_end(self):
        if (
            getattr(self, "latent_enabled", False)
            and self.training_epoch_metrics
            and getattr(self, "global_rank", 0) == 0
        ):
            metric_names = sorted({
                key
                for batch_metrics in self.training_epoch_metrics
                for key in batch_metrics
            })
            train_epoch_dict = {}
            for key in metric_names:
                values = [
                    batch_metrics[key]
                    for batch_metrics in self.training_epoch_metrics
                    if key in batch_metrics
                ]
                train_epoch_dict[key] = float(
                    torch.stack(values).mean().detach().cpu().item()
                )
            train_epoch_dict["epoch"] = int(self.current_epoch)
            train_epoch_dict["global_step"] = int(self.global_step)
            train_epoch_dict["rank"] = int(self.global_rank)
            out_path = os.path.join(self._exp_cfg.checkpointer.dirpath, "latent_train_epoch_metrics.csv")
            os.makedirs(os.path.dirname(out_path), exist_ok=True)
            pd.DataFrame([train_epoch_dict]).to_csv(
                out_path,
                mode="a",
                header=not os.path.exists(out_path),
                index=False,
            )
            stage_name = epoch_summary_stage(train_epoch_dict)
            # Curated console watch-list: loss + <=5 decision-driving metrics, one per
            # line, each tagged with the wanted trend/range. The FULL metric set is
            # still written to latent_train_epoch_metrics.csv above; this only trims
            # the console noise so the few numbers that decide the run are readable.
            _watch = [
                ("official_loss",             "want ~0.85 stable; rising = backbone degrading"),
                ("mode_max_cosine_abs",       "want down <0.9; nearing 1 = about to diverge"),
                ("gen_response_abs_mean",     "want 0.1~0.5; ->0 = inert / blow-up = over-disperse"),
                ("gen_trace_ratio_to_anchor", "want ->1; response amplitude calibrating to MD"),
                ("cross_cov_far_corr",        "want up 0.1->0.2; PCA-W2 proxy"),
            ]
            _loss = train_epoch_dict.get("train_loss", float("nan"))
            _lines = [f"[epoch {int(self.current_epoch):03d} {stage_name}] loss={_loss:.4g}"]
            for _k, _hint in _watch:
                if _k in train_epoch_dict and pd.notna(train_epoch_dict[_k]):
                    _lines.append(f"    {_k}={train_epoch_dict[_k]:.4g}   [{_hint}]")
            print("\n".join(_lines), flush=True)
        self.training_epoch_metrics = []
        self._grad_flow_reported = False
        return super().on_train_epoch_end()

    # ------------------------------------------------------------------
    # CMFM failure localization
    #
    # The gradient collapse is only observable per rank and per microbatch:
    # the rank-0/every-50-steps log cannot explain a rank-1 step-170 failure,
    # and gradient accumulation hides which microbatch poisoned the buffers.
    # These helpers record every candidate numerator/denominator and freeze the
    # exact failing microbatch to disk. Nothing here clips, skips, or rescales.
    # ------------------------------------------------------------------

    CMFM_NUMERICS_FIELDS = (
        "prior_hidden_abs_max",
        "prior_raw_mode_abs_max",
        "prior_raw_mode_rms_min",
        "prior_raw_mode_rms_max",
        "prior_mode_norm_min",
        "prior_mode_norm_max",
        "prior_q_mu_abs_max",
        "prior_q_scale_abs_max",
        "prior_qr_diag_abs_min",
        "prior_qr_rel_diag_min",
        "prior_qr_condition_max",
        "collective_target_variance_min",
        "collective_target_variance_max",
        "collective_retained_fraction",
        "collective_observed_target_variance_min",
        "collective_observed_target_variance_max",
        "collective_covariance_scale_min",
        "collective_covariance_inverse_scale_max",
        "collective_target_cov_rate_absmax",
        "collective_predicted_cov_rate_absmax",
        "collective_covariance_error_absmax",
        "collective_z_t_absmax",
        "collective_z_target_absmax",
        "collective_target_velocity_absmax",
        "collective_predicted_velocity_absmax",
        "collective_update_abs",
        "collective_update_absmax",
    )

    def _cmfm_debug_dir(self):
        path = os.path.join(
            str(self._exp_cfg.trainer.default_root_dir), "cmfm_failure_dumps"
        )
        os.makedirs(path, exist_ok=True)
        return path

    def _record_cmfm_numerics(
        self,
        latent_metrics,
        official_loss,
        shape_recon_loss,
        collective_loss,
        group_diagnostics,
        noisy_batch,
    ):
        """Append one row per rank per microbatch to cmfm_numerics_rank{r}.csv."""
        microbatch = int(getattr(self, "_cmfm_microbatch_index", 0))
        self._cmfm_microbatch_index = microbatch + 1

        available = [name for name in self.CMFM_NUMERICS_FIELDS if name in latent_metrics]
        values = torch.stack([
            latent_metrics[name].detach().float().reshape(()) for name in available
        ] + [
            official_loss.detach().float().reshape(()),
            shape_recon_loss.detach().float().reshape(()),
            collective_loss.detach().float().reshape(()),
        ]).cpu().tolist()
        metrics = dict(zip(list(available) + ["official", "latent", "collective"], values))
        for name in self.CMFM_NUMERICS_FIELDS:
            metrics.setdefault(name, float("nan"))

        pdb_names = noisy_batch.get("pdb_name")
        time_values = noisy_batch["t"].detach().float().reshape(-1)
        row = {
            "rank": int(self.global_rank),
            "epoch": int(self.current_epoch),
            "global_step": int(self.global_step),
            "microbatch": microbatch,
            "num_particles": int(noisy_batch["res_mask"].shape[0]),
            "num_res": int(noisy_batch["res_mask"].shape[1]),
            "pdb_name": None if pdb_names is None else str(pdb_names[0]),
            "t_min": float(time_values.min().item()),
            "t_max": float(time_values.max().item()),
            "num_groups": len(group_diagnostics),
            **metrics,
        }
        numerics_path = os.path.join(
            str(self._exp_cfg.trainer.default_root_dir),
            f"cmfm_numerics_rank{int(self.global_rank)}.csv",
        )
        pd.DataFrame([row]).to_csv(
            numerics_path,
            mode="a",
            header=not os.path.exists(numerics_path),
            index=False,
        )

        message = (
            "[cmfm-numerics] "
            f"rank={row['rank']} epoch={row['epoch']} step={row['global_step']} "
            f"micro={microbatch} pdb={row['pdb_name']} N={row['num_res']} "
            f"t=[{row['t_min']:.4g},{row['t_max']:.4g}] "
            f"h_max={metrics['prior_hidden_abs_max']:.4g} "
            f"raw_u_max={metrics['prior_raw_mode_abs_max']:.4g} "
            f"qr_rel_diag_min={metrics['prior_qr_rel_diag_min']:.4g} "
            f"qr_cond={metrics['prior_qr_condition_max']:.4g} "
            f"q_target_var=[{metrics['collective_target_variance_min']:.4g},"
            f"{metrics['collective_target_variance_max']:.4g}] "
            f"obs_target_var=[{metrics['collective_observed_target_variance_min']:.4g},"
            f"{metrics['collective_observed_target_variance_max']:.4g}] "
            f"cov_scale_min={metrics['collective_covariance_scale_min']:.4g} "
            f"cov_rate_absmax={metrics['collective_target_cov_rate_absmax']:.4g} "
            f"ctrl_update_absmax={metrics['collective_update_absmax']:.4g} "
            f"losses=[official:{metrics['official']:.4g},"
            f"latent:{metrics['latent']:.4g},"
            f"collective:{metrics['collective']:.4g}]"
        )
        interval = int(getattr(
            self._exp_cfg.training, "cmfm_numerics_log_interval", 50
        ))
        if microbatch < 5 or (interval > 0 and microbatch % interval == 0):
            logging.warning(message)
        self._cmfm_last_numerics_row = row
        self._cmfm_last_numerics_message = message
        self._cmfm_last_group_diagnostics = [
            {
                key: (
                    float(value.detach().float().item())
                    if torch.is_tensor(value) else value
                )
                for key, value in entry.items()
            }
            for entry in group_diagnostics
        ]
        return metrics

    def _stash_cmfm_microbatch(self, noisy_batch, group_index):
        """Keep a CPU copy of the current microbatch so a failure can be replayed."""
        if not bool(getattr(self._exp_cfg.training, "cmfm_capture_failure", True)):
            self._cmfm_last_microbatch = None
            return
        tensors = {}
        for key, value in noisy_batch.items():
            if key == "z":
                continue
            if torch.is_tensor(value):
                tensors[key] = value.detach().to("cpu").clone()
            elif isinstance(value, (list, tuple)) and all(
                isinstance(item, str) for item in value
            ):
                tensors[key] = list(value)
        tensors["group_index"] = group_index.detach().to("cpu").clone()
        self._cmfm_last_microbatch = tensors

    def _cmfm_grad_guard(self):
        """Fail on the first microbatch whose backward produced non-finite grads."""
        if not bool(getattr(self._exp_cfg.training, "cmfm_grad_guard", True)):
            return
        graded = [
            (name, param.grad.detach())
            for name, param in self.named_parameters()
            if param.grad is not None
        ]
        if not graded:
            return
        # One device sync for the whole check; the per-parameter walk only runs
        # once the step is already known to be lost.
        if bool(torch.stack([
            torch.isfinite(grad).all() for _, grad in graded
        ]).all()):
            return
        nonfinite_names = [
            name for name, grad in graded if not bool(torch.isfinite(grad).all())
        ]

        dump_path = self._dump_cmfm_failure(nonfinite_names)
        preview = ", ".join(nonfinite_names[:8])
        if len(nonfinite_names) > 8:
            preview += f", ... (+{len(nonfinite_names) - 8} more)"
        raise FloatingPointError(
            "non-finite gradients after backward on a single CMFM microbatch "
            f"(rank={self.global_rank}, epoch={self.current_epoch}, "
            f"global_step={self.global_step}, "
            f"microbatch={int(getattr(self, '_cmfm_microbatch_index', 0)) - 1}, "
            f"nonfinite_parameters={len(nonfinite_names)}, [{preview}]); "
            f"failure dump written to {dump_path}"
        )

    def _dump_cmfm_failure(self, nonfinite_names):
        """Freeze the failing microbatch, its numerics, and the pre-step weights."""
        directory = self._cmfm_debug_dir()
        microbatch = int(getattr(self, "_cmfm_microbatch_index", 0)) - 1
        stem = (
            f"rank{int(self.global_rank)}_epoch{int(self.current_epoch)}"
            f"_step{int(self.global_step)}_micro{microbatch}"
        )
        batch = getattr(self, "_cmfm_last_microbatch", None)
        numerics_row = getattr(self, "_cmfm_last_numerics_row", None)
        group_diagnostics = getattr(self, "_cmfm_last_group_diagnostics", None)

        grad_summary = []
        for name, param in self.named_parameters():
            if param.grad is None:
                continue
            grad = param.grad.detach()
            finite = torch.isfinite(grad)
            grad_summary.append({
                "name": name,
                "nonfinite_elements": int((~finite).sum().item()),
                "elements": int(grad.numel()),
                "finite_absmax": float(
                    grad[finite].abs().max().item() if bool(finite.any()) else float("nan")
                ),
            })

        metadata = {
            "rank": int(self.global_rank),
            "world_size": int(getattr(self._trainer, "world_size", 1))
            if getattr(self, "_trainer", None) is not None else 1,
            "epoch": int(self.current_epoch),
            "global_step": int(self.global_step),
            "microbatch": microbatch,
            "precision": str(getattr(self._exp_cfg.trainer, "precision", "unknown")),
            "accumulate_grad_batches": int(
                getattr(self._exp_cfg.trainer, "accumulate_grad_batches", 1)
            ),
            "collective_rank": int(self.collective_rank),
            "checkpoint_dir": str(
                getattr(self._exp_cfg.checkpointer, "dirpath", "")
            ),
            "nonfinite_parameter_count": len(nonfinite_names),
            "nonfinite_parameters": nonfinite_names,
            "numerics": numerics_row,
            "group_diagnostics": group_diagnostics,
            "grad_summary": grad_summary,
        }
        if batch is not None:
            metadata["pdb_name"] = batch.get("pdb_name")
            for key in ("group_index", "conformation_idx", "trajectory_idx", "t"):
                if key in batch:
                    metadata[key] = batch[key].reshape(-1).tolist()

        json_path = os.path.join(directory, f"{stem}.json")
        with open(json_path, "w") as handle:
            json.dump(metadata, handle, indent=2, default=str)

        full_cfg = getattr(self, "_cfg", None)
        payload = {
            "metadata": metadata,
            "batch": batch,
            "config": (
                None if full_cfg is None
                else OmegaConf.to_container(full_cfg, resolve=True)
            ),
        }
        if bool(getattr(self._exp_cfg.training, "cmfm_dump_state_dict", True)):
            payload["state_dict"] = {
                name: tensor.detach().to("cpu").clone()
                for name, tensor in self.state_dict().items()
            }
        dump_path = os.path.join(directory, f"{stem}.pt")
        torch.save(payload, dump_path)
        logging.error(
            "[cmfm-failure] wrote %s and %s (%d non-finite parameter grads)",
            dump_path,
            json_path,
            len(nonfinite_names),
        )
        return dump_path

    def cmfm_debug_losses(self, noisy_batch):
        """Recompute official/latent/collective for an already-corrupted batch.

        Used by scripts/cmfm_replay_failure.py to backpropagate each component
        separately on the captured microbatch. It deliberately mirrors
        training_step instead of wrapping it so that no Trainer state is needed.
        """
        (
            z,
            group_index,
            latent_metrics,
            latent_regularizer,
            _,
        ) = self._latent_group_z(noisy_batch)
        noisy_batch = dict(noisy_batch)
        noisy_batch["z"] = z
        model_output = self._run_training_model(noisy_batch)
        collective_parts = collective_measure_dynamics_loss(
            noisy_batch["trans_t"],
            noisy_batch["trans_1"],
            model_output["pred_trans"],
            noisy_batch["trans_equilibrium"],
            noisy_batch["res_mask"],
            z["collective_basis_global"],
            group_index,
            noisy_batch["t"],
            t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip),
            target_covariance=self._collective_population_covariance(z),
            rate_weighted=self.collective_rate_weighted,
        )
        group_diagnostics = collective_parts.pop("collective_group_diagnostics", [])
        batch_losses = self.loss_fn(noisy_batch, model_output)
        official_loss = (
            torch.mean(batch_losses[self._exp_cfg.training.loss])
            + torch.mean(batch_losses["auxiliary_loss"])
        )
        # Sub-losses exposed individually. "official" is a sum of four terms with
        # very different numerics (a squared error, an SO(3) log map, and two
        # pairwise-distance terms), so attributing a non-finite backward to
        # "official" is not yet a location.
        official_subcomponents = {
            f"official:{name}": torch.mean(value)
            for name, value in batch_losses.items()
            if torch.is_tensor(value) and value.requires_grad
        }
        return {
            **official_subcomponents,
            "official": official_loss,
            "latent": float(
                getattr(self._exp_cfg.training, "lambda_shape", 1.0)
            ) * latent_regularizer,
            "collective": float(
                getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0)
            ) * collective_parts["collective_measure_loss"],
            "metrics": {
                key: value for key, value in latent_metrics.items()
            },
            "collective_parts": collective_parts,
            "group_diagnostics": group_diagnostics,
        }

    def on_before_optimizer_step(self, optimizer):
        parent_hook = getattr(super(), "on_before_optimizer_step", None)
        if parent_hook is not None:
            parent_hook(optimizer)
        if not getattr(self, "latent_enabled", False) or not self.collective_enabled:
            return

        training_grads = [
            (name, param.grad.detach())
            for name, param in self.named_parameters()
            if param.grad is not None
        ]
        if not training_grads:
            return
        all_finite = torch.stack([
            torch.isfinite(grad).all() for _, grad in training_grads
        ]).all()
        if bool(all_finite):
            return

        nonfinite_names = [
            name for name, grad in training_grads
            if not bool(torch.isfinite(grad).all())
        ]
        preview = ", ".join(nonfinite_names[:8])
        if len(nonfinite_names) > 8:
            preview += f", ... (+{len(nonfinite_names) - 8} more)"
        raise FloatingPointError(
            "non-finite training gradients before optimizer step; refusing to update "
            f"corrupted parameters (rank={self.global_rank}, "
            f"epoch={self.current_epoch}, global_step={self.global_step}, "
            f"parameters=[{preview}])"
        )

    def _grad_norm_for_prefixes(self, prefixes):
        total = 0.0
        count = 0
        for name, param in self.named_parameters():
            if not any(name.startswith(prefix) or prefix in name for prefix in prefixes):
                continue
            if param.grad is None:
                continue
            total += float(param.grad.detach().float().norm().cpu().item())
            count += 1
        return total, count

    def on_after_backward(self):
        parent_hook = getattr(super(), "on_after_backward", None)
        if parent_hook is not None:
            parent_hook()
        if not getattr(self, "latent_enabled", False):
            return
        if self.collective_enabled:
            # Runs on every rank and every microbatch, i.e. before accumulation
            # can smear the first bad microbatch across the whole window.
            self._cmfm_grad_guard()
        if self._grad_flow_reported:
            return
        if int(getattr(self, "global_step", 0)) != 0 or getattr(self, "global_rank", 0) != 0:
            return
        if not bool(getattr(self._exp_cfg.training, "grad_flow_check", False)):
            return
        groups = {
            "bbflow_backbone": ["model."],
            "prior_template_head": ["latent_encoder.template_"],
            "prior_energy_head": ["latent_encoder.energy_out"],
            "prior_mixture_head": ["latent_encoder.mixture_"],
            "collective_controller": ["model.collective_controller"],
            "condition_adapters_film": [
                "model.embedder.z_node_adapter",
                "model.embedder.z_edge_adapter",
                "model.embedder.disp_node_adapter",
                "model.embedder.disp_edge_adapter",
                "model.film_mlp",
            ],
        }
        rows = []
        for group_name, prefixes in groups.items():
            norm, count = self._grad_norm_for_prefixes(prefixes)
            rows.append(f"{group_name}:grad_norm={norm:.4g}:params_with_grad={count}")
        print("[grad-flow-check] " + ", ".join(rows), flush=True)
        self._grad_flow_reported = True
    def _condition_usage_ranking_loss(self, noisy_batch, z, ell_pos):
        """Contrastive 'the generator must USE c'. Same X_t: the correct c must give a
        LOWER flow error than a WRONG c (another batch item's c, SAME modes). If the
        model ignores c then ell_pos ~= ell_neg and this loss cannot be reduced -> it
        forces c to matter. Cost: one extra forward on a fraction of steps (no 20-step
        rollout). ell_pos is detached (the main flow loss already trains it); the
        gradient here only pushes the wrong-c error UP. Off by default (lambda=0).

        NOTE: this is the single-step 'c is used' signal. It does NOT guarantee the
        20-step endpoint recovers c (that is the drift/terminal-calibration question);
        keep measuring c* vs c_hat_20 separately.
        """
        lam = float(getattr(self._exp_cfg.training, "lambda_condition_usage", 0.0))
        if lam <= 0.0 or not isinstance(z, dict) or "mode_coefficients" not in z:
            return noisy_batch["res_mask"].new_zeros(())
        frac = float(getattr(self._exp_cfg.training, "condition_usage_frac", 0.15))
        B = int(noisy_batch["res_mask"].shape[0])
        if B < 2 or random.random() > frac:
            return noisy_batch["res_mask"].new_zeros(())
        perm = torch.roll(torch.arange(B, device=noisy_batch["res_mask"].device), shifts=1)
        coeff_neg = z["mode_coefficients"][perm]  # wrong coefficients, SAME modes/subspace
        with torch.autocast(device_type="cuda", enabled=False):
            z_neg = self.latent_encoder.condition_from_mode_coefficients(
                z["u_global"].float(),
                coeff_neg.float(),
                noisy_batch["rotmats_equilibrium"],
                noisy_batch["res_mask"],
                include_statistics=False,
            )
        neg_batch = dict(noisy_batch)
        neg_batch["z"] = z_neg
        neg_batch.pop("trans_sc", None)  # no self-conditioning leakage from the + path
        neg_out = self.model(neg_batch)
        neg_losses = self.loss_fn(neg_batch, neg_out)
        ell_neg = torch.mean(
            neg_losses[self._exp_cfg.training.loss] + neg_losses["auxiliary_loss"]
        )
        margin = float(getattr(self._exp_cfg.training, "condition_usage_margin", 0.0))
        return lam * torch.clamp(margin + ell_pos.detach() - ell_neg, min=0.0)

    def _run_training_model(self, noisy_batch):
        collective_chunk_size = int(
            getattr(
                self._exp_cfg.training,
                "collective_backbone_chunk_size",
                0,
            )
        )
        if self.collective_enabled and collective_chunk_size > 0:
            return self.model.forward_chunked(
                noisy_batch,
                chunk_size=collective_chunk_size,
                checkpoint_chunks=True,
            )

        use_checkpoint = bool(
            self.training
            and torch.is_grad_enabled()
            and bool(getattr(self._exp_cfg.training, "full_model_activation_checkpoint", False))
        )
        if not use_checkpoint:
            return self.model(noisy_batch)

        def model_forward(batch):
            return self.model(batch)

        return torch.utils.checkpoint.checkpoint(
            model_forward,
            noisy_batch,
            use_reentrant=False,
        )

    def training_step(self, batch: Any, stage: int):
        step_start_time = time.time()
        self.interpolant.set_device(batch['res_mask'].device)
        # Lightning bf16 autocast wraps training_step; OT/Kabsch/SVD/linalg.det need fp32.
        # Keep rigid-body corruption in fp32, but let the learned latent prior
        # use the trainer mixed-precision context. Its pairwise message passing
        # is checkpointed inside LatentEncoder.
        with torch.autocast(device_type="cuda", enabled=False):
            shared_time = self._collective_shared_time(batch) if self.collective_enabled else None
            noisy_batch = self.interpolant.corrupt_batch(batch, t=shared_time)

        if getattr(self, "latent_enabled", False):
            (
                z,
                group_index,
                latent_metrics,
                shape_recon_loss,
                shape_baseline_error,
            ) = self._latent_group_z(noisy_batch)
        else:
            z = None
            group_index = torch.arange(
                noisy_batch["res_mask"].shape[0],
                device=noisy_batch["res_mask"].device,
                dtype=torch.long,
            )
            latent_metrics = {}
            shape_recon_loss = noisy_batch["res_mask"].new_zeros(())
            shape_baseline_error = noisy_batch["res_mask"].new_zeros(())

        if z is not None:
            noisy_batch["z"] = z

        log_latent_batch_debug = bool(
            getattr(self._exp_cfg.training, "log_latent_batch_debug", False)
        )
        should_log_latent_batch = bool(
            log_latent_batch_debug
            and getattr(self, "global_rank", 0) == 0
            and not getattr(self, "_latent_batch_debug_logged", False)
        )
        if should_log_latent_batch:
            groups_unique, group_counts = torch.unique(
                group_index.detach().cpu(),
                sorted=True,
                return_counts=True,
            )
            logging.info(
                "latent batch before forward | rank=%s step=%s B=%s N=%s groups=%s group_sizes=%s precision=%s",
                getattr(self, "global_rank", 0),
                int(self.global_step),
                int(noisy_batch["res_mask"].shape[0]),
                int(noisy_batch["res_mask"].shape[1]),
                int(groups_unique.numel()),
                group_counts.tolist(),
                str(getattr(self._exp_cfg.trainer, "precision", "32-true")),
            )
            self._latent_batch_debug_logged = True

        if self._interpolant_cfg.self_condition and random.random() > 0.5:
            with torch.no_grad():
                model_sc = self._run_training_model(noisy_batch)
                noisy_batch['trans_sc'] = model_sc['pred_trans']

        model_output = self._run_training_model(noisy_batch)
        if z is not None:
            latent_metrics.update(self._condition_probe_metrics(noisy_batch, model_output, z))
        condition_cycle_loss, condition_cycle_metrics = self._condition_cycle_loss(
            noisy_batch,
            model_output,
            z,
        )
        latent_metrics.update(condition_cycle_metrics)
        gen_cov_loss, gen_cov_metrics = self._generator_response_cov_loss(noisy_batch, z)
        latent_metrics.update(gen_cov_metrics)
        if self.collective_enabled:
            collective_parts = collective_measure_dynamics_loss(
                noisy_batch["trans_t"],
                noisy_batch["trans_1"],
                model_output["pred_trans"],
                noisy_batch["trans_equilibrium"],
                noisy_batch["res_mask"],
                z["collective_basis_global"],
                group_index,
                noisy_batch["t"],
                t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip),
                target_covariance=self._collective_population_covariance(z),
                rate_weighted=self.collective_rate_weighted,
            )
            collective_loss = collective_parts["collective_measure_loss"]
            collective_group_diagnostics = collective_parts.pop(
                "collective_group_diagnostics", []
            )
            latent_metrics.update({
                key: value.detach() for key, value in collective_parts.items()
            })
            collective_update = model_output["collective_update_global"].detach().float()
            latent_metrics["collective_update_abs"] = collective_update.abs().mean()
            latent_metrics["collective_update_absmax"] = collective_update.abs().amax()
        else:
            collective_group_diagnostics = []
            collective_loss = model_output["pred_trans"].new_zeros(())
        batch_losses = self.loss_fn(noisy_batch, model_output)
        num_batch = batch_losses['bb_atom_loss'].shape[0]
        total_losses = {
            k: torch.mean(v) for k,v in batch_losses.items()
        }

        official_loss = (
            total_losses[self._exp_cfg.training.loss]
            +  total_losses['auxiliary_loss']
        )
        condition_usage_loss = self._condition_usage_ranking_loss(noisy_batch, z, official_loss)
        train_loss = (
            official_loss
            + float(getattr(self._exp_cfg.training, "lambda_shape", 1.0)) * shape_recon_loss
            + condition_cycle_loss
            + gen_cov_loss
            + condition_usage_loss
            + float(getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0))
            * collective_loss
        )

        nonfinite_detected = (~torch.isfinite(train_loss)).float()
        if self.trainer.world_size > 1:
            dist.all_reduce(nonfinite_detected, op=dist.ReduceOp.SUM)

        if nonfinite_detected > 0:
            raise FloatingPointError(
                "non-finite training loss; refusing to skip a corrupted CMFM step "
                f"(rank={self.global_rank}, epoch={self.current_epoch}, "
                f"global_step={self.global_step}, "
                f"official={official_loss.detach().float().item():.6g}, "
                f"latent={shape_recon_loss.detach().float().item():.6g}, "
                f"collective={collective_loss.detach().float().item():.6g})"
            )

        if self.collective_enabled:
            self._record_cmfm_numerics(
                latent_metrics,
                official_loss,
                shape_recon_loss,
                collective_loss,
                collective_group_diagnostics,
                noisy_batch,
            )
            self._stash_cmfm_microbatch(noisy_batch, group_index)

        for k,v in total_losses.items():
            self._log_scalar(
                f"train/{k}", v, prog_bar=False, batch_size=num_batch)

        self._log_scalar("train/official_loss", official_loss, prog_bar=False, batch_size=num_batch)
        self._log_scalar("train/shape_recon_loss", shape_recon_loss, prog_bar=False, batch_size=num_batch)
        self._log_scalar("train/shape_baseline_error", shape_baseline_error, prog_bar=False, batch_size=num_batch)
        self._log_scalar("train/condition_usage_loss", condition_usage_loss, prog_bar=False, batch_size=num_batch)
        for metric_name, metric_value in latent_metrics.items():
            self._log_scalar(f"train/{metric_name}", metric_value, prog_bar=False, batch_size=num_batch)

        def detached_scalar(value):
            if torch.is_tensor(value):
                return value.detach().float().mean()
            return train_loss.detach().new_tensor(float(value), dtype=torch.float32)

        batch_metrics = {
            k: detached_scalar(v) for k, v in total_losses.items()
        }
        batch_metrics.update({
            "official_loss": detached_scalar(official_loss),
            "shape_recon_loss": detached_scalar(shape_recon_loss),
            "shape_baseline_error": detached_scalar(shape_baseline_error),
            "train_loss": detached_scalar(train_loss),
        })
        batch_metrics.update({
            k: detached_scalar(v) for k, v in latent_metrics.items()
        })

        t = torch.squeeze(noisy_batch['t'])
        self._log_scalar(
            "train/t", t.detach().float().mean(),
            prog_bar=False, batch_size=num_batch)

        if self._exp_cfg.training.t_bins > 1 and self._diagnostic_step():
            for loss_name, loss_dict in batch_losses.items():
                stratified_losses = mu.t_stratified_loss(
                    t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name)
                batch_metrics.update({
                    k: detached_scalar(v) for k, v in stratified_losses.items()
                })

                for k,v in stratified_losses.items():
                    self._log_scalar(
                        f"train/{k}", v, prog_bar=False, batch_size=num_batch)

        self.training_epoch_metrics.append(batch_metrics)

        self._log_scalar(
            "train/length", float(batch['res_mask'].shape[1]), prog_bar=False, batch_size=num_batch)
        self._log_scalar(
            "train/batch_size", float(num_batch), prog_bar=False)
        step_time = time.time() - step_start_time
        self._log_scalar(
            "train/examples_per_second", num_batch / step_time)
        self._log_scalar(
            "train/loss", train_loss, batch_size=num_batch)

        if self._exp_cfg.use_wandb:
            wandb_logs = {}
            time_indices = torch.bucketize(noisy_batch["t"].detach().cpu(), self._time_bins)
            time_indices_unique, counts = torch.unique(time_indices-1, return_counts=True)
            time_indices_unique[time_indices_unique < 0] = 0
            self._time_histogram[time_indices_unique] += counts
            wandb_logs["sampled_time_cumulative"] = wandb.Histogram(
                np_histogram=((
                    (self._time_histogram/self._time_histogram.sum()).numpy(),
                    self._time_bins.numpy()
                ))
            )
            time_histogram_step = torch.zeros(self._time_histogram.shape)
            time_histogram_step[time_indices_unique] += counts
            wandb_logs["sampled_time_per_step"] = wandb.Histogram(
                np_histogram=((
                    (time_histogram_step/time_histogram_step.sum()).numpy(),
                    self._time_bins.numpy()
                ))
            )
            self.logger.experiment.log(wandb_logs)

        return train_loss

    def configure_optimizers(self):
        if not getattr(self, "latent_enabled", False):
            return super().configure_optimizers()

        params = [p for p in list(self.model.parameters()) + list(self.latent_encoder.parameters()) if p.requires_grad]
        if getattr(self, "global_rank", 0) == 0 and bool(getattr(self._exp_cfg.training, "log_optimizer_coverage", True)):
            num_params = sum(p.numel() for p in params)
            print(f"[optimizer-coverage] trainable_tensors={len(params)} trainable_params={num_params}", flush=True)
        if not self._exp_cfg.scheduler.enabled:
            return torch.optim.AdamW(
                params=params,
                **self._exp_cfg.optimizer,
            )
        optimizer = torch.optim.AdamW(
            params=params,
            **self._exp_cfg.optimizer,
        )
        scheduler = torch.optim.lr_scheduler.LambdaLR(
            optimizer,
            lr_lambda=self.lr_lambda
        )
        return [optimizer], [scheduler]
    

    def predict_step(self, batch, batch_idx):
        device = f'cuda:{torch.cuda.current_device()}'
        interpolant = InterpolantBBFlow(self._infer_cfg.interpolant) 
        interpolant.set_device(device)
        
        pdb_dir = os.path.join(self._output_dir, batch["pdb_name"][0])
        if os.path.exists(os.path.join(pdb_dir, "sampled_conformations.pdb")):
            print(f"Skipping {batch['pdb_name']} as it already exists")
            return
        os.makedirs(pdb_dir, exist_ok=True)

        sample_time_start = datetime.now()

        N = batch["trans_equilibrium"].shape[1]
        requested_batch_size = int(self._infer_cfg.samples.batch_size)
        batch_size = self._infer_cfg.samples.num_res_squared / N**2
        batch_size = max(
            1,
            min(
                requested_batch_size,
                int(batch_size/5)*5
            )
        )
        if self.collective_enabled:
            if batch_size != requested_batch_size:
                raise ValueError(
                    f"CMFM requested joint group size {requested_batch_size}, but the "
                    f"length-based sampler reduced it to {batch_size} for N={N}. "
                    "Increase inference.samples.num_res_squared; CMFM does not shrink groups."
                )
            if batch_size <= self.collective_rank:
                raise ValueError(
                    f"CMFM inference batch_size={batch_size} must exceed "
                    f"collective_rank={self.collective_rank}"
                )
            if int(self._infer_cfg.samples.samples_per_protein) % batch_size != 0:
                raise ValueError(
                    "CMFM samples_per_protein must be divisible by the joint group size"
                )

        sampled_conformations = self._sample_multiple(
            batch["trans_equilibrium"],
            batch["rotmats_equilibrium"],
            batch["seq"],
            self._infer_cfg.samples.samples_per_protein,
            batch_size,
            interpolant,
            pdb_dir=pdb_dir if self._infer_cfg.save_traj else None
        )

        sample_time = (datetime.now()-sample_time_start).total_seconds()

        aatype = batch["seq"][0].argmax(-1).cpu().numpy()

        samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb')
        au.write_prot_to_pdb(
            sampled_conformations,
            samples_path,
            aatype=aatype,
            no_indexing=True
        )

        if bool(getattr(self._infer_cfg, "postprocess_bfactors", True)):
            confs = mdtraj.load(samples_path)
            avg = np.mean(confs.xyz, axis=0)
            avg -= np.mean(avg[confs.top.select("name CA")], axis=0, keepdims=True)
            avg = mdtraj.Trajectory(avg[None, :, :], confs.top)
            confs = confs.superpose(avg)
            rmsf = mdtraj.rmsf(confs, avg)
            confs.save_pdb(samples_path, bfactors=rmsf)


        if not self._infer_cfg.single_file:
            os.makedirs(os.path.join(pdb_dir, "samples"))
            confs = mdtraj.load(samples_path)
            for i in range(len(confs)):
                single_sample_path = os.path.join(pdb_dir, "samples", f"sample_{i}.pdb")
                confs[i].save(single_sample_path)

            os.remove(samples_path)


        if self._infer_cfg.log_times:
            self._print_logger.info(f"Generating time for {batch['pdb_name']} for {self._infer_cfg.samples.samples_per_protein} samples of length {N}: {sample_time}s")
            sample_time = (datetime.now()-sample_time_start).total_seconds()
            self._print_logger.info(f"Time with pdb saving and plotting: {sample_time}s")