File size: 79,814 Bytes
3f316da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
#!/usr/bin/env python3
"""Controlled representation-learning baselines for the LOBench revision."""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import math
import os
import random
import socket
import sys
import time
from datetime import datetime, timezone
from functools import partial
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

ROOT = Path(__file__).resolve().parents[3]
SRC = ROOT / "experiments/adma2026_representation/src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from models import (  # noqa: E402
    Classifier,
    LOBConvGridEncoder,
    LOBShapeGatedFlowLevelSimLOBEncoder,
    LOBShapeFlowLevelSimLOBEncoder,
    LOBShapeFlowSimLOBEncoder,
    LOBShapeHybridLevelSimLOBEncoder,
    LOBShapeLevelSimLOBEncoder,
    LOBShapeStructuredLevelSimLOBEncoder,
    LOBGridEncoder,
    LOBShapeGridFusionEncoder,
    LOBShapeSimLOBEncoder,
    LOBShapeWideSimLOBEncoder,
    LOBStructEncoder,
    PositionalEncoding,
    SimLOBStyleEncoder,
    TLOB2025Encoder,
)
from train_downstream import (  # noqa: E402
    classification_metrics,
    count_parameters,
    evaluate,
    load_npz,
    sample_label_budget,
    set_seed,
    train_epoch,
)


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


def sha256_file(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(chunk_size):
            digest.update(chunk)
    return digest.hexdigest()


def sha256_tensor(tensor: torch.Tensor) -> str:
    import numpy as np  # noqa: PLC0415

    value = np.ascontiguousarray(
        tensor.detach().cpu().numpy(),
        dtype=np.int64,
    )
    return hashlib.sha256(value.tobytes()).hexdigest()


def sha256_state_dict(state_dict: dict[str, torch.Tensor]) -> str:
    digest = hashlib.sha256()
    for name in sorted(state_dict):
        value = state_dict[name].detach().cpu().contiguous()
        digest.update(name.encode("utf-8"))
        digest.update(b"\0")
        digest.update(str(tuple(value.shape)).encode("ascii"))
        digest.update(b"\0")
        digest.update(str(value.dtype).encode("ascii"))
        digest.update(b"\0")
        digest.update(value.numpy().tobytes())
    return digest.hexdigest()


def atomic_write_json(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}")
    temporary.write_text(json.dumps(value, indent=2), encoding="utf-8")
    os.replace(temporary, path)


def atomic_torch_save(state_dict: dict[str, torch.Tensor], path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}")
    torch.save(state_dict, temporary)
    os.replace(temporary, path)


def result_setting_name(config: dict, setting: str) -> str:
    return str(config.get("result_setting_names", {}).get(setting, setting))


def result_path_for(
    config: dict,
    stock: str,
    method: str,
    setting: str,
    seed: int,
    label_budget: float,
) -> Path:
    tag = int(round(label_budget * 100))
    condition = result_setting_name(config, setting)
    return Path(config["results_dir"]) / (
        f"{stock}_{method}_{condition}_seed{seed}_budget{tag:03d}.json"
    )


class AdapterClassifier(nn.Module):
    def __init__(self, encoder: nn.Module, latent_dim: int = 128, num_classes: int = 3, bottleneck: int = 32):
        super().__init__()
        self.encoder = encoder
        self.adapter = nn.Sequential(
            nn.LayerNorm(latent_dim),
            nn.Linear(latent_dim, bottleneck),
            nn.GELU(),
            nn.Linear(bottleneck, latent_dim),
        )
        self.head = nn.Sequential(nn.LayerNorm(latent_dim), nn.Linear(latent_dim, num_classes))

    def forward(self, x):
        z = self.encoder(x)
        z = z + self.adapter(z)
        return self.head(z)


class TransformerBackbone(nn.Module):
    def __init__(self, latent_dim: int = 128, d_model: int = 96, layers: int = 2, nhead: int = 4):
        super().__init__()
        self.in_proj = nn.Linear(40, d_model)
        self.pos = PositionalEncoding(d_model)
        layer = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=nhead,
            dim_feedforward=4 * d_model,
            batch_first=True,
            dropout=0.1,
            activation="gelu",
        )
        self.encoder = nn.TransformerEncoder(layer, num_layers=layers)
        self.out = nn.Linear(d_model, latent_dim)

    def sequence(self, x):
        return self.encoder(self.pos(self.in_proj(x)))

    def forward(self, x):
        return self.out(self.sequence(x).mean(dim=1))


class DilatedConvBackbone(nn.Module):
    def __init__(self, latent_dim: int = 128, d_model: int = 96):
        super().__init__()
        self.in_proj = nn.Conv1d(40, d_model, kernel_size=1)
        self.blocks = nn.ModuleList(
            [
                nn.Sequential(
                    nn.Conv1d(d_model, d_model, kernel_size=3, padding=d, dilation=d),
                    nn.GELU(),
                    nn.Conv1d(d_model, d_model, kernel_size=1),
                )
                for d in (1, 2, 4, 8)
            ]
        )
        self.norm = nn.LayerNorm(d_model)
        self.out = nn.Linear(d_model, latent_dim)

    def sequence(self, x):
        h = self.in_proj(x.transpose(1, 2))
        for block in self.blocks:
            h = h + block(h)
        return self.norm(h.transpose(1, 2))

    def forward(self, x):
        return self.out(self.sequence(x).mean(dim=1))


def legalize_lob_prices(raw, gap_scale: float = 0.02):
    bid_raw = raw[:, :, :10].flip(-1)
    ask_raw = raw[:, :, 10:20]
    best_bid = bid_raw[:, :, :1]
    spread = torch.nn.functional.softplus(ask_raw[:, :, :1] - bid_raw[:, :, :1]) * gap_scale + 1e-5
    bid_gaps = torch.nn.functional.softplus(bid_raw[:, :, 1:]) * gap_scale + 1e-5
    ask_gaps = torch.nn.functional.softplus(ask_raw[:, :, 1:]) * gap_scale + 1e-5
    bid_near = torch.cat([best_bid, best_bid - torch.cumsum(bid_gaps, dim=-1)], dim=-1)
    best_ask = best_bid + spread
    ask_near = torch.cat([best_ask, best_ask + torch.cumsum(ask_gaps, dim=-1)], dim=-1)
    out = raw.clone()
    out[:, :, :10] = bid_near.flip(-1)
    out[:, :, 10:20] = ask_near
    return out


class ReconstructionPretrainer(nn.Module):
    def __init__(self, encoder: nn.Module, d_model: int = 96, legalize_prices: bool = False):
        super().__init__()
        self.encoder = encoder
        self.decode = nn.Sequential(nn.Linear(d_model, d_model), nn.GELU(), nn.Linear(d_model, 40))
        self.legalize_prices = legalize_prices

    def forward(self, x):
        pred = self.decode(self.encoder.sequence(x))
        if self.legalize_prices:
            pred = legalize_lob_prices(pred)
        return pred


class TrendReconstructionPretrainer(ReconstructionPretrainer):
    def __init__(self, encoder: nn.Module, d_model: int = 96, legalize_prices: bool = False, latent_dim: int = 128):
        super().__init__(encoder, d_model=d_model, legalize_prices=legalize_prices)
        self.trend_head = nn.Sequential(nn.LayerNorm(latent_dim), nn.Linear(latent_dim, 3))
        self.auxtrend_weight = 0.25
        self.auxtrend_class_weights = None

    def trend_logits(self, x):
        return self.trend_head(self.encoder(x))


class TFCPretrainer(nn.Module):
    def __init__(self, latent_dim: int, d_model: int):
        super().__init__()
        self.encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model)
        self.freq_encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model)

    def frequency_view(self, x):
        freq = torch.fft.rfft(x, dim=1).abs()
        if freq.size(1) < x.size(1):
            freq = torch.nn.functional.pad(freq, (0, 0, 0, x.size(1) - freq.size(1)))
        return freq[:, : x.size(1)]

    def forward(self, x):
        return self.encoder(x), self.freq_encoder(self.frequency_view(x))


def make_loader(x, y, idx, batch_size, shuffle, num_workers=0, pin_memory=False):
    return DataLoader(
        TensorDataset(x[idx], y[idx]),
        batch_size=batch_size,
        shuffle=shuffle,
        num_workers=num_workers,
        pin_memory=pin_memory,
    )


def load_npz_with_train_index(
    path: Path,
    index_key: str = "train_idx",
    relabel_threshold: float | None = None,
):
    x, y, splits = load_npz(path)
    if index_key != "train_idx" or relabel_threshold is not None:
        import numpy as np  # noqa: PLC0415

        data = np.load(path)
        if index_key != "train_idx":
            if index_key not in data.files:
                raise KeyError(f"{path} does not contain requested index {index_key}")
            splits["train"] = torch.tensor(data[index_key], dtype=torch.long)
        if relabel_threshold is not None:
            if relabel_threshold <= 0:
                raise ValueError("The relabel threshold must be positive")
            if "future_returns" not in data.files:
                raise KeyError(f"{path} does not contain future_returns")
            future_returns = data["future_returns"]
            labels = np.where(
                future_returns > relabel_threshold,
                2,
                np.where(future_returns < -relabel_threshold, 0, 1),
            )
            y = torch.tensor(labels, dtype=torch.long)
    return x, y, splits


def load_test_group_ids(path: Path, test_idx) -> list[str] | None:
    """Return exchange-date labels aligned with the test-loader order."""

    import numpy as np  # noqa: PLC0415

    data = np.load(path)
    if "end_times" not in data.files:
        if "relative_day_id" in data.files:
            return [str(value) for value in data["relative_day_id"][test_idx.cpu().numpy()]]
        return None
    values = data["end_times"][test_idx.cpu().numpy()]
    return [str(value).split("T", 1)[0].split(" ", 1)[0] for value in values]


def data_path_for_stock(config, stock: str) -> Path:
    template = str(config.get("data_file_template", "{stock}_pilot.npz"))
    return Path(config["processed_dir"]) / template.format(stock=stock)


def make_pooled_loader(config, stocks, split, batch_size, shuffle, num_workers=0, pin_memory=False):
    xs = []
    ys = []
    keep_labels = bool(config.get("pooled_keep_labels", False))
    pretrain_index_key = str(config.get("pretrain_index_key", "train_idx"))
    for stock in stocks:
        x, y, splits = load_npz_with_train_index(
            data_path_for_stock(config, stock),
            pretrain_index_key,
        )
        idx = splits[split]
        xs.append(x[idx])
        ys.append(y[idx] if keep_labels else torch.zeros(len(idx), dtype=torch.long))
    return DataLoader(
        TensorDataset(torch.cat(xs, dim=0), torch.cat(ys, dim=0)),
        batch_size=batch_size,
        shuffle=shuffle,
        num_workers=num_workers,
        pin_memory=pin_memory,
    )


def _log_epochs_enabled(cfg):
    return bool(cfg.get("log_epochs", False))


def _log_epoch(cfg, message):
    if _log_epochs_enabled(cfg):
        print(message, flush=True)


def augment(x, mask_prob: float = 0.12, noise_std: float = 0.02):
    out = x + noise_std * torch.randn_like(x)
    mask = torch.rand_like(out) < mask_prob
    return out.masked_fill(mask, 0.0)


def mask_points(x, mask_prob: float):
    mask = torch.rand(x.size(0), x.size(1), 1, device=x.device) < mask_prob
    return x.masked_fill(mask, 0.0), mask.expand_as(x)


def mask_patches(x, patch_len: int = 10, mask_ratio: float = 0.35):
    bsz, steps, _ = x.shape
    n_patches = max(1, steps // patch_len)
    patch_mask = torch.rand(bsz, n_patches, device=x.device) < mask_ratio
    mask = torch.zeros(bsz, steps, 1, device=x.device, dtype=torch.bool)
    for i in range(n_patches):
        mask[:, i * patch_len : min((i + 1) * patch_len, steps)] = patch_mask[:, i].view(bsz, 1, 1)
    return x.masked_fill(mask, 0.0), mask.expand_as(x)


def nt_xent(z1, z2, temperature: float = 0.2):
    z1 = torch.nn.functional.normalize(z1, dim=1)
    z2 = torch.nn.functional.normalize(z2, dim=1)
    logits = z1 @ z2.t() / temperature
    labels = torch.arange(z1.size(0), device=z1.device)
    return 0.5 * (
        torch.nn.functional.cross_entropy(logits, labels)
        + torch.nn.functional.cross_entropy(logits.t(), labels)
    )


def frequency_loss(pred, target):
    pred_freq = torch.fft.rfft(pred, dim=1).abs()
    target_freq = torch.fft.rfft(target, dim=1).abs()
    return torch.mean((pred_freq - target_freq) ** 2)


def lob_sides(x):
    bid_p = x[:, :, :10].flip(-1)
    ask_p = x[:, :, 10:20]
    bid_v = x[:, :, 20:30].flip(-1)
    ask_v = x[:, :, 30:40]
    return bid_p, ask_p, bid_v, ask_v


def lob_validity_penalty(
    pred,
    volume_zero_threshold=None,
    price_zero_threshold=None,
    price_gap_margin=0.0,
):
    """Soft LOB constraints in normalized coordinates.

    Price ordering and spread are invariant under the benchmark's shared
    positive affine price transform. Raw volume zero is not invariant under
    z-scoring, so callers must provide its normalized value
    ``(0 - volume_mean) / volume_std``. If it is unavailable, the volume term is
    deliberately omitted instead of using the minimum target value as a
    surrogate.
    """
    bid_p, ask_p, bid_v, ask_v = lob_sides(pred)
    gap = torch.as_tensor(
        price_gap_margin,
        dtype=pred.dtype,
        device=pred.device,
    ).reshape(1, 1, 1)
    bid_order = torch.relu(gap - (bid_p[:, :, :-1] - bid_p[:, :, 1:])).mean()
    ask_order = torch.relu(gap - (ask_p[:, :, 1:] - ask_p[:, :, :-1])).mean()
    spread = torch.relu(gap - (ask_p[:, :, :1] - bid_p[:, :, :1])).mean()
    volume = pred[:, :, 20:40]
    if price_zero_threshold is not None:
        price_floor = torch.as_tensor(
            price_zero_threshold,
            dtype=pred.dtype,
            device=pred.device,
        ).reshape(1, 1, 1)
        price_penalty = torch.relu(price_floor - pred[:, :, :20]).mean()
    else:
        price_penalty = pred.new_zeros(())
    if volume_zero_threshold is not None:
        volume_floor = torch.as_tensor(
            volume_zero_threshold,
            dtype=volume.dtype,
            device=volume.device,
        ).reshape(1, 1, 1)
        volume_penalty = torch.relu(volume_floor - volume).mean()
    else:
        volume_penalty = volume.new_zeros(())
    return bid_order + ask_order + spread + price_penalty + volume_penalty


def lob_aware_reconstruction_loss(
    pred,
    target,
    mask=None,
    structure_weight: float = 2.0,
    volume_zero_threshold=None,
    price_zero_threshold=None,
    price_gap_margin=0.0,
):
    if mask is not None and mask.any():
        mse = torch.mean((pred[mask] - target[mask]) ** 2)
    else:
        mse = torch.mean((pred - target) ** 2)
    return mse + structure_weight * lob_validity_penalty(
        pred,
        volume_zero_threshold=volume_zero_threshold,
        price_zero_threshold=price_zero_threshold,
        price_gap_margin=price_gap_margin,
    )


def inverse_grouped_normalization(x, normalization):
    raw = x.clone()
    raw[:, :, :20] = (
        raw[:, :, :20] * float(normalization["price_std"])
        + float(normalization["price_mean"])
    )
    raw[:, :, 20:40] = (
        raw[:, :, 20:40] * float(normalization["volume_std"])
        + float(normalization["volume_mean"])
    )
    return raw


def lob_validity_metrics(
    pred,
    target=None,
    normalization=None,
    raw_price_tick_size=None,
):
    """Return strict/weak validity and, when possible, raw-unit errors.

    Raw volume validity and price/volume MAE are emitted only when the exact
    training-partition normalization statistics are supplied.
    """
    with torch.no_grad():
        evaluated_pred = (
            inverse_grouped_normalization(pred, normalization)
            if normalization is not None
            else pred
        )
        evaluated_target = (
            inverse_grouped_normalization(target, normalization)
            if target is not None and normalization is not None
            else target
        )
        bid_p, ask_p, _, _ = lob_sides(evaluated_pred)
        spread_gap = ask_p[:, :, 0] - bid_p[:, :, 0]
        bid_gaps = bid_p[:, :, :-1] - bid_p[:, :, 1:]
        ask_gaps = ask_p[:, :, 1:] - ask_p[:, :, :-1]
        spread_bad = spread_gap <= 0
        bid_strict_bad = (bid_p[:, :, 1:] >= bid_p[:, :, :-1]).any(dim=-1)
        ask_strict_bad = (ask_p[:, :, 1:] <= ask_p[:, :, :-1]).any(dim=-1)
        bid_weak_bad = (bid_p[:, :, 1:] > bid_p[:, :, :-1]).any(dim=-1)
        ask_weak_bad = (ask_p[:, :, 1:] < ask_p[:, :, :-1]).any(dim=-1)
        metrics = {
            "spread_cross_rate": float(spread_bad.float().mean().item()),
            "spread_valid_rate": float((~spread_bad).float().mean().item()),
            "bid_order_strict_bad_rate": float(bid_strict_bad.float().mean().item()),
            "bid_order_strict_valid_rate": float((~bid_strict_bad).float().mean().item()),
            "ask_order_strict_bad_rate": float(ask_strict_bad.float().mean().item()),
            "ask_order_strict_valid_rate": float((~ask_strict_bad).float().mean().item()),
            "bid_order_weak_bad_rate": float(bid_weak_bad.float().mean().item()),
            "bid_order_weak_valid_rate": float((~bid_weak_bad).float().mean().item()),
            "ask_order_weak_bad_rate": float(ask_weak_bad.float().mean().item()),
            "ask_order_weak_valid_rate": float((~ask_weak_bad).float().mean().item()),
        }
        if normalization is not None:
            price_bad = (evaluated_pred[:, :, :20] <= 0).any(dim=-1)
            volume = evaluated_pred[:, :, 20:40]
            volume_bad = (volume < 0).any(dim=-1)
            any_bad = (
                spread_bad
                | bid_strict_bad
                | ask_strict_bad
                | price_bad
                | volume_bad
            )
            metrics.update(
                {
                    "price_nonpositive_rate": float(price_bad.float().mean().item()),
                    "price_positive_valid_rate": float((~price_bad).float().mean().item()),
                    "volume_negative_rate": float(volume_bad.float().mean().item()),
                    "volume_nonnegative_valid_rate": float((~volume_bad).float().mean().item()),
                    "any_lob_illegal_rate": float(any_bad.float().mean().item()),
                    "all_lob_constraints_valid_rate": float((~any_bad).float().mean().item()),
                }
            )
            if raw_price_tick_size is not None:
                tick = float(raw_price_tick_size)
                if tick <= 0:
                    raise ValueError("raw_price_tick_size must be positive")
                tolerance = max(1e-8, tick * 1e-4)
                tick_bid_bad = (bid_gaps < tick - tolerance).any(dim=-1)
                tick_ask_bad = (ask_gaps < tick - tolerance).any(dim=-1)
                tick_spread_bad = spread_gap < tick - tolerance
                tick_price_bad = (evaluated_pred[:, :, :20] < tick - tolerance).any(dim=-1)
                joint_bad = (
                    tick_bid_bad
                    | tick_ask_bad
                    | tick_spread_bad
                    | tick_price_bad
                    | volume_bad
                )
                bid_violation = torch.relu(tick - bid_gaps) / tick
                ask_violation = torch.relu(tick - ask_gaps) / tick
                spread_violation = torch.relu(tick - spread_gap) / tick
                price_violation = torch.relu(tick - evaluated_pred[:, :, :20]) / tick
                all_price_violations = torch.cat(
                    [
                        bid_violation.reshape(-1),
                        ask_violation.reshape(-1),
                        spread_violation.reshape(-1),
                        price_violation.reshape(-1),
                    ]
                )
                metrics.update(
                    {
                        "raw_price_tick_size": tick,
                        "tick_bid_order_valid_rate": float((~tick_bid_bad).float().mean().item()),
                        "tick_ask_order_valid_rate": float((~tick_ask_bad).float().mean().item()),
                        "tick_spread_valid_rate": float((~tick_spread_bad).float().mean().item()),
                        "tick_price_positive_valid_rate": float((~tick_price_bad).float().mean().item()),
                        "joint_five_constraint_snapshot_valid_rate": float((~joint_bad).float().mean().item()),
                        "bid_order_violation_ticks": float(bid_violation.mean().item()),
                        "ask_order_violation_ticks": float(ask_violation.mean().item()),
                        "spread_violation_ticks": float(spread_violation.mean().item()),
                        "price_floor_violation_ticks": float(price_violation.mean().item()),
                        "mean_price_constraint_violation_ticks": float(all_price_violations.mean().item()),
                    }
                )
            if evaluated_target is not None:
                metrics["raw_price_mae"] = float(
                    torch.mean(torch.abs(evaluated_pred[:, :, :20] - evaluated_target[:, :, :20])).item()
                )
                metrics["raw_volume_mae"] = float(
                    torch.mean(torch.abs(evaluated_pred[:, :, 20:40] - evaluated_target[:, :, 20:40])).item()
                )
        return metrics


def build_method(
    method: str,
    latent_dim: int,
    d_model: int,
    nhead: int = 4,
):
    if method == "ts2vec":
        return DilatedConvBackbone(latent_dim=latent_dim, d_model=d_model)
    if method in {"simmtm", "timae", "timae_lobloss", "timae_softlobloss", "timesurl", "tfc"}:
        return TransformerBackbone(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
    if method in {"lobconv_timae", "lobconv_timae_lobloss", "lobconv_timae_softlobloss"}:
        return LOBConvGridEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobgrid_timae", "lobgrid_timae_lobloss", "lobgrid_timae_softlobloss"}:
        return LOBGridEncoder(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
    if method in {"lobstruct_timae", "lobstruct_timae_lobloss"}:
        return LOBStructEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"tlob2025", "tlob2025_lobloss", "tlob2025_softlobloss"}:
        return TLOB2025Encoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"simlob2026", "simlob2026_lobloss", "simlob2026_softlobloss"}:
        return SimLOBStyleEncoder(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
    if method in {
        "lobshape_simlob",
        "lobshape_simlob_lobloss",
        "lobshape_simlob_lobloss_auxtrend",
        "lobshape_simlob_twostage_lobloss",
    }:
        return LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_level_simlob", "lobshape_level_simlob_lobloss"}:
        return LOBShapeLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_structured_level_simlob", "lobshape_structured_level_simlob_lobloss"}:
        return LOBShapeStructuredLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_hybrid_level_simlob", "lobshape_hybrid_level_simlob_lobloss"}:
        return LOBShapeHybridLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_flow_simlob", "lobshape_flow_simlob_lobloss", "lobshape_flow_simlob_lobloss_auxtrend"}:
        return LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_flow_level_simlob", "lobshape_flow_level_simlob_lobloss"}:
        return LOBShapeFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_gated_flow_level_simlob", "lobshape_gated_flow_level_simlob_lobloss"}:
        return LOBShapeGatedFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_wide_simlob", "lobshape_wide_simlob_lobloss"}:
        return LOBShapeWideSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
    if method in {"lobshape_gridfusion", "lobshape_gridfusion_lobloss"}:
        return LOBShapeGridFusionEncoder(latent_dim=latent_dim, d_model=d_model)
    raise KeyError(f"unknown representation baseline method: {method}")


def _run_pretrain_stage(
    model,
    save_model,
    train_step,
    val_step,
    train_loader,
    val_loader,
    cfg,
    device,
    ckpt_path,
    stage_name,
    epochs,
    patience,
    learning_rate,
):
    opt = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=cfg["weight_decay"])
    best = float("inf")
    best_epoch = 0
    history = []
    epochs_without_improvement = 0
    started = time.perf_counter()
    for epoch in range(1, int(epochs) + 1):
        epoch_started = time.perf_counter()
        model.train()
        train_loss = 0.0
        train_n = 0
        for x, y in train_loader:
            x = x.to(device)
            y = y.to(device)
            opt.zero_grad(set_to_none=True)
            loss = train_step(model, x, y)
            loss.backward()
            opt.step()
            train_loss += float(loss.item()) * len(x)
            train_n += len(x)
        model.eval()
        val_loss = 0.0
        val_n = 0
        with torch.no_grad():
            for x, y in val_loader:
                x = x.to(device)
                y = y.to(device)
                loss = val_step(model, x, y)
                val_loss += float(loss.item()) * len(x)
                val_n += len(x)
        train_loss /= max(train_n, 1)
        val_loss /= max(val_n, 1)
        history.append(
            {
                "stage": stage_name,
                "epoch": epoch,
                "train_loss": train_loss,
                "val_loss": val_loss,
                "epoch_seconds": time.perf_counter() - epoch_started,
            }
        )
        next_best = min(best, val_loss)
        _log_epoch(
            cfg,
            f"EPOCH pretrain:{stage_name} {epoch}/{int(epochs)} "
            f"train_loss={train_loss:.6f} val_loss={val_loss:.6f} "
            f"best={next_best:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}",
        )
        if val_loss < best:
            best = val_loss
            best_epoch = epoch
            atomic_torch_save(save_model.state_dict(), ckpt_path)
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1
        if patience and epochs_without_improvement >= patience:
            break
    return {
        "stage": stage_name,
        "best_val_loss": best,
        "best_epoch": best_epoch,
        "seconds": time.perf_counter() - started,
        "history": history,
    }


def pretrain_method(
    method,
    latent_dim,
    d_model,
    train_loader,
    val_loader,
    cfg,
    device,
    ckpt_path,
    *,
    nhead=4,
    mask_ratio=0.4,
    force=False,
):
    meta_path = ckpt_path.with_suffix(".pretrain.json")
    if not force and ckpt_path.exists() and meta_path.exists():
        return json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True}

    if method == "lobshape_simlob_twostage_lobloss":
        encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=False).to(device)
        stage1_epochs = int(cfg.get("twostage_mse_epochs", max(1, int(cfg["pretrain_epochs"]) // 2)))
        stage2_epochs = int(cfg.get("twostage_lob_epochs", max(1, int(cfg["pretrain_epochs"]) - stage1_epochs)))
        stage1_patience = int(cfg.get("twostage_mse_patience", cfg.get("pretrain_patience", 0)))
        stage2_patience = int(cfg.get("twostage_lob_patience", cfg.get("pretrain_patience", 0)))
        stage1_path = ckpt_path.with_suffix(".mse_stage.pt")
        stage1 = _run_pretrain_stage(
            model,
            model.encoder,
            timae_step,
            timae_step,
            train_loader,
            val_loader,
            cfg,
            device,
            stage1_path,
            "mse",
            stage1_epochs,
            stage1_patience,
            float(cfg["learning_rate"]),
        )
        model.encoder.load_state_dict(torch.load(stage1_path, map_location=device))
        model.legalize_prices = True
        stage2 = _run_pretrain_stage(
            model,
            model.encoder,
            lob_aware_timae_step,
            lob_aware_timae_step,
            train_loader,
            val_loader,
            cfg,
            device,
            ckpt_path,
            "lob_aware",
            stage2_epochs,
            stage2_patience,
            float(cfg.get("twostage_lob_learning_rate", float(cfg["learning_rate"]) * 0.5)),
        )
        history = stage1["history"] + stage2["history"]
        meta = {
            "method": method,
            "best_val_loss": stage2["best_val_loss"],
            "best_epoch": stage1_epochs + stage2["best_epoch"],
            "seconds": stage1["seconds"] + stage2["seconds"],
            "stages": [
                {key: value for key, value in stage1.items() if key != "history"},
                {key: value for key, value in stage2.items() if key != "history"},
            ],
            "history": history,
            "cached": False,
            "implementation": "local_lite_twostage",
        }
        atomic_write_json(meta_path, meta)
        return meta

    if method == "ts2vec":
        model = DilatedConvBackbone(latent_dim=latent_dim, d_model=d_model).to(device)
        train_step = ts2vec_step
        val_step = ts2vec_step
        save_model = model
    elif method == "tfc":
        model = TFCPretrainer(latent_dim=latent_dim, d_model=d_model).to(device)
        train_step = tfc_step
        val_step = tfc_step
        save_model = model.encoder
    elif method == "simmtm":
        encoder = TransformerBackbone(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
        model = ReconstructionPretrainer(encoder, d_model=d_model).to(device)
        train_step = simmtm_step
        val_step = simmtm_step
        save_model = model.encoder
    elif method in {"timae", "timae_lobloss", "timae_softlobloss"}:
        encoder = TransformerBackbone(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
        use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss")
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        step = lob_aware_timae_step if use_lob_loss else timae_step
        train_step = partial(step, mask_ratio=mask_ratio)
        val_step = partial(step, mask_ratio=mask_ratio)
        save_model = model.encoder
    elif method in {"lobconv_timae", "lobconv_timae_lobloss", "lobconv_timae_softlobloss"}:
        encoder = LOBConvGridEncoder(latent_dim=latent_dim, d_model=d_model)
        use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss")
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if use_lob_loss else timae_step
        val_step = lob_aware_timae_step if use_lob_loss else timae_step
        save_model = model.encoder
    elif method in {"lobgrid_timae", "lobgrid_timae_lobloss", "lobgrid_timae_softlobloss"}:
        encoder = LOBGridEncoder(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
        use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss")
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        step = lob_aware_timae_step if use_lob_loss else timae_step
        train_step = partial(step, mask_ratio=mask_ratio)
        val_step = partial(step, mask_ratio=mask_ratio)
        save_model = model.encoder
    elif method in {"lobstruct_timae", "lobstruct_timae_lobloss"}:
        encoder = LOBStructEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"tlob2025", "tlob2025_lobloss", "tlob2025_softlobloss"}:
        encoder = TLOB2025Encoder(latent_dim=latent_dim, d_model=d_model)
        use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss")
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if use_lob_loss else timae_step
        val_step = lob_aware_timae_step if use_lob_loss else timae_step
        save_model = model.encoder
    elif method in {"simlob2026", "simlob2026_lobloss", "simlob2026_softlobloss"}:
        encoder = SimLOBStyleEncoder(
            latent_dim=latent_dim,
            d_model=d_model,
            nhead=nhead,
        )
        use_lob_loss = method.endswith("_lobloss") or method.endswith("_softlobloss")
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        step = lob_aware_timae_step if use_lob_loss else timae_step
        train_step = partial(step, mask_ratio=mask_ratio)
        val_step = partial(step, mask_ratio=mask_ratio)
        save_model = model.encoder
    elif method in {"lobshape_simlob", "lobshape_simlob_lobloss"}:
        encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_level_simlob", "lobshape_level_simlob_lobloss"}:
        encoder = LOBShapeLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_structured_level_simlob", "lobshape_structured_level_simlob_lobloss"}:
        encoder = LOBShapeStructuredLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_hybrid_level_simlob", "lobshape_hybrid_level_simlob_lobloss"}:
        encoder = LOBShapeHybridLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method == "lobshape_simlob_lobloss_auxtrend":
        encoder = LOBShapeSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = TrendReconstructionPretrainer(
            encoder,
            d_model=d_model,
            legalize_prices=True,
            latent_dim=latent_dim,
        ).to(device)
        model.auxtrend_weight = float(cfg.get("auxtrend_weight", 0.25))
        if cfg.get("auxtrend_class_weights") is not None:
            model.auxtrend_class_weights = torch.tensor(
                cfg["auxtrend_class_weights"],
                dtype=torch.float32,
                device=device,
            )
        train_step = auxtrend_lob_aware_timae_step
        val_step = auxtrend_lob_aware_timae_step
        save_model = model.encoder
    elif method in {"lobshape_flow_simlob", "lobshape_flow_simlob_lobloss"}:
        encoder = LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_flow_level_simlob", "lobshape_flow_level_simlob_lobloss"}:
        encoder = LOBShapeFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_gated_flow_level_simlob", "lobshape_gated_flow_level_simlob_lobloss"}:
        encoder = LOBShapeGatedFlowLevelSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method == "lobshape_flow_simlob_lobloss_auxtrend":
        encoder = LOBShapeFlowSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = TrendReconstructionPretrainer(
            encoder,
            d_model=d_model,
            legalize_prices=True,
            latent_dim=latent_dim,
        ).to(device)
        model.auxtrend_weight = float(cfg.get("auxtrend_weight", 0.25))
        if cfg.get("auxtrend_class_weights") is not None:
            model.auxtrend_class_weights = torch.tensor(
                cfg["auxtrend_class_weights"],
                dtype=torch.float32,
                device=device,
            )
        train_step = auxtrend_lob_aware_timae_step
        val_step = auxtrend_lob_aware_timae_step
        save_model = model.encoder
    elif method in {"lobshape_wide_simlob", "lobshape_wide_simlob_lobloss"}:
        encoder = LOBShapeWideSimLOBEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method in {"lobshape_gridfusion", "lobshape_gridfusion_lobloss"}:
        encoder = LOBShapeGridFusionEncoder(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model, legalize_prices=method.endswith("_lobloss")).to(device)
        train_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        val_step = lob_aware_timae_step if method.endswith("_lobloss") else timae_step
        save_model = model.encoder
    elif method == "timesurl":
        encoder = TransformerBackbone(latent_dim=latent_dim, d_model=d_model)
        model = ReconstructionPretrainer(encoder, d_model=d_model).to(device)
        train_step = timesurl_step
        val_step = timesurl_step
        save_model = model.encoder
    else:
        raise KeyError(method)

    opt = torch.optim.AdamW(model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"])
    best = float("inf")
    best_epoch = 0
    history = []
    epochs_without_improvement = 0
    patience = int(cfg.get("pretrain_patience", 0))
    started = time.perf_counter()
    for epoch in range(1, int(cfg["pretrain_epochs"]) + 1):
        epoch_started = time.perf_counter()
        model.train()
        train_loss = 0.0
        train_n = 0
        for x, y in train_loader:
            x = x.to(device)
            y = y.to(device)
            opt.zero_grad(set_to_none=True)
            loss = train_step(model, x, y)
            loss.backward()
            opt.step()
            train_loss += float(loss.item()) * len(x)
            train_n += len(x)
        model.eval()
        val_loss = 0.0
        val_n = 0
        with torch.no_grad():
            for x, y in val_loader:
                x = x.to(device)
                y = y.to(device)
                loss = val_step(model, x, y)
                val_loss += float(loss.item()) * len(x)
                val_n += len(x)
        train_loss /= max(train_n, 1)
        val_loss /= max(val_n, 1)
        history.append(
            {
                "epoch": epoch,
                "train_loss": train_loss,
                "val_loss": val_loss,
                "epoch_seconds": time.perf_counter() - epoch_started,
            }
        )
        next_best = min(best, val_loss)
        _log_epoch(
            cfg,
            f"EPOCH pretrain:{method} {epoch}/{int(cfg['pretrain_epochs'])} "
            f"train_loss={train_loss:.6f} val_loss={val_loss:.6f} "
            f"best={next_best:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}",
        )
        if val_loss < best:
            best = val_loss
            best_epoch = epoch
            atomic_torch_save(save_model.state_dict(), ckpt_path)
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1
        if patience and epochs_without_improvement >= patience:
            break

    meta = {
        "method": method,
        "best_val_loss": best,
        "best_epoch": best_epoch,
        "seconds": time.perf_counter() - started,
        "history": history,
        "stopped_epoch": len(history),
        "batches_per_epoch": len(train_loader),
        "optimizer_steps": len(history) * len(train_loader),
        "cached": False,
        "epoch_cap": int(cfg["pretrain_epochs"]),
        "patience": int(cfg.get("pretrain_patience", 0)),
        "max_epoch_hit": len(history) >= int(cfg["pretrain_epochs"]),
        "implementation": "controlled_benchmark_v1",
        "hyperparameters": {
            "latent_dim": int(latent_dim),
            "d_model": int(d_model),
            "nhead": int(nhead),
            "mask_ratio": float(mask_ratio),
            "learning_rate": float(cfg["learning_rate"]),
            "batch_size": int(cfg["batch_size"]),
            "epoch_cap": int(cfg["pretrain_epochs"]),
            "patience": int(cfg.get("pretrain_patience", 0)),
        },
    }
    atomic_write_json(meta_path, meta)
    return meta


def ts2vec_step(model, x, y=None):
    z1 = model(augment(x))
    z2 = model(augment(x))
    return nt_xent(z1, z2)


def tfc_step(model, x, y=None):
    time_z, freq_z = model(augment(x))
    return nt_xent(time_z, freq_z)


def simmtm_step(model, x, y=None):
    masked, mask = mask_points(x, mask_prob=0.25)
    pred = model(masked)
    recon = torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2)
    align = nt_xent(model.encoder(x), model.encoder(masked))
    return recon + 0.2 * align


def timae_step(model, x, y=None, mask_ratio=0.4):
    masked, mask = mask_patches(x, patch_len=10, mask_ratio=mask_ratio)
    pred = model(masked)
    return torch.mean((pred[mask] - x[mask]) ** 2) if mask.any() else torch.mean((pred - x) ** 2)


def lob_aware_timae_step(model, x, y=None, mask_ratio=0.4):
    masked, mask = mask_patches(x, patch_len=10, mask_ratio=mask_ratio)
    pred = model(masked)
    return lob_aware_reconstruction_loss(pred, x, mask=mask, structure_weight=2.0)


def auxtrend_lob_aware_timae_step(model, x, y=None):
    masked, mask = mask_patches(x, patch_len=10, mask_ratio=0.4)
    pred = model(masked)
    recon = lob_aware_reconstruction_loss(pred, x, mask=mask, structure_weight=2.0)
    if y is None:
        return recon
    logits = model.trend_logits(x)
    trend = torch.nn.functional.cross_entropy(logits, y, weight=model.auxtrend_class_weights)
    return recon + float(model.auxtrend_weight) * trend


def timesurl_step(model, x, y=None):
    point_masked, point_mask = mask_points(x, mask_prob=0.2)
    pred = model(point_masked)
    recon = torch.mean((pred[point_mask] - x[point_mask]) ** 2) if point_mask.any() else torch.mean((pred - x) ** 2)
    contrast = nt_xent(model.encoder(augment(x)), model.encoder(augment(x, mask_prob=0.18, noise_std=0.015)))
    return recon + 0.2 * contrast + 0.05 * frequency_loss(pred, x)


def collect_logits(model, loader, device):
    model.eval()
    logits_all = []
    y_all = []
    with torch.no_grad():
        for x, y in loader:
            logits_all.append(model(x.to(device)).cpu())
            y_all.append(y)
    return torch.cat(logits_all), torch.cat(y_all)


def confusion_summary(logits, y_true):
    pred = logits.argmax(dim=1)
    matrix = torch.zeros(3, 3, dtype=torch.long)
    for true_cls in range(3):
        for pred_cls in range(3):
            matrix[true_cls, pred_cls] = ((y_true == true_cls) & (pred == pred_cls)).sum()
    pred_counts = torch.bincount(pred, minlength=3)
    true_counts = torch.bincount(y_true, minlength=3)
    return {
        "matrix_rows_true_cols_pred": matrix.tolist(),
        "pred_counts": pred_counts.tolist(),
        "true_counts": true_counts.tolist(),
    }


def classification_metrics_by_group(logits, y_true, group_ids):
    if group_ids is None:
        return None
    if len(group_ids) != len(y_true):
        raise ValueError(
            f"group label count {len(group_ids)} does not match predictions {len(y_true)}"
        )
    rows = {}
    for group in sorted(set(group_ids)):
        keep = torch.tensor(
            [value == group for value in group_ids],
            dtype=torch.bool,
        )
        rows[group] = {
            "n": int(keep.sum().item()),
            "metrics": classification_metrics(logits[keep], y_true[keep]),
            "confusion": confusion_summary(logits[keep], y_true[keep]),
        }
    return rows


def evaluate_with_logit_bias(model, loader, device, bias):
    logits, y_true = collect_logits(model, loader, device)
    bias_tensor = torch.tensor(bias, dtype=logits.dtype).view(1, -1)
    return classification_metrics(logits + bias_tensor, y_true)


def tune_logit_bias(model, val_loader, device):
    logits, y_true = collect_logits(model, val_loader, device)
    best_bias = torch.zeros(3)
    best_metrics = classification_metrics(logits, y_true)
    best_score = best_metrics["macro_f1"]
    grid = torch.linspace(-1.5, 1.5, steps=13)
    for b0 in grid:
        for b1 in grid:
            for b2 in grid:
                bias = torch.tensor([b0, b1, b2], dtype=logits.dtype)
                bias = bias - bias.mean()
                metrics = classification_metrics(logits + bias.view(1, -1), y_true)
                if metrics["macro_f1"] > best_score:
                    best_score = metrics["macro_f1"]
                    best_metrics = metrics
                    best_bias = bias
    return {"bias": [float(v) for v in best_bias.tolist()], "val": best_metrics}


def train_downstream_model(
    encoder,
    x,
    y,
    splits,
    train_idx,
    train_cfg,
    setting,
    device,
    return_artifacts=False,
    test_group_ids=None,
):
    if setting == "multiinit_fine_tune":
        trials = []
        best_result = None
        best_score = -1.0
        start_seed = int(train_cfg.get("multiinit_seed_start", 31000))
        for init_id in range(int(train_cfg.get("multiinit_count", 5))):
            set_seed(start_seed + init_id)
            trial = train_downstream_model(
                copy.deepcopy(encoder),
                x,
                y,
                splits,
                train_idx,
                train_cfg,
                "fine_tune",
                device,
                return_artifacts=False,
                test_group_ids=test_group_ids,
            )
            trials.append(
                {
                    "init_id": init_id,
                    "seed": start_seed + init_id,
                    "best_val_macro_f1": trial["best_val_macro_f1"],
                    "best_epoch": trial["best_epoch"],
                    "test": trial["test"],
                    "test_confusion": trial["test_confusion"],
                    "downstream_seconds": trial["downstream_seconds"],
                }
            )
            if trial["best_val_macro_f1"] > best_score:
                best_score = trial["best_val_macro_f1"]
                best_result = trial
        best_result = copy.deepcopy(best_result)
        best_result["multiinit"] = {
            "selected_by": "validation_macro_f1",
            "count": len(trials),
            "trials": trials,
        }
        best_result["downstream_seconds"] = sum(trial["downstream_seconds"] for trial in trials)
        return best_result

    ensemble_pairs = {
        "probe_finetune_ensemble": ("frozen_probe", "fine_tune"),
        "probe_adapter_ensemble": ("frozen_probe", "adapter_tune"),
        "adapter_finetune_ensemble": ("adapter_tune", "fine_tune"),
    }
    if setting in ensemble_pairs:
        left_name, right_name = ensemble_pairs[setting]
        left = train_downstream_model(
            copy.deepcopy(encoder),
            x,
            y,
            splits,
            train_idx,
            train_cfg,
            left_name,
            device,
            return_artifacts=True,
            test_group_ids=test_group_ids,
        )
        right = train_downstream_model(
            copy.deepcopy(encoder),
            x,
            y,
            splits,
            train_idx,
            train_cfg,
            right_name,
            device,
            return_artifacts=True,
            test_group_ids=test_group_ids,
        )
        best_alpha = 0.0
        best_val = None
        best_score = -1.0
        for alpha in torch.linspace(0.0, 1.0, steps=int(train_cfg.get("ensemble_alpha_steps", 21))):
            alpha_value = float(alpha.item())
            val_logits = (1.0 - alpha_value) * left["_val_logits"] + alpha_value * right["_val_logits"]
            metrics = classification_metrics(val_logits, left["_val_true"])
            if metrics["macro_f1"] > best_score:
                best_score = metrics["macro_f1"]
                best_alpha = alpha_value
                best_val = metrics
        test_logits = (1.0 - best_alpha) * left["_test_logits"] + best_alpha * right["_test_logits"]
        test_metrics = classification_metrics(test_logits, left["_test_true"])
        result = {
            "parameters": {
                "total": left["parameters"]["total"] + right["parameters"]["total"],
                "trainable": left["parameters"]["trainable"] + right["parameters"]["trainable"],
            },
            "best_val_macro_f1": best_score,
            "best_epoch": {
                left_name: left["best_epoch"],
                right_name: right["best_epoch"],
            },
            "downstream_seconds": left["downstream_seconds"] + right["downstream_seconds"],
            "val": best_val,
            "test": test_metrics,
            "val_confusion": confusion_summary(
                (1.0 - best_alpha) * left["_val_logits"] + best_alpha * right["_val_logits"],
                left["_val_true"],
            ),
            "test_confusion": confusion_summary(test_logits, left["_test_true"]),
            "test_by_group": classification_metrics_by_group(
                test_logits,
                left["_test_true"],
                test_group_ids,
            ),
            "calibration": None,
            "history": {
                left_name: left["history"],
                right_name: right["history"],
            },
            "ensemble": {
                f"alpha_{right_name}": best_alpha,
                f"alpha_{left_name}": 1.0 - best_alpha,
                f"{left_name}_test": left["test"],
                f"{right_name}_test": right["test"],
                f"{left_name}_best_val_macro_f1": left["best_val_macro_f1"],
                f"{right_name}_best_val_macro_f1": right["best_val_macro_f1"],
            },
        }
        return result

    if setting in {"frozen_probe", "adapter_tune", "calibrated_probe", "adapter_calibrated"}:
        for param in encoder.parameters():
            param.requires_grad = False
    if setting == "fusion_tune":
        for param in encoder.parameters():
            param.requires_grad = False
        for module_name in ("fuse", "time_score", "out"):
            module = getattr(encoder, module_name, None)
            if module is not None:
                for param in module.parameters():
                    param.requires_grad = True
    if setting in {"adapter_tune", "adapter_calibrated"}:
        model = AdapterClassifier(
            encoder,
            latent_dim=int(train_cfg["latent_dim"]),
            bottleneck=int(train_cfg.get("adapter_bottleneck", 32)),
        ).to(device)
    else:
        model = Classifier(encoder, latent_dim=int(train_cfg["latent_dim"])).to(device)
    parameters = count_parameters(model)
    if setting == "slow_fine_tune" and hasattr(model, "encoder") and hasattr(model, "head"):
        encoder_lr = float(train_cfg["learning_rate"]) * float(train_cfg.get("encoder_lr_mult", 0.25))
        opt = torch.optim.AdamW(
            [
                {"params": [p for p in model.encoder.parameters() if p.requires_grad], "lr": encoder_lr},
                {"params": [p for p in model.head.parameters() if p.requires_grad], "lr": train_cfg["learning_rate"]},
            ],
            weight_decay=train_cfg["weight_decay"],
        )
    else:
        opt = torch.optim.AdamW(
            [p for p in model.parameters() if p.requires_grad],
            lr=train_cfg["learning_rate"],
            weight_decay=train_cfg["weight_decay"],
        )
    class_weights = train_cfg.get("class_weights")
    if class_weights == "balanced":
        counts = torch.bincount(y[train_idx], minlength=3).to(dtype=torch.float32)
        weights = counts.sum() / (3.0 * counts.clamp_min(1.0))
        criterion = nn.CrossEntropyLoss(weight=weights.to(device))
    elif class_weights is not None:
        criterion = nn.CrossEntropyLoss(weight=torch.tensor(class_weights, dtype=torch.float32, device=device))
    else:
        criterion = nn.CrossEntropyLoss()
    batch_size = int(train_cfg["batch_size"])
    num_workers = int(train_cfg.get("num_workers", 0))
    pin_memory = device.type == "cuda"
    train_loader = make_loader(x, y, train_idx, batch_size, True, num_workers, pin_memory)
    val_loader = make_loader(x, y, splits["val"], batch_size, False, num_workers, pin_memory)
    test_loader = make_loader(x, y, splits["test"], batch_size, False, num_workers, pin_memory)
    best_val_macro_f1 = -1.0
    best_epoch = 0
    best_state = copy.deepcopy(model.state_dict())
    history = []
    patience = int(train_cfg.get("downstream_patience", 0))
    epochs_without_improvement = 0
    started = time.perf_counter()
    for epoch in range(1, int(train_cfg["downstream_epochs"]) + 1):
        epoch_started = time.perf_counter()
        loss = train_epoch(model, train_loader, opt, device, criterion)
        metrics = evaluate(model, val_loader, device)
        if metrics["macro_f1"] > best_val_macro_f1:
            best_val_macro_f1 = metrics["macro_f1"]
            best_epoch = epoch
            best_state = copy.deepcopy(model.state_dict())
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1
        history.append(
            {
                "epoch": epoch,
                "loss": loss,
                "epoch_seconds": time.perf_counter() - epoch_started,
                **{f"val_{k}": v for k, v in metrics.items()},
            }
        )
        _log_epoch(
            train_cfg,
            f"EPOCH downstream:{setting} {epoch}/{int(train_cfg['downstream_epochs'])} "
            f"loss={loss:.6f} val_macro_f1={metrics['macro_f1']:.6f} "
            f"best={best_val_macro_f1:.6f} epoch_seconds={history[-1]['epoch_seconds']:.2f}",
        )
        if patience and epochs_without_improvement >= patience:
            break
    model.load_state_dict(best_state)
    calibration = None
    val_logits, val_true = collect_logits(model, val_loader, device)
    test_logits, test_true = collect_logits(model, test_loader, device)
    val_metrics = classification_metrics(val_logits, val_true)
    test_metrics = classification_metrics(test_logits, test_true)
    val_confusion = confusion_summary(val_logits, val_true)
    test_confusion = confusion_summary(test_logits, test_true)
    if setting in {"calibrated_probe", "adapter_calibrated", "fine_tune_calibrated"}:
        calibration = tune_logit_bias(model, val_loader, device)
        bias_tensor = torch.tensor(calibration["bias"], dtype=val_logits.dtype).view(1, -1)
        val_metrics = classification_metrics(val_logits + bias_tensor, val_true)
        test_metrics = classification_metrics(test_logits + bias_tensor, test_true)
        val_confusion = confusion_summary(val_logits + bias_tensor, val_true)
        test_confusion = confusion_summary(test_logits + bias_tensor, test_true)
    result = {
        "parameters": parameters,
        "best_val_macro_f1": best_val_macro_f1,
        "best_epoch": best_epoch,
        "downstream_seconds": time.perf_counter() - started,
        "val": val_metrics,
        "test": test_metrics,
        "val_confusion": val_confusion,
        "test_confusion": test_confusion,
        "test_by_group": classification_metrics_by_group(
            test_logits,
            test_true,
            test_group_ids,
        ),
        "calibration": calibration,
        "history": history,
        "stopped_epoch": len(history),
        "epoch_cap": int(train_cfg["downstream_epochs"]),
        "patience": patience,
        "max_epoch_hit": len(history) >= int(train_cfg["downstream_epochs"]),
        "optimizer_steps": len(history) * len(train_loader),
        "batches_per_epoch": len(train_loader),
    }
    if return_artifacts:
        result["_val_logits"] = val_logits
        result["_val_true"] = val_true
        result["_test_logits"] = test_logits
        result["_test_true"] = test_true
    return result


def completed_result(path: Path) -> bool:
    if not path.exists():
        return False
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return False
    return value.get("status") == "complete" and isinstance(value.get("test"), dict)


def checkpoint_pair_valid(ckpt: Path, meta_path: Path) -> bool:
    if not ckpt.exists() or not meta_path.exists():
        return False
    try:
        meta = json.loads(meta_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return False
    expected = meta.get("checkpoint_sha256")
    return bool(expected) and expected == sha256_file(ckpt)


def index_provenance(path: Path, index_key: str) -> dict:
    import numpy as np  # noqa: PLC0415

    with np.load(path) as data:
        if index_key not in data.files:
            raise KeyError(f"{path} does not contain requested index {index_key}")
        indices = np.asarray(data[index_key], dtype=np.int64)
    contiguous = np.ascontiguousarray(indices, dtype=np.int64)
    return {
        "samples": int(len(indices)),
        "index_sha256": hashlib.sha256(contiguous.tobytes()).hexdigest(),
    }


def dataset_provenance(config: dict, stock: str, data_path: Path) -> dict:
    manifest_path = Path(
        config.get(
            "dataset_manifest",
            Path(config["processed_dir"]).parent / "manifest.json",
        )
    )
    value = {
        "dataset_path": str(data_path.resolve()),
        "manifest_path": str(manifest_path.resolve()),
    }
    if not manifest_path.exists():
        value["manifest_available"] = False
        return value
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    duration = str(config.get("duration", Path(config["processed_dir"]).name))
    condition = manifest.get("stocks", {}).get(stock, {}).get("conditions", {}).get(duration, {})
    value.update(
        {
            "manifest_available": True,
            "manifest_schema": manifest.get("manifest_schema"),
            "manifest_sha256": sha256_file(manifest_path),
            "dataset_sha256": condition.get("npz_sha256"),
            "train_dates": condition.get("train_dates"),
            "validation_dates": condition.get("validation_dates"),
            "test_dates": condition.get("test_dates"),
            "normalization": condition.get("normalization"),
            "holdout_fingerprints": condition.get("holdout_fingerprints"),
        }
    )
    return value


def run_one(
    config,
    stock,
    method,
    seed,
    label_budget,
    settings,
    force=False,
    force_pretrain=False,
):
    train_cfg = config["training"]
    out_dir = Path(config["results_dir"])
    out_dir.mkdir(parents=True, exist_ok=True)
    result_paths = [
        result_path_for(config, stock, method, setting, seed, label_budget)
        for setting in settings
    ]
    if not force and all(completed_result(path) for path in result_paths):
        print(f"SKIP {stock} {method}: downstream results already exist", flush=True)
        return

    set_seed(seed)
    device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu")
    data_path = data_path_for_stock(config, stock)
    downstream_index_key = str(config.get("downstream_index_key", "train_idx"))
    pretrain_index_key = str(config.get("pretrain_index_key", "train_idx"))
    data_cfg = config.get("data", {})
    relabel_threshold = (
        float(data_cfg["label_threshold"])
        if data_cfg.get("relabel_from_future_returns", False)
        else None
    )
    x, y, splits = load_npz_with_train_index(
        data_path,
        downstream_index_key,
        relabel_threshold=relabel_threshold,
    )
    test_group_ids = load_test_group_ids(data_path, splits["test"])
    _log_epoch(
        train_cfg,
        f"START {stock} {method} seed={seed} budget={label_budget} "
        f"device={device} train={len(splits['train'])} val={len(splits['val'])} test={len(splits['test'])}",
    )
    batch_size = int(train_cfg["batch_size"])
    num_workers = int(train_cfg.get("num_workers", 0))
    pin_memory = device.type == "cuda"
    pretrain_scope = config.get("pretrain_scope", "local")
    pretrain_stocks = config.get("pretrain_stocks", config.get("stocks", [stock]))
    pretrain_id = config.get("pretrain_id", f"pooled{len(pretrain_stocks)}")
    latent_dim = int(train_cfg["latent_dim"])
    d_model = int(train_cfg.get("d_model", 96))
    nhead = int(train_cfg.get("nhead", 4))
    mask_ratio = float(train_cfg.get("mask_ratio", 0.4))
    if d_model % nhead:
        raise ValueError(
            f"d_model={d_model} must be divisible by nhead={nhead}"
        )
    if not 0.0 < mask_ratio < 1.0:
        raise ValueError(f"mask_ratio must lie in (0, 1), got {mask_ratio}")
    pretrain_dir = Path(config.get("pretrain_dir", out_dir))
    pretrain_dir.mkdir(parents=True, exist_ok=True)
    if pretrain_scope == "pooled":
        ckpt = pretrain_dir / f"{pretrain_id}_{method}_seed{seed}_encoder.pt"
        pretrain_run_id = f"{config.get('duration', 'duration')}:{pretrain_id}:{method}:seed{seed}"
    else:
        ckpt = pretrain_dir / f"{stock}_{method}_seed{seed}_encoder.pt"
        pretrain_run_id = (
            f"{config.get('duration', 'duration')}:target-local:{stock}:{method}:seed{seed}"
        )
    meta_path = ckpt.with_suffix(".pretrain.json")
    needs_pretraining = any(setting != "from_scratch" for setting in settings)
    if not needs_pretraining:
        pretrain = {
            "method": method,
            "skipped": True,
            "seconds": 0.0,
            "history": [],
            "best_epoch": None,
            "stopped_epoch": 0,
            "batches_per_epoch": 0,
            "optimizer_steps": 0,
            "cached": False,
            "epoch_cap": int(train_cfg.get("pretrain_epochs", 0)),
            "patience": int(train_cfg.get("pretrain_patience", 0)),
            "max_epoch_hit": False,
        }
    elif not force_pretrain and checkpoint_pair_valid(ckpt, meta_path):
        pretrain = json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True}
        _log_epoch(train_cfg, f"PRETRAIN cache hit {ckpt}")
    else:
        producer_started = utc_now()
        if pretrain_scope == "pooled":
            train_loader = make_pooled_loader(config, pretrain_stocks, "train", batch_size, True, num_workers, pin_memory)
            val_loader = make_pooled_loader(config, pretrain_stocks, "val", batch_size, False, num_workers, pin_memory)
        else:
            _, _, pretrain_splits = load_npz_with_train_index(data_path, pretrain_index_key)
            train_loader = make_loader(x, y, pretrain_splits["train"], batch_size, True, num_workers, pin_memory)
            val_loader = make_loader(x, y, splits["val"], batch_size, False, num_workers, pin_memory)
        pretrain = pretrain_method(
            method,
            latent_dim,
            d_model,
            train_loader,
            val_loader,
            train_cfg,
            device,
            ckpt,
            nhead=nhead,
            mask_ratio=mask_ratio,
            # The outer checksum-aware cache check already decided that this
            # pair must be produced (or reproduced).
            force=True,
        )
        producer_finished = utc_now()
        partition_stocks = pretrain_stocks if pretrain_scope == "pooled" else [stock]
        partition_provenance = {
            value: index_provenance(
                data_path_for_stock(config, value),
                pretrain_index_key,
            )
            for value in partition_stocks
        }
        pretrain.update(
            {
                "cached": False,
                "run_id": pretrain_run_id,
                "scope": pretrain_scope,
                "duration": config.get("duration"),
                "checkpoint_path": str(ckpt.resolve()),
                "checkpoint_sha256": sha256_file(ckpt),
                "meta_path": str(meta_path.resolve()),
                "train_partitions": partition_provenance,
                "natural_partition_concatenation": pretrain_scope == "pooled",
                "producer_started_at_utc": producer_started,
                "producer_finished_at_utc": producer_finished,
                "cache_producer": {
                    "hostname": socket.gethostname(),
                    "pid": os.getpid(),
                    "stock_invocation": stock,
                    "task_id": os.environ.get("LOBENCH_TASK_ID"),
                    "attempt": int(os.environ.get("LOBENCH_RUN_ATTEMPT", "1")),
                },
                "epoch_cap": int(train_cfg["pretrain_epochs"]),
                "patience": int(train_cfg.get("pretrain_patience", 0)),
            }
        )
        pretrain["max_epoch_hit"] = int(pretrain.get("stopped_epoch", 0)) >= int(
            train_cfg["pretrain_epochs"]
        )
        atomic_write_json(meta_path, pretrain)
    if needs_pretraining and not checkpoint_pair_valid(ckpt, meta_path):
        raise RuntimeError(f"Incomplete or checksum-mismatched pretrain cache: {ckpt}")
    downstream_train_idx = sample_label_budget(y, splits["train"], label_budget, seed)
    train_class_counts = torch.bincount(y[downstream_train_idx], minlength=3)
    downstream_index_sha256 = sha256_tensor(downstream_train_idx)
    data_lineage = dataset_provenance(config, stock, data_path)

    for setting, result_path in zip(settings, result_paths):
        if completed_result(result_path) and not force:
            print(f"SKIP {stock} {method} {setting}: {result_path}", flush=True)
            continue
        # Reset before every downstream arm so that the random encoder/head
        # initialization is paired across from-scratch and pretrained controls.
        set_seed(seed)
        encoder = build_method(method, latent_dim, d_model, nhead=nhead)
        uses_pretraining = setting != "from_scratch"
        if uses_pretraining:
            encoder.load_state_dict(torch.load(ckpt, map_location="cpu"))
        initial_encoder_state_sha256 = sha256_state_dict(encoder.state_dict())
        downstream_setting = "fine_tune" if setting == "from_scratch" else setting
        downstream = train_downstream_model(
            encoder,
            x,
            y,
            splits,
            downstream_train_idx,
            train_cfg,
            downstream_setting,
            device,
            test_group_ids=test_group_ids,
        )
        condition_name = result_setting_name(config, setting)
        training_condition = (
            "direct"
            if setting == "from_scratch"
            else ("pooled" if pretrain_scope == "pooled" else "target_local")
        )
        task_id = os.environ.get("LOBENCH_TASK_ID") or (
            f"{config.get('duration')}__{training_condition}__{stock}__"
            f"{method}__seed{seed}"
        )
        result = {
            "schema": "training_duration_core_result_v1",
            "status": "complete",
            "experiment_id": config.get("experiment_id"),
            "config_path": config.get("_config_path"),
            "config_sha256": config.get("_config_sha256"),
            "duration": config.get("duration"),
            "stock": stock,
            "method": method,
            "setting": setting,
            "condition": condition_name,
            "training_condition": training_condition,
            "downstream_setting": downstream_setting,
            "initialization": "pretrained" if uses_pretraining else "random",
            "pretrain_used": uses_pretraining,
            "seed": seed,
            "label_budget": label_budget,
            "label_horizon": config.get("data", {}).get("label_horizon"),
            "label_threshold": config.get("data", {}).get("label_threshold"),
            "hyperparameters": {
                "latent_dim": latent_dim,
                "d_model": d_model,
                "nhead": nhead,
                "mask_ratio": mask_ratio,
                "learning_rate": float(train_cfg["learning_rate"]),
                "batch_size": int(train_cfg["batch_size"]),
                "weight_decay": float(train_cfg["weight_decay"]),
                "pretrain_epoch_cap": int(train_cfg.get("pretrain_epochs", 0)),
                "pretrain_patience": int(train_cfg.get("pretrain_patience", 0)),
                "downstream_epoch_cap": int(train_cfg["downstream_epochs"]),
                "downstream_patience": int(train_cfg.get("downstream_patience", 0)),
            },
            "train_samples": int(len(downstream_train_idx)),
            "full_train_samples": int(len(splits["train"])),
            "downstream_train_index_sha256": downstream_index_sha256,
            "downstream_train_index_count": int(len(downstream_train_idx)),
            "downstream_train_index_class_counts": {
                "down": int(train_class_counts[0]),
                "stationary": int(train_class_counts[1]),
                "up": int(train_class_counts[2]),
            },
            "downstream_train_class_counts": {
                "down": int(train_class_counts[0]),
                "stationary": int(train_class_counts[1]),
                "up": int(train_class_counts[2]),
            },
            "classification_head": {
                "architecture": "LayerNorm(latent_dim)+Linear(latent_dim,3)",
                "latent_dim": latent_dim,
                "classes": ["down", "stationary", "up"],
                "paired_initialization_seed": seed,
            },
            "pretrain": pretrain,
            "pretrain_scope": pretrain_scope if uses_pretraining else "none",
            "configured_pretrain_scope": pretrain_scope,
            "pretrain_id": (
                pretrain_id if pretrain_scope == "pooled" else stock
            ) if uses_pretraining else None,
            "pretrain_run_id": pretrain_run_id if uses_pretraining else None,
            "pretrain_index_key": pretrain_index_key,
            "downstream_index_key": downstream_index_key,
            "pretrain_cached": bool(pretrain.get("cached")),
            "pretrain_cache_dir": str(pretrain_dir),
            "encoder_checkpoint_path": str(ckpt.resolve()) if uses_pretraining else None,
            "encoder_checkpoint_sha256": sha256_file(ckpt) if uses_pretraining else None,
            "initial_encoder_state_sha256": initial_encoder_state_sha256,
            "random_initialization_sha256": (
                initial_encoder_state_sha256 if not uses_pretraining else None
            ),
            "data_lineage": data_lineage,
            "reproducibility": {
                "paired_seed_reset": True,
                "deterministic_algorithms": bool(
                    torch.are_deterministic_algorithms_enabled()
                ),
                "cudnn_deterministic": bool(torch.backends.cudnn.deterministic),
                "cudnn_benchmark": bool(torch.backends.cudnn.benchmark),
                "task_id": task_id,
                "attempt": int(os.environ.get("LOBENCH_RUN_ATTEMPT", "1")),
            },
            "data_protocol": {
                "sessions": config.get("data", {}).get("sessions"),
                "session_end_inclusive": config.get("data", {}).get(
                    "session_end_inclusive"
                ),
                "sampling": config.get("data", {}).get("sampling"),
                "label_budget_sampling": "per-class-stratified-within-natural-train",
            },
            **downstream,
        }
        result["total_seconds"] = result["downstream_seconds"] + (
            float(pretrain.get("seconds", 0.0)) if uses_pretraining else 0.0
        )
        result["completed_at_utc"] = utc_now()
        atomic_write_json(result_path, result)
        print(
            f"DONE {stock} {method} {setting}: "
            f"macro_f1={result['test']['macro_f1']:.4f} acc={result['test']['accuracy']:.4f}",
            flush=True,
        )


def summarize(config, name: str):
    out_dir = Path(config["results_dir"])
    rows = []
    for path in sorted(out_dir.glob("*.json")):
        if path.name.endswith(".pretrain.json"):
            continue
        data = json.loads(path.read_text(encoding="utf-8"))
        if "test" not in data:
            continue
        rows.append(
            {
                "stock": data["stock"],
                "method": data["method"],
                "setting": data["setting"],
                "seed": data["seed"],
                "label_budget": data["label_budget"],
                "macro_f1": data["test"]["macro_f1"],
                "balanced_accuracy": data["test"]["balanced_accuracy"],
                "accuracy": data["test"]["accuracy"],
                "best_epoch": data["best_epoch"],
                "pretrain_best_epoch": data["pretrain"].get("best_epoch"),
                "total_seconds": data["total_seconds"],
            }
        )
    summary_dir = out_dir.parent / "summary"
    summary_dir.mkdir(parents=True, exist_ok=True)
    csv_path = summary_dir / f"{name}_per_stock.csv"
    md_path = summary_dir / f"{name}_summary.md"
    if rows:
        import csv

        with csv_path.open("w", newline="", encoding="utf-8") as fh:
            writer = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
            writer.writeheader()
            writer.writerows(rows)
    grouped = {}
    for row in rows:
        grouped.setdefault((row["method"], row["setting"]), []).append(row["macro_f1"])
    lines = [f"# {name} Summary", "", "| method | setting | n | mean_macro_f1 |", "|---|---|---:|---:|"]
    for (method, setting), values in sorted(grouped.items()):
        lines.append(f"| {method} | {setting} | {len(values)} | {sum(values) / len(values):.4f} |")
    md_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"wrote {csv_path}", flush=True)
    print(f"wrote {md_path}", flush=True)


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", required=True)
    parser.add_argument("--stocks", nargs="+")
    parser.add_argument("--methods", nargs="+")
    parser.add_argument("--settings", nargs="+")
    parser.add_argument("--seeds", nargs="+", type=int)
    parser.add_argument("--label-budgets", nargs="+", type=float)
    parser.add_argument("--force", action="store_true")
    parser.add_argument("--force-pretrain", action="store_true")
    parser.add_argument("--pretrain-epochs", type=int, default=None)
    parser.add_argument("--downstream-epochs", type=int, default=None)
    parser.add_argument("--summarize-only", action="store_true")
    parser.add_argument("--no-summarize", action="store_true")
    parser.add_argument("--name", default=None)
    return parser.parse_args()


def main():
    args = parse_args()
    config_path = Path(args.config)
    config = json.loads(config_path.read_text(encoding="utf-8"))
    config["_config_path"] = str(config_path.resolve())
    config["_config_sha256"] = sha256_file(config_path)
    if args.pretrain_epochs is not None:
        config["training"]["pretrain_epochs"] = int(args.pretrain_epochs)
    if args.downstream_epochs is not None:
        config["training"]["downstream_epochs"] = int(args.downstream_epochs)
    name = args.name or Path(args.config).stem
    if args.summarize_only:
        summarize(config, name)
        return
    stocks = args.stocks or config["stocks"]
    methods = args.methods or config["methods"]
    settings = args.settings or config["settings"]
    seeds = args.seeds or config["seeds"]
    label_budgets = args.label_budgets or config["label_budgets"]
    total = len(stocks) * len(methods) * len(seeds) * len(label_budgets)
    i = 0
    for stock in stocks:
        for method in methods:
            for seed in seeds:
                for label_budget in label_budgets:
                    i += 1
                    print(f"RUN {i}/{total} {stock} {method} seed={seed} budget={label_budget}", flush=True)
                    run_one(
                        config,
                        stock,
                        method,
                        seed,
                        label_budget,
                        settings,
                        force=args.force,
                        force_pretrain=args.force_pretrain,
                    )
    if not args.no_summarize:
        summarize(config, name)


if __name__ == "__main__":
    main()