File size: 71,051 Bytes
2ede4d3 | 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 | #!/usr/bin/env python3
import argparse
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConf, open_dict
from pytorch_lightning.callbacks import Callback, TQDMProgressBar
import nemo.collections.asr as nemo_asr
###############################################################################
# DATASET CONFIGURATION
###############################################################################
# train.py is intended to live directly inside the training-data folder.
# This makes the whole training-data directory portable as one upload.
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:
# train_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 / "train_manifest-test.json"
else:
TRAIN_MANIFEST = DATA_ROOT / "train_manifest_max30s.json"
# Always score the real/full validation sets, including --test.
KIRTAN_VAL_MANIFEST = DATA_ROOT / "kirtan_val_manifest.json"
SEHAJ_VAL_MANIFEST = DATA_ROOT / "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
###############################################################################
# Restore the multilingual AI4Bharat base model with Punjabi ('pa') support.
MODEL_PATH = Path(
"/workspace/resume_checkpoint/baniguru_kirtan_v2_best.nemo"
).expanduser().resolve()
# Optional checkpoint overlay.
# Set to None to train directly from MODEL_PATH only.
# Example:
LAST_STABLE_CHECKPOINT_PATH = Path(
"/workspace/resume_checkpoint/last_stable.ckpt"
).expanduser().resolve()
# Resume from the latest CTC-verified stable checkpoint.
START_CHECKPOINT_PATH = LAST_STABLE_CHECKPOINT_PATH
# START_CHECKPOINT_PATH = None
###############################################################################
# TRAINING CONFIGURATION
###############################################################################
BATCH_SIZE = 8
# Conservative full-model fine-tuning rate after Stage-2 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 = 10
# 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
# Kirtan CER is the primary checkpoint metric. 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 the Kirtan-primary / Sehaj-tie-break rule 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/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_training"
).expanduser().resolve()
# Final .nemo model saved when training finishes / early-stops.
OUTPUT_MODEL = (
OUTPUT_ROOT
/ "baniguru_kirtan_v3.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_training_test").expanduser().resolve()
OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_v3.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-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 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's training/eval state and previous decoder are restored even if
validation raises an exception.
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
# CTC health guard. A catastrophic decoder collapse must never be turned
# into a fake WER, checkpoint, R2 upload, or early-stop event.
special_or_empty_outputs = 0
checked_outputs = 0
was_training = model.training
previous_decoder = getattr(
model,
"cur_decoder",
None,
)
model.eval()
# Hybrid RNNT+CTC models keep a current decoder. Force validation to use
# exactly the same branch every time. The AI4Bharat/NeMo hybrid model
# exposes cur_decoder; fail loudly if that contract is unavailable.
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 = model.transcribe(
audio_paths,
batch_size=batch_size,
return_hypotheses=False,
verbose=True,
language_id=LANGUAGE_CODE,
)
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
)
# Print one compact diagnostic batch per validation manifest.
# This is intentionally kept in the normal log so a future
# decoder regression can be diagnosed without another rerun.
if start == 0:
print("\nVALIDATION DEBUG")
print(f"Manifest: {manifest_path}")
print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}")
print(f"Outputs type: {type(outputs)}")
normalized_debug = normalized_batch
# The failure observed previously produced one special token
# (for example <unk>) for every sample. Never turn that
# decoder failure into a fake 100% WER / early-stop event.
if normalized_debug and all(
value in {"<unk>", "<blank>", ""}
for value in normalized_debug
):
raise RuntimeError(
"Validation decoder returned only special/empty "
f"tokens for {manifest_path}: "
f"{normalized_debug[: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
)
# CER excludes spaces.
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:
# Restore decoder state before handing the model back to Lightning.
model.cur_decoder = previous_decoder
if was_training:
model.train()
else:
model.eval()
# Full-manifest protection as a second line of defense. The historical
# failure returned <unk> for essentially every sample. Abort before any
# metric/checkpoint action if >=95% of outputs are special/empty.
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 = [s["audio_filepath"] for s in self.probe_samples]
references = [s["text"] for s in self.probe_samples]
pl_module.eval()
pl_module.cur_decoder = VALIDATION_DECODER
try:
with torch.no_grad():
outputs = pl_module.transcribe(
audio_paths,
batch_size=len(audio_paths),
return_hypotheses=False,
verbose=False,
language_id=LANGUAGE_CODE,
)
hypotheses = select_primary_transcriptions(
outputs,
expected_count=len(audio_paths),
)
normalized = [
" ".join(str(v).strip().split())
for v 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(v in special_values for v in normalized)
epoch_number = trainer.current_epoch + 1
print("\n======================================")
print(f"EPOCH {epoch_number} - CTC PROBE @ OPTIMIZER STEP {global_step}")
print("======================================")
for i, (ref, hyp) in enumerate(zip(references, normalized), 1):
print(f" [{i}] REF : {ref}")
print(f" [{i}] PRED: {hyp}")
print(f"CTC probe special/empty: {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 hypotheses "
f"were <unk>/<blank>/empty: {normalized}."
)
print(f"CTC probe HEALTHY at optimizer step {global_step}")
# Probe every 500 optimizer steps, but only write the rolling full
# Lightning checkpoint every 2000 optimizer steps. A checkpoint is
# written only after the probe at that exact step has passed.
if global_step % self.save_every_optimizer_steps != 0:
print(
f"No checkpoint save at step {global_step}; next stable save is "
f"on a multiple of {self.save_every_optimizer_steps} optimizer steps."
)
return
# Save to a temporary file first, then replace atomically so an
# interrupted write does not destroy the previous known-good checkpoint.
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 {global_step}: "
f"{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. Use Kirtan CER as the PRIMARY best.ckpt metric.
5. Also accept a Sehaj WER improvement when Kirtan CER is within the
configured tolerance of the currently selected best checkpoint.
6. Reset early-stopping patience for either kind of accepted improvement.
"""
def __init__(
self,
metrics_path: Path,
best_checkpoint_path: Path,
kirtan_manifest: Path,
sehaj_manifest: Path,
batch_size: int,
patience: int = 3,
min_delta: float = 0.0001,
kirtan_cer_tolerance_for_sehaj: float = 0.005,
):
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 = patience
self.min_delta = min_delta
self.kirtan_cer_tolerance_for_sehaj = float(
kirtan_cer_tolerance_for_sehaj
)
self.best_kirtan_cer = float("inf")
self.best_kirtan_wer = float("inf")
self.best_sehaj_wer = float("inf")
self.best_epoch = None
self.bad_epochs = 0
self.history = []
self.r2_best_uploaded = False
def write_history(self):
best_kirtan_cer = (
None if self.best_kirtan_cer == float("inf") else self.best_kirtan_cer
)
best_kirtan_wer = (
None if self.best_kirtan_wer == float("inf") else self.best_kirtan_wer
)
best_sehaj_wer = (
None if self.best_sehaj_wer == float("inf") else self.best_sehaj_wer
)
data = {
"selection_metric": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance",
"best_epoch": self.best_epoch,
"best_kirtan_cer": best_kirtan_cer,
"best_kirtan_cer_percent": (
None if best_kirtan_cer is None else best_kirtan_cer * 100.0
),
"best_kirtan_wer": best_kirtan_wer,
"best_kirtan_wer_percent": (
None if best_kirtan_wer is None else best_kirtan_wer * 100.0
),
"best_sehaj_wer": best_sehaj_wer,
"best_sehaj_wer_percent": (
None if best_sehaj_wer is None else best_sehaj_wer * 100.0
),
"patience": self.patience,
"min_metric_improvement": self.min_delta,
"kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj,
"kirtan_cer_tolerance_for_sehaj_percent_points": (
self.kirtan_cer_tolerance_for_sehaj * 100.0
),
"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 is primary checkpoint metric)...")
kirtan = score_validation_manifest(
model=pl_module,
manifest_path=self.kirtan_manifest,
batch_size=self.batch_size,
)
print("Scoring SEHAJ PAATH validation (WER secondary metric)...")
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_sehaj_wer = self.best_sehaj_wer
# Selection rule:
# 1. Kirtan CER is primary. Improvement >= min_delta always wins.
# 2. Sehaj WER may also win when it improves >= min_delta and Kirtan CER
# is no more than the configured tolerance worse than the selected best.
primary_improved = (
kirtan["cer"] < previous_best_kirtan_cer - self.min_delta
)
sehaj_improved = (
sehaj["wer"] < previous_best_sehaj_wer - self.min_delta
)
kirtan_within_sehaj_tolerance = (
kirtan["cer"]
<= previous_best_kirtan_cer + self.kirtan_cer_tolerance_for_sehaj
)
sehaj_tiebreak_improved = (
sehaj_improved and kirtan_within_sehaj_tolerance
)
improved = primary_improved or sehaj_tiebreak_improved
if primary_improved:
improvement_reason = "kirtan_cer_primary"
elif sehaj_tiebreak_improved:
improvement_reason = "sehaj_wer_with_kirtan_cer_tolerance"
else:
improvement_reason = None
if improved:
self.best_kirtan_cer = kirtan["cer"]
self.best_kirtan_wer = kirtan["wer"]
self.best_sehaj_wer = sehaj["wer"]
self.best_epoch = epoch_number
self.bad_epochs = 0
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.")
if improvement_reason == "kirtan_cer_primary":
print("\nNEW BEST — KIRTAN CER IMPROVED")
else:
print("\nNEW BEST — SEHAJ WER IMPROVED WITH KIRTAN CER WITHIN TOLERANCE")
print(
"Kirtan CER is within the allowed "
f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} "
"percentage-point tolerance."
)
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 accepted validation improvement.")
print(
f"Current Kirtan CER: {kirtan['cer']:.6f} "
f"({kirtan['cer_percent']:.3f}%)"
)
print(
f"Best 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"Current Sehaj WER: {sehaj['wer']:.6f} "
f"({sehaj['wer_percent']:.3f}%)"
)
print(
f"Best Sehaj WER for selected checkpoint: {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": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance",
"improved": improved,
"improvement_reason": improvement_reason,
"primary_kirtan_cer_improved": primary_improved,
"sehaj_tiebreak_improved": sehaj_tiebreak_improved,
"sehaj_wer_improved": sehaj_improved,
"kirtan_cer_within_sehaj_tolerance": kirtan_within_sehaj_tolerance,
"kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj,
"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,
"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: KIRTAN CER primary; "
"SEHAJ WER can also win when it improves and Kirtan CER is within +"
f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} percentage points "
"of the selected best Kirtan CER"
)
print(f"Metrics JSON: {self.metrics_path}")
print("--------------------------------------")
if self.bad_epochs >= self.patience:
print("\n########################################")
print("EARLY STOPPING: NO ACCEPTED KIRTAN/SEHAJ IMPROVEMENT")
print("########################################")
print(
f"No accepted primary/secondary improvement for "
f"{self.bad_epochs} epochs."
)
print(f"Best epoch: {self.best_epoch}")
print(
f"Best Kirtan CER: {self.best_kirtan_cer:.6f} "
f"({self.best_kirtan_cer * 100:.3f}%)"
)
print(
f"Best Kirtan WER at selected checkpoint: {self.best_kirtan_wer:.6f} "
f"({self.best_kirtan_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}"
)
if (
START_CHECKPOINT_PATH is not None
and not START_CHECKPOINT_PATH.exists()
):
raise FileNotFoundError(
"Starting 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")
###############################################################################
# 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) MULTILINGUAL 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
)
)
)
# Overlay the best Stage-2 learned weights only.
load_start_checkpoint_weights(
model
)
# --------------------------------------------------------
# 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}"
)
domain_validation_callback = (
DomainValidationAndEarlyStopping(
metrics_path=(
EPOCH_METRICS_PATH
),
best_checkpoint_path=(
BEST_CHECKPOINT_PATH
),
kirtan_manifest=(
KIRTAN_VAL_MANIFEST
),
sehaj_manifest=(
SEHAJ_VAL_MANIFEST
),
batch_size=(
BATCH_SIZE
),
patience=(
EARLY_STOP_PATIENCE
),
min_delta=(
MIN_WER_IMPROVEMENT
),
kirtan_cer_tolerance_for_sehaj=(
KIRTAN_CER_TOLERANCE_FOR_SEHAJ
),
)
)
checkpoint_callback = (
LastTwoEpochCheckpoints(
dirpath=(
CHECKPOINT_DIR
)
)
)
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}"
)
ctc_probe_callback = CTCHealthProbe(
manifest_path=KIRTAN_VAL_MANIFEST,
stable_checkpoint_path=LAST_STABLE_CHECKPOINT_PATH,
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,
# IMPORTANT:
# Validation is done explicitly in the domain callback after each
# training epoch. Disable Lightning's built-in validation loop so
# kirtan is not evaluated twice.
limit_val_batches=0,
# Keep Lightning logs under the Vast workspace too.
default_root_dir=str(OUTPUT_ROOT / "lightning"),
# Checkpoints are managed manually by the callbacks below.
enable_checkpointing=False,
callbacks=[
EpochProgressBar(),
EpochTimer(),
ctc_probe_callback,
domain_validation_callback,
checkpoint_callback,
],
)
model.set_trainer(
trainer
)
print(
"\nSetting up training dataset..."
)
model.setup_training_data(
model.cfg.train_ds
)
# Critical safety gate: verify CTC BEFORE the first optimizer step.
# If this raises, trainer.fit() is never entered.
run_pretrain_ctc_health_check(
model=model,
batch_size=BATCH_SIZE,
)
print(
"\n======================================"
)
print(
"STARTING GURBANI PUNJABI (pa) FINE-TUNING"
)
print(
"======================================"
)
try:
trainer.fit(
model,
ckpt_path=(
str(START_CHECKPOINT_PATH)
if START_CHECKPOINT_PATH is not None
else None
),
)
except Exception:
print("\n======================================")
print("TRAINING STOPPED / FAILED")
print("======================================")
print("Last CTC-verified stable checkpoint:")
print(LAST_STABLE_CHECKPOINT_PATH)
print("\nRestart with the same train.py.")
print("It will resume model + optimizer + scheduler state from last_stable.ckpt.")
raise
print(
"\n======================================"
)
print(
"TRAINING FINISHED"
)
print(
"======================================"
)
print("Last CTC-verified stable checkpoint:")
print(LAST_STABLE_CHECKPOINT_PATH)
print("This same train.py resumes full Lightning state from that checkpoint.")
if (
domain_validation_callback.best_epoch
is not None
):
print(
f"Best epoch: "
f"{domain_validation_callback.best_epoch}"
)
print(
f"Best Kirtan validation WER: "
f"{domain_validation_callback.best_kirtan_wer:.6f} "
f"({domain_validation_callback.best_kirtan_wer * 100:.3f}%)"
)
print(
f"Best checkpoint Sehaj validation WER: "
f"{domain_validation_callback.best_sehaj_wer:.6f} "
f"({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 domain_validation_callback.best_epoch is None:
print(
"\nVast instance NOT destroyed: no best checkpoint was produced."
)
elif not 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()
|