File size: 85,774 Bytes
0b3b2a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

train_single_lang.py



Single-language fine-tuning of Nemotron-Speech-Streaming.

Adapted from train_multilingual_nemotron.py for per-language training.



This script is the entry point for every (language, hours, init) cell of

the main grid in the paper.  The init arm is selected by the combination

of --resume_from and --encoder_from / --reinit_encoder; the multilingual

tokenizer, decoder and joint always come from the multilingual base.



  ML init (paper's "ML" arm)

      --resume_from <multilingual_base.nemo>

      Encoder, decoder, joint and tokenizer all come from the multilingual

      base checkpoint.



  EN init (paper's "EN" arm)

      --resume_from <multilingual_base.nemo>

      --encoder_from nvidia/nemotron-speech-streaming-en-0.6b

      The decoder, joint and tokenizer are kept from the multilingual base

      (so the comparison isolates the encoder), and the encoder weights are

      overwritten layer-for-layer with the English-only Nemotron encoder.



  Random-encoder ablation (NOT the paper's EN arm)

      --resume_from <multilingual_base.nemo>

      --reinit_encoder

      Same as ML init except the encoder is freshly random-initialized.



  Direct from English checkpoint (legacy / not used in the main grid)

      --student nvidia/nemotron-speech-streaming-en-0.6b

      No --resume_from.  Everything (encoder, decoder, joint, tokenizer) is

      taken from the English checkpoint and only the prediction-network

      output layer is resized to the target tokenizer.



Example usage (paper ML init for German, 100 h):

  torchrun --nproc_per_node=1 train_single_lang.py \

    --lang de \

    --resume_from   <CKPT_DIR>/multilingual_base.nemo \

    --train_manifest <DATA_ROOT>/de/100h/train.jsonl \

    --val_manifest   <VAL_MANIFEST> \

    --output_dir ./out/de_100h_ml \

    --epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \

    --early_stop_patience 8 --decay_spec_augment --seed 42



Example usage (paper EN init for the same cell):

  torchrun --nproc_per_node=1 train_single_lang.py \

    --lang de \

    --resume_from   <CKPT_DIR>/multilingual_base.nemo \

    --encoder_from  nvidia/nemotron-speech-streaming-en-0.6b \

    --train_manifest <DATA_ROOT>/de/100h/train.jsonl \

    --val_manifest   <VAL_MANIFEST> \

    --output_dir ./out/de_100h_en \

    --epochs 30 --batch_size 16 --grad_accum 3 --lr 1e-4 \

    --early_stop_patience 8 --decay_spec_augment --seed 42



Manifest format (one JSON object per line):

  {"audio_filepath": "/abs/path/utt.wav", "duration": 8.4, "text": "reference transcript"}

  `duration` (seconds) is required: it drives min/max-duration filtering and

  the --max_train_hours subsampling.



Requirements:

  pip install nemo_toolkit[asr] soundfile jiwer tqdm

  Evaluation also requires Whisper's BasicMultilingualTextNormalizer from the

  Open ASR Leaderboard repo (clone https://github.com/huggingface/open_asr_leaderboard

  and add it to PYTHONPATH).

"""

import argparse
import json
import math
import os
import gc
import re
import sys
import unicodedata
from collections import defaultdict

import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from tqdm import tqdm

# Use Whisper's BasicMultilingualTextNormalizer for consistent eval
try:
    from normalizer import BasicMultilingualTextNormalizer
    _ml_normalizer = BasicMultilingualTextNormalizer()
    _has_real_normalizer = True
except ImportError:
    print(
        "ERROR: could not import BasicMultilingualTextNormalizer. "
        "This script requires Whisper's BasicMultilingualTextNormalizer, "
        "shipped in the Open ASR Leaderboard repo. "
        "Clone https://github.com/huggingface/open_asr_leaderboard and add it "
        "to PYTHONPATH (or set OPEN_ASR_LB_ROOT).",
        file=sys.stderr,
    )
    exit(1)
    _ml_normalizer = None
    _has_real_normalizer = False


# ═══════════════════════════════════════════════════════════
# DDP Utilities
# ═══════════════════════════════════════════════════════════

def setup_ddp():
    """Initialize distributed training. Returns (rank, world_size, local_rank, is_distributed)."""
    if "RANK" in os.environ:
        rank = int(os.environ["RANK"])
        world_size = int(os.environ["WORLD_SIZE"])
        local_rank = int(os.environ["LOCAL_RANK"])
        from datetime import timedelta
        dist.init_process_group("nccl", timeout=timedelta(minutes=60))
        torch.cuda.set_device(local_rank)
        return rank, world_size, local_rank, True
    else:
        return 0, 1, 0, False


def cleanup_ddp(is_distributed):
    if is_distributed:
        dist.destroy_process_group()


def is_main(rank):
    return rank == 0


def print_rank0(msg, rank=0):
    if is_main(rank):
        print(msg, flush=True)


# ═══════════════════════════════════════════════════════════
# Configuration
# ═══════════════════════════════════════════════════════════

def parse_args():
    p = argparse.ArgumentParser(
        description="Single-language Nemotron Streaming ASR Training",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    # Language
    p.add_argument("--lang", type=str, required=True,
                   help="Language code (e.g., de, es, fr, it, nl, sv, pt, pl)")

    # Models
    p.add_argument("--teacher", default="nvidia/parakeet-tdt-0.6b-v3",
                   help="Teacher model for tokenizer extraction")
    p.add_argument("--student", default="nvidia/nemotron-speech-streaming-en-0.6b",
                   help="Student model (English, streaming)")

    # Data
    p.add_argument("--train_manifest", type=str, required=True,
                   help="Path to training manifest (JSONL)")
    p.add_argument("--val_manifest", type=str, required=True,
                   help="Path to validation manifest (JSONL)")

    # Training
    p.add_argument("--output_dir", default="./nemotron_lang")
    p.add_argument("--epochs", type=int, default=30)
    p.add_argument("--batch_size", type=int, default=16,
                   help="Per-GPU batch size")
    p.add_argument("--grad_accum", type=int, default=2,
                   help="Gradient accumulation steps")
    p.add_argument("--lr", type=float, default=1e-4)
    p.add_argument("--min_lr", type=float, default=1e-6)
    p.add_argument("--weight_decay", type=float, default=1e-3)
    p.add_argument("--warmup_epochs", type=int, default=1)
    p.add_argument("--max_duration", type=float, default=20.0)
    p.add_argument("--min_duration", type=float, default=0.3)

    # SpecAugment
    p.add_argument("--no_spec_augment", action="store_true", default=False)
    p.add_argument("--freq_masks", type=int, default=2)
    p.add_argument("--freq_width", type=int, default=27)
    p.add_argument("--time_masks", type=int, default=10)
    p.add_argument("--time_width", type=float, default=0.05)

    # Speed perturbation
    p.add_argument("--speed_perturb", action="store_true", default=True)
    p.add_argument("--speed_perturb_factors", type=float, nargs='+', default=[0.9, 1.0, 1.1])

    # Misc
    p.add_argument("--freeze_encoder_epochs", type=int, default=0,
                   help="Freeze encoder for first N epochs")
    p.add_argument("--reinit_encoder", action="store_true", default=False,
                   help="Randomly reinitialize all encoder weights (ablation). "
                        "NOT the paper's EN arm -- EN init uses --encoder_from "
                        "to copy the English encoder weights, not random init.")
    p.add_argument("--reinit_joint", action="store_true", default=False,
                   help="Randomly reinitialize the RNNT joint network weights (ablation study). "
                        "Useful after swapping encoders so the joint relearns the encoder->vocab mapping.")
    p.add_argument("--lr_decay_epochs", type=int, default=25,
                   help="Cosine decay reaches min_lr after N epochs (0=use total epochs)")
    p.add_argument("--constant_lr", action="store_true", default=False)
    p.add_argument("--log_every", type=int, default=50)
    p.add_argument("--eval_every_epoch", type=int, default=1)
    p.add_argument("--save_every_epoch", type=int, default=0,
                   help="Save training state every N epochs (0=disabled)")
    p.add_argument("--early_stop_patience", type=int, default=30,
                   help="Stop if WER doesn't improve for N evals (0=disabled)")
    p.add_argument("--grad_clip", type=float, default=1.0,
                   help="Gradient clipping max norm")
    p.add_argument("--rnnt_clamp", type=float, default=-1.0,
                   help="RNNT loss per-frame clamping value (-1=disabled, 1.0=recommended)")
    p.add_argument("--bf16", action="store_true", default=True)
    p.add_argument("--fp16", action="store_true", default=False)
    p.add_argument("--num_workers", type=int, default=4)
    p.add_argument("--max_train_hours", type=float, default=0,
                   help="Limit training data to N hours (0=use all data). Samples randomly.")
    p.add_argument("--data_seed", type=int, default=12345,
                   help="Seed for data subsampling (separate from training seed for reproducibility)")
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--resume_from", type=str, default=None,
                   help="Resume from .nemo checkpoint (the multilingual base for both "
                        "the ML and EN arms of the paper's main grid). Sets the "
                        "tokenizer, decoder and joint; the encoder is then either kept "
                        "(ML arm), overwritten via --encoder_from (EN arm), or "
                        "re-initialized via --reinit_encoder (ablation).")
    p.add_argument("--encoder_from", type=str, default=None,
                   help="Overwrite encoder weights with those of this checkpoint after "
                        "--resume_from has loaded the multilingual base. This is how "
                        "the paper's EN arm is built: multilingual tokenizer/decoder/joint "
                        "+ English encoder (nvidia/nemotron-speech-streaming-en-0.6b).")
    p.add_argument("--swap_joint_enc", action="store_true", default=False,
                   help="When using --encoder_from, also copy the joint network's encoder projection (enc linear + enc_hat) from the source model. Keeps encoder and joint.enc in sync.")
    p.add_argument("--encoder_from_layers", type=str, default="all",
                   help="Which Conformer layer indices to copy from --encoder_from. "
                        "Examples: 'all' (default, full encoder), 'none' (skip layers, only use preencode/postnorm flags), "
                        "'0:8' (Python slice, layers 0..7), '-8:' (last 8 layers), '0:8,16:24' (multiple ranges). "
                        "Negative indices count from the end. Layers outside the slice stay from --resume_from/--student.")
    p.add_argument("--encoder_from_preencode", type=str, default="off", choices=["auto", "on", "off"],
                   help="Copy the pre-encoder subsampling (conv frontend) and positional embeddings from --encoder_from. "
                        "Default 'off' keeps the destination model's preencode (ML baseline when --resume_from is set), "
                        "which is preferable for cross-lingual splices since the ML preencode has seen the target language. "
                        "'auto': on iff layer 0 is in --encoder_from_layers.")
    p.add_argument("--encoder_from_postnorm", type=str, default="off", choices=["auto", "on", "off"],
                   help="Copy the final encoder norm/output projection from --encoder_from. "
                        "Default 'off' keeps the destination model's postnorm (ML baseline when --resume_from is set), "
                        "which is the natural pairing when the top layers also come from the destination. "
                        "'auto': on iff the last layer is in --encoder_from_layers.")
    p.add_argument("--decay_spec_augment", action="store_true", default=False,
                   help="Linearly decay SpecAugment mask counts over training (time_masks: N->2, freq_masks: N->1)")
    p.add_argument("--resume_training", type=str, default=None,
                   help="Resume training from a training_state.pt checkpoint (saved in output_dir). Restores optimizer, scheduler, epoch, and all training state.")
    p.add_argument("--confidence_penalty", type=float, default=0.0,
                   help="Entropy regularization weight (0=off). Penalizes overconfident joint predictions. Try 0.1-0.3.")
    p.add_argument("--streaming_chunk_sec", type=float, default=0,
                   help="Enable chunk-aware streaming training. Chunk duration in seconds (e.g., 1.2). 0=full context training.")
    p.add_argument("--test_manifest", type=str, default=None,
                   help="Path to test manifest (JSONL) for final evaluation")
    p.add_argument("--decoder_hidden", type=int, default=0,
                   help="Override RNNT decoder (prediction network) LSTM hidden size. 0=keep original (640). E.g., 860, 1024.")
    p.add_argument("--decoder_layers", type=int, default=0,
                   help="Override RNNT decoder LSTM layer count. 0=keep original (2). E.g., 3, 4.")

    return p.parse_args()


# ═══════════════════════════════════════════════════════════
# Tokenizer Extraction (from teacher)
# ═══════════════════════════════════════════════════════════

def extract_tokenizer(model, tokenizer_dir):
    """Extract tokenizer .model file from a NeMo ASR model."""
    from pathlib import Path

    os.makedirs(tokenizer_dir, exist_ok=True)
    out_model = Path(tokenizer_dir) / "tokenizer.model"

    tok = getattr(model, "tokenizer", None)
    sp = getattr(tok, "tokenizer", None)

    if sp is not None and hasattr(sp, "serialized_model_proto"):
        blob = sp.serialized_model_proto()
        if blob:
            out_model.write_bytes(blob)
            _generate_vocab_txt(tokenizer_dir)
            vs = getattr(sp, "vocab_size", None)
            if callable(vs):
                vs = vs()
            return str(Path(tokenizer_dir)), int(vs) if vs else 0

    raise RuntimeError("Could not extract tokenizer from teacher model")


def _generate_vocab_txt(tokenizer_dir):
    import sentencepiece as spm_lib
    model_path = os.path.join(tokenizer_dir, "tokenizer.model")
    vocab_path = os.path.join(tokenizer_dir, "vocab.txt")
    if os.path.exists(vocab_path):
        return
    sp = spm_lib.SentencePieceProcessor()
    sp.load(model_path)
    with open(vocab_path, "w", encoding="utf-8") as f:
        for i in range(sp.get_piece_size()):
            f.write(sp.id_to_piece(i) + "\n")


# ═══════════════════════════════════════════════════════════
# Model Setup
# ═══════════════════════════════════════════════════════════

def setup_spec_augment(student, args):
    from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation

    if args.no_spec_augment:
        student.spec_augmentation = None
        return

    spec_aug = SpectrogramAugmentation(
        freq_masks=args.freq_masks,
        time_masks=args.time_masks,
        freq_width=args.freq_width,
        time_width=args.time_width,
    )
    student.spec_augmentation = spec_aug.to(next(student.parameters()).device)


def update_spec_augment(student, args, epoch, total_epochs, rank):
    """Linearly decay SpecAugment mask counts over training."""
    if not args.decay_spec_augment or args.no_spec_augment:
        return
    from nemo.collections.asr.modules.audio_preprocessing import SpectrogramAugmentation

    progress = epoch / max(1, total_epochs - 1)
    new_time_masks = max(2, round(args.time_masks * (1 - progress)))
    new_freq_masks = max(1, round(args.freq_masks * (1 - 0.5 * progress)))

    model = student.module if isinstance(student, DDP) else student
    spec_aug = SpectrogramAugmentation(
        freq_masks=new_freq_masks,
        time_masks=new_time_masks,
        freq_width=args.freq_width,
        time_width=args.time_width,
    )
    model.spec_augmentation = spec_aug.to(next(model.parameters()).device)
    print_rank0(f"    SpecAug decay: freq={new_freq_masks}x{args.freq_width} time={new_time_masks}x{args.time_width}", rank)

    from omegaconf import open_dict
    with open_dict(model.cfg):
        model.cfg.spec_augment.freq_masks = new_freq_masks
        model.cfg.spec_augment.time_masks = new_time_masks
        model.cfg.spec_augment.freq_width = args.freq_width
        model.cfg.spec_augment.time_width = args.time_width


def _parse_layer_slice(spec, num_layers):
    """Parse a slice spec like 'all', 'none', '0:8', '-8:', '0:8,16:24' into a sorted set of indices.



    Supports Python-style slice ranges, comma-separated. Negative indices count from num_layers.

    Returns a set of ints in [0, num_layers).

    """
    if spec is None:
        return set()
    s = spec.strip().lower()
    if s in ("all", "*"):
        return set(range(num_layers))
    if s in ("none", ""):
        return set()
    out = set()
    for part in s.split(","):
        part = part.strip()
        if not part:
            continue
        if ":" in part:
            lo_s, hi_s = part.split(":", 1)
            lo = int(lo_s) if lo_s else 0
            hi = int(hi_s) if hi_s else num_layers
            if lo < 0:
                lo += num_layers
            if hi < 0:
                hi += num_layers
            lo = max(0, min(num_layers, lo))
            hi = max(0, min(num_layers, hi))
            out.update(range(lo, hi))
        else:
            idx = int(part)
            if idx < 0:
                idx += num_layers
            if 0 <= idx < num_layers:
                out.add(idx)
    return out


def _splice_encoder(dst_encoder, src_encoder, layer_indices, include_preencode, include_postnorm, rank):
    """Merge src_encoder weights into dst_encoder for the given layer indices, plus optional

    preencode (subsampling + positional encoding) and postnorm modules.



    Layer keys are expected to start with 'layers.<i>.'. Everything else is treated as

    'preencode-like' if its name matches pre_encode/pos_enc/embedding, or 'postnorm-like' otherwise.

    """
    src_sd = src_encoder.state_dict()
    dst_sd = dst_encoder.state_dict()

    PREENC_PREFIXES = ("pre_encode", "pos_enc", "pos_embedding", "pos_embed", "embedding")

    copied_layers = set()
    copied_pre = []
    copied_post = []
    skipped_shape = []
    skipped_missing = []

    for k, v in src_sd.items():
        if k.startswith("layers."):
            try:
                idx = int(k.split(".", 2)[1])
            except (ValueError, IndexError):
                continue
            if idx not in layer_indices:
                continue
            target_key = k
            bucket = ("layer", idx)
        elif any(k.startswith(p) for p in PREENC_PREFIXES):
            if not include_preencode:
                continue
            target_key = k
            bucket = ("pre", k)
        else:
            if not include_postnorm:
                continue
            target_key = k
            bucket = ("post", k)

        if target_key not in dst_sd:
            skipped_missing.append(target_key)
            continue
        if dst_sd[target_key].shape != v.shape:
            skipped_shape.append((target_key, tuple(v.shape), tuple(dst_sd[target_key].shape)))
            continue

        dst_sd[target_key] = v
        if bucket[0] == "layer":
            copied_layers.add(bucket[1])
        elif bucket[0] == "pre":
            copied_pre.append(target_key)
        else:
            copied_post.append(target_key)

    missing, unexpected = dst_encoder.load_state_dict(dst_sd, strict=False)
    print_rank0(
        f"  Encoder splice: copied layers {sorted(copied_layers)} "
        f"({len(copied_layers)} of {len(layer_indices)} requested)", rank
    )
    if copied_pre:
        print_rank0(f"  Encoder splice: copied {len(copied_pre)} preencode keys", rank)
    if copied_post:
        print_rank0(f"  Encoder splice: copied {len(copied_post)} postnorm/other keys", rank)
    if skipped_shape:
        print_rank0(f"  WARNING: skipped {len(skipped_shape)} keys due to shape mismatch (first: {skipped_shape[0]})", rank)
    if skipped_missing:
        print_rank0(f"  WARNING: skipped {len(skipped_missing)} keys missing in dst encoder (first: {skipped_missing[0]})", rank)


def load_student(args, device, rank):
    """Load student model, optionally swap tokenizer."""
    import nemo.collections.asr as nemo_asr

    if args.resume_from:
        print_rank0(f"  Resuming from: {args.resume_from}", rank)
        student = nemo_asr.models.ASRModel.restore_from(args.resume_from, map_location='cpu')
        print_rank0(f"  Vocab: {student.tokenizer.vocab_size} tokens", rank)
        args.freeze_encoder_epochs = 0

        # Optionally override encoder weights from a different model (e.g., English)
        if args.encoder_from:
            print_rank0(f"  Loading encoder from: {args.encoder_from}", rank)
            if args.encoder_from.endswith('.nemo'):
                encoder_model = nemo_asr.models.ASRModel.restore_from(args.encoder_from, map_location='cpu')
            else:
                encoder_model = nemo_asr.models.ASRModel.from_pretrained(args.encoder_from, map_location='cpu')

            # Determine number of Conformer layers from the source encoder
            src_layers_attr = getattr(encoder_model.encoder, "layers", None)
            num_layers = len(src_layers_attr) if src_layers_attr is not None else 0
            dst_layers_attr = getattr(student.encoder, "layers", None)
            dst_num_layers = len(dst_layers_attr) if dst_layers_attr is not None else 0
            if num_layers == 0 or dst_num_layers == 0:
                raise RuntimeError(
                    f"Could not locate '.encoder.layers' on src ({num_layers}) or dst ({dst_num_layers}); "
                    f"layer splicing requires a Conformer-style encoder with .layers nn.ModuleList."
                )
            if num_layers != dst_num_layers:
                print_rank0(
                    f"  WARNING: src encoder has {num_layers} layers but dst has {dst_num_layers}; "
                    f"only layers present in both will be copied.", rank
                )

            spec = args.encoder_from_layers or "all"
            effective_layers = min(num_layers, dst_num_layers)
            layer_indices = _parse_layer_slice(spec, effective_layers)

            # Auto-detect: preencode if EN provides layer 0; postnorm if EN provides last layer.
            auto_preencode = 0 in layer_indices
            auto_postnorm = (effective_layers - 1) in layer_indices

            def _resolve(flag, auto_value, name):
                if flag == "on":
                    return True
                if flag == "off":
                    return False
                return auto_value  # "auto"

            include_preencode = _resolve(args.encoder_from_preencode, auto_preencode, "preencode")
            include_postnorm = _resolve(args.encoder_from_postnorm, auto_postnorm, "postnorm")

            # Fast path: entire encoder copied (all layers + both boundaries) -> direct load_state_dict.
            full_copy = (
                len(layer_indices) == effective_layers
                and include_preencode
                and include_postnorm
                and num_layers == dst_num_layers
            )
            if full_copy:
                student.encoder.load_state_dict(encoder_model.encoder.state_dict())
                enc_params = sum(p.numel() for p in student.encoder.parameters()) / 1e6
                print_rank0(f"  Encoder fully swapped: {enc_params:.1f}M params from {args.encoder_from}", rank)
            else:
                print_rank0(
                    f"  Encoder splice spec='{spec}' ({len(layer_indices)}/{effective_layers} layers); "
                    f"preencode={include_preencode} ({args.encoder_from_preencode}"
                    f"{' -> auto=' + str(auto_preencode) if args.encoder_from_preencode == 'auto' else ''}), "
                    f"postnorm={include_postnorm} ({args.encoder_from_postnorm}"
                    f"{' -> auto=' + str(auto_postnorm) if args.encoder_from_postnorm == 'auto' else ''})", rank
                )
                _splice_encoder(
                    student.encoder,
                    encoder_model.encoder,
                    layer_indices,
                    include_preencode=include_preencode,
                    include_postnorm=include_postnorm,
                    rank=rank,
                )

            # Optionally also swap the joint network's encoder-side projection
            if args.swap_joint_enc:
                swapped_keys = []
                src_joint_sd = encoder_model.joint.state_dict()
                dst_joint_sd = student.joint.state_dict()
                for key in src_joint_sd:
                    # Match encoder-side projection layers (enc, enc_hat, etc.)
                    if 'enc' in key and key in dst_joint_sd and src_joint_sd[key].shape == dst_joint_sd[key].shape:
                        dst_joint_sd[key] = src_joint_sd[key]
                        swapped_keys.append(key)
                if swapped_keys:
                    student.joint.load_state_dict(dst_joint_sd)
                    print_rank0(f"  Joint encoder projection swapped: {swapped_keys}", rank)
                else:
                    print_rank0(f"  WARNING: --swap_joint_enc set but no matching joint.enc keys found", rank)

            del encoder_model
    else:
        # Extract teacher tokenizer (only rank 0 does this, then all read from disk)
        tokenizer_dir = os.path.join(args.output_dir, "teacher_tokenizer")
        if is_main(rank):
            print_rank0(f"  Loading teacher for tokenizer: {args.teacher}", rank)
            teacher = nemo_asr.models.ASRModel.from_pretrained(args.teacher)
            tokenizer_dir, teacher_vocab_size = extract_tokenizer(teacher, tokenizer_dir)
            print_rank0(f"  Teacher vocab: {teacher_vocab_size}", rank)
            del teacher
            torch.cuda.empty_cache()

        if dist.is_initialized():
            dist.barrier()

        # Load student
        print_rank0(f"  Loading student: {args.student}", rank)
        student = nemo_asr.models.ASRModel.from_pretrained(args.student)

        old_vocab = student.tokenizer.vocab_size
        student.change_vocabulary(new_tokenizer_dir=tokenizer_dir, new_tokenizer_type="bpe")
        new_vocab = student.tokenizer.vocab_size
        print_rank0(f"  Tokenizer swap: {old_vocab} → {new_vocab}", rank)

    # Optionally resize decoder (prediction network)
    if args.decoder_hidden > 0 or args.decoder_layers > 0:
        from omegaconf import open_dict, OmegaConf
        old_hidden = student.cfg.decoder.prednet.pred_hidden
        old_layers = student.cfg.decoder.prednet.pred_rnn_layers
        new_hidden = args.decoder_hidden if args.decoder_hidden > 0 else old_hidden
        new_layers = args.decoder_layers if args.decoder_layers > 0 else old_layers

        with open_dict(student.cfg):
            student.cfg.decoder.prednet.pred_hidden = new_hidden
            student.cfg.decoder.prednet.pred_rnn_layers = new_layers

        # Rebuild decoder + joint with new dimensions
        from nemo.collections.asr.modules import RNNTDecoder, RNNTJoint
        student.decoder = RNNTDecoder(
            prednet=OmegaConf.to_container(student.cfg.decoder.prednet, resolve=True),
            vocab_size=student.tokenizer.vocab_size,
            normalization_mode=student.cfg.decoder.get('normalization_mode', None),
            random_state_sampling=student.cfg.decoder.get('random_state_sampling', False),
            blank_as_pad=student.cfg.decoder.get('blank_as_pad', True),
        )

        # Rebuild joint network to match new decoder hidden
        with open_dict(student.cfg):
            student.cfg.joint.jointnet.pred_hidden = new_hidden
            student.cfg.joint.jointnet.encoder_hidden = student.cfg.encoder.d_model
            student.cfg.joint.num_classes = student.tokenizer.vocab_size
        joint_cfg = OmegaConf.to_container(student.cfg.joint, resolve=True)
        joint_cfg.pop('_target_', None)
        joint_cfg.pop('vocabulary', None)
        student.joint = RNNTJoint(**joint_cfg)

        dec_params = sum(p.numel() for p in student.decoder.parameters()) / 1e6
        joint_params = sum(p.numel() for p in student.joint.parameters()) / 1e6
        print_rank0(f"  Decoder resized: hidden {old_hidden}->{new_hidden}, layers {old_layers}->{new_layers}", rank)
        print_rank0(f"  New decoder params: {dec_params:.1f}M, joint params: {joint_params:.1f}M", rank)

    student = student.to(device)

    # Optionally reinitialize encoder weights (ablation study)
    if args.reinit_encoder:
        print_rank0("  REINITIALIZING ENCODER WEIGHTS (random init)", rank)
        for name, param in student.encoder.named_parameters():
            if param.dim() >= 2:
                torch.nn.init.xavier_uniform_(param)
            else:
                torch.nn.init.zeros_(param)
        # Also reinit batch norm running stats
        for module in student.encoder.modules():
            if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)):
                module.reset_running_stats()
        enc_params = sum(p.numel() for p in student.encoder.parameters())
        print_rank0(f"  Reinitialized {enc_params/1e6:.1f}M encoder parameters", rank)

    # Optionally reinitialize joint network weights (ablation study)
    if args.reinit_joint:
        print_rank0("  REINITIALIZING JOINT NETWORK WEIGHTS (random init)", rank)
        # Re-seed RNG with a fixed value so ML and EN arms get IDENTICAL joint init
        # (independent of prior RNG state consumed by different checkpoint loads).
        # Using args.seed (not args.seed+rank) ensures same init across DDP ranks too.
        _joint_seed = args.seed
        _gen_state_cpu = torch.random.get_rng_state()
        _gen_state_cuda = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None
        torch.manual_seed(_joint_seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(_joint_seed)
        print_rank0(f"  Joint reinit RNG seeded with {_joint_seed} (identical across ML/EN arms)", rank)
        for name, param in student.joint.named_parameters():
            if param.dim() >= 2:
                torch.nn.init.xavier_uniform_(param)
            else:
                torch.nn.init.zeros_(param)
        for module in student.joint.modules():
            if isinstance(module, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d)):
                module.reset_running_stats()
        # Restore prior RNG state so training stochasticity is unaffected
        torch.random.set_rng_state(_gen_state_cpu)
        if _gen_state_cuda is not None:
            torch.cuda.set_rng_state_all(_gen_state_cuda)
        joint_params = sum(p.numel() for p in student.joint.parameters())
        print_rank0(f"  Reinitialized {joint_params/1e6:.1f}M joint parameters", rank)

    # SpecAugment
    setup_spec_augment(student, args)

    # Streaming chunk-aware training: restrict attention context
    if args.streaming_chunk_sec > 0:
        # Force single attention context mode [70, 13] instead of random multi-context
        # Default model has 4 modes: [70,13], [70,6], [70,1], [70,0] sampled randomly
        # This forces always using [70, 13] (largest context, lowest latency mode)
        student.encoder.att_context_size = [70, 13]
        student.encoder.att_context_size_all = [[70, 13]]
        student.encoder.att_context_probs = [1.0]
        print_rank0(f"  Streaming training: forced att_context=[70,13] only (no multi-context)", rank)

    # Disable CUDA graphs and typecheck
    from omegaconf import open_dict
    from nemo.core.classes.common import typecheck
    typecheck.set_typecheck_enabled(False)
    with open_dict(student.cfg):
        student.cfg.decoding.greedy.use_cuda_graph_decoder = False
    student.change_decoding_strategy(student.cfg.decoding)

    # Override RNNT loss clamping if requested
    if args.rnnt_clamp > 0:
        from nemo.collections.asr.losses.rnnt import RNNTLoss
        with open_dict(student.cfg):
            student.cfg.loss.warprnnt_numba_kwargs.clamp = args.rnnt_clamp
        student.loss = RNNTLoss(num_classes=student.decoder.vocab_size, loss_name='default',
                                loss_kwargs=dict(student.cfg.loss.warprnnt_numba_kwargs))
        print_rank0(f"  RNNT loss clamping: {args.rnnt_clamp}", rank)

    params = sum(p.numel() for p in student.parameters()) / 1e6
    print_rank0(f"  Student params: {params:.1f}M", rank)

    return student


# ═══════════════════════════════════════════════════════════
# Dataset & DataLoader
# ═══════════════════════════════════════════════════════════

class ASRManifestDataset(torch.utils.data.Dataset):
    def __init__(self, manifest_path, tokenizer, min_duration=0.3, max_duration=20.0,

                 speed_perturb=False, speed_perturb_factors=None,

                 max_train_hours=0, seed=42):
        self.tokenizer = tokenizer
        self.speed_perturb = speed_perturb
        self.speed_perturb_factors = speed_perturb_factors or [0.9, 1.0, 1.1]
        self.samples = []

        with open(manifest_path) as f:
            for line in f:
                item = json.loads(line)
                dur = item["duration"]
                if min_duration <= dur <= max_duration:
                    self.samples.append(item)

        # Subsample to max_train_hours if specified
        if max_train_hours > 0:
            target_seconds = max_train_hours * 3600
            rng = np.random.RandomState(seed)
            rng.shuffle(self.samples)
            selected = []
            total_dur = 0.0
            for s in self.samples:
                if total_dur >= target_seconds:
                    break
                selected.append(s)
                total_dur += s["duration"]
            self.samples = selected
            self.total_hours = total_dur / 3600

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

    def __getitem__(self, idx):
        import soundfile as sf
        item = self.samples[idx]
        try:
            audio, sr = sf.read(item["audio_filepath"], dtype="float32")
        except Exception as e:
            print(f"    Corrupt audio: {item['audio_filepath']} ({e})", flush=True)
            return None

        if sr != 16000:
            ratio = 16000 / sr
            new_len = int(len(audio) * ratio)
            audio = np.interp(
                np.linspace(0, len(audio) - 1, new_len),
                np.arange(len(audio)), audio,
            ).astype(np.float32)

        # Speed perturbation
        if self.speed_perturb:
            import random
            speed = random.choice(self.speed_perturb_factors)
            if speed != 1.0:
                new_len = int(len(audio) / speed)
                audio = np.interp(
                    np.linspace(0, len(audio) - 1, new_len),
                    np.arange(len(audio)), audio,
                ).astype(np.float32)

        audio_tensor = torch.FloatTensor(audio)

        text = unicodedata.normalize("NFKC", item["text"])
        text = " ".join(text.split())
        tokens = torch.LongTensor(self.tokenizer.text_to_ids(text))

        return audio_tensor, tokens


def collate_asr(batch):
    batch = [b for b in batch if b is not None]
    if len(batch) == 0:
        return None
    audios = [b[0] for b in batch]
    tokens_list = [b[1] for b in batch]

    audio_lens = torch.LongTensor([len(a) for a in audios])
    token_lens = torch.LongTensor([len(t) for t in tokens_list])

    max_audio = audio_lens.max().item()
    max_tokens = token_lens.max().item()
    B = len(audios)

    padded_audio = torch.zeros(B, max_audio)
    padded_tokens = torch.zeros(B, max_tokens, dtype=torch.long)

    for i in range(B):
        padded_audio[i, :audio_lens[i]] = audios[i]
        padded_tokens[i, :token_lens[i]] = tokens_list[i]

    return padded_audio, audio_lens, padded_tokens, token_lens


# ═══════════════════════════════════════════════════════════
# Training Step
# ═══════════════════════════════════════════════════════════

def train_step(student, batch, device, confidence_penalty=0.0):
    """Single forward/backward step: RNNT loss + optional entropy regularization."""
    audio, audio_len, tokens, token_len = batch
    audio = audio.to(device)
    audio_len = audio_len.to(device)
    tokens = tokens.to(device)
    token_len = token_len.to(device)

    model = student.module if isinstance(student, DDP) else student

    # Mel spectrogram
    mel, mel_len = model.preprocessor(input_signal=audio, length=audio_len)

    # Spec augmentation
    if model.spec_augmentation is not None and model.training:
        mel = model.spec_augmentation(input_spec=mel, length=mel_len)

    # Encoder
    enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)

    # Decoder
    dec_out = model.decoder(targets=tokens, target_length=token_len)
    if isinstance(dec_out, tuple):
        dec_out = dec_out[0]

    # Joint + RNNT loss
    if getattr(model.joint, 'fuse_loss_wer', False):
        result = model.joint(
            encoder_outputs=enc, decoder_outputs=dec_out,
            encoder_lengths=enc_len, transcripts=tokens,
            transcript_lengths=token_len, compute_wer=False,
        )
        loss = result[0]
    else:
        joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
        loss = model.loss(
            log_probs=joint_out, targets=tokens,
            input_lengths=enc_len, target_lengths=token_len,
        )

    if loss.dim() > 0:
        loss = loss.mean()

    # Confidence penalty: negative entropy regularization on joint output
    # Encourages less confident (more spread) predictions, acts like label smoothing
    if confidence_penalty > 0.0:
        # Extra forward pass through joint to get logits (works with fuse_loss_wer too)
        joint_logits = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
        # joint_logits: (B, T, U, V) log-probabilities
        probs = torch.exp(joint_logits)
        entropy = -(probs * joint_logits).sum(dim=-1)  # (B, T, U)
        # Maximize entropy = minimize negative entropy = subtract from loss
        loss = loss - confidence_penalty * entropy.mean()

    return loss


# ═══════════════════════════════════════════════════════════
# Evaluation
# ═══════════════════════════════════════════════════════════

def normalize_text(text):
    if _ml_normalizer is not None:
        return _ml_normalizer(text)
    text = unicodedata.normalize('NFKC', text)
    text = text.lower()
    text = re.sub(r'[^\w\s]', '', text)
    return ' '.join(text.split())


def normalize_text_fallback(text):
    """Always use fallback normalizer for consistency with older runs."""
    text = unicodedata.normalize('NFKC', text)
    text = text.lower()
    text = re.sub(r'[^\w\s]', '', text)
    return ' '.join(text.split())


def simple_wer(ref_words, hyp_words):
    n, m = len(ref_words), len(hyp_words)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n + 1): dp[i][0] = i
    for j in range(m + 1): dp[0][j] = j
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            dp[i][j] = dp[i-1][j-1] if ref_words[i-1] == hyp_words[j-1] \
                else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
    return dp[n][m]


def compute_wer_ids(ref_words, hyp_words):
    """Edit distance with backtrace to get S/D/I counts."""
    n, m = len(ref_words), len(hyp_words)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n + 1): dp[i][0] = i
    for j in range(m + 1): dp[0][j] = j
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if ref_words[i - 1] == hyp_words[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
    subs, dels, ins = 0, 0, 0
    i, j = n, m
    while i > 0 or j > 0:
        if i > 0 and j > 0 and ref_words[i - 1] == hyp_words[j - 1]:
            i -= 1; j -= 1
        elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1:
            subs += 1; i -= 1; j -= 1
        elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
            dels += 1; i -= 1
        else:
            ins += 1; j -= 1
    return subs, dels, ins


@torch.no_grad()
def evaluate_batch(student, manifest_path, device, max_samples=None, normalizer_fn=None, rank=0):
    """Evaluate WER using batch (non-streaming) inference."""
    import soundfile as sf_eval

    if normalizer_fn is None:
        normalizer_fn = normalize_text

    model = student.module if isinstance(student, DDP) else student
    model.eval()

    samples = []
    with open(manifest_path) as f:
        for line in f:
            samples.append(json.loads(line))
    if max_samples and len(samples) > max_samples:
        samples = samples[:max_samples]

    total_edits, total_words = 0, 0
    total_subs, total_dels, total_ins = 0, 0, 0
    errors = 0
    batch_size = 16
    examples = []

    total_batches = (len(samples) + batch_size - 1) // batch_size
    for start in range(0, len(samples), batch_size):
        batch_samples = samples[start:start + batch_size]
        batch_num = start // batch_size + 1
        if (batch_num % 10 == 0 or batch_num == 1) and rank == 0:
            print(f"    [eval batch {batch_num}/{total_batches}]", flush=True)
        try:
            audios = []
            for s in batch_samples:
                audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
                if len(audio.shape) > 1:
                    audio = audio.mean(axis=1)
                audios.append(torch.FloatTensor(audio))

            audio_lens = torch.LongTensor([len(a) for a in audios])
            max_len = audio_lens.max().item()
            padded = torch.zeros(len(audios), max_len)
            for i, a in enumerate(audios):
                padded[i, :len(a)] = a

            padded = padded.to(device)
            audio_lens = audio_lens.to(device)

            mel, mel_len = model.preprocessor(input_signal=padded, length=audio_lens)
            enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)

            best_hyps = model.decoding.rnnt_decoder_predictions_tensor(enc, enc_len)
            if isinstance(best_hyps, tuple):
                best_hyps = best_hyps[0]

            for s, hyp in zip(batch_samples, best_hyps):
                if hasattr(hyp, 'text') and hyp.text:
                    pred = hyp.text
                elif hasattr(hyp, 'y_sequence'):
                    tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
                    pred = model.tokenizer.ids_to_text(tids) if tids else ""
                else:
                    pred = str(hyp)

                ref_n = normalizer_fn(s["text"])
                pred_n = normalizer_fn(pred)
                ref_words = ref_n.split()
                pred_words = pred_n.split()
                if ref_words:
                    sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words)
                    total_subs += sub_c
                    total_dels += del_c
                    total_ins += ins_c
                    total_edits += sub_c + del_c + ins_c
                    total_words += len(ref_words)

                if len(examples) < 5:
                    examples.append((s["text"][:55], pred[:55]))

        except Exception as e:
            errors += 1
            if errors <= 3 and rank == 0:
                print(f"    [batch eval error] {type(e).__name__}: {e}")

    wer_score = total_edits / max(total_words, 1) * 100

    if normalizer_fn is normalize_text and rank == 0:  # Only print examples for primary eval
        print(f"\n    {'Reference':<55} | {'Prediction':<55}")
        print(f"    {'-'*55} | {'-'*55}")
        for ref, pred in examples:
            print(f"    {ref:<55} | {pred:<55}")
        if errors:
            print(f"    ({errors} batch eval errors)")

    model.train()
    return wer_score, total_subs, total_dels, total_ins, total_words


@torch.no_grad()
def evaluate_streaming(student, manifest_path, device, max_samples=None, rank=0):
    """Evaluate WER using streaming inference."""
    import soundfile as sf_eval
    from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer

    model = student.module if isinstance(student, DDP) else student
    model.eval()

    right_context = 13
    chunk_frames = 1 + right_context
    model.encoder.setup_streaming_params(
        chunk_size=chunk_frames,
        shift_size=chunk_frames,
        left_chunks=70 // max(chunk_frames, 1),
    )

    samples = []
    with open(manifest_path) as f:
        for line in f:
            samples.append(json.loads(line))
    if max_samples and len(samples) > max_samples:
        samples = samples[:max_samples]

    total_edits, total_words = 0, 0
    total_subs, total_dels, total_ins = 0, 0, 0
    examples = []
    errors = 0

    for s in samples:
        try:
            audio, sr = sf_eval.read(s["audio_filepath"], dtype="float32")
            if len(audio.shape) > 1:
                audio = audio.mean(axis=1)

            buffer = CacheAwareStreamingAudioBuffer(model=model)
            buffer.append_audio(audio)

            cache_last_channel, cache_last_time, cache_last_channel_len = \
                model.encoder.get_initial_cache_state(batch_size=1, dtype=torch.float32, device=device)
            previous_hypotheses = None
            pred = ""

            for chunk_audio, chunk_len in buffer:
                if chunk_audio is None:
                    break
                result = model.conformer_stream_step(
                    processed_signal=chunk_audio,
                    processed_signal_length=chunk_len,
                    cache_last_channel=cache_last_channel,
                    cache_last_time=cache_last_time,
                    cache_last_channel_len=cache_last_channel_len,
                    previous_hypotheses=previous_hypotheses,
                    return_transcription=True,
                )
                if isinstance(result, tuple) and len(result) >= 6:
                    cache_last_channel = result[2]
                    cache_last_time = result[3]
                    cache_last_channel_len = result[4]
                    previous_hypotheses = result[5]
                    if result[5] and len(result[5]) > 0:
                        hyp = result[5][0]
                        new_text = ""
                        if hasattr(hyp, 'text') and hyp.text:
                            new_text = hyp.text
                        elif hasattr(hyp, 'y_sequence'):
                            tids = hyp.y_sequence.tolist() if torch.is_tensor(hyp.y_sequence) else list(hyp.y_sequence)
                            if tids:
                                new_text = model.tokenizer.ids_to_text(tids)
                        if new_text and len(new_text) > len(pred):
                            pred = new_text

            ref_n = normalize_text(s["text"])
            pred_n = normalize_text(pred)
            ref_words = ref_n.split()
            pred_words = pred_n.split()

            if ref_words:
                sub_c, del_c, ins_c = compute_wer_ids(ref_words, pred_words)
                total_subs += sub_c
                total_dels += del_c
                total_ins += ins_c
                total_edits += sub_c + del_c + ins_c
                total_words += len(ref_words)

            if len(examples) < 5:
                examples.append((s["text"][:55], pred[:55]))

        except Exception as e:
            errors += 1
            if errors <= 3 and rank == 0:
                print(f"    [streaming eval error] {type(e).__name__}: {e}")

    wer_score = total_edits / max(total_words, 1) * 100

    if rank == 0:
        print(f"\n    {'Reference':<55} | {'Prediction':<55}")
        print(f"    {'-'*55} | {'-'*55}")
        for ref, pred in examples:
            print(f"    {ref:<55} | {pred:<55}")
        if errors:
            print(f"    ({errors} samples failed)")

    model.train()
    return wer_score, total_subs, total_dels, total_ins, total_words


@torch.no_grad()
def compute_val_loss(student, manifest_path, device, max_samples=500):
    """Compute RNNT loss on validation set."""
    import soundfile as sf_val

    model = student.module if isinstance(student, DDP) else student
    model.eval()

    samples = []
    with open(manifest_path) as f:
        for line in f:
            samples.append(json.loads(line))
    if max_samples and len(samples) > max_samples:
        samples = samples[:max_samples]

    total_loss = 0.0
    count = 0

    for s in samples:
        try:
            audio, sr = sf_val.read(s["audio_filepath"], dtype="float32")
            if len(audio.shape) > 1:
                audio = audio.mean(axis=1)

            text = unicodedata.normalize("NFKC", s["text"])
            text = " ".join(text.split())
            tokens = model.tokenizer.text_to_ids(text)
            if not tokens:
                continue

            audio_tensor = torch.FloatTensor(audio).unsqueeze(0).to(device)
            audio_len = torch.LongTensor([len(audio)]).to(device)
            token_tensor = torch.LongTensor([tokens]).to(device)
            token_len = torch.LongTensor([len(tokens)]).to(device)

            mel, mel_len = model.preprocessor(input_signal=audio_tensor, length=audio_len)
            enc, enc_len = model.encoder(audio_signal=mel, length=mel_len)
            dec_out = model.decoder(targets=token_tensor, target_length=token_len)
            if isinstance(dec_out, tuple):
                dec_out = dec_out[0]

            if getattr(model.joint, 'fuse_loss_wer', False):
                result = model.joint(
                    encoder_outputs=enc, decoder_outputs=dec_out,
                    encoder_lengths=enc_len, transcripts=token_tensor,
                    transcript_lengths=token_len, compute_wer=False,
                )
                loss = result[0]
            else:
                joint_out = model.joint(encoder_outputs=enc, decoder_outputs=dec_out)
                loss = model.loss(log_probs=joint_out, targets=token_tensor,
                                  input_lengths=enc_len, target_lengths=token_len)

            if loss.dim() > 0:
                loss = loss.mean()
            total_loss += loss.item()
            count += 1
        except Exception:
            continue

    model.train()
    return total_loss / max(count, 1)


# ═══════════════════════════════════════════════════════════
# LR Schedule
# ═══════════════════════════════════════════════════════════

def get_cosine_schedule(optimizer, warmup_steps, total_steps, min_lr=1e-6):
    base_lr = optimizer.defaults["lr"]

    def lr_lambda(step):
        if step < warmup_steps:
            return max(1e-8 / base_lr, step / max(1, warmup_steps))
        progress = min(1.0, (step - warmup_steps) / max(1, total_steps - warmup_steps))
        return (min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * progress))) / base_lr

    return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)


def get_constant_schedule(optimizer, warmup_steps):
    base_lr = optimizer.defaults["lr"]

    def lr_lambda(step):
        if step < warmup_steps:
            return max(1e-8 / base_lr, step / max(1, warmup_steps))
        return 1.0

    return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)


# ═══════════════════════════════════════════════════════════
# Main Training Loop
# ═══════════════════════════════════════════════════════════

def train(student, train_loader, train_sampler, args, device, rank, is_distributed):
    os.makedirs(args.output_dir, exist_ok=True)

    lang = args.lang.upper()
    model = student.module if isinstance(student, DDP) else student

    trainable_params = [p for p in student.parameters() if p.requires_grad]
    optimizer = torch.optim.AdamW(
        trainable_params,
        lr=args.lr,
        weight_decay=args.weight_decay,
        betas=(0.9, 0.98),
        eps=1e-9,
    )

    steps_per_epoch = len(train_loader) // args.grad_accum
    total_steps = steps_per_epoch * args.epochs
    warmup_steps = steps_per_epoch * args.warmup_epochs

    if args.constant_lr:
        scheduler = get_constant_schedule(optimizer, warmup_steps)
    else:
        decay_epochs = args.lr_decay_epochs if args.lr_decay_epochs > 0 else args.epochs
        cosine_total_steps = steps_per_epoch * decay_epochs
        scheduler = get_cosine_schedule(optimizer, warmup_steps, cosine_total_steps, args.min_lr)

    use_amp = args.bf16 or args.fp16
    amp_dtype = torch.bfloat16 if args.bf16 else torch.float16
    scaler = torch.amp.GradScaler("cuda") if args.fp16 else None

    effective_batch = args.batch_size * args.grad_accum
    if is_distributed:
        world_size = dist.get_world_size()
        effective_batch *= world_size
    else:
        world_size = 1

    starting_from = args.resume_from if args.resume_from else args.student
    print_rank0(f"\n{'='*65}", rank)
    print_rank0(f"  {lang} Training Configuration", rank)
    print_rank0(f"{'='*65}", rank)
    print_rank0(f"  Language:           {lang}", rank)
    print_rank0(f"  Starting from:      {starting_from}", rank)
    print_rank0(f"  GPUs:               {world_size}", rank)
    print_rank0(f"  Train samples:      {len(train_loader.dataset)}", rank)
    print_rank0(f"  Per-GPU batch:      {args.batch_size}", rank)
    print_rank0(f"  Effective batch:    {args.batch_size} x {args.grad_accum} x {world_size} = {effective_batch}", rank)
    print_rank0(f"  Steps/epoch:        {steps_per_epoch}", rank)
    print_rank0(f"  Total steps:        {total_steps}", rank)
    print_rank0(f"  Warmup steps:       {warmup_steps}", rank)
    print_rank0(f"  Learning rate:      {args.lr} ({'constant' if args.constant_lr else 'cosine decay'})", rank)
    print_rank0(f"  Min LR:             {args.min_lr}", rank)
    print_rank0(f"  Freeze encoder:     first {args.freeze_encoder_epochs} epochs", rank)
    print_rank0(f"  Mixed precision:    {'bf16' if args.bf16 else 'fp16' if args.fp16 else 'off'}", rank)
    print_rank0(f"  Weight decay:       {args.weight_decay}", rank)
    print_rank0(f"  Grad clip norm:     {args.grad_clip}", rank)
    if args.no_spec_augment:
        print_rank0(f"  SpecAugment:        OFF", rank)
    else:
        print_rank0(f"  SpecAugment:        freq={args.freq_masks}x{args.freq_width} time={args.time_masks}x{args.time_width}", rank)
    print_rank0(f"  Speed perturb:      {args.speed_perturb_factors if args.speed_perturb else 'OFF'}", rank)
    print_rank0(f"  LR decay epochs:    {args.lr_decay_epochs}", rank)
    print_rank0(f"  Early stop:         {args.early_stop_patience} epochs", rank)
    if args.confidence_penalty > 0:
        print_rank0(f"  Confidence penalty: {args.confidence_penalty}", rank)
    if args.streaming_chunk_sec > 0:
        print_rank0(f"  Streaming train:    forced att_context=[70,13] only", rank)
    print_rank0(f"  Val manifest:       {args.val_manifest}", rank)
    print_rank0(f"{'='*65}\n", rank)

    global_step = 0
    best_wer = float("inf")
    best_val_loss = float("inf")
    patience_counter = 0
    start_epoch = 0

    # Track top-K best WER checkpoints
    top_k_wer = 3
    top_k_checkpoints = []  # list of (wer, epoch, path)

    # Track WER per epoch for convergence analysis
    wer_history = []

    import time as time_module

    # Resume from training checkpoint if specified
    if args.resume_training:
        ckpt_path = args.resume_training
        if os.path.isdir(ckpt_path):
            # Load latest model weights if available
            latest_model_path = os.path.join(ckpt_path, "latest_model.pt")
            if os.path.exists(latest_model_path):
                print_rank0(f"  Loading latest model weights from: {latest_model_path}", rank)
                sd = torch.load(latest_model_path, map_location=device, weights_only=False)
                model.load_state_dict(sd)
                del sd
                torch.cuda.empty_cache()
            ckpt_path = os.path.join(ckpt_path, "training_state.pt")
        if os.path.exists(ckpt_path):
            print_rank0(f"  Resuming training state from: {ckpt_path}", rank)
            ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
            optimizer.load_state_dict(ckpt["optimizer"])
            scheduler.load_state_dict(ckpt["scheduler"])
            start_epoch = ckpt["epoch"]
            global_step = ckpt["global_step"]
            best_wer = ckpt["best_wer"]
            best_val_loss = ckpt["best_val_loss"]
            patience_counter = ckpt["patience_counter"]
            wer_history = ckpt.get("wer_history", [])
            if scaler and "scaler" in ckpt:
                scaler.load_state_dict(ckpt["scaler"])
            print_rank0(f"  Resumed at epoch {start_epoch}, step {global_step}, best_wer={best_wer:.2f}%", rank)
            del ckpt
            torch.cuda.empty_cache()
        else:
            print_rank0(f"  WARNING: resume_training path not found: {ckpt_path}", rank)

    if is_distributed:
        dist.barrier()

    # ── Epoch 0: evaluate before any training ──
    if start_epoch == 0:
        print_rank0(f"\n  === Epoch 0 (pre-training baseline) ===", rank)
        import sys as _sys

        # Compute initial train loss + grad norm on first few batches (all ranks)
        student.train()
        e0_loss = 0.0
        e0_gnorm = 0.0
        e0_steps = 0
        e0_max_batches = 20
        for batch_idx, batch in enumerate(train_loader):
            if batch is None:
                continue
            if batch_idx >= e0_max_batches:
                break
            try:
                if use_amp:
                    with torch.amp.autocast("cuda", dtype=amp_dtype):
                        loss = train_step(student, batch, device, confidence_penalty=0.0)
                    loss.backward()
                else:
                    loss = train_step(student, batch, device, confidence_penalty=0.0)
                    loss.backward()
                trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
                gnorm = torch.nn.utils.clip_grad_norm_(trainable, 1e6).item()
                e0_loss += loss.item()
                if math.isfinite(gnorm):
                    e0_gnorm += gnorm
                e0_steps += 1
                optimizer.zero_grad()
            except Exception:
                optimizer.zero_grad()
                continue

        if e0_steps > 0:
            print_rank0(f"    Epoch 0 train_loss={e0_loss/e0_steps:.4f} gnorm={e0_gnorm/e0_steps:.3f} (avg over {e0_steps} batches)", rank)

        # Tear down DDP before eval (same as regular epoch eval)
        if is_distributed:
            optimizer.zero_grad(set_to_none=True)
            del student
            student = None
            torch.cuda.empty_cache()
            dist.barrier()

        # Free GPU memory before eval
        optimizer.zero_grad(set_to_none=True)
        opt_state_backup_e0 = {}
        for k, v in optimizer.state.items():
            opt_state_backup_e0[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()}
        optimizer.state.clear()
        torch.cuda.empty_cache()
        gc.collect()

        # Evaluate WER + val_loss (all ranks run forward passes)
        print_rank0(f"\n  Evaluating {lang} (epoch 0)...", rank)
        _sys.stdout.flush()
        val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank)
        print_rank0(f"    [eval] WER done", rank); _sys.stdout.flush()
        val_loss = compute_val_loss(model, args.val_manifest, device)
        print_rank0(f"    [eval] val_loss done", rank); _sys.stdout.flush()

        if is_main(rank):
            print_rank0(f"    Epoch 0 WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank)
            wer_history.append({
                'epoch': 0,
                'wer': val_wer,
                'val_loss': val_loss,
                'lr': 0.0,
                'train_loss': e0_loss / max(1, e0_steps),
            })
        _sys.stdout.flush()

        # Restore optimizer states from CPU
        for k, v in opt_state_backup_e0.items():
            optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()}
        del opt_state_backup_e0
        torch.cuda.empty_cache()

        # Rebuild DDP for training
        if is_distributed:
            student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True)
            optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad]

        # Reset dataloader state
        if train_sampler is not None:
            train_sampler.set_epoch(0)

    for epoch in range(start_epoch, args.epochs):
        epoch_start = time_module.time()
        student.train()

        # Decay SpecAugment if enabled (all ranks need updated module)
        if args.decay_spec_augment:
            update_spec_augment(student, args, epoch, args.epochs, rank)

        if train_sampler is not None:
            train_sampler.set_epoch(epoch)

        # Phase management
        if epoch < args.freeze_encoder_epochs:
            for p in model.encoder.parameters():
                p.requires_grad = False
            phase = f"Encoder frozen ({epoch+1}/{args.freeze_encoder_epochs})"
        else:
            for p in model.encoder.parameters():
                p.requires_grad = True
            phase = "Full training"

        optimizer.param_groups[0]["params"] = [
            p for p in student.parameters() if p.requires_grad
        ]

        epoch_loss = 0.0
        epoch_steps = 0
        epoch_grad_norm = 0.0
        grad_norm_steps = 0
        inf_grad_steps = 0

        pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{args.epochs} [{lang}]",
                    leave=True, ncols=120, disable=not is_main(rank) or not sys.stderr.isatty())
        optimizer.zero_grad()

        max_batch_audio_sec = 0.0
        batch_lengths = []

        for batch_idx, batch in enumerate(pbar):
            if batch is None:
                continue

            # Track batch audio lengths
            audio, audio_len_t, _, _ = batch
            max_audio_samples = audio_len_t.max().item()
            total_audio_samples = audio_len_t.sum().item()
            max_sec = max_audio_samples / 16000
            total_sec = total_audio_samples / 16000
            batch_lengths.append(max_sec)
            if max_sec > max_batch_audio_sec:
                max_batch_audio_sec = max_sec

            try:
                if use_amp:
                    with torch.amp.autocast("cuda", dtype=amp_dtype):
                        loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty)
                    if scaler:
                        scaled_loss = loss / args.grad_accum
                        scaler.scale(scaled_loss).backward()
                    else:
                        (loss / args.grad_accum).backward()
                else:
                    loss = train_step(student, batch, device, confidence_penalty=args.confidence_penalty)
                    (loss / args.grad_accum).backward()

            except RuntimeError as e:
                if "out of memory" in str(e).lower():
                    torch.cuda.empty_cache()
                    print_rank0(f"\n    OOM at batch {batch_idx} (max_audio={max_sec:.1f}s, total={total_sec:.1f}s, batch_size={len(audio_len_t)}), skipping", rank)
                    optimizer.zero_grad()
                    continue
                raise

            epoch_loss += loss.item()
            epoch_steps += 1

            if (batch_idx + 1) % args.grad_accum == 0:
                if scaler:
                    scaler.unscale_(optimizer)
                trainable = [p for p in student.parameters() if p.requires_grad and p.grad is not None]
                grad_norm = torch.nn.utils.clip_grad_norm_(trainable, args.grad_clip).item()
                if scaler:
                    scaler.step(optimizer)
                    scaler.update()
                else:
                    optimizer.step()

                if math.isfinite(grad_norm):
                    epoch_grad_norm += grad_norm
                    grad_norm_steps += 1
                else:
                    inf_grad_steps += 1
                scheduler.step()
                optimizer.zero_grad()
                global_step += 1

            if epoch_steps % args.log_every == 0 and epoch_steps > 0 and is_main(rank):
                avg_loss = epoch_loss / epoch_steps
                avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
                lr = optimizer.param_groups[0]["lr"]
                gnorm_str = f"{avg_gnorm:.2f}" if grad_norm_steps > 0 else "n/a"
                if inf_grad_steps > 0:
                    gnorm_str += f" ({inf_grad_steps} skipped)"
                pbar.set_postfix(loss=f"{avg_loss:.3f}", gnorm=gnorm_str,
                                 lr=f"{lr:.1e}", step=global_step)

        # End of epoch
        epoch_time = time_module.time() - epoch_start
        avg_loss = epoch_loss / max(1, epoch_steps)
        avg_gnorm = epoch_grad_norm / max(1, grad_norm_steps)
        gnorm_display = f"{avg_gnorm:.3f}" if grad_norm_steps > 0 else "n/a"
        if inf_grad_steps > 0:
            gnorm_display += f" ({inf_grad_steps} inf-skipped)"
        samples_per_sec = (epoch_steps * args.batch_size) / epoch_time
        gpu_mem = torch.cuda.max_memory_allocated(device) / 1e9 if torch.cuda.is_available() else 0

        # Batch length stats
        if batch_lengths:
            avg_max_sec = sum(batch_lengths) / len(batch_lengths)
            p95 = sorted(batch_lengths)[int(0.95 * len(batch_lengths))]
            print_rank0(f"    [batch stats] max_audio={max_batch_audio_sec:.1f}s avg_max={avg_max_sec:.1f}s p95={p95:.1f}s", rank)

        print_rank0(f"\n  Epoch {epoch+1} [{lang}] | {phase} | loss={avg_loss:.4f} "
                    f"gnorm={gnorm_display} lr={optimizer.param_groups[0]['lr']:.2e}"
                    f" | {epoch_time/60:.1f}min | {samples_per_sec:.0f} samples/s | GPU: {gpu_mem:.1f}GB", rank)

        # Tear down DDP before eval to remove forward hooks from model.
        # DDP with find_unused_parameters=True registers hooks on the underlying
        # model, so calling model.forward() during rank-0-only eval would trigger
        # DDP communication and deadlock the other ranks.
        if is_distributed:
            optimizer.zero_grad(set_to_none=True)
            del student
            student = None
            torch.cuda.empty_cache()
            dist.barrier()

        # Free GPU memory before eval: offload optimizer states to CPU
        optimizer.zero_grad(set_to_none=True)
        opt_state_backup = {}
        for k, v in optimizer.state.items():
            opt_state_backup[k] = {sk: sv.cpu() if torch.is_tensor(sv) else sv for sk, sv in v.items()}
        optimizer.state.clear()
        torch.cuda.empty_cache()
        gc.collect()

        mem_after = torch.cuda.memory_allocated(device) / 1e9
        print_rank0(f"    [pre-eval] GPU mem after offload: {mem_after:.1f}GB", rank)
        import sys as _sys; _sys.stdout.flush()

        # Evaluation — ALL ranks run forward passes (needed for SyncBatchNorm / distributed
        # layers inside NeMo encoder), but only rank 0 uses the results.
        if (epoch + 1) % args.eval_every_epoch == 0:
            try:
                print_rank0(f"\n  Evaluating {lang}...", rank)
                _sys.stdout.flush()

                val_wer, _, _, _, _ = evaluate_batch(model, args.val_manifest, device, rank=rank)
                print_rank0(f"    [eval] WER done", rank); _sys.stdout.flush()
                val_loss = compute_val_loss(model, args.val_manifest, device)
                print_rank0(f"    [eval] val_loss done", rank); _sys.stdout.flush()

                if is_main(rank):
                    print_rank0(f"    {lang} Batch WER: {val_wer:.2f}% | Val loss: {val_loss:.4f}", rank)

                    wer_history.append({
                        'epoch': epoch + 1,
                        'wer': val_wer,
                        'val_loss': val_loss,
                        'lr': optimizer.param_groups[0]["lr"],
                        'train_loss': avg_loss,
                    })

                    if val_wer < best_wer:
                        best_wer = val_wer
                        patience_counter = 0
                        save_path = os.path.join(args.output_dir, "best_model.nemo")
                        print_rank0(f"    [saving] best_model.nemo...", rank); _sys.stdout.flush()
                        model.save_to(save_path)
                        print_rank0(f"    New best WER! WER={best_wer:.2f}% -> {save_path}", rank)
                    else:
                        patience_counter += 1
                        print_rank0(f"    No WER improvement ({patience_counter}/{args.early_stop_patience})", rank)

                    # Save top-K best WER checkpoints for post-hoc evaluation
                    should_save_topk = len(top_k_checkpoints) < top_k_wer or val_wer < top_k_checkpoints[-1][0]
                    if should_save_topk:
                        topk_path = os.path.join(args.output_dir, f"best_model_wer_ep{epoch+1}.nemo")
                        print_rank0(f"    [saving] top-{top_k_wer} checkpoint (WER={val_wer:.2f}%)...", rank); _sys.stdout.flush()
                        model.save_to(topk_path)
                        top_k_checkpoints.append((val_wer, epoch + 1, topk_path))
                        top_k_checkpoints.sort(key=lambda x: x[0])  # sort by WER ascending
                        # Remove worst checkpoint if we exceed top_k_wer
                        while len(top_k_checkpoints) > top_k_wer:
                            _, _, old_path = top_k_checkpoints.pop()
                            if os.path.exists(old_path):
                                os.remove(old_path)
                                print_rank0(f"    [removed] {os.path.basename(old_path)}", rank)

                    if args.early_stop_patience > 0 and patience_counter >= args.early_stop_patience:
                        print_rank0(f"\n    Early stopping! No improvement for {args.early_stop_patience} epochs.", rank)
                        break

                    if val_loss < best_val_loss:
                        best_val_loss = val_loss
                        save_path = os.path.join(args.output_dir, "best_model_loss.nemo")
                        print_rank0(f"    [saving] best_model_loss.nemo...", rank); _sys.stdout.flush()
                        model.save_to(save_path)
                        print_rank0(f"    New best loss! loss={best_val_loss:.4f} -> {save_path}", rank)
            except Exception as e:
                print_rank0(f"    [eval error] {type(e).__name__}: {e} — skipping", rank)

        print_rank0(f"    [post-eval] reaching barrier...", rank); sys.stdout.flush()

        # Restore optimizer states from CPU
        for k, v in opt_state_backup.items():
            optimizer.state[k] = {sk: sv.to(device) if torch.is_tensor(sv) else sv for sk, sv in v.items()}
        del opt_state_backup
        torch.cuda.empty_cache()

        # Rebuild DDP for next training epoch (after eval is done)
        if is_distributed:
            student = DDP(model, device_ids=[int(os.environ.get("LOCAL_RANK", 0))], find_unused_parameters=True)
            optimizer.param_groups[0]["params"] = [p for p in student.parameters() if p.requires_grad]

        # Save full training state for resumability
        if is_main(rank) and args.save_every_epoch > 0 and (epoch + 1) % args.save_every_epoch == 0:
            # Save latest model weights as raw state dict (fast, avoids NeMo save_to overhead)
            latest_path = os.path.join(args.output_dir, "latest_model.pt")
            torch.save(model.state_dict(), latest_path + ".tmp")
            os.replace(latest_path + ".tmp", latest_path)

            state = {
                "epoch": epoch + 1,
                "global_step": global_step,
                "optimizer": optimizer.state_dict(),
                "scheduler": scheduler.state_dict(),
                "best_wer": best_wer,
                "best_val_loss": best_val_loss,
                "patience_counter": patience_counter,
                "wer_history": wer_history,
            }
            if scaler:
                state["scaler"] = scaler.state_dict()
            state_path = os.path.join(args.output_dir, "training_state.pt")
            torch.save(state, state_path + ".tmp")
            os.replace(state_path + ".tmp", state_path)

        # Clear GPU memory fragmentation from eval/save before next training epoch
        torch.cuda.empty_cache()

        if is_distributed:
            dist.barrier()

    # Save WER history for convergence analysis
    if is_main(rank):
        history_path = os.path.join(args.output_dir, "wer_history.json")
        with open(history_path, "w") as f:
            json.dump(wer_history, f, indent=2)
        print_rank0(f"\n  WER history saved to {history_path}", rank)

        # Final save
        save_path = os.path.join(args.output_dir, "final_model.nemo")
        model.save_to(save_path)
        print_rank0(f"  Final model -> {save_path}", rank)
        print_rank0(f"  Best {lang} WER: {best_wer:.2f}%", rank)

    return student


# ═══════════════════════════════════════════════════════════
# Entry Point
# ═══════════════════════════════════════════════════════════

def main():
    args = parse_args()

    rank, world_size, local_rank, is_distributed = setup_ddp()
    device = torch.device(f"cuda:{local_rank}")

    torch.manual_seed(args.seed + rank)
    np.random.seed(args.seed + rank)
    torch.cuda.manual_seed_all(args.seed + rank)
    import random
    random.seed(args.seed + rank)

    os.makedirs(args.output_dir, exist_ok=True)

    lang = args.lang.upper()
    starting_from = "multilingual base" if args.resume_from else "English checkpoint"

    print_rank0(f"\n{'='*65}", rank)
    print_rank0(f"  Nemotron Streaming ASR — {lang} Training", rank)
    print_rank0(f"{'='*65}", rank)
    print_rank0(f"  Language:  {lang}", rank)
    print_rank0(f"  Path:      {starting_from}", rank)
    print_rank0(f"  GPUs:      {world_size}", rank)
    if args.resume_from:
        print_rank0(f"  Base:      {args.resume_from}", rank)
    else:
        print_rank0(f"  Student:   {args.student}", rank)
    print_rank0(f"  Train:     {args.train_manifest}", rank)
    print_rank0(f"  Val:       {args.val_manifest}", rank)
    print_rank0(f"{'='*65}", rank)

    # Load model
    print_rank0(f"\n[1/3] Loading model...", rank)
    student = load_student(args, device, rank)

    # Wrap in DDP
    if is_distributed:
        student = DDP(student, device_ids=[local_rank], find_unused_parameters=True)
        print_rank0(f"  Wrapped in DDP (find_unused_parameters=True)", rank)

    # Create dataloader
    print_rank0(f"\n[2/3] Creating data loaders...", rank)
    model_for_tok = student.module if isinstance(student, DDP) else student
    train_dataset = ASRManifestDataset(
        args.train_manifest,
        model_for_tok.tokenizer,
        min_duration=args.min_duration,
        max_duration=args.max_duration,
        speed_perturb=args.speed_perturb,
        speed_perturb_factors=args.speed_perturb_factors,
        max_train_hours=args.max_train_hours,
        seed=args.data_seed,
    )
    print_rank0(f"  Train dataset: {len(train_dataset)} samples", rank)
    if args.max_train_hours > 0:
        print_rank0(f"  Subsampled to {train_dataset.total_hours:.1f}h (requested {args.max_train_hours}h)", rank)

    # Offset by -42 so --seed=42 (default) keeps PyTorch's default sampler seed=0
    # for backward compat with prior runs. --seed=43 -> sampler seed=1, etc.
    train_sampler = DistributedSampler(train_dataset, shuffle=True, seed=args.seed - 42) if is_distributed else None
    train_loader = DataLoader(
        train_dataset,
        batch_size=args.batch_size,
        shuffle=(train_sampler is None),
        sampler=train_sampler,
        num_workers=args.num_workers,
        collate_fn=collate_asr,
        pin_memory=True,
        drop_last=True,
    )

    # Train
    print_rank0(f"\n[3/3] Starting {lang} training...", rank)
    student = train(
        student, train_loader, train_sampler,
        args, device, rank, is_distributed,
    )

    # Final eval on best model — all ranks run eval (NeMo model has distributed internals),
    # only rank 0 prints/uses results
    import nemo.collections.asr as nemo_asr

    best_path = os.path.join(args.output_dir, "best_model.nemo")
    if os.path.exists(best_path):
        print_rank0(f"\n  Loading best model from {best_path}...", rank)
        best_model = nemo_asr.models.ASRModel.restore_from(best_path, map_location=device)
        best_model = best_model.to(device)
        best_model.eval()
    else:
        print_rank0(f"\n  Best model not found, using final model.", rank)
        best_model = model

    print_rank0(f"\n{'='*65}", rank)
    print_rank0(f"  Final Evaluation — {lang} (best checkpoint)", rank)
    print_rank0(f"{'='*65}", rank)

    batch_wer, b_s, b_d, b_i, b_w = evaluate_batch(best_model, args.val_manifest, device, rank=rank)
    if is_main(rank):
        print_rank0(f"  {lang} Val Batch WER:     {batch_wer:.2f}%  (S={b_s/max(b_w,1)*100:.2f}% D={b_d/max(b_w,1)*100:.2f}% I={b_i/max(b_w,1)*100:.2f}%)", rank)
        print_rank0(f"    Counts: subs={b_s} dels={b_d} ins={b_i} / {b_w} ref words", rank)

    print_rank0(f"\n  Running streaming eval...", rank)
    stream_wer, s_s, s_d, s_i, s_w = evaluate_streaming(best_model, args.val_manifest, device, rank=rank)
    if is_main(rank):
        print_rank0(f"  {lang} Val Streaming WER:  {stream_wer:.2f}%  (S={s_s/max(s_w,1)*100:.2f}% D={s_d/max(s_w,1)*100:.2f}% I={s_i/max(s_w,1)*100:.2f}%)", rank)
        print_rank0(f"    Counts: subs={s_s} dels={s_d} ins={s_i} / {s_w} ref words", rank)

    if args.test_manifest:
        print_rank0(f"\n{'='*65}", rank)
        print_rank0(f"  Test Evaluation — {lang} (best checkpoint)", rank)
        print_rank0(f"{'='*65}", rank)

        test_batch_wer, tb_s, tb_d, tb_i, tb_w = evaluate_batch(best_model, args.test_manifest, device, rank=rank)
        if is_main(rank):
            print_rank0(f"  {lang} Test Batch WER:     {test_batch_wer:.2f}%  (S={tb_s/max(tb_w,1)*100:.2f}% D={tb_d/max(tb_w,1)*100:.2f}% I={tb_i/max(tb_w,1)*100:.2f}%)", rank)
            print_rank0(f"    Counts: subs={tb_s} dels={tb_d} ins={tb_i} / {tb_w} ref words", rank)

        print_rank0(f"\n  Running streaming test eval...", rank)
        test_stream_wer, ts_s, ts_d, ts_i, ts_w = evaluate_streaming(best_model, args.test_manifest, device, rank=rank)
        if is_main(rank):
            print_rank0(f"  {lang} Test Streaming WER:  {test_stream_wer:.2f}%  (S={ts_s/max(ts_w,1)*100:.2f}% D={ts_d/max(ts_w,1)*100:.2f}% I={ts_i/max(ts_w,1)*100:.2f}%)", rank)
            print_rank0(f"    Counts: subs={ts_s} dels={ts_d} ins={ts_i} / {ts_w} ref words", rank)

    del best_model
    torch.cuda.empty_cache()

    # Evaluate best-by-loss model if it exists
    best_loss_path = os.path.join(args.output_dir, "best_model_loss.nemo")
    if os.path.exists(best_loss_path):
        print_rank0(f"\n{'='*65}", rank)
        print_rank0(f"  Final Evaluation — {lang} (best loss checkpoint)", rank)
        print_rank0(f"{'='*65}", rank)

        print_rank0(f"  Loading best-by-loss model from {best_loss_path}...", rank)
        best_loss_model = nemo_asr.models.ASRModel.restore_from(best_loss_path, map_location=device)
        best_loss_model = best_loss_model.to(device)
        best_loss_model.eval()

        bl_wer, bl_s, bl_d, bl_i, bl_w = evaluate_batch(best_loss_model, args.val_manifest, device, rank=rank)
        if is_main(rank):
            print_rank0(f"  {lang} Val Batch WER (loss-best):     {bl_wer:.2f}%  (S={bl_s/max(bl_w,1)*100:.2f}% D={bl_d/max(bl_w,1)*100:.2f}% I={bl_i/max(bl_w,1)*100:.2f}%)", rank)

        if args.test_manifest:
            tbl_wer, tbl_s, tbl_d, tbl_i, tbl_w = evaluate_batch(best_loss_model, args.test_manifest, device, rank=rank)
            if is_main(rank):
                print_rank0(f"  {lang} Test Batch WER (loss-best):    {tbl_wer:.2f}%  (S={tbl_s/max(tbl_w,1)*100:.2f}% D={tbl_d/max(tbl_w,1)*100:.2f}% I={tbl_i/max(tbl_w,1)*100:.2f}%)", rank)

        del best_loss_model
        torch.cuda.empty_cache()

    # All ranks must wait for rank 0's final eval before destroying process group
    if is_distributed:
        dist.barrier()

    cleanup_ddp(is_distributed)


if __name__ == "__main__":
    main()