File size: 207,920 Bytes
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b70b8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
52d8046
 
 
610dce0
 
52d8046
610dce0
52d8046
 
610dce0
52d8046
 
610dce0
52d8046
 
 
 
 
 
610dce0
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
bf6fa82
 
 
 
 
 
 
610dce0
 
 
3534f8f
 
 
 
 
610dce0
3534f8f
610dce0
 
 
3534f8f
610dce0
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3534f8f
 
 
 
f7bed3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3534f8f
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
f7bed3c
 
 
 
3534f8f
 
610dce0
 
 
 
d7d9530
 
 
 
 
 
610dce0
ebda5b7
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
2193102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
2193102
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebda5b7
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebda5b7
 
 
 
 
 
 
 
 
610dce0
 
ebda5b7
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3534f8f
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
3534f8f
 
 
bf6fa82
 
3534f8f
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
3534f8f
 
 
 
 
bf6fa82
3534f8f
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
bf6fa82
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3534f8f
 
610dce0
 
3534f8f
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
ebda5b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3534f8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
3534f8f
610dce0
 
 
 
 
 
 
 
 
3534f8f
 
610dce0
 
 
 
 
 
bf6fa82
 
610dce0
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
610dce0
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
610dce0
 
 
 
 
 
 
 
6ca6d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebda5b7
 
 
 
 
 
 
 
 
 
 
 
6ca6d36
 
 
 
ebda5b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
6ca6d36
bf6fa82
6ca6d36
bf6fa82
ebda5b7
bf6fa82
ebda5b7
bf6fa82
6ca6d36
bf6fa82
 
6ca6d36
bf6fa82
 
 
6ca6d36
ebda5b7
 
 
6ca6d36
 
ebda5b7
 
 
 
 
 
 
6ca6d36
 
 
 
ebda5b7
 
 
 
bf6fa82
 
 
6ca6d36
 
 
 
 
 
 
090be4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
090be4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
 
 
610dce0
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc6d29f
 
 
 
 
 
bf6fa82
 
 
 
 
fc6d29f
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
fc6d29f
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
090be4d
 
 
 
6ca6d36
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca6d36
 
610dce0
 
 
bf6fa82
 
 
 
610dce0
bf6fa82
610dce0
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
97e1ca3
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
97e1ca3
 
 
610dce0
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
bf6fa82
610dce0
fc6d29f
6ca6d36
610dce0
 
97e1ca3
 
 
 
bf6fa82
97e1ca3
610dce0
 
 
 
 
 
 
 
 
52d8046
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
610dce0
52d8046
 
 
610dce0
52d8046
bf6fa82
52d8046
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
52d8046
bf6fa82
 
 
 
 
 
 
 
 
 
52d8046
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
52d8046
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
bf6fa82
 
 
 
 
52d8046
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
bf6fa82
 
 
 
 
 
 
 
 
 
 
52d8046
bf6fa82
 
 
 
 
 
 
 
52d8046
 
bf6fa82
 
 
 
 
 
52d8046
bf6fa82
52d8046
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52d8046
 
 
 
 
 
 
 
 
 
 
bf6fa82
52d8046
 
 
 
 
 
 
 
bf6fa82
 
52d8046
 
 
 
 
 
bf6fa82
52d8046
 
 
 
 
 
 
 
 
 
 
 
bf6fa82
 
 
 
 
52d8046
 
bf6fa82
 
 
 
 
52d8046
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdd1e6f
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc6d29f
 
 
97e1ca3
 
 
 
fc6d29f
97e1ca3
 
 
fc6d29f
 
 
97e1ca3
 
 
 
610dce0
 
 
 
 
fc6d29f
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
fc6d29f
 
52d8046
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97e1ca3
 
 
52d8046
 
610dce0
 
ebda5b7
 
 
 
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc6d29f
6ca6d36
97e1ca3
bf6fa82
 
 
 
 
 
 
 
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
 
bf6fa82
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
bf6fa82
 
 
610dce0
 
 
 
 
bf6fa82
 
610dce0
 
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
610dce0
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
 
 
fc6d29f
 
 
 
bf6fa82
 
 
 
 
 
610dce0
 
fc6d29f
 
 
 
bf6fa82
610dce0
fc6d29f
bf6fa82
 
610dce0
 
 
bf6fa82
 
610dce0
 
fc6d29f
bf6fa82
 
 
 
 
610dce0
 
 
 
 
 
bf6fa82
610dce0
 
 
bf6fa82
 
 
 
 
 
 
610dce0
 
 
 
 
bf6fa82
 
610dce0
 
 
 
2193102
 
 
610dce0
2193102
 
610dce0
 
 
 
 
 
 
 
2193102
610dce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4d2fa0
bf6fa82
a4d2fa0
610dce0
 
 
72212b6
 
 
 
 
 
610dce0
 
fc6d29f
610dce0
 
fc6d29f
 
 
6ca6d36
090be4d
ebda5b7
090be4d
 
 
6ca6d36
ebda5b7
 
090be4d
 
 
ebda5b7
 
a4d2fa0
 
610dce0
 
 
52d8046
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
97e1ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
 
 
 
 
 
bf6fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
610dce0
a4d2fa0
bf6fa82
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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
#!/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 = {
    # Alemannic's tag is gsw_Latn, never als_Latn. The key `als` is the Wikipedia prefix --
    # als.wikipedia.org is Alemannic, there is no gsw.wikipedia.org -- but in ISO 639-3, and
    # therefore in NLLB, `als` is Tosk ALBANIAN and Alemannic is `gsw`. NLLB ships als_Latn,
    # so language_tags() took the "tag already exists, use it as-is" path and trained
    # Alemannic on top of Albanian's pretrained embedding instead of seeding a fresh token
    # from German the way bar and frr do. gsw_Latn is absent from NLLB (verified against the
    # nllb-200 tokenizer), so it is added and seeded from deu_Latn, which is what every
    # other Germanic language here does. The same trap is handled explicitly in
    # build_baseline_corpus.py (FineTranslations gsw_Latn) and in WIKIPEDIA_CONFIGS below.
    "als": {"tag": "gsw_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"},
    # Gemma 4 12B is a second, three-times-larger LLM arm. It answers a question llm_lora
    # alone cannot: whether an LLM that loses to NLLB does so because it is an LLM or
    # because it is small. The instruction-tuned checkpoint is used, matching Qwen3-4B,
    # which is also instruction tuned -- pairing a base model against an instruct model
    # would confound size with tuning.
    #
    # Its reasoning mode is off. Gemma 4 turns thinking on with a <|think|> token at the
    # start of the system prompt, and lora_prompt() emits a bare completion prompt with no
    # system turn, so nothing switches it on. The card warns that 12B still emits the
    # channel tags with an empty body, so generate_causal_lora strips any thought channel
    # and counts what it stripped rather than trusting that.
    "gemma_lora": {"base": "google/gemma-4-12B-it", "kind": "causal_lora", "tagged": False,
                   "train": True, "loader": "multimodal",
                   "why": "a 12B LLM arm, so the LLM class is represented at two sizes and "
                          "an LLM result is not just a statement about a 4B model"},
}

# Gemma 4 is encoder-free: it projects raw image patches and audio directly into the
# language model, so it loads as Gemma4UnifiedForConditionalGeneration under
# AutoModelForMultimodalLM rather than AutoModelForCausalLM. Qwen3-4B is a plain causal LM.
# The class is read from the spec rather than sniffed per call, so an unknown value fails
# loudly instead of silently falling back to the wrong class.
CAUSAL_LOADERS = {"causal": "AutoModelForCausalLM", "multimodal": "AutoModelForMultimodalLM"}

# 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"},
    # Built by build_pooled_arms as a post-pass, not from these `sources`, because they
    # union data across language-pivot pairs and the main prepare loop only sees one pair at
    # a time. Listed here so they have a rival, appear in the report and can be asked for by
    # name; the entries are otherwise inert.
    #
    # The diagnosis these answer: more aligned data of the same kind has stopped paying
    # (bar->en is 38.75 at 5k pairs and 39.02 at 105k), the tokenizer is not the problem
    # (1.4-1.6x English fertility), and the weak side is generating the low-resource
    # language (en->bar 29.0 against bar->en 39.1). So the lever is more exposure to these
    # languages rather than more pairs -- and pooling is the one form of that which needs no
    # new data at all.
    # Written by the backtranslate stage, not by prepare: they need a trained model to
    # exist first. `sources` is empty for the same reason the pooled arms' is.
    "bt_only": {"sources": [], "rival": "ours", "synthetic": True,
                "why": "the back-translated data alone. Not expected to win -- it is the "
                       "diagnostic that says whether the synthetic pairs carry signal at "
                       "all before they are mixed in"},
    "ours_plus_bt": {"sources": [], "rival": "ours", "synthetic": True,
                     "why": "ours plus back-translated monolingual Wikipedia. Aimed at the "
                            "measured weak side -- generating the low-resource language -- "
                            "where the target is real human text rather than model output"},
    "ours_multipivot": {"sources": [], "rival": "ours", "pooled": True,
                        "why": "one model over both of a language's pivots. Every rival "
                               "corpus covers a single pivot, so this comparison is only "
                               "available to us"},
    "ours_multilingual": {"sources": [], "rival": "ours", "pooled": True,
                          "why": "one model over every language sharing a pivot and a "
                                 "script: glk with mzn, bar with als and frr. The rivals "
                                 "are single-language, so again only we can run it"},
    "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"},
    # FineTranslations split by where its source text came from. It beats our corpus at
    # matched size in all nine model-by-pair cells, with no test contamination, so the next
    # question is what that lead is made of: better translations, or a wider domain than the
    # Wikipedia we mine. These four arms separate those. The crawl turns out to include the
    # languages' own Wikipedias -- bar.wikipedia.org appears throughout the Bavarian half --
    # so a same-domain comparison is actually available rather than hypothetical.
    "finetrans_wiki": {"sources": ["finetrans_wiki"], "rival": None,
                       "why": "FineTranslations restricted to articles on the language's own "
                              "Wikipedia: the same domain our corpus is mined from, so the "
                              "only remaining difference is who produced the translation"},
    "ours_matched_finetrans_wiki": {"sources": ["ours"], "rival": "finetrans_wiki",
                                    "match_size_of": "finetrans_wiki",
                                    "why": "ours at the size of the Wikipedia half, the "
                                           "like-for-like comparison on domain and count"},
    "finetrans_nonwiki": {"sources": ["finetrans_nonwiki"], "rival": None,
                          "why": "the rest of FineTranslations -- crawled web pages, forums "
                                 "and documents. If its lead lives here and not in the "
                                 "Wikipedia half, the lead is domain breadth, not quality"},
    "ours_matched_finetrans_nonwiki": {"sources": ["ours"], "rival": "finetrans_nonwiki",
                                       "match_size_of": "finetrans_nonwiki",
                                       "why": "ours at the size of the non-Wikipedia half, so "
                                              "the two halves are each read against an "
                                              "equal-sized slice of ours"},
    # Matched on words rather than on pairs, which is what the three arms above should have
    # been. A FineTranslations record is a machine-translated FineWeb2 document averaging
    # 179 English words against our 12.9, so "same number of pairs" gave it about twelve
    # times the text -- and its records sit under the 512-token limit, so none of that
    # advantage was truncated away. These arms cut FineTranslations down to the pivot-side
    # word count of the ours arm it is read against, leaving the ours side untouched so the
    # already-scored runs stay valid.
    #
    # The residual asymmetry is epochs, and it is stated rather than hidden: equal words in
    # records of different lengths cannot also be equal in record count, so at a fixed step
    # budget the word-cut FineTranslations arm cycles its text many more times than ours
    # does. --patience is what keeps that from deciding the result, and the epoch counts are
    # recorded so a reader can see which side the budget bound.
    "finetrans_wordmatched": {"sources": ["finetrans_clean"], "rival": None,
                              "match_words_of": "ours_matched_finetrans",
                              "why": "FineTranslations cut to the same number of English "
                                     "words as the ours arm it is compared with, since "
                                     "matching on pair count gave it ~12x the text"},
    "finetrans_wordmatched_wiki": {"sources": ["finetrans_wiki"], "rival": None,
                                   "match_words_of": "ours_matched_finetrans_wiki",
                                   "why": "the Wikipedia half at equal word count: same "
                                          "domain and same quantity of text, so the only "
                                          "remaining difference is who translated it"},
    "finetrans_wordmatched_nonwiki": {"sources": ["finetrans_nonwiki"], "rival": None,
                                      "match_words_of": "ours_matched_finetrans_nonwiki",
                                      "why": "the non-Wikipedia half at equal word count, "
                                             "isolating domain breadth from sheer volume"},
    # The non-Wikipedia half cut to the Wikipedia half's English word count. This is the one
    # FineTranslations comparison that holds everything but the source domain fixed: one
    # corpus, one filtering pipeline, one translation system, paragraph records on both sides,
    # and now equal volume. Against `ours` the segmentation, the domain and the human-vs-MT
    # provenance all differ at once and no size knob repairs that; here only the domain does.
    #
    # Non-Wikipedia is the side that gets cut because Wikipedia is the smaller half in every
    # pair -- bar-en 2.58M English words against 8.63M, als-en 6.58M against 13.64M, glk-en
    # 0.08M against 0.49M. Uncut, "non-Wikipedia wins" would partly mean "non-Wikipedia is
    # 1.9 to 5.9 times larger", which is the error this whole pass exists to stop making.
    # Leaving finetrans_wiki untouched also keeps its scored bar-en cell valid.
    "finetrans_nonwiki_matched_wiki": {"sources": ["finetrans_nonwiki"], "rival": None,
                                       "match_words_of": "finetrans_wiki",
                                       "why": "the non-Wikipedia half at the Wikipedia "
                                              "half's word count: same corpus, same "
                                              "pipeline, same translator, same record "
                                              "granularity, equal text -- so a difference on "
                                              "test is attributable to the source domain"},
}

# 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"}

# ----------------------------------------- every gathered baseline, corpus by corpus
#
# `public` and `public_prose` pool the published baseline corpus into one arm each, which
# answers "is our data better than what exists" but not "better than *which* of the things
# that exist". These arms train on one upstream corpus at a time, so the answer names the
# rival. For the five languages in this study the whole baseline release reduces to six
# corpora, and they are not remotely alike -- 174k LLM translations, 59k automatically mined
# sentence pairs, 36k entity lists, 10k UI strings, 152 Tatoeba sentences -- so a single
# "public baseline" number is an average over things a practitioner would never confuse.
#
# An arm whose pool comes out empty is skipped, so one static list covers every pair: glk-en
# gets FineTranslations, translatewiki and wikimedia; bar-de gets WikiMatrix, XLEnt and
# wikimedia; frr-en gets translatewiki alone.
BASELINE_CORPORA = ("FineTranslations", "WikiMatrix", "XLEnt", "translatewiki",
                    "wikimedia", "Tatoeba")

ARMS["baseline_all"] = {
    "sources": ["baseline_all"], "rival": None,
    "why": "every record the gathered baseline release holds for this pair, including the "
           "LLM translations and entity lists -- the most data a practitioner could "
           "assemble today without mining anything themselves"}
ARMS["ours_matched_baseline_all"] = {
    "sources": ["ours"], "rival": "baseline_all", "match_size_of": "baseline_all",
    "why": "ours at the size of everything already available, so the comparison is not "
           "simply a comparison of corpus sizes"}
for _corpus in BASELINE_CORPORA:
    _slug = _corpus.lower()
    ARMS[f"baseline_{_slug}"] = {
        "sources": [f"baseline_{_slug}"], "rival": None,
        "why": f"the {_corpus} half of the gathered baseline, on its own"}
    ARMS[f"ours_matched_baseline_{_slug}"] = {
        "sources": ["ours"], "rival": f"baseline_{_slug}",
        "match_size_of": f"baseline_{_slug}",
        "why": f"ours at {_corpus}'s size"}

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 wiki_article_url(url: str | None, language: str | None = None) -> bool:
    """Is this crawled page an article on the low-resource language's own Wikipedia?

    Needed because FineTranslations is web text and our corpus is mined Wikipedia, so any
    comparison between them confounds who translated the sentence with what the sentence is
    about. Splitting FineTranslations on this predicate separates the two.

    Two exclusions that matter. Wikipedia pages outside the article namespace are not article
    prose -- bar.wikipedia's FineTranslations rows include Dischkrian: (talk), Wikipedia:
    (village-pump archives) and Nutza: (user) pages, and village-pump chatter against our
    article text would just swap one domain confound for another. Namespaces are language
    specific, so rather than enumerate them, any title containing a colon is treated as
    non-article; that loses the rare article whose own title has one. The main page is
    excluded by name for the same reason -- it is a portal, not prose.
    """
    if not url:
        return False
    import urllib.parse
    parsed = urllib.parse.urlparse(url)
    host = parsed.netloc.lower().removeprefix("www.")
    if not host.endswith(".wikipedia.org"):
        return False
    # The language's own Wikipedia, not any Wikipedia. Without this, a de.wikipedia.org page
    # counts as same-domain for Bavarian, which is the opposite of the point: the comparison
    # is against the bar.wikipedia.org text our corpus mines. The subdomain is the Wikipedia
    # prefix, which is what the LANGUAGES keys are -- `als` for Alemannic, since there is no
    # gsw.wikipedia.org even though gsw is its ISO code.
    if language is not None:
        site = host.removesuffix(".wikipedia.org").removesuffix(".m")
        if site != language:
            return False
    path = urllib.parse.unquote(parsed.path)
    if "/wiki/" not in path:
        return False
    title = path.split("/wiki/", 1)[1]
    if ":" in title.split("/")[0]:
        return False
    return title.split("/")[0].lower() not in {"hauptseitn", "hauptseite", "main_page", ""}


def finetrans_pairs(language: str, pivot: str, *, min_score: float = 0.0,
                    domain: str | None = None):
    """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.

    ``domain`` splits the corpus by where its source page came from: "wiki" keeps only
    articles on the language's own Wikipedia, "nonwiki" keeps everything else. Both halves
    are needed to say anything, and they answer different questions. If FineTranslations
    still beats ours on the Wikipedia half, its lead is about translation quality. If it only
    beats ours on the other half, the lead is about domain, and the fair comparison is the
    Wikipedia half. One half alone cannot tell those apart.
    """
    if pivot != "en":
        return
    if domain not in (None, "wiki", "nonwiki"):
        raise SystemExit(f"finetrans domain must be wiki, nonwiki or unset, not {domain!r}")
    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
        url = columns["document_url"][index]
        if domain is not None and wiki_article_url(url, language) != (domain == "wiki"):
            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],
                   "document_url": url,
                   "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)
    for language in languages:
        if language not in LANGUAGES:
            raise SystemExit(f"{language}: not a configured source language")
    if args.reindex:
        return reindex_arms(languages)
    if args.baselines_only:
        path = WORK / "prepare_manifest.json"
        manifest = load_json(path) if path.exists() else {"arms": {}}
        manifest.setdefault("arms", {})
        build_baseline_arms(manifest, languages, args.seed)
        save_json(path, manifest)
        print(f"\nmanifest now lists {len(manifest['arms'])} arms")
        return 0
    if args.finetrans_domains_only:
        # Same post-pass reasoning as --baselines-only: four new arms are not worth
        # rewriting the splits that several hundred scored runs are tied to.
        path = WORK / "prepare_manifest.json"
        manifest = load_json(path) if path.exists() else {"arms": {}}
        manifest.setdefault("arms", {})
        build_finetrans_domain_arms(manifest, languages, args.seed)
        save_json(path, manifest)
        print(f"\nmanifest now lists {len(manifest['arms'])} arms")
        return 0
    if args.finetrans_domain_matched_only:
        # One arm, and the only FineTranslations comparison with a single free variable:
        # the non-Wikipedia half at the Wikipedia half's word count. Post-pass, so
        # finetrans_wiki keeps its bytes and its scored cells.
        path = WORK / "prepare_manifest.json"
        manifest = load_json(path) if path.exists() else {"arms": {}}
        manifest.setdefault("arms", {})
        build_finetrans_domain_matched_arms(manifest, languages, args.seed)
        save_json(path, manifest)
        print(f"\nmanifest now lists {len(manifest['arms'])} arms")
        return 0
    if args.finetrans_wordmatched_only:
        # Post-pass, same reasoning again: the ours arms these are compared against keep
        # their bytes, so every run already scored against them stands.
        path = WORK / "prepare_manifest.json"
        manifest = load_json(path) if path.exists() else {"arms": {}}
        manifest.setdefault("arms", {})
        build_finetrans_wordmatched_arms(manifest, languages, args.seed)
        save_json(path, manifest)
        print(f"\nmanifest now lists {len(manifest['arms'])} arms")
        return 0
    if args.pooled_only:
        # Only the post-pass. Rebuilding glk and bar in full would rewrite their
        # train/dev/test files, and 88 scored runs are tied to the exact bytes of those
        # splits -- regenerating them to add two new arms would be the wrong trade.
        path = WORK / "prepare_manifest.json"
        manifest = load_json(path) if path.exists() else {"arms": {}}
        manifest.setdefault("arms", {})
        build_pooled_arms(manifest, languages, args.seed)
        save_json(path, manifest)
        print(f"\nmanifest now lists {len(manifest['arms'])} arms")
        return 0
    # Carry over the arms of every language this run is not rebuilding. A --languages glk
    # prepare used to reinitialise "arms", silently deleting the bar entries -- and because
    # stage_train validates its --arm against this manifest, that left bar arms sitting
    # prepared on disk while every train call exited saying they did not exist.
    manifest: dict = {"built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                      "seed": args.seed, "parme_revision": PARME_REVISION, "arms": {}}
    existing = WORK / "prepare_manifest.json"
    if existing.exists() and not args.refresh:
        rebuilding = {f"{language}-{pivot}"
                      for language in languages if language in LANGUAGES
                      for pivot in LANGUAGES[language]["pivots"]}
        for key, entry in load_json(existing).get("arms", {}).items():
            if key.split("/")[0] not in rebuilding:
                manifest["arms"][key] = entry
        if manifest["arms"]:
            print(f"carrying over {len(manifest['arms'])} arms from previous prepare runs")

    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))
            # Split by source domain. No min_score here on purpose: these are read against
            # baseline_finetranslations, which is the unfiltered corpus, so adding GlotLID
            # filtering to one side would change two things at once and the halves would no
            # longer sum to the arm they are splitting.
            for _half in ("wiki", "nonwiki"):
                pools[f"finetrans_{_half}"] = list(finetrans_pairs(
                    language, pivot, domain=_half))
            # The gathered baseline, whole and then corpus by corpus. `corpus` is carried on
            # every row by public_pairs, so the split costs one pass and no extra download.
            pools["baseline_all"] = list(public_pairs(language, pivot))
            for corpus in BASELINE_CORPORA:
                pools[f"baseline_{corpus.lower()}"] = [
                    row for row in pools["baseline_all"] if row.get("corpus") == corpus]
            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,
                          seed=args.seed)

            # 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, seed=args.seed)

    # After every pair exists on disk, since these arms are unions across pairs.
    print("\npooled arms (the comparisons only this corpus can make)")
    build_pooled_arms(manifest, [l for l in languages if l in LANGUAGES], args.seed)

    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 pivot_words(row: dict) -> int:
    """Words on the pivot side, which is the one side every arm has in common."""
    return len((row.get("pivot") or "").split())


def sample_by_word_budget(rows: list[dict], budget: int, seed: int) -> list[dict]:
    """Whole documents until the pivot-side word count reaches ``budget``.

    Why this exists at all: matching arms on *pair count* assumes a pair means the same
    thing in both, and against FineTranslations it does not. Measured on the English side,
    bar-en reads 12.9 words per pair in our corpus and 178.9 in FineTranslations -- their
    records are machine-translated FineWeb2 *documents*, ours are aligned sentences. So
    every "size-matched" FineTranslations cell handed it roughly twelve times the text, and
    at --max-length 512 a 155-word record is not truncated, so that text all became training
    signal. The arms built on this function match the quantity the two corpora actually
    share, which is words.

    Documents are kept whole, like sample_by_document, so a paragraph is never cut in half
    and the overshoot is at most one document -- about 0.1% of the budget at these sizes.
    """
    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] = []
    words = 0
    for key in keys:
        if words >= budget:
            break
        picked.extend(groups[key])
        words += sum(pivot_words(row) for row in groups[key])
    return picked


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]


# Monolingual Wikipedia, for back-translation. One trap here, and it is the mirror image of
# the FineTranslations one: `als.wikipedia.org` IS the Alemannic Wikipedia, so the config
# `20231101.als` is the right source for our `als`. In FineTranslations and NLLB, `als_Latn`
# is Tosk Albanian and the Alemannic config is `gsw_Latn`. The same three letters mean
# different languages in the two places, so each mapping is written out rather than derived.
WIKIPEDIA_REPO = "wikimedia/wikipedia"
WIKIPEDIA_CONFIGS = {
    "als": "20231101.als",      # Alemannic -- the Wikipedia sense of `als`, not Albanian
    "bar": "20231101.bar",
    "frr": "20231101.frr",
    "glk": "20231101.glk",
    "mzn": "20231101.mzn",
}

# Marks a back-translated source at training time. The model otherwise learns to trust
# synthetic input exactly as much as real input, and tagging is the standard remedy: at test
# time the input carries no tag, so the model falls back on what it learned from real pairs.
BT_TAG = "<bt> "

# Sentence terminators, including the Perso-Arabic ones. A splitter that only knows "." cuts
# Gilaki and Mazanderani text at the wrong places, or not at all.
SENTENCE_END = ".!?؟۔;،"[:5] + "؟۔"


def split_sentences(text: str, minimum: int = 20, maximum: int = 400) -> list[str]:
    """Break an article into sentence-like spans.

    Deliberately crude: this feeds back-translation, where a slightly ragged split costs a
    little quality on one synthetic example, while pulling in a sentence splitter for five
    under-resourced languages costs a dependency none of them is well served by.

    Spans shorter than `minimum` characters are dropped -- Wikipedia is full of headings,
    table fragments and one-word stubs, and translating those teaches the model nothing.
    """
    out, current = [], []
    for char in text:
        current.append(char)
        if char in SENTENCE_END:
            span = "".join(current).strip()
            if minimum <= len(span) <= maximum:
                out.append(span)
            current = []
    span = "".join(current).strip()
    if minimum <= len(span) <= maximum:
        out.append(span)
    return out


def monolingual_sentences(language: str, limit: int) -> list[str]:
    """Sentences from the language's own Wikipedia, deduplicated, in article order."""
    config = WIKIPEDIA_CONFIGS.get(language)
    if not config:
        raise SystemExit(f"{language}: no Wikipedia config recorded")
    import pyarrow.parquet as pq
    from huggingface_hub import snapshot_download

    folder = Path(snapshot_download(WIKIPEDIA_REPO, repo_type="dataset",
                                    allow_patterns=[f"{config}/*"],
                                    cache_dir=str(CACHE / "wikipedia")))
    sentences, seen = [], set()
    for path in sorted((folder / config).glob("*.parquet")):
        table = pq.read_table(path, columns=["text"])
        for text in table.column("text").to_pylist():
            for span in split_sentences(text or ""):
                key = text_key(span)
                if key in seen:
                    continue
                seen.add(key)
                sentences.append(span)
                if len(sentences) >= limit:
                    return sentences
    return sentences


def stage_backtranslate(args) -> int:
    """Translate monolingual low-resource text into the pivot, and build the synthetic arms.

    Why this and not more aligned data. Three measurements say the parallel corpus has given
    what it has to give:

      * the scale curve is flat -- bar->en scores 38.75 on 5,000 pairs and 39.02 on 105,419;
      * tokenizer fertility is 1.36x English for bar and 1.56x for glk, which is mild, so
        the vocabulary is not the limit either;
      * what is weak is writing the low-resource language: en->bar 29.02 against bar->en
        39.10, en->glk 9.90 against glk->en 15.60.

    Back-translation attacks exactly that gap, and it is well suited here because the
    direction we are strong in is the one it needs: our bar->en model scores 39 chrF++, and
    it is used to produce the synthetic *source* while the target stays real human
    Wikipedia text. That also answers the standing objection to the into-pivot arms, whose
    targets are model-written -- here the target is not.

    The synthetic pivot text is marked with BT_TAG during training rather than in the file,
    so the data on disk stays honest about what it is and the tagging remains a training
    choice that can be ablated.
    """
    import torch
    from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

    pair = f"{args.language}-{args.pivot}"
    folder = WORK / "arms" / pair / "ours"
    if not folder.exists():
        raise SystemExit(f"{pair}/ours is not prepared; back-translation needs its splits")
    source_model = WORK / "runs" / pair / "ours" / args.model / "to_pivot" / "model"
    if not source_model.exists():
        raise SystemExit(f"no trained to_pivot model at {source_model}. Back-translation "
                         f"uses the strong direction to make the synthetic side, so that "
                         f"model has to exist first")

    train = load_jsonl(folder / "train.jsonl")
    dev = load_jsonl(folder / "dev.jsonl")
    test = load_jsonl(folder / "test.jsonl")
    # Everything already seen, for either reason: test and dev text must never be trained
    # on, and text already in train adds nothing but duplicates.
    known = {text_key(row[side]) for row in train + dev + test
             for side in ("low", "pivot") if row.get(side)}

    print(f"reading monolingual {args.language} Wikipedia "
          f"({WIKIPEDIA_CONFIGS[args.language]})", flush=True)
    candidates = monolingual_sentences(args.language, args.bt_candidates)
    fresh = [s for s in candidates if text_key(s) not in known]
    print(f"  {len(candidates):,} sentences, {len(fresh):,} not already in this pair's "
          f"splits", flush=True)
    fresh = fresh[:args.bt_sentences]
    if not fresh:
        raise SystemExit("no monolingual sentences left after filtering")

    tokenizer = AutoTokenizer.from_pretrained(str(source_model))
    model = AutoModelForSeq2SeqLM.from_pretrained(str(source_model),
                                                  dtype=torch.bfloat16).to("cuda").eval()
    spec = LANGUAGES[args.language]
    tokenizer.src_lang = spec["tag"]
    target_tag = spec["pivots"][args.pivot]
    forced = tokenizer.convert_tokens_to_ids(target_tag)

    synthetic = []
    batch_size = args.generation_batch_size
    started = time.monotonic()
    for start in range(0, len(fresh), batch_size):
        chunk = fresh[start:start + batch_size]
        batch = tokenizer(chunk, return_tensors="pt", padding=True, truncation=True,
                          max_length=args.max_length).to("cuda")
        with torch.no_grad():
            output = model.generate(**batch, forced_bos_token_id=forced,
                                    num_beams=args.beams, max_new_tokens=args.max_length,
                                    length_penalty=args.length_penalty)
        for low, pivot in zip(chunk, tokenizer.batch_decode(output,
                                                            skip_special_tokens=True)):
            if pivot.strip():
                synthetic.append({"low": low, "pivot": pivot.strip(),
                                  "origin": "backtranslation",
                                  # Says which side a model wrote, so training can mark it
                                  # and a reader can never mistake it for human text.
                                  "synthetic_side": "pivot",
                                  "tag_language": args.language,
                                  "tag_pivot": args.pivot})
        if start % (batch_size * 20) == 0:
            done = start + len(chunk)
            rate = done / max(time.monotonic() - started, 1e-9)
            print(f"  {done:,}/{len(fresh):,}  {rate:.1f} sent/s", flush=True)

    # Guard against the silent failure mode: a model that emits the input unchanged produces
    # synthetic pairs that teach the decoder to copy.
    copied = sum(1 for row in synthetic if text_key(row["low"]) == text_key(row["pivot"]))
    if copied > len(synthetic) * 0.1:
        raise SystemExit(f"{copied:,}/{len(synthetic):,} back-translations are identical to "
                         f"their input; the source model is copying, not translating")

    manifest = load_json(WORK / "prepare_manifest.json")
    manifest.setdefault("arms", {})
    print(f"\n  {copied:,} identical to input ({copied / max(len(synthetic), 1):.1%})")
    write_arm(manifest, args.language, args.pivot, "bt_only", synthetic, dev, test,
              seed=args.seed)
    write_arm(manifest, args.language, args.pivot, "ours_plus_bt", train + synthetic,
              dev, test, seed=args.seed)
    save_json(WORK / "prepare_manifest.json", manifest)
    print(f"\nbt_only {len(synthetic):,}; ours_plus_bt {len(train) + len(synthetic):,} "
          f"({len(train):,} real + {len(synthetic):,} synthetic)")
    return 0


def sibling_languages(language: str) -> list[str]:
    """Languages that share this one's donor, and so its script and nearest high-resource
    relative: glk with mzn, bar with als and frr.

    These are the groups worth pooling. Pooling glk with bar would mix Perso-Arabic with
    Latin and Iranian with Germanic, which is transfer in name only.
    """
    donor = LANGUAGES[language]["donor"]
    return sorted(code for code, spec in LANGUAGES.items()
                  if spec["donor"] == donor and code != language)


def build_baseline_arms(manifest: dict, languages: list[str], seed: int) -> None:
    """Add the per-corpus baseline arms without rebuilding anything already prepared.

    A full prepare rewrites every train/dev/test file for the languages it touches, and
    several hundred scored runs are tied to the exact bytes of those splits. So this is a
    post-pass, like build_pooled_arms: it reads each pair's existing dev and test straight
    off disk, rebuilds only the pools the new arms need, and writes only those arms.

    Contamination is re-checked here rather than trusted. The published baseline release
    already drops records that overlap its own evaluation corpus, but our test sets are not
    that corpus -- they are PARME and our own held-out splits -- so the same filter has to be
    applied again against the splits these models are actually scored on.
    """
    for language in languages:
        if language not in LANGUAGES:
            continue
        for pivot in LANGUAGES[language]["pivots"]:
            folder = WORK / "arms" / f"{language}-{pivot}"
            reference = folder / "ours"
            if not (reference / "test.jsonl").exists():
                print(f"[skip] {language}-{pivot}: not prepared yet", flush=True)
                continue
            test = load_jsonl(reference / "test.jsonl")
            dev = load_jsonl(reference / "dev.jsonl")
            forbidden = {text_key(row["low"]) for row in test + dev}
            forbidden |= {text_key(row["pivot"]) for row in test + dev}

            everything = list(public_pairs(language, pivot))
            pools = {"baseline_all": everything, "ours": list(ours_pairs(language, pivot))}
            for corpus in BASELINE_CORPORA:
                pools[f"baseline_{corpus.lower()}"] = [row for row in everything
                                                       if row.get("corpus") == corpus]
            cleaned = {}
            for name, rows in pools.items():
                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
                    if (low_key, pivot_key) in seen:
                        continue
                    seen.add((low_key, pivot_key))
                    kept.append(row)
                cleaned[name] = kept
                if rows:
                    print(f"  {language}-{pivot:3s} {name:28s} {len(rows):7,} -> "
                          f"{len(kept):7,}  (contaminated {leaked:,})", flush=True)

            for name in ["baseline_all"] + [f"baseline_{c.lower()}" for c in BASELINE_CORPORA]:
                rows = cleaned.get(name) or []
                if not rows:
                    continue
                write_arm(manifest, language, pivot, name, rows, dev, test, seed=seed)
                matched = sample_by_document(cleaned["ours"], len(rows), seed)
                write_arm(manifest, language, pivot, f"ours_matched_{name}", matched,
                          dev, test, seed=seed)


def build_finetrans_domain_arms(manifest: dict, languages: list[str], seed: int) -> None:
    """Split FineTranslations by source domain and size-match ours against each half.

    A post-pass for the same reason build_baseline_arms is one: a full prepare rewrites every
    train/dev/test file, and the scored runs are tied to the exact bytes of those splits.
    Adding four arms is not worth invalidating the table.

    What this answers: FineTranslations beats our corpus at matched size in all nine
    model-by-pair cells with no test contamination, so either it translates better or it
    simply covers more ground than the Wikipedia we mine. Its crawl includes the languages'
    own Wikipedias, so the Wikipedia half is a genuine like-for-like comparison and the rest
    is the domain-breadth half. Both are written, because either on its own is unreadable.

    Contamination is re-checked against the splits these models are actually scored on, not
    trusted from the published release, exactly as build_baseline_arms does -- and separately
    for each half, since a filter that passed on the whole corpus says nothing about how the
    leakage was distributed between the halves.
    """
    halves = ("wiki", "nonwiki")
    for language in languages:
        if language not in LANGUAGES:
            continue
        for pivot in LANGUAGES[language]["pivots"]:
            # FineTranslations pairs every language with English only, so another pivot has
            # no Wikipedia half to compare and no non-Wikipedia half either.
            if pivot != "en":
                continue
            folder = WORK / "arms" / f"{language}-{pivot}"
            reference = folder / "ours"
            if not (reference / "test.jsonl").exists():
                print(f"[skip] {language}-{pivot}: not prepared yet", flush=True)
                continue
            test = load_jsonl(reference / "test.jsonl")
            dev = load_jsonl(reference / "dev.jsonl")
            forbidden = {text_key(row["low"]) for row in test + dev}
            forbidden |= {text_key(row["pivot"]) for row in test + dev}

            pools = {"ours": list(ours_pairs(language, pivot))}
            for half in halves:
                pools[f"finetrans_{half}"] = list(
                    finetrans_pairs(language, pivot, domain=half))
            cleaned = {}
            for name, rows in pools.items():
                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
                    if (low_key, pivot_key) in seen:
                        continue
                    seen.add((low_key, pivot_key))
                    kept.append(row)
                cleaned[name] = kept
                if rows:
                    print(f"  {language}-{pivot:3s} {name:28s} {len(rows):7,} -> "
                          f"{len(kept):7,}  (contaminated {leaked:,})", flush=True)

            for half in halves:
                name = f"finetrans_{half}"
                rows = cleaned.get(name) or []
                if not rows:
                    print(f"  {language}-{pivot}: {name} is empty, skipping", flush=True)
                    continue
                write_arm(manifest, language, pivot, name, rows, dev, test, seed=seed)
                matched = sample_by_document(cleaned["ours"], len(rows), seed)
                write_arm(manifest, language, pivot, f"ours_matched_{name}", matched,
                          dev, test, seed=seed)


def build_finetrans_domain_matched_arms(manifest: dict, languages: list[str],
                                        seed: int) -> None:
    """Cut the non-Wikipedia half of FineTranslations to the Wikipedia half's word count.

    This is the only size-matched FineTranslations comparison that isolates one variable.
    Both sides are the same corpus filtered the same way, machine-translated by the same
    system, at the same paragraph granularity -- 149 to 199 English words a record on either
    side -- so once the text volume is equalised the remaining difference is the domain the
    pages were crawled from. Set against ``ours`` instead, segmentation (sentence against
    paragraph), domain and human-against-machine provenance all vary at once, and matching on
    words does not repair that; it only removes one of the three.

    Only the non-Wikipedia side is written. Wikipedia is the smaller half in every pair, so
    it is the budget rather than the thing cut, which also leaves its already-scored cells
    untouched.

    The cut is by whole documents, so the result lands at or just above the budget rather
    than exactly on it -- a paragraph is never split, because half a paragraph is not a
    record either corpus contains. Both figures are printed for every pair.
    """
    for language in languages:
        if language not in LANGUAGES:
            continue
        for pivot in LANGUAGES[language]["pivots"]:
            if pivot != "en":          # FineTranslations pairs every language with English
                continue
            folder = WORK / "arms" / f"{language}-{pivot}"
            reference = folder / "ours"
            if not (reference / "test.jsonl").exists():
                print(f"[skip] {language}-{pivot}: not prepared yet", flush=True)
                continue
            test = load_jsonl(reference / "test.jsonl")
            dev = load_jsonl(reference / "dev.jsonl")
            # Re-screened against the splits actually on disk rather than trusted from the
            # earlier pass: this arm is a different slice of the same pool, and a pair that
            # was never sampled before has never been checked before.
            forbidden = {text_key(row["low"]) for row in test + dev}
            forbidden |= {text_key(row["pivot"]) for row in test + dev}

            def clean(rows: list[dict]) -> list[dict]:
                kept, seen = [], set()
                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:
                        continue
                    if (low_key, pivot_key) in seen:
                        continue
                    seen.add((low_key, pivot_key))
                    kept.append(row)
                return kept

            wiki = clean(list(finetrans_pairs(language, pivot, domain="wiki")))
            nonwiki = clean(list(finetrans_pairs(language, pivot, domain="nonwiki")))
            if not wiki or not nonwiki:
                print(f"  {language}-{pivot}: one half of FineTranslations is empty, skipping",
                      flush=True)
                continue
            budget = sum(pivot_words(row) for row in wiki)
            if not budget:
                print(f"  {language}-{pivot}: finetrans_wiki has no pivot text, skipping",
                      flush=True)
                continue
            cut = sample_by_word_budget(nonwiki, budget, seed)
            if not cut:
                print(f"  {language}-{pivot}: came out empty at a {budget:,}-word budget, "
                      "skipping", flush=True)
                continue
            got = sum(pivot_words(row) for row in cut)
            full = sum(pivot_words(row) for row in nonwiki)
            print(f"  {language}-{pivot:3s} finetrans_nonwiki_matched_wiki "
                  f"{len(cut):7,} pairs / {got:9,} words   against finetrans_wiki: "
                  f"{len(wiki):7,} pairs / {budget:9,} words  "
                  f"(uncut non-wiki was {len(nonwiki):,} pairs / {full:,} words, "
                  f"{full / max(budget, 1):.1f}x)", flush=True)
            write_arm(manifest, language, pivot, "finetrans_nonwiki_matched_wiki",
                      cut, dev, test, seed=seed)


def build_finetrans_wordmatched_arms(manifest: dict, languages: list[str],
                                     seed: int) -> None:
    """Cut FineTranslations to the word count of the ours arm it is read against.

    The comparison these replace was matched on pair count, and a pair is not the same
    object on the two sides: measured on the English side, bar-en is 12.9 words per pair in
    our corpus and 178.9 in FineTranslations, which translates whole FineWeb2 documents with
    Gemma3 27B. So every "matched size" cell gave FineTranslations roughly twelve times the
    text, none of it truncated at --max-length 512. Its twelve wins over our size-matched
    corpus therefore measured volume as much as anything else.

    Only the FineTranslations side is rewritten. The ours arms keep their bytes, which is
    what lets the runs already scored against them stand -- and it means the budget here has
    to be recomputed from the same seed and the same sampler the existing arm was built
    with, rather than read off a file, so the two are guaranteed to describe the same slice.

    What this cannot equalise is epochs. Equal words in records of unequal length means
    unequal record counts, so at a fixed step budget the word-cut arm sees its text far more
    often than ours sees its own. --patience is the control for that; the sizes printed below
    are what a reader needs to judge it, so they are printed for both sides.
    """
    plans = [("finetrans_clean", "ours_matched_finetrans", "finetrans_wordmatched"),
             ("finetrans_wiki", "ours_matched_finetrans_wiki",
              "finetrans_wordmatched_wiki"),
             ("finetrans_nonwiki", "ours_matched_finetrans_nonwiki",
              "finetrans_wordmatched_nonwiki")]
    for language in languages:
        if language not in LANGUAGES:
            continue
        for pivot in LANGUAGES[language]["pivots"]:
            if pivot != "en":          # FineTranslations pairs every language with English
                continue
            folder = WORK / "arms" / f"{language}-{pivot}"
            reference = folder / "ours"
            if not (reference / "test.jsonl").exists():
                print(f"[skip] {language}-{pivot}: not prepared yet", flush=True)
                continue
            test = load_jsonl(reference / "test.jsonl")
            dev = load_jsonl(reference / "dev.jsonl")
            forbidden = {text_key(row["low"]) for row in test + dev}
            forbidden |= {text_key(row["pivot"]) for row in test + dev}

            def clean(rows: list[dict]) -> list[dict]:
                kept, seen = [], set()
                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:
                        continue
                    if (low_key, pivot_key) in seen:
                        continue
                    seen.add((low_key, pivot_key))
                    kept.append(row)
                return kept

            ours = clean(list(ours_pairs(language, pivot)))
            for source, ours_arm, name in plans:
                domain = {"finetrans_clean": None, "finetrans_wiki": "wiki",
                          "finetrans_nonwiki": "nonwiki"}[source]
                rows = clean(list(finetrans_pairs(language, pivot, domain=domain)))
                if not rows:
                    print(f"  {language}-{pivot}: {source} is empty, skipping", flush=True)
                    continue
                # The budget, rebuilt exactly as the ours arm it is compared against was.
                matched = sample_by_document(ours, len(rows), seed)
                budget = sum(pivot_words(row) for row in matched)
                if not budget:
                    print(f"  {language}-{pivot}: {ours_arm} has no pivot text, skipping",
                          flush=True)
                    continue
                cut = sample_by_word_budget(rows, budget, seed)
                if not cut:
                    print(f"  {language}-{pivot}: {name} came out empty at a {budget:,}-word "
                          "budget, skipping", flush=True)
                    continue
                got = sum(pivot_words(row) for row in cut)
                print(f"  {language}-{pivot:3s} {name:32s} {len(cut):7,} pairs / "
                      f"{got:9,} words   against {ours_arm}: {len(matched):7,} pairs / "
                      f"{budget:9,} words  (was {len(rows):,} pairs / "
                      f"{sum(pivot_words(r) for r in rows):,} words)", flush=True)
                write_arm(manifest, language, pivot, name, cut, dev, test, seed=seed)


def build_pooled_arms(manifest: dict, languages: list[str], seed: int) -> None:
    """Build the arms that pool training data across pivots and across sibling languages.

    A post-pass, because these arms need data from language-pivot pairs other than their
    own and the main loop only ever sees one pair at a time. They read the train files the
    main loop has already written, so a pooled arm is exactly the union of arms that have
    each been reported, not a separately mined corpus.

    Two arms, and they exist because they are the only claims in this project that our
    corpus can make and no rival can:

      ours_multipivot    Gilaki paired with English AND with Persian in one model. Every
                         rival covers one pivot.
      ours_multilingual  all the languages sharing a pivot and a script in one model. PARME
                         is two languages but publishes no multilingual system; Lin et al.
                         and FineTranslations are compared here one language at a time.

    Each row carries the language and pivot it came from, so training can set NLLB's tags
    per example instead of per run. Without that the pooled data would be fed to the model
    under the wrong language tag, which is worse than not pooling at all.

    The contamination gate runs again here, against the primary pair's own test set. It has
    to: the rows being pooled in were only ever checked against *their* test set, and for
    one language across two pivots those two test sets are not the same sentences.
    """
    def read(language: str, pivot: str) -> list[dict]:
        path = WORK / "arms" / f"{language}-{pivot}" / "ours" / "train.jsonl"
        if not path.exists():
            return []
        rows = load_jsonl(path)
        for row in rows:
            # Stamped, not inferred later from the file it sits in: once these are unioned
            # the file no longer says which pair a row came from.
            # Named tag_* because `pivot` is already this row's pivot-side text.
            row["tag_language"] = language
            row["tag_pivot"] = pivot
        return rows

    for language in languages:
        for pivot in LANGUAGES[language]["pivots"]:
            own = read(language, pivot)
            if not own:
                continue
            folder = WORK / "arms" / f"{language}-{pivot}"
            dev = load_jsonl(folder / "ours" / "dev.jsonl")
            test = load_jsonl(folder / "ours" / "test.jsonl")
            forbidden = {text_key(row[side]) for row in test + dev
                         for side in ("low", "pivot") if row.get(side)}

            additions = {
                "ours_multipivot": [read(language, other)
                                    for other in LANGUAGES[language]["pivots"]
                                    if other != pivot],
                "ours_multilingual": [read(sibling, pivot)
                                      for sibling in sibling_languages(language)],
            }
            for arm_name, extra_sets in additions.items():
                extra = [row for rows in extra_sets for row in rows]
                if not extra:
                    continue            # no sibling or no second pivot: skip, do not fake it
                rows, seen, leaked = list(own), set(), 0
                for row in own:
                    seen.add((text_key(row["low"]), text_key(row["pivot"])))
                for row in extra:
                    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
                    if (low_key, pivot_key) in seen:
                        continue
                    seen.add((low_key, pivot_key))
                    rows.append(row)
                sources = sorted({f"{r['tag_language']}-{r['tag_pivot']}"
                                  for r in rows if r.get("tag_language")})
                print(f"  {language}-{pivot:3s} {arm_name:18s} {len(own):7,} + "
                      f"{len(rows) - len(own):7,} = {len(rows):7,}  "
                      f"(contaminated {leaked:,}; pools {', '.join(sources)})", flush=True)
                write_arm(manifest, language, pivot, arm_name, rows, dev, test, seed=seed)


def reindex_arms(languages: list[str]) -> int:
    """Rebuild manifest entries from arm files already on disk, writing no data.

    The repair path for a manifest that lost a language. Re-running prepare would also
    restore the entries, but it would rewrite train/dev/test -- and 85 scored runs are tied
    to those exact files, so regenerating them to fix a bookkeeping error is the wrong
    trade. Counts and checksums are read back from the files, so the restored entry is
    measured rather than assumed.
    """
    path = WORK / "prepare_manifest.json"
    manifest = load_json(path) if path.exists() else {"arms": {}}
    manifest.setdefault("arms", {})
    wanted = {f"{language}-{pivot}" for language in languages
              for pivot in LANGUAGES[language]["pivots"]}
    restored = 0
    for folder in sorted((WORK / "arms").glob("*/*")):
        if not folder.is_dir() or folder.parent.name not in wanted:
            continue
        key = f"{folder.parent.name}/{folder.name}"
        files = {name: folder / f"{name}.jsonl" for name in ("train", "dev", "test")}
        if not all(each.exists() for each in files.values()):
            print(f"  skip {key}: incomplete on disk")
            continue
        rows = {name: load_jsonl(each) for name, each in files.items()}
        language, pivot = folder.parent.name.split("-", 1)
        manifest["arms"][key] = {
            "language": language, "pivot": pivot, "arm": folder.name,
            "reindexed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            # Deliberately absent: the seed. These files were written by a prepare run whose
            # seed this process never saw, and inventing one would be worse than a gap.
            "seed": None,
            **{name: len(each) for name, each in rows.items()},
            "origins": sorted({row["origin"] for row in rows["train"] if "origin" in row}),
            "checksums": {f"{name}.jsonl": sha256_file(each)
                          for name, each in files.items()},
            "test_sources": sorted({row["source"] for row in rows["test"]
                                    if row.get("source")}),
        }
        restored += 1
        print(f"  {key}: train {len(rows['train']):,} dev {len(rows['dev']):,} "
              f"test {len(rows['test']):,}")
    save_json(path, manifest)
    print(f"\nreindexed {restored} arms; manifest now lists {len(manifest['arms'])}")
    return 0


def write_arm(manifest, language, pivot, arm, train, dev, test, *, seed=None) -> 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,
        # Per-arm, because arms carried over from an earlier prepare no longer share the
        # top-level built_at or seed. Without these a mixed manifest cannot be audited.
        "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "seed": seed,
        "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.
    # The language-pivot prefixes every group key. A pooled arm holds several pairs in one
    # file, and without the prefix a document id shared across two languages would merge a
    # Gilaki sentence onto a Mazanderani one -- and the random fallback would mix languages
    # inside a single training example.
    def pair_of(row: dict) -> str:
        return f"{row.get('tag_language') or ''}-{row.get('tag_pivot') or ''}"

    groups: dict[str, list[dict]] = {}
    loose: dict[str, list[dict]] = {}
    for row in rows:
        pair = pair_of(row)
        if unit == "paragraph" and row.get("paragraph_id"):
            groups.setdefault(f"{pair}|{row['paragraph_id']}", []).append(row)
        elif row.get("document_id"):
            groups.setdefault(f"{pair}|{row['document_id']}", []).append(row)
        else:
            loose.setdefault(pair, []).append(row)
    for pair, pair_rows in loose.items():
        shuffler = random.Random(seed)
        shuffler.shuffle(pair_rows)
        for index in range(0, len(pair_rows), window):
            groups[f"{pair}|random-{index}"] = pair_rows[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"),
                          "tag_language": chunk[0].get("tag_language"),
                          "tag_pivot": chunk[0].get("tag_pivot")})
    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"),
                              "tag_language": chunk[0].get("tag_language"),
                              "tag_pivot": chunk[0].get("tag_pivot")})
    # 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 check_sampling_strategy(trainer, rows) -> None:
    """Confirm --group-by-length actually reordered the data, rather than being ignored.

    The flag it sets is upstream configuration, and upstream has already renamed it once:
    group_by_length=True became train_sampling_strategy="group_by_length" in transformers 5.
    A value that stops being recognised does not raise -- Trainer's own ``else`` branch
    returns a RandomSampler -- so the run would train in random order while its path says
    "gbl" and its metadata claims the saving. That is the kind of silence that gets written
    into a paper, so it is checked rather than trusted.

    Asserting on the sampler's class, not on the batch widths: the sampler shuffles within
    megabatches on purpose, so a short dataset can legitimately come back in an order that
    looks unsorted.
    """
    try:
        from transformers.trainer_pt_utils import LengthGroupedSampler
    except ImportError as exc:                 # pragma: no cover - upstream layout change
        raise SystemExit(
            f"--group-by-length cannot be verified: {exc}. Refusing to claim a saving that "
            "has not been confirmed; drop the flag or fix the import.")
    sampler = trainer._get_train_sampler(rows)
    if not isinstance(sampler, LengthGroupedSampler):
        raise SystemExit(
            f"--group-by-length was requested but Trainer built a {type(sampler).__name__}, "
            "not a LengthGroupedSampler. The option this maps to has been renamed or removed "
            f"in transformers {__import__('transformers').__version__}; the run would train "
            "in random order while its path and metadata claimed otherwise. Fix the mapping "
            "in train_causal_lora before running the sweep.")


def effective_batch(args) -> int:
    """Examples per optimizer update, as the training path for this model actually computes it.

    The adapter path quarters the micro-batch and doubles accumulation for memory, so the same
    --batch-size 16 --accumulation 4 means 64 examples per update on a seq2seq arm and 32 on an
    adapter arm. Under a budget fixed in updates that is a 2x difference in data seen, which is
    why it has to be computed rather than assumed equal across the columns.
    """
    batch = getattr(args, "batch_size", 16)
    accumulation = getattr(args, "accumulation", 4)
    if MODELS.get(getattr(args, "model", ""), {}).get("kind") == "causal_lora":
        return max(batch // 4, 1) * (accumulation * 2)
    return batch * accumulation


def default_effective_batch(args) -> int:
    """What this path has always run at, so existing run directories keep their names."""
    if MODELS.get(getattr(args, "model", ""), {}).get("kind") == "causal_lora":
        return 32
    return 64


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}")
    # Effective batch, but only when it differs from this path's own default. Batch and
    # accumulation are otherwise absent from the run path on purpose: PAPER_MEM_nllb1b3 trades
    # 16x4 for 8x8, which is the same 64 examples per update and therefore the same
    # measurement, so it must land in the same directory. Changing the *product* is a
    # different measurement and must not overwrite its own control.
    #
    # The reference is per path, not one number, because the two paths have always run at
    # different products: seq2seq at 16x4 = 64 and the adapter at (16//4)x(4*2) = 32. Using 64
    # for both would stamp eb32 onto every adapter run already on disk and orphan the column.
    effective = effective_batch(args)
    if effective != default_effective_batch(args):
        parts.append(f"eb{effective}")
    # Length-grouped batching changes which examples share a batch, and therefore the
    # gradient noise, so a grouped run is not the same measurement as a random-order one and
    # must not overwrite it. Measured on glk-en/ours with Gemma-4-12B: at micro-batch 8 only
    # 54.3% of the padded tokens are real content under random order against 99.3% grouped,
    # so this is worth about 45% of the compute -- but it is a change to the training
    # distribution, not just to its arithmetic, which is why it earns a segment where
    # PAPER_MEM's 8x8-for-16x4 swap does not.
    if getattr(args, "group_by_length", False):
        parts.append("gbl")
    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}")
    # The LoRA path takes its rate from --lora-learning-rate and ignores --learning-rate
    # entirely, so the adapter needs its own path segment. Without this a sweep over
    # --lora-learning-rate writes every rate to the same directory and only the last
    # survives, while a sweep over --learning-rate produces four differently-named
    # directories holding four identically-trained models -- which would read as "LoRA is
    # insensitive to its learning rate".
    if abs(getattr(args, "lora_learning_rate", 2e-4) - 2e-4) > 1e-12:
        parts.append(f"loralr{args.lora_learning_rate:g}")
    if getattr(args, "lora_rank", 16) != 16:
        parts.append(f"lorar{args.lora_rank}")
    if getattr(args, "warmup_steps", 0):
        parts.append(f"wu{args.warmup_steps}")
    if getattr(args, "max_steps", 0):
        parts.append(f"ms{args.max_steps}")
    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)
    # Dropout has to be set here, as a construction argument, not afterwards on model.config.
    # Marian and M2M100 copy config.dropout into a float attribute on every layer while the
    # model is being built and then call F.dropout(p=self.dropout); there is no nn.Dropout
    # module to reconfigure. Assigning model.config.dropout after from_pretrained therefore
    # changed the recorded recipe and nothing else, which is how `--dropout 0.3` came to move
    # marian's test chrF++ by 0.02 -- run-to-run noise, not a measurement of dropout.
    overrides = {}
    if args.dropout is not None:
        overrides = {"dropout": args.dropout, "activation_dropout": args.dropout,
                     # attention_dropout is raised only to the same value: the low-resource
                     # reports that motivate 0.3 found going beyond it unhelpful.
                     "attention_dropout": args.dropout}
    model = AutoModelForSeq2SeqLM.from_pretrained(base, dtype=torch.bfloat16, **overrides)
    if overrides:
        layer = model.base_model.encoder.layers[0]
        print(f"dropout set to {args.dropout} "
              f"(layer reads {getattr(layer, 'dropout', 'n/a')})", flush=True)
        if getattr(layer, "dropout", None) != args.dropout:
            raise SystemExit(f"--dropout {args.dropout} did not reach the layers; refusing to "
                             f"train a run that would be filed under a recipe it did not use")
    # 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})
    # A pooled arm mixes language-pivot pairs in one file, so the tags are a property of each
    # row rather than of the run. Every row of a normal arm simply resolves to the run's own
    # pair and the behaviour is unchanged.
    pooled = sorted({(row.get("tag_language") or args.language,
                      row.get("tag_pivot") or args.pivot)
                     for row in load_jsonl(folder / "train.jsonl")})
    tag_cache = {(args.language, args.pivot): tags}
    if model_spec.get("tagged") and len(pooled) > 1:
        for language, pivot in pooled:
            if (language, pivot) not in tag_cache:
                tag_cache[(language, pivot)] = language_tags(tokenizer, model,
                                                             language, pivot)
        print(f"pooled training over {len(pooled)} language-pivot pairs: "
              + ", ".join(f"{l}-{p}" for l, p in pooled), flush=True)

    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.

        Rows are grouped by their own language and pivot before encoding. Tokenizer tags are
        global mutable state, so encoding a mixed batch in one call would stamp every row
        with whichever pair was set last -- feeding Mazanderani to the model labelled as
        Gilaki, which is worse than not pooling at all.
        """
        encoded = []
        groups: dict[tuple, list[dict]] = {}
        for row in rows:
            key = (row.get("tag_language") or args.language,
                   row.get("tag_pivot") or args.pivot)
            groups.setdefault(key, []).append(row)
        for key, group_rows in groups.items():
            group_tags = tag_cache.get(key, tags)
            if model_spec.get("tagged"):
                source_tag, target_tag = (
                    (group_tags["low"], group_tags["pivot"]) if direction == "to_pivot"
                    else (group_tags["pivot"], group_tags["low"]))
                tokenizer.src_lang, tokenizer.tgt_lang = source_tag, target_tag
            source_side = "low" if direction == "to_pivot" else "pivot"
            target_side = "pivot" if direction == "to_pivot" else "low"
            # Tagged back-translation. The marker goes on the source and only when the
            # source is the machine-written side: a model trained on untagged synthetic
            # input learns to trust it as much as real input, while tagging lets it keep
            # the two apart and fall back on real-pair behaviour at test time, where no
            # marker is present. Marking a synthetic TARGET would instead teach the model
            # to emit the marker.
            sources = [((BT_TAG if (args.bt_tag
                                    and r.get("synthetic_side") == source_side) else "")
                        + r[source_side]) for r in group_rows]
            targets = [r[target_side] for r in group_rows]
            batch = tokenizer(sources, text_target=targets, truncation=True,
                              max_length=args.max_length)
            encoded.extend({"input_ids": batch["input_ids"][i],
                            "attention_mask": batch["attention_mask"][i],
                            "labels": batch["labels"][i]} for i in range(len(sources)))
        return encoded

    # "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"

    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_pairs = load_jsonl(folder / "dev.jsonl") if entry["dev"] else []
    held_back = 0
    if not dev_pairs:
        # bar-de has no dev split at all: no source in the evaluation corpus publishes
        # German-Bavarian development data. Training with eval_strategy="steps" and nothing
        # to evaluate leaves checkpoint selection and early stopping with no signal, and
        # selecting on the 78-sentence test set instead would be selection on test.
        #
        # So carve a dev split out of train, by document, and say so. Sampling whole
        # documents matters for the same reason it does when size-matching: loose sentences
        # drawn from a document corpus leave near-duplicate neighbours behind in train.
        wanted = min(500, max(50, len(raw_train) // 50))
        if len(raw_train) > wanted * 3:
            holdout = sample_by_document(raw_train, wanted, args.seed)
            keys = {id(row) for row in holdout}
            kept = [row for row in raw_train if id(row) not in keys]
            held_back = len(holdout)
            print(f"no dev split for {args.language}-{args.pivot}: holding back "
                  f"{held_back:,} training examples as dev", flush=True)
            raw_train, dev_pairs = kept, holdout
            train_rows = encode_all(raw_train)
    dev_rows = encode_all(dev_pairs) if dev_pairs 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"),
        # max_steps overrides the epoch count when set. It exists for the steps-matched
        # scale curve: with epochs fixed instead, a 1,000-pair arm gets 48 optimizer steps
        # and a 105,419-pair arm gets 4,944, so the curve varies data and training together
        # and cannot say which one the shape comes from.
        num_train_epochs=args.epochs,
        max_steps=args.max_steps if args.max_steps else -1,
        learning_rate=args.learning_rate,
        per_device_train_batch_size=args.batch_size,
        gradient_accumulation_steps=args.accumulation,
        # Deliberately 0 even when smoothing is wanted: see SmoothedTrainer below. Trainer's
        # own label_smoothing_factor pops ``labels`` out of the batch before the forward
        # pass, which leaves an encoder-decoder model with nothing to build its decoder
        # input from, and M2M100 then raises "cannot specify both decoder_input_ids and
        # decoder_inputs_embeds" -- a misleading message, because that guard is an XOR and
        # fires just as readily when both are absent. Smoothing is applied in the loss
        # instead, with labels left in place.
        label_smoothing_factor=0.0,
        # A ratio alone gives the small arms almost no warmup: 5% of 48 steps is 2, and 5%
        # of glk-en/human's 162 steps is 8. --warmup-steps sets a floor so a short run still
        # gets a real warmup, which is exactly where a high learning rate would otherwise
        # diverge in the first few updates.
        **({"warmup_steps": args.warmup_steps} if args.warmup_steps
           else {"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))
    # Plain padding. The model is not handed to the collator: with it, the collator adds
    # decoder_input_ids to every batch including the evaluation ones, and
    # predict_with_generate then passes that to generate() as a forced prefix -- so the dev
    # chrF++ used for checkpoint selection would be measured on teacher-forced output, not
    # on what the model actually produces.
    collator = DataCollatorForSeq2Seq(tokenizer)

    class SmoothedTrainer(Seq2SeqTrainer):
        """Label smoothing computed in the loss, with ``labels`` left in the batch.

        The reason for not using Trainer's own label_smoothing_factor is above. Keeping
        labels in the batch means the model shifts them into decoder_input_ids itself, which
        is the path every already-scored run took -- so turning smoothing on no longer
        changes anything else about how the model is driven.

        torch's cross_entropy does the smoothing natively and honours ignore_index, so the
        -100 label padding is handled rather than having to be masked by hand.
        """

        def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
            labels = inputs.get("labels")
            outputs = model(**inputs)
            if labels is None or not args.label_smoothing:
                loss = outputs.loss
            else:
                logits = outputs.logits
                loss = torch.nn.functional.cross_entropy(
                    logits.reshape(-1, logits.size(-1)).float(),
                    labels.reshape(-1),
                    ignore_index=-100,
                    label_smoothing=args.label_smoothing)
            return (loss, outputs) if return_outputs else loss

    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_class = SmoothedTrainer if args.label_smoothing else Seq2SeqTrainer
    trainer = trainer_class(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"))

    # The dev curve, kept so a recipe can be chosen without looking at the test set.
    #
    # This is not bookkeeping. Comparing recipes on test chrF++ and then reporting test
    # chrF++ is selection on the test set, and it inflates exactly the headline number this
    # paper rests on. Only train_loss was recorded before, which left no honest way to pick
    # between the recipe variants at all.
    history = [entry for entry in trainer.state.log_history if "eval_loss" in entry]
    dev = {
        "evaluations": len(history),
        "best_eval_loss": min((e["eval_loss"] for e in history), default=None),
        # Absent unless --select-on chrf, which is the only mode that generates on dev.
        "best_eval_chrf2pp": max((e["eval_chrf2pp"] for e in history
                                  if "eval_chrf2pp" in e), default=None),
        "final_eval_loss": history[-1]["eval_loss"] if history else None,
        # Which evaluation won, as a fraction of the run. A best at the very last step means
        # the run was still improving and the epoch budget, not the recipe, was the limit.
        "best_at_fraction": (
            round((max(range(len(history)),
                       key=lambda i: history[i].get("eval_chrf2pp",
                                                    -history[i]["eval_loss"])) + 1)
                  / len(history), 3) if history else None),
    }
    save_json(run / "dev_curve.json", {"history": history, **dev})

    save_json(run / "training_complete.json", {
        "dev": dev,
        "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,
        "warmup_steps": args.warmup_steps, "max_steps": args.max_steps,
        "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"}

# The ISO 639-3 code to report each language under. It differs from the key only for
# Alemannic, where the key is the Wikipedia prefix `als` and the correct code is `gsw`;
# writing `als` in a paper would name Tosk Albanian. Use this for anything a reader sees.
ISO_CODES = {"als": "gsw", "bar": "bar", "frr": "frr", "glk": "glk", "mzn": "mzn",
             "en": "eng", "de": "deu", "fa": "fas"}


def load_causal_base(base: str, model_name: str | None, dtype):
    """The pretrained LLM behind an adapter arm, under the class its architecture needs.

    ``model_name`` is the key in MODELS, not the Hub id, because the class is a property of
    our configuration rather than something to infer from the checkpoint at call time.
    """
    # Checked before transformers is imported: a typo in a model spec is a configuration
    # error and should say so on any machine, not only on one with torch installed.
    spec = MODELS.get(model_name or "", {})
    which = spec.get("loader", "causal")
    if which not in CAUSAL_LOADERS:
        raise SystemExit(f"{model_name}: unknown loader {which!r}; "
                         f"expected one of {sorted(CAUSAL_LOADERS)}")
    import transformers
    loader = getattr(transformers, CAUSAL_LOADERS[which], None)
    if loader is None:
        raise SystemExit(f"{CAUSAL_LOADERS[which]} is missing from transformers "
                         f"{transformers.__version__}; {model_name} cannot be loaded")
    return loader.from_pretrained(base, dtype=dtype)


# Gemma 4 emits reasoning as ``<|channel>thought\n...<channel|>``, and the 12B checkpoint
# emits the tags even with thinking off, with an empty body. A thought left in the
# hypothesis would be scored as if it were the translation, so it is removed before scoring
# and the removals are counted: a non-zero count on a model we believe has reasoning
# disabled is a finding, not housekeeping.
THOUGHT_CHANNEL = re.compile(r"<\|channel>\s*thought.*?<channel\|>", re.S)
THINK_TOKENS = re.compile(r"<\|/?think\|>|<\|channel>|<channel\|>")


def strip_reasoning(text: str) -> tuple[str, bool]:
    """A hypothesis with any reasoning channel removed, and whether one was present."""
    cleaned = THOUGHT_CHANNEL.sub(" ", text)
    cleaned, count = THINK_TOKENS.subn(" ", cleaned)
    had = count > 0 or cleaned != text
    return " ".join(cleaned.split()), had


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 dev_chrf_causal(args, model, tokenizer, folder, entry):
    """Dev chrF++ for the LoRA arm: one greedy pass over dev with the just-trained adapter.

    The seq2seq arms generate on dev during training under `--select-on chrf`, so their dev
    number is chrF++. The LoRA path reported dev loss only, which left the recipe selector
    ranking this architecture's learning rates on loss -- and loss is measurably the wrong
    currency here: on NLLB it ranked 5e-4 *below* 1e-4 while the test set made 5e-4 the best
    rate of the sweep. Choosing Qwen's rate that way would defeat the purpose of sweeping per
    architecture.

    This does not select the checkpoint -- the LoRA path saves one adapter at the end, so
    there is nothing to select between. It measures the recipe, once, after training, which is
    all the selector needs. Cost is a single generation pass, minutes against an hour of
    training.
    """
    import torch

    if not (folder / "dev.jsonl").exists() or not entry.get("dev"):
        return None
    pairs = load_jsonl(folder / "dev.jsonl")
    if not pairs:
        return None
    # Same convention as the test path: "low" is the low-resource side, "pivot" the other.
    sources = [r["low"] if args.direction == "to_pivot" else r["pivot"] for r in pairs]
    references = [r["pivot"] if args.direction == "to_pivot" else r["low"] for r in pairs]
    if not sources:
        return None

    was_padding_side = tokenizer.padding_side
    tokenizer.padding_side = "left"          # required for batched decoder-only generation
    model.eval()
    hypotheses: list[str] = []
    batch_size = max(args.generation_batch_size // 3, 1)
    try:
        for start in range(0, len(sources), batch_size):
            chunk = sources[start:start + batch_size]
            prompts = [lora_prompt(args.language, args.pivot, args.direction, 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)
            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()
                # Same stripping as the test-time path. This score is what the recipe
                # selector ranks learning rates on, so leaving a reasoning channel in here
                # would corrupt the rate choice itself, not just one reported number.
                text, _ = strip_reasoning(text)
                hypotheses.append(text.split("\n")[0].strip())
            print(f"  dev generated {len(hypotheses)}/{len(sources)}", end="\r", flush=True)
    finally:
        tokenizer.padding_side = was_padding_side
        model.train()

    import sacrebleu
    score = sacrebleu.CHRF(word_order=2).corpus_score(hypotheses, [references]).score
    print(f"dev chrF++ {score:.2f} over {len(hypotheses)} sentences", flush=True)
    return score


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 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 = load_causal_base(base, args.model, torch.bfloat16)
    # alpha tracks 2*r, the usual convention: it keeps the effective update scale
    # (alpha/r) constant as the rank changes, so a rank sweep measures capacity rather than
    # capacity confounded with a change in update magnitude.
    model = get_peft_model(model, LoraConfig(
        r=args.lora_rank, lora_alpha=2 * args.lora_rank, lora_dropout=0.05,
        bias="none", task_type="CAUSAL_LM",
        # The same four projections for every arm, so the LLM comparison is a size comparison
        # and not a comparison of two adapter topologies. Checked against Gemma-4-12B on the
        # meta device (scripts/gemma_lora_targets.py) before committing a sweep to it: all 184
        # matches are under model.language_model.layers.*.self_attn, so nothing attaches to
        # the vision or audio towers of that encoder-free multimodal checkpoint, and the
        # adapter is 0.1642% of the model against Qwen3-4B's 0.2924%. Eight of Gemma's 48
        # layers carry q/k/o but no v_proj -- its attention is hybrid -- which is why the
        # counts there are 48/48/40/48 rather than four equal numbers.
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]))
    model.print_trainable_parameters()
    # PEFT raises when nothing matches, but it is happy to match too little -- and on a
    # multimodal checkpoint the same projection names can appear outside the language model.
    # A share far from the ~0.3% Qwen3-4B reports at rank 16 means the adapter attached to
    # the wrong set of modules, which would show up only as an inexplicably weak arm.
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    total = sum(p.numel() for p in model.parameters())
    share = trainable / total if total else 0
    if not 0.0001 <= share <= 0.05:
        raise SystemExit(f"LoRA attached to {share:.4%} of {args.model} "
                         f"({trainable:,} of {total:,} parameters); expected 0.01%-5%. "
                         "Check target_modules against this architecture.")

    if args.gradient_checkpointing:
        # Why this exists: a bf16 Gemma-4-12B process measures about 58 GB -- 23.9 for the
        # weights plus roughly twice Qwen3-4B's activations, since 48 layers x 3840 hidden is
        # 2.0x 36 x 2560 -- so two fit on the 143.8 GB card and three do not. Recomputing
        # activations in the backward pass brings it to about 35 GB and lets three streams
        # run. It is the cheap way to buy that concurrency: the gradients are the same ones,
        # so unlike 4-bit quantisation it leaves the arm comparable to the bf16 Qwen column.
        #
        # use_reentrant=False is not optional here. Under the reentrant implementation the
        # inputs to each checkpointed block arrive detached, and with every base weight
        # frozen the backward pass finds nothing requiring grad and quietly produces zero
        # adapter gradients -- print_trainable_parameters still reports 0.29% and the loss
        # simply never moves. enable_input_require_grads is the belt to that braces.
        model.enable_input_require_grads()
        model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={
            "use_reentrant": False})
        if getattr(model.config, "use_cache", False):
            model.config.use_cache = False   # incompatible, and transformers only warns

    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"]
                # The row's own pair, not the run's. A pooled arm mixes language-pivot pairs
                # in one file: ours_multipivot for glk-en also holds the glk-fa rows. Built
                # from args.pivot, every one of those was presented as "Translate the
                # following Gilaki sentence into English" with a Persian answer, so the model
                # was taught to answer an English prompt in Persian about half the time.
                # It shows up exactly as you would expect -- glk-en multipivot 10.18 against
                # 19.85 for the plain arm, bar-de 37.70 against 58.71 -- which reads as a
                # finding about pooling and is a labelling bug. The seq2seq path groups rows
                # by these same tags before setting the tokenizer's language tags; this is
                # the same fix in the one path that did not get it. A normal arm's rows have
                # no tags and resolve to the run's own pair, so nothing else changes.
                prompt = lora_prompt(row.get("tag_language") or args.language,
                                     row.get("tag_pivot") or 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"))
    # Dev rows, encoded the same way, so this path reports a dev curve. Without one the
    # recipe selector has nothing to rank LoRA runs by and would silently fall back to the
    # library default -- leaving the one model in the ladder whose rate was never measured.
    dev_rows = (encode(load_jsonl(folder / "dev.jsonl"))
                if (folder / "dev.jsonl").exists() and entry.get("dev") else None)
    arguments = TrainingArguments(
        output_dir=str(run / "checkpoints"), num_train_epochs=args.epochs,
        # Two things this path was missing, both of which made a Qwen run cost 15 hours and
        # end on whatever the last update happened to produce:
        #
        # 1. max_steps. Without it --max-steps was silently ignored here, so while every
        #    seq2seq arm stopped at 3,000 updates, Qwen trained the full 12 epochs -- about
        #    39,000 updates on bar-de's 104,418 pairs at this path's effective batch of 32.
        # 2. Early stopping. eval_strategy was "epoch", and at 3,000 updates x 32 = 96,000
        #    examples a six-figure arm does not finish one epoch, so the dev set was never
        #    evaluated at all: no dev curve, nothing for --patience to act on, and
        #    save_strategy="no" meant the best adapter could not have been restored anyway.
        #    Stopping on dev loss is what the seq2seq path does on dev chrF++; loss is the
        #    only in-training signal available here, because chrF++ for a causal model needs
        #    a generation pass and is computed once, after training, by dev_chrf_causal.
        max_steps=args.max_steps if args.max_steps else -1,
        learning_rate=args.lora_learning_rate,
        **({"eval_strategy": "steps", "eval_steps": args.eval_steps,
            "save_strategy": "steps", "save_steps": args.eval_steps, "save_total_limit": 1,
            "load_best_model_at_end": True, "metric_for_best_model": "eval_loss",
            "greater_is_better": False,
            "per_device_eval_batch_size": max(args.batch_size // 4, 1)} if dev_rows else {}),
        per_device_train_batch_size=max(args.batch_size // 4, 1),
        gradient_accumulation_steps=args.accumulation * 2,
        # A ratio alone gives the small arms almost no warmup: 5% of 48 steps is 2, and 5%
        # of glk-en/human's 162 steps is 8. --warmup-steps sets a floor so a short run still
        # gets a real warmup, which is exactly where a high learning rate would otherwise
        # diverge in the first few updates.
        **({"warmup_steps": args.warmup_steps} if args.warmup_steps
           else {"warmup_ratio": 0.05}),
        # Renamed upstream: transformers 5.x dropped group_by_length=True in favour of
        # train_sampling_strategy="group_by_length". Passing the old keyword raises
        # TypeError, which at least fails loudly, but the hazard worth guarding is the other
        # direction -- a future rename that leaves our value unrecognised would reorder
        # nothing and report a 45% saving we never got. check_sampling_strategy below fails
        # the run instead.
        train_sampling_strategy=("group_by_length" if args.group_by_length else "random"),
        weight_decay=0.01, bf16=True, logging_steps=50,
        # Without a dev split there is nothing to select on, so keep the old behaviour and
        # write no checkpoints. Passing save_strategy here unconditionally would collide
        # with the one in the dict above -- Python raises TypeError on a duplicate keyword.
        **({} if dev_rows else {"save_strategy": "no"}),
        report_to=[], seed=args.seed)
    callbacks = []
    # `and args.patience`, matching the seq2seq path: --patience defaults to 0, and
    # EarlyStoppingCallback(0) halts at the first evaluation that fails to improve rather
    # than disabling early stopping. Without this guard a run launched with no recipe --
    # which is what happens when the recipe selector has no data to rank -- stopped after a
    # couple of hundred updates and looked like a fast success.
    if dev_rows and args.patience:
        from transformers import EarlyStoppingCallback
        callbacks.append(EarlyStoppingCallback(early_stopping_patience=args.patience))
    trainer = Trainer(model=model, args=arguments, train_dataset=train_rows,
                      eval_dataset=dev_rows, data_collator=collate,
                      callbacks=callbacks or None)
    if args.group_by_length:
        check_sampling_strategy(trainer, train_rows)
    # Fingerprint of the adapter before training, so "the optimiser never moved it" cannot
    # pass as a finished run. The attachment assertion above cannot see this: a checkpointed
    # graph that delivers zero gradient still reports 0.29% trainable, still writes an
    # adapter, and still scores -- as the untrained base model, which would read as an
    # honest result for a 12B arm rather than as a bug.
    before = sum(float(p.detach().float().sum()) for p in model.parameters()
                 if p.requires_grad)
    result = trainer.train()
    after = sum(float(p.detach().float().sum()) for p in model.parameters()
                if p.requires_grad)
    if before == after:
        raise SystemExit(
            "no adapter parameter changed during training; the gradients are not reaching "
            "the LoRA weights. With --gradient-checkpointing this is the reentrant-autograd "
            "failure: every base weight is frozen, so a detached block input leaves nothing "
            "requiring grad. Check use_reentrant=False and enable_input_require_grads.")
    model.save_pretrained(str(run / "model"))
    tokenizer.save_pretrained(str(run / "model"))
    history = [e for e in trainer.state.log_history if "eval_loss" in e]
    dev = {"evaluations": len(history),
           "best_eval_loss": min((e["eval_loss"] for e in history), default=None),
           "best_eval_chrf2pp": dev_chrf_causal(args, model, tokenizer, folder, entry),
           "final_eval_loss": history[-1]["eval_loss"] if history else None}
    save_json(run / "dev_curve.json", {"history": history, **dev})
    save_json(run / "training_complete.json", {
        "dev": dev,
        "base": base, "model": args.model, "direction": args.direction,
        "trained_directions": directions, "adapter": "lora",
        "train_pairs": entry["train"], "epochs": args.epochs,
        # Recorded under both names: `learning_rate` is what this path actually used, and
        # `lora_learning_rate` is the flag that sets it, which is what the selector has to
        # hand back as a reproducible command line.
        "learning_rate": args.lora_learning_rate,
        "lora_learning_rate": args.lora_learning_rate,
        "lora_rank": args.lora_rank,
        # The literal, not args.select_on, which main() has already normalised to it for
        # this path. Belt and braces on the one field a reviewer would read as a claim about
        # how the checkpoint was chosen: eval_loss, unconditionally, per
        # metric_for_best_model above.
        "select_on": "loss",
        "gradient_checkpointing": bool(args.gradient_checkpointing),
        # Recorded because it changes the training distribution, so a reader comparing a
        # grouped run with an ungrouped one needs to see it without reading the path.
        # check_sampling_strategy has already confirmed it took effect.
        "group_by_length": bool(args.group_by_length),
        "effective_batch": effective_batch(args),
        "patience": args.patience, "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 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 = load_causal_base(config["base"], config.get("model") or args.model,
                             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] = []
    reasoning = 0
    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()
            # Reasoning first, then the first line: a thought channel can contain newlines,
            # so taking the first line before stripping it would keep "<|channel>thought"
            # and throw the translation away.
            text, had_reasoning = strip_reasoning(text)
            reasoning += had_reasoning
            hypotheses.append(text.split("\n")[0].strip())
        print(f"  generated {len(hypotheses)}/{len(inputs)}", end="\r", flush=True)
    if reasoning:
        # Not fatal -- the text is already stripped -- but it means the model emitted
        # reasoning we believed was off, which belongs in the record rather than in a log
        # line nobody reads.
        print(f"\n  stripped reasoning from {reasoning}/{len(inputs)} hypotheses", 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():
        # Name the trained models that *do* exist for this arm. Train and evaluate are two
        # processes, so a change to how the recipe suffix is built lands between them for any
        # run in flight: two Qwen arms trained into .../to_pivot/sel-chrf/pat5/... and were
        # then evaluated against .../to_pivot/pat5/..., and "train first" sent the reader
        # looking for a training failure that had not happened -- the 67-minute adapter was
        # sitting one directory away. Listing the siblings turns that into a one-line
        # diagnosis, and the recovery into a move rather than a retrain.
        base = WORK / "runs" / f"{args.language}-{args.pivot}" / args.arm / args.model
        siblings = sorted(str(p.parent.relative_to(base)) for p in base.rglob("model")
                          if p.is_dir()) if base.exists() else []
        hint = ("; trained models under this arm: " + ", ".join(siblings[:6])
                if siblings else "; no trained model exists under this arm at all")
        raise SystemExit(f"no trained model at {trained / 'model'}; train first{hint}")

    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,
        # The recipe, recorded per run. Without these the run directory is the only record
        # of what was varied, and the paper's tables would have to infer the experimental
        # condition from a path -- which is how an ablation gets mislabelled.
        "recipe": {"label_smoothing": args.label_smoothing, "dropout": args.dropout,
                   "select_on": args.select_on, "patience": args.patience,
                   "epochs": args.epochs, "learning_rate": args.learning_rate,
                   "warmup_steps": args.warmup_steps,
                   "max_steps": args.max_steps, "seed": args.seed},
        "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


# sacrebleu keys its results by each metric's own display name, not by the keys handed to
# PairedTest, so a caller asking for "chrf2pp" gets back "chrF2++". Mapping them back to the
# names used everywhere else in this file keeps the footgun in one place.
PAIRED_METRICS = {"chrF2++": "chrf2pp", "BLEU": "bleu", "TER": "ter"}
# TER counts edits, so a negative delta is an improvement. Anything reading a delta's sign
# has to know which way each metric runs.
LOWER_IS_BETTER = {"ter"}


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.

    Returns one entry per metric keyed by this file's own names, each with an `improved`
    flag that already accounts for TER running the other way.
    """
    import sacrebleu
    from sacrebleu.significance import PairedTest
    test = PairedTest([("baseline", baseline), ("system", system)],
                      {"chrf2pp": sacrebleu.CHRF(word_order=2),
                       "bleu": sacrebleu.BLEU(),
                       "ter": sacrebleu.TER()},
                      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
        delta = system_result.score - base_result.score
        name = PAIRED_METRICS.get(metric, metric)
        out[name] = {"baseline": base_result.score, "system": system_result.score,
                     "delta": delta,
                     "lower_is_better": name in LOWER_IS_BETTER,
                     "improved": delta < 0 if name in LOWER_IS_BETTER else delta > 0,
                     "p_value": system_result.p_value,
                     "baseline_ci": base_result.ci, "system_ci": system_result.ci}
    return out


# Every field whose change makes a run a different experiment, with the value the already
# scored runs used. epochs and learning_rate are in here for the same reason `unit` is: two
# runs that differ only in learning rate would otherwise share a predictions key, and the
# significance test would compare one of them against the other's rival. That exact bug has
# already been found once in this file, for the training unit.
BASELINE_RECIPE = {"label_smoothing": 0.0, "dropout": None, "select_on": "loss",
                   "patience": 0, "epochs": 3, "learning_rate": 3e-5,
                   "warmup_steps": 0, "max_steps": 0}
# How each one reads in a label. Without this a learning rate prints as 0.0001.
RECIPE_LABELS = {"label_smoothing": lambda v: f"ls{v:g}",
                 "dropout": lambda v: f"do{v:g}",
                 "select_on": lambda v: f"sel-{v}",
                 "patience": lambda v: f"pat{v:g}",
                 "epochs": lambda v: f"ep{v:g}",
                 "learning_rate": lambda v: f"lr{v:g}",
                 "warmup_steps": lambda v: f"wu{v:g}",
                 "max_steps": lambda v: f"ms{v:g}"}


def run_variant(meta: dict) -> str:
    """Every deviation of one run from the baseline recipe, as a short label.

    Read from the fields the run recorded, not from its directory: the directory is a
    naming convention and the fields are the record. Runs scored before the recipe block
    existed have none, which is correct -- they used the baseline.
    """
    parts = []
    if meta.get("unit", "sentence") != "sentence":
        parts.append(meta["unit"])
    if meta.get("length_penalty", 1.0) != 1.0:
        parts.append(f"lp{meta['length_penalty']}")
    recipe = meta.get("recipe") or {}
    for name, default in BASELINE_RECIPE.items():
        value = recipe.get(name, default)
        if value is None or default is None:
            if value != default:
                parts.append(RECIPE_LABELS[name](value))
            continue
        # Floats, so compared with a tolerance rather than ==: 3e-5 read back from json is
        # not always bit-identical to the literal, and an inequality there would label every
        # baseline run as a variant.
        if isinstance(value, (int, float)) and isinstance(default, (int, float)):
            if abs(float(value) - float(default)) > 1e-12:
                parts.append(RECIPE_LABELS[name](value))
        elif value != default:
            parts.append(RECIPE_LABELS[name](value))
    return "+".join(parts)


def run_identity(meta: dict) -> tuple:
    """What makes two runs the same experiment, and therefore comparable."""
    return (f"{meta['language']}-{meta['pivot']}", meta["arm"], meta["model"],
            meta["direction"], meta.get("trained_on", meta["direction"]),
            run_variant(meta))


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.
    #
    # The variant is part of the key. Without it every ablation of an arm collapsed onto one
    # entry -- 15 glk-en/ours runs at different units, length penalties and recipes became
    # whichever sorted last -- so each variant row was tested against the wrong predictions
    # and printed an identical delta beside a different score. Four bar-en/ours rows all
    # claimed "+3.40 vs public_prose" while scoring 39.07, 39.10, 39.13 and 39.15.
    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[run_identity(meta)] = load_jsonl(path)

    header = (f"{'lang':4s} {'piv':3s} {'arm':22s} {'model':9s} {'trained':9s} {'scored':9s} "
              f"{'variant':26s} {'train':>9s} {'n':>5s} {'chrF++':>7s} {'chrF2':>6s} "
              f"{'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"],
                                           run_variant(r))):
        rival_name = ARMS.get(row["arm"], {}).get("rival")
        verdict = ""
        trained_on = row.get("trained_on", row["direction"])
        key = run_identity(row)
        # The rival at the same variant, never the rival's baseline: comparing a
        # paragraph-unit system against a sentence-unit rival would report the unit change
        # as a data difference.
        rival_key = (key[0], rival_name, *key[2:])
        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.get("chrf2pp") or 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}")
                # TER disagreeing with chrF++ is the interesting case, so say so rather
                # than leaving it in the json for someone to find.
                ter = result.get("ter")
                if ter:
                    ter_mark = "*" if (ter["p_value"] or 1) < 0.05 else " "
                    verdict += (f" | TER {ter['delta']:+.2f} "
                                f"p={ter['p_value']:.3f}{ter_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} {run_variant(row) or '-':26s} "
              f"{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",
                                         "backtranslate",
                                          "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("--lora-rank", type=int, default=16,
                        help="LoRA rank; alpha follows at 2x so the update scale is held "
                             "fixed while capacity varies")
    parser.add_argument("--gradient-checkpointing", action="store_true",
                        help="recompute activations in the backward pass instead of storing "
                             "them. Measured on Gemma-4-12B at micro-batch 4 "
                             "(scripts/gemma_speed_probe.py): 5%% slower per pass -- 3.90 "
                             "against 4.12 -- for 27.5 GB instead of 41.2 GB. The 30%% this "
                             "help text used to claim was an estimate, and it was wrong by "
                             "enough to have argued against a setting that is nearly free. "
                             "The gradients are unchanged, so an arm trained with it stays "
                             "comparable to one trained without. Off by default: the Qwen "
                             "column was measured without it and must not change mid-column")
    parser.add_argument("--group-by-length", action="store_true",
                        help="draw each batch from examples of similar length. The collator "
                             "pads to the longest item in the batch, so under random order "
                             "one long sentence inflates every short one beside it: measured "
                             "on glk-en/ours at micro-batch 8, only 54.3%% of the padded "
                             "tokens were real content against 99.3%% grouped, which is "
                             "about 45%% of the compute. Off by default because it changes "
                             "which examples share a batch -- a run with it is not strictly "
                             "comparable to one without, and it earns its own path segment "
                             "for that reason")
    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")
    parser.add_argument("--max-steps", type=int, default=0,
                        help="train for a fixed number of optimizer steps instead of a "
                             "fixed number of epochs. Holds training constant while the "
                             "data size varies, which --epochs cannot do")
    parser.add_argument("--warmup-steps", type=int, default=0,
                        help="fixed warmup steps, overriding the 5%% ratio. The ratio gives "
                             "a 1,000-pair arm 2 warmup steps, which is no warmup at all")
    parser.add_argument("--bt-sentences", type=int, default=50000,
                        help="how many monolingual sentences to back-translate")
    parser.add_argument("--bt-candidates", type=int, default=400000,
                        help="how many Wikipedia sentences to read before filtering")
    parser.add_argument("--bt-tag", action="store_true", default=True,
                        help="mark a back-translated source with a tag during training")
    parser.add_argument("--no-bt-tag", dest="bt_tag", action="store_false",
                        help="train on untagged synthetic input, to measure what the tag "
                             "is worth")
    parser.add_argument("--baselines-only", action="store_true",
                        help="add only the per-corpus arms of the gathered baseline release, "
                             "leaving every prepared split byte-identical")
    parser.add_argument("--finetrans-domains-only", action="store_true",
                        help="add only the FineTranslations Wikipedia / non-Wikipedia halves "
                             "and ours size-matched to each, leaving every prepared split "
                             "byte-identical. English pivot only, which is all "
                             "FineTranslations covers")
    parser.add_argument("--finetrans-wordmatched-only", action="store_true",
                        help="add only the FineTranslations arms cut to the pivot-side word "
                             "count of the ours arm each is compared against. The pair-count "
                             "match these replace gave FineTranslations about twelve times "
                             "the text, because its records are translated FineWeb2 "
                             "documents (179 English words) and ours are sentences (13). "
                             "Leaves every existing split byte-identical")
    parser.add_argument("--finetrans-domain-matched-only", action="store_true",
                        help="add only finetrans_nonwiki_matched_wiki: the non-Wikipedia "
                             "half of FineTranslations cut to the Wikipedia half's "
                             "pivot-side word count. The one FineTranslations comparison "
                             "with a single free variable -- same corpus, pipeline, "
                             "translator and paragraph granularity on both sides, so a "
                             "difference on test is attributable to the source domain. "
                             "Leaves every existing split byte-identical")
    parser.add_argument("--pooled-only", action="store_true",
                        help="prepare only: build just the cross-pivot and "
                             "cross-language pooled arms, leaving every existing arm's "
                             "files untouched")
    parser.add_argument("--reindex", action="store_true",
                        help="prepare only: rebuild the manifest entries of the named "
                             "languages from the arm files already on disk, writing no "
                             "data. The repair for a manifest that lost a language")
    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)}")
    # The GPU pin is not optional for the stages that open one. CONNECT.md asks us not to
    # occupy both cards, and this project is explicitly confined to device 1 so the second
    # stays free for the rest of the group. launch.sh exports it for every sweep stream, but a
    # one-off recovery or diagnostic invoked directly inherits nothing, and torch then takes
    # device 0 by default -- scripts/recover_orphans.sh did precisely that and put 8.7 GB on
    # the reserved card. Refusing is better than warning: a warning scrolls past in a detached
    # log and the card stays occupied until someone looks at nvidia-smi.
    if args.stage in {"train", "evaluate", "backtranslate"} \
            and "CUDA_VISIBLE_DEVICES" not in os.environ \
            and os.environ.get("ALLOW_ANY_GPU") != "1":
        raise SystemExit(
            f"{args.stage} needs CUDA_VISIBLE_DEVICES set, so it cannot take the GPU this "
            "project is not allowed to use. Export CUDA_VISIBLE_DEVICES=1 (what "
            "scripts/launch.sh does), or set ALLOW_ANY_GPU=1 if you really mean to let torch "
            "choose.")
    # Normalised here, before anything reads it, so the three places that record the
    # selection metric cannot disagree: the run path (run_label appends "sel-chrf"),
    # training_complete.json (what best_recipe.py matches on), and what the adapter trainer
    # actually does -- checkpoint on eval_loss, because chrF++ for a decoder-only model needs
    # a generation pass. Left unnormalised, an adapter run asked for chrF selection lands in
    # a directory named sel-chrf, records a metric it never used, and then fails to match
    # --baseline-select-on chrf in the ranking command, which is three ways of being wrong
    # about the same thing.
    if (MODELS.get(args.model, {}).get("kind") == "causal_lora"
            and getattr(args, "select_on", "loss") != "loss"):
        print(f"note: --select-on {args.select_on} is not available for the adapter arms; "
              "using loss. chrF++ is computed once after training by dev_chrf_causal, which "
              "is what the rate sweep ranks the rungs on.")
        args.select_on = "loss"
    if args.stage == "backtranslate":
        # No --arm: this stage writes arms rather than reading one.
        missing = [name for name in ("language", "pivot") if not getattr(args, name)]
        if missing:
            raise SystemExit(f"backtranslate needs --{' --'.join(missing)}")
    return {"plan": stage_plan, "prepare": stage_prepare, "train": stage_train,
            "evaluate": stage_evaluate, "rescore": stage_rescore,
            "backtranslate": stage_backtranslate,
            "report": stage_report}[args.stage](args)


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