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

The dataset claim needs an experiment, not an argument: for each low-resource language,
fine-tune the same model on different corpora and see which one scores higher on human test
data. The corpora compared are the three we have published --

  sigiranic/grounded-alignment-wiki       ours, model-generated, document-level
  sigiranic/underserved-translation-baseline   existing public data (OPUS)
  sigiranic/underserved-translation-eval       human test sets, never trained on

-- plus PARME's human-translated training split, which is the real rival for Gilaki and
Mazanderani and is fetched from its own repository at a pinned revision.

Two prior works set the shape of this. PARME (ACL 2025) fine-tunes
``facebook/nllb-200-distilled-600M`` with a new language token per target language, reports
BLEU and chrF, and runs an incremental-sample curve; its published scores are in RIVALS
below, so its systems do not have to be re-run to be compared against. "Open Machine
Translation for Esperanto" (SIGUL 2026) compares a ladder of system classes -- rule-based,
compact encoder-decoder, large encoder-decoder, fine-tuned LLM -- and found the NLLB family
ahead with compact models close behind, which is why MODELS is a ladder rather than a single
choice.

Four design rules, each of which exists because the obvious version of this experiment would
be unconvincing:

1. Equal-budget arms. Ours is far larger than every alternative, so "ours wins" could just
   mean "more data wins". Every headline comparison therefore has a subsampled twin that
   matches the rival's pair count exactly.
2. Additive arms. Nobody deletes their existing corpus to adopt a new one. ours+public and
   ours+human answer the question practitioners actually have.
3. Both directions, reported separately. Our source side is human Wikipedia text and our
   target side is model output, so pivot->low-resource trains on a *human* target -- the
   configuration back-translation is known to help -- while low-resource->pivot trains on a
   model target and should be read more sceptically. Averaging the two would hide that.
4. Significance, not point estimates. The test sets here run from 197 to 4,896 sentences, and
   at the low end a two-point chrF gap is noise. Every comparison is reported with a paired
   bootstrap p-value against its arm's designated rival.

Stages
  plan      print the arm x language matrix and the scores to beat; no network, no GPU
  prepare   fetch every corpus, build each arm's train/dev/test, run the contamination gate
  train     fine-tune one arm on one pinned GPU
  evaluate  generate on the test split and score it against the human references
  report    collect every finished arm into one table, next to the published rival numbers

Stages plan, prepare and report need neither torch nor a GPU, so the data work can run
anywhere and only train/evaluate have to run on the server.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import random
import re
import sys
import time
import unicodedata
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
WORK = ROOT / "dist" / "data_value"
CACHE = ROOT / "cache" / "data_value"

OURS = "sigiranic/grounded-alignment-wiki"
PUBLIC = "sigiranic/underserved-translation-baseline"
HUMAN_EVAL = "sigiranic/underserved-translation-eval"

# PARME's training data is not in our eval dataset -- we took only its test and dev splits,
# so its train split is still a clean rival corpus. Pinned so the comparison is reproducible.
PARME_REPO = "DOLMA-NLP/PARME"
PARME_REVISION = "6df9269acc75377ed6be3bf2f7966c8e238a62bd"
PARME_RAW = f"https://raw.githubusercontent.com/{PARME_REPO}/{PARME_REVISION}"

# The languages we have grounded data for, each with the pivots it was generated against and
# the NLLB language tag to seed a new token from when NLLB has no tag of its own. The donor is
# the closest language NLLB does cover, so the new embedding starts somewhere sensible rather
# than at random.
LANGUAGES = {
    "als": {"tag": "als_Latn", "donor": "deu_Latn",
            "pivots": {"de": "deu_Latn", "en": "eng_Latn"}},
    "bar": {"tag": "bar_Latn", "donor": "deu_Latn",
            "pivots": {"de": "deu_Latn", "en": "eng_Latn"}},
    "frr": {"tag": "frr_Latn", "donor": "deu_Latn",
            "pivots": {"de": "deu_Latn", "en": "eng_Latn"}},
    "glk": {"tag": "glk_Arab", "donor": "pes_Arab",
            "pivots": {"fa": "pes_Arab", "en": "eng_Latn"}},
    "mzn": {"tag": "mzn_Arab", "donor": "pes_Arab",
            "pivots": {"fa": "pes_Arab", "en": "eng_Latn"}},
}

# PARME's own published numbers, read from codes/results/ in the pinned revision. Having them
# means its systems are competitors without costing us a single GPU hour. Its results files do
# not record the direction, so confirm against codes/scorer.py before quoting these as
# directly comparable -- they are recorded here as "the number to beat", not as a verified
# like-for-like.
RIVALS = {
    ("glk", "parme_nllb_base"): {"bleu": 2.7, "bleu_ci": 0.6, "chrf2": 20.0, "chrf2_ci": 0.6,
                                 "test": "PARME GLK-test", "comparable": True},
    ("glk", "parme_nllb_augmented"): {"bleu": 3.5, "bleu_ci": 0.6, "chrf2": 20.7,
                                      "chrf2_ci": 0.7, "test": "PARME GLK-test",
                                      "comparable": True},
    ("mzn", "parme_nllb_base"): {"bleu": 5.2, "bleu_ci": 0.9, "chrf2": 22.9, "chrf2_ci": 0.8,
                                 "test": "PARME MZN-test", "comparable": True},
    ("mzn", "parme_nllb_augmented"): {"bleu": 5.3, "bleu_ci": 0.9, "chrf2": 23.5,
                                      "chrf2_ci": 0.9, "test": "PARME MZN-test",
                                      "comparable": True},
    # Her & Kruschwitz, SIGUL 2024, "Investigating NMT for Low-Resource Languages: Using
    # Bavarian as a Case Study" (github.com/whher/nmt-de-bar). Transformer trained from
    # scratch on 42K OPUS pairs, 5-fold cross-validation.
    #
    # These scores are NOT comparable to anything else in this file and must never be quoted
    # beside a human-benchmark number. Their test split is a random fold of the same mined
    # OPUS corpus they trained on -- 33,813 train against 8,453 test, drawn from WikiMatrix
    # and friends. Mined corpora are full of near-duplicates, so a random split leaks, which
    # is how an under-resourced pair reaches 73 BLEU. Their own limitations section calls for
    # "a more refined and organized parallel corpus ... to help establish a high quality
    # benchmark", which is the gap this dataset exists to fill. The useful experiment is to
    # reproduce their recipe and show what it scores on a human test set instead.
    ("bar", "her_baseline_bar_de"): {"bleu": 66.0, "chrf2": 78.1, "ter": 32.7,
                                     "test": "random fold of mined OPUS (in-domain)",
                                     "comparable": False},
    ("bar", "her_backtranslated_bar_de"): {"bleu": 73.4, "chrf2": 82.5, "ter": 25.0,
                                           "test": "random fold of mined OPUS (in-domain)",
                                           "comparable": False},
    ("bar", "her_transferred_bar_de"): {"bleu": 53.9, "chrf2": 70.5, "ter": 41.9,
                                        "test": "random fold of mined OPUS (in-domain)",
                                        "comparable": False},
    ("bar", "her_baseline_de_bar"): {"bleu": 61.2, "chrf2": 74.4, "ter": 36.2,
                                     "test": "random fold of mined OPUS (in-domain)",
                                     "comparable": False},
    ("bar", "her_backtranslated_de_bar"): {"bleu": 63.4, "chrf2": 76.3, "ter": 31.9,
                                           "test": "random fold of mined OPUS (in-domain)",
                                           "comparable": False},
    ("bar", "her_transferred_de_bar"): {"bleu": 48.2, "chrf2": 63.9, "ter": 44.4,
                                        "test": "random fold of mined OPUS (in-domain)",
                                        "comparable": False},
}

# Bavarian has more prior work than any other language here, and two pieces of it are rival
# *corpora* rather than rival scores, so they become arms.
#
# cis-lmu/bavarian_to_english is the closest thing to a controlled rival that exists: Lin et
# al., "Construction-Based Reduction of Translationese for Low-Resource Languages: A Pilot
# Study on Bavarian" (SIGTYP 2025) took the same source we did -- the Bavarian Wikipedia --
# and had GPT-4 translate it to English with no grounding. Same source, same idea, no
# evidence. It is document-level and unaligned, so it has to be sentence-split before use.
LIN_BLIND = "cis-lmu/bavarian_to_english"

# adahmpl/gga-bavarian-20k-test holds five methods over an identical 20,000 Bavarian sources
# with a shared 500-pair validation set: blind translation, LASER mining, BGE-M3 mining,
# Variant A (translate then refine) and Variant B (evidence then translate). A size- and
# source-controlled five-way comparison, which is worth more than any arm built here.
#
# PROVENANCE, and it changes how these arms may be described. This is not an independent
# third party and not this pipeline either: it is a student of this project's supervisor,
# given a similar task and working separately. So the gga_* arms are a concurrent
# independent implementation of the same idea under the same supervision.
#
# What follows from that:
#   - They are not an arm's-length external baseline. A write-up that lists gga_blind among
#     "rival systems" without saying where it came from would overstate the independence of
#     the comparison, and the relationship has to be disclosed.
#   - They are not ours to claim either. Variant A and Variant B are her design decisions,
#     not ours, so "our method ties blind translation" is not what these arms measure.
#   - The dataset is CC-BY-SA-4.0, so attribution is required in any case, and authorship
#     credit is a question for the people involved rather than for this file.
#
# The comparison itself remains the most tightly controlled one available here -- identical
# sources, identical validation split, method as the only variable -- which is exactly why it
# is worth being precise about whose method each arm is.
GGA_20K = "adahmpl/gga-bavarian-20k-test"
GGA_METHODS = ["blind", "laser", "bge_m3", "variant_a", "variant_b"]

# The system ladder. Sizes are what the model cards report; the point of the ladder is that a
# data claim which only holds for one architecture is not a data claim.
# ``tagged`` means the model selects its languages through NLLB-style language tokens. Marian
# models do not: each one is built for its own pair, so there is no tag to set and no token to
# add. ``kind`` selects the training and generation path.
MODELS = {
    "zeroshot": {"base": "facebook/nllb-200-distilled-600M", "kind": "seq2seq",
                 "tagged": True, "train": False,
                 "why": "off-the-shelf NLLB, the floor every trained arm must clear"},
    "nllb600m": {"base": "facebook/nllb-200-distilled-600M", "kind": "seq2seq",
                 "tagged": True, "train": True,
                 "why": "PARME's exact setup, so our numbers sit beside theirs"},
    "nllb1b3": {"base": "facebook/nllb-200-distilled-1.3B", "kind": "seq2seq",
                "tagged": True, "train": True,
                "why": "does the data advantage survive more capacity"},
    "marian": {"base": None, "kind": "seq2seq", "tagged": False, "train": True,
               "why": "the compact 76.9M class the Esperanto work found competitive; a "
                      "different architecture, so a data claim that holds here is not an "
                      "artefact of NLLB"},
    "llm_lora": {"base": "Qwen/Qwen3-4B", "kind": "causal_lora", "tagged": False,
                 "train": True,
                 "why": "the fine-tuned general-purpose LLM arm; the Esperanto work put this "
                        "close behind NLLB"},
}

# Which corpus each arm trains on. ``rival`` names the arm a significance test compares
# against, so the report can say "better than X, p=..." rather than listing bare scores.
ARMS = {
    # Both public arms exclude llm_translated. The baseline corpus now also carries
    # FineTranslations, which is an order of magnitude larger than everything else in it, so
    # leaving it in would have silently redefined these two arms -- every number already
    # measured for them would have become a different experiment under the same name. It gets
    # its own arms below instead, which is also the only way to compare against it.
    "public": {"sources": ["public"], "rival": None,
               "drop_corpus_types": ["llm_translated"],
               "why": "existing public data as-is -- for Bavarian that is mostly WikiMatrix "
                      "mining and XLEnt entity lists"},
    "public_prose": {"sources": ["public"], "rival": "public",
                     "drop_corpus_types": ["entity_list", "ui_strings", "llm_translated"],
                     "why": "the same corpus with entity lists and UI strings removed, which "
                            "is the fair version of the public baseline"},
    "human": {"sources": ["human"], "rival": None,
              "why": "PARME's human translations; the strongest rival, and tiny"},
    "ours": {"sources": ["ours"], "rival": "public_prose",
             "why": "the headline arm"},
    "ours_filtered": {"sources": ["ours"], "rival": "ours", "apply_checks": True,
                      "why": "ours, dropping documents our own checks flag; tests whether "
                             "the published quality metrics predict training value"},
    "ours_matched_public": {"sources": ["ours"], "rival": "public_prose",
                            "match_size_of": "public_prose",
                            "why": "ours cut to the public corpus's size, so a win cannot be "
                                   "explained by volume"},
    "ours_matched_human": {"sources": ["ours"], "rival": "human", "match_size_of": "human",
                           "why": "ours cut to PARME's size: model-generated against "
                                  "human-translated at equal count"},
    "ours_plus_public": {"sources": ["ours", "public"], "rival": "public",
                         "why": "what a practitioner would actually do"},
    "ours_plus_human": {"sources": ["ours", "human"], "rival": "human",
                        "why": "does ours still add on top of human data"},
    # Bavarian only, and the cleanest comparison in the file: same source wikipedia, same
    # idea, one grounded and one not.
    "lin_blind": {"sources": ["lin_blind"], "rival": None,
                  "why": "Lin et al.'s GPT-4 blind translation of the same Bavarian "
                         "Wikipedia; grounding is the only difference"},
    "ours_matched_lin": {"sources": ["ours"], "rival": "lin_blind",
                         "match_size_of": "lin_blind",
                         "why": "ours cut to Lin et al.'s size: grounded against blind at "
                                "equal count, from the same source corpus"},
    # FineTranslations: the same blind-translation idea as Lin et al. but at web scale and
    # across 500+ languages, which makes it the rival most practitioners will actually reach
    # for. Gemma3 27B over FineWeb2, chunk-aligned, English pivot only.
    #
    # It is used in its cleaned form only, and that is FineWeb2's own position rather than a
    # correction of it: the FineWeb2 paper discusses the Gilaki data not being clean, and
    # GlotLID v4 and the GlotLID wordlists are the tools it names for the problem. So the
    # rival is FineTranslations as its authors would have it used -- chunks GlotLID v4
    # assigns to the right language, at a confidence of at least 0.90. Running the raw
    # config beside it would be arguing with a point nobody disputes, and would stake the
    # comparison on a weakness of their language identification rather than on translation
    # quality, which is the thing actually under test.
    #
    # For scale, the filter is not cosmetic: of 27,135 glk_Arab chunks, GlotLID rejects
    # 22,462 as Persian outright, and 2,011 survive at 0.90. bar_Latn keeps 31,569 of 99,457.
    "finetrans_clean": {"sources": ["finetrans_clean"], "rival": None,
                        "why": "FineTranslations as its own authors would have it filtered: "
                               "GlotLID v4 agreement at 0.90 or better. Blind LLM "
                               "translation at web scale, the rival most practitioners will "
                               "actually reach for"},
    "ours_matched_finetrans": {"sources": ["ours"], "rival": "finetrans_clean",
                               "match_size_of": "finetrans_clean",
                               "why": "ours cut to the cleaned FineTranslations size: "
                                      "grounded against blind at web scale, equal count"},
    "ours_plus_finetrans": {"sources": ["ours", "finetrans_clean"],
                            "rival": "finetrans_clean",
                            "why": "does grounded data still add on top of the large blind "
                                   "corpus a practitioner already has"},
}

# The GlotLID v4 confidence a pair needs to enter the FineTranslations arm. FineTranslations'
# own language_score is deliberately not used: it rates the glk_Arab config at a median of
# 0.651 while GlotLID finds 83% of it to be Persian, so it does not measure what it appears
# to measure. GlotLID v4 is the identifier FineWeb2 itself names for this.
FINETRANS_MIN_SCORE = 0.90

# The five methods of the 20k comparison become arms too, each against the same 20,000
# Bavarian sources. Ours joins them at the same size, so the six are directly comparable.
for _method in GGA_METHODS:
    ARMS[f"gga_{_method}"] = {
        "sources": [f"gga_{_method}"],
        # blind is the reference every other method is measured against, so it has no rival
        # of its own. Leaving it pointing at itself made the report compare it with itself
        # and print "+0.00 chrF++ vs gga_blind p=0.001*" -- a significant difference from
        # itself, which is nonsense dressed as a result.
        "rival": None if _method == "blind" else "gga_blind",
        "why": f"the {_method} arm of the size-controlled 20k Bavarian comparison"}
# The translator isolated: identical Bavarian source sentences, our English against hers.
# Every other variable -- count, sources, lengths, document mix -- is held fixed by
# construction, so a gap here is the model and nothing else. See the pool comment in
# stage_prepare for why the unpaired 20k comparison cannot answer this.
ARMS["paired_gga"] = {
    "sources": ["paired_gga"], "rival": None,
    "why": "the shared Bavarian sentences as her pipeline translated them (Gemma)"}
ARMS["paired_ours"] = {
    "sources": ["paired_ours"], "rival": "paired_gga",
    "why": "the same sentences as ours translated them (astra); the only difference from "
           "paired_gga is the translator"}

ARMS["ours_matched_gga"] = {
    "sources": ["ours"], "rival": "gga_blind", "match_size_of": "gga_blind",
    "why": "ours at the same 20k budget as every arm of that comparison"}

SCALE_POINTS = [1_000, 5_000, 20_000, 100_000, 0]   # 0 means every pair available


# ---------------------------------------------------------------------------- small helpers

def load_json(path: Path):
    return json.loads(Path(path).read_text(encoding="utf-8"))


def plain(value):
    """Turn numpy scalars into python ones so json.dumps accepts them.

    sacrebleu's paired bootstrap returns float32 for the confidence interval, which the
    stdlib encoder refuses. Converting here rather than at each call site means no future
    caller has to remember which fields came out of numpy.
    """
    if hasattr(value, "item") and not isinstance(value, (str, bytes)):
        return value.item()
    if isinstance(value, dict):
        return {key: plain(entry) for key, entry in value.items()}
    if isinstance(value, (list, tuple)):
        return [plain(entry) for entry in value]
    return value


def save_json(path: Path, value) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(plain(value), ensure_ascii=False, indent=1) + "\n",
                    encoding="utf-8")


def save_jsonl(path: Path, rows) -> int:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        count = 0
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")
            count += 1
    return count


def load_jsonl(path: Path) -> list[dict]:
    with Path(path).open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for block in iter(lambda: handle.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def text_key(text: str) -> str:
    """Normalise a sentence for contamination and duplicate checks.

    Casefolded, NFKC, punctuation and whitespace collapsed. Deliberately aggressive: a test
    sentence that reappears in training with different spacing or a swapped quote mark is
    still contamination, and a false positive only costs us one training pair.
    """
    folded = unicodedata.normalize("NFKC", text).casefold()
    return re.sub(r"[^\w]+", " ", folded, flags=re.UNICODE).strip()


# ----------------------------------------------------------------------------- corpus loaders

def hub_parquet(repo: str, filename: str):
    from huggingface_hub import hf_hub_download
    sys.path.insert(0, str(ROOT / "scripts"))
    import pyarrow.parquet as pq
    path = hf_hub_download(repo, filename=filename, repo_type="dataset",
                           token=maybe_token(), cache_dir=str(CACHE / "hub"))
    return pq.read_table(path)


def ours_pairs(language: str, pivot: str, *, apply_checks: bool = False):
    """Sentence pairs from our document-level data, one per aligned sentence.

    Rows are documents, so each contributes len(srcs) pairs. When ``apply_checks`` is set the
    document's own ``checks`` blob gates it: a document that dropped a protected span or came
    back largely identical to its source is exactly what the dataset card warns about, and
    this is where that warning gets tested rather than repeated.
    """
    import glob
    import pyarrow.parquet as pq
    local = sorted(glob.glob(str(ROOT / "dist/grounded_alignment/*/data/*.parquet")))
    if not local:
        # On a GPU host there is no local generate output, so fall back to the published
        # dataset. Only this language's folder is fetched: the whole thing is 87k documents
        # and a single language is a fraction of that.
        local = sorted(glob.glob(str(Path(ours_snapshot(language)) / "data" / language
                                      / "*.parquet")))
    if not local:
        raise SystemExit("no grounded-alignment shards, local or published")
    seen: set[str] = set()
    for path in local:
        table = pq.read_table(path, columns=["id", "sl", "tl", "srcs", "trgs", "checks",
                                             "sep"])
        columns = table.to_pydict()
        for index in range(table.num_rows):
            if columns["sl"][index] != language or columns["tl"][index] != pivot:
                continue
            row_id = columns["id"][index]
            if row_id in seen:        # local disk still holds superseded shards
                continue
            seen.add(row_id)
            checks = json.loads(columns["checks"][index] or "{}")
            if apply_checks:
                dropped = (checks.get("protected_spans", 0)
                           - checks.get("protected_spans_kept", 0))
                sentences = max(checks.get("sentences") or 1, 1)
                if dropped or checks.get("off_script_sentences"):
                    continue
                if (checks.get("identical_to_source", 0) / sentences) > 0.5:
                    continue
            # ``sep`` holds the text that followed each sentence in the source article, so a
            # separator containing a newline is a real paragraph break. Carrying the
            # paragraph number and the sentence's position lets build_units reproduce the
            # article's own paragraphs instead of chopping documents into fixed windows.
            separators = columns["sep"][index] or []
            paragraph = 0
            for position, (source, target) in enumerate(
                    zip(columns["srcs"][index], columns["trgs"][index])):
                separator = separators[position] if position < len(separators) else " "
                if source.strip() and target.strip():
                    yield {"low": source, "pivot": target, "origin": "ours",
                           "document_id": row_id,
                           "paragraph_id": f"{row_id}#{paragraph}",
                           "sentence_index": position,
                           "sep": separator}
                if "\n" in (separator or ""):
                    paragraph += 1


def maybe_token() -> str | None:
    """The project Hub credential when it is available, otherwise None.

    Every dataset this experiment reads is public, and the GPU host has no macOS Keychain to
    read the credential from. Treating a missing token as fatal would make the whole thing
    un-runnable on the server for no reason, so a missing one simply means anonymous access.
    """
    try:
        from hf_publishing_auth import publishing_token
        return publishing_token()
    except Exception:
        return None


def ours_snapshot(language: str) -> str:
    """Download one language's folder of the published dataset, once, and cache it."""
    from huggingface_hub import snapshot_download
    sys.path.insert(0, str(ROOT / "scripts"))
    return snapshot_download(OURS, repo_type="dataset",
                             allow_patterns=[f"data/{language}/*.parquet"],
                             local_dir=str(CACHE / "ours"), token=maybe_token(),
                             max_workers=8)


def public_pairs(language: str, pivot: str, *, drop_corpus_types=()):
    """Pairs from the published baseline corpus, optionally minus the non-prose corpus types."""
    table = hub_parquet(PUBLIC, "data/baseline.parquet")
    columns = table.to_pydict()
    drop = set(drop_corpus_types)
    for index in range(table.num_rows):
        sl, tl = columns["sl"][index], columns["tl"][index]
        if {sl, tl} != {language, pivot}:
            continue
        if columns["corpus_type"][index] in drop:
            continue
        src, trg = columns["src"][index], columns["trg"][index]
        low, piv = (src, trg) if sl == language else (trg, src)
        if low.strip() and piv.strip():
            yield {"low": low, "pivot": piv, "origin": "public",
                   "corpus": columns["corpus"][index]}


def finetrans_pairs(language: str, pivot: str, *, min_score: float = 0.0):
    """FineTranslations pairs from the baseline corpus, optionally score-filtered.

    English pivot only, because FineTranslations pairs every language with English and
    nothing else -- there is no Gilaki-Persian side to it. Asking for another pivot yields
    nothing rather than falling back to English, which would compare two different tasks.

    ``min_score`` is GlotLID v4's confidence, not FineTranslations' own language_score; the
    published baseline already contains only chunks GlotLID assigned to this language, so
    this threshold narrows a verified corpus rather than cleaning an unverified one.

    ``document_id`` is carried through so the size-matched arm can sample whole documents and
    the training-unit ablation can regroup these pairs the same way it regroups ours.
    """
    if pivot != "en":
        return
    table = hub_parquet(PUBLIC, "data/baseline.parquet")
    columns = table.to_pydict()
    for index in range(table.num_rows):
        if columns["corpus"][index] != "FineTranslations":
            continue
        if columns["tl"][index] != language:
            continue
        score = columns["glotlid_prob"][index]
        if min_score and (score is None or score < min_score):
            continue
        low, piv = columns["trg"][index], columns["src"][index]
        if low.strip() and piv.strip():
            yield {"low": low, "pivot": piv, "origin": "finetrans",
                   "corpus": "FineTranslations",
                   "document_id": columns["document_id"][index],
                   "glotlid_prob": score}


def parme_pairs(language: str, pivot: str, split: str = "train"):
    """PARME's human translations for Gilaki and Mazanderani.

    Its TSVs carry an English and a Farsi column beside the target language, so one file
    serves both pivots. Only glk and mzn are covered; the Germanic languages have no PARME.
    """
    import urllib.request
    if language not in {"glk", "mzn"}:
        return
    name = f"{language.upper()}-{split}.tsv"
    cached = CACHE / "parme" / name
    if not cached.exists():
        cached.parent.mkdir(parents=True, exist_ok=True)
        with urllib.request.urlopen(f"{PARME_RAW}/datasets/{name}", timeout=120) as response:
            cached.write_bytes(response.read())
    lines = cached.read_text(encoding="utf-8").splitlines()
    if not lines:
        return
    header = [h.strip().lower() for h in lines[0].split("\t")]
    wanted = {"en": ("en_sentence", "en", "english"),
              "fa": ("fa_sentence", "fa", "farsi", "persian")}[pivot]
    pivot_column = next((i for i, h in enumerate(header) if h in wanted), None)
    target_column = next((i for i, h in enumerate(header)
                          if h in ("translation", language, f"{language}_sentence")), None)
    if pivot_column is None or target_column is None:
        raise SystemExit(f"{name}: cannot find pivot/target columns in header {header}")
    for line in lines[1:]:
        cells = line.split("\t")
        if len(cells) <= max(pivot_column, target_column):
            continue
        low, piv = cells[target_column].strip(), cells[pivot_column].strip()
        if low and piv:
            yield {"low": low, "pivot": piv, "origin": "human"}


def lin_blind_pairs(language: str, pivot: str):
    """Lin et al.'s GPT-4 translation of the Bavarian Wikipedia, sentence-aligned.

    Their release is document-level and unaligned: one Bavarian article beside one English
    translation, wiki markup and all. To use it as MT training data the two sides have to be
    split and matched, and a document whose two sides disagree on sentence count is dropped
    rather than guessed at. The drop rate is itself a result worth reporting -- our own
    release is aligned by construction, with a ``sep`` field that rebuilds the document, and
    this is where that difference stops being a design claim and becomes a number.
    """
    if language != "bar" or pivot != "en":
        return
    table = hub_parquet_revision(LIN_BLIND, "bar-eng/train/0000.parquet")
    columns = table.to_pydict()
    for index in range(table.num_rows):
        low_side = strip_markup(columns["org_bar"][index] or "")
        pivot_side = strip_markup(columns["trans_eng"][index] or "")
        low_sentences = split_sentences(low_side)
        pivot_sentences = split_sentences(pivot_side)
        if not low_sentences or len(low_sentences) != len(pivot_sentences):
            continue
        for low, piv in zip(low_sentences, pivot_sentences):
            if low.strip() and piv.strip():
                yield {"low": low, "pivot": piv, "origin": "lin_blind",
                       "document_id": f"lin-{columns['id'][index]}"}


def gga_pairs(method: str, language: str, pivot: str, split: str = "train"):
    """One method's arm from the size-controlled 20k Bavarian comparison."""
    if language != "bar" or pivot != "en":
        return
    table = hub_parquet_revision(GGA_20K, f"{method}/{split}/0000.parquet")
    columns = table.to_pydict()
    for index in range(table.num_rows):
        if columns["source_lang"][index] != "bar" or columns["target_lang"][index] != "en":
            continue
        low, piv = columns["source_text"][index], columns["target_text"][index]
        if low and piv and low.strip() and piv.strip():
            yield {"low": low, "pivot": piv, "origin": f"gga_{method}",
                   "document_id": f"gga-{columns['source_article'][index]}"}


def hub_parquet_revision(repo: str, filename: str):
    """Read a parquet from the Hub's auto-converted branch, where third-party data lives."""
    from huggingface_hub import hf_hub_download
    sys.path.insert(0, str(ROOT / "scripts"))
    import pyarrow.parquet as pq
    path = hf_hub_download(repo, filename=filename, repo_type="dataset",
                           revision="refs/convert/parquet", token=maybe_token(),
                           cache_dir=str(CACHE / "hub"))
    return pq.read_table(path)


def strip_markup(text: str) -> str:
    """Remove the wiki and HTML leftovers in Lin et al.'s article text."""
    text = re.sub(r"<[^>]+>", " ", text)
    text = re.sub(r"\{\{[^}]*\}\}", " ", text)
    text = re.sub(r"\[\[([^\]|]*\|)?([^\]]*)\]\]", r"\2", text)
    return re.sub(r"[ \t]+", " ", text)


def split_sentences(text: str) -> list[str]:
    """Split on sentence-final punctuation followed by a capital or a line break.

    Deliberately conservative. A wrong split here silently misaligns a pair, and since the
    alignment of this rival corpus is the thing being measured, over-splitting would flatter
    us by discarding its documents for the wrong reason.
    """
    parts = []
    for line in text.split("\n"):
        line = line.strip()
        if not line:
            continue
        parts.extend(s.strip() for s in re.split(r"(?<=[.!?])\s+(?=[A-ZÄÖÜ])", line))
    return [p for p in parts if len(p) > 1]


def eval_pairs(language: str, pivot: str, split: str):
    """Human test or dev pairs. Never used for training, only for scoring and the gate."""
    table = hub_parquet(HUMAN_EVAL, "data/eval.parquet")
    columns = table.to_pydict()
    for index in range(table.num_rows):
        sl, tl = columns["sl"][index], columns["tl"][index]
        if {sl, tl} != {language, pivot} or columns["split"][index] != split:
            continue
        # SMOL is released as training data elsewhere, so it is not a safe test set.
        if columns["released_as"][index] == "training":
            continue
        src, trg = columns["src"][index], columns["trg"][index]
        low, piv = (src, trg) if sl == language else (trg, src)
        if low.strip() and piv.strip():
            yield {"low": low, "pivot": piv, "source": columns["source"][index],
                   "document_id": columns["document_id"][index]}


# --------------------------------------------------------------------------------- the stages

def stage_plan(args) -> int:
    print("arms (same model, same seed, same hyperparameters; only the corpus differs)\n")
    width = max(len(name) for name in ARMS)
    for name, arm in ARMS.items():
        extra = []
        if arm.get("match_size_of"):
            extra.append(f"size-matched to {arm['match_size_of']}")
        if arm.get("drop_corpus_types"):
            extra.append("minus " + "/".join(arm["drop_corpus_types"]))
        if arm.get("apply_checks"):
            extra.append("checks-filtered")
        note = f"  [{'; '.join(extra)}]" if extra else ""
        print(f"  {name:{width}s}  {'+'.join(arm['sources']):14s} {arm['why']}{note}")
    print(f"\nscale curve on ours: {SCALE_POINTS} (0 = all)")
    print("\nmodel ladder")
    for name, model in MODELS.items():
        print(f"  {name:10s} {str(model['base']):38s} {model['why']}")
    print("\nlanguages and directions")
    for code, spec in LANGUAGES.items():
        pivots = ", ".join(f"{code}<->{p}" for p in spec["pivots"])
        print(f"  {code}  tag {spec['tag']:9s} donor {spec['donor']:9s} {pivots}")
    def rival_line(code, system, scores):
        bleu = f"{scores['bleu']:5.1f}" + (f" +-{scores['bleu_ci']:.1f}"
                                           if "bleu_ci" in scores else "       ")
        chrf = f"{scores['chrf2']:5.1f}" + (f" +-{scores['chrf2_ci']:.1f}"
                                            if "chrf2_ci" in scores else "       ")
        return f"  {code} {system:28s} BLEU {bleu}  chrF2 {chrf}  {scores['test']}"

    print("\npublished rival scores, comparable -- same test split, same metric")
    for (code, system), scores in sorted(RIVALS.items()):
        if scores.get("comparable"):
            print(rival_line(code, system, scores))
    print("\npublished rival scores, NOT comparable -- do not quote beside the above")
    for (code, system), scores in sorted(RIVALS.items()):
        if not scores.get("comparable"):
            print(rival_line(code, system, scores))
    print("  ^ these are a random fold of the mined corpus they trained on. Near-duplicates")
    print("    leak across the split, which is how a low-resource pair reaches 73 BLEU. The")
    print("    experiment worth running is their recipe scored on a human test set.")
    print("\nnote: glk and mzn have a PARME rival; bar has three rival corpora (Lin et al.")
    print("and the five-method 20k comparison). als and frr have no rival but the public")
    print("corpus and zero-shot NLLB -- for als that public corpus is 9 sentence pairs.")
    return 0


def stage_prepare(args) -> int:
    """Build every arm's data, then refuse to continue if any of it touches the test sets."""
    random.seed(args.seed)
    languages = args.languages or list(LANGUAGES)
    manifest: dict = {"built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                      "seed": args.seed, "parme_revision": PARME_REVISION, "arms": {}}

    for language in languages:
        if language not in LANGUAGES:
            raise SystemExit(f"{language}: not a configured source language")
        for pivot in LANGUAGES[language]["pivots"]:
            # Held-out data first: the gate needs it before any training file is accepted.
            test = list(eval_pairs(language, pivot, "test"))
            dev = list(eval_pairs(language, pivot, "dev"))
            if not test:
                print(f"[skip] {language}-{pivot}: no human test data", flush=True)
                continue
            forbidden = {text_key(row["low"]) for row in test + dev}
            forbidden |= {text_key(row["pivot"]) for row in test + dev}

            pools: dict[str, list[dict]] = {}
            pools["ours"] = list(ours_pairs(language, pivot))
            pools["ours_checked"] = list(ours_pairs(language, pivot, apply_checks=True))
            pools["public"] = list(public_pairs(
                language, pivot, drop_corpus_types=ARMS["public"]["drop_corpus_types"]))
            pools["public_prose"] = list(public_pairs(
                language, pivot, drop_corpus_types=ARMS["public_prose"]["drop_corpus_types"]))
            pools["finetrans_clean"] = list(finetrans_pairs(
                language, pivot, min_score=FINETRANS_MIN_SCORE))
            pools["human"] = list(parme_pairs(language, pivot, "train"))
            # Bavarian-only rival corpora. Both return nothing for every other language, so
            # their arms simply do not appear elsewhere.
            pools["lin_blind"] = list(lin_blind_pairs(language, pivot))
            for method in GGA_METHODS:
                pools[f"gga_{method}"] = list(gga_pairs(method, language, pivot))

            # The translator, isolated. Both corpora mine the same Bavarian Wikipedia, so
            # thousands of source sentences appear in both -- each with a different English
            # translation. Training on exactly that intersection, once with each side's
            # English, holds the sources, the count, the sentence lengths and the document
            # mix fixed and leaves the translator as the only variable.
            #
            # Without this the comparison is unreadable: the two corpora also differ in
            # sentences per document (8.5 against 31.8), sentence length (69 against 79
            # characters) and article count (2,365 against 629), and any of those could
            # explain a gap as easily as the model could.
            shared_index = {text_key(row["low"]): row for row in pools["gga_blind"]}
            if shared_index:
                ours_by_key = {}
                for row in pools["ours"]:
                    ours_by_key.setdefault(text_key(row["low"]), row)
                shared = sorted(set(ours_by_key) & set(shared_index))
                pools["paired_ours"] = [ours_by_key[key] for key in shared]
                pools["paired_gga"] = [shared_index[key] for key in shared]

            def clean(rows: list[dict]) -> tuple[list[dict], int, int]:
                """Drop contaminated and duplicate pairs, reporting how many of each."""
                kept, seen, leaked = [], set(), 0
                for row in rows:
                    low_key, pivot_key = text_key(row["low"]), text_key(row["pivot"])
                    if low_key in forbidden or pivot_key in forbidden:
                        leaked += 1
                        continue
                    pair_key = (low_key, pivot_key)
                    if pair_key in seen:
                        continue
                    seen.add(pair_key)
                    kept.append(row)
                return kept, leaked, len(rows) - len(kept) - leaked

            cleaned = {}
            for name, rows in pools.items():
                kept, leaked, duplicated = clean(rows)
                cleaned[name] = kept
                if rows:
                    print(f"  {language}-{pivot:3s} {name:14s} {len(rows):7,} -> {len(kept):7,}"
                          f"  (contaminated {leaked:,}, duplicate {duplicated:,})", flush=True)

            def pool_for(arm_name: str, arm: dict, source: str) -> str:
                """Which prepared pool an arm's named source resolves to.

                Filtered variants of a source live in a pool named after the arm that
                defines the filter -- 'public' and 'public_prose' are both built from the
                public corpus with different drop lists, and both are pool names. This used
                to be inferred from whether the arm had a drop list at all, which silently
                broke the moment 'public' acquired one of its own: the public arm started
                reading the public_prose pool.
                """
                if source == "ours" and arm.get("apply_checks"):
                    return "ours_checked"
                if source == "public" and arm.get("drop_corpus_types"):
                    return arm_name if arm_name in ("public", "public_prose") else "public"
                return source

            for arm_name, arm in ARMS.items():
                pool_names = [pool_for(arm_name, arm, s) for s in arm["sources"]]
                rows: list[dict] = []
                for pool in pool_names:
                    rows.extend(cleaned.get(pool, []))
                if not rows:
                    continue
                if arm.get("match_size_of"):
                    target_arm = ARMS[arm["match_size_of"]]
                    reference = []
                    for pool in target_arm["sources"]:
                        reference.extend(cleaned.get(
                            pool_for(arm["match_size_of"], target_arm, pool), []))
                    if not reference:
                        continue
                    # Sample whole documents, not loose sentences: taking sentences at random
                    # from a document corpus would quietly hand the matched arm an easier,
                    # more diverse sample than the rival ever had.
                    rows = sample_by_document(rows, len(reference), args.seed)
                write_arm(manifest, language, pivot, arm_name, rows, dev, test)

            # The scale curve, ours only. A steeper slope is a stronger claim than any single
            # point, and it is the comparison PARME itself ran in 100-sentence increments.
            for size in SCALE_POINTS:
                rows = cleaned["ours"]
                if size and size < len(rows):
                    rows = sample_by_document(rows, size, args.seed)
                elif size:
                    continue        # no point in a curve point larger than the corpus
                write_arm(manifest, language, pivot, f"ours_scale_{size or 'all'}",
                          rows, dev, test)

    save_json(WORK / "prepare_manifest.json", manifest)
    total = sum(entry["train"] for entry in manifest["arms"].values())
    print(f"\n{len(manifest['arms'])} arms prepared, {total:,} training pairs written")
    print(f"manifest: {WORK / 'prepare_manifest.json'}")
    return 0


def sample_by_document(rows: list[dict], size: int, seed: int) -> list[dict]:
    """Take whole documents until ``size`` pairs are reached, so arms stay comparable."""
    groups: dict[str, list[dict]] = {}
    for row in rows:
        groups.setdefault(row.get("document_id") or id(row), []).append(row)
    keys = sorted(groups)
    random.Random(seed).shuffle(keys)
    picked: list[dict] = []
    for key in keys:
        if len(picked) >= size:
            break
        picked.extend(groups[key])
    return picked[:size]


def write_arm(manifest, language, pivot, arm, train, dev, test) -> None:
    folder = WORK / "arms" / f"{language}-{pivot}" / arm
    files = {"train.jsonl": train, "dev.jsonl": dev, "test.jsonl": test}
    counts = {}
    checksums = {}
    for name, rows in files.items():
        path = folder / name
        counts[name.split(".")[0]] = save_jsonl(path, rows)
        checksums[name] = sha256_file(path)
    manifest["arms"][f"{language}-{pivot}/{arm}"] = {
        "language": language, "pivot": pivot, "arm": arm,
        "train": counts["train"], "dev": counts["dev"], "test": counts["test"],
        "origins": sorted({row["origin"] for row in train if "origin" in row}),
        "checksums": checksums,
        # Recorded so a reader can verify the claim rather than take it on faith.
        "test_sources": sorted({row["source"] for row in test if row.get("source")}),
    }


def build_units(rows: list[dict], unit: str, window: int, seed: int) -> list[dict]:
    """Regroup sentence pairs into the training unit.

    Our rows are sentences carved out of documents, and ``document_id`` says which document
    each came from -- so the document structure can be put back. That matters because it is
    the one thing this dataset has that its rivals do not, and training on loose sentences
    throws it away.

    What the literature actually supports, which is narrower than "document level is better":

    * Concatenating consecutive pairs reliably gains about +1 BLEU on low-resource pairs,
      but Nguyen et al. (arXiv:2105.01691) show the gain is *not* discourse. Masking
      attention across the join still helps, and position, context and length diversity
      explain nearly all of it. It works as augmentation.
    * Paragraph-level fine-tuning of NLLB beat sentence-level by ~0.9 chrF++ on Karelian,
      Livvi, Ludian and Veps (NoDaLiDa 2025) -- the closest published analogue to this setup.
    * Full-document concatenation is where it breaks: one attempt failed to converge and was
      fixed by mixing document- and sentence-level data, and several papers find doc-level
      fine-tuning *worse* than sentence-level, blaming the scarcity of document-level
      parallel data. That particular objection does not apply here: 87,596 aligned documents
      is exactly the resource whose absence those papers blame.

    Hence four units rather than a winner: ``mixed`` is the combination the one failed
    convergence was fixed with, and ``paragraph`` is the setting with the best evidence.

    Rows with no document (PARME, OPUS) are grouped at random, which the same concatenation
    work found works about as well as consecutive grouping -- further evidence the effect is
    augmentation rather than context.

    Paragraphs are read from the corpus, not guessed. Each document carries a ``sep`` list
    holding the text that followed each sentence, and a separator containing a newline is a
    paragraph break in the source article. ``paragraph_id`` is built from that, so the
    paragraph unit reproduces the article's own paragraphs -- 441,836 of them across 87,756
    documents, averaging 2.48 sentences. An earlier version of this function chopped every
    document into fixed ``window``-sized chunks instead, which cut across real boundaries and
    joined the end of one paragraph to the start of the next. The window is now only the
    fallback for corpora that ship no paragraph information at all.

    Sentences are rejoined with the separator the source used, so a paragraph reads as the
    article wrote it rather than as space-joined fragments.
    """
    if unit == "sentence":
        return rows

    def join(chunk: list[dict], field: str) -> str:
        """Rejoin a run of sentences using each one's own trailing separator.

        A newline separator is kept, so a document-level unit still shows its paragraph
        breaks. An absent or empty separator means end-of-document in the source, which
        inside a concatenation can only sensibly be a space.
        """
        parts = []
        for position, row in enumerate(chunk):
            parts.append(row[field])
            if position < len(chunk) - 1:
                parts.append(row.get("sep") or " ")
        return "".join(parts).strip()

    # Paragraph grouping keys on paragraph_id where the corpus provides it; document grouping
    # always keys on the document. Anything with neither is grouped at random.
    groups: dict[str, list[dict]] = {}
    loose: list[dict] = []
    for row in rows:
        if unit == "paragraph" and row.get("paragraph_id"):
            groups.setdefault(row["paragraph_id"], []).append(row)
        elif row.get("document_id"):
            groups.setdefault(row["document_id"], []).append(row)
        else:
            loose.append(row)
    if loose:
        shuffler = random.Random(seed)
        shuffler.shuffle(loose)
        for index in range(0, len(loose), window):
            groups[f"random-{index}"] = loose[index:index + window]

    # Within a group keep the article's own order; sentence_index is the only reliable
    # ordering once rows have passed through contamination filtering and deduplication,
    # which can drop sentences from the middle of a document.
    built: list[dict] = []
    for key in sorted(groups):
        sentences = sorted(groups[key], key=lambda r: r.get("sentence_index", 0))
        # A real paragraph is already the unit; only the document unit and the windowed
        # fallback need further chunking.
        if unit == "paragraph" and all(r.get("paragraph_id") for r in sentences):
            step = len(sentences)
        else:
            step = len(sentences) if unit == "document" else window
        for start in range(0, len(sentences), step):
            chunk = sentences[start:start + step]
            if not chunk:
                continue
            built.append({"low": join(chunk, "low"), "pivot": join(chunk, "pivot"),
                          "document_id": chunk[0].get("document_id", key),
                          "paragraph_id": chunk[0].get("paragraph_id"),
                          "sentence_index": chunk[0].get("sentence_index", 0),
                          "origin": chunk[0].get("origin")})
    if unit == "mixed":
        # Both granularities in one training set, which is how the one documented
        # non-convergence of pure document-level training was repaired.
        return rows + built
    return built


def build_multi(rows: list[dict], window: int, seed: int, cap: float = 4.0,
                max_ratio: float = 3.0) -> list[dict]:
    """Every granularity at once: sentences, sliding merges, paragraphs, documents.

    The units above each pick one size. This builds all of them from the same data, which is
    what the separators make possible and what the disjoint chunking threw away:

    * Sliding rather than disjoint. ``build_units`` cut a paragraph into consecutive
      non-overlapping groups, so a 6-sentence paragraph at window 3 produced 2 examples.
      Sliding by one produces 4 at width 3 and 5 at width 2, and every sentence appears in
      several positions. Position diversity is precisely what the concatenation work found
      the gain comes from, so sliding should extract more of it than chunking.
    * Merges stay inside a paragraph. A window that straddles a paragraph break joins text
      the article kept apart, which is noise rather than augmentation.
    * Alignment is not always one-to-one. One source sentence can correspond to two target
      sentences -- visible in the corpus, where a single Alemannic sentence maps to an
      English pair -- so a merged unit can be better aligned than its parts. ``max_ratio``
      drops merges whose two sides differ in length by more than that factor, which is the
      signature of a bad alignment rather than a legitimate expansion.

    ``cap`` bounds the result at a multiple of the sentence count, because the full cross
    product of widths would multiply training time by more than it adds. When the cap binds,
    the *built* units are subsampled and every original sentence is kept, so the sentence
    baseline is never degraded in order to add augmentation.
    """
    sentences = [row for row in rows if row.get("low")]
    groups: dict[str, list[dict]] = {}
    for row in sentences:
        key = row.get("paragraph_id") or row.get("document_id")
        if key:
            groups.setdefault(key, []).append(row)

    def join(chunk, field):
        parts = []
        for position, row in enumerate(chunk):
            parts.append(row[field])
            if position < len(chunk) - 1:
                parts.append(row.get("sep") or " ")
        return "".join(parts).strip()

    built: list[dict] = []
    for key in sorted(groups):
        ordered = sorted(groups[key], key=lambda r: r.get("sentence_index", 0))
        for width in range(2, max(window, 2) + 1):
            for start in range(0, len(ordered) - width + 1):
                chunk = ordered[start:start + width]
                low, pivot = join(chunk, "low"), join(chunk, "pivot")
                if not low or not pivot:
                    continue
                ratio = len(pivot) / max(len(low), 1)
                if ratio > max_ratio or ratio < 1 / max_ratio:
                    continue
                built.append({"low": low, "pivot": pivot,
                              "document_id": chunk[0].get("document_id"),
                              "paragraph_id": chunk[0].get("paragraph_id"),
                              "sentence_index": chunk[0].get("sentence_index", 0),
                              "origin": chunk[0].get("origin")})
    # Whole paragraphs and whole documents on top, for the widths sliding does not reach.
    for unit in ("paragraph", "document"):
        built.extend(build_units(sentences, unit, window, seed))

    # One dedup pass over everything, seeded with the original sentences so a single-sentence
    # paragraph does not re-enter as a copy of its own sentence, and one ratio filter over
    # everything so the paragraph and document units are held to the same alignment check as
    # the sliding merges rather than bypassing it.
    seen = {(row["low"], row["pivot"]) for row in sentences}
    unique = []
    for row in built:
        key = (row["low"], row["pivot"])
        if key in seen:
            continue
        ratio = len(row["pivot"]) / max(len(row["low"]), 1)
        if ratio > max_ratio or ratio < 1 / max_ratio:
            continue
        seen.add(key)
        unique.append(row)

    budget = int(cap * len(sentences)) - len(sentences)
    if budget < 0:
        budget = 0
    if len(unique) > budget:
        random.Random(seed).shuffle(unique)
        unique = unique[:budget]
    return sentences + unique


def variant_suffix(args, *, decoding: bool = True) -> str:
    """A path segment naming whatever this run changed from the baseline recipe.

    Empty when nothing differs, so the runs already on disk keep their paths and stay
    directly comparable. Anything else gets its own directory named after the change --
    "ls0.1", "sel-chrf", "lp0.6" -- which means a sweep cannot quietly overwrite the result
    it is being compared against. That is not hypothetical: without it, a length-penalty
    sweep writes every value to the same scores.json and only the last one survives.

    ``decoding`` is False when building a *training* path: the length penalty is a decoding
    choice, so a model trained once can be scored at several penalties and must not be
    retrained for each.
    """
    parts = []
    if args.unit != "sentence":
        parts.append(f"unit_{args.unit}")
    if getattr(args, "label_smoothing", 0.0):
        parts.append(f"ls{args.label_smoothing:g}")
    if getattr(args, "dropout", None) is not None:
        parts.append(f"do{args.dropout:g}")
    if getattr(args, "select_on", "loss") != "loss":
        parts.append(f"sel-{args.select_on}")
    if getattr(args, "patience", 0):
        parts.append(f"pat{args.patience}")
    if abs(getattr(args, "epochs", 3) - 3) > 1e-9:
        parts.append(f"ep{args.epochs:g}")
    if abs(getattr(args, "learning_rate", 3e-5) - 3e-5) > 1e-12:
        parts.append(f"lr{args.learning_rate:g}")
    if decoding and abs(getattr(args, "length_penalty", 1.0) - 1.0) > 1e-9:
        parts.append(f"lp{args.length_penalty:g}")
    return "/".join(parts)


def stage_train(args) -> int:
    """Fine-tune one arm. One arm, one GPU, one process -- kept deliberately dumb."""
    manifest = load_json(WORK / "prepare_manifest.json")
    key = f"{args.language}-{args.pivot}/{args.arm}"
    if key not in manifest["arms"]:
        raise SystemExit(f"{key} was not prepared; run the prepare stage first")
    entry = manifest["arms"][key]
    folder = WORK / "arms" / f"{args.language}-{args.pivot}" / args.arm
    for name, expected in entry["checksums"].items():
        if sha256_file(folder / name) != expected:
            raise SystemExit(f"{name} changed since prepare; re-run prepare")

    model_spec = MODELS[args.model]
    run = WORK / "runs" / f"{args.language}-{args.pivot}" / args.arm / args.model / args.direction
    suffix = variant_suffix(args, decoding=False)
    if suffix:
        run = run / suffix
    run.mkdir(parents=True, exist_ok=True)
    if (run / "training_complete.json").exists() and not args.refresh:
        print(f"already trained: {run}")
        return 0
    if not model_spec["train"]:
        save_json(run / "training_complete.json",
                  {"skipped": "zero-shot arm has nothing to train"})
        return 0

    for name in ("HF_HUB_DISABLE_TELEMETRY", "DO_NOT_TRACK"):
        os.environ[name] = "1"
    os.environ["WANDB_DISABLED"] = "true"
    os.environ["TOKENIZERS_PARALLELISM"] = "false"

    try:
        import torch
        from transformers import (AutoModelForSeq2SeqLM, AutoTokenizer,
                                  DataCollatorForSeq2Seq, Seq2SeqTrainer,
                                  Seq2SeqTrainingArguments, set_seed)
    except ModuleNotFoundError as error:
        raise SystemExit(
            f"{error.name} is not installed here. plan/prepare/report run on any machine, but "
            f"train/evaluate need torch and transformers on a GPU host.") from None

    # Pin the GPU explicitly. Two people share this machine and an unpinned job can land on a
    # card someone else is using.
    if not torch.cuda.is_available() or not os.environ.get("CUDA_VISIBLE_DEVICES"):
        raise SystemExit("set CUDA_VISIBLE_DEVICES to one GPU before training")
    set_seed(args.seed)

    base = model_spec["base"] or marian_base(args.language, args.pivot, args.direction)
    if base is None:
        raise SystemExit(f"no {args.model} checkpoint exists for {args.language}-"
                         f"{args.pivot}/{args.direction}; skipping is correct")
    if model_spec["kind"] == "causal_lora":
        return train_causal_lora(args, entry, folder, run, base, started=time.monotonic())

    tokenizer = AutoTokenizer.from_pretrained(base)
    model = AutoModelForSeq2SeqLM.from_pretrained(base, dtype=torch.bfloat16)
    # Marian is bilingual by construction: no language tokens to set, nothing to add.
    tags = (language_tags(tokenizer, model, args.language, args.pivot)
            if model_spec.get("tagged") else
            {"low": None, "pivot": None, "added": False})
    def encode(rows, direction):
        """Tokenize one direction. The language tags carry the direction, not the weights.

        NLLB prepends the source tag to the input and starts the target with the target tag,
        so a model trained on both directions learns which way to translate from the tags
        alone. That is what makes ``--direction both`` a single model rather than two.
        """
        if model_spec.get("tagged"):
            source_tag, target_tag = ((tags["low"], tags["pivot"]) if direction == "to_pivot"
                                      else (tags["pivot"], tags["low"]))
            tokenizer.src_lang, tokenizer.tgt_lang = source_tag, target_tag
        sources = [r["low"] if direction == "to_pivot" else r["pivot"] for r in rows]
        targets = [r["pivot"] if direction == "to_pivot" else r["low"] for r in rows]
        batch = tokenizer(sources, text_target=targets, truncation=True,
                          max_length=args.max_length)
        return [{"input_ids": batch["input_ids"][i],
                 "attention_mask": batch["attention_mask"][i],
                 "labels": batch["labels"][i]} for i in range(len(sources))]

    # "both" sees every pair twice, once in each direction, so it trains on exactly the same
    # sentences as the two single-direction models combined -- the comparison is between one
    # model that learned both ways and two that each learned one.
    directions = ["to_pivot", "from_pivot"] if args.direction == "both" else [args.direction]

    def encode_all(rows):
        encoded = []
        for direction in directions:
            encoded.extend(encode(rows, direction))
        return encoded

    select_on_chrf = args.select_on == "chrf"
    # Dropout is raised through the config rather than the training arguments, because it is
    # a property of the architecture and not of the optimiser. Reported low-resource settings
    # run to 0.3 against the 0.1 these checkpoints ship with; left alone unless asked.
    if args.dropout is not None:
        for attribute in ("dropout", "activation_dropout", "attention_dropout"):
            # attention_dropout is set for completeness but the low-resource study found it
            # unhelpful, so it is raised only to the same value rather than beyond it.
            if hasattr(model.config, attribute):
                setattr(model.config, attribute, args.dropout)
        print(f"dropout set to {args.dropout}", flush=True)

    loaded = load_jsonl(folder / "train.jsonl")
    raw_train = (build_multi(loaded, args.window, args.seed, cap=args.multi_cap)
                 if args.unit == "multi"
                 else build_units(loaded, args.unit, args.window, args.seed))
    # Dev stays at sentence level: it selects the checkpoint, and the test set it stands in
    # for is scored sentence by sentence whatever the training unit was.
    train_rows = encode_all(raw_train)
    dev_rows = encode_all(load_jsonl(folder / "dev.jsonl")) if entry["dev"] else None
    print(f"training unit {args.unit}: {entry['train']:,} sentence pairs -> "
          f"{len(raw_train):,} examples", flush=True)

    arguments = Seq2SeqTrainingArguments(
        output_dir=str(run / "checkpoints"),
        num_train_epochs=args.epochs,
        learning_rate=args.learning_rate,
        per_device_train_batch_size=args.batch_size,
        gradient_accumulation_steps=args.accumulation,
        # Label smoothing is off by default, and when it is on the collator below supplies
        # decoder_input_ids itself. Trainer implements smoothing by popping ``labels`` out of
        # the batch and computing the loss itself, which leaves an encoder-decoder model with
        # neither labels to shift nor a decoder input of its own -- and in transformers 5
        # neither DataCollatorForSeq2Seq variant supplies one, so the decoder raises. The
        # error names decoder_inputs_embeds and is misleading: that guard is an XOR and fires
        # just as readily when both inputs are missing. Building the decoder input in the
        # collator removes the dependency rather than working around it.
        label_smoothing_factor=args.label_smoothing,
        warmup_ratio=0.05, weight_decay=0.01,
        bf16=True, logging_steps=50, save_total_limit=1, report_to=[], seed=args.seed,
        # Checkpoint selection uses dev only. The test split must never influence a weight or
        # a checkpoint choice, or every number downstream is worthless.
        eval_strategy="steps" if dev_rows else "no", eval_steps=args.eval_steps,
        save_strategy="steps" if dev_rows else "epoch", save_steps=args.eval_steps,
        predict_with_generate=select_on_chrf,
        generation_num_beams=args.dev_beams, generation_max_length=args.max_length,
        load_best_model_at_end=bool(dev_rows),
        # Selecting on dev loss is the convenient choice and the literature's consistent
        # advice is against it: loss and generation quality diverge, with reported cases of
        # perplexity bottoming out at 30k steps while dev BLEU kept climbing to 70k. With
        # --select-on chrf the dev set is generated at each evaluation and the checkpoint is
        # chosen on chrF++ instead. Kept opt-in because every run scored so far used loss.
        metric_for_best_model="eval_chrf2pp" if select_on_chrf else "eval_loss",
        greater_is_better=bool(select_on_chrf))
    # The collator pads, and passing ``model`` lets it build decoder_input_ids, which is
    # what makes label smoothing usable: with smoothing on, Trainer removes ``labels`` before
    # the forward pass, so the decoder input has to already be in the batch.
    collator = DataCollatorForSeq2Seq(tokenizer, model=model if args.label_smoothing else None)

    def compute_metrics(prediction):
        """chrF++ on the dev split, for checkpoint selection only.

        -100 is the label padding Trainer uses to mask loss; it is not a token id, so it has
        to be restored to the pad id before decoding or the tokenizer raises.
        """
        import numpy as np
        predictions, labels = prediction.predictions, prediction.label_ids
        if isinstance(predictions, tuple):
            predictions = predictions[0]
        predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id)
        labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
        hypotheses = tokenizer.batch_decode(predictions, skip_special_tokens=True)
        references = tokenizer.batch_decode(labels, skip_special_tokens=True)
        import sacrebleu
        return {"chrf2pp": sacrebleu.CHRF(word_order=2).corpus_score(
            hypotheses, [references]).score}

    callbacks = []
    if args.patience and dev_rows:
        from transformers import EarlyStoppingCallback
        callbacks.append(EarlyStoppingCallback(early_stopping_patience=args.patience))
    trainer = Seq2SeqTrainer(model=model, args=arguments, train_dataset=train_rows,
                             eval_dataset=dev_rows, data_collator=collator,
                             compute_metrics=compute_metrics if select_on_chrf else None,
                             callbacks=callbacks or None)
    started = time.monotonic()
    result = trainer.train()
    trainer.save_model(str(run / "model"))
    tokenizer.save_pretrained(str(run / "model"))
    save_json(run / "training_complete.json", {
        "base": base, "model": args.model, "direction": args.direction,
        "trained_directions": directions, "tags": tags,
        "unit": args.unit, "window": args.window, "examples": len(raw_train),
        "train_pairs": entry["train"], "dev_pairs": entry["dev"],
        "epochs": args.epochs, "learning_rate": args.learning_rate, "seed": args.seed,
        # The recipe, recorded per run. Without this a run cannot be compared with another
        # one, and the whole point of keeping the old defaults is comparability.
        "label_smoothing": args.label_smoothing, "dropout": args.dropout,
        "select_on": args.select_on, "patience": args.patience,
        "batch_size": args.batch_size, "accumulation": args.accumulation,
        "seconds": round(time.monotonic() - started, 1),
        "train_loss": result.training_loss,
        "gpu": torch.cuda.get_device_name(0),
        "cuda_visible_devices": os.environ["CUDA_VISIBLE_DEVICES"]})
    print(f"trained {key} / {args.model} / {args.direction} in "
          f"{(time.monotonic() - started) / 60:.1f} min -> {run / 'model'}")
    return 0


LANGUAGE_NAMES = {"als": "Alemannic", "bar": "Bavarian", "frr": "North Frisian",
                  "glk": "Gilaki", "mzn": "Mazanderani",
                  "en": "English", "de": "German", "fa": "Persian"}


def lora_prompt(language: str, pivot: str, direction: str, source: str) -> str:
    """The instruction an LLM arm is trained and evaluated on.

    Identical at training and generation time except for the answer, which is why the
    trailing newline matters: the model is taught that the translation begins right there.
    """
    low, high = LANGUAGE_NAMES[language], LANGUAGE_NAMES[pivot]
    src, tgt = (low, high) if direction == "to_pivot" else (high, low)
    return f"Translate the following {src} sentence into {tgt}.\n{src}: {source}\n{tgt}:"


def train_causal_lora(args, entry, folder, run, base, started) -> int:
    """Fine-tune a decoder-only LLM with LoRA, the Esperanto paper's fourth system class.

    The loss is masked to the answer: everything up to and including the final "<Target>:"
    is prompt, and training the model to reproduce its own instruction would waste capacity
    and bias the comparison against the encoder-decoder arms, which never see a prompt.
    """
    import torch
    from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
                              set_seed)
    try:
        from peft import LoraConfig, get_peft_model
    except ModuleNotFoundError:
        raise SystemExit("peft is not installed; pip install peft inside the container")

    set_seed(args.seed)
    tokenizer = AutoTokenizer.from_pretrained(base)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    model = AutoModelForCausalLM.from_pretrained(base, dtype=torch.bfloat16)
    model = get_peft_model(model, LoraConfig(
        r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]))
    model.print_trainable_parameters()

    directions = ["to_pivot", "from_pivot"] if args.direction == "both" else [args.direction]

    def encode(rows):
        examples = []
        for direction in directions:
            for row in rows:
                source = row["low"] if direction == "to_pivot" else row["pivot"]
                target = row["pivot"] if direction == "to_pivot" else row["low"]
                prompt = lora_prompt(args.language, args.pivot, direction, source)
                prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
                answer_ids = tokenizer(" " + target, add_special_tokens=False)["input_ids"]
                answer_ids = answer_ids + [tokenizer.eos_token_id]
                ids = (prompt_ids + answer_ids)[:args.max_length]
                labels = ([-100] * len(prompt_ids) + answer_ids)[:args.max_length]
                if len(labels) > len(ids):
                    labels = labels[:len(ids)]
                examples.append({"input_ids": ids, "labels": labels})
        return examples

    def collate(batch):
        width = max(len(item["input_ids"]) for item in batch)
        pad = tokenizer.pad_token_id
        return {
            "input_ids": torch.tensor([item["input_ids"] + [pad] * (width - len(item["input_ids"]))
                                       for item in batch]),
            "attention_mask": torch.tensor([[1] * len(item["input_ids"])
                                            + [0] * (width - len(item["input_ids"]))
                                            for item in batch]),
            "labels": torch.tensor([item["labels"] + [-100] * (width - len(item["labels"]))
                                    for item in batch]),
        }

    train_rows = encode(load_jsonl(folder / "train.jsonl"))
    arguments = TrainingArguments(
        output_dir=str(run / "checkpoints"), num_train_epochs=args.epochs,
        learning_rate=args.lora_learning_rate,
        per_device_train_batch_size=max(args.batch_size // 4, 1),
        gradient_accumulation_steps=args.accumulation * 2,
        warmup_ratio=0.05, weight_decay=0.01, bf16=True, logging_steps=50,
        save_strategy="no", report_to=[], seed=args.seed)
    trainer = Trainer(model=model, args=arguments, train_dataset=train_rows,
                      data_collator=collate)
    result = trainer.train()
    model.save_pretrained(str(run / "model"))
    tokenizer.save_pretrained(str(run / "model"))
    save_json(run / "training_complete.json", {
        "base": base, "model": args.model, "direction": args.direction,
        "trained_directions": directions, "adapter": "lora",
        "train_pairs": entry["train"], "epochs": args.epochs,
        "learning_rate": args.lora_learning_rate, "seed": args.seed,
        "seconds": round(time.monotonic() - started, 1),
        "train_loss": result.training_loss,
        "gpu": torch.cuda.get_device_name(0),
        "cuda_visible_devices": os.environ["CUDA_VISIBLE_DEVICES"]})
    print(f"trained {run} in {(time.monotonic() - started) / 60:.1f} min")
    return 0


def generate_causal_lora(args, source_dir, inputs, scoring) -> list[str]:
    """Greedy decoding from the LoRA arm, with the prompt stripped back off."""
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from peft import PeftModel

    adapter = Path(source_dir)
    config = load_json(adapter.parent / "training_complete.json")
    tokenizer = AutoTokenizer.from_pretrained(str(adapter))
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    tokenizer.padding_side = "left"      # required for batched decoder-only generation
    model = AutoModelForCausalLM.from_pretrained(config["base"], dtype=torch.bfloat16)
    model = PeftModel.from_pretrained(model, str(adapter)).eval()
    if torch.cuda.is_available():
        model = model.cuda()

    batch_size = max(args.generation_batch_size // 3, 1)
    hypotheses: list[str] = []
    for start in range(0, len(inputs), batch_size):
        chunk = inputs[start:start + batch_size]
        prompts = [lora_prompt(args.language, args.pivot, scoring, text) for text in chunk]
        encoded = tokenizer(prompts, return_tensors="pt", padding=True, truncation=True,
                            max_length=args.max_length).to(model.device)
        with torch.no_grad():
            generated = model.generate(**encoded, max_new_tokens=256, do_sample=False,
                                       pad_token_id=tokenizer.pad_token_id)
        # Only the continuation is the translation; the prompt is echoed back by design.
        for index in range(len(chunk)):
            new_tokens = generated[index][encoded["input_ids"].shape[1]:]
            text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
            hypotheses.append(text.split("\n")[0].strip())
        print(f"  generated {len(hypotheses)}/{len(inputs)}", end="\r", flush=True)
    return hypotheses


# Which OPUS-MT checkpoint the compact arm starts from. Marian is per-pair and Helsinki
# publishes no Persian pair at all, so the Iranian languages start from the multilingual
# mul-en/en-mul models and the Germanic ones from the German pair, which is the closest
# relative that exists. Verified against the Hub: opus-mt-de-en, opus-mt-en-de,
# opus-mt-mul-en and opus-mt-en-mul exist; opus-mt-fa-en and opus-mt-en-fa do not.
MARIAN_BASES = {
    "de": ("Helsinki-NLP/opus-mt-de-en", "Helsinki-NLP/opus-mt-en-de"),
    "mul": ("Helsinki-NLP/opus-mt-mul-en", "Helsinki-NLP/opus-mt-en-mul"),
}
MARIAN_FAMILY = {"als": "de", "bar": "de", "frr": "de", "glk": "mul", "mzn": "mul"}


def marian_base(language: str, pivot: str, direction: str) -> str | None:
    """The OPUS-MT checkpoint for this pair, or None when Helsinki publishes nothing usable.

    Only the English pivot is supported. A German pivot would need a German-to-German model
    for bar->de, and a Persian pivot a Persian-to-Persian one for glk->fa; neither is a real
    model, and substituting a mismatched pair would quietly measure the wrong thing. Those
    combinations are skipped rather than faked.
    """
    if pivot != "en":
        return None
    into_english, out_of_english = MARIAN_BASES[MARIAN_FAMILY[language]]
    return into_english if direction == "to_pivot" else out_of_english


def language_tags(tokenizer, model, language: str, pivot: str) -> dict:
    """Make sure both sides have a real NLLB language tag, adding one if NLLB lacks it.

    NLLB covers the pivots but not necessarily the low-resource side. Where the tag is
    missing it is added and its embedding seeded from the configured donor, which is what
    PARME does for its eight languages. Where NLLB already has the tag, it is used as-is --
    adding a duplicate would throw away whatever the pretrained model already knows.
    """
    import torch
    spec = LANGUAGES[language]
    pivot_tag = spec["pivots"][pivot]
    vocabulary = tokenizer.convert_tokens_to_ids
    if vocabulary(pivot_tag) == tokenizer.unk_token_id:
        raise SystemExit(f"{pivot_tag} missing from the tokenizer; wrong base model?")

    wanted, donor = spec["tag"], spec["donor"]
    existing = vocabulary(wanted)
    if existing != tokenizer.unk_token_id:
        return {"low": wanted, "pivot": pivot_tag, "added": False,
                "low_id": existing, "pivot_id": vocabulary(pivot_tag)}

    before = {tag: vocabulary(tag) for tag in (pivot_tag, donor, "eng_Latn")}
    # add_tokens(..., special_tokens=True) appends, and unlike add_special_tokens it has kept
    # the same signature across transformers 4 and 5 -- v5 dropped the
    # replace_additional_special_tokens argument that stopped the older call from wiping
    # NLLB's existing language tags. The assertion below is what actually guarantees they
    # survived, whichever path added the token.
    tokenizer.add_tokens([wanted], special_tokens=True)
    for tag, identifier in before.items():
        if vocabulary(tag) != identifier:
            raise SystemExit(f"adding {wanted} moved the existing tag {tag}")
    new_id, donor_id = vocabulary(wanted), vocabulary(donor)
    if new_id in (tokenizer.unk_token_id, donor_id):
        raise SystemExit(f"{wanted} did not get a distinct id")
    model.resize_token_embeddings(max(len(tokenizer),
                                      model.get_input_embeddings().num_embeddings))
    with torch.no_grad():
        embeddings = model.get_input_embeddings()
        embeddings.weight[new_id].copy_(embeddings.weight[donor_id])
        output = model.get_output_embeddings()
        if output is not None and output.weight.data_ptr() != embeddings.weight.data_ptr():
            output.weight[new_id].copy_(output.weight[donor_id])
    return {"low": wanted, "pivot": pivot_tag, "added": True, "seeded_from": donor,
            "low_id": new_id, "pivot_id": vocabulary(pivot_tag)}


def stage_evaluate(args) -> int:
    """Generate on the test split and score against the human references."""
    try:
        import torch
        from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
    except ModuleNotFoundError as error:
        raise SystemExit(
            f"{error.name} is not installed here. plan/prepare/report run on any machine, but "
            f"train/evaluate need torch and transformers on a GPU host.") from None

    # A model trained with --direction both translates both ways, so it is scored twice and
    # each score lands in its own folder beneath the one model. --eval-direction says which
    # way to score; for a single-direction model it is the direction it was trained on.
    # The trained model lives under the training variant, built exactly as stage_train built
    # it. The scores live one level deeper, under the decoding variant, so a single trained
    # model can be scored at several length penalties without retraining and without one
    # scoring overwriting another.
    trained = WORK / "runs" / f"{args.language}-{args.pivot}" / args.arm / args.model / args.direction
    training_suffix = variant_suffix(args, decoding=False)
    if training_suffix:
        trained = trained / training_suffix
    scoring = args.eval_direction or (args.direction if args.direction != "both"
                                      else "to_pivot")
    run = trained / scoring if args.direction == "both" else trained
    decoding_suffix = variant_suffix(args, decoding=True)
    decoding_only = decoding_suffix[len(training_suffix):].strip("/")
    if decoding_only:
        run = run / decoding_only
    folder = WORK / "arms" / f"{args.language}-{args.pivot}" / args.arm
    if (run / "scores.json").exists() and not args.refresh:
        print(f"already evaluated: {run / 'scores.json'}")
        return 0
    spec = MODELS[args.model]
    source = str(trained / "model") if spec["train"] else (
        spec["base"] or marian_base(args.language, args.pivot, scoring))
    if spec["train"] and not (trained / "model").exists():
        raise SystemExit(f"no trained model at {trained / 'model'}; train first")

    rows = load_jsonl(folder / "test.jsonl")
    inputs = [r["low"] if scoring == "to_pivot" else r["pivot"] for r in rows]
    references = [r["pivot"] if scoring == "to_pivot" else r["low"] for r in rows]

    if spec["kind"] == "causal_lora":
        hypotheses = generate_causal_lora(args, source, inputs, scoring)
    else:
        tokenizer = AutoTokenizer.from_pretrained(source)
        model = AutoModelForSeq2SeqLM.from_pretrained(source, dtype=torch.bfloat16).eval()
        if torch.cuda.is_available():
            model = model.cuda()
        forced = None
        if spec.get("tagged"):
            tags = language_tags(tokenizer, model, args.language, args.pivot)
            source_tag, target_tag = ((tags["low"], tags["pivot"]) if scoring == "to_pivot"
                                      else (tags["pivot"], tags["low"]))
            tokenizer.src_lang = source_tag
            # Forcing the target tag is what makes a tagged model translate the right way.
            # Marian has no such token, and passing one would corrupt its first position.
            forced = tokenizer.convert_tokens_to_ids(target_tag)
        hypotheses = []
        for start in range(0, len(inputs), args.generation_batch_size):
            chunk = inputs[start:start + args.generation_batch_size]
            encoded = tokenizer(chunk, return_tensors="pt", padding=True, truncation=True,
                                max_length=args.max_length).to(model.device)
            with torch.no_grad():
                generated = model.generate(**encoded, forced_bos_token_id=forced,
                                           num_beams=args.beams,
                                           length_penalty=args.length_penalty,
                                           max_new_tokens=256)
            hypotheses.extend(tokenizer.batch_decode(generated, skip_special_tokens=True))
            print(f"  generated {len(hypotheses)}/{len(inputs)}", end="\r", flush=True)

    scores = score(hypotheses, references)
    # The target language of the scored direction: to_pivot generates the pivot, from_pivot
    # generates the low-resource language. COMET is only meaningful for the former.
    scored_target = args.pivot if scoring == "to_pivot" else args.language
    scores["comet22"] = comet_score(inputs, hypotheses, references, scored_target)
    # Also score each test source on its own. The test set is a union of several benchmarks,
    # and the one comparison that has a published rival -- PARME's -- is only valid against
    # PARME's own split. An aggregate over four benchmarks cannot be set beside their number.
    by_source: dict[str, dict] = {}
    for name in sorted({row["source"] for row in rows if row.get("source")}):
        picked = [(h, r) for h, r, row in zip(hypotheses, references, rows)
                  if row.get("source") == name]
        if len(picked) >= 50:
            by_source[name] = {"pairs": len(picked),
                               **score([h for h, _ in picked], [r for _, r in picked])}
    save_jsonl(run / "predictions.jsonl",
               [{"input": i, "hypothesis": h, "reference": r, "source": row.get("source")}
                for i, h, r, row in zip(inputs, hypotheses, references, rows)])
    save_json(run / "scores.json", {
        "language": args.language, "pivot": args.pivot, "arm": args.arm,
        "model": args.model, "direction": scoring, "trained_on": args.direction,
        "unit": args.unit,
        "beams": args.beams, "length_penalty": args.length_penalty,
        "model_source": source,
        "test_pairs": len(rows),
        "test_sources": sorted({row["source"] for row in rows if row.get("source")}),
        "by_test_source": by_source,
        **scores})
    for name, entry in by_source.items():
        print(f"    {name:18s} n={entry['pairs']:5d}  chrF++ {entry['chrf2pp']:6.2f}  "
              f"chrF2 {entry['chrf2']:6.2f}  BLEU {entry['bleu']:6.2f}")
    comet = f"  COMET {scores['comet22']:.4f}" if scores.get("comet22") else ""
    print(f"\n{args.language}-{args.pivot} {args.arm} {args.model} "
          f"{args.direction}->{scoring}: "
          f"chrF++ {scores['chrf2pp']:.2f}  chrF2 {scores['chrf2']:.2f}  "
          f"BLEU {scores['bleu']:.2f}  TER {scores['ter']:.2f}  "
          f"len {scores['length_ratio']:.3f}{comet}  (n={len(rows)})")
    return 0


def stage_rescore(args) -> int:
    """Recompute every metric for finished runs from their saved predictions.

    Two jobs, one pass, and neither needs a GPU or a single regenerated translation. Any
    metric added after a run finished -- TER and the length ratio were -- is filled in for
    every existing run, so a new metric does not mean re-running the sweep. And COMET-22 is
    added for into-English runs.

    COMET is here rather than in evaluate on purpose: unbabel-comet brings its own
    pytorch-lightning stack, and installing that into the container that is mid-sweep risks
    breaking the training environment for the sake of an additional metric. Running it
    afterwards from a separate environment touches nothing.

    COMET is computed only where the generated side is English; the rest get an explicit
    null, so a missing COMET never reads as a zero.
    """
    runs = sorted(WORK.glob("runs/**/scores.json"))
    if not runs:
        raise SystemExit("no scored runs")
    added = skipped = 0
    for path in runs:
        scores = load_json(path)
        predictions = path.parent / "predictions.jsonl"
        if not predictions.exists():
            skipped += 1
            continue
        rows = [json.loads(line) for line in
                predictions.read_text(encoding="utf-8").splitlines() if line.strip()]
        if not rows:
            skipped += 1
            continue
        hypotheses = [r["hypothesis"] for r in rows]
        references = [r["reference"] for r in rows]
        fresh = score(hypotheses, references)
        # The headline metrics are recomputed and compared rather than trusted. These runs
        # were scored by an earlier copy of this file, and a silent disagreement would mean
        # the saved numbers and the ones in the report came from different code.
        for metric in ("chrf2pp", "chrf2", "bleu"):
            previous = scores.get(metric)
            if previous is not None and abs(previous - fresh[metric]) > 0.01:
                raise SystemExit(f"{path}: {metric} was {previous:.4f}, recomputes to "
                                 f"{fresh[metric]:.4f} -- the saved scores and this code "
                                 f"disagree")
        scores.update(fresh)
        target = (scores["pivot"] if scores["direction"] == "to_pivot"
                  else scores["language"])
        if target == "en" and (scores.get("comet22") is None or args.force_comet):
            value = comet_score([r["input"] for r in rows], hypotheses, references, "en")
            if value is None and not args.allow_missing_comet:
                raise SystemExit("COMET could not be loaded; install unbabel-comet or pass "
                                 "--allow-missing-comet to rescore without it")
            scores["comet22"] = value
        elif target != "en":
            scores["comet22"] = None
        save_json(path, scores)
        added += 1
        label = "/".join(path.parent.parts[-4:])
        comet = f"  COMET {scores['comet22']:.4f}" if scores.get("comet22") else ""
        print(f"  {label:54s} chrF++ {scores['chrf2pp']:6.2f}  TER {scores['ter']:6.2f}  "
              f"len {scores['length_ratio']:.3f}{comet}", flush=True)
    print(f"\nrescored {added} runs, {skipped} skipped")
    return 0


def score(hypotheses: list[str], references: list[str], sources=None) -> dict:
    """chrF++, chrF2, BLEU, TER, a literalness diagnostic, and COMET where it is valid.

    chrF++ stays the headline: it is the most reliable surface metric on morphologically
    rich, low-resource targets. Plain chrF2 is computed because PARME reports it, and a
    comparison against a published number has to use that number's metric. TER is added
    because Her & Kruschwitz report BLEU/chrF/TER for Bavarian, so their row and ours line up
    on all three.

    The reason for not stopping at surface metrics is specific rather than hopeful. All four
    of those count n-gram and character overlap with one reference, so a translation that
    reorders into idiomatic English is penalised against one that preserves source word
    order -- even when both are correct. That matters here because the Bavarian test sets are
    human translations *of English originals*, so scoring into English rewards whatever
    reconstructs the original wording, which is a different skill from translating well. On
    the 5,621 sentences both corpora share, ours renders "1 + 2 = 3 vasteht a jeda fast
    iabaroi" as "Almost anyone anywhere in the world understands 1 + 2 = 3" while the rival
    keeps the Bavarian order; the surface metrics prefer the second regardless of which is
    better English.

    COMET-22 is a learned metric over source, hypothesis and reference, and is the WMT
    primary metric precisely because it tolerates legitimate paraphrase. It is computed
    **only when the target is English**: its XLM-R encoder has no meaningful coverage of
    Bavarian, Gilaki or Alemannic, so a COMET score for en->glk would be a number without a
    meaning. Returning None there is the honest option, and it keeps anyone from averaging
    the two directions together.
    """
    import sacrebleu
    scores = {
        "chrf2pp": sacrebleu.CHRF(word_order=2).corpus_score(hypotheses, [references]).score,
        "chrf2": sacrebleu.CHRF(word_order=0).corpus_score(hypotheses, [references]).score,
        "bleu": sacrebleu.BLEU().corpus_score(hypotheses, [references]).score,
        "ter": sacrebleu.TER().corpus_score(hypotheses, [references]).score,
    }
    # How closely the output tracks the reference's length. A system that reorders and
    # compresses reads differently from one that renders word by word, and this separates
    # "wrong" from "differently worded" when chrF++ cannot.
    hypothesis_length = sum(len(text) for text in hypotheses) or 1
    reference_length = sum(len(text) for text in references) or 1
    scores["length_ratio"] = round(hypothesis_length / reference_length, 4)
    return scores


def comet_score(sources: list[str], hypotheses: list[str], references: list[str],
                target_language: str) -> float | None:
    """COMET-22 for into-English output only; None otherwise or if COMET is unavailable.

    Loading the model costs about 2.3 GB and a minute, so it is loaded once per process and
    cached. A missing dependency returns None rather than failing the run: COMET is an
    addition to the surface metrics, not a replacement, and an evaluation that already
    produced chrF++ should not be thrown away because a neural metric could not load.
    """
    if target_language != "en":
        return None
    global _COMET
    try:
        if _COMET is None:
            from comet import download_model, load_from_checkpoint
            _COMET = load_from_checkpoint(download_model("Unbabel/wmt22-comet-da"))
    except Exception as error:   # noqa: BLE001 - optional metric, never fatal
        print(f"  [comet unavailable: {type(error).__name__}: {error}]", flush=True)
        _COMET = False
    if not _COMET:
        return None
    data = [{"src": source, "mt": hypothesis, "ref": reference}
            for source, hypothesis, reference in zip(sources, hypotheses, references)]
    output = _COMET.predict(data, batch_size=32, gpus=1, progress_bar=False)
    return round(float(output.system_score), 4)


_COMET = None


def paired_test(baseline: list[str], system: list[str], references: list[str],
                samples: int = 1000) -> dict:
    """Paired bootstrap of system against baseline on the same references.

    With 197 test sentences for Frisian, a two-point gap can easily be noise. Reporting a
    p-value is the difference between a result and an anecdote.
    """
    import sacrebleu
    from sacrebleu.significance import PairedTest
    test = PairedTest([("baseline", baseline), ("system", system)],
                      {"chrf2pp": sacrebleu.CHRF(word_order=2),
                       "bleu": sacrebleu.BLEU()},
                      references=[references], test_type="bs", n_samples=samples)
    _, results = test()
    out = {}
    for metric, scored in results.items():
        if metric == "System":
            continue
        base_result, system_result = scored
        out[metric] = {"baseline": base_result.score, "system": system_result.score,
                       "delta": system_result.score - base_result.score,
                       "p_value": system_result.p_value,
                       "baseline_ci": base_result.ci, "system_ci": system_result.ci}
    return out


def stage_report(args) -> int:
    """Collect every finished arm, add the significance tests, print one table."""
    rows = []
    for path in sorted((WORK / "runs").rglob("scores.json")):
        rows.append(load_json(path))
    if not rows:
        raise SystemExit("no evaluated runs yet")

    # Key predictions off the scores file beside them rather than off the path. A
    # single-direction run lives at lang-pivot/arm/model/direction, a bidirectional one one
    # level deeper at .../both/direction, and the comparison has to pair like with like:
    # a bidirectional system is only a fair rival to another bidirectional system.
    predictions: dict[tuple, list[dict]] = {}
    for path in sorted((WORK / "runs").rglob("predictions.jsonl")):
        beside = path.parent / "scores.json"
        if not beside.exists():
            continue
        meta = load_json(beside)
        predictions[(f"{meta['language']}-{meta['pivot']}", meta["arm"], meta["model"],
                     meta["direction"], meta.get("trained_on", meta["direction"]))] = \
            load_jsonl(path)

    header = (f"{'lang':4s} {'piv':3s} {'arm':22s} {'model':9s} {'trained':9s} {'scored':9s} "
              f"{'train':>9s} {'n':>5s} {'chrF++':>7s} {'chrF2':>6s} {'BLEU':>6s}  vs rival")
    print(header)
    print("-" * len(header))
    comparisons = []
    for row in sorted(rows, key=lambda r: (r["language"], r["pivot"], r["arm"], r["model"])):
        rival_name = ARMS.get(row["arm"], {}).get("rival")
        verdict = ""
        trained_on = row.get("trained_on", row["direction"])
        key = (f"{row['language']}-{row['pivot']}", row["arm"], row["model"],
               row["direction"], trained_on)
        rival_key = (key[0], rival_name, row["model"], row["direction"], trained_on)
        if rival_name and key in predictions and rival_key in predictions:
            mine, theirs = predictions[key], predictions[rival_key]
            if len(mine) == len(theirs):
                result = paired_test([r["hypothesis"] for r in theirs],
                                     [r["hypothesis"] for r in mine],
                                     [r["reference"] for r in mine], args.bootstrap_samples)
                chrf = result["chrF2++"] if "chrF2++" in result else list(result.values())[0]
                mark = "*" if (chrf["p_value"] or 1) < 0.05 else " "
                verdict = (f"{chrf['delta']:+.2f} chrF++ vs {rival_name} "
                           f"p={chrf['p_value']:.3f}{mark}")
                comparisons.append({"key": "/".join(key), "rival": rival_name, **result})
        manifest_key = f"{row['language']}-{row['pivot']}/{row['arm']}"
        train_pairs = load_json(WORK / "prepare_manifest.json")["arms"].get(
            manifest_key, {}).get("train", 0)
        print(f"{row['language']:4s} {row['pivot']:3s} {row['arm']:22s} {row['model']:9s} "
              f"{trained_on:9s} {row['direction']:9s} {train_pairs:9,} {row['test_pairs']:5d} "
              f"{row['chrf2pp']:7.2f} {row['chrf2']:6.2f} {row['bleu']:6.2f}  {verdict}")

    # The only numbers comparable to PARME's are ours on PARME's own split, with its metric.
    print("\nagainst PARME's published numbers -- its test split only, its chrF2, not chrF++")
    # The pivot belongs in this table: glk-en and glk-fa are scored on the same PARME split
    # and without the column the two rows are indistinguishable from a duplicate.
    print(f"  {'lang':4s} {'piv':3s} {'arm':22s} {'model':9s} {'dir':9s} {'n':>5s} "
          f"{'chrF2':>6s} {'BLEU':>6s}   PARME base / augmented")
    for row in sorted(rows, key=lambda r: (r["language"], r["pivot"], r["arm"],
                                           r["model"], r["direction"])):
        entry = (row.get("by_test_source") or {}).get("parme")
        if not entry:
            continue
        base = RIVALS.get((row["language"], "parme_nllb_base"), {})
        augmented = RIVALS.get((row["language"], "parme_nllb_augmented"), {})
        if not base:
            continue
        gap = entry["chrf2"] - augmented["chrf2"]
        print(f"  {row['language']:4s} {row['pivot']:3s} {row['arm']:22s} {row['model']:9s} "
              f"{row['direction']:9s} {entry['pairs']:5d} {entry['chrf2']:6.2f} "
              f"{entry['bleu']:6.2f}   {base['chrf2']:.1f} / {augmented['chrf2']:.1f}"
              f"   {gap:+.2f} chrF2 vs augmented")
    print("\nnotes")
    print("  * marks p < 0.05 on a paired bootstrap against the arm's rival.")
    print("  PARME's results files do not state the direction; confirm against its scorer.py")
    print("  before quoting the comparison above as like-for-like.")
    tiny = [key for key, entry in load_json(WORK / "prepare_manifest.json")["arms"].items()
            if entry["train"] < 500]
    if tiny:
        print(f"  {len(tiny)} arms train on under 500 pairs and cannot be read as system "
              f"quality -- they measure how little data the rival had: {', '.join(tiny[:6])}"
              + (" ..." if len(tiny) > 6 else ""))
    save_json(WORK / "report.json", {"runs": rows, "comparisons": comparisons,
                                     "rivals": {f"{k[0]}/{k[1]}": v
                                                for k, v in RIVALS.items()}})
    print(f"\nwritten: {WORK / 'report.json'}")
    return 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("stage", choices=["plan", "prepare", "train", "evaluate",
                                          "rescore", "report"])
    parser.add_argument("--languages", nargs="*", help="default: every configured language")
    parser.add_argument("--language")
    parser.add_argument("--pivot")
    # No choices= here. The scale-curve arms (ours_scale_1000 ... ours_scale_all) are named
    # at prepare time and never appear in ARMS, so a fixed choice list silently rejects
    # exactly the arms that measure how quality scales. stage_train validates the name
    # against the prepare manifest instead, which is the list that actually exists on disk.
    parser.add_argument("--arm", help=f"an arm from ARMS ({', '.join(sorted(ARMS))}) "
                                      f"or a prepared scale arm such as ours_scale_5000")
    parser.add_argument("--model", default="nllb600m", choices=sorted(MODELS))
    parser.add_argument("--direction", default="to_pivot",
                        choices=["to_pivot", "from_pivot", "both"],
                        help="to_pivot trains on a model-written target; from_pivot trains on "
                             "genuine human text and is the stronger use of this data")
    parser.add_argument("--eval-direction", choices=["to_pivot", "from_pivot"],
                        help="which way to score a --direction both model; ignored for "
                             "single-direction models")
    parser.add_argument("--unit", default="sentence",
                        choices=["sentence", "paragraph", "document", "mixed", "multi"],
                        help="the training example: one sentence pair, the article's own "
                             "paragraph, a whole document, sentences and paragraphs "
                             "together, or multi: every granularity at once via sliding "
                             "merges inside each paragraph")
    parser.add_argument("--window", type=int, default=3,
                        help="sentences per group, used only for corpora that ship no "
                             "paragraph boundaries; ours are read from the data")
    parser.add_argument("--multi-cap", type=float, default=4.0,
                        help="for --unit multi, the ceiling on examples as a multiple of "
                             "the sentence count; every sentence is always kept")
    parser.add_argument("--force-comet", action="store_true",
                        help="recompute COMET for runs that already have it")
    parser.add_argument("--allow-missing-comet", action="store_true",
                        help="rescore surface metrics even where COMET cannot load")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--epochs", type=float, default=3)
    parser.add_argument("--learning-rate", type=float, default=3e-5)
    # LoRA needs a much larger step than a full fine-tune: only the adapter moves.
    parser.add_argument("--lora-learning-rate", type=float, default=2e-4)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--accumulation", type=int, default=4)
    parser.add_argument("--max-length", type=int, default=512)
    parser.add_argument("--eval-steps", type=int, default=250)
    parser.add_argument("--beams", type=int, default=4)
    parser.add_argument("--length-penalty", type=float, default=1.0,
                        help="beam-search length penalty. Below 1 favours shorter output; "
                             "Wu et al. use 0.6. The lever for over-generation, and it "
                             "needs no retraining")
    # Every flag below defaults to the behaviour the already-scored runs used. The published
    # literature argues for different values on small data, but changing a default would
    # silently make 65 finished runs incomparable with everything after it, so each is
    # opt-in and measured in its own block.
    parser.add_argument("--label-smoothing", type=float, default=0.0,
                        help="label smoothing. 0.1-0.2 is reported to help low-resource "
                             "fine-tuning; 0.0 keeps the recipe the scored runs used")
    parser.add_argument("--dropout", type=float, default=None,
                        help="override the model's dropout. 0.3 is the reported "
                             "low-resource setting; None keeps the checkpoint's own value")
    parser.add_argument("--select-on", default="loss", choices=["loss", "chrf"],
                        help="checkpoint selection signal. 'chrf' generates on dev and "
                             "selects on chrF++, which the literature prefers to dev loss; "
                             "'loss' is what the scored runs used")
    parser.add_argument("--patience", type=int, default=0,
                        help="early-stopping patience in evaluations; 0 disables it")
    parser.add_argument("--dev-beams", type=int, default=1,
                        help="beams when generating on dev for --select-on chrf. Greedy by "
                             "default: this runs at every eval step")
    parser.add_argument("--generation-batch-size", type=int, default=24)
    parser.add_argument("--bootstrap-samples", type=int, default=1000)
    parser.add_argument("--refresh", action="store_true")
    args = parser.parse_args()

    if args.stage in {"train", "evaluate"}:
        missing = [name for name in ("language", "pivot", "arm") if not getattr(args, name)]
        if missing:
            raise SystemExit(f"{args.stage} needs --{' --'.join(missing)}")
    return {"plan": stage_plan, "prepare": stage_prepare, "train": stage_train,
            "evaluate": stage_evaluate, "rescore": stage_rescore,
            "report": stage_report}[args.stage](args)


if __name__ == "__main__":
    raise SystemExit(main())