File size: 98,563 Bytes
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
import math

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint

from bbflow.data.alignment import kabsch_align
from bbflow.models.collective import (
    mixture_mean_and_covariance,
    mixture_mean_and_covariance_factor,
    physical_low_rank_target,
)

class _MotionPriorBlock(nn.Module):
    """Single edge/node message passing block for the motion prior."""

    def __init__(self, hidden_dim):
        super().__init__()
        self.edge_norm = nn.LayerNorm(3 * hidden_dim)
        self.node_norm = nn.LayerNorm(2 * hidden_dim)
        self.edge_update = nn.Sequential(
            nn.Linear(3 * hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
        )
        self.node_update = nn.Sequential(
            nn.Linear(2 * hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
        )

    def forward(self, node_state, edge_state, pair_mask):
        pair_mask = pair_mask[..., None]
        masked_edge = edge_state * pair_mask

        src = node_state[:, :, None, :].expand(-1, -1, node_state.shape[1], -1)
        dst = node_state[:, None, :, :].expand(-1, node_state.shape[1], -1, -1)

        edge_input = torch.cat([masked_edge, src, dst], dim=-1)
        edge_state = edge_state + self.edge_update(self.edge_norm(edge_input))
        edge_state = edge_state * pair_mask

        node_mask = pair_mask.squeeze(-1).sum(dim=2).clamp_min(1.0)[..., None]
        incoming = (edge_state * pair_mask).sum(dim=2) / node_mask
        outgoing = (edge_state * pair_mask).sum(dim=1) / node_mask
        node_input = torch.cat([incoming, outgoing], dim=-1)
        node_state = node_state + self.node_update(self.node_norm(node_input))
        return node_state, edge_state


class LatentEncoder(nn.Module):
    """Equilibrium-conditioned template-mode motion prior.

    The prior predicts K global template motion fields from x_eq. Each mode has a
    shared template generated by omega/v/center plus signed per-residue participation
    and a small local-frame residual. The resulting modes reconstruct local/cross
    covariance targets and provide node/edge conditions for BBFlow adapters.
    """

    def __init__(self, latent_cfg):
        super().__init__()
        self.dim = int(getattr(latent_cfg, "dim", 16))
        self.num_modes = int(getattr(latent_cfg, "num_modes", 8))
        self.node_cond_dim = self.num_modes
        self.edge_cond_dim = self.num_modes
        self.z_stochastic = False
        hidden_dim = int(getattr(latent_cfg, "motion_hidden_dim", 128))
        dist_bins = int(getattr(latent_cfg, "motion_dist_bins", 16))
        self.register_buffer("dist_centers", torch.linspace(0.0, 40.0, dist_bins))
        self.dist_width = float(getattr(latent_cfg, "motion_dist_width", 4.0))
        # Raised 1e-6 -> 1e-4 (norm floor 1e-3 -> 1e-2): bounds how far a collapsing
        # mode's normalization can amplify in the forward, hardening against overflow
        # in the u^4 covariance terms under bf16.
        self.mode_norm_eps = float(getattr(latent_cfg, "mode_norm_eps", 1e-4))
        # Relative ridge on the mode Gram before the gauge factorisation. It caps
        # the gauge backward at ~1/sqrt(ridge) times the input scale; the forward
        # deviation from exact orthonormality is of order the ridge itself.
        self.mode_gauge_ridge = float(getattr(latent_cfg, "mode_gauge_ridge", 1e-6))
        self.cross_cov_near_distance = float(getattr(latent_cfg, "cross_cov_near_distance", 12.0))
        self.pca_align_top_m = int(getattr(latent_cfg, "pca_align_top_m", 2))
        if bool(getattr(latent_cfg, "use_enm_features", False)):
            raise ValueError("ENM cannot be used as a forward feature; use experiment.training.enm_warmup_epochs for ENM initialization only.")
        self.use_enm_features = False
        self.enm_num_modes = int(getattr(latent_cfg, "enm_num_modes", self.num_modes))
        self.enm_cutoff = float(getattr(latent_cfg, "enm_cutoff", 12.0))
        self.enm_eps = float(getattr(latent_cfg, "enm_eps", 1e-6))
        self.mixture_components = int(getattr(latent_cfg, "mixture_components", 2))
        self.q_lstsq_ridge = float(getattr(latent_cfg, "q_lstsq_ridge", 1e-4))
        self.q_cholesky_jitter = float(getattr(latent_cfg, "q_cholesky_jitter", 1e-4))
        self.q_detach_projection = bool(getattr(latent_cfg, "q_detach_projection", True))
        self.q_detach_shared_encoder = bool(
            getattr(latent_cfg, "q_detach_shared_encoder", False)
        )
        self.sample_coefficients = bool(getattr(latent_cfg, "sample_coefficients", False))
        # Inference-time only; 0.0 is exactly the current behaviour. Set from the
        # inference config so no training path is affected.
        self.coefficient_tilt_alpha = float(getattr(latent_cfg, "coefficient_tilt_alpha", 0.0) or 0.0)
        self.energy_from_q = bool(getattr(latent_cfg, "energy_from_q", False))
        self.energy_from_q_full_cov = bool(getattr(latent_cfg, "energy_from_q_full_cov", False))
        self.collective_enabled = bool(getattr(latent_cfg, "collective_enable", False))
        self.collective_rank = int(getattr(latent_cfg, "collective_rank", 4))
        self.collective_spectrum_eps = float(
            getattr(latent_cfg, "collective_spectrum_eps", 1e-6)
        )
        if self.collective_enabled and not (1 <= self.collective_rank <= self.num_modes):
            raise ValueError(
                f"collective_rank must be in [1, {self.num_modes}], "
                f"got {self.collective_rank}"
            )
        tril = torch.tril_indices(self.num_modes, self.num_modes)
        self.register_buffer("mixture_tril_rows", tril[0], persistent=False)
        self.register_buffer("mixture_tril_cols", tril[1], persistent=False)

        # The scalar prior encoder must be rotation-invariant. Vector quantities
        # are recovered later as weighted sums of coordinates or local-frame
        # residuals; feeding raw coordinates/rotations here breaks equivariance.
        node_in = 1 + 21 + dist_bins
        pair_in = dist_bins
        self.prior_node_mlp = nn.Sequential(
            nn.Linear(node_in, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
        )
        self.prior_pair_mlp = nn.Sequential(
            nn.Linear(pair_in, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
        )
        self.motion_message_passing_layers = int(getattr(latent_cfg, "motion_message_passing_layers", 4))
        self.activation_checkpoint = bool(
            getattr(latent_cfg, "activation_checkpoint", False)
        )
        self.prior_message_passing_layers = nn.ModuleList(
            [_MotionPriorBlock(hidden_dim) for _ in range(self.motion_message_passing_layers)]
        )
        self.prior_update = nn.Sequential(
            nn.Linear(2 * hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
        )
        self.energy_out = nn.Sequential(
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, self.num_modes),
        )
        self.template_residual_scale = float(getattr(latent_cfg, "template_residual_scale", 0.1))
        self.template_remove_rotation = bool(getattr(latent_cfg, "template_remove_rotation", True))
        self.template_center_logits = nn.Linear(hidden_dim, self.num_modes)
        self.template_omega_logits = nn.Linear(hidden_dim, self.num_modes)
        self.template_velocity_logits = nn.Linear(hidden_dim, self.num_modes)
        self.template_participation = nn.Linear(hidden_dim, self.num_modes)
        self.template_residual = nn.Linear(hidden_dim, self.num_modes * 3)
        self.mixture_logits_out = nn.Linear(hidden_dim, self.mixture_components)
        self.mixture_mu_out = nn.Linear(hidden_dim, self.mixture_components * self.num_modes)
        self.mixture_tril_out = nn.Linear(
            hidden_dim,
            self.mixture_components * (self.num_modes * (self.num_modes + 1) // 2),
        )

    @staticmethod
    def _masked_mean(x, mask):
        denom = mask.sum(dim=1, keepdim=True).clamp_min(1.0)
        return (x * mask[..., None]).sum(dim=1) / denom

    @staticmethod
    def _masked_std(x, mask):
        mean = LatentEncoder._masked_mean(x[..., None], mask).squeeze(-1)
        denom = mask.sum(dim=1).clamp_min(1.0)
        var = (((x - mean[:, None]) ** 2) * mask).sum(dim=1) / denom
        return torch.sqrt(var.clamp_min(1e-12))

    @staticmethod
    def _nonfinite_summary(value):
        value = value.detach().float()
        finite = torch.isfinite(value)
        finite_values = value[finite]
        finite_abs_max = (
            finite_values.abs().max().item() if finite_values.numel() else float("nan")
        )
        return (
            f"shape={tuple(value.shape)} "
            f"nan={int(torch.isnan(value).sum().item())} "
            f"posinf={int(torch.isposinf(value).sum().item())} "
            f"neginf={int(torch.isneginf(value).sum().item())} "
            f"finite_abs_max={finite_abs_max:.6g}"
        )

    @classmethod
    def _require_finite(cls, name, value):
        if not bool(torch.isfinite(value).all()):
            raise FloatingPointError(
                f"{name} contains non-finite values; {cls._nonfinite_summary(value)}"
            )

    @staticmethod
    def align_to_reference(trans, ref_trans, res_mask):
        return kabsch_align(trans, ref_trans, res_mask)

    @staticmethod
    def relative_displacement(trans, ref_trans, res_mask):
        aligned = LatentEncoder.align_to_reference(trans, ref_trans, res_mask)
        if ref_trans.dim() == 2:
            ref_trans = ref_trans.unsqueeze(0).expand_as(aligned)
        return aligned - ref_trans

    @staticmethod
    def _group_mean(x, group_index):
        groups = torch.unique(group_index, sorted=True)
        pooled = []
        for group in groups:
            pooled.append(x[group_index == group].mean(dim=0))
        return torch.stack(pooled, dim=0), groups

    def _pair_rbf(self, trans_eq, res_mask):
        with torch.autocast(device_type=trans_eq.device.type, enabled=False):
            trans = trans_eq.float()
            dists = torch.cdist(trans, trans)
            centers = self.dist_centers.to(device=trans_eq.device, dtype=torch.float32)
            rbf = torch.exp(-((dists[..., None] - centers) / self.dist_width) ** 2)
            pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
            return rbf.to(dtype=trans_eq.dtype), pair_mask.to(dtype=trans_eq.dtype)

    def _pair_distance_features(self, trans_eq, res_mask):
        rbf, pair_mask = self._pair_rbf(trans_eq, res_mask)
        denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0)
        return (rbf * pair_mask[..., None]).sum(dim=2) / denom

    def _enm_modes_and_weights_single(self, coords, mask):
        valid = mask.bool()
        n_total = coords.shape[0]
        out = coords.new_zeros(n_total, self.enm_num_modes, 3, dtype=torch.float32)
        weights = coords.new_zeros(self.enm_num_modes, dtype=torch.float32)
        coords_valid = coords[valid].float()
        n_valid = coords_valid.shape[0]
        if n_valid < 3:
            return out, weights

        diff = coords_valid[:, None, :] - coords_valid[None, :, :]
        dist = torch.linalg.norm(diff, dim=-1).clamp_min(self.enm_eps)
        contact = (dist < self.enm_cutoff) & (~torch.eye(n_valid, device=coords.device, dtype=torch.bool))
        if not contact.any():
            return out, weights

        unit = diff / dist[..., None]
        outer = unit[..., :, None] * unit[..., None, :]
        off_diag = -outer * contact[..., None, None].float()
        h_blocks = off_diag.clone()
        diag_blocks = -off_diag.sum(dim=1)
        idx = torch.arange(n_valid, device=coords.device)
        h_blocks[idx, idx] = diag_blocks
        hessian = h_blocks.permute(0, 2, 1, 3).reshape(3 * n_valid, 3 * n_valid)
        hessian = 0.5 * (hessian + hessian.transpose(0, 1))

        evals, evecs = torch.linalg.eigh(hessian.float())
        start = min(6, evecs.shape[1])
        stop = min(start + self.enm_num_modes, evecs.shape[1])
        if stop <= start:
            return out, weights
        modes = evecs[:, start:stop].reshape(n_valid, 3, stop - start).permute(0, 2, 1).contiguous()
        inv_evals = 1.0 / evals[start:stop].float().clamp_min(self.enm_eps)
        inv_evals = inv_evals / inv_evals.mean().clamp_min(self.enm_eps)

        flat = modes.reshape(modes.shape[0], modes.shape[1], 3)
        for mode_idx in range(modes.shape[1]):
            values = flat[:, mode_idx, :].reshape(-1)
            max_idx = values.abs().argmax()
            sign = torch.sign(values[max_idx]).clamp_min(0.0) * 2.0 - 1.0
            modes[:, mode_idx, :] = modes[:, mode_idx, :] * sign
        out[valid, :modes.shape[1], :] = modes
        weights[:modes.shape[1]] = inv_evals
        return out, weights

    def _enm_modes_single(self, coords, mask):
        modes, _ = self._enm_modes_and_weights_single(coords, mask)
        return modes

    def _enm_modes_batch(self, trans_eq, res_mask):
        modes = []
        with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False):
            for coords, mask in zip(trans_eq.float(), res_mask.float()):
                modes.append(self._enm_modes_single(coords, mask))
        return torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32)

    def _enm_modes_and_weights_batch(self, trans_eq, res_mask):
        modes = []
        weights = []
        with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False):
            for coords, mask in zip(trans_eq.float(), res_mask.float()):
                mode, weight = self._enm_modes_and_weights_single(coords, mask)
                modes.append(mode)
                weights.append(weight)
        return (
            torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32),
            torch.stack(weights, dim=0).to(device=trans_eq.device, dtype=torch.float32),
        )

    def _enm_motion_targets(self, trans_eq, res_mask):
        modes, energy = self._enm_modes_and_weights_batch(trans_eq, res_mask)
        if modes.shape[2] < self.num_modes:
            pad = modes.new_zeros(modes.shape[0], modes.shape[1], self.num_modes - modes.shape[2], 3)
            modes = torch.cat([modes, pad], dim=2)
            energy = torch.cat([energy, energy.new_zeros(energy.shape[0], self.num_modes - energy.shape[1])], dim=1)
        modes = modes[:, :, : self.num_modes, :]
        energy = energy[:, : self.num_modes]
        mask = res_mask.float()
        local_cov = torch.einsum("bk,bnki,bnkj->bnij", energy, modes, modes) * mask[:, :, None, None]
        cross_cov = torch.einsum("bk,bikd,bjkd->bij", energy, modes, modes) * mask[:, :, None] * mask[:, None, :]
        rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) * mask
        return {
            "enm_modes": modes,
            "enm_energy": energy,
            "local_cov": local_cov,
            "cross_cov": cross_cov,
            "rmsf": rmsf,
        }
    def _enm_node_features(self, trans_eq, rotmats_eq, res_mask):
        del rotmats_eq
        enm_global = self._enm_modes_batch(trans_eq, res_mask)
        enm_mag = torch.linalg.norm(enm_global, dim=-1) * res_mask.float()[:, :, None]
        return enm_mag.to(dtype=trans_eq.dtype)

    def _enm_pair_features(self, trans_eq, res_mask):
        enm_global = self._enm_modes_batch(trans_eq, res_mask)
        enm_pair = torch.einsum("bikd,bjkd->bijk", enm_global, enm_global)
        pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
        return (enm_pair * pair_mask[..., None]).to(dtype=trans_eq.dtype)

    def _equilibrium_node_feature_segments(self, trans_eq, rotmats_eq, seq, res_mask):
        center = self._masked_mean(trans_eq, res_mask)
        centered = trans_eq - center[:, None, :]
        radius = torch.linalg.norm(centered, dim=-1, keepdim=True)
        dist_feat = self._pair_distance_features(trans_eq, res_mask).to(dtype=trans_eq.dtype)
        segments = [
            ("radius_from_center", radius),
            ("sequence_onehot", seq),
            ("pair_distance_rbf_mean", dist_feat),
        ]
        return segments

    def _equilibrium_node_features(self, trans_eq, rotmats_eq, seq, res_mask):
        segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask)
        return torch.cat([tensor for _, tensor in segments], dim=-1)

    def prior_feature_breakdown(self, trans_eq, rotmats_eq, seq, res_mask):
        segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask)
        rows = []
        start = 0
        for name, tensor in segments:
            dim = int(tensor.shape[-1])
            end = start + dim
            valid = tensor[res_mask.bool()]
            rows.append({
                "name": name,
                "start": start,
                "end": end,
                "dim": dim,
                "shape": list(tensor.shape),
                "mean_abs": float(valid.detach().float().abs().mean().cpu().item()) if valid.numel() else 0.0,
                "std": float(valid.detach().float().std().cpu().item()) if valid.numel() > 1 else 0.0,
            })
            start = end
        node_features = torch.cat([tensor for _, tensor in segments], dim=-1)
        expected_dim = int(self.prior_node_mlp[0].in_features)
        return {
            "segments": rows,
            "total_dim": int(node_features.shape[-1]),
            "expected_prior_node_in": expected_dim,
            "matches_prior_node_in": int(node_features.shape[-1]) == expected_dim,
            "order": [name for name, _ in segments],
        }

    def _encode_equilibrium(self, trans_eq, rotmats_eq, seq, res_mask):
        node_features = self._equilibrium_node_features(trans_eq, rotmats_eq, seq, res_mask)
        node_state = self.prior_node_mlp(node_features)
        pair_rbf, pair_mask = self._pair_rbf(trans_eq, res_mask)
        pair_features = pair_rbf
        edge_state = self.prior_pair_mlp(pair_features.to(dtype=node_state.dtype))
        pair_mask = pair_mask.to(dtype=node_state.dtype)
        for block in self.prior_message_passing_layers:
            if self.training and self.activation_checkpoint and torch.is_grad_enabled():
                def block_forward(node_state_, edge_state_, pair_mask_, block_=block):
                    return block_(node_state_, edge_state_, pair_mask_)

                node_state, edge_state = checkpoint(
                    block_forward,
                    node_state,
                    edge_state,
                    pair_mask,
                    use_reentrant=False,
                    preserve_rng_state=False,
                )
            else:
                node_state, edge_state = block(node_state, edge_state, pair_mask)
        denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0)
        pair_context = (edge_state * pair_mask[..., None]).sum(dim=2) / denom
        return self.prior_update(torch.cat([node_state, pair_context], dim=-1))

    @staticmethod
    def _masked_mode_softmax(logits, res_mask):
        mask = res_mask.bool()[:, None, :]
        logits = logits.float().masked_fill(~mask, -1e9)
        return torch.softmax(logits, dim=-1)

    @staticmethod
    def _global_to_local(u_global, rotmats_eq):
        return torch.einsum("bnij,bnki->bnkj", rotmats_eq.float(), u_global.float())

    @staticmethod
    def _rotation_design(coords):
        x, y, z = coords.unbind(dim=-1)
        zeros = torch.zeros_like(x)
        return torch.stack([
            torch.stack([zeros, z, -y], dim=-1),
            torch.stack([-z, zeros, x], dim=-1),
            torch.stack([y, -x, zeros], dim=-1),
        ], dim=-2)
    def _fit_rigid_motion(self, u_global, centered_coords, res_mask):
        mask = res_mask.float()
        translation = (u_global.float() * mask[:, :, None, None]).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)[:, None, None]
        centered = (u_global.float() - translation[:, None, :, :]) * mask[:, :, None, None]
        eye = torch.eye(3, device=u_global.device, dtype=torch.float32)
        omega_out = []
        rigid_out = []
        coords = centered_coords.float()
        for batch_idx in range(u_global.shape[0]):
            valid = res_mask[batch_idx].bool()
            if valid.sum() < 3:
                omega_out.append(u_global.new_zeros(self.num_modes, 3))
                rigid_out.append(centered[batch_idx])
                continue
            design = self._rotation_design(coords[batch_idx, valid]).reshape(-1, 3).float()
            gram = design.transpose(0, 1) @ design + 1e-4 * eye
            mode_omegas = []
            mode_rigid = []
            for mode_idx in range(self.num_modes):
                target = centered[batch_idx, valid, mode_idx].reshape(-1).float()
                rhs = (design.transpose(0, 1) @ target.float()).float()
                omega = torch.linalg.solve(gram, rhs)
                rigid = (design @ omega).reshape(-1, 3)
                full = centered[batch_idx, :, mode_idx].clone()
                full[valid] = centered[batch_idx, valid, mode_idx] - rigid
                mode_omegas.append(omega)
                mode_rigid.append(full)
            omega_out.append(torch.stack(mode_omegas, dim=0))
            rigid_out.append(torch.stack(mode_rigid, dim=1))
        return translation, torch.stack(omega_out, dim=0), torch.stack(rigid_out, dim=0)

    def _remove_rigid_component(self, u_global, centered_coords, res_mask):
        translation, _, cleaned = self._fit_rigid_motion(u_global, centered_coords, res_mask)
        del translation
        return cleaned * res_mask.float()[:, :, None, None]
    def _mixture_params(self, pooled):
        logits = self.mixture_logits_out(pooled)
        mu = self.mixture_mu_out(pooled).reshape(
            pooled.shape[0], self.mixture_components, self.num_modes
        )
        raw_tril = self.mixture_tril_out(pooled).reshape(
            pooled.shape[0],
            self.mixture_components,
            self.num_modes * (self.num_modes + 1) // 2,
        )
        scale_tril = raw_tril.new_zeros(
            pooled.shape[0], self.mixture_components, self.num_modes, self.num_modes
        )
        rows = self.mixture_tril_rows.to(device=raw_tril.device)
        cols = self.mixture_tril_cols.to(device=raw_tril.device)
        scale_tril[:, :, rows, cols] = raw_tril
        diag = torch.diagonal(scale_tril, dim1=-2, dim2=-1)
        scale_tril = scale_tril - torch.diag_embed(diag)
        scale_tril = scale_tril + torch.diag_embed(F.softplus(diag) + self.q_cholesky_jitter)
        return {
            "mixture_logits": logits,
            "mixture_log_probs": F.log_softmax(logits.float(), dim=-1).to(dtype=logits.dtype),
            "mixture_mu": mu,
            "mixture_scale_tril": scale_tril,
        }

    @staticmethod
    def _mixture_entropy(logits):
        probs = torch.softmax(logits.float(), dim=-1)
        return -(probs * probs.clamp_min(1e-8).log()).sum(dim=-1)

    @staticmethod
    def mixture_second_moment(condition):
        logits = condition["mixture_logits"].float()
        mu = condition["mixture_mu"].float()
        scale_tril = condition["mixture_scale_tril"].float()
        probs = torch.softmax(logits, dim=-1)
        cov = torch.einsum("bmik,bmjk->bmij", scale_tril, scale_tril)
        second = cov + torch.einsum("bmi,bmj->bmij", mu, mu)
        return torch.einsum("bm,bmij->bij", probs, second)

    def mixture_nll(self, condition, coefficients):
        coefficients = coefficients.float()
        logits = condition["mixture_logits"].float()
        mu = condition["mixture_mu"].float()
        scale_tril = condition["mixture_scale_tril"].float()
        diff = coefficients[:, None, :] - mu
        solved = torch.linalg.solve_triangular(
            scale_tril,
            diff[..., None],
            upper=False,
        ).squeeze(-1)
        maha = solved.square().sum(dim=-1)
        logdet = torch.diagonal(scale_tril, dim1=-2, dim2=-1).clamp_min(1e-8).log().sum(dim=-1)
        normalizer = self.num_modes * math.log(2.0 * math.pi)
        comp_log_prob = -0.5 * (normalizer + maha) - logdet
        log_prob = torch.logsumexp(F.log_softmax(logits, dim=-1) + comp_log_prob, dim=-1)
        return -log_prob.mean()

    def sample_coefficients_from_q(self, condition):
        logits = condition["mixture_logits"].float()
        mu = condition["mixture_mu"].float()
        scale_tril = condition["mixture_scale_tril"].float()
        component = torch.distributions.Categorical(logits=logits).sample()
        batch = torch.arange(logits.shape[0], device=logits.device)
        selected_mu = mu[batch, component]
        selected_scale = scale_tril[batch, component]
        eps = torch.randn_like(selected_mu)
        coeff = selected_mu + torch.einsum("bij,bj->bi", selected_scale, eps)
        return coeff.to(dtype=condition["u_global"].dtype), component

    def _condition_from_modes(self, u_global, rotmats_eq, res_mask, h, extra=None):
        mask = res_mask.float()[:, :, None]
        mode_norm = torch.sqrt(
            ((u_global.float().square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps)
        )
        raw_modes_global = u_global
        u_global, qr_diagnostics = self._masked_orthonormalize_modes(
            u_global, res_mask, return_diagnostics=True
        )
        u_local = self._global_to_local(u_global, rotmats_eq)
        pooled = self._masked_mean(h, res_mask)
        q_pooled = pooled.detach() if self.q_detach_shared_encoder else pooled
        mixture = self._mixture_params(q_pooled)
        q_second_moment = self.mixture_second_moment(mixture)
        raw_energy = F.softplus(self.energy_out(pooled)) + 1e-6
        if self.energy_from_q or self.energy_from_q_full_cov:
            energy = torch.diagonal(q_second_moment, dim1=-2, dim2=-1).clamp_min(1e-8)
            energy = energy + raw_energy * 0.0
        else:
            energy = raw_energy
        sqrt_energy = torch.sqrt(energy).to(dtype=u_local.dtype)
        node_cond = torch.linalg.norm(u_global.float(), dim=-1).to(dtype=u_local.dtype) * sqrt_energy[:, None, :]
        disp_global = torch.einsum("bk,bnkd->bnd", sqrt_energy.float(), u_global.float())
        disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global)
        disp_local = disp_local * res_mask.float()[:, :, None]
        disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None]
        pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
        disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None]
        dot = torch.einsum("bikd,bjkd->bijk", u_global.float(), u_global.float())
        edge_cond = dot.to(dtype=u_local.dtype) * energy[:, None, None, :].to(dtype=u_local.dtype)
        if self.energy_from_q_full_cov:
            local_cov_pred = torch.einsum(
                "bkl,bnki,bnlj->bnij",
                q_second_moment,
                u_global.float(),
                u_global.float(),
            )
            cross_cov_pred = torch.einsum(
                "bkl,bikd,bjld->bij",
                q_second_moment,
                u_global.float(),
                u_global.float(),
            )
        else:
            local_cov_pred = torch.einsum("bk,bnki,bnkj->bnij", energy.float(), u_global.float(), u_global.float())
            cross_cov_pred = edge_cond.float().sum(dim=-1)
        rmsf_pred = torch.sqrt(torch.diagonal(local_cov_pred, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8))
        condition = {
            "node_cond": node_cond,
            "edge_cond": edge_cond,
            "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype),
            "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype),
            "u_local": u_local.to(dtype=rotmats_eq.dtype),
            "u_global": u_global.to(dtype=rotmats_eq.dtype),
            "energy": energy.to(dtype=rotmats_eq.dtype),
            "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype),
            "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype),
            "cross_cov_pred": cross_cov_pred.to(dtype=rotmats_eq.dtype),
            "rmsf_pred": rmsf_pred.to(dtype=rotmats_eq.dtype),
            "q_second_moment": q_second_moment.to(dtype=rotmats_eq.dtype),
            # Pre-gauge modes. mode_orthogonality_loss has to run on these: the
            # gauge output is orthonormal by construction, so measuring it there
            # reports ~0 no matter how collinear the mode head has become.
            "raw_modes_global": raw_modes_global,
        }
        condition.update(qr_diagnostics)
        condition.update(mixture)
        if self.collective_enabled:
            # CMFM treats the q-implied physical measure as a fixed target for this
            # step. Build its covariance from the exact GMM factor instead of the
            # cancellation-prone E[cc^T] - E[c]E[c]^T route.
            with torch.no_grad():
                _, coefficient_covariance_factor = mixture_mean_and_covariance_factor(
                    mixture["mixture_logits"].detach(),
                    mixture["mixture_mu"].detach(),
                    mixture["mixture_scale_tril"].detach(),
                )
                collective_target = physical_low_rank_target(
                    u_global.detach(),
                    res_mask,
                    coefficient_covariance_factor,
                    rank=self.collective_rank,
                    eps=self.collective_spectrum_eps,
                )
            condition.update({
                key: value.to(dtype=rotmats_eq.dtype)
                for key, value in collective_target.items()
            })

        if extra:
            condition.update(extra)
        return condition

    def _masked_orthonormalize_modes(
        self,
        modes,
        res_mask,
        return_diagnostics=False,
        ridge=None,
    ):
        """Fix the mode gauge with a masked orthonormal basis of unit per-residue norm.

        Implemented as a ridge-regularised Cholesky-QR rather than
        ``torch.linalg.qr``. Both produce the same positive-diagonal-R factor, so
        the forward value is unchanged for well-conditioned modes, but their
        backwards differ where it matters: QR backward carries ``1 / r_ii`` and
        is unbounded as the raw mode head becomes collinear, while here the ridge
        caps ``||L^-1||`` at ``1 / sqrt(ridge * mean_column_energy)``. The ridge
        is relative to the modes' own scale, so the gauge stays equivariant under
        a global rescaling of the coordinates.

        ``return_diagnostics`` additionally reports the conditioning that used to
        be invisible in the training log.
        """
        modes = modes.float()
        batch, num_res, num_modes, spatial_dim = modes.shape
        if spatial_dim != 3 or res_mask.shape != (batch, num_res):
            raise ValueError("modes and res_mask have incompatible shapes")

        mask_xyz = res_mask.bool()[..., None].expand(-1, -1, 3).reshape(batch, -1)
        valid_residues = res_mask.float().sum(dim=-1)
        if torch.any(valid_residues * 3 < num_modes).detach().item():
            raise ValueError("not enough valid coordinates to orthonormalize all modes")

        modes_flat = modes.permute(0, 1, 3, 2).reshape(batch, num_res * 3, num_modes)
        modes_flat = modes_flat * mask_xyz[..., None]

        # The factorization runs in float64. Cholesky-QR forms A^T A, which
        # squares the condition number: a mode head aligned to MD's steep
        # spectrum reaches cond(A) ~ 2e3 in normal operation, so cond(A^T A)
        # ~ 4e6. Forming that in float32 carries a rounding error of about
        # eps * lambda_max = 1.2e-7 * lambda_max, only ~8x below the relative
        # ridge of 1e-6 * lambda_max, and once it crosses the smallest
        # eigenvalue goes negative and `cholesky` fails outright on a Gram that
        # is mathematically positive definite. K is 8, so the whole solve is
        # negligible next to the rest of the forward and float64 removes the
        # failure mode instead of papering over it with a larger ridge.
        modes_flat = modes_flat.double()

        gram = modes_flat.transpose(-1, -2) @ modes_flat
        gram = 0.5 * (gram + gram.transpose(-1, -2))
        mean_energy = (
            torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1, keepdim=True)
        ).clamp_min(torch.finfo(gram.dtype).tiny)
        if ridge is None:
            ridge = self.mode_gauge_ridge
        ridge_value = float(ridge) * mean_energy
        identity = torch.eye(num_modes, device=gram.device, dtype=gram.dtype)
        try:
            cholesky_factor = torch.linalg.cholesky(
                gram + ridge_value[..., None] * identity
            )
        except torch._C._LinAlgError:
            # float64 should make this unreachable; escalating once rather than
            # dying keeps an unattended multi-day run alive if some batch still
            # lands on the boundary. Loud on purpose -- if this fires the gauge
            # is being held up by the ridge and the run's mode diagnostics
            # should not be trusted at face value.
            ridge_value = ridge_value * 1e3
            print(
                "[cmfm-numerics] masked orthonormalization Cholesky failed at "
                f"ridge={float(ridge):.3g}; retrying at {float(ridge) * 1e3:.3g}. "
                "Raw Gram is at the edge of positive definiteness.",
                flush=True,
            )
            cholesky_factor = torch.linalg.cholesky(
                gram + ridge_value[..., None] * identity
            )

        # Kept as an outright failure, not a clamp: a Gram this degenerate means
        # the mode head has collapsed and the gauge is meaningless, ridge or not.
        diagonal = torch.diagonal(cholesky_factor, dim1=-2, dim2=-1)
        input_scale = torch.linalg.vector_norm(
            modes_flat, dim=-2
        ).amax(dim=-1, keepdim=True).clamp_min(torch.finfo(gram.dtype).tiny)
        relative_diagonal = diagonal.abs() / input_scale
        if torch.any(relative_diagonal <= 1e-6).detach().item():
            raise ValueError(
                "template modes are rank deficient before masked orthonormalization; "
                f"minimum relative Cholesky diagonal="
                f"{relative_diagonal.detach().min().item():.6g}"
            )

        # q = modes_flat @ L^-T, i.e. the Q of a QR with positive diagonal R = L^T.
        q = torch.linalg.solve_triangular(
            cholesky_factor.transpose(-1, -2),
            modes_flat,
            upper=True,
            left=False,
        ).to(dtype=modes.dtype)
        q = q * torch.sqrt(valid_residues)[:, None, None]
        q = q * mask_xyz[..., None]
        basis = q.reshape(batch, num_res, 3, num_modes).permute(0, 1, 3, 2)
        if not return_diagnostics:
            return basis

        with torch.no_grad():
            singular_values = torch.linalg.svdvals(cholesky_factor.detach())
            gauge_condition = singular_values[:, 0] / singular_values[:, -1].clamp_min(
                torch.finfo(singular_values.dtype).tiny
            )
            # Cast back from the float64 factorization: these are stacked with
            # float32 metrics downstream.
            diagnostics = {
                "prior_qr_diag_abs_min": diagonal.detach().abs().amin(dim=-1),
                "prior_qr_rel_diag_min": relative_diagonal.detach().amin(dim=-1),
                "prior_qr_condition": gauge_condition,
                "prior_gauge_ridge": ridge_value.detach().reshape(batch),
            }
            diagnostics = {
                key: value.to(dtype=modes.dtype)
                for key, value in diagnostics.items()
            }
        return basis, diagnostics

    def set_tilt(self, alpha, coeff_cov):
        """Fix the per-mode gain vector for one protein, from its coefficient covariance.

        Computed once per protein and then applied unchanged to every sample, so the
        transformed coefficient covariance is exactly `G Gamma G` and the linearised gate
        evaluates the same transform the sampler applies. A per-sample renormalisation
        such as `||c||/||Gc|| * Gc` would look equivalent but is not: its covariance is not
        `G Gamma G`, so the gate and the experiment would be measuring different things.

        Modes are ranked by their marginal variance under `q` -- fixed per protein, not
        per sample. Ranking within each sample by `|c_k|` implements no modal
        redistribution at all: under an exchangeable coefficient distribution every fixed
        mode keeps its marginal variance and the transform only pushes individual samples
        toward coordinate axes, amplifying whichever coordinate drew large.

        The gains are renormalised so `tr(G Gamma G) == tr(Gamma)`. That fixes the
        coefficient energy; it does NOT fix the conditioning payload, because `edge_cond`
        and `disp_edge_cond` are quadratic in the coefficients, so concentrating a fixed
        `tr(Gamma)` raises terms in `c^4`. `alpha` is therefore not orthogonal to
        `condition_scale` and any effect may still be partly amplitude-mediated.
        """
        alpha = float(alpha or 0.0)
        if alpha == 0.0 or coeff_cov is None:
            self._tilt_gain = None
            return None
        gamma = coeff_cov.detach().float()
        if gamma.dim() == 3:
            gamma = gamma[0]
        k = gamma.shape[-1]
        var = torch.diagonal(gamma)
        order = torch.argsort(var, descending=True)
        rank = torch.empty(k, device=gamma.device, dtype=gamma.dtype)
        rank[order] = torch.arange(1, k + 1, device=gamma.device, dtype=gamma.dtype)
        g = rank ** (-alpha)
        tilted = g[:, None] * gamma * g[None, :]
        scale = (torch.diagonal(gamma).sum()
                 / torch.diagonal(tilted).sum().clamp_min(1e-30)).sqrt()
        self._tilt_gain = (g * scale).detach()
        return self._tilt_gain

    def _tilt_coefficients(self, coefficients):
        gain = getattr(self, "_tilt_gain", None)
        if gain is None:
            return coefficients
        return coefficients * gain.to(coefficients.device, coefficients.dtype)

    def condition_from_mode_coefficients(
        self,
        u_global,
        coefficients,
        rotmats_eq,
        res_mask,
        extra=None,
        include_statistics=True,
    ):
        """Build a sample-specific condition from fixed modes and per-frame coefficients.

        Per-frame training uses signed mode coordinates c* from the current MD frame,
        giving d_i = sum_k c*_k U_k[i] rather than a static sqrt(energy) field.
        """
        mask = res_mask.float()[:, :, None]
        u_global = u_global.float()
        coefficients = coefficients.float()
        coefficients = self._tilt_coefficients(coefficients)
        mode_norm = torch.sqrt(
            ((u_global.square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps)
        )
        # Stop-gradient on the gauge norm (same 1/mode_norm^2 explosion as above).
        # Detaching in BOTH the division and the compensating multiply leaves the
        # forward product coeff*u_global identical while removing the runaway gradient.
        mode_norm_sg = mode_norm.detach()
        u_global = u_global / mode_norm_sg[:, None, :, None]
        coefficients = coefficients * mode_norm_sg
        u_local = self._global_to_local(u_global, rotmats_eq)
        coeff_abs = coefficients.abs().to(dtype=u_local.dtype)
        node_cond = torch.linalg.norm(u_global, dim=-1).to(dtype=u_local.dtype) * coeff_abs[:, None, :]
        disp_global = torch.einsum("bk,bnkd->bnd", coefficients, u_global)
        disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global)
        disp_local = disp_local * res_mask.float()[:, :, None]
        pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
        disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None]
        disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None]
        dot = torch.einsum("bikd,bjkd->bijk", u_global, u_global)
        edge_cond = dot.to(dtype=u_local.dtype) * coefficients.square()[:, None, None, :].to(dtype=u_local.dtype)
        energy = coefficients.square()
        condition = {
            "node_cond": node_cond,
            "edge_cond": edge_cond,
            "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype),
            "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype),
            "u_local": u_local.to(dtype=rotmats_eq.dtype),
            "u_global": u_global.to(dtype=rotmats_eq.dtype),
            "energy": energy.to(dtype=rotmats_eq.dtype),
            "mode_coefficients": coefficients.to(dtype=rotmats_eq.dtype),
            "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype),
        }
        if include_statistics:
            local_cov_pred = torch.einsum(
                "bk,bnki,bnkj->bnij", energy, u_global, u_global
            )
            condition.update({
                "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype),
                "cross_cov_pred": edge_cond.float().sum(dim=-1).to(dtype=rotmats_eq.dtype),
                "rmsf_pred": torch.sqrt(
                    torch.diagonal(local_cov_pred, dim1=-2, dim2=-1)
                    .sum(dim=-1)
                    .clamp_min(1e-8)
                ).to(dtype=rotmats_eq.dtype),
            })
        if extra:
            condition.update(extra)
        return condition

    def oracle_condition_from_targets(self, trans_1, trans_eq, rotmats_eq, res_mask, targets):
        modes = targets["oracle_modes"].to(device=trans_eq.device, dtype=torch.float32)
        mean_disp = targets.get("oracle_mean_disp")
        if mean_disp is None:
            mean_disp = torch.zeros_like(trans_eq, dtype=torch.float32)
        else:
            mean_disp = mean_disp.to(device=trans_eq.device, dtype=torch.float32)
        disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask)
        centered_disp = (disp - mean_disp) * res_mask.float()[:, :, None]
        coefficients = self.project_displacement_to_modes(centered_disp, modes, res_mask)
        recon = torch.einsum("bk,bnkd->bnd", coefficients.float(), modes.float())
        return self.condition_from_mode_coefficients(
            modes,
            coefficients,
            rotmats_eq,
            res_mask,
            extra={
                "oracle_centered_disp": centered_disp.to(dtype=rotmats_eq.dtype),
                "oracle_recon_disp": recon.to(dtype=rotmats_eq.dtype),
            },
        )

    def frame_condition_from_projection(
        self,
        trans_1,
        trans_eq,
        rotmats_eq,
        res_mask,
        prior_condition,
        mean_disp=None,
    ):
        """Project the frame's centered fluctuation onto predicted motion modes.

        Motion covariance targets are centered over MD time, so the coefficient
        target must remove the same per-protein mean displacement. The solve uses
        detached modes by default, while flow loss still reaches the original modes
        through the reconstructed generator condition.
        """
        raw_disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask)
        mask = res_mask.float()[:, :, None]
        if mean_disp is None:
            raise ValueError(
                "per-frame mode projection requires oracle_mean_disp in the motion-target cache; "
                "regenerate the cache or use one that contains centered MD targets"
            )
        mean_disp = mean_disp.to(device=raw_disp.device, dtype=raw_disp.dtype)
        disp = (raw_disp - mean_disp) * mask
        coefficients = self.project_displacement_lstsq(
            disp,
            prior_condition["u_global"],
            res_mask,
            ridge=self.q_lstsq_ridge,
            detach_modes=self.q_detach_projection,
        )
        recon_objective = self.projection_reconstruction_objective(
            disp,
            prior_condition["u_global"],
            coefficients,
            res_mask,
            ridge=self.q_lstsq_ridge,
        )
        recon = recon_objective["recon"]
        uncentered_error = ((raw_disp - recon).square() * mask).sum(dim=(1, 2)).sqrt()
        uncentered_denom = (raw_disp.square() * mask).sum(dim=(1, 2)).sqrt().clamp_min(1e-8)
        passthrough = {
            key: prior_condition[key]
            for key in [
                "mixture_logits",
                "mixture_log_probs",
                "mixture_mu",
                "mixture_scale_tril",
                "collective_basis_global",
                "collective_target_covariance",
                "collective_target_variance",
                "collective_retained_fraction",
            ]
            if key in prior_condition
        }
        condition = self.condition_from_mode_coefficients(
            prior_condition["u_global"],
            coefficients,
            rotmats_eq,
            res_mask,
            extra=passthrough,
            include_statistics=False,
        )
        condition["projection_uncentered_target_disp"] = raw_disp.to(dtype=rotmats_eq.dtype)
        condition["projection_mean_disp"] = mean_disp.to(dtype=rotmats_eq.dtype)
        condition["projection_target_disp"] = disp.to(dtype=rotmats_eq.dtype)
        condition["projection_recon_disp"] = recon.to(dtype=rotmats_eq.dtype)
        condition["projection_recon_loss"] = recon_objective["loss"].to(dtype=rotmats_eq.dtype)
        condition["projection_recon_rel_error"] = recon_objective["rel_error"].to(dtype=rotmats_eq.dtype)
        condition["projection_uncentered_recon_rel_error"] = (
            uncentered_error / uncentered_denom
        ).to(dtype=rotmats_eq.dtype)
        return condition, coefficients

    def _mode_predictions(self, h, trans_eq, rotmats_eq, res_mask):
        center = self._masked_mean(trans_eq.float(), res_mask)
        centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]

        residual_local = torch.tanh(self.template_residual(h).reshape(h.shape[0], h.shape[1], self.num_modes, 3))
        residual_global = torch.einsum("bnij,bnkj->bnki", rotmats_eq.float(), residual_local.float())
        residual_global = self.template_residual_scale * residual_global

        center_logits = self.template_center_logits(h).transpose(1, 2)
        omega_logits = self.template_omega_logits(h).transpose(1, 2)
        velocity_logits = self.template_velocity_logits(h).transpose(1, 2)
        center_weights = self._masked_mode_softmax(center_logits, res_mask)
        omega_weights = self._masked_mode_softmax(omega_logits, res_mask)
        velocity_weights = self._masked_mode_softmax(velocity_logits, res_mask)

        mode_center = torch.einsum("bkn,bnd->bkd", center_weights, centered)
        omega = torch.einsum("bkn,bnd->bkd", omega_weights, centered)
        velocity = torch.einsum("bkn,bnd->bkd", velocity_weights, centered)
        participation = self.template_participation(h)

        rel = centered[:, :, None, :] - mode_center[:, None, :, :]
        base = torch.cross(omega[:, None, :, :].expand_as(rel), rel, dim=-1) + velocity[:, None, :, :]
        u_global = participation[..., None].float() * base + residual_global
        if not bool(torch.isfinite(u_global).all()):
            components = {
                "hidden": h,
                "residual_local": residual_local,
                "center_logits": center_logits,
                "omega_logits": omega_logits,
                "velocity_logits": velocity_logits,
                "participation": participation,
                "base": base,
                "raw_modes": u_global,
            }
            details = "; ".join(
                f"{name}: {self._nonfinite_summary(value)}"
                for name, value in components.items()
                if not bool(torch.isfinite(value).all())
            )
            raise FloatingPointError(
                f"raw template modes contain non-finite values; {details}"
            )
        u_global = self._remove_rigid_component(u_global, centered, res_mask)
        self._require_finite("rigid-cleaned template modes", u_global)
        raw_mode_rms = torch.sqrt(
            (
                (u_global.square().sum(dim=-1) * res_mask.float()[:, :, None]).sum(dim=1)
                / res_mask.float().sum(dim=1, keepdim=True).clamp_min(1.0)
            ).clamp_min(0.0)
        )
        extra = {
            "template_center": mode_center.to(dtype=rotmats_eq.dtype),
            "template_omega": omega.to(dtype=rotmats_eq.dtype),
            "template_velocity": velocity.to(dtype=rotmats_eq.dtype),
            "template_participation": participation.to(dtype=rotmats_eq.dtype),
            "template_residual_global": residual_global.to(dtype=rotmats_eq.dtype),
            "prior_hidden_abs_max": (
                h.float().abs() * res_mask.float()[..., None]
            ).amax(dim=(1, 2)),
            "prior_raw_mode_abs_max": u_global.abs().amax(dim=(1, 2, 3)),
            "prior_raw_mode_rms_min": raw_mode_rms.amin(dim=-1),
            "prior_raw_mode_rms_max": raw_mode_rms.amax(dim=-1),
        }
        return self._condition_from_modes(u_global, rotmats_eq, res_mask, h, extra=extra)

    def forward_prior(self, trans_eq, rotmats_eq, seq, res_mask):
        if self.collective_enabled:
            # CMFM evaluates one equilibrium representative per particle group.
            # Keeping this small prior path in fp32 prevents bf16 corruption of h
            # from reaching the physical mode basis; the particle backbone remains
            # mixed precision and still dominates memory and runtime.
            with torch.autocast(device_type=trans_eq.device.type, enabled=False):
                h = self._encode_equilibrium(
                    trans_eq.float(),
                    rotmats_eq.float(),
                    seq.float(),
                    res_mask.float(),
                )
                self._require_finite("equilibrium prior hidden state", h)
                condition = self._mode_predictions(
                    h,
                    trans_eq.float(),
                    rotmats_eq.float(),
                    res_mask.float(),
                )
            return condition, None

        h = self._encode_equilibrium(trans_eq, rotmats_eq, seq, res_mask)
        # Mode construction and its small linear-algebra problems must remain fp32
        # because CUDA linalg does not support bf16 consistently.
        with torch.autocast(device_type=trans_eq.device.type, enabled=False):
            condition = self._mode_predictions(
                h.float(),
                trans_eq.float(),
                rotmats_eq,
                res_mask,
            )
        return condition, None

    def _prior_backbone_modules(self):
        """Every module that participates in computing u_global: the shared trunk
        (h) plus the template_* heads that turn h into modes. Deliberately excludes
        mixture_*/energy_out, which read the same trunk's pooled features but do
        NOT feed back into u_global."""
        return [
            self.prior_node_mlp,
            self.prior_pair_mlp,
            self.prior_message_passing_layers,
            self.prior_update,
            self.template_center_logits,
            self.template_omega_logits,
            self.template_velocity_logits,
            self.template_participation,
            self.template_residual,
        ]

    def freeze_prior_backbone(self):
        """Stage-2 entry point: freeze everything U depends on (trunk + template
        heads). Freezing ONLY the template_* linears is not enough -- if the shared
        trunk keeps training (e.g. via q's gradient), h drifts and u_global drifts
        with it even though the template weights are frozen. Freezing the whole
        pathway makes u_global (and therefore c* = Proj_U(D)) a fixed target, which
        is the point of the two-stage split. mixture_*/energy_out are left
        trainable so q can still be fit/refined on top of the frozen features."""
        for module in self._prior_backbone_modules():
            for param in module.parameters():
                param.requires_grad = False

    def set_frozen_prior_backbone_eval(self):
        for module in self._prior_backbone_modules():
            module.eval()

    def prior_backbone_grad_check(self):
        """Diagnostic: count trainable params in the U-pathway vs the q/energy
        heads, so 'U frozen in stage 2' is verifiable at runtime, not assumed."""
        frozen_params = sum(
            p.numel() for m in self._prior_backbone_modules() for p in m.parameters()
        )
        frozen_trainable = sum(
            p.numel() for m in self._prior_backbone_modules() for p in m.parameters() if p.requires_grad
        )
        q_modules = [self.mixture_logits_out, self.mixture_mu_out, self.mixture_tril_out, self.energy_out]
        q_trainable = sum(p.numel() for m in q_modules for p in m.parameters() if p.requires_grad)
        return {
            "u_pathway_params": frozen_params,
            "u_pathway_trainable": frozen_trainable,
            "q_head_trainable": q_trainable,
        }

    def sample_prior_z(self, trans_eq, rotmats_eq, seq, res_mask):
        condition, _ = self.forward_prior(trans_eq, rotmats_eq, seq, res_mask)
        if not self.sample_coefficients:
            return condition
        coefficients, component = self.sample_coefficients_from_q(condition)
        sampled = self.condition_from_mode_coefficients(
            condition["u_global"],
            coefficients,
            rotmats_eq,
            res_mask,
            extra={
                key: condition[key]
                for key in [
                    "mixture_logits",
                    "mixture_log_probs",
                    "mixture_mu",
                    "mixture_scale_tril",
                    "collective_basis_global",
                    "collective_target_covariance",
                    "collective_target_variance",
                    "collective_retained_fraction",
                ]
                if key in condition
            },
        )
        sampled["sampled_mixture_component"] = component
        return sampled
    @staticmethod
    def repeat_condition(condition, batch_size):
        repeated = {}
        for key, value in condition.items():
            if torch.is_tensor(value):
                repeated[key] = value.repeat(batch_size, *([1] * (value.dim() - 1)))
            else:
                repeated[key] = value
        return repeated

    @staticmethod
    def compute_motion_targets(frames_group, x_eq, res_mask, num_modes=8):
        """Offline targets from full MD: covariance targets plus oracle PCA modes."""
        with torch.no_grad():
            disp = LatentEncoder.relative_displacement(
                frames_group.float(),
                x_eq.float(),
                res_mask,
            )
            if res_mask.dim() == 1:
                mask = res_mask.float()
            else:
                mask = res_mask[0].float()
            valid = mask.bool()
            disp_centered = disp - disp.mean(dim=0, keepdim=True)
            denom = float(max(disp_centered.shape[0] - 1, 1))
            local_cov = torch.einsum("tni,tnj->nij", disp_centered, disp_centered) / denom
            cross_cov = torch.einsum("tnd,tmd->nm", disp_centered, disp_centered) / denom
            rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8))
            local_var = torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)
            dccm = cross_cov / torch.sqrt(local_var[:, None] * local_var[None, :]).clamp_min(1e-8)
            local_cov = local_cov * mask[:, None, None]
            cross_cov = cross_cov * mask[:, None] * mask[None, :]
            dccm = dccm * mask[:, None] * mask[None, :]
            rmsf = rmsf * mask
            oracle_modes, oracle_energy = LatentEncoder.pca_modes_from_centered_displacement(
                disp_centered,
                mask,
                num_modes=num_modes,
            )
            return {
                "local_cov": local_cov.detach().cpu(),
                "cross_cov": cross_cov.detach().cpu(),
                "dccm": dccm.detach().cpu(),
                "rmsf": rmsf.detach().cpu(),
                "res_mask": mask.detach().cpu(),
                "oracle_modes": oracle_modes.detach().cpu(),
                "oracle_energy": oracle_energy.detach().cpu(),
                "oracle_mean_disp": (disp.mean(dim=0) * mask[:, None]).detach().cpu(),
                "num_res": torch.tensor(int(valid.sum().item()), dtype=torch.long),
            }

    @staticmethod
    def pca_modes_from_centered_displacement(disp_centered, res_mask, num_modes=8):
        mask = res_mask.float()
        flat = (disp_centered.float() * mask[None, :, None]).reshape(disp_centered.shape[0], -1)
        flat = flat - flat.mean(dim=0, keepdim=True)
        if flat.shape[0] < 2 or flat.abs().sum() <= 0:
            return (
                disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3),
                disp_centered.new_zeros(num_modes),
            )
        _, singular_values, vh = torch.linalg.svd(flat, full_matrices=False)
        take = min(num_modes, vh.shape[0])
        modes = disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3)
        modes[:, :take, :] = vh[:take].reshape(take, disp_centered.shape[1], 3).permute(1, 0, 2)
        energy = disp_centered.new_zeros(num_modes)
        energy[:take] = singular_values[:take].square() / float(max(flat.shape[0] - 1, 1))
        return modes * mask[:, None, None], energy

    @staticmethod
    def project_displacement_to_modes(centered_disp, modes, res_mask):
        mask = res_mask.float()[:, :, None, None]
        modes = modes.float() * mask
        disp = centered_disp.float() * res_mask.float()[:, :, None]
        numerator = torch.einsum("bnd,bnkd->bk", disp, modes)
        denom = modes.square().sum(dim=(1, 3)).clamp_min(1e-8)
        return numerator / denom

    @staticmethod
    def mode_orthogonality_loss(modes, res_mask):
        """Scale-invariant squared cosine penalty over distinct mode pairs."""
        basis = modes.float() * res_mask.float()[:, :, None, None]
        gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
        norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-8).sqrt()
        # Cosine similarity is scale invariant only when gradients also flow
        # through its norm. Detaching this denominator creates a false radial
        # gradient that rewards shrinking the raw modes.
        denom = norms[:, :, None] * norms[:, None, :]
        cosine = gram / denom
        eye = torch.eye(gram.shape[-1], device=gram.device, dtype=gram.dtype)[None]
        offdiag = 1.0 - eye
        return (cosine.square() * offdiag).sum() / (
            offdiag.sum() * gram.shape[0]
        ).clamp_min(1.0)

    @staticmethod
    def mode_gram_diagnostics(modes, res_mask):
        """Measure mode collinearity after masking, without changing the modes."""
        basis = modes.detach().float() * res_mask.float()[:, :, None, None]
        gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
        eigvals = torch.linalg.eigvalsh(gram.float())
        min_eig = eigvals[:, 0].clamp_min(0.0)
        max_eig = eigvals[:, -1].clamp_min(0.0)
        condition = max_eig / min_eig.clamp_min(1e-12)

        norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-12).sqrt()
        cosine = gram / (norms[:, :, None] * norms[:, None, :])
        eye = torch.eye(gram.shape[-1], device=gram.device, dtype=torch.bool)[None]
        max_cosine = cosine.abs().masked_fill(eye, 0.0).amax(dim=(1, 2))
        return {
            "mode_gram_min_eig": min_eig,
            "mode_gram_max_eig": max_eig,
            "mode_gram_condition": condition,
            "mode_max_cosine_abs": max_cosine,
        }

    @staticmethod
    def project_displacement_lstsq(displacement, modes, res_mask, ridge=1e-4, detach_modes=True):
        basis = modes.float()
        if detach_modes:
            basis = basis.detach()
        mask = res_mask.float()
        basis = basis * mask[:, :, None, None]
        disp = displacement.float() * mask[:, :, None]
        gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
        rhs = torch.einsum("bnd,bnkd->bk", disp, basis)
        eye = torch.eye(modes.shape[2], device=modes.device, dtype=gram.dtype)[None]
        # Relative (Levenberg-Marquardt) ridge: an absolute `ridge` (e.g. 1e-4) is
        # numerically swallowed in float32 once the unnormalized modes make the gram
        # scale large (mode-norm gauge -> gram entries up to ~1e13), leaving a
        # near-collinear batch element singular and crashing torch.linalg.solve.
        # Scaling the damping by the mean diagonal keeps it effective at every gauge.
        scale = torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1).clamp_min(1e-8)
        gram = gram.float()
        rhs = rhs.float()
        coeff = torch.linalg.solve(
            gram + (float(ridge) * scale)[:, None, None] * eye, rhs[..., None]
        ).squeeze(-1)
        return coeff

    @staticmethod
    def projection_reconstruction_objective(
        displacement,
        modes,
        coefficients,
        res_mask,
        ridge=1e-4,
        eps=1e-8,
    ):
        """Evaluate the ridge least-squares value with stop-gradient coefficients."""
        mask = res_mask.float()[:, :, None]
        disp = displacement.float() * mask
        basis = modes.float() * mask[:, :, None]
        coefficients_for_recon = coefficients.detach().float()
        recon = torch.einsum(
            "bk,bnkd->bnd", coefficients_for_recon, basis
        )
        residual_sq = ((disp - recon).square() * mask).sum(dim=(1, 2))
        target_sq = (disp.square() * mask).sum(dim=(1, 2)).clamp_min(float(eps))
        ridge_sq = float(ridge) * coefficients_for_recon.square().sum(dim=-1)
        return {
            "loss": (residual_sq + ridge_sq) / target_sq,
            "rel_error": torch.sqrt(residual_sq / target_sq),
            "recon": recon,
        }

    @staticmethod
    def _masked_corr(pred, target, mask):
        pred = pred.float()[mask.bool()]
        target = target.float()[mask.bool()]
        if pred.numel() < 2:
            return pred.new_zeros(())
        pred = pred - pred.mean()
        target = target - target.mean()
        denom = pred.norm() * target.norm()
        if denom <= 1e-8:
            return pred.new_zeros(())
        return (pred * target).sum() / denom

    @staticmethod
    def _top_abs_sign_agree(pred, target, mask, fraction=0.1):
        pred = pred.float()[mask.bool()]
        target = target.float()[mask.bool()]
        if pred.numel() == 0:
            return pred.new_zeros(())
        k = max(1, int(round(float(pred.numel()) * fraction)))
        k = min(k, pred.numel())
        idx = torch.topk(target.abs(), k=k, largest=True).indices
        return (torch.sign(pred[idx]) == torch.sign(target[idx])).float().mean()

    def motion_alignment_metrics(self, condition, targets, res_mask, spatial_dists):
        with torch.no_grad():
            mask = res_mask.float()
            pair_mask = mask[:, :, None] * mask[:, None, :]
            eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
            offdiag_mask = pair_mask * (1.0 - eye)
            spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype)
            near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
            far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
            pred = condition["cross_cov_pred"].detach().float()
            target = targets["cross_cov"].to(device=pred.device, dtype=pred.dtype)
            return {
                "cross_cov_corr_all": self._masked_corr(pred, target, offdiag_mask),
                "cross_cov_near_corr": self._masked_corr(pred, target, near_mask),
                "cross_cov_far_corr": self._masked_corr(pred, target, far_mask),
                "cross_cov_near_top10_sign_agree": self._top_abs_sign_agree(pred, target, near_mask),
                "cross_cov_far_top10_sign_agree": self._top_abs_sign_agree(pred, target, far_mask),
                "cross_cov_near_pred_abs_mean": (pred.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0),
                "cross_cov_near_true_abs_mean": (target.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0),
                "cross_cov_far_pred_abs_mean": (pred.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0),
                "cross_cov_far_true_abs_mean": (target.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0),
            }

    def rigid_component_metrics(self, condition, trans_eq, res_mask):
        with torch.no_grad():
            center = self._masked_mean(trans_eq.float(), res_mask)
            coords = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]
            translation, omega, _ = self._fit_rigid_motion(condition["u_global"], coords, res_mask)
            translation = translation.float()
            omega = omega.float()
            return {
                "rigid_translation_abs_mean": translation.abs().mean(),
                "rigid_translation_abs_max": translation.abs().max(),
                "rigid_rotation_omega_abs_mean": omega.abs().mean(),
                "rigid_rotation_omega_abs_max": omega.abs().max(),
            }

    @staticmethod
    def _mode_subspace_basis(u_global, res_mask):
        mask = res_mask.float()[:, :, None, None]
        u = (u_global.float() * mask).permute(0, 2, 1, 3).reshape(u_global.shape[0], u_global.shape[2], -1)
        bases = []
        for sample in u:
            matrix = sample.transpose(0, 1)
            q, _ = torch.linalg.qr(matrix.float(), mode="reduced")
            bases.append(q)
        return torch.stack(bases, dim=0)

    @staticmethod
    def _mode_subspace_loss(pred_modes, target_modes, res_mask):
        pred_basis = LatentEncoder._mode_subspace_basis(pred_modes, res_mask)
        target_basis = LatentEncoder._mode_subspace_basis(target_modes, res_mask)
        overlap = torch.matmul(pred_basis.transpose(-1, -2), target_basis).square().sum(dim=(-1, -2))
        num_modes = pred_basis.shape[-1]
        normalized_overlap = (overlap / float(max(num_modes, 1))).clamp(0.0, 1.0)
        return 1.0 - normalized_overlap.mean(), normalized_overlap.mean().detach()

    @staticmethod
    def _masked_flat_modes(modes, res_mask):
        mask = res_mask.float()[:, :, None, None]
        modes = modes.float() * mask
        return modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1)

    def md_subspace_shape_loss(self, condition, targets, res_mask, eps=1e-8, weight_exp=0.0):
        """Match the model's implied covariance to MD's, in MD's own eigenbasis.

        No sampling enters. ``Cov[c]`` is closed form under the mixture, ``U`` is the
        encoder output, and the reference eigenvectors ``V`` and variances ``beta`` are
        precomputed from the full trajectory. The group of ``G`` conformations that the
        collective objective needs in order to *estimate* a covariance is therefore not
        required: what it was estimating from 8 samples is already known exactly from
        ~10^4. The ``G < k`` rank deficiency that forced the rank-4 restriction does not
        arise either, since no sample covariance is inverted or square-rooted.

        With ``V`` orthonormal, ``M = V^T U`` and ``A = M Cov[c] M^T`` is the model's
        covariance expressed in the reference eigenbasis, against the diagonal target
        ``B = diag(beta)``.

        The residual is normalised by the norm of the target, so the loss is 1.0 when the
        model produces no covariance and approaches 0 as ``A`` approaches ``B``. It is
        scale sensitive -- dilating the model rescales ``Cov[c]`` -- so it does not carry
        the dilation invariance that made the covariance-entry correlation useless as an
        optimisation target.

        ``md_subspace_diag_sq`` and ``md_subspace_offdiag_sq`` are reported separately and
        in absolute terms: the off-diagonal part is the eigenvector misalignment and the
        diagonal part is the variance error, and a ratio between them moves whenever
        either does, so the share is not reported.
        """
        u_global = condition["u_global"].float()
        modes = targets["oracle_modes"].to(device=u_global.device).float()
        energy = targets["oracle_energy"].to(device=u_global.device).float()

        mask = res_mask.float()[:, :, None, None]
        u_global = u_global * mask
        modes = modes * mask

        # Stored reference modes are unit norm, but masking removes weight; the
        # projection below assumes orthonormal columns.
        mode_norm = modes.square().sum(dim=(1, 3)).clamp_min(eps).sqrt()
        modes = modes / mode_norm[:, None, :, None]

        projection = torch.einsum("bnrd,bnkd->brk", modes, u_global)
        _, coeff_cov = mixture_mean_and_covariance(
            condition["mixture_logits"],
            condition["mixture_mu"],
            condition["mixture_scale_tril"],
        )
        implied = projection @ coeff_cov @ projection.transpose(1, 2)

        target_var = energy.clamp_min(eps)
        # `weight_exp` is applied on both sides, so the residual is weighted by
        # `beta**(2*weight_exp)`.
        #
        #   -0.25  the local quadratic approximation to the Bures metric. It weights
        #          every direction by its *relative* error, which up-weights the small
        #          eigenvalues -- directions 9-12 here -- and down-weights the leading
        #          ones by the same factor.
        #    0.00  plain Frobenius: absolute error, dominated by the largest eigenvalues.
        #   +0.25  emphasises the leading directions further still.
        #
        # The evaluation is an absolute W2 restricted to the leading principal
        # directions, so it is dominated by the largest eigenvalues. Bures weighting
        # therefore spends the objective on precisely the directions the score cannot
        # see, and the measured symptom matches: the generated ensembles carry 0.403 of
        # the reference's 0.552 variance in the top two directions while exceeding it
        # overall. Default is unweighted.
        weight = target_var.pow(float(weight_exp)) if weight_exp != 0.0 else None
        residual = (implied - torch.diag_embed(target_var))
        if weight is not None:
            residual = residual * weight[:, :, None] * weight[:, None, :]
        # Divide by the norm of the (identically weighted) target, so the loss is
        # exactly 1.0 when the model produces no covariance at all and falls toward 0
        # as A approaches B. That fixes the scale for any `weight_exp` and for any
        # protein, which is what makes a single lambda meaningful: without it the
        # magnitude tracks the spectrum and lambda has to be re-guessed per
        # configuration. The previous version ran with the term roughly 100x
        # official_loss, which is how an auxiliary objective ends up steering the
        # backbone.
        weighted_target = target_var if weight is None else target_var * weight.square()
        denom = weighted_target.square().sum(dim=-1).clamp_min(eps)
        shape_loss = (residual.square().sum(dim=(1, 2)) / denom).mean()

        implied_trace = torch.diagonal(implied, dim1=-2, dim2=-1).sum(dim=-1)
        target_trace = target_var.sum(dim=-1).clamp_min(eps)
        trace_loss = ((implied_trace / target_trace) - 1.0).square().mean()

        with torch.no_grad():
            diag = torch.diagonal(residual, dim1=-2, dim2=-1)
            diag_sq = diag.square().sum(dim=-1)
            offdiag_sq = residual.square().sum(dim=(1, 2)) - diag_sq
            # Absolute, not the ratio. The share moves whenever *either* part moves, so a
            # trace term shrinking the diagonal inflates it even with the off-diagonal
            # error flat -- the same defect that made the covariance-entry correlation
            # useless. Read these two independently.
            variance_ratio = (implied_trace / target_trace).mean()

            # Direction only: mean squared cosine of the principal angles between
            # span(U) and span(V). Orthonormalise U first, since its columns are neither
            # unit norm nor mutually orthogonal. Amplitude cannot move this.
            num_modes = u_global.shape[2]
            u_flat = u_global.permute(0, 2, 1, 3).reshape(u_global.shape[0], num_modes, -1)
            q_basis, _ = torch.linalg.qr(u_flat.transpose(1, 2))
            v_flat = modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1)
            cosines = torch.bmm(v_flat, q_basis)
            span_overlap = (
                cosines.square().sum(dim=(1, 2)) / float(min(modes.shape[2], num_modes))
            ).mean()

            # The floor this family imposes, independent of Cov[c]:
            #   inf_{Gamma >= 0} W2^2(M Gamma M^T, B) / tr B = tr((I - P_M) B) / tr B
            # with P_M the projector onto range(M). No choice of q can beat it, so a
            # shape loss stalling near this value means the modes, not the mixture, are
            # the binding constraint. It is identically zero whenever M has full row
            # rank -- with as many reference modes as model modes that is the generic
            # case, and the number only becomes informative once the cache carries more
            # reference directions than the model has.
            left, sing, _ = torch.linalg.svd(projection, full_matrices=False)
            keep = (sing > sing[..., :1].clamp_min(eps) * 1e-6).to(left.dtype)
            left = left * keep[:, None, :]
            proj_diag = left.square().sum(dim=-1)
            floor = (
                ((1.0 - proj_diag) * target_var).sum(dim=-1) / target_trace
            ).clamp_min(0.0).sqrt().mean()

        return {
            "md_subspace_shape_loss": shape_loss,
            "md_subspace_trace_loss": trace_loss,
            "md_subspace_variance_ratio": variance_ratio,
            "md_subspace_diag_sq": diag_sq.mean(),
            "md_subspace_offdiag_sq": offdiag_sq.mean(),
            "md_subspace_span_overlap": span_overlap,
            "md_subspace_floor": floor,
        }

    def pca_alignment_loss(self, condition, targets, res_mask, top_m=2):
        """Favor assigning high predicted energy to modes aligned with MD top PCs."""
        pred_modes = condition["u_global"].float()
        target_modes = targets["oracle_modes"].to(
            device=pred_modes.device,
            dtype=torch.float32,
        )
        top_m = int(max(1, min(top_m, pred_modes.shape[2], target_modes.shape[2])))
        target_modes = target_modes[:, :, :top_m, :]

        pred_flat = F.normalize(self._masked_flat_modes(pred_modes, res_mask), dim=-1, eps=1e-8)
        target_basis = self._mode_subspace_basis(target_modes, res_mask)
        mode_overlap = torch.matmul(pred_flat, target_basis).square().sum(dim=-1).clamp(0.0, 1.0)

        energy = condition["energy"].float().clamp_min(1e-8)
        weights = energy / energy.sum(dim=-1, keepdim=True).clamp_min(1e-8)
        weighted_overlap = (weights * mode_overlap).sum(dim=-1)
        pca_align_loss = 1.0 - weighted_overlap.mean()

        with torch.no_grad():
            order = torch.argsort(energy, dim=-1, descending=True)
            top1_overlap = mode_overlap.gather(1, order[:, :1]).mean()
            best_overlap = mode_overlap.max(dim=-1).values.mean()
            top_idx = order[:, :top_m]
            gather_idx = top_idx[:, None, :, None].expand(-1, pred_modes.shape[1], -1, pred_modes.shape[-1])
            pred_top_modes = pred_modes.gather(2, gather_idx)
            _, top_subspace_overlap = self._mode_subspace_loss(pred_top_modes, target_modes, res_mask)

        return {
            "pca_align_loss": pca_align_loss,
            "pca_align_weighted_overlap": weighted_overlap.detach().mean(),
            "pca_align_best_overlap": best_overlap,
            "pca_align_top_energy_overlap": top1_overlap,
            "pca_align_top_energy_subspace_overlap": top_subspace_overlap,
        }

    def enm_initialization_loss(self, condition, trans_eq, res_mask):
        """Warmup loss that aligns only the ENM direction subspace.

        ENM is used only as an initialization target. It is not an input feature
        and does not appear in the mode forward formula. The projection loss is
        invariant to per-mode sign flips and rotations inside a near-degenerate
        ENM subspace, unlike ordered mode-by-mode cosine matching.
        """
        targets = self._enm_motion_targets(trans_eq, res_mask)
        target_modes = targets["enm_modes"].to(device=condition["u_global"].device, dtype=torch.float32)
        center = self._masked_mean(trans_eq.float(), res_mask)
        centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]
        if self.template_remove_rotation:
            target_modes = self._remove_rigid_component(target_modes, centered, res_mask)
        subspace_loss, subspace_overlap = self._mode_subspace_loss(
            condition["u_global"].float(),
            target_modes,
            res_mask,
        )
        with torch.autocast(device_type=trans_eq.device.type, enabled=False):
            spatial_dists = torch.cdist(trans_eq.float(), trans_eq.float())
        align = self.motion_alignment_metrics(condition, targets, res_mask, spatial_dists)
        metrics = {
            "enm_warmup_loss": subspace_loss,
            "enm_warmup_subspace_loss": subspace_loss.detach(),
            "enm_warmup_subspace_overlap": subspace_overlap,
        }
        metrics.update({f"enm_warmup_{key}": value for key, value in align.items()})
        
        return metrics
    def motion_recon_loss(self, condition, targets, res_mask, spatial_dists=None):
        mask = res_mask.float()
        pair_mask = mask[:, :, None] * mask[:, None, :]
        eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
        offdiag_mask = pair_mask * (1.0 - eye)
        local_mask = mask[..., None, None]

        local_target = targets["local_cov"].to(condition["local_cov_pred"].device, condition["local_cov_pred"].dtype)
        cross_target = targets["cross_cov"].to(condition["cross_cov_pred"].device, condition["cross_cov_pred"].dtype)
        rmsf_target = targets["rmsf"].to(condition["rmsf_pred"].device, condition["rmsf_pred"].dtype)

        local_diff = (condition["local_cov_pred"] - local_target) * local_mask
        local_denom = ((local_target * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
        local_cov_loss = (local_diff.square().sum() / local_mask.sum().clamp_min(1.0)) / local_denom

        if spatial_dists is None:
            raise ValueError("spatial_dists is required for near/far cross-cov diagnostics")
        spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype)
        near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
        far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)

        cross_diff = (condition["cross_cov_pred"] - cross_target) * offdiag_mask
        cross_denom = ((cross_target * offdiag_mask).square().sum() / offdiag_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
        cross_cov_loss = (cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)) / cross_denom

        near_diff = (condition["cross_cov_pred"] - cross_target) * near_mask
        near_denom = ((cross_target * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
        cross_cov_near_loss = (near_diff.square().sum() / near_mask.sum().clamp_min(1.0)) / near_denom

        far_diff = (condition["cross_cov_pred"] - cross_target) * far_mask
        far_denom = ((cross_target * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
        cross_cov_far_loss = (far_diff.square().sum() / far_mask.sum().clamp_min(1.0)) / far_denom

        rmsf_diff = (condition["rmsf_pred"] - rmsf_target) * mask
        rmsf_denom = ((rmsf_target * mask).square().sum() / mask.sum().clamp_min(1.0)).clamp_min(1e-6)
        rmsf_loss = (rmsf_diff.square().sum() / mask.sum().clamp_min(1.0)) / rmsf_denom

        losses = {
            "local_cov_loss": local_cov_loss,
            "cross_cov_loss": cross_cov_loss,
            "cross_cov_near_loss": cross_cov_near_loss,
            "cross_cov_far_loss": cross_cov_far_loss,
            "rmsf_loss": rmsf_loss,
        }
        if "oracle_modes" in targets:
            losses.update(self.pca_alignment_loss(
                condition,
                targets,
                res_mask,
                top_m=int(getattr(self, "pca_align_top_m", 2)),
            ))
        return losses

    def generator_response_cov_loss(
        self,
        response_deltas,
        res_mask,
        targets,
        use_cross=False,
        sample_weight=None,
        teacher_response_deltas=None,
        teacher_trace_anchor=None,
        teacher_trace_denominator="teacher",
        amplitude_anchor="teacher_trace",
        trace_target_scale=None,
        oracle_rank=0,
    ):
        """Match generator response shape without rewarding global expansion.

        ``response_deltas`` has shape ``(S, B, N, 3)`` and contains antithetic
        central-difference responses for S independent coefficient perturbations.
        The loss first averages ``d d^T`` over S and then normalizes by total
        response trace before comparing to MD covariance. This avoids the v1
        shortcut where a single rank-1 sample, or a globally amplified response,
        can reduce the generator-response objective.

        If ``teacher_response_deltas`` is provided, a weak trace anchor keeps the
        current response norm near the frozen initial/A30 response under the same
        ``t`` and coefficient perturbations. This anchor does not assume that
        one-step trace equals the 20-step inference ensemble trace.

        ``oracle_rank > 0`` adds a term comparing the response covariance projected
        onto the cached MD principal directions against their variances. This is the
        only target in this function that lives in the basis the reported PCA-W2 is
        computed in: ``local_cov`` is per-residue 3x3 and ``cross_cov`` is summed
        over coordinates to N x N, so neither can identify a direction in the 3N
        space where the principal plane lives.

        Two limits are deliberate rather than incidental. It is a **shape** term
        only: by the law of total covariance the generated covariance splits into an
        initial-noise part and a coefficient-steerable part, ``response_deltas``
        approximates only the second, and ``oracle_energy`` is the total. Anchoring
        the response trace to the MD trace would double-count. And the projected
        covariance has rank at most ``S = response_deltas.shape[0]``, so a rank
        beyond that cannot be matched even in principle -- with the default two
        antithetic perturbations, ``oracle_rank`` above 2 is not estimable.
        """
        with torch.autocast(device_type=res_mask.device.type, enabled=False):
            d = response_deltas.float()
            if d.dim() == 3:
                d = d[None]
            mask = res_mask.float()
            if sample_weight is not None:
                mask = mask * sample_weight.float().to(mask.device)[:, None]
            d = d * mask[None, :, :, None]

            local_target = targets["local_cov"].to(device=d.device, dtype=d.dtype)
            target_mask = res_mask.float().to(device=d.device, dtype=d.dtype)
            local_mask = mask[:, :, None, None]
            target_local_mask = target_mask[:, :, None, None]

            local_sample = torch.einsum("sbni,sbnj->bnij", d, d) / float(d.shape[0])
            trace_sample = (
                torch.diagonal(local_sample, dim1=-2, dim2=-1).sum(dim=-1) * mask
            ).sum(dim=-1).clamp_min(1e-8)
            trace_target = (
                torch.diagonal(local_target, dim1=-2, dim2=-1).sum(dim=-1) * target_mask
            ).sum(dim=-1).clamp_min(1e-8)
            local_sample_norm = local_sample / trace_sample[:, None, None, None]
            local_target_norm = local_target / trace_target[:, None, None, None]
            local_diff = (local_sample_norm - local_target_norm) * local_mask
            local_denom = (
                (local_target_norm * target_local_mask).square().sum()
                / target_local_mask.sum().clamp_min(1.0)
            ).clamp_min(1e-8)
            local_shape_loss = (
                local_diff.square().sum() / local_mask.sum().clamp_min(1.0)
            ) / local_denom

            losses = {
                "gen_local_shape_loss": local_shape_loss,
            }
            metrics = {
                "gen_response_abs_mean": d.detach().abs().mean(),
                "gen_response_trace_mean": trace_sample.detach().mean(),
                "gen_response_active_frac": (
                    mask.sum() / res_mask.float().sum().clamp_min(1.0)
                ).detach(),
            }

            anchor_trace = None
            if amplitude_anchor in ("md_trace", "rollout_trace"):
                # Anchor the response magnitude to the MD ensemble's own trace.
                # trace_target is already computed above for the shape normalization,
                # so this needs no teacher and no extra forwards.
                # "rollout_trace" divides the MD trace by a detached no-grad
                # rollout-measured trace amplification factor before anchoring.
                #
                # The "teacher_trace" anchor below is unusable in this codebase: the frozen
                # teacher is deep-copied from the model at step 0, where every condition
                # adapter (embedder z_*/disp_* adapters and bbflow_model film_mlp) is
                # zero-initialized so that a warm-started model reproduces vanilla BBFlow.
                # The teacher's response to c is therefore identically zero forever, so
                # teacher_trace pins to the 1e-8 clamp floor and log(trace_sample/1e-8)^2
                # drives the student's response to zero -- the opposite of the anchor's
                # purpose. A model that ignores c cannot calibrate a response to c.
                anchor_trace = trace_target
                if trace_target_scale is not None:
                    scale = trace_target_scale.to(device=d.device, dtype=d.dtype)
                    anchor_trace = anchor_trace * scale.reshape(-1)[0].clamp_min(1e-8)
            elif amplitude_anchor != "none" and (
                teacher_response_deltas is not None or teacher_trace_anchor is not None
            ):
                if teacher_trace_anchor is not None:
                    teacher_trace = teacher_trace_anchor.to(device=d.device, dtype=d.dtype)
                    if teacher_trace.dim() > 1:
                        teacher_trace = teacher_trace.reshape(teacher_trace.shape[0], -1).mean(dim=-1)
                    teacher_trace = teacher_trace.reshape(-1).clamp_min(1e-8)
                else:
                    teacher_d = teacher_response_deltas.float()
                    if teacher_d.dim() == 3:
                        teacher_d = teacher_d[None]
                    teacher_d = teacher_d.to(device=d.device, dtype=d.dtype) * mask[None, :, :, None]
                    if teacher_trace_denominator == "teacher":
                        teacher_denom = float(teacher_d.shape[0])
                    elif teacher_trace_denominator == "student":
                        teacher_denom = float(d.shape[0])
                    elif teacher_trace_denominator == "none":
                        teacher_denom = 1.0
                    else:
                        raise ValueError(
                            "teacher_trace_denominator must be one of "
                            f"'teacher', 'student', or 'none'; got {teacher_trace_denominator!r}"
                        )
                    teacher_local = (
                        torch.einsum("sbni,sbnj->bnij", teacher_d, teacher_d)
                        / teacher_denom
                    )
                    teacher_trace = (
                        torch.diagonal(teacher_local, dim1=-2, dim2=-1).sum(dim=-1) * mask
                    ).sum(dim=-1).clamp_min(1e-8)
                anchor_trace = teacher_trace

            if anchor_trace is not None:
                valid = (mask.sum(dim=-1) > 0).to(dtype=d.dtype)
                trace_ratio = (trace_sample / anchor_trace).clamp_min(1e-8)
                trace_loss = (trace_ratio.log().square() * valid).sum() / valid.sum().clamp_min(1.0)
                losses["gen_trace_anchor_loss"] = trace_loss
                # Ratio to whichever amplitude anchor is active (MD trace or teacher trace).
                # Healthy value is ~1; orders of magnitude away means the anchor is broken.
                metrics["gen_trace_ratio_to_teacher"] = (
                    (trace_sample.detach() / anchor_trace.detach()).clamp_min(1e-8)
                    * valid
                ).sum() / valid.sum().clamp_min(1.0)
                metrics["gen_trace_ratio_to_anchor"] = metrics["gen_trace_ratio_to_teacher"]
                metrics["gen_trace_anchor_mean"] = anchor_trace.detach().mean()

            if use_cross:
                pair_mask = mask[:, :, None] * mask[:, None, :]
                target_pair_mask = target_mask[:, :, None] * target_mask[:, None, :]
                eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
                offdiag_mask = pair_mask * (1.0 - eye)
                target_offdiag_mask = target_pair_mask * (1.0 - eye)
                cross_target = targets["cross_cov"].to(device=d.device, dtype=d.dtype)
                cross_sample = torch.einsum("sbnd,sbmd->bnm", d, d) / float(d.shape[0])
                cross_sample_norm = cross_sample / trace_sample[:, None, None]
                cross_target_norm = cross_target / trace_target[:, None, None]
                cross_diff = (cross_sample_norm - cross_target_norm) * offdiag_mask
                cross_denom = (
                    (cross_target_norm * target_offdiag_mask).square().sum()
                    / target_offdiag_mask.sum().clamp_min(1.0)
                ).clamp_min(1e-8)
                cross_shape_loss = (
                    cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)
                ) / cross_denom
                losses["gen_cross_shape_loss"] = cross_shape_loss

            if int(oracle_rank or 0) > 0:
                for field in ("oracle_modes", "oracle_energy"):
                    if field not in targets:
                        raise KeyError(
                            f"generator_cov_oracle_rank > 0 requires {field} in the "
                            "motion target cache; regenerate it with "
                            "scripts/extract_shape_fingerprints.py"
                        )
                modes = targets["oracle_modes"].to(device=d.device, dtype=d.dtype)
                energy = targets["oracle_energy"].to(device=d.device, dtype=d.dtype)
                # The projected covariance is a sum of S outer products, so its rank
                # cannot exceed S. Accepting a larger request would silently train
                # against a target that is unmatchable by construction.
                if int(oracle_rank) > int(d.shape[0]):
                    raise ValueError(
                        f"generator_cov_oracle_rank={int(oracle_rank)} exceeds the "
                        f"{int(d.shape[0])} antithetic perturbations available; the "
                        "projected response covariance cannot have that rank. Raise "
                        "generator_cov_num_deltas or lower the rank."
                    )
                rank = min(int(oracle_rank), int(modes.shape[2]), int(energy.shape[1]))
                # Mask before renormalising: the cached modes are unit norm over the
                # full 3N of their own protein, and padding rows would otherwise
                # leak into the projection.
                basis = modes[:, :, :rank, :] * target_mask[:, :, None, None]
                basis = basis / torch.linalg.vector_norm(
                    basis, dim=(1, 3), keepdim=True
                ).clamp_min(1e-8)

                proj = torch.einsum("sbnd,bnrd->sbr", d, basis)
                resp_cov = torch.einsum("sbr,sbq->brq", proj, proj) / float(d.shape[0])
                resp_trace = torch.diagonal(resp_cov, dim1=-2, dim2=-1).sum(dim=-1)

                target_cov = torch.diag_embed(energy[:, :rank])
                target_trace = energy[:, :rank].sum(dim=-1)

                # Activity is decided by the exogenous masks alone, never by the
                # response magnitude. Gating on `resp_trace > eps` would hand the
                # model a discontinuous escape: shrink an example's response below
                # the threshold and its loss becomes exactly zero and it leaves the
                # denominator. That reads as training success while the objective is
                # being switched off example by example.
                #
                # Examples outside the t window still have to be excluded -- `d` was
                # zeroed for them upstream, so normalising their covariance would
                # charge them the full shape error for having been excluded -- but
                # that is a property of `sample_weight`, which is exogenous.
                active = (mask.sum(dim=-1) > 0) & (target_trace > 1e-8)
                resp_norm = resp_cov / resp_trace.clamp_min(1e-8)[:, None, None]
                target_norm = target_cov / target_trace.clamp_min(1e-8)[:, None, None]
                per_example = (resp_norm - target_norm).square().sum(dim=(-2, -1))
                oracle_shape_loss = (
                    (per_example * active.to(per_example.dtype)).sum()
                    / active.sum().clamp_min(1).to(per_example.dtype)
                )
                losses["gen_oracle_shape_loss"] = oracle_shape_loss
                metrics["gen_oracle_active_frac"] = (
                    active.detach().float().mean()
                )
                metrics["gen_oracle_rank_used"] = torch.tensor(
                    float(rank), device=d.device
                )
            return losses, metrics

    def motion_metrics(self, condition, res_mask):
        with torch.no_grad():
            mask = res_mask.float()
            energy = condition["energy"].float()
            energy_sum = energy.sum(dim=-1).clamp_min(1e-8)
            prob = energy / energy_sum[:, None]
            entropy = -(prob * prob.clamp_min(1e-8).log()).sum(dim=-1)
            effective_modes = torch.exp(entropy)
            u_flat = condition["u_global"].float().permute(0, 2, 1, 3).reshape(condition["u_global"].shape[0], condition["u_global"].shape[2], -1)
            u_flat = F.normalize(u_flat, dim=-1)
            if self.num_modes > 1:
                cos = torch.matmul(u_flat, u_flat.transpose(-1, -2))
                eye = torch.eye(self.num_modes, device=cos.device, dtype=torch.bool)[None].expand_as(cos)
                mode_cosine_abs = cos.masked_select(~eye).abs().mean()
            else:
                mode_cosine_abs = energy.new_zeros(())
            metrics = {
                "latent_energy_mean": energy.mean(),
                "latent_energy_std": energy.std(),
                "latent_effective_modes": effective_modes.mean(),
                "latent_mode_cosine_abs": mode_cosine_abs,
                "latent_node_cond_abs": condition["node_cond"].detach().abs().mean(),
                "latent_edge_cond_abs": condition["edge_cond"].detach().abs().mean(),
                "latent_u_global_abs": condition["u_global"].detach().abs().mean(),
                "latent_u_position_std": (condition["u_global"].detach().float() * mask[:, :, None, None]).std(),
            }
            if "template_participation" in condition:
                metrics.update({
                    "latent_template_participation_abs": condition["template_participation"].detach().float().abs().mean(),
                    "latent_template_omega_abs": condition["template_omega"].detach().float().abs().mean(),
                    "latent_template_velocity_abs": condition["template_velocity"].detach().float().abs().mean(),
                    "latent_template_residual_abs": condition["template_residual_global"].detach().float().abs().mean(),
                })
            if "mixture_logits" in condition:
                diag = torch.diagonal(condition["mixture_scale_tril"].detach().float(), dim1=-2, dim2=-1)
                metrics.update({
                    "q_mixture_entropy": self._mixture_entropy(condition["mixture_logits"].detach()).mean(),
                    "q_mu_abs": condition["mixture_mu"].detach().float().abs().mean(),
                    "q_scale_diag_mean": diag.mean(),
                    "q_scale_diag_std": diag.std(),
                })            
            return metrics