File size: 73,213 Bytes
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d305e3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
196a33b
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90f559d
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90f559d
 
 
 
 
 
196a33b
 
 
 
 
4f2fd46
196a33b
 
 
 
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90f559d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90f559d
 
 
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
196a33b
 
 
 
4f2fd46
196a33b
 
4f2fd46
196a33b
4f2fd46
 
 
 
196a33b
4f2fd46
 
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
196a33b
4f2fd46
196a33b
 
 
 
 
 
 
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
196a33b
4f2fd46
 
 
 
 
196a33b
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
4f2fd46
 
 
196a33b
 
4f2fd46
 
 
 
 
196a33b
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
196a33b
4f2fd46
196a33b
4f2fd46
 
 
196a33b
4f2fd46
 
 
 
196a33b
4f2fd46
 
196a33b
 
4f2fd46
196a33b
4f2fd46
 
 
 
 
196a33b
4f2fd46
 
196a33b
4f2fd46
196a33b
4f2fd46
196a33b
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
4ad8f70
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ad8f70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
4ad8f70
 
 
 
 
196a33b
 
 
4f2fd46
 
 
 
 
 
4ad8f70
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
4f2fd46
196a33b
 
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
4f2fd46
196a33b
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
196a33b
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d305e3e
 
 
 
 
 
 
 
 
 
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ad8f70
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
4f2fd46
 
 
 
 
 
 
196a33b
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
 
 
 
4f2fd46
196a33b
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196a33b
 
 
 
 
 
4f2fd46
196a33b
 
 
4f2fd46
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Meta-Learner Inference Script

Loads a deployment config exported by meta_learner_trainer.py and runs
inference on new data.

Usage:
    python meta_learner_inference.py \
        --config     meta_outputs/deployment/deployment_config.json \
        --data_path  new_data.parquet \
        --text_col   text \
        --output_path predictions.parquet

The output parquet contains:
    - All original columns from new_data.parquet
    - predicted_label       : string label (e.g. "NEAR")
    - predicted_class       : integer class index
    - prob_{class}          : softmax probability for each class
    - meta_confidence       : max probability (argmax confidence)

How base model inference works
-------------------------------
Each selected model has K fold checkpoints. All K are loaded and their
probability outputs are averaged before feeding to the meta-learner.
This matches training: the meta-learner was trained on OOF probs which
are averaged fold outputs. Using a single fold would introduce bias.

For split_unknown_stage models, stage1 and stage2 are run independently
and their outputs composed to the final class probabilities.

For tfidf_lgbm, the fold_1 pickle is used (TF-IDF models are deterministic
so fold averaging doesn't apply in the same way).
"""
# =============================================================================
# LABEL MAPPING CONVENTION (read this before creating a new task!)
#
# The --mapping_dict_path json MUST contain EVERY label value present in the
# data, in this form (example from condition_tier):
#
#     { "N": -1, "D": 1, "C": 2, "B": 3, "A": 4 }
#
#   * UNKNOWN class  -> value -1 (sentinel: "not part of the ordinal scale").
#     It must ALSO be named via --unknown_label_value. Omitting it from the
#     mapping makes label lookup produce NaN and crashes at astype(int).
#   * Known classes  -> 1-indexed integers whose ORDER defines the ordinal
#     scale (1 = one end, N = the other; e.g. worst -> best).
#
# OUTPUT COLUMN ORDER produced everywhere downstream (oof_probs.npy,
# *_logprob_* columns, soft labels, deployment prob_* columns):
#
#     [ known classes sorted by mapping value ASCENDING, then UNKNOWN last ]
#
# e.g. condition_tier: [D, C, B, A, N]
#      dist_to_main_street: [ON_MAIN_STREET, ADJACENT, NEAR, MODERATE, FAR, UNKNOWN]
#
# Any consumer that hard-codes a class list must match this order exactly.
# (Forensic note: the May-2026 condition_tier "phobert collapse", F1 0.087,
# was an eval comparing against this order REVERSED; true F1 was 0.9008.)
# =============================================================================


import os
# Reduce CUDA allocator fragmentation. Must be set before torch initialises
# CUDA (torch is imported lazily below, so top-of-module is early enough).
# A value already set in the shell takes precedence.
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import argparse
import gc
import json
import pickle
import time
import warnings
from pathlib import Path

import numpy as np
import pandas as pd

warnings.filterwarnings("ignore")


# MetaLearner lives in meta_learner_core.py β€” shared with meta_learner_trainer.py.
# Importing it here ensures pickle/joblib can deserialise saved MetaLearner instances
# regardless of which script originally created them.
import sys as _sys, os as _os
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
from meta_learner_core import MetaLearner  # noqa: E402


# =============================================================================
# ARGUMENT PARSING
# =============================================================================
def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--config",      type=str, required=True,
                   help="Path to deployment_config.json")
    p.add_argument("--data_path",   type=str, required=True,
                   help="Parquet with new data to score")
    p.add_argument("--text_col",    type=str, required=True,
                   help="Column in data_path containing raw text")
    p.add_argument("--output_path", type=str, default="predictions.parquet",
                   help="Output parquet path")
    p.add_argument("--device",      type=str, default="cpu",
                   help="Device for model inference ('cpu' or 'cuda')")
    p.add_argument("--batch_size",  type=int, default=64,
                   help="Tokenisation batch size for transformer inference")
    p.add_argument("--num_workers", type=int, default=4,
                   help="Number of CPU workers for parallel tokenisation. "
                        "Set to 0 to disable (single-threaded). "
                        "Rule of thumb: number of physical CPU cores - 1.")
    p.add_argument("--prefetch",    type=int, default=2,
                   help="Number of batches to prefetch per worker. "
                        "Higher values use more CPU RAM but keep GPU busier.")
    p.add_argument("--chunk_size",  type=int, default=50000,
                   help="Number of rows to process per write chunk. Controls peak "
                        "memory usage for the feature assembly + meta predict step. "
                        "Model inference (transformers / tfidf) always runs over the "
                        "full dataset in a single sequential pass per model to avoid "
                        "reloading weights repeatedly. Default: 50000.")
    p.add_argument("--keep_cols",   type=str, default=None,
                   help="Comma-separated list of extra columns from --data_path to "
                        "carry through to the output (in addition to text_col and "
                        "other_cols required by the models). If not set, only the "
                        "prediction columns are written (no original columns). "
                        "Use --keep_cols '*' to keep everything (memory-intensive "
                        "for large datasets).")
    p.add_argument("--cache_dir",   type=str, default=None,
                   help="Override the resume-cache directory. Default: "
                        "<output dir>/inference_cache. Use distinct dirs for "
                        "kfold vs final checkpoint runs β€” cache filenames are "
                        "identical across modes and would collide.")
    p.add_argument("--clear_cache", action="store_true",
                   help="Delete the inference cache dir after a successful run. "
                        "Default: keep it (reusable for re-runs on the same data, "
                        "e.g. after swapping the meta-learner).")
    p.add_argument("--no_dedup",    action="store_true",
                   help="Disable text deduplication. Use when per-row tabular features "
                        "(other_cols) vary significantly across duplicate texts and you "
                        "want each row inferred independently. Increases compute by "
                        "n_total/n_unique factor.")
    return p.parse_args()


# =============================================================================
# NORMALISE DEVICE
# =============================================================================
def _normalise_device(d):
    return "cuda" if d.lower() == "gpu" else d.lower()


# =============================================================================
# MODEL LOADING HELPERS
# =============================================================================
def _load_encoder(model_name, dtype, device):
    from transformers import AutoModel
    enc = AutoModel.from_pretrained(model_name, trust_remote_code=True, dtype=dtype)
    enc.eval()
    enc.to(device)
    return enc


def _load_fold_model(fold_dir: Path, original_model_name: str,
                     dtype, device):
    """
    Load the fine-tuned fold encoder, stripping the base_model. prefix
    used by MultimodalClassificationModel / OrdinalRegressionModel wrappers.
    Falls back to direct load for plain AutoModel checkpoints.
    """
    import torch
    from transformers import AutoModel

    st = fold_dir / "model.safetensors"
    use_safe = st.exists()
    if not use_safe:
        st = fold_dir / "pytorch_model.bin"
    if not st.exists():
        raise FileNotFoundError("No weights in " + str(fold_dir))

    if use_safe:
        from safetensors.torch import load_file
        raw_sd = load_file(str(st))
    else:
        raw_sd = torch.load(str(st), map_location="cpu", weights_only=True)

    encoder_sd = {k[len("base_model."):]: v
                  for k, v in raw_sd.items()
                  if k.startswith("base_model.")}
    if not encoder_sd:
        encoder_sd = raw_sd

    enc = AutoModel.from_pretrained(
        original_model_name, trust_remote_code=True, dtype=dtype)
    enc.load_state_dict(encoder_sd, strict=False)
    enc.eval()
    enc.to(device)
    return enc


def _get_fold_dir(artifacts_dir, model_name, fold_n, stage=None):
    artifact_name = model_name if stage is None else model_name + "__" + stage
    safe_name = artifact_name.replace("/", "__")
    # 'final' is the single-checkpoint layout from --training_mode final;
    # numbered folds come from the kfold layout.
    sub = "final" if str(fold_n) == "final" else "fold_" + str(fold_n)
    return Path(artifacts_dir) / safe_name / sub / "model"


# =============================================================================
# FEATURE EXTRACTION
# =============================================================================
def _encode_texts(encoder, tokenizer, texts, max_length, device,
                  batch_size, drop_token_type_ids):
    import torch
    all_embs = []
    for start in range(0, len(texts), batch_size):
        batch = texts[start:start + batch_size]
        enc = tokenizer(batch, padding=True, truncation=True,
                        max_length=max_length, return_tensors="pt")
        if drop_token_type_ids:
            enc.pop("token_type_ids", None)
        enc = {k: v.to(device) for k, v in enc.items()}
        with torch.no_grad():
            out = encoder(**enc)
        all_embs.append(out.last_hidden_state[:, 0, :].float().cpu().numpy())
    return np.vstack(all_embs)


# =============================================================================
# PARALLEL TOKENISATION DATASET
# =============================================================================
class _TextDataset:
    """
    Simple torch Dataset wrapping a list of strings + optional tabular features.
    Each worker tokenises its own shard, keeping GPU fed without waiting.
    """
    def __init__(self, texts, tokenizer, max_length, drop_token_type_ids,
                 tabular_features=None):
        self.texts               = texts
        self.tok                 = tokenizer
        self.max_length          = max_length
        self.drop_tti            = drop_token_type_ids
        self.tab                 = tabular_features   # (N, d) numpy or None

    def __len__(self):
        return len(self.texts)

    def __getitem__(self, idx):
        enc = self.tok(
            self.texts[idx],
            padding        = False,   # pad in collate to max length of batch
            truncation     = True,
            max_length     = self.max_length,
            return_tensors = None,    # return plain lists β€” faster to collate
        )
        if self.drop_tti:
            enc.pop("token_type_ids", None)
        item = {"__idx": idx, **{k: v for k, v in enc.items()}}
        if self.tab is not None:
            item["__tab"] = self.tab[idx]
        return item


def _collate(batch):
    """Pad a list of tokenised items to the longest sequence in the batch."""
    import torch
    indices  = [x.pop("__idx") for x in batch]
    tab_rows = [x.pop("__tab", None) for x in batch]

    keys = list(batch[0].keys())
    out  = {}
    for k in keys:
        seqs = [x[k] for x in batch]
        # Determine pad value: 0 for attention_mask, 1 for input_ids (safe default)
        pad_val  = 0
        max_len  = max(len(s) for s in seqs)
        padded   = [s + [pad_val] * (max_len - len(s)) for s in seqs]
        out[k]   = torch.tensor(padded, dtype=torch.long)

    out["__idx"] = torch.tensor(indices, dtype=torch.long)
    if tab_rows[0] is not None:
        import numpy as np
        out["__tab"] = torch.tensor(np.stack(tab_rows), dtype=torch.float32)
    return out


def _build_head(head_keys, device, model_type=None):
    """
    Reconstruct the task head from saved weight keys, matching the EXACT
    architectures defined in ensemble_distillation_generator.py:

      1. Multimodal classification (MultimodalClassificationModel):
           classifier.0 = Linear(hidden+tab, hidden)
           classifier.3 = Linear(hidden, num_labels)
         keys: classifier.0.{weight,bias}, classifier.3.{weight,bias}

      2. Ordinal regression (OrdinalRegressionModel):
           feature_extractor.0 = Linear(hidden+tab, hidden)
           ordinal_head        = Linear(hidden, num_classes-1)
         keys: feature_extractor.0.{weight,bias}, ordinal_head.{weight,bias}

      3. Plain sequence classification (AutoModelForSequenceClassification,
         used when other_cols is empty, e.g. rembert):
           classifier = Linear(hidden, num_labels)
         keys: classifier.{weight,bias}   (NO numeric index)

      3b. HF two-layer classification head (other_cols empty, roberta/electra
         families): classifier.dense + classifier.out_proj on the RAW CLS
         token (never the AutoModel pooler, which is untrained in these
         checkpoints). Activation differs by family: roberta=tanh, electra=gelu.
         keys: classifier.dense.{weight,bias}, classifier.out_proj.{weight,bias}

    Returns (head_module, head_type, expects_tabular, n_out) where
      head_type      = "classification" | "ordinal" | "plain"
      expects_tabular= whether the head's input dim includes tabular features
      n_out          = output dimension (num_labels or num_thresholds)
    """
    import torch.nn as nn

    def _lin(w, b):
        m = nn.Linear(w.shape[1], w.shape[0])
        m.weight = nn.Parameter(w.float())
        if b is not None:
            m.bias = nn.Parameter(b.float())
        return m

    keys = set(head_keys.keys())

    # Case 2: ordinal
    if "ordinal_head.weight" in keys and "feature_extractor.0.weight" in keys:
        fe_w = head_keys["feature_extractor.0.weight"]
        fe_b = head_keys.get("feature_extractor.0.bias")
        oh_w = head_keys["ordinal_head.weight"]
        oh_b = head_keys.get("ordinal_head.bias")
        head = nn.Sequential(
            _lin(fe_w, fe_b), nn.ReLU(), nn.Dropout(0.1),
            _lin(oh_w, oh_b),
        ).to(device)
        in_dim = fe_w.shape[1]      # hidden + tab
        n_out  = oh_w.shape[0]      # num_thresholds = num_classes - 1
        return head, "ordinal", in_dim, n_out

    # Case 1: multimodal classification (classifier.0 + classifier.3)
    if "classifier.0.weight" in keys and "classifier.3.weight" in keys:
        c0_w = head_keys["classifier.0.weight"]; c0_b = head_keys.get("classifier.0.bias")
        c3_w = head_keys["classifier.3.weight"]; c3_b = head_keys.get("classifier.3.bias")
        head = nn.Sequential(
            _lin(c0_w, c0_b), nn.ReLU(), nn.Dropout(0.1),
            _lin(c3_w, c3_b),
        ).to(device)
        in_dim = c0_w.shape[1]
        n_out  = c3_w.shape[0]
        return head, "classification", in_dim, n_out

    # Case 3b: HF two-layer head (RobertaClassificationHead / Electra-
    # ClassificationHead). Consumes the RAW CLS token; head_type "hf_head"
    # (NOT "plain") so the forward pass never routes through pooler_output β€”
    # roberta AutoModels have an UNTRAINED pooler in these checkpoints.
    if "classifier.dense.weight" in keys and "classifier.out_proj.weight" in keys:
        d_w = head_keys["classifier.dense.weight"];    d_b = head_keys.get("classifier.dense.bias")
        o_w = head_keys["classifier.out_proj.weight"]; o_b = head_keys.get("classifier.out_proj.bias")
        mt  = (model_type or "").lower()
        act = nn.GELU() if mt == "electra" else nn.Tanh()
        if mt not in ("electra", "roberta", "xlm-roberta", "camembert"):
            print("    [WARN] hf_head activation defaulting to tanh for "
                  "model_type=%r β€” verify against the HF head class." % model_type)
        head = nn.Sequential(_lin(d_w, d_b), act, _lin(o_w, o_b)).to(device)
        return head, "hf_head", d_w.shape[1], o_w.shape[0]

    # Case 3: plain classification (single classifier.{weight,bias})
    if "classifier.weight" in keys:
        w = head_keys["classifier.weight"]; b = head_keys.get("classifier.bias")
        head = _lin(w, b).to(device)
        in_dim = w.shape[1]
        n_out  = w.shape[0]
        return head, "plain", in_dim, n_out

    # Fallback: any output_layer
    if "output_layer.weight" in keys:
        w = head_keys["output_layer.weight"]; b = head_keys.get("output_layer.bias")
        head = _lin(w, b).to(device)
        return head, "plain", w.shape[1], w.shape[0]

    return None, None, None, None


def _load_sd(fold_dir):
    """Load state dict from safetensors or pytorch_model.bin."""
    import torch
    st = fold_dir / "model.safetensors"
    if not st.exists():
        st = fold_dir / "pytorch_model.bin"
    if st.suffix == ".safetensors":
        from safetensors.torch import load_file
        return load_file(str(st))
    return torch.load(str(st), map_location="cpu", weights_only=True)


# Head parameter name stems β€” anything starting with these is a task head,
# NOT part of the transformer encoder. Matches the architectures defined in
# ensemble_distillation_generator.py plus HF's default seq-classification heads.
_HEAD_STEMS = ("classifier", "ordinal_head", "feature_extractor",
               "output_layer", "score", "pre_classifier")


def _split_sd(raw_sd):
    """
    Split a checkpoint state dict into (encoder_sd, head_keys).

    Handles three checkpoint layouts:
      1. Multimodal/ordinal wrapper: encoder under 'base_model.<prefix>.*',
         head at top level (classifier.* / ordinal_head.* / feature_extractor.*).
      2. Plain HF AutoModelForSequenceClassification: encoder under
         '<model_prefix>.*' (e.g. 'rembert.', 'roberta.', 'electra.', 'bert.'),
         head at top level (classifier.weight/bias).
      3. Bare encoder: everything is encoder.

    Head keys are identified by their parameter name stem, independent of any
    prefix. Encoder keys have their leading prefix stripped so they load into a
    plain AutoModel.
    """
    head_keys  = {}
    encoder_raw = {}

    for k, v in raw_sd.items():
        # Strip a leading "base_model." if present (multimodal wrapper)
        kk = k[len("base_model."):] if k.startswith("base_model.") else k
        # Is this a head parameter? Check the FIRST path component.
        first = kk.split(".", 1)[0]
        if first in _HEAD_STEMS:
            head_keys[kk] = v
        else:
            encoder_raw[kk] = v

    # encoder_raw may still be prefixed by the model type (rembert., roberta.,
    # electra., bert., deberta., etc). Detect and strip a single common prefix
    # so keys match a plain AutoModel (which expects e.g. 'embeddings.*').
    prefixes = {k.split(".", 1)[0] for k in encoder_raw if "." in k}
    # A real encoder prefix is one shared by (almost) all keys and is a known
    # backbone name. If there's exactly one dominant prefix, strip it.
    encoder_sd = {}
    known_backbones = {"rembert", "roberta", "electra", "bert", "deberta",
                       "deberta_v2", "xlm_roberta", "camembert", "distilbert",
                       "albert", "mpnet", "model", "transformer"}
    strip_prefix = None
    if len(prefixes) == 1:
        only = next(iter(prefixes))
        if only in known_backbones:
            strip_prefix = only
    else:
        # Multiple prefixes β€” pick the one that's a known backbone if unique
        bk = [p for p in prefixes if p in known_backbones]
        if len(bk) == 1:
            strip_prefix = bk[0]

    if strip_prefix:
        plen = len(strip_prefix) + 1
        for k, v in encoder_raw.items():
            if k.startswith(strip_prefix + "."):
                encoder_sd[k[plen:]] = v
            else:
                encoder_sd[k] = v
    else:
        encoder_sd = encoder_raw

    return encoder_sd, head_keys


class _PreTokenizedDataset:
    """
    Dataset backed by already-tokenised arrays stored on disk.
    Workers just index into numpy mmaps β€” zero CPU tokenisation overhead.
    """
    def __init__(self, cache_dir, n, tabular_features=None):
        self.input_ids      = np.load(str(cache_dir / "input_ids.npy"),      mmap_mode="r")
        self.attention_mask = np.load(str(cache_dir / "attention_mask.npy"), mmap_mode="r")
        tok_type_path       = cache_dir / "token_type_ids.npy"
        self.token_type_ids = (np.load(str(tok_type_path), mmap_mode="r")
                               if tok_type_path.exists() else None)
        self.tab            = tabular_features
        self.n              = n

    def __len__(self):
        return self.n

    def __getitem__(self, idx):
        item = {
            "__idx":        idx,
            "input_ids":    self.input_ids[idx].tolist(),
            "attention_mask": self.attention_mask[idx].tolist(),
        }
        if self.token_type_ids is not None:
            item["token_type_ids"] = self.token_type_ids[idx].tolist()
        if self.tab is not None:
            item["__tab"] = self.tab[idx]
        return item


def _tokenize_and_cache(texts, tokenizer, max_length, drop_tti,
                         cache_dir, num_workers):
    """
    Tokenize all texts once, padding to max_length, saving as numpy arrays.
    Subsequent folds/stages read via mmap β€” zero re-tokenisation cost.
    """
    import torch
    from torch.utils.data import DataLoader

    print("  Tokenising {:,} texts (once for all folds)...".format(len(texts)))
    cache_dir.mkdir(parents=True, exist_ok=True)

    # Use _TextDataset + DataLoader for parallel tokenisation
    class _RawTextDS:
        def __init__(self, texts, tok, ml, drop):
            self.texts = texts; self.tok = tok
            self.ml = ml; self.drop = drop
        def __len__(self): return len(self.texts)
        def __getitem__(self, i):
            enc = self.tok(self.texts[i], padding="max_length",
                           truncation=True, max_length=self.ml, return_tensors=None)
            if self.drop: enc.pop("token_type_ids", None)
            return {k: v for k, v in enc.items()}

    def _collate_raw(batch):
        import torch
        out = {}
        for k in batch[0]:
            out[k] = torch.tensor([x[k] for x in batch], dtype=torch.long)
        return out

    ds = _RawTextDS(texts, tokenizer, max_length, drop_tti)
    dl = DataLoader(ds, batch_size=512, shuffle=False,
                    num_workers=num_workers, collate_fn=_collate_raw)

    n  = len(texts)
    id_arr   = np.zeros((n, max_length), dtype=np.int32)
    mask_arr = np.zeros((n, max_length), dtype=np.int8)
    tti_arr  = None
    has_tti  = False

    for b_idx, batch in enumerate(dl):
        start = b_idx * 512
        end   = min(start + 512, n)
        sl    = batch["input_ids"].numpy()[:end-start]
        id_arr[start:end]   = sl
        mask_arr[start:end] = batch["attention_mask"].numpy()[:end-start]
        if "token_type_ids" in batch and not has_tti:
            tti_arr  = np.zeros((n, max_length), dtype=np.int8)
            has_tti  = True
        if has_tti:
            tti_arr[start:end] = batch["token_type_ids"].numpy()[:end-start]
        if b_idx % 100 == 0:
            print("  Tokenising... {:.0f}%".format(end / n * 100), flush=True)

    np.save(str(cache_dir / "input_ids.npy"),      id_arr)
    np.save(str(cache_dir / "attention_mask.npy"), mask_arr)
    if has_tti:
        np.save(str(cache_dir / "token_type_ids.npy"), tti_arr)
    print("  Tokenisation cached -> {}".format(cache_dir))


def run_transformer_model(model_cfg, texts, tabular_features,
                           max_length, device, batch_size, k_folds,
                           num_workers=4, prefetch=2,
                           token_cache_dir=None):
    """
    Run a transformer model (all K folds), returning averaged probabilities.

    Optimisations vs naive approach:
      1. Tokenise ONCE before the fold loop, cache to disk as numpy arrays.
         All folds read from mmap β€” zero re-tokenisation.
      2. Load encoder ARCHITECTURE once (AutoConfig + empty init), then per
         fold just call load_state_dict(). Avoids re-downloading/re-reading
         the original pretrained weights K times.
      3. Running average accumulation β€” O(NΓ—C) memory regardless of K folds.
      4. DataLoader with num_workers for prefetch during GPU forward pass.
    """
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    from transformers import AutoTokenizer, AutoModel, AutoConfig
    from torch.utils.data import DataLoader

    mname      = model_cfg["model_name"]
    cname      = model_cfg["clean_name"]
    task       = model_cfg["task_type"]
    tok_name   = model_cfg.get("tokenizer_name") or mname
    drop_tti   = model_cfg.get("drop_token_type_ids", False)
    split_unk  = model_cfg.get("split_unknown_stage", False)
    other_cols = model_cfg.get("other_cols", [])
    use_fp16   = model_cfg.get("use_fp16", False)
    use_bf16   = model_cfg.get("use_bf16", False)
    art_dir    = model_cfg["artifacts_dir"]
    tab_feats  = tabular_features if (other_cols and tabular_features is not None) else None

    dtype = (torch.bfloat16 if use_bf16 else
             torch.float16 if use_fp16 else torch.float32)
    n = len(texts)

    # ── Step 1: Tokenise once ────────────────────────────────────────────────
    tok_cache = (token_cache_dir / "{}.tokens".format(
                     cname.replace("/", "__")))
    if tok_cache.exists() and (tok_cache / "input_ids.npy").exists():
        print("  Tokenisation cache found for {} β€” skipping re-tokenisation.".format(cname))
    else:
        tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True)
        _tokenize_and_cache(texts, tokenizer, max_length, drop_tti,
                             tok_cache, num_workers)
        del tokenizer
        gc.collect()

    pre_tok_ds = _PreTokenizedDataset(tok_cache, n, tab_feats)

    # ── Step 2: Load encoder architecture ONCE (no pretrained weights) ───────
    print("  Loading encoder architecture for {} ...".format(cname))
    config  = AutoConfig.from_pretrained(mname, trust_remote_code=True)
    encoder = AutoModel.from_config(config)
    encoder = encoder.to(dtype)
    # Don't move to device yet β€” weights are wrong; load_state_dict first

    def _run_fold(fold_dir, fold_label, partial_cache_path=None):
        """
        Swap weights into the shared encoder, run inference, return (N,C) array.

        Intra-fold resumability:
        - Every `save_every` batches, fold_sum and samples_done are written to
          a .npz partial cache file.
        - On entry, if the partial cache exists, the running sum is restored and
          already-processed samples are skipped via a sliced DataLoader.
        - On completion the partial cache is deleted (full fold cache takes over).
        """
        # How often to checkpoint within a fold (every ~5% of batches, min 50)
        n_batches_total = (n + batch_size - 1) // batch_size
        save_every      = max(50, n_batches_total // 20)

        # ── Resume partial fold if checkpoint exists ──────────────────────────
        fold_sum      = None
        samples_done  = 0
        if partial_cache_path and partial_cache_path.exists():
            try:
                data = np.load(str(partial_cache_path))
                fold_sum     = data["fold_sum"]
                samples_done = int(data["samples_done"])
                print("    {} β€” resuming from sample {:,} / {:,} ({:.0f}%)".format(
                      fold_label, samples_done, n, samples_done / n * 100))
            except Exception as e:
                print("    {} β€” partial cache load failed ({}), starting fresh".format(
                      fold_label, e))
                fold_sum     = None
                samples_done = 0

        # ── Load weights only if we actually need to run inference ────────────
        if samples_done < n:
            raw_sd     = _load_sd(fold_dir)
            encoder_sd, head_keys = _split_sd(raw_sd)
            del raw_sd
            gc.collect()

            load_res = encoder.load_state_dict(encoder_sd, strict=False)
            n_missing    = len(load_res.missing_keys)
            n_unexpected = len(load_res.unexpected_keys)
            if n_missing or n_unexpected:
                print("    {} β€” load report: {} missing, {} unexpected keys".format(
                      fold_label, n_missing, n_unexpected))
                if n_missing > 5:
                    print("      [WARN] Many missing keys β€” encoder may be "
                          "partially random. First few: {}".format(
                          load_res.missing_keys[:4]))
            del encoder_sd
            encoder.eval()
            encoder.to(device)

            head, head_type, head_in_dim, n_out = _build_head(
                head_keys, device,
                model_type=getattr(getattr(encoder, "config", None), "model_type", None))
            if head is None:
                raise RuntimeError(
                    "Could not reconstruct head for {} β€” keys: {}".format(
                        fold_label, sorted(head_keys.keys())[:10]))
            del head_keys
            gc.collect()

            # Determine whether the head expects tabular features concatenated.
            # head_in_dim is the head's input width; encoder hidden size is the
            # CLS dim. If head_in_dim > hidden, the head was trained with tabular
            # features appended (multimodal). If equal, it's a plain head (no tab).
            encoder_hidden = encoder.config.hidden_size
            head_wants_tab = head_in_dim is not None and head_in_dim > encoder_hidden
            tab_width      = (head_in_dim - encoder_hidden) if head_wants_tab else 0
            print("    {} β€” head={} n_out={} hidden={} tab={}".format(
                  fold_label, head_type, n_out, encoder_hidden,
                  tab_width if head_wants_tab else "none"), flush=True)

            from torch.utils.data import Subset
            remaining_ds = (Subset(pre_tok_ds, list(range(samples_done, n)))
                            if samples_done > 0 else pre_tok_ds)

            loader = DataLoader(
                remaining_ds,
                batch_size      = batch_size,
                shuffle         = False,
                num_workers     = num_workers,
                prefetch_factor = prefetch if num_workers > 0 else None,
                pin_memory      = device.startswith("cuda"),
                collate_fn      = _collate,
            )

            n_batches    = len(loader)
            report_every = max(1, n_batches // 20)

            for b_idx, batch in enumerate(loader):
                indices = batch.pop("__idx")
                tab_b   = batch.pop("__tab", None)
                enc_in  = {k: v.to(device, non_blocking=True) for k, v in batch.items()}

                with torch.no_grad():
                    out = encoder(**enc_in)

                    # Feature extraction must match how the head was TRAINED:
                    # - Multimodal/ordinal wrapper models (classification/ordinal
                    #   head types) classify on the raw CLS token:
                    #   last_hidden_state[:, 0, :]  β€” the wrapper's design.
                    # - Plain HF AutoModelForSequenceClassification (head_type
                    #   "plain", e.g. rembert) classifies on the POOLER output:
                    #   tanh(dense(CLS)). Feeding raw CLS into that classifier
                    #   produces near-constant garbage predictions.
                    if head_type == "plain" and getattr(out, "pooler_output", None) is not None:
                        cls_emb = out.pooler_output.float()
                    else:
                        cls_emb = out.last_hidden_state[:, 0, :].float()

                    # Concatenate tabular features ONLY if the head expects them.
                    if head_wants_tab:
                        if tab_b is not None:
                            tab_t = tab_b.to(device, non_blocking=True).float()
                        else:
                            # Head expects tab but none provided β€” pad with zeros
                            tab_t = torch.zeros(cls_emb.shape[0], tab_width,
                                                device=device)
                        # Match width exactly (guard against mismatch)
                        if tab_t.shape[1] != tab_width:
                            if tab_t.shape[1] > tab_width:
                                tab_t = tab_t[:, :tab_width]
                            else:
                                pad = torch.zeros(cls_emb.shape[0],
                                                  tab_width - tab_t.shape[1],
                                                  device=device)
                                tab_t = torch.cat([tab_t, pad], dim=1)
                        cls_emb = torch.cat([cls_emb, tab_t], dim=1)

                    logits = head(cls_emb)

                    if head_type == "ordinal":
                        # logits: (B, num_thresholds=num_classes-1)
                        # Cumulative P(label > i) via sigmoid, expand to num_classes
                        cum = torch.sigmoid(logits)
                        K   = cum.shape[1]            # thresholds
                        p   = torch.zeros(cum.shape[0], K + 1, device=device)
                        p[:, 0] = 1 - cum[:, 0]
                        for i in range(1, K):
                            p[:, i] = cum[:, i-1] - cum[:, i]
                        p[:, -1] = cum[:, -1]
                        probs_np = p.clamp(min=0).cpu().numpy()
                    else:
                        # classification / plain
                        probs_np = F.softmax(logits, dim=-1).cpu().numpy()

                if fold_sum is None:
                    fold_sum = np.zeros((n, probs_np.shape[1]), dtype=np.float64)
                fold_sum[indices.numpy()] += probs_np
                samples_done += len(indices)

                if b_idx % report_every == 0 or b_idx == n_batches - 1:
                    print("    {} β€” {}/{} batches ({:.0f}%)".format(
                          fold_label, b_idx + 1, n_batches,
                          (b_idx + 1) / n_batches * 100), flush=True)

                # Periodic intra-fold checkpoint
                if partial_cache_path and (b_idx + 1) % save_every == 0:
                    np.savez(str(partial_cache_path),
                             fold_sum=fold_sum.astype(np.float32),
                             samples_done=np.array(samples_done))

            # Move encoder back to CPU to free GPU memory
            encoder.cpu()
            if head is not None:
                del head
            gc.collect()
            if device.startswith("cuda"):
                torch.cuda.empty_cache()

        # Delete partial cache β€” full fold result saved by caller
        if partial_cache_path and partial_cache_path.exists():
            partial_cache_path.unlink()

        return fold_sum.astype(np.float32)

    def _fold_cache_path(key, fold_n, stage=None):
        """Per-fold cache: saved immediately after each fold completes."""
        tag = "{}_fold{}".format(key, fold_n)
        if stage:
            tag += "_{}".format(stage)
        safe = tag.replace(":", "_").replace("/", "__")
        return token_cache_dir / "{}.npy".format(safe)

    def _run_fold_cached(fold_dir, fold_n, stage, label):
        """
        Run a fold or load from cache.
        - If the completed fold .npy exists: load instantly.
        - Otherwise: run with intra-fold partial checkpointing.
          A .partial.npz is written every ~5% of batches so a crash
          mid-fold can resume from the last checkpoint rather than fold 1.
        """
        model_key   = "{}:{}".format(model_cfg["source"], cname)
        fold_cache  = _fold_cache_path(model_key, fold_n, stage)
        partial_key = "{}_fold{}{}".format(
            model_key, fold_n, "_{}".format(stage) if stage else "")
        safe        = partial_key.replace(":", "_").replace("/", "__")
        partial_cache = token_cache_dir / "{}.partial.npz".format(safe)

        # Completed fold already cached
        if fold_cache.exists():
            arr = np.load(str(fold_cache))
            if arr.shape[0] == n:
                print("    {} β€” loaded from fold cache".format(label))
                return arr
            print("    {} β€” fold cache shape mismatch, re-running".format(label))

        # Run with intra-fold checkpointing
        arr = _run_fold(fold_dir, label, partial_cache_path=partial_cache)
        np.save(str(fold_cache), arr)
        print("    {} β€” fold cached -> {}".format(label, fold_cache.name))
        return arr

    # ── Checkpoint layout detection: final (single-pass) vs K folds ──────────
    # --training_mode final saves ONE checkpoint per model under final/model/.
    # When present it is preferred: 1/K the serving cost, trained on all
    # non-holdout data. Fold checkpoints remain the fallback.
    _probe = _get_fold_dir(art_dir, mname, "final", "stage1" if split_unk else None)
    if _probe.exists():
        fold_ids = ["final"]
        print("  Using FINAL checkpoint for {} (single pass)".format(cname))
    else:
        fold_ids = list(range(1, k_folds + 1))

    # ── Stage 1 (all models) ─────────────────────────────────────────────────
    s1_sum = None; s1_count = 0
    for fold_n in fold_ids:
        stage    = "stage1" if split_unk else None
        fold_dir = _get_fold_dir(art_dir, mname, fold_n, stage)
        if not fold_dir.exists():
            print("  [WARN] Fold {} not found for {} β€” skipping".format(fold_n, cname))
            continue
        label    = ("fold {}/{} [stage1]".format(fold_n, len(fold_ids)) if split_unk
                    else "fold {}/{}".format(fold_n, len(fold_ids)))
        fold_arr = _run_fold_cached(fold_dir, fold_n, stage, label)
        s1_sum   = fold_arr.astype(np.float64) if s1_sum is None else s1_sum + fold_arr
        s1_count += 1
        del fold_arr; gc.collect()

    if s1_count == 0:
        raise RuntimeError("No fold checkpoints loaded for " + cname)

    s1_avg = (s1_sum / s1_count).astype(np.float32)
    del s1_sum; gc.collect()

    # ── Stage 2 (split_unknown_stage only) ───────────────────────────────────
    if split_unk:
        s2_sum = None; s2_count = 0
        for fold_n in fold_ids:
            fold_dir2 = _get_fold_dir(art_dir, mname, fold_n, "stage2")
            if not fold_dir2.exists():
                continue
            label2   = "fold {}/{} [stage2]".format(fold_n, len(fold_ids))
            fold_arr = _run_fold_cached(fold_dir2, fold_n, "stage2", label2)
            s2_sum   = fold_arr.astype(np.float64) if s2_sum is None else s2_sum + fold_arr
            s2_count += 1
            del fold_arr; gc.collect()

        if s2_count > 0:
            s2_avg = (s2_sum / s2_count).astype(np.float32)
            del s2_sum

            # Compose EXACTLY as the generator does (split_unknown_stage):
            #   stage1 (plain classification, label 1=unknown, 0=known):
            #     stage1_probs[:, 0] = P(known), stage1_probs[:, 1] = P(unknown)
            #   Calibrate P(unknown) by dividing odds by ordinal_num_classes:
            #     odds = p_unknown / p_known
            #     adj  = odds / ordinal_num_classes
            #     p_unknown_cal = adj / (1 + adj);  p_known_cal = 1 - p_unknown_cal
            #   stage2 (ordinal) gives P(class | known) over ordinal_num_classes.
            #   Final: [p_known_cal * stage2_i  for each known class] + [p_unknown_cal]
            #   Known classes come first, UNKNOWN last β€” matches class_order.
            ordinal_num_classes = s2_avg.shape[1]          # = n_classes - 1
            p_known   = s1_avg[:, 0]
            p_unknown = s1_avg[:, 1]
            odds_unknown = p_unknown / np.clip(p_known, 1e-7, 1.0)
            adj_odds     = odds_unknown / ordinal_num_classes
            p_unknown_cal = adj_odds / (1.0 + adj_odds)
            p_known_cal   = 1.0 - p_unknown_cal

            composed = np.zeros((s1_avg.shape[0], ordinal_num_classes + 1),
                                dtype=np.float32)
            for i in range(ordinal_num_classes):
                composed[:, i] = p_known_cal * s2_avg[:, i]
            composed[:, -1] = p_unknown_cal
            return composed

    del encoder; gc.collect()
    return s1_avg


def run_tfidf_lgbm(model_cfg, texts, tabular_features, k_folds):
    """Run TF-IDF + LightGBM from fold_1 pickle."""
    from scipy.sparse import hstack, csr_matrix

    art_dir  = model_cfg["artifacts_dir"]
    pkl_path = Path(art_dir) / "tfidf_lgbm" / "fold_1" / "model.pkl"
    if not pkl_path.exists():
        raise FileNotFoundError("tfidf_lgbm pickle not found: " + str(pkl_path))

    with open(pkl_path, "rb") as f:
        bundle = pickle.load(f)

    cal = bundle["calibrated_model"]
    wtf = bundle["word_tfidf"]
    ctf = bundle["char_tfidf"]
    X   = hstack([wtf.transform(texts), ctf.transform(texts)])

    if tabular_features is not None and tabular_features.shape[1] > 0:
        tab = csr_matrix(tabular_features.astype("float32"))
        X   = hstack([X, tab])

    return cal.predict_proba(X)


# =============================================================================
# DERIVED FEATURES (mirrors OOFFeatureBuilder)
# =============================================================================
def entropy(probs, eps=1e-7):
    p = np.clip(probs, eps, 1.0)
    return -np.sum(p * np.log(p), axis=1)


def sym_kl(p, q, eps=1e-7):
    p = np.clip(p, eps, 1.0)
    q = np.clip(q, eps, 1.0)
    return 0.5 * (np.sum(p * np.log(p/q), axis=1) +
                  np.sum(q * np.log(q/p), axis=1))


def build_feature_vector(probs_by_key, class_order, n_classes,
                          use_derived, expected_names=None):
    """
    Build the feature vector to EXACTLY match the trainer's OOFFeatureBuilder.

    probs_by_key: dict "CE:<cname>" / "KL:<cname>" -> (N, n_classes) array

    Strategy: compute every candidate feature into a name->column dict, then
    emit columns in the order given by `expected_names` (the training feature
    list stored in the meta-learner pickle). This guarantees the inference
    matrix matches the trained model's expected feature set and order exactly,
    eliminating count/order mismatches.

    Trainer naming conventions (must match exactly):
      base:    "CE_<cname>_<CLASS>"     e.g. CE_mlm_listing_NEAR
      derived: "CE_<cname>_entropy", "CE_<cname>_argmax"
               "CE_KL_<cname>_sym_kl", "CE_KL_<cname>_diff_class<i>"
               "CE_pair_CE_<n1>_vs_CE_<n2>_kl"
    Note: trainer uses underscore between source and name (CE_<cname>),
    while keys here use colon (CE:<cname>).
    """
    feat = {}   # name -> (N,) or (N,1) column

    # ── Base probabilities ────────────────────────────────────────────────────
    for key, probs in probs_by_key.items():
        src, cname = key.split(":", 1)
        for i, cls in enumerate(class_order):
            feat["{}_{}_{}".format(src, cname, cls)] = probs[:, i]

    if use_derived:
        all_p = dict(probs_by_key)

        # entropy + argmax per model
        for key, probs in probs_by_key.items():
            src, cname = key.split(":", 1)
            feat["{}_{}_entropy".format(src, cname)] = entropy(probs)
            feat["{}_{}_argmax".format(src, cname)]  = np.argmax(probs, axis=1).astype(float)

        # CE-KL pair divergence (same model name in both CE and KL)
        ce_keys = [k for k in all_p if k.startswith("CE:")]
        for ce_k in ce_keys:
            cname = ce_k.split(":", 1)[1]
            kl_k  = "KL:" + cname
            if kl_k in all_p:
                feat["CE_KL_{}_sym_kl".format(cname)] = sym_kl(all_p[ce_k], all_p[kl_k])
                diff = all_p[ce_k] - all_p[kl_k]
                for i in range(diff.shape[1]):
                    feat["CE_KL_{}_diff_class{}".format(cname, i)] = diff[:, i]

        # Pairwise CE disagreement β€” trainer key format: CE_pair_CE_<n1>_vs_CE_<n2>_kl
        from itertools import combinations
        ce_prob_list = [(k.split(":", 1)[1], all_p[k]) for k in ce_keys]
        for (n1, p1), (n2, p2) in combinations(ce_prob_list, 2):
            feat["CE_pair_CE_{}_vs_CE_{}_kl".format(n1, n2)] = sym_kl(p1, p2)

    # ── Assemble in the trainer's exact order ─────────────────────────────────
    if expected_names:
        N = next(iter(feat.values())).shape[0]
        cols = []
        missing = []
        for name in expected_names:
            if name in feat:
                cols.append(feat[name].reshape(-1, 1))
            else:
                missing.append(name)
                cols.append(np.zeros((N, 1)))   # placeholder; will warn
        if missing:
            print("  [WARN] {} expected features not produced (filled 0): {}".format(
                  len(missing), missing[:8]))
        # Warn about extra features we built that the model doesn't expect
        extra = [k for k in feat if k not in set(expected_names)]
        if extra:
            print("  [INFO] {} computed features not used by model (ignored): {}".format(
                  len(extra), extra[:8]))
        return np.hstack(cols), list(expected_names)

    # No expected names β€” fall back to deterministic order (base then derived)
    names = list(feat.keys())
    return np.hstack([feat[k].reshape(-1, 1) for k in names]), names


# =============================================================================
# FROZEN ENCODER EMBEDDINGS
# =============================================================================
def get_frozen_embeddings(texts, cfg, device, batch_size, cache_dir=None):
    """
    Extract embeddings from the frozen encoder and apply PCA.
    The PCA transform is reconstructed from the cached training embeddings
    (frozen_emb_cache) by re-fitting on those β€” since frozen encoder weights
    never change, this is equivalent to the original fit.
    """
    from sklearn.decomposition import PCA
    from transformers import AutoTokenizer, AutoModel
    import torch

    model_name = cfg["frozen_encoder"]
    tok_name   = cfg.get("frozen_encoder_tokenizer") or model_name
    n_comp     = cfg["frozen_emb_n_components"]
    cache_path = cfg.get("frozen_emb_cache")

    tokenizer = AutoTokenizer.from_pretrained(tok_name, trust_remote_code=True)
    encoder   = AutoModel.from_pretrained(model_name, trust_remote_code=True)
    encoder.eval()
    encoder.to(device)

    vocab_size = encoder.config.vocab_size

    # Cap max_length at the model's position-embedding limit. Models like
    # PhoBERT have max_position_embeddings=258 (256 usable + 2 special tokens);
    # tokenising to 512 produces position IDs beyond the table -> CUDA OOB assert
    # in the embeddings LayerNorm. Use the config value, with the standard
    # RoBERTa offset of 2 for the padding-idx position scheme.
    max_pos = getattr(encoder.config, "max_position_embeddings", 512)
    # RoBERTa reserves positions 0,1 (pad/offset) so usable length is max_pos - 2
    safe_max_len = max_pos - 2 if max_pos <= 600 else 512
    frozen_max_len = int(cfg.get("frozen_max_length", safe_max_len))
    frozen_max_len = min(frozen_max_len, safe_max_len)
    print("  frozen encoder max_length = {} (model max_position={})".format(
          frozen_max_len, max_pos))

    n_batches    = (len(texts) + batch_size - 1) // batch_size
    report_every = max(1, n_batches // 10)

    # ── Crash-safe persistence: raw embeddings in a resumable memmap ────────
    # This stage is the slowest in the pipeline (serial slow-BPE tokenisation
    # starves the GPU); losing it to a downstream crash costs ~10h. Progress
    # is checkpointed every 200 batches.
    hidden = encoder.config.hidden_size
    raw_path = prog_path = None
    start_batch = 0
    emb_mm = None
    if cache_dir:
        Path(cache_dir).mkdir(parents=True, exist_ok=True)
        raw_path  = Path(cache_dir) / "_frozen_emb_raw.npy"
        prog_path = Path(cache_dir) / "_frozen_emb_raw.progress"
        if raw_path.exists() and prog_path.exists():
            try:
                cand = np.lib.format.open_memmap(str(raw_path), mode="r+")
                done = int(prog_path.read_text().strip() or 0)
                if cand.shape == (len(texts), hidden) and 0 < done <= n_batches:
                    emb_mm, start_batch = cand, done
                    print("  frozen emb: RESUMING from batch {}/{}".format(
                          done, n_batches), flush=True)
            except Exception as e:
                print("  frozen emb: cache unreadable ({}) β€” restarting".format(e))
        if emb_mm is None:
            emb_mm = np.lib.format.open_memmap(str(raw_path), mode="w+",
                        dtype=np.float32, shape=(len(texts), hidden))
    else:
        emb_mm = np.zeros((len(texts), hidden), dtype=np.float32)

    # Tokenise ONCE in parallel to cached arrays (proven _tokenize_and_cache
    # machinery), then stream the mmap through the GPU. Long-lived DataLoader
    # workers over the raw text list leak memory via fork copy-on-write; this
    # bounds worker lifetime to the tokenisation phase. max_length padding is
    # attention-masked, so embeddings match dynamic padding.
    frozen_tok_dir = Path(cache_dir) / "_frozen_tokens" if cache_dir else None
    if frozen_tok_dir is None:
        raise RuntimeError("frozen embeddings now require --cache_dir")
    if not (frozen_tok_dir / "input_ids.npy").exists():
        _tokenize_and_cache(texts, tokenizer, frozen_max_len, True,
                            frozen_tok_dir, num_workers=8)
    ids  = np.load(str(frozen_tok_dir / "input_ids.npy"),      mmap_mode="r")
    mask = np.load(str(frozen_tok_dir / "attention_mask.npy"), mmap_mode="r")

    for b_idx in range(start_batch, n_batches):
        s = b_idx * batch_size
        e = min(s + batch_size, len(texts))
        input_ids = torch.from_numpy(np.ascontiguousarray(ids[s:e])).long() \
                         .clamp(0, vocab_size - 1).to(device)
        attn      = torch.from_numpy(np.ascontiguousarray(mask[s:e])).long().to(device)
        with torch.no_grad():
            out = encoder(input_ids=input_ids, attention_mask=attn)
        emb_mm[s:e] = out.last_hidden_state[:, 0, :].float().cpu().numpy()
        if prog_path is not None and (b_idx % 200 == 0 or b_idx == n_batches - 1):
            emb_mm.flush()
            prog_path.write_text(str(b_idx + 1))
        if b_idx % report_every == 0 or b_idx == n_batches - 1:
            print("  frozen emb {}/{} ({:.0f}%)".format(
                  b_idx + 1, n_batches, (b_idx + 1) / n_batches * 100), flush=True)

    del encoder
    gc.collect()
    if device.startswith("cuda"):
        torch.cuda.empty_cache()

    raw = np.asarray(emb_mm)

    # Apply the SAME PCA fitted during training. Re-fitting here would produce
    # different components and feed the meta-learner inconsistent features.
    import joblib
    pca_path = str(Path(cache_path).with_suffix("")) + "_pca.joblib" if cache_path else None

    if pca_path and Path(pca_path).exists():
        bundle = joblib.load(pca_path)
        pca    = bundle["pca"]
        reduced = pca.transform(raw).astype(np.float32)   # transform, NOT fit_transform
        print("  Applied saved training PCA ({} -> {} dims)".format(
              raw.shape[1], reduced.shape[1]))
    else:
        raise FileNotFoundError(
            "Frozen PCA transform not found at {}.\n".format(pca_path) +
            "The meta-learner was trained with a specific PCA fit that must be "
            "reused at inference. Regenerate it by running the trainer's frozen "
            "embedding step on the TRAINING data, which saves <cache>_pca.joblib.\n"
            "Quick fix command:\n"
            "  python scripts/regenerate_frozen_pca.py \\\n"
            "      --frozen_encoder {} \\\n".format(model_name) +
            "      --frozen_encoder_tokenizer {} \\\n".format(tok_name) +
            "      --data_path data/labelled/<training_data>.parquet \\\n"
            "      --text_col text --max_length {} --n_components {} \\\n".format(
                  frozen_max_len, n_comp) +
            "      --cache_path {}".format(cache_path))

    return reduced


# =============================================================================
# MAIN
# =============================================================================
def main():
    args   = parse_args()
    device = _normalise_device(args.device)

    # ── Load config, resolving all paths relative to the config file ──────────
    config_dir = Path(args.config).parent.resolve()
    with open(args.config) as f:
        cfg = json.load(f)

    def _resolve(p):
        """
        Resolve a path from the config to an absolute path.

        Priority:
          1. Absolute path in config          -> use as-is
          2. Relative to config_dir           -> use if exists
          3. Relative to cwd (project root)   -> use if exists (catches paths
             like "experiments/ce_v1/artifacts" that were stored relative to
             the project root rather than the config file)
          4. Just the filename next to config -> fallback for configs written
             before directory restructuring
        """
        if p is None:
            return None
        pp = Path(p)
        if pp.is_absolute():
            return str(pp)

        # Try relative to config dir
        by_config = (config_dir / pp).resolve()
        if by_config.exists():
            return str(by_config)

        # Try relative to cwd (project root β€” most common for artifacts_dir)
        by_cwd = (Path.cwd() / pp).resolve()
        if by_cwd.exists():
            return str(by_cwd)

        # Try just the filename next to the config
        by_name = (config_dir / pp.name).resolve()
        if by_name.exists():
            print("  [NOTE] '{}' resolved to '{}' (filename fallback).".format(
                  p, by_name))
            return str(by_name)

        # Nothing found β€” return cwd-relative resolution so the error is readable
        print("  [WARN] Could not resolve path '{}' β€” tried:".format(p))
        print("         config-relative : {}".format(by_config))
        print("         cwd-relative    : {}".format(by_cwd))
        print("         filename        : {}".format(by_name))
        return str(by_cwd)

    # Patch all paths in cfg to be absolute
    cfg["meta_learner_path"] = _resolve(cfg["meta_learner_path"])
    if cfg.get("frozen_emb_cache"):
        cfg["frozen_emb_cache"] = _resolve(cfg["frozen_emb_cache"])
    for m in cfg.get("models", []):
        if m.get("artifacts_dir"):
            m["artifacts_dir"] = _resolve(m["artifacts_dir"])

    print("="*60)
    print("META-LEARNER INFERENCE")
    print("="*60)
    print("Config    :", cfg["label"])
    print("Meta type :", cfg["meta_type"], " | CV F1:", cfg["meta_f1_cv"])
    print("Classes   :", cfg["class_order"])
    print("Config dir:", config_dir)

    # ── Determine which columns to load from the parquet ─────────────────────
    # Load only what's needed: text + any tabular cols the models use.
    # This is critical for 1.7M-row datasets β€” loading all columns is wasteful.
    required_cols = {args.text_col}
    for m_cfg in cfg.get("models", []):
        required_cols.update(m_cfg.get("other_cols", []))

    keep_all = args.keep_cols == "*"
    extra_keep = []
    if args.keep_cols and args.keep_cols != "*":
        extra_keep = [c.strip() for c in args.keep_cols.split(",")]
        required_cols.update(extra_keep)

    print("\nLoading parquet columns:", sorted(required_cols)
          if not keep_all else "(all)")

    if keep_all:
        df = pd.read_parquet(args.data_path)
    else:
        import pyarrow.parquet as pq
        available = pq.read_schema(args.data_path).names
        cols_to_read = [c for c in required_cols if c in available]
        missing_at_load = required_cols - set(available)
        if missing_at_load:
            print("  [WARN] Columns not in parquet (will be filled with 0):",
                  sorted(missing_at_load))
        df = pd.read_parquet(args.data_path, columns=cols_to_read)

    n_total = len(df)
    print("Total rows:", n_total)

    # ── Separate null/empty text rows β€” assign UNKNOWN directly ──────────────
    # Handles actual NaN, Python None, empty string, and string "None".
    null_mask = (
        df[args.text_col].isna() |
        (df[args.text_col].astype(str).str.strip() == "") |
        (df[args.text_col].astype(str).str.strip().str.lower() == "none")
    )
    n_null = null_mask.sum()
    if n_null:
        print("  Null/empty text rows: {:,} β€” will be assigned UNKNOWN directly.".format(n_null))

    # ── Deduplicate on text for inference efficiency ───────────────────────────
    # Rows sharing the same text get inferred once and results are broadcast back.
    # Note: tabular other_cols may differ across dup rows β€” we use values from the
    # first occurrence. Use --no_dedup to run every row independently.
    df_valid = df[~null_mask].copy()

    if args.no_dedup:
        df_unique = df_valid
        n_unique  = len(df_valid)
        n_dups    = 0
        print("  Deduplication disabled (--no_dedup).")
    else:
        df_unique = df_valid.drop_duplicates(subset=[args.text_col], keep="first")
        n_unique  = len(df_unique)
        n_dups    = len(df_valid) - n_unique

    print("  Valid rows     : {:,}".format(len(df_valid)))
    print("  Unique texts   : {:,}".format(n_unique))
    print("  Duplicate rows : {:,} (will be filled from unique results)".format(n_dups))
    print("  Inference on   : {:,} rows ({:.1f}% of total)".format(
          n_unique, n_unique / n_total * 100))

    texts = df_unique[args.text_col].fillna("").tolist()
    n     = len(texts)   # n is now unique count

    # ── Load meta-learner ─────────────────────────────────────────────────────
    import joblib
    bundle      = joblib.load(cfg["meta_learner_path"])
    meta        = bundle["model"]
    class_order = bundle["class_order"]
    idx_to_lbl  = bundle["idx_to_label"]
    n_classes   = bundle["n_classes"]
    n_prob_cols = bundle["n_prob_cols"]
    feature_names = bundle.get("feature_names")   # exact training feature order
    meta._n_prob_cols = n_prob_cols
    if feature_names:
        print("  Meta-learner expects {} features: {} prob/derived + {} embedding".format(
              len(feature_names), n_prob_cols, len(feature_names) - n_prob_cols))

    k_folds     = cfg.get("k_folds", 5)
    max_length  = cfg.get("max_length", 256)
    use_derived = cfg.get("use_derived_features", False)

    # ── [1] Run each base model over the FULL dataset sequentially ────────────
    # Models are loaded once and run end-to-end. This avoids reloading K fold
    # checkpoints per chunk, which would be extremely slow for 1.7M rows.
    # Memory: each model's output is (N, n_classes) float32 β€” ~39MB for 1.7M rows.
    # Cache dir: store per-model prob arrays next to output so a crash can resume.
    cache_dir = (Path(args.cache_dir) if args.cache_dir
                 else Path(args.output_path).parent / "inference_cache")
    cache_dir.mkdir(parents=True, exist_ok=True)

    def _model_cache_path(key):
        safe = key.replace(":", "_").replace("/", "__")
        return cache_dir / "{}.npy".format(safe)

    def _frozen_cache_path():
        return cache_dir / "_frozen_emb.npy"

    print("\n[1] Running base models (full dataset, sequential)...")
    print("  Resume cache dir: {}".format(cache_dir))
    probs_by_key = {}

    for m_cfg in cfg["models"]:
        cname      = m_cfg["clean_name"]
        src        = m_cfg["source"]
        key        = "{}:{}".format(src, cname)
        task       = m_cfg.get("task_type", "classification")
        other_cols = m_cfg.get("other_cols", [])
        cache_path = _model_cache_path(key)

        # Resume: load cached probs if this model already completed
        if cache_path.exists():
            probs = np.load(str(cache_path))
            if probs.shape[0] == n:
                print("  [{}] {} β€” loaded from cache ({})".format(
                      src, cname, cache_path.name))
                probs_by_key[key] = probs
                continue
            else:
                print("  [{}] {} β€” cache shape mismatch ({}), re-running.".format(
                      src, cname, probs.shape))

        tab_feats = None
        if other_cols:
            tab_arr = np.zeros((n, len(other_cols)), dtype=np.float32)
            for i, col in enumerate(other_cols):
                if col in df_unique.columns:
                    tab_arr[:, i] = df_unique[col].fillna(0).values.astype(np.float32)
                else:
                    print("  [WARN] Tabular col '{}' missing for {} β€” using 0.".format(
                          col, cname))
            # --- train/serve parity: standardize tab features exactly like the generator
            # (ensemble_distillation_generator.py ~1833-1835: fillna(0) then StandardScaler)
            import joblib as _joblib
            _scaler_path = os.path.join(os.path.dirname(os.path.abspath(args.config)), 'tab_scaler.joblib')
            if not os.path.exists(_scaler_path):
                raise FileNotFoundError(
                    'other_cols=%s requires %s β€” heads were trained on standardized '
                    'features; refusing to feed raw values' % (other_cols, _scaler_path))
            _bundle = _joblib.load(_scaler_path)
            assert list(_bundle['other_cols']) == list(other_cols), (
                'scaler cols %s != config other_cols %s' % (_bundle['other_cols'], other_cols))
            tab_arr = _bundle['scaler'].transform(tab_arr).astype(np.float32)
            tab_feats = tab_arr

        t0 = time.perf_counter()
        if task == "tfidf_lgbm":
            print("  [{}] {} β€” tfidf_lgbm...".format(src, cname))
            probs = run_tfidf_lgbm(m_cfg, texts, tab_feats, k_folds)
        else:
            print("  [{}] {} β€” {} folds...".format(src, cname, k_folds))
            probs = run_transformer_model(
                m_cfg, texts, tab_feats, max_length, device,
                args.batch_size, k_folds,
                num_workers=args.num_workers,
                prefetch=args.prefetch,
                token_cache_dir=cache_dir)

        elapsed = (time.perf_counter() - t0) * 1000
        mem_mb  = probs.nbytes / 1e6
        print("    done  shape={}  {:.0f}ms  {:.1f}MB".format(
              probs.shape, elapsed, mem_mb))

        # Save to cache immediately β€” crash-safe
        np.save(str(cache_path), probs)
        print("    cached -> {}".format(cache_path.name))
        probs_by_key[key] = probs

    # ── [2] Frozen encoder embeddings (full dataset) ──────────────────────────
    frozen_emb = None
    if cfg.get("frozen_encoder"):
        frozen_cache = _frozen_cache_path()
        if frozen_cache.exists():
            frozen_emb = np.load(str(frozen_cache))
            if frozen_emb.shape[0] == n:
                print("\n[2] Frozen embeddings loaded from cache ({}).".format(
                      frozen_cache.name))
            else:
                print("\n[2] Frozen cache shape mismatch β€” re-extracting...")
                frozen_emb = None

        if frozen_emb is None:
            print("\n[2] Frozen encoder embeddings (full dataset)...")
            t0 = time.perf_counter()
            frozen_emb = get_frozen_embeddings(texts, cfg, device, args.batch_size,
                                               cache_dir=args.cache_dir)
            np.save(str(frozen_cache), frozen_emb)
            print("  done  shape={}  {:.0f}ms  {:.1f}MB  cached->{}".format(
                  frozen_emb.shape,
                  (time.perf_counter() - t0) * 1000,
                  frozen_emb.nbytes / 1e6,
                  frozen_cache.name))

    # Free the text list β€” no longer needed
    del texts
    gc.collect()

    # ── [3] Chunked feature assembly + meta predict on UNIQUE texts ─────────
    # Assemble features and run meta-learner in chunks over the unique-text rows.
    # Results are stored as arrays indexed by unique-row position.
    print("\n[3] Chunked meta-learner inference on {:,} unique texts "
          "(chunk_size={})...".format(n_unique, args.chunk_size))

    all_preds  = np.empty(n_unique, dtype=np.int32)
    all_proba  = np.empty((n_unique, n_classes), dtype=np.float32)
    n_chunks   = (n_unique + args.chunk_size - 1) // args.chunk_size

    # The bundle's feature_names lists ALL features (prob/derived + embeddings).
    # The first n_prob_cols are the prob/derived features build_feature_vector
    # must reproduce; the rest are embedding columns appended separately.
    prob_feat_names = feature_names[:n_prob_cols] if feature_names else None

    for chunk_idx in range(n_chunks):
        start = chunk_idx * args.chunk_size
        end   = min(start + args.chunk_size, n_unique)
        sl    = slice(start, end)

        chunk_probs = {k: v[sl] for k, v in probs_by_key.items()}
        X_chunk, _  = build_feature_vector(
            chunk_probs, class_order, n_classes, use_derived,
            expected_names=prob_feat_names)
        if frozen_emb is not None:
            X_chunk = np.hstack([X_chunk, frozen_emb[sl]])

        proba_chunk = meta.predict_proba(X_chunk)
        all_preds[start:end] = np.argmax(proba_chunk, axis=1)
        all_proba[start:end] = proba_chunk

        if chunk_idx % 10 == 0 or chunk_idx == n_chunks - 1:
            print("  chunk {}/{}  rows {}-{}  ({:.0f}%)".format(
                  chunk_idx + 1, n_chunks, start, end, end / n_unique * 100))

        del X_chunk, proba_chunk
        gc.collect()

    # Free model prob arrays β€” no longer needed
    del probs_by_key, frozen_emb
    gc.collect()

    # ── [4] Build unique-text result lookup and broadcast to all rows ─────────
    print("\n[4] Broadcasting results to {:,} total rows...".format(n_total))

    # Build a text -> (pred, proba) lookup using the unique results
    unique_texts_list = df_unique[args.text_col].tolist()
    text_to_pred  = dict(zip(unique_texts_list, all_preds.tolist()))
    text_to_proba = dict(zip(unique_texts_list, all_proba.tolist()))
    del all_preds, all_proba, unique_texts_list
    gc.collect()

    # Unknown label index
    # Normalise idx_to_lbl keys to int β€” the pickle may store them as int OR str,
    # and inconsistent key types caused every label lookup to silently fall back
    # to UNKNOWN. Build one canonical int-keyed map used everywhere below.
    idx_to_lbl_int = {int(k): v for k, v in idx_to_lbl.items()}
    print("  Label map: {}".format(
          {k: idx_to_lbl_int[k] for k in sorted(idx_to_lbl_int)}))

    unknown_idx = next(
        (k for k, v in idx_to_lbl_int.items() if v == "UNKNOWN"),
        n_classes - 1)
    unknown_label = idx_to_lbl_int.get(unknown_idx, "UNKNOWN")
    unknown_proba = [0.0] * n_classes
    unknown_proba[unknown_idx] = 1.0

    # Write output in chunks, reading original row index to broadcast
    output_path = Path(args.output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    pred_cols = (["predicted_class", "predicted_label", "meta_confidence"] +
                 ["prob_" + cls for cls in class_order])

    first_chunk  = True
    label_counts = {}
    out_chunks   = (n_total + args.chunk_size - 1) // args.chunk_size
    orig_texts   = df[args.text_col].astype(str).str.strip().values

    for chunk_idx in range(out_chunks):
        start = chunk_idx * args.chunk_size
        end   = min(start + args.chunk_size, n_total)

        out = {}
        if extra_keep:
            for col in extra_keep:
                if col in df.columns:
                    out[col] = df[col].iloc[start:end].values
                else:
                    out[col] = np.zeros(end - start, dtype=np.float32)

        preds_out = []
        labels_out = []
        conf_out  = []
        proba_out  = [[] for _ in range(n_classes)]

        for row_text, is_null in zip(
                orig_texts[start:end],
                null_mask.values[start:end]):

            if is_null or row_text.lower() == "none" or row_text == "":
                # Null text β€” assign UNKNOWN
                p_idx  = unknown_idx
                p_lbl  = unknown_label
                p_prob = unknown_proba
            else:
                p_idx  = text_to_pred.get(row_text, unknown_idx)
                p_lbl  = idx_to_lbl_int.get(int(p_idx), unknown_label)
                p_prob = text_to_proba.get(row_text, unknown_proba)

            preds_out.append(p_idx)
            labels_out.append(p_lbl)
            conf_out.append(max(p_prob))
            for i, v in enumerate(p_prob):
                proba_out[i].append(v)

        out["predicted_class"] = preds_out
        out["predicted_label"] = labels_out
        out["meta_confidence"]  = conf_out
        for i, cls in enumerate(class_order):
            out["prob_" + cls] = proba_out[i]

        chunk_df = pd.DataFrame(out)

        # Track distribution
        for lbl, cnt in chunk_df["predicted_label"].value_counts().items():
            label_counts[lbl] = label_counts.get(lbl, 0) + cnt

        # Write / append
        try:
            if first_chunk:
                chunk_df.to_parquet(str(output_path), index=False,
                                    engine="fastparquet")
            else:
                chunk_df.to_parquet(str(output_path), index=False,
                                    engine="fastparquet", append=True)
        except Exception:
            chunk_path = output_path.parent / "_chunk_{:05d}.parquet".format(chunk_idx)
            chunk_df.to_parquet(str(chunk_path), index=False)

        if chunk_idx % 10 == 0 or chunk_idx == out_chunks - 1:
            print("  wrote chunk {}/{}  ({:.0f}%)".format(
                  chunk_idx + 1, out_chunks, end / n_total * 100))

        first_chunk = False
        del chunk_df
        gc.collect()

    # Merge loose chunk files if fastparquet wasn't available
    chunk_files = sorted(output_path.parent.glob("_chunk_*.parquet"))
    if chunk_files:
        print("  Merging {} chunk files...".format(len(chunk_files)))
        pd.concat([pd.read_parquet(f) for f in chunk_files],
                  ignore_index=True).to_parquet(str(output_path), index=False)
        for f in chunk_files:
            f.unlink()

    # Keep the cache by default: base-model outputs and tokenisation are
    # expensive and reusable for re-runs on the same pool (e.g. after a
    # meta-learner swap, which needs no GPU work at all). Pass --clear_cache
    # to remove it on success.
    if args.clear_cache and cache_dir.exists():
        import shutil
        shutil.rmtree(cache_dir)
        print("  Resume cache cleared (--clear_cache).")
    else:
        print("  Resume cache kept -> {}".format(cache_dir))

    print("\n  Predictions saved ->", output_path)
    print("  Total rows         : {:,}".format(n_total))
    print("  Null rows (UNKNOWN): {:,}".format(n_null))
    print("  Deduped rows saved : {:,}".format(n_dups))
    print("  Label distribution :")
    for lbl, cnt in sorted(label_counts.items(), key=lambda x: -x[1]):
        print("    {:<20s}  {:>8,}  ({:.1f}%)".format(
              lbl, cnt, cnt / n_total * 100))
    print("="*60)


if __name__ == "__main__":
    main()