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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
#!/usr/bin/env python3

# Version: starts from baniguru_kirtan_stream_v2_224_27.nemo and fine-tunes
# using [202,100] attention context (about 8.08 s left, 4.00 s right).

import argparse
import copy
import json
import os
import shutil
import subprocess
import time
from pathlib import Path

import torch
import pytorch_lightning as pl
from hydra.utils import instantiate
from omegaconf import OmegaConf, open_dict
from pytorch_lightning.callbacks import Callback, TQDMProgressBar

import nemo.collections.asr as nemo_asr


###############################################################################
# DATASET CONFIGURATION
###############################################################################

# The script lives in /workspace and manifests live in /workspace/training_data.
DATA_ROOT = Path(__file__).resolve().parent

# Manifest paths are selected at startup.
#
# Normal:
#   train_manifest.json
#   kirtan_val_manifest.json
#   sehaj_paath_val_manifest.json
#
# --test:
#   training_manifest_test.json
#   kirtan_val_manifest.json       (FULL validation)
#   sehaj_paath_val_manifest.json   (FULL validation)
#
# Audio paths inside the manifests are used exactly as written.
TRAIN_MANIFEST = None
KIRTAN_VAL_MANIFEST = None
SEHAJ_VAL_MANIFEST = None


def configure_manifests(test_mode: bool) -> None:
    """Use small training data in --test, but always use full validation."""
    global TRAIN_MANIFEST
    global KIRTAN_VAL_MANIFEST
    global SEHAJ_VAL_MANIFEST

    if test_mode:
        TRAIN_MANIFEST = DATA_ROOT / "training_data/training_manifest_test.json"
    else:
        TRAIN_MANIFEST = DATA_ROOT / "training_data/training_manifest.json"

    # Always score the real/full validation sets, including --test.
    KIRTAN_VAL_MANIFEST = DATA_ROOT / "training_data/kirtan_val_manifest.json"
    SEHAJ_VAL_MANIFEST = DATA_ROOT / "training_data/sehaj_paath_val_manifest.json"

EXPECTED_SAMPLE_RATE = 16_000
LANGUAGE_CODE = "pa"

# Use one explicit decoder for validation so the metric is stable across epochs.
# The model is hybrid RNNT+CTC; CTC is used here only for explicit WER/CER scoring.
VALIDATION_DECODER = "ctc"


###############################################################################
# MODEL CONFIGURATION
###############################################################################

# Start from the currently exported streaming model. Its learned weights and
# [224,27] streaming configuration are restored first; the encoder is then
# rebuilt from those weights below for the new [202,100] training context.
MODEL_PATH = Path(
    "/workspace/resume_checkpoint/baniguru_kirtan_stream_v2_224_27.nemo"
).expanduser().resolve()
SOURCE_MODEL_ATT_CONTEXT = [224, 27]

# The first run uses MODEL_PATH directly (weights only; fresh optimizer and
# scheduler). After that, only this context-specific rolling checkpoint is used
# to resume the complete Lightning state.
START_CHECKPOINT_PATH = None

# Rolling full-Lightning checkpoint produced by THIS NEW [202,100] run.
# On any restart, this takes precedence over the exported-model initialization and
# restores the complete Lightning state (model + optimizer + scheduler + epoch +
# callback state). The distinct filename prevents resuming a different context.
LAST_STABLE_CHECKPOINT_PATH = Path(
    "/workspace/resume_checkpoint/stream_202_100_last_stable.ckpt"
).expanduser().resolve()


###############################################################################
# CACHE-AWARE / STREAMING ENCODER CONFIGURATION

# Context	Look-ahead	Chunk
# [112,27]	1080 ms	1120 ms
# [224,27]	520 ms	560 ms
# [112,6]	240 ms	280 ms
# [112,3]	120 ms	160 ms
# [112,1]	40 ms	80 ms
# [112,0]	0 ms	40 ms

# Exported MODEL_PATH context: [224,27] (224x40ms left, 27x40ms right).
# Training context: [202,100] = 202x40ms left (~8.08s), 100x40ms right (~4.00s).

# Diagnostic:
# [112, 100]                     4 sec right

###############################################################################

STREAM_ATT_CONTEXTS = [[202, 100]]

# Train the complete manifest using ~8.08 s of left context and ~4.00 s of right context.

CAUSAL_CONV_CONTEXT = [30, 0]

###############################################################################
# TRAINING CONFIGURATION
###############################################################################

BATCH_SIZE = 8

# Conservative full-model fine-tuning rate for the [202,100] adaptation.
LEARNING_RATE = 1e-5

# Upper limit.
# Early stopping can stop training before reaching this.
MAX_EPOCHS = 50

# Effective batch size:
#
# BATCH_SIZE * ACCUMULATE_GRAD_BATCHES
#
# 4 * 2 = 8
ACCUMULATE_GRAD_BATCHES = 1

# Tiny fixed CTC probe during training.
CTC_PROBE_EVERY_OPTIMIZER_STEPS = 1000
CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS = 2000
CTC_PROBE_SAMPLE_COUNT = 2


###############################################################################
# EARLY STOPPING CONFIGURATION
###############################################################################

# Stop after this many consecutive validation epochs without improvement.
EARLY_STOP_PATIENCE = 20
EARLY_STOP_WARMUP_EPOCHS = 0

# WER needs to improve by at least this much to count as an improvement.
#
# Example:
#   old WER = 0.1000
#   new WER = 0.09995
#
# Difference = 0.00005
#
# With MIN_WER_IMPROVEMENT = 0.0001,
# that would NOT count as an improvement.
MIN_WER_IMPROVEMENT = 0.0001

# Match the offline v3 checkpoint rule: Kirtan CER is primary. Sehaj WER may
# also promote a checkpoint when it improves by at least MIN_WER_IMPROVEMENT
# and Kirtan CER is no more than 0.5 percentage points worse than the currently
# selected best checkpoint. CER is stored as a fraction, so 0.005 == 0.5 points.
KIRTAN_CER_TOLERANCE_FOR_SEHAJ = 0.005


###############################################################################
# CLOUDFLARE R2 BACKUP CONFIGURATION
###############################################################################

# Upload ONLY best.ckpt when any accepted metric (Kirtan CER, Kirtan WER, or Sehaj WER) improves.
# Credentials are read from environment variables so secrets are not stored
# inside this training script.
R2_UPLOAD_ENABLED = True
R2_OBJECT_KEY = os.environ.get(
    "R2_OBJECT_KEY",
    "checkpoints/stream-202_100-best.ckpt",
)
R2_UPLOAD_RETRIES = 3
R2_RETRY_DELAY_SECONDS = 10


###############################################################################
# VAST.AI AUTO-DESTROY CONFIGURATION
###############################################################################

# Full runs automatically destroy the current Vast instance only after:
#   1. training has finished (early stopping or max epochs), AND
#   2. a best.ckpt was successfully uploaded to R2.
#
# --test NEVER destroys the instance.
AUTO_DESTROY_VAST = False


###############################################################################
# OUTPUT / CHECKPOINT / LOG CONFIGURATION
###############################################################################

# Put large/persistent training outputs under this directory.
#
# Vast.ai workspace output directory.
#
# Checkpoints, metrics, and the final model stay under OUTPUT_ROOT.
#
#   OUTPUT_ROOT/
#   β”œβ”€β”€ checkpoints/
#   β”‚   β”œβ”€β”€ best.ckpt
#   β”‚   β”œβ”€β”€ epoch_XXX.ckpt
#   β”‚   └── epoch_YYY.ckpt
#   β”œβ”€β”€ wer_history.json
#   └── gurbani_sehaj_paath_v1_base_indicconformer_stt_multi_hybrid_rnnt_600m.nemo
#
OUTPUT_ROOT = Path(
    "/workspace/asr_stream_training_202_100"
).expanduser().resolve()

# Final .nemo model saved when training finishes / early-stops.
OUTPUT_MODEL = (
    OUTPUT_ROOT
    / "baniguru_kirtan_stream_202_100.nemo"
)

# Best checkpoint + last two epoch checkpoints.
CHECKPOINT_DIR = (
    OUTPUT_ROOT / "checkpoints"
)

BEST_CHECKPOINT_PATH = (
    CHECKPOINT_DIR / "best.ckpt"
)

# Per-epoch validation metrics for BOTH domains.
# Contains kirtan WER/CER + sehaj WER/CER.
EPOCH_METRICS_PATH = (
    OUTPUT_ROOT / "epoch_metrics.json"
)


def configure_outputs(test_mode: bool, offline: bool = False) -> None:
    """Keep test artifacts separate and optionally disable R2 for test runs."""
    global OUTPUT_ROOT
    global OUTPUT_MODEL
    global CHECKPOINT_DIR
    global BEST_CHECKPOINT_PATH
    global EPOCH_METRICS_PATH
    global R2_OBJECT_KEY
    global R2_UPLOAD_ENABLED

    if test_mode:
        OUTPUT_ROOT = Path("/workspace/asr_stream_training_202_100_test").expanduser().resolve()
        OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_stream_202_100.nemo"
        CHECKPOINT_DIR = OUTPUT_ROOT / "checkpoints"
        BEST_CHECKPOINT_PATH = CHECKPOINT_DIR / "best.ckpt"
        EPOCH_METRICS_PATH = OUTPUT_ROOT / "epoch_metrics.json"

        # Online test runs use a separate R2 object and never overwrite
        # the full-run best checkpoint.
        R2_OBJECT_KEY = "checkpoints/test-202_100-best.ckpt"

    if offline:
        # --offline is intentionally restricted to --test in parse_args().
        R2_UPLOAD_ENABLED = False

###############################################################################
# CALLBACK: PROGRESS BAR WITH HUMAN-READABLE EPOCH NUMBER
###############################################################################

class EpochProgressBar(TQDMProgressBar):
    def get_metrics(self, trainer, pl_module):
        items = super().get_metrics(trainer, pl_module)
        items["epoch"] = trainer.current_epoch + 1
        return items


###############################################################################
# CALLBACK: EPOCH TIMER
###############################################################################

class EpochTimer(Callback):
    def __init__(self):
        super().__init__()
        self.start_time = None

    def on_train_epoch_start(
        self,
        trainer,
        pl_module,
    ):
        self.start_time = time.time()

    def on_train_epoch_end(
        self,
        trainer,
        pl_module,
    ):
        if self.start_time is None:
            print(
                f"\nEpoch {trainer.current_epoch + 1} completed "
                "(timer unavailable because training resumed mid-epoch)"
            )
            return

        elapsed = time.time() - self.start_time

        print(
            f"\nEpoch {trainer.current_epoch + 1} "
            f"completed in {elapsed / 60:.2f} minutes"
        )


###############################################################################
# VALIDATION METRICS HELPERS
###############################################################################

def levenshtein_ops(reference, hypothesis):
    """
    Return (substitutions, deletions, insertions) for two sequences.
    """
    n = len(reference)
    m = len(hypothesis)

    # dp[i][j] = (cost, S, D, I)
    dp = [[None] * (m + 1) for _ in range(n + 1)]

    dp[0][0] = (0, 0, 0, 0)

    for i in range(1, n + 1):
        dp[i][0] = (i, 0, i, 0)

    for j in range(1, m + 1):
        dp[0][j] = (j, 0, 0, j)

    for i in range(1, n + 1):
        for j in range(1, m + 1):

            if reference[i - 1] == hypothesis[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
                continue

            sub_prev = dp[i - 1][j - 1]
            del_prev = dp[i - 1][j]
            ins_prev = dp[i][j - 1]

            candidates = [
                (
                    sub_prev[0] + 1,
                    sub_prev[1] + 1,
                    sub_prev[2],
                    sub_prev[3],
                ),
                (
                    del_prev[0] + 1,
                    del_prev[1],
                    del_prev[2] + 1,
                    del_prev[3],
                ),
                (
                    ins_prev[0] + 1,
                    ins_prev[1],
                    ins_prev[2],
                    ins_prev[3] + 1,
                ),
            ]

            dp[i][j] = min(
                candidates,
                key=lambda item: (
                    item[0],
                    item[2],  # prefer fewer deletions on ties
                    item[3],
                    item[1],
                ),
            )

    _, substitutions, deletions, insertions = dp[n][m]

    return substitutions, deletions, insertions


def extract_text_from_hypothesis(item):
    if isinstance(item, str):
        return item

    if hasattr(item, "text"):
        return str(item.text)

    if isinstance(item, dict):
        if "text" in item:
            return str(item["text"])

        if "pred_text" in item:
            return str(item["pred_text"])

    return str(item)


def select_primary_transcriptions(outputs, expected_count):
    """
    Normalize NeMo transcribe() output.

    Hybrid RNNT+CTC models can return more than one decoding branch.
    We select the first complete branch, which is treated here as the
    primary transcription stream for BOTH domains and all epochs.
    """
    if isinstance(outputs, tuple):
        outputs = list(outputs)

    if isinstance(outputs, list):

        # Normal case: one hypothesis per input.
        if len(outputs) == expected_count and (
            expected_count == 0
            or not isinstance(outputs[0], (list, tuple))
        ):
            return [
                extract_text_from_hypothesis(item)
                for item in outputs
            ]

        # Hybrid case: [rnnt_outputs, ctc_outputs, ...]
        for branch in outputs:
            if (
                isinstance(branch, (list, tuple))
                and len(branch) == expected_count
            ):
                return [
                    extract_text_from_hypothesis(item)
                    for item in branch
                ]

    raise RuntimeError(
        "Could not identify the primary transcribe() output branch. "
        f"Expected {expected_count} predictions; got type={type(outputs)}"
    )


def load_validation_manifest(manifest_path: Path):
    samples = []

    with Path(manifest_path).open(
        "r",
        encoding="utf-8",
    ) as handle:

        for line_number, line in enumerate(
            handle,
            start=1,
        ):
            line = line.strip()

            if not line:
                continue

            item = json.loads(line)

            audio_path = item.get(
                "audio_filepath"
            )

            text = item.get(
                "text"
            )

            if not audio_path:
                raise RuntimeError(
                    f"{manifest_path}: line {line_number} "
                    "has no audio_filepath."
                )

            if text is None:
                raise RuntimeError(
                    f"{manifest_path}: line {line_number} "
                    "has no text."
                )

            language = item.get("lang")

            if language != LANGUAGE_CODE:
                raise RuntimeError(
                    f"{manifest_path}: line {line_number} "
                    f"must have lang='{LANGUAGE_CODE}', got {language!r}."
                )

            samples.append(
                {
                    "audio_filepath": str(audio_path),
                    "text": " ".join(
                        str(text).strip().split()
                    ),
                    "lang": language,
                }
            )

    if not samples:
        raise RuntimeError(
            f"Validation manifest is empty: {manifest_path}"
        )

    return samples



def gpu_safe_transcribe(
    model,
    audio_paths,
    batch_size: int,
    verbose: bool,
):
    """
    Explicit transcription helper.

    The model is moved to CUDA before the pre-train health check. The patched
    AI4Bharat hybrid _transcribe_forward() moves file-dataloader audio tensors
    onto the same model device before forward(), so no runtime monkey-patching
    is needed here.
    """
    return model.transcribe(
        audio_paths,
        batch_size=batch_size,
        return_hypotheses=False,
        verbose=verbose,
        language_id=LANGUAGE_CODE,
    )

def score_validation_manifest(
    model,
    manifest_path: Path,
    batch_size: int,
):
    """
    Explicitly transcribe one validation manifest and return STRICT
    word-level WER and character-level CER.

    Validation is forced onto one decoder (CTC) for every epoch so a hybrid
    RNNT+CTC model cannot silently switch decoding branches between calls.
    The model stays on its existing device (normally CUDA) and its training/eval
    state and previous decoder are restored even if validation raises.

    Spaces are excluded from CER.
    """

    samples = load_validation_manifest(manifest_path)

    total_word_substitutions = 0
    total_word_deletions = 0
    total_word_insertions = 0
    total_reference_words = 0
    total_predicted_words = 0

    total_char_substitutions = 0
    total_char_deletions = 0
    total_char_insertions = 0
    total_reference_chars = 0
    total_predicted_chars = 0

    special_or_empty_outputs = 0
    checked_outputs = 0

    was_training = model.training
    previous_decoder = getattr(model, "cur_decoder", None)

    model.eval()

    if not hasattr(model, "cur_decoder"):
        raise RuntimeError(
            "Hybrid validation expected model.cur_decoder, but the restored "
            "model does not expose it. Refusing to compute an ambiguous WER."
        )

    model.cur_decoder = VALIDATION_DECODER

    try:
        with torch.no_grad():
            for start in range(0, len(samples), batch_size):
                batch = samples[start:start + batch_size]

                audio_paths = [
                    item["audio_filepath"]
                    for item in batch
                ]

                outputs = gpu_safe_transcribe(
                    model=model,
                    audio_paths=audio_paths,
                    batch_size=batch_size,
                    verbose=True,
                )

                hypotheses = select_primary_transcriptions(
                    outputs,
                    expected_count=len(batch),
                )

                normalized_batch = [
                    " ".join(str(value).strip().split())
                    for value in hypotheses
                ]

                checked_outputs += len(normalized_batch)
                special_or_empty_outputs += sum(
                    value in {"<unk>", "<blank>", ""}
                    for value in normalized_batch
                )

                if start == 0:
                    print("\nVALIDATION DEBUG")
                    print(f"Manifest: {manifest_path}")
                    print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}")
                    print(f"Device: {next(model.parameters()).device}")
                    print(f"Outputs type: {type(outputs)}")

                    if normalized_batch and all(
                        value in {"<unk>", "<blank>", ""}
                        for value in normalized_batch
                    ):
                        raise RuntimeError(
                            "Validation decoder returned only special/empty "
                            f"tokens for {manifest_path}: "
                            f"{normalized_batch[:5]}. "
                            "Stopping instead of recording a false WER."
                        )

                for batch_index, (sample, hypothesis) in enumerate(
                    zip(batch, hypotheses),
                ):
                    reference = " ".join(
                        sample["text"].strip().split()
                    )
                    hypothesis = " ".join(
                        hypothesis.strip().split()
                    )

                    validation_index = start + batch_index + 1
                    print(f"  [{validation_index}] REF : {reference}")
                    print(f"  [{validation_index}] PRED: {hypothesis}")

                    ref_words = reference.split()
                    hyp_words = hypothesis.split()

                    word_s, word_d, word_i = levenshtein_ops(
                        ref_words,
                        hyp_words,
                    )

                    total_word_substitutions += word_s
                    total_word_deletions += word_d
                    total_word_insertions += word_i
                    total_reference_words += len(ref_words)
                    total_predicted_words += len(hyp_words)

                    ref_chars = list(reference.replace(" ", ""))
                    hyp_chars = list(hypothesis.replace(" ", ""))

                    char_s, char_d, char_i = levenshtein_ops(
                        ref_chars,
                        hyp_chars,
                    )

                    total_char_substitutions += char_s
                    total_char_deletions += char_d
                    total_char_insertions += char_i
                    total_reference_chars += len(ref_chars)
                    total_predicted_chars += len(hyp_chars)

    finally:
        model.cur_decoder = previous_decoder

        if was_training:
            model.train()
        else:
            model.eval()

    special_ratio = (
        special_or_empty_outputs / checked_outputs
        if checked_outputs
        else 1.0
    )

    if checked_outputs == 0:
        raise RuntimeError(
            f"Validation produced zero hypotheses for {manifest_path}."
        )

    if special_ratio >= 0.95:
        raise RuntimeError(
            "CTC VALIDATION COLLAPSE DETECTED: "
            f"{special_or_empty_outputs}/{checked_outputs} "
            f"({special_ratio * 100.0:.2f}%) hypotheses were "
            f"<unk>/<blank>/empty for {manifest_path}. "
            "Training is being aborted. No checkpoint from this epoch "
            "will be promoted or uploaded."
        )

    word_errors = (
        total_word_substitutions
        + total_word_deletions
        + total_word_insertions
    )

    char_errors = (
        total_char_substitutions
        + total_char_deletions
        + total_char_insertions
    )

    wer = (
        word_errors / total_reference_words
        if total_reference_words
        else 0.0
    )

    cer = (
        char_errors / total_reference_chars
        if total_reference_chars
        else 0.0
    )

    return {
        "samples": len(samples),
        "ctc_special_or_empty_outputs": special_or_empty_outputs,
        "ctc_checked_outputs": checked_outputs,
        "ctc_special_or_empty_ratio": special_ratio,
        "wer": wer,
        "wer_percent": wer * 100.0,
        "word_errors": word_errors,
        "total_reference_words": total_reference_words,
        "total_predicted_words": total_predicted_words,
        "word_substitutions": total_word_substitutions,
        "word_deletions": total_word_deletions,
        "word_insertions": total_word_insertions,
        "cer": cer,
        "cer_percent": cer * 100.0,
        "char_errors": char_errors,
        "total_reference_characters": total_reference_chars,
        "total_predicted_characters": total_predicted_chars,
        "char_substitutions": total_char_substitutions,
        "char_deletions": total_char_deletions,
        "char_insertions": total_char_insertions,
    }


###############################################################################
# PRE-TRAIN CTC HEALTH CHECK
###############################################################################

def run_pretrain_ctc_health_check(model, batch_size: int) -> None:
    """
    Refuse to begin training unless the clean base model can successfully
    decode BOTH full validation manifests through the exact same CTC path
    used after every epoch.
    """

    print("\n======================================")
    print("PRE-TRAIN CTC HEALTH CHECK")
    print("======================================")
    print("No training has happened yet.")
    print("Kirtan and Sehaj must both decode successfully before trainer.fit().")

    print("\nPre-train KIRTAN CTC validation...")
    kirtan = score_validation_manifest(
        model=model,
        manifest_path=KIRTAN_VAL_MANIFEST,
        batch_size=batch_size,
    )

    print("\nPre-train SEHAJ PAATH CTC validation...")
    sehaj = score_validation_manifest(
        model=model,
        manifest_path=SEHAJ_VAL_MANIFEST,
        batch_size=batch_size,
    )

    print("\nPRE-TRAIN CTC HEALTH CHECK PASSED")
    print(
        f"Kirtan WER: {kirtan['wer']:.6f} "
        f"({kirtan['wer_percent']:.3f}%)"
    )
    print(
        f"Kirtan CTC special/empty: "
        f"{kirtan['ctc_special_or_empty_outputs']}/"
        f"{kirtan['ctc_checked_outputs']}"
    )
    print(
        f"Sehaj WER: {sehaj['wer']:.6f} "
        f"({sehaj['wer_percent']:.3f}%)"
    )
    print(
        f"Sehaj CTC special/empty: "
        f"{sehaj['ctc_special_or_empty_outputs']}/"
        f"{sehaj['ctc_checked_outputs']}"
    )
    print("βœ“ Safe to begin training")


###############################################################################
# CLOUDFLARE R2 HELPERS
###############################################################################

def get_r2_config():
    """Read and validate Cloudflare R2 connection settings."""
    account_id = os.environ.get("R2_ACCOUNT_ID")
    access_key_id = os.environ.get("R2_ACCESS_KEY_ID")
    secret_access_key = os.environ.get("R2_SECRET_ACCESS_KEY")
    bucket = os.environ.get("R2_BUCKET")

    missing = [
        name
        for name, value in (
            ("R2_ACCOUNT_ID", account_id),
            ("R2_ACCESS_KEY_ID", access_key_id),
            ("R2_SECRET_ACCESS_KEY", secret_access_key),
            ("R2_BUCKET", bucket),
        )
        if not value
    ]

    if missing:
        raise RuntimeError(
            "R2 upload is enabled but these environment variables are "
            f"missing: {', '.join(missing)}"
        )

    return {
        "account_id": account_id,
        "access_key_id": access_key_id,
        "secret_access_key": secret_access_key,
        "bucket": bucket,
        "endpoint_url": (
            f"https://{account_id}.r2.cloudflarestorage.com"
        ),
    }


def upload_best_checkpoint_to_r2(checkpoint_path: Path) -> None:
    """Upload the completed local best.ckpt to Cloudflare R2."""
    if not R2_UPLOAD_ENABLED:
        return

    checkpoint_path = Path(checkpoint_path)

    if not checkpoint_path.is_file():
        raise FileNotFoundError(
            f"Cannot upload missing checkpoint: {checkpoint_path}"
        )

    try:
        import boto3
    except ImportError as exc:
        raise RuntimeError(
            "R2 upload requires boto3. Install it with: pip install boto3"
        ) from exc

    config = get_r2_config()

    client = boto3.client(
        "s3",
        endpoint_url=config["endpoint_url"],
        aws_access_key_id=config["access_key_id"],
        aws_secret_access_key=config["secret_access_key"],
        region_name="auto",
    )

    last_error = None

    for attempt in range(1, R2_UPLOAD_RETRIES + 1):
        try:
            print(
                f"Uploading best checkpoint to R2 "
                f"(attempt {attempt}/{R2_UPLOAD_RETRIES})..."
            )

            client.upload_file(
                str(checkpoint_path),
                config["bucket"],
                R2_OBJECT_KEY,
            )

            print(
                "βœ“ R2 upload complete: "
                f"r2://{config['bucket']}/{R2_OBJECT_KEY}"
            )
            return

        except Exception as exc:
            last_error = exc
            print(
                f"R2 upload attempt {attempt} failed: {exc}"
            )

            if attempt < R2_UPLOAD_RETRIES:
                time.sleep(R2_RETRY_DELAY_SECONDS)

    raise RuntimeError(
        "best.ckpt was saved locally, but R2 upload failed after "
        f"{R2_UPLOAD_RETRIES} attempts."
    ) from last_error


###############################################################################
# VAST.AI AUTO-DESTROY HELPERS
###############################################################################

def get_vast_instance_id():
    """
    Return the current Vast instance ID.

    Vast may expose CONTAINER_ID directly. Older/current environments may
    instead expose VAST_CONTAINERLABEL in the form C.123456.
    """
    container_id = os.environ.get("CONTAINER_ID")

    if container_id:
        value = str(container_id).strip()
        if value.isdigit():
            return value

    label = os.environ.get("VAST_CONTAINERLABEL")

    if label:
        value = str(label).strip()

        if value.startswith("C."):
            value = value[2:]

        if value.isdigit():
            return value

    return None


def validate_vast_auto_destroy_config(test_mode: bool) -> None:
    """
    Fail before a FULL training run if auto-destroy cannot be attempted.

    Test mode deliberately skips this because --test never destroys.
    """
    if test_mode or not AUTO_DESTROY_VAST:
        return

    if shutil.which("vastai") is None:
        raise RuntimeError(
            "AUTO_DESTROY_VAST is enabled, but the Vast CLI is not installed. "
            "Install it before the full run with: pip install vastai"
        )

    instance_id = get_vast_instance_id()

    if instance_id is None:
        raise RuntimeError(
            "AUTO_DESTROY_VAST is enabled, but the current Vast instance ID "
            "could not be determined from CONTAINER_ID or VAST_CONTAINERLABEL."
        )


def destroy_current_vast_instance() -> None:
    """
    Permanently destroy this Vast instance.

    This is intentionally called only at the very end of a successful FULL
    run and only after best.ckpt has already been uploaded successfully to R2.
    """
    if not AUTO_DESTROY_VAST:
        print("\nVast auto-destroy is disabled.")
        return

    instance_id = get_vast_instance_id()

    if instance_id is None:
        raise RuntimeError(
            "Cannot auto-destroy Vast instance: instance ID is unavailable."
        )

    command = [
        "vastai",
        "destroy",
        "instance",
        instance_id,
        "-y",  # non-interactive confirmation
    ]

    # Vast images may expose a per-instance API key. If it is present,
    # pass it explicitly. Otherwise the Vast CLI uses its configured key.
    container_api_key = os.environ.get("CONTAINER_API_KEY")

    if container_api_key:
        command.extend(
            [
                "--api-key",
                container_api_key,
            ]
        )

    print(
        "\n======================================"
    )
    print(
        "AUTO-DESTROYING VAST INSTANCE"
    )
    print(
        "======================================"
    )
    print(
        f"Instance ID: {instance_id}"
    )
    print(
        "best.ckpt has already been uploaded successfully to R2."
    )
    print(
        "This instance and its local files will now be permanently destroyed."
    )

    # Make sure the final messages are visible before the container disappears.
    import sys
    sys.stdout.flush()
    sys.stderr.flush()

    try:
        result = subprocess.run(
            command,
            check=False,
            text=True,
            capture_output=True,
            timeout=60,
        )
    except Exception as exc:
        raise RuntimeError(
            f"Failed to execute Vast destroy command: {exc}"
        ) from exc

    if result.stdout:
        print(result.stdout.strip())

    if result.returncode != 0:
        if result.stderr:
            print(result.stderr.strip())

        raise RuntimeError(
            "Vast auto-destroy command failed. "
            "The instance was NOT intentionally destroyed by this script."
        )

    print(
        f"βœ“ Vast destroy request accepted for instance {instance_id}"
    )



###############################################################################
# DURING-TRAINING CTC HEALTH PROBE
###############################################################################

class CTCHealthProbe(Callback):
    """Run a fixed CTC probe and overwrite one last-known-good checkpoint."""

    def __init__(
        self,
        manifest_path: Path,
        stable_checkpoint_path: Path,
        every_optimizer_steps: int = 500,
        save_every_optimizer_steps: int = 2000,
        sample_count: int = 4,
    ):
        super().__init__()
        self.manifest_path = Path(manifest_path)
        self.stable_checkpoint_path = Path(stable_checkpoint_path)
        self.every_optimizer_steps = int(every_optimizer_steps)
        self.save_every_optimizer_steps = int(save_every_optimizer_steps)
        self.sample_count = int(sample_count)
        self.probe_samples = None
        self.last_probed_global_step = -1

        if self.every_optimizer_steps <= 0:
            raise ValueError("CTC probe interval must be > 0")
        if self.save_every_optimizer_steps <= 0:
            raise ValueError("Stable checkpoint interval must be > 0")
        if self.save_every_optimizer_steps % self.every_optimizer_steps != 0:
            raise ValueError(
                "Stable checkpoint interval must be a multiple of the CTC probe interval."
            )
        if self.sample_count <= 0:
            raise ValueError("CTC probe sample_count must be > 0")

    def setup(self, trainer, pl_module, stage=None):
        samples = load_validation_manifest(self.manifest_path)
        if len(samples) < self.sample_count:
            raise RuntimeError(
                f"CTC probe requested {self.sample_count} samples but only "
                f"{len(samples)} are available."
            )

        self.probe_samples = samples[:self.sample_count]

        print("\n======================================")
        print("CTC DURING-TRAINING PROBE ENABLED")
        print("======================================")
        print(f"Probe interval: every {self.every_optimizer_steps} optimizer steps")
        print(
            f"Stable checkpoint interval: every "
            f"{self.save_every_optimizer_steps} optimizer steps, after a healthy probe"
        )
        print(f"Fixed probe samples: {self.sample_count}")
        print(f"Rolling stable checkpoint: {self.stable_checkpoint_path}")
        for i, sample in enumerate(self.probe_samples, 1):
            print(f"  Probe {i}: {sample['audio_filepath']}")

    def _run_probe(
        self,
        trainer,
        pl_module,
        global_step: int,
    ):
        if not self.probe_samples:
            raise RuntimeError(
                "CTC probe samples were not initialized."
            )

        if not hasattr(pl_module, "cur_decoder"):
            raise RuntimeError(
                "CTC probe expected model.cur_decoder."
            )

        was_training = pl_module.training
        previous_decoder = getattr(
            pl_module,
            "cur_decoder",
            None,
        )

        audio_paths = [
            sample["audio_filepath"]
            for sample in self.probe_samples
        ]

        references = [
            sample["text"]
            for sample in self.probe_samples
        ]

        # Keep the training model on CUDA. gpu_safe_transcribe() moves only
        # transcription-batch tensors to the model device before NeMo forward.
        pl_module.eval()
        pl_module.cur_decoder = VALIDATION_DECODER

        try:
            with torch.no_grad():
                outputs = gpu_safe_transcribe(
                    model=pl_module,
                    audio_paths=audio_paths,
                    batch_size=len(audio_paths),
                    verbose=False,
                )

                hypotheses = select_primary_transcriptions(
                    outputs,
                    expected_count=len(audio_paths),
                )

                normalized = [
                    " ".join(str(value).strip().split())
                    for value in hypotheses
                ]

        finally:
            pl_module.cur_decoder = previous_decoder

            if was_training:
                pl_module.train()
            else:
                pl_module.eval()

        special_values = {"<unk>", "<blank>", ""}
        special_count = sum(
            value in special_values
            for value in normalized
        )

        epoch_number = trainer.current_epoch + 1

        print("\n======================================")
        print(
            f"EPOCH {epoch_number} - "
            f"CTC PROBE @ OPTIMIZER STEP {global_step}"
        )
        print("======================================")
        print(f"CTC probe device: {next(pl_module.parameters()).device}")

        for i, (reference, hypothesis) in enumerate(
            zip(references, normalized),
            1,
        ):
            print(f"  [{i}] REF : {reference}")
            print(f"  [{i}] PRED: {hypothesis}")

        print(
            f"CTC probe special/empty: "
            f"{special_count}/{len(normalized)}"
        )

        if normalized and special_count == len(normalized):
            raise RuntimeError(
                "CTC TRAINING COLLAPSE DETECTED at optimizer step "
                f"{global_step}: all {len(normalized)} fixed probe "
                f"hypotheses were <unk>/<blank>/empty: {normalized}."
            )

        print(
            f"CTC probe HEALTHY at optimizer step {global_step}"
        )

        if global_step % self.save_every_optimizer_steps != 0:
            print(
                f"No checkpoint save at step {global_step}; "
                f"next stable save is on a multiple of "
                f"{self.save_every_optimizer_steps} optimizer steps."
            )
            return

        self.stable_checkpoint_path.parent.mkdir(
            parents=True,
            exist_ok=True,
        )

        temp_path = self.stable_checkpoint_path.with_suffix(
            self.stable_checkpoint_path.suffix + ".tmp"
        )

        trainer.save_checkpoint(str(temp_path))
        os.replace(temp_path, self.stable_checkpoint_path)

        print(
            f"βœ“ Updated last stable checkpoint at optimizer step "
            f"{global_step}: {self.stable_checkpoint_path}"
        )

    def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
        global_step = int(trainer.global_step)

        if global_step <= 0:
            return
        if global_step % self.every_optimizer_steps != 0:
            return
        if global_step == self.last_probed_global_step:
            return

        self.last_probed_global_step = global_step
        self._run_probe(trainer, pl_module, global_step)


###############################################################################
# POST-EPOCH KIRTAN + SEHAJ WER/CER + BEST CHECKPOINT + EARLY STOPPING
###############################################################################

class DomainValidationAndEarlyStopping(Callback):
    """
    After every TRAINING epoch:

    1. Explicitly transcribe Kirtan validation data.
    2. Explicitly transcribe Sehaj Paath validation data.
    3. Save BOTH WER and CER to epoch_metrics.json.
    4. Promote the epoch to best.ckpt if ANY of these improves by min_delta:
         - Kirtan CER
         - Kirtan WER
         - Sehaj WER
    5. Kirtan CER remains a first-class selection metric: any new lower Kirtan
       CER always promotes the new epoch even if either WER is worse.
    6. Keep independent best-ever baselines for all three metrics so a checkpoint
       selected for one metric never makes another metric's baseline worse.
    7. Preserve callback state across Lightning resumes, and seed from the existing
       epoch_metrics.json when resuming from an older checkpoint that did not yet
       contain callback state.
    """

    def __init__(
        self,
        metrics_path: Path,
        best_checkpoint_path: Path,
        kirtan_manifest: Path,
        sehaj_manifest: Path,
        batch_size: int,
        patience: int = 5,
        min_delta: float = 0.0001,
    ):
        super().__init__()
        self.metrics_path = Path(metrics_path)
        self.best_checkpoint_path = Path(best_checkpoint_path)
        self.kirtan_manifest = Path(kirtan_manifest)
        self.sehaj_manifest = Path(sehaj_manifest)
        self.batch_size = int(batch_size)
        self.patience = int(patience)
        self.min_delta = float(min_delta)

        # Independent BEST-EVER baselines. Do not overwrite a metric just because
        # some other metric caused the current epoch to be selected.
        self.best_kirtan_cer = float("inf")
        self.best_kirtan_wer = float("inf")
        self.best_sehaj_wer = float("inf")

        # Metrics belonging specifically to the checkpoint currently stored as best.ckpt.
        self.selected_kirtan_cer = float("inf")
        self.selected_kirtan_wer = float("inf")
        self.selected_sehaj_wer = float("inf")

        self.best_epoch = None
        self.bad_epochs = 0
        self.history = []
        self.r2_best_uploaded = False

        # This matters for the FIRST restart with the newly updated callback:
        # On a restart, seed metric baselines/history from the existing JSON before
        # trainer.fit(). The rolling [202,100] checkpoint also carries state_dict()
        # below, so Lightning will restore the authoritative callback state.
        self._seed_from_existing_metrics_json()

    @staticmethod
    def _finite_or_inf(value):
        if value is None:
            return float("inf")
        try:
            return float(value)
        except (TypeError, ValueError):
            return float("inf")

    def _seed_from_existing_metrics_json(self):
        if not self.metrics_path.is_file():
            return

        try:
            with self.metrics_path.open("r", encoding="utf-8") as handle:
                data = json.load(handle)
        except Exception as exc:
            print(
                f"WARNING: could not seed validation callback from "
                f"{self.metrics_path}: {exc}"
            )
            return

        history = data.get("history")
        if not isinstance(history, list):
            history = []

        self.history = history

        # Derive independent best-ever metric values from complete epoch records.
        kirtan_cers = []
        kirtan_wers = []
        sehaj_wers = []
        for record in history:
            try:
                kirtan = record.get("kirtan", {})
                sehaj = record.get("sehaj", {})
                if kirtan.get("cer") is not None:
                    kirtan_cers.append(float(kirtan["cer"]))
                if kirtan.get("wer") is not None:
                    kirtan_wers.append(float(kirtan["wer"]))
                if sehaj.get("wer") is not None:
                    sehaj_wers.append(float(sehaj["wer"]))
            except (TypeError, ValueError, AttributeError):
                continue

        if kirtan_cers:
            self.best_kirtan_cer = min(kirtan_cers)
        else:
            self.best_kirtan_cer = self._finite_or_inf(data.get("best_kirtan_cer"))

        if kirtan_wers:
            self.best_kirtan_wer = min(kirtan_wers)
        else:
            self.best_kirtan_wer = self._finite_or_inf(data.get("best_kirtan_wer"))

        if sehaj_wers:
            self.best_sehaj_wer = min(sehaj_wers)
        else:
            self.best_sehaj_wer = self._finite_or_inf(data.get("best_sehaj_wer"))

        self.best_epoch = data.get("best_epoch")
        self.bad_epochs = int(data.get("epochs_without_improvement", 0) or 0)

        # Recover metrics for the checkpoint that was selected by the old logic,
        # when that epoch is present in history.
        for record in reversed(history):
            if record.get("epoch") == self.best_epoch:
                kirtan = record.get("kirtan", {})
                sehaj = record.get("sehaj", {})
                self.selected_kirtan_cer = self._finite_or_inf(kirtan.get("cer"))
                self.selected_kirtan_wer = self._finite_or_inf(kirtan.get("wer"))
                self.selected_sehaj_wer = self._finite_or_inf(sehaj.get("wer"))
                break

        print("\nRestored validation-selection history from existing metrics JSON:")
        print(self.metrics_path)
        print(f"  best-ever Kirtan CER: {self.best_kirtan_cer}")
        print(f"  best-ever Kirtan WER: {self.best_kirtan_wer}")
        print(f"  best-ever Sehaj WER:  {self.best_sehaj_wer}")
        print(f"  selected best epoch:  {self.best_epoch}")
        print(f"  epochs without improvement: {self.bad_epochs}")

    def state_dict(self):
        """Persist selection/early-stop state inside full Lightning checkpoints."""
        return {
            "best_kirtan_cer": self.best_kirtan_cer,
            "best_kirtan_wer": self.best_kirtan_wer,
            "best_sehaj_wer": self.best_sehaj_wer,
            "selected_kirtan_cer": self.selected_kirtan_cer,
            "selected_kirtan_wer": self.selected_kirtan_wer,
            "selected_sehaj_wer": self.selected_sehaj_wer,
            "best_epoch": self.best_epoch,
            "bad_epochs": self.bad_epochs,
            "history": self.history,
            "r2_best_uploaded": self.r2_best_uploaded,
        }

    def load_state_dict(self, state_dict):
        """Restore selection/early-stop state on a true Lightning resume."""
        if not state_dict:
            return

        self.best_kirtan_cer = self._finite_or_inf(
            state_dict.get("best_kirtan_cer", self.best_kirtan_cer)
        )
        self.best_kirtan_wer = self._finite_or_inf(
            state_dict.get("best_kirtan_wer", self.best_kirtan_wer)
        )
        self.best_sehaj_wer = self._finite_or_inf(
            state_dict.get("best_sehaj_wer", self.best_sehaj_wer)
        )
        self.selected_kirtan_cer = self._finite_or_inf(
            state_dict.get("selected_kirtan_cer", self.selected_kirtan_cer)
        )
        self.selected_kirtan_wer = self._finite_or_inf(
            state_dict.get("selected_kirtan_wer", self.selected_kirtan_wer)
        )
        self.selected_sehaj_wer = self._finite_or_inf(
            state_dict.get("selected_sehaj_wer", self.selected_sehaj_wer)
        )
        self.best_epoch = state_dict.get("best_epoch", self.best_epoch)
        self.bad_epochs = int(state_dict.get("bad_epochs", self.bad_epochs) or 0)
        restored_history = state_dict.get("history")
        if isinstance(restored_history, list):
            self.history = restored_history
        self.r2_best_uploaded = bool(
            state_dict.get("r2_best_uploaded", self.r2_best_uploaded)
        )

        print("\nβœ“ Restored validation callback state from Lightning checkpoint")
        print(f"  best-ever Kirtan CER: {self.best_kirtan_cer}")
        print(f"  best-ever Kirtan WER: {self.best_kirtan_wer}")
        print(f"  best-ever Sehaj WER:  {self.best_sehaj_wer}")
        print(f"  selected best epoch:  {self.best_epoch}")
        print(f"  epochs without improvement: {self.bad_epochs}")

    def write_history(self):
        def optional(value):
            return None if value == float("inf") else value

        best_kirtan_cer = optional(self.best_kirtan_cer)
        best_kirtan_wer = optional(self.best_kirtan_wer)
        best_sehaj_wer = optional(self.best_sehaj_wer)
        selected_kirtan_cer = optional(self.selected_kirtan_cer)
        selected_kirtan_wer = optional(self.selected_kirtan_wer)
        selected_sehaj_wer = optional(self.selected_sehaj_wer)

        data = {
            "selection_metric": "any_improvement_kirtan_cer_or_kirtan_wer_or_sehaj_wer",
            "best_epoch": self.best_epoch,
            "best_kirtan_cer_percent": (
                None if best_kirtan_cer is None else best_kirtan_cer * 100.0
            ),
            "best_kirtan_wer_percent": (
                None if best_kirtan_wer is None else best_kirtan_wer * 100.0
            ),
            "best_sehaj_wer_percent": (
                None if best_sehaj_wer is None else best_sehaj_wer * 100.0
            ),
            "best_kirtan_cer": best_kirtan_cer,
            "best_kirtan_wer": best_kirtan_wer,
            "best_sehaj_wer": best_sehaj_wer,
            "selected_checkpoint_kirtan_cer": selected_kirtan_cer,
            "selected_checkpoint_kirtan_wer": selected_kirtan_wer,
            "selected_checkpoint_sehaj_wer": selected_sehaj_wer,
            "patience": self.patience,
            "min_metric_improvement": self.min_delta,
            "epochs_without_improvement": self.bad_epochs,
            "history": self.history,
        }

        self.metrics_path.parent.mkdir(parents=True, exist_ok=True)
        temp_path = self.metrics_path.with_suffix(self.metrics_path.suffix + ".tmp")
        with temp_path.open("w", encoding="utf-8") as handle:
            json.dump(data, handle, indent=2, ensure_ascii=False)
        temp_path.replace(self.metrics_path)

    def on_train_epoch_end(self, trainer, pl_module):
        epoch_number = trainer.current_epoch + 1

        print("\n======================================")
        print("EXPLICIT DOMAIN VALIDATION")
        print("======================================")
        print("Scoring KIRTAN validation (CER + WER can promote best.ckpt)...")

        kirtan = score_validation_manifest(
            model=pl_module,
            manifest_path=self.kirtan_manifest,
            batch_size=self.batch_size,
        )

        print("Scoring SEHAJ PAATH validation (WER can promote best.ckpt)...")
        sehaj = score_validation_manifest(
            model=pl_module,
            manifest_path=self.sehaj_manifest,
            batch_size=self.batch_size,
        )

        previous_best_kirtan_cer = self.best_kirtan_cer
        previous_best_kirtan_wer = self.best_kirtan_wer
        previous_best_sehaj_wer = self.best_sehaj_wer

        kirtan_cer_improved = (
            kirtan["cer"] < previous_best_kirtan_cer - self.min_delta
        )
        kirtan_wer_improved = (
            kirtan["wer"] < previous_best_kirtan_wer - self.min_delta
        )
        sehaj_wer_improved = (
            sehaj["wer"] < previous_best_sehaj_wer - self.min_delta
        )

        # Any one of the three metrics can promote this epoch.
        improved = (
            kirtan_cer_improved
            or kirtan_wer_improved
            or sehaj_wer_improved
        )

        reasons = []
        if kirtan_cer_improved:
            reasons.append("kirtan_cer")
        if kirtan_wer_improved:
            reasons.append("kirtan_wer")
        if sehaj_wer_improved:
            reasons.append("sehaj_wer")
        improvement_reason = "+".join(reasons) if reasons else None

        # Update each best-ever baseline independently.
        if kirtan_cer_improved:
            self.best_kirtan_cer = kirtan["cer"]
        if kirtan_wer_improved:
            self.best_kirtan_wer = kirtan["wer"]
        if sehaj_wer_improved:
            self.best_sehaj_wer = sehaj["wer"]

        if improved:
            self.best_epoch = epoch_number
            self.bad_epochs = 0

            # Record the actual metrics of the checkpoint being promoted now.
            self.selected_kirtan_cer = kirtan["cer"]
            self.selected_kirtan_wer = kirtan["wer"]
            self.selected_sehaj_wer = sehaj["wer"]

            self.best_checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
            pl_module.train()
            trainer.save_checkpoint(str(self.best_checkpoint_path))
            upload_best_checkpoint_to_r2(self.best_checkpoint_path)

            if R2_UPLOAD_ENABLED:
                self.r2_best_uploaded = True
            else:
                print("R2 upload skipped: offline test mode.")

            print("\nNEW BEST CHECKPOINT β€” ACCEPTED METRIC IMPROVEMENT")
            print(f"Epoch: {epoch_number}")
            print(
                f"Kirtan CER: {kirtan['cer']:.6f} "
                f"({kirtan['cer_percent']:.3f}%)"
            )
            print(
                f"Kirtan WER: {kirtan['wer']:.6f} "
                f"({kirtan['wer_percent']:.3f}%)"
            )
            print(
                f"Sehaj WER: {sehaj['wer']:.6f} "
                f"({sehaj['wer_percent']:.3f}%)"
            )
            print(f"Selection reason: {improvement_reason}")
            print("Saved best checkpoint:")
            print(self.best_checkpoint_path)
        else:
            self.bad_epochs += 1
            print("\nNo Kirtan CER / Kirtan WER / Sehaj WER improvement.")
            print(
                f"Current Kirtan CER: {kirtan['cer']:.6f} "
                f"({kirtan['cer_percent']:.3f}%)"
            )
            print(
                f"Best-ever Kirtan CER: {self.best_kirtan_cer:.6f} "
                f"({self.best_kirtan_cer * 100:.3f}%)"
            )
            print(
                f"Current Kirtan WER: {kirtan['wer']:.6f} "
                f"({kirtan['wer_percent']:.3f}%)"
            )
            print(
                f"Best-ever Kirtan WER: {self.best_kirtan_wer:.6f} "
                f"({self.best_kirtan_wer * 100:.3f}%)"
            )
            print(
                f"Current Sehaj WER: {sehaj['wer']:.6f} "
                f"({sehaj['wer_percent']:.3f}%)"
            )
            print(
                f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} "
                f"({self.best_sehaj_wer * 100:.3f}%)"
            )
            print(
                f"Epochs without improvement: {self.bad_epochs}/{self.patience}"
            )

        epoch_record = {
            "epoch": epoch_number,
            "kirtan": kirtan,
            "sehaj": sehaj,
            "selection_metric": "any_improvement_kirtan_cer_or_kirtan_wer_or_sehaj_wer",
            "improved": improved,
            "improvement_reason": improvement_reason,
            "kirtan_cer_improved": kirtan_cer_improved,
            "kirtan_wer_improved": kirtan_wer_improved,
            "sehaj_wer_improved": sehaj_wer_improved,
            "best_epoch": self.best_epoch,
            "best_kirtan_cer": self.best_kirtan_cer,
            "best_kirtan_cer_percent": self.best_kirtan_cer * 100.0,
            "best_kirtan_wer": self.best_kirtan_wer,
            "best_kirtan_wer_percent": self.best_kirtan_wer * 100.0,
            "best_sehaj_wer": self.best_sehaj_wer,
            "best_sehaj_wer_percent": self.best_sehaj_wer * 100.0,
            "selected_checkpoint_kirtan_cer": self.selected_kirtan_cer,
            "selected_checkpoint_kirtan_wer": self.selected_kirtan_wer,
            "selected_checkpoint_sehaj_wer": self.selected_sehaj_wer,
            "epochs_without_improvement": self.bad_epochs,
        }

        self.history.append(epoch_record)
        self.write_history()

        print("\n--------------------------------------")
        print(
            f"Epoch {epoch_number} KIRTAN: "
            f"CER {kirtan['cer_percent']:.3f}% | "
            f"WER {kirtan['wer_percent']:.3f}%"
        )
        print(
            f"Epoch {epoch_number} SEHAJ:  "
            f"WER {sehaj['wer_percent']:.3f}% | "
            f"CER {sehaj['cer_percent']:.3f}%"
        )
        print(
            "Checkpoint / early-stop rule: promote when ANY improves β€” "
            "Kirtan CER OR Kirtan WER OR Sehaj WER."
        )
        print(f"Minimum required improvement: {self.min_delta}")
        print(f"Metrics JSON: {self.metrics_path}")
        print("--------------------------------------")

        if self.bad_epochs >= self.patience:
            print("\n########################################")
            print("EARLY STOPPING: NO ACCEPTED METRIC IMPROVEMENT")
            print("########################################")
            print(
                f"No Kirtan CER / Kirtan WER / Sehaj WER improvement for "
                f"{self.bad_epochs} epochs."
            )
            print(f"Selected best epoch: {self.best_epoch}")
            print(
                f"Best-ever Kirtan CER: {self.best_kirtan_cer:.6f} "
                f"({self.best_kirtan_cer * 100:.3f}%)"
            )
            print(
                f"Best-ever Kirtan WER: {self.best_kirtan_wer:.6f} "
                f"({self.best_kirtan_wer * 100:.3f}%)"
            )
            print(
                f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} "
                f"({self.best_sehaj_wer * 100:.3f}%)"
            )
            trainer.should_stop = True


###############################################################################
# POST-EPOCH: KEEP LAST TWO EPOCH CHECKPOINTS
###############################################################################

class LastTwoEpochCheckpoints(Callback):
    """
    Save one checkpoint after every completed training epoch.

    Keep only the latest two:

        epoch_004.ckpt
        epoch_005.ckpt

    When epoch 6 finishes:

        epoch_004.ckpt -> deleted
        epoch_005.ckpt -> kept
        epoch_006.ckpt -> saved

    best.ckpt is NOT deleted by this callback.
    """

    def __init__(
        self,
        dirpath: Path,
    ):
        super().__init__()

        self.dirpath = Path(
            dirpath
        )

    def on_train_epoch_end(
        self,
        trainer,
        pl_module,
    ):

        self.dirpath.mkdir(
            parents=True,
            exist_ok=True,
        )

        epoch_number = (
            trainer.current_epoch + 1
        )

        checkpoint_path = (
            self.dirpath
            / f"epoch_{epoch_number:03d}.ckpt"
        )

        trainer.save_checkpoint(
            str(checkpoint_path)
        )

        print(
            "\nSaved epoch checkpoint:"
        )

        print(
            checkpoint_path
        )

        # Only look at epoch_XXX.ckpt files.
        # best.ckpt will therefore never be removed.
        checkpoints = sorted(
            self.dirpath.glob(
                "epoch_*.ckpt"
            )
        )

        while len(checkpoints) > 2:

            oldest_checkpoint = (
                checkpoints.pop(0)
            )

            try:
                oldest_checkpoint.unlink()

                print(
                    "Removed old epoch checkpoint:"
                )

                print(
                    oldest_checkpoint
                )

            except FileNotFoundError:
                pass


###############################################################################
# DATASET CONFIGURATION
###############################################################################

def make_dataset_config(
    manifest_path: Path,
    shuffle: bool,
):
    """
    Build a fresh NeMo dataset configuration for Punjabi ('pa') fine-tuning
    of the multilingual Gurbani model.

    Fresh train_ds and validation_ds configs are created here at fine-tuning
    time. The manifests provide lang='pa' and NeMo is asked to return the
    language ID so the multilingual model uses the Punjabi path.
    """

    return OmegaConf.create({
        "manifest_filepath": [
            str(manifest_path)
        ],
        "sample_rate": EXPECTED_SAMPLE_RATE,
        "batch_size": BATCH_SIZE,
        "shuffle": shuffle,
        "num_workers": 2,
        "pin_memory": False,
        "persistent_workers": False,
        "max_duration": None,
        "min_duration": 0.0,
        "is_tarred": False,
        "tarred_audio_filepaths": None,
        "use_start_end_token": False,

        # IMPORTANT: this is a multilingual model. The manifests contain
        # lang="pa", and the dataset must return the language ID.
        "return_language_id": True,
    })



###############################################################################
# PATH VALIDATION
###############################################################################

def validate_paths() -> None:

    if not DATA_ROOT.exists():
        raise FileNotFoundError(
            f"DATA_ROOT does not exist: "
            f"{DATA_ROOT}"
        )

    if not DATA_ROOT.is_dir():
        raise ValueError(
            f"DATA_ROOT is not a directory: "
            f"{DATA_ROOT}"
        )

    if not TRAIN_MANIFEST.exists():
        raise FileNotFoundError(
            "Training manifest not found: "
            f"{TRAIN_MANIFEST}"
        )

    if not KIRTAN_VAL_MANIFEST.exists():
        raise FileNotFoundError(
            "Kirtan validation manifest not found: "
            f"{KIRTAN_VAL_MANIFEST}"
        )

    if not SEHAJ_VAL_MANIFEST.exists():
        raise FileNotFoundError(
            "Sehaj validation manifest not found: "
            f"{SEHAJ_VAL_MANIFEST}"
        )

    if not MODEL_PATH.exists():
        raise FileNotFoundError(
            "NeMo model not found: "
            f"{MODEL_PATH}"
        )

    # A brand-new run starts from MODEL_PATH. A restarted [202,100] run resumes
    # from its own rolling stable checkpoint and does not need another checkpoint.
    if not LAST_STABLE_CHECKPOINT_PATH.exists():
        if (
            START_CHECKPOINT_PATH is not None
            and not START_CHECKPOINT_PATH.exists()
        ):
            raise FileNotFoundError(
                "Optional initialization checkpoint not found: "
                f"{START_CHECKPOINT_PATH}"
            )

    if R2_UPLOAD_ENABLED:
        # Validate required R2 environment variables before long training starts.
        get_r2_config()


###############################################################################
# LOAD STAGE-2 BEST CHECKPOINT WEIGHTS ONLY
###############################################################################

def load_start_checkpoint_weights(model) -> None:
    """Optionally load checkpoint model weights without optimizer state."""

    if START_CHECKPOINT_PATH is None:
        print(
            "\nNo starting checkpoint configured. "
            "Using MODEL_PATH weights directly."
        )
        return

    print("\n======================================")
    print("LOADING OPTIONAL START CHECKPOINT WEIGHTS")
    print("======================================")
    print(START_CHECKPOINT_PATH)

    checkpoint = torch.load(
        str(START_CHECKPOINT_PATH),
        map_location="cpu",
    )

    state_dict = checkpoint.get(
        "state_dict",
        checkpoint,
    )

    result = model.load_state_dict(
        state_dict,
        strict=False,
    )

    missing = list(result.missing_keys)
    unexpected = list(result.unexpected_keys)

    print(f"Missing keys: {len(missing)}")
    print(f"Unexpected keys: {len(unexpected)}")

    if missing:
        for key in missing[:30]:
            print("  MISSING:", key)

    if unexpected:
        for key in unexpected[:30]:
            print("  UNEXPECTED:", key)

    if missing or unexpected:
        raise RuntimeError(
            "Starting checkpoint does not cleanly match "
            "the restored .nemo model."
        )

    print("βœ“ Starting checkpoint weights loaded cleanly")
    print("βœ“ Old optimizer state NOT restored")
    print("βœ“ Old scheduler state NOT restored")


###############################################################################
# CACHE-AWARE ENCODER CONVERSION
###############################################################################

def rebuild_encoder_cache_aware(model, attention_context) -> None:
    """
    Rebuild the existing Conformer encoder for one cache-aware/chunked-limited
    attention context while preserving all learned encoder weights.

    This helper rebuilds the encoder for the requested cache-aware context
    while preserving the learned encoder weights.
    """

    attention_context = list(attention_context)

    print("\n======================================")
    print("CACHE-AWARE ENCODER CONVERSION")
    print("======================================")

    old_cfg = copy.deepcopy(model.cfg.encoder)

    print("Original attention context:", old_cfg.get("att_context_size"))
    print("Original attention probabilities:", old_cfg.get("att_context_probs", None))
    print("Original attention style:", old_cfg.get("att_context_style", "regular"))
    print("Original convolution context:", old_cfg.get("conv_context_size", None))

    old_state = copy.deepcopy(model.encoder.state_dict())
    new_cfg = copy.deepcopy(old_cfg)

    with open_dict(new_cfg):
        new_cfg.att_context_size = attention_context
        new_cfg.att_context_probs = None
        new_cfg.att_context_style = "chunked_limited"
        new_cfg.conv_context_size = CAUSAL_CONV_CONTEXT

    print("\nRebuilding encoder...")
    print("Attention context:", attention_context)
    print("Attention style: chunked_limited")
    print("Convolution context:", CAUSAL_CONV_CONTEXT)

    new_encoder = instantiate(new_cfg)
    new_encoder.load_state_dict(old_state, strict=True)

    model.encoder = new_encoder

    with open_dict(model.cfg):
        model.cfg.encoder = new_cfg

    print("βœ“ Existing encoder weights loaded strict=True")
    print(f"βœ“ Full-data streaming context: {attention_context}")
    print("βœ“ Causal convolution: [30,0]")
    print("======================================\n")


###############################################################################
# MODEL INFORMATION
###############################################################################

def print_model_information(
    model,
) -> None:

    total_parameters = sum(
        parameter.numel()
        for parameter
        in model.parameters()
    )

    trainable_parameters = sum(
        parameter.numel()
        for parameter
        in model.parameters()
        if parameter.requires_grad
    )

    frozen_parameters = (
        total_parameters
        - trainable_parameters
    )

    print(
        "\n======================================"
    )

    print(
        "MODEL INFORMATION"
    )

    print(
        "======================================"
    )

    print(
        f"Total parameters: "
        f"{total_parameters:,}"
    )

    print(
        f"Trainable parameters: "
        f"{trainable_parameters:,}"
    )

    print(
        f"Frozen parameters: "
        f"{frozen_parameters:,}"
    )

    print(
        "======================================"
    )


###############################################################################
# COMMAND LINE
###############################################################################

def parse_args():
    parser = argparse.ArgumentParser(
        description="Fine-tune the Gurbani/Punjabi NeMo ASR model."
    )
    parser.add_argument(
        "--test",
        action="store_true",
        help=(
            "Use the small *-test.json manifests for an infrastructure "
            "test run. Test artifacts are written under "
            "/workspace/asr_training_test."
        ),
    )
    parser.add_argument(
        "--offline",
        action="store_true",
        help=(
            "TEST MODE ONLY: disable all Cloudflare R2 validation/uploads. "
            "Use as: python train.py --test --offline"
        ),
    )

    args = parser.parse_args()

    if args.offline and not args.test:
        parser.error("--offline is only allowed together with --test")

    return args


###############################################################################
# MAIN
###############################################################################

def main() -> None:

    args = parse_args()
    configure_manifests(test_mode=args.test)
    configure_outputs(
        test_mode=args.test,
        offline=args.offline,
    )

    # Test mode runs only 2 epochs.
    max_epochs = 2 if args.test else MAX_EPOCHS

    if args.test and args.offline:
        run_mode = "TEST OFFLINE (*-test.json manifests, 2 epochs, NO R2)"
    elif args.test:
        run_mode = "TEST (*-test.json manifests, 2 epochs, separate R2 test checkpoint)"
    else:
        run_mode = "FULL"

    print(
        "\nRUN MODE:",
        run_mode,
    )

    validate_vast_auto_destroy_config(
        test_mode=args.test
    )
    validate_paths()

    if not torch.cuda.is_available():
        raise RuntimeError(
            "CUDA GPU is not available. This script is configured for Vast GPU training."
        )

    print("\nGPU:", torch.cuda.get_device_name(0))
    print("CUDA version:", torch.version.cuda)

    # Create all output directories under /workspace.
    OUTPUT_ROOT.mkdir(
        parents=True,
        exist_ok=True,
    )

    CHECKPOINT_DIR.mkdir(
        parents=True,
        exist_ok=True,
    )

    print(
        "======================================"
    )

    print(
        "GURBANI PUNJABI (pa) STREAMING FINE-TUNING"
    )

    print(
        "======================================"
    )

    print(
        f"Training manifest:"
    )

    print(
        TRAIN_MANIFEST
    )

    print(
        f"\nKirtan validation manifest:"
    )

    print(
        KIRTAN_VAL_MANIFEST
    )

    print(
        f"\nSehaj validation manifest:"
    )

    print(
        SEHAJ_VAL_MANIFEST
    )

    print(
        f"\nBase model:"
    )

    print(
        MODEL_PATH
    )

    print(
        f"\nStarting checkpoint:"
    )

    print(
        START_CHECKPOINT_PATH
        if START_CHECKPOINT_PATH is not None
        else "None β€” using MODEL_PATH only"
    )

    print(
        f"\nOutput model:"
    )

    print(
        OUTPUT_MODEL
    )

    print(
        f"\nEpoch metrics JSON:"
    )

    print(
        EPOCH_METRICS_PATH
    )

    print(
        f"\nOutput root:"
    )

    print(
        OUTPUT_ROOT
    )

    print(
        f"\nCheckpoint directory:"
    )

    print(
        CHECKPOINT_DIR
    )

    if R2_UPLOAD_ENABLED:
        r2_config = get_r2_config()
        print(
            f"\nR2 best-checkpoint backup: "
            f"r2://{r2_config['bucket']}/{R2_OBJECT_KEY}"
        )
    else:
        print(
            "\nR2 backup: DISABLED (--test --offline)"
        )

    print(
        "\nLoading Gurbani/Punjabi multilingual model..."
    )

    model = (
        nemo_asr.models.ASRModel.restore_from(
            restore_path=str(
                MODEL_PATH
            )
        )
    )

    # Fail early if the downloaded starting model is not the expected export.
    # The encoder will later be rebuilt to [202,100] for the new training run.
    loaded_context = model.cfg.encoder.get("att_context_size", None)
    if loaded_context is None:
        raise RuntimeError(
            "Starting model does not specify encoder.att_context_size; "
            f"expected {SOURCE_MODEL_ATT_CONTEXT} from {MODEL_PATH}."
        )
    loaded_context = [int(value) for value in loaded_context]
    print("Starting model attention context:", loaded_context)
    if loaded_context != SOURCE_MODEL_ATT_CONTEXT:
        raise RuntimeError(
            "Wrong starting model context: "
            f"expected {SOURCE_MODEL_ATT_CONTEXT}, got {loaded_context}. "
            f"Model path: {MODEL_PATH}"
        )

    # Decide whether this is the first [202,100] run or a restart of
    # an already-running [202,100] job.
    resume_ckpt = (
        LAST_STABLE_CHECKPOINT_PATH
        if LAST_STABLE_CHECKPOINT_PATH.exists()
        else None
    )

    if resume_ckpt is None:
        print(
            "\nNo [202,100] stable checkpoint exists. "
            "This is the FIRST [202,100] run; initializing from the exported model."
        )
        load_start_checkpoint_weights(model)
    else:
        print(
            "\nFound [202,100] rolling stable checkpoint. "
            "Lightning will restore the full [202,100] training state."
        )
        print(resume_ckpt)

    # --------------------------------------------------------
    # Verify that the restored multilingual model supports Punjabi ('pa').
    # Keep the original multilingual vocabulary and language masks intact.
    # --------------------------------------------------------

    tokenizer_vocab_size = getattr(
        model.tokenizer,
        "vocab_size",
        None,
    )

    print(
        "\nLoaded tokenizer vocabulary:",
        tokenizer_vocab_size,
    )

    if tokenizer_vocab_size is None:
        raise RuntimeError(
            "Could not determine tokenizer vocabulary size."
        )

    tokenizer_langs = getattr(
        model.tokenizer,
        "langs",
        None,
    )

    print(
        "Tokenizer languages:",
        tokenizer_langs,
    )

    if tokenizer_langs is None or LANGUAGE_CODE not in tokenizer_langs:
        raise RuntimeError(
            f"Restored multilingual tokenizer does not contain "
            f"Punjabi ({LANGUAGE_CODE!r})."
        )

    rnnt_vocab_size = getattr(
        model.decoder,
        "vocab_size",
        None,
    )

    print(
        "RNNT decoder vocabulary:",
        rnnt_vocab_size,
    )

    if rnnt_vocab_size is None:
        raise RuntimeError(
            "Could not determine RNNT decoder vocabulary size."
        )

    if hasattr(model, "ctc_decoder"):
        ctc_vocab_size = len(
            getattr(
                model.ctc_decoder,
                "vocabulary",
                [],
            )
        )

        print(
            "CTC decoder vocabulary:",
            ctc_vocab_size,
        )

        language_masks = getattr(
            model.ctc_decoder,
            "language_masks",
            None,
        )

        print(
            "CTC language masks present:",
            language_masks is not None,
        )

    print(
        f"βœ“ Multilingual model with Punjabi ({LANGUAGE_CODE!r}) support verified"
    )

    print_model_information(
        model
    )

    print(
        "\nCreating fresh Punjabi (pa) training "
        "and validation dataset configs..."
    )

    train_cfg = make_dataset_config(
        manifest_path=TRAIN_MANIFEST,
        shuffle=True,
    )

    # Validation is performed explicitly by DomainValidationAndEarlyStopping
    # at on_train_epoch_end().
    #
    # IMPORTANT:
    # NeMo's model.transcribe() still reads model.cfg.validation_ds internally
    # (for fields such as use_start_end_token), so validation_ds must NOT be None.
    # We keep a valid Kirtan validation config here, but Lightning's built-in
    # validation loop remains disabled with limit_val_batches=0 below.
    validation_cfg = make_dataset_config(
        manifest_path=KIRTAN_VAL_MANIFEST,
        shuffle=False,
    )

    OmegaConf.set_struct(
        train_cfg,
        False,
    )

    OmegaConf.set_struct(
        validation_cfg,
        False,
    )

    with open_dict(
        model.cfg
    ):

        model.cfg.train_ds = train_cfg
        model.cfg.validation_ds = validation_cfg
        model.cfg.test_ds = None

        # Keep the conservative fine-tuning LR.
        model.cfg.optim.lr = (
            LEARNING_RATE
        )

    print(
        "\nTraining dataset config:"
    )
    print(
        OmegaConf.to_yaml(
            model.cfg.train_ds
        )
    )

    print(
        "\nValidation mode: explicit post-epoch transcription "
        "(Lightning validation disabled)"
    )
    print(
        f"Kirtan validation: {KIRTAN_VAL_MANIFEST}"
    )
    print(
        f"Sehaj validation: {SEHAJ_VAL_MANIFEST}"
    )

    print(
        "\nTraining configuration:"
    )

    print(
        f"Batch size: "
        f"{BATCH_SIZE}"
    )

    print(
        f"Gradient accumulation: "
        f"{ACCUMULATE_GRAD_BATCHES}"
    )

    print(
        f"Effective batch size: "
        f"{BATCH_SIZE * ACCUMULATE_GRAD_BATCHES}"
    )

    print(
        f"Learning rate: "
        f"{LEARNING_RATE}"
    )

    print(
        f"Maximum epochs: "
        f"{max_epochs}"
    )

    print(
        f"Early-stop patience: "
        f"{EARLY_STOP_PATIENCE}"
    )

    print(
        f"Minimum WER improvement: "
        f"{MIN_WER_IMPROVEMENT}"
    )

    print(
        f"Streaming attention context (full data): "
        f"{STREAM_ATT_CONTEXTS}"
    )

    print(
        f"Causal convolution context: "
        f"{CAUSAL_CONV_CONTEXT}"
    )

    # ------------------------------------------------------------------
    # Full-data streaming training
    # ------------------------------------------------------------------
    # Train the complete selected manifest using the configured [202,100]
    # streaming attention context.
    # ------------------------------------------------------------------

    for stage_index, attention_context in enumerate(STREAM_ATT_CONTEXTS, start=1):
        context_tag = f"{attention_context[0]}_{attention_context[1]}"
        stage_root = OUTPUT_ROOT
        stage_checkpoint_dir = stage_root / "checkpoints"
        stage_best_checkpoint = stage_checkpoint_dir / "best.ckpt"
        stage_metrics_path = stage_root / "epoch_metrics.json"
        stage_stable_checkpoint = LAST_STABLE_CHECKPOINT_PATH

        stage_root.mkdir(parents=True, exist_ok=True)
        stage_checkpoint_dir.mkdir(parents=True, exist_ok=True)

        print("\n############################################################")
        print(
            f"FULL-DATA STREAMING TRAINING - ATTENTION {attention_context}"
        )
        print("############################################################")

        rebuild_encoder_cache_aware(
            model,
            attention_context=attention_context,
        )

        # Keep the dataset config unchanged, so this stage consumes the entire
        # selected training manifest once per epoch.
        model.setup_training_data(
            model.cfg.train_ds
        )

        # The pre-train transcription health check runs before trainer.fit().
        # Lightning has therefore not yet moved the model to the GPU. Move the
        # full hybrid model explicitly so model parameters, preprocessor/STFT
        # buffers, and the patched transcribe input tensors all use cuda:0.
        model.to(torch.device("cuda:0"))
        print(f"Pre-train health-check model device: {next(model.parameters()).device}")

        # Verify CTC after changing the streaming attention context and before
        # the first optimizer step of this stage.
        run_pretrain_ctc_health_check(
            model=model,
            batch_size=BATCH_SIZE,
        )

        stage_domain_validation_callback = DomainValidationAndEarlyStopping(
            metrics_path=stage_metrics_path,
            best_checkpoint_path=stage_best_checkpoint,
            kirtan_manifest=KIRTAN_VAL_MANIFEST,
            sehaj_manifest=SEHAJ_VAL_MANIFEST,
            batch_size=BATCH_SIZE,
            patience=EARLY_STOP_PATIENCE,
            min_delta=MIN_WER_IMPROVEMENT,
        )

        stage_checkpoint_callback = LastTwoEpochCheckpoints(
            dirpath=stage_checkpoint_dir
        )

        stage_ctc_probe_callback = CTCHealthProbe(
            manifest_path=KIRTAN_VAL_MANIFEST,
            stable_checkpoint_path=stage_stable_checkpoint,
            every_optimizer_steps=CTC_PROBE_EVERY_OPTIMIZER_STEPS,
            save_every_optimizer_steps=CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS,
            sample_count=CTC_PROBE_SAMPLE_COUNT,
        )

        trainer = pl.Trainer(
            accelerator="gpu",
            devices=1,
            max_epochs=max_epochs,
            precision=16,
            accumulate_grad_batches=ACCUMULATE_GRAD_BATCHES,
            log_every_n_steps=100,
            limit_val_batches=0,
            default_root_dir=str(stage_root / "lightning"),
            enable_checkpointing=False,
            callbacks=[
                EpochProgressBar(),
                EpochTimer(),
                stage_ctc_probe_callback,
                stage_domain_validation_callback,
                stage_checkpoint_callback,
            ],
        )

        model.set_trainer(trainer)

        print("\n======================================")
        print(
            f"STARTING FULL-DATA STREAM TRAINING "
            f"FOR ATTENTION {attention_context}"
        )
        print("======================================")

        if resume_ckpt is not None:
            print(
                "\nResuming FULL [202,100] Lightning state from: "
                f"{resume_ckpt}"
            )
        else:
            print(
                "\nStarting fresh [202,100] training from exported model weights: "
                f"{MODEL_PATH}"
            )
            print("Optimizer/scheduler state: FRESH")

        try:
            trainer.fit(
                model,
                ckpt_path=str(resume_ckpt)
                if resume_ckpt is not None
                else None,
            )
        except Exception:
            print("\n======================================")
            print("STREAM TRAINING STOPPED / FAILED")
            print("======================================")
            print("Attention context:", attention_context)
            print("Last CTC-verified stable checkpoint:")
            print(stage_stable_checkpoint)
            raise

        print(
            f"\nβœ“ Completed full-data streaming training: "
            f"attention {attention_context}"
        )

        # Restore the best streaming weights before final export.
        if stage_best_checkpoint.exists():
            print("Loading best streaming checkpoint before continuing:")
            print(stage_best_checkpoint)
            checkpoint = torch.load(
                str(stage_best_checkpoint),
                map_location="cpu",
            )
            state_dict = checkpoint.get("state_dict", checkpoint)
            result = model.load_state_dict(state_dict, strict=False)

            missing = list(result.missing_keys)
            unexpected = list(result.unexpected_keys)

            if missing or unexpected:
                print("Missing keys:", missing[:30])
                print("Unexpected keys:", unexpected[:30])
                raise RuntimeError(
                    "Best streaming checkpoint did not cleanly reload."
                )

            print("βœ“ Best streaming weights restored")

    print(
        "\n======================================"
    )

    print(
        "TRAINING FINISHED"
    )

    print(
        "======================================"
    )

    print("Last CTC-verified stable checkpoint:")
    print(LAST_STABLE_CHECKPOINT_PATH)
    print("This checkpoint resumes the full [202,100] Lightning training state.")

    if (
        stage_domain_validation_callback.best_epoch
        is not None
    ):

        print(
            f"Best epoch: "
            f"{stage_domain_validation_callback.best_epoch}"
        )

        print(
            f"Best Kirtan validation WER: "
            f"{stage_domain_validation_callback.best_kirtan_wer:.6f} "
            f"({stage_domain_validation_callback.best_kirtan_wer * 100:.3f}%)"
        )

        print(
            f"Best checkpoint Sehaj validation WER: "
            f"{stage_domain_validation_callback.best_sehaj_wer:.6f} "
            f"({stage_domain_validation_callback.best_sehaj_wer * 100:.3f}%)"
        )

        print(
            f"Best checkpoint: "
            f"{BEST_CHECKPOINT_PATH}"
        )

    print(
        "\nLast two epoch checkpoints:"
    )

    last_checkpoints = sorted(
        CHECKPOINT_DIR.glob(
            "epoch_*.ckpt"
        )
    )

    for checkpoint in last_checkpoints:
        print(
            f"  {checkpoint}"
        )

    print(
        "\nSaving final training-state "
        ".nemo model to:"
    )

    print(
        OUTPUT_MODEL
    )

    model.save_to(
        str(
            OUTPUT_MODEL
        )
    )

    print(
        "\n======================================"
    )

    print(
        "COMPLETE"
    )

    print(
        "======================================"
    )

    print(
        f"Final model: "
        f"{OUTPUT_MODEL}"
    )

    print(
        f"Best checkpoint: "
        f"{BEST_CHECKPOINT_PATH}"
    )

    print(
        f"Epoch metrics: "
        f"{EPOCH_METRICS_PATH}"
    )

    # Never destroy during infrastructure testing.
    if args.test:
        if args.offline:
            print(
                "\nTEST OFFLINE MODE: no R2 upload was attempted."
            )
        print(
            "TEST MODE: Vast instance will NOT be destroyed."
        )

    elif not AUTO_DESTROY_VAST:
        print(
            "\nAUTO_DESTROY_VAST is disabled; instance will remain running."
        )

    elif stage_domain_validation_callback.best_epoch is None:
        print(
            "\nVast instance NOT destroyed: no best checkpoint was produced."
        )

    elif not stage_domain_validation_callback.r2_best_uploaded:
        print(
            "\nVast instance NOT destroyed: best.ckpt was not confirmed "
            "uploaded to R2."
        )

    else:
        destroy_current_vast_instance()


###############################################################################
# ENTRY POINT
###############################################################################

if __name__ == "__main__":
    main()