Sukhpal Singh commited on
Commit
2ede4d3
·
verified ·
1 Parent(s): 7eff3fe

Added Nemo train scripts

Browse files
Files changed (2) hide show
  1. train-stream.py +2784 -0
  2. train.py +2446 -0
train-stream.py ADDED
@@ -0,0 +1,2784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Version: starts from baniguru_kirtan_stream_v2_224_27.nemo and fine-tunes
4
+ # using [202,100] attention context (about 8.08 s left, 4.00 s right).
5
+
6
+ import argparse
7
+ import copy
8
+ import json
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import torch
16
+ import pytorch_lightning as pl
17
+ from hydra.utils import instantiate
18
+ from omegaconf import OmegaConf, open_dict
19
+ from pytorch_lightning.callbacks import Callback, TQDMProgressBar
20
+
21
+ import nemo.collections.asr as nemo_asr
22
+
23
+
24
+ ###############################################################################
25
+ # DATASET CONFIGURATION
26
+ ###############################################################################
27
+
28
+ # The script lives in /workspace and manifests live in /workspace/training_data.
29
+ DATA_ROOT = Path(__file__).resolve().parent
30
+
31
+ # Manifest paths are selected at startup.
32
+ #
33
+ # Normal:
34
+ # train_manifest.json
35
+ # kirtan_val_manifest.json
36
+ # sehaj_paath_val_manifest.json
37
+ #
38
+ # --test:
39
+ # training_manifest_test.json
40
+ # kirtan_val_manifest.json (FULL validation)
41
+ # sehaj_paath_val_manifest.json (FULL validation)
42
+ #
43
+ # Audio paths inside the manifests are used exactly as written.
44
+ TRAIN_MANIFEST = None
45
+ KIRTAN_VAL_MANIFEST = None
46
+ SEHAJ_VAL_MANIFEST = None
47
+
48
+
49
+ def configure_manifests(test_mode: bool) -> None:
50
+ """Use small training data in --test, but always use full validation."""
51
+ global TRAIN_MANIFEST
52
+ global KIRTAN_VAL_MANIFEST
53
+ global SEHAJ_VAL_MANIFEST
54
+
55
+ if test_mode:
56
+ TRAIN_MANIFEST = DATA_ROOT / "training_data/training_manifest_test.json"
57
+ else:
58
+ TRAIN_MANIFEST = DATA_ROOT / "training_data/training_manifest.json"
59
+
60
+ # Always score the real/full validation sets, including --test.
61
+ KIRTAN_VAL_MANIFEST = DATA_ROOT / "training_data/kirtan_val_manifest.json"
62
+ SEHAJ_VAL_MANIFEST = DATA_ROOT / "training_data/sehaj_paath_val_manifest.json"
63
+
64
+ EXPECTED_SAMPLE_RATE = 16_000
65
+ LANGUAGE_CODE = "pa"
66
+
67
+ # Use one explicit decoder for validation so the metric is stable across epochs.
68
+ # The model is hybrid RNNT+CTC; CTC is used here only for explicit WER/CER scoring.
69
+ VALIDATION_DECODER = "ctc"
70
+
71
+
72
+ ###############################################################################
73
+ # MODEL CONFIGURATION
74
+ ###############################################################################
75
+
76
+ # Start from the currently exported streaming model. Its learned weights and
77
+ # [224,27] streaming configuration are restored first; the encoder is then
78
+ # rebuilt from those weights below for the new [202,100] training context.
79
+ MODEL_PATH = Path(
80
+ "/workspace/resume_checkpoint/baniguru_kirtan_stream_v2_224_27.nemo"
81
+ ).expanduser().resolve()
82
+ SOURCE_MODEL_ATT_CONTEXT = [224, 27]
83
+
84
+ # The first run uses MODEL_PATH directly (weights only; fresh optimizer and
85
+ # scheduler). After that, only this context-specific rolling checkpoint is used
86
+ # to resume the complete Lightning state.
87
+ START_CHECKPOINT_PATH = None
88
+
89
+ # Rolling full-Lightning checkpoint produced by THIS NEW [202,100] run.
90
+ # On any restart, this takes precedence over the exported-model initialization and
91
+ # restores the complete Lightning state (model + optimizer + scheduler + epoch +
92
+ # callback state). The distinct filename prevents resuming a different context.
93
+ LAST_STABLE_CHECKPOINT_PATH = Path(
94
+ "/workspace/resume_checkpoint/stream_202_100_last_stable.ckpt"
95
+ ).expanduser().resolve()
96
+
97
+
98
+ ###############################################################################
99
+ # CACHE-AWARE / STREAMING ENCODER CONFIGURATION
100
+
101
+ # Context Look-ahead Chunk
102
+ # [112,27] 1080 ms 1120 ms
103
+ # [224,27] 520 ms 560 ms
104
+ # [112,6] 240 ms 280 ms
105
+ # [112,3] 120 ms 160 ms
106
+ # [112,1] 40 ms 80 ms
107
+ # [112,0] 0 ms 40 ms
108
+
109
+ # Exported MODEL_PATH context: [224,27] (224x40ms left, 27x40ms right).
110
+ # Training context: [202,100] = 202x40ms left (~8.08s), 100x40ms right (~4.00s).
111
+
112
+ # Diagnostic:
113
+ # [112, 100] 4 sec right
114
+
115
+ ###############################################################################
116
+
117
+ STREAM_ATT_CONTEXTS = [[202, 100]]
118
+
119
+ # Train the complete manifest using ~8.08 s of left context and ~4.00 s of right context.
120
+
121
+ CAUSAL_CONV_CONTEXT = [30, 0]
122
+
123
+ ###############################################################################
124
+ # TRAINING CONFIGURATION
125
+ ###############################################################################
126
+
127
+ BATCH_SIZE = 8
128
+
129
+ # Conservative full-model fine-tuning rate for the [202,100] adaptation.
130
+ LEARNING_RATE = 1e-5
131
+
132
+ # Upper limit.
133
+ # Early stopping can stop training before reaching this.
134
+ MAX_EPOCHS = 50
135
+
136
+ # Effective batch size:
137
+ #
138
+ # BATCH_SIZE * ACCUMULATE_GRAD_BATCHES
139
+ #
140
+ # 4 * 2 = 8
141
+ ACCUMULATE_GRAD_BATCHES = 1
142
+
143
+ # Tiny fixed CTC probe during training.
144
+ CTC_PROBE_EVERY_OPTIMIZER_STEPS = 1000
145
+ CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS = 2000
146
+ CTC_PROBE_SAMPLE_COUNT = 2
147
+
148
+
149
+ ###############################################################################
150
+ # EARLY STOPPING CONFIGURATION
151
+ ###############################################################################
152
+
153
+ # Stop after this many consecutive validation epochs without improvement.
154
+ EARLY_STOP_PATIENCE = 20
155
+ EARLY_STOP_WARMUP_EPOCHS = 0
156
+
157
+ # WER needs to improve by at least this much to count as an improvement.
158
+ #
159
+ # Example:
160
+ # old WER = 0.1000
161
+ # new WER = 0.09995
162
+ #
163
+ # Difference = 0.00005
164
+ #
165
+ # With MIN_WER_IMPROVEMENT = 0.0001,
166
+ # that would NOT count as an improvement.
167
+ MIN_WER_IMPROVEMENT = 0.0001
168
+
169
+ # Match the offline v3 checkpoint rule: Kirtan CER is primary. Sehaj WER may
170
+ # also promote a checkpoint when it improves by at least MIN_WER_IMPROVEMENT
171
+ # and Kirtan CER is no more than 0.5 percentage points worse than the currently
172
+ # selected best checkpoint. CER is stored as a fraction, so 0.005 == 0.5 points.
173
+ KIRTAN_CER_TOLERANCE_FOR_SEHAJ = 0.005
174
+
175
+
176
+ ###############################################################################
177
+ # CLOUDFLARE R2 BACKUP CONFIGURATION
178
+ ###############################################################################
179
+
180
+ # Upload ONLY best.ckpt when any accepted metric (Kirtan CER, Kirtan WER, or Sehaj WER) improves.
181
+ # Credentials are read from environment variables so secrets are not stored
182
+ # inside this training script.
183
+ R2_UPLOAD_ENABLED = True
184
+ R2_OBJECT_KEY = os.environ.get(
185
+ "R2_OBJECT_KEY",
186
+ "checkpoints/stream-202_100-best.ckpt",
187
+ )
188
+ R2_UPLOAD_RETRIES = 3
189
+ R2_RETRY_DELAY_SECONDS = 10
190
+
191
+
192
+ ###############################################################################
193
+ # VAST.AI AUTO-DESTROY CONFIGURATION
194
+ ###############################################################################
195
+
196
+ # Full runs automatically destroy the current Vast instance only after:
197
+ # 1. training has finished (early stopping or max epochs), AND
198
+ # 2. a best.ckpt was successfully uploaded to R2.
199
+ #
200
+ # --test NEVER destroys the instance.
201
+ AUTO_DESTROY_VAST = False
202
+
203
+
204
+ ###############################################################################
205
+ # OUTPUT / CHECKPOINT / LOG CONFIGURATION
206
+ ###############################################################################
207
+
208
+ # Put large/persistent training outputs under this directory.
209
+ #
210
+ # Vast.ai workspace output directory.
211
+ #
212
+ # Checkpoints, metrics, and the final model stay under OUTPUT_ROOT.
213
+ #
214
+ # OUTPUT_ROOT/
215
+ # ├── checkpoints/
216
+ # │ ├── best.ckpt
217
+ # │ ├── epoch_XXX.ckpt
218
+ # │ └── epoch_YYY.ckpt
219
+ # ├── wer_history.json
220
+ # └── gurbani_sehaj_paath_v1_base_indicconformer_stt_multi_hybrid_rnnt_600m.nemo
221
+ #
222
+ OUTPUT_ROOT = Path(
223
+ "/workspace/asr_stream_training_202_100"
224
+ ).expanduser().resolve()
225
+
226
+ # Final .nemo model saved when training finishes / early-stops.
227
+ OUTPUT_MODEL = (
228
+ OUTPUT_ROOT
229
+ / "baniguru_kirtan_stream_202_100.nemo"
230
+ )
231
+
232
+ # Best checkpoint + last two epoch checkpoints.
233
+ CHECKPOINT_DIR = (
234
+ OUTPUT_ROOT / "checkpoints"
235
+ )
236
+
237
+ BEST_CHECKPOINT_PATH = (
238
+ CHECKPOINT_DIR / "best.ckpt"
239
+ )
240
+
241
+ # Per-epoch validation metrics for BOTH domains.
242
+ # Contains kirtan WER/CER + sehaj WER/CER.
243
+ EPOCH_METRICS_PATH = (
244
+ OUTPUT_ROOT / "epoch_metrics.json"
245
+ )
246
+
247
+
248
+ def configure_outputs(test_mode: bool, offline: bool = False) -> None:
249
+ """Keep test artifacts separate and optionally disable R2 for test runs."""
250
+ global OUTPUT_ROOT
251
+ global OUTPUT_MODEL
252
+ global CHECKPOINT_DIR
253
+ global BEST_CHECKPOINT_PATH
254
+ global EPOCH_METRICS_PATH
255
+ global R2_OBJECT_KEY
256
+ global R2_UPLOAD_ENABLED
257
+
258
+ if test_mode:
259
+ OUTPUT_ROOT = Path("/workspace/asr_stream_training_202_100_test").expanduser().resolve()
260
+ OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_stream_202_100.nemo"
261
+ CHECKPOINT_DIR = OUTPUT_ROOT / "checkpoints"
262
+ BEST_CHECKPOINT_PATH = CHECKPOINT_DIR / "best.ckpt"
263
+ EPOCH_METRICS_PATH = OUTPUT_ROOT / "epoch_metrics.json"
264
+
265
+ # Online test runs use a separate R2 object and never overwrite
266
+ # the full-run best checkpoint.
267
+ R2_OBJECT_KEY = "checkpoints/test-202_100-best.ckpt"
268
+
269
+ if offline:
270
+ # --offline is intentionally restricted to --test in parse_args().
271
+ R2_UPLOAD_ENABLED = False
272
+
273
+ ###############################################################################
274
+ # CALLBACK: PROGRESS BAR WITH HUMAN-READABLE EPOCH NUMBER
275
+ ###############################################################################
276
+
277
+ class EpochProgressBar(TQDMProgressBar):
278
+ def get_metrics(self, trainer, pl_module):
279
+ items = super().get_metrics(trainer, pl_module)
280
+ items["epoch"] = trainer.current_epoch + 1
281
+ return items
282
+
283
+
284
+ ###############################################################################
285
+ # CALLBACK: EPOCH TIMER
286
+ ###############################################################################
287
+
288
+ class EpochTimer(Callback):
289
+ def __init__(self):
290
+ super().__init__()
291
+ self.start_time = None
292
+
293
+ def on_train_epoch_start(
294
+ self,
295
+ trainer,
296
+ pl_module,
297
+ ):
298
+ self.start_time = time.time()
299
+
300
+ def on_train_epoch_end(
301
+ self,
302
+ trainer,
303
+ pl_module,
304
+ ):
305
+ if self.start_time is None:
306
+ print(
307
+ f"\nEpoch {trainer.current_epoch + 1} completed "
308
+ "(timer unavailable because training resumed mid-epoch)"
309
+ )
310
+ return
311
+
312
+ elapsed = time.time() - self.start_time
313
+
314
+ print(
315
+ f"\nEpoch {trainer.current_epoch + 1} "
316
+ f"completed in {elapsed / 60:.2f} minutes"
317
+ )
318
+
319
+
320
+ ###############################################################################
321
+ # VALIDATION METRICS HELPERS
322
+ ###############################################################################
323
+
324
+ def levenshtein_ops(reference, hypothesis):
325
+ """
326
+ Return (substitutions, deletions, insertions) for two sequences.
327
+ """
328
+ n = len(reference)
329
+ m = len(hypothesis)
330
+
331
+ # dp[i][j] = (cost, S, D, I)
332
+ dp = [[None] * (m + 1) for _ in range(n + 1)]
333
+
334
+ dp[0][0] = (0, 0, 0, 0)
335
+
336
+ for i in range(1, n + 1):
337
+ dp[i][0] = (i, 0, i, 0)
338
+
339
+ for j in range(1, m + 1):
340
+ dp[0][j] = (j, 0, 0, j)
341
+
342
+ for i in range(1, n + 1):
343
+ for j in range(1, m + 1):
344
+
345
+ if reference[i - 1] == hypothesis[j - 1]:
346
+ dp[i][j] = dp[i - 1][j - 1]
347
+ continue
348
+
349
+ sub_prev = dp[i - 1][j - 1]
350
+ del_prev = dp[i - 1][j]
351
+ ins_prev = dp[i][j - 1]
352
+
353
+ candidates = [
354
+ (
355
+ sub_prev[0] + 1,
356
+ sub_prev[1] + 1,
357
+ sub_prev[2],
358
+ sub_prev[3],
359
+ ),
360
+ (
361
+ del_prev[0] + 1,
362
+ del_prev[1],
363
+ del_prev[2] + 1,
364
+ del_prev[3],
365
+ ),
366
+ (
367
+ ins_prev[0] + 1,
368
+ ins_prev[1],
369
+ ins_prev[2],
370
+ ins_prev[3] + 1,
371
+ ),
372
+ ]
373
+
374
+ dp[i][j] = min(
375
+ candidates,
376
+ key=lambda item: (
377
+ item[0],
378
+ item[2], # prefer fewer deletions on ties
379
+ item[3],
380
+ item[1],
381
+ ),
382
+ )
383
+
384
+ _, substitutions, deletions, insertions = dp[n][m]
385
+
386
+ return substitutions, deletions, insertions
387
+
388
+
389
+ def extract_text_from_hypothesis(item):
390
+ if isinstance(item, str):
391
+ return item
392
+
393
+ if hasattr(item, "text"):
394
+ return str(item.text)
395
+
396
+ if isinstance(item, dict):
397
+ if "text" in item:
398
+ return str(item["text"])
399
+
400
+ if "pred_text" in item:
401
+ return str(item["pred_text"])
402
+
403
+ return str(item)
404
+
405
+
406
+ def select_primary_transcriptions(outputs, expected_count):
407
+ """
408
+ Normalize NeMo transcribe() output.
409
+
410
+ Hybrid RNNT+CTC models can return more than one decoding branch.
411
+ We select the first complete branch, which is treated here as the
412
+ primary transcription stream for BOTH domains and all epochs.
413
+ """
414
+ if isinstance(outputs, tuple):
415
+ outputs = list(outputs)
416
+
417
+ if isinstance(outputs, list):
418
+
419
+ # Normal case: one hypothesis per input.
420
+ if len(outputs) == expected_count and (
421
+ expected_count == 0
422
+ or not isinstance(outputs[0], (list, tuple))
423
+ ):
424
+ return [
425
+ extract_text_from_hypothesis(item)
426
+ for item in outputs
427
+ ]
428
+
429
+ # Hybrid case: [rnnt_outputs, ctc_outputs, ...]
430
+ for branch in outputs:
431
+ if (
432
+ isinstance(branch, (list, tuple))
433
+ and len(branch) == expected_count
434
+ ):
435
+ return [
436
+ extract_text_from_hypothesis(item)
437
+ for item in branch
438
+ ]
439
+
440
+ raise RuntimeError(
441
+ "Could not identify the primary transcribe() output branch. "
442
+ f"Expected {expected_count} predictions; got type={type(outputs)}"
443
+ )
444
+
445
+
446
+ def load_validation_manifest(manifest_path: Path):
447
+ samples = []
448
+
449
+ with Path(manifest_path).open(
450
+ "r",
451
+ encoding="utf-8",
452
+ ) as handle:
453
+
454
+ for line_number, line in enumerate(
455
+ handle,
456
+ start=1,
457
+ ):
458
+ line = line.strip()
459
+
460
+ if not line:
461
+ continue
462
+
463
+ item = json.loads(line)
464
+
465
+ audio_path = item.get(
466
+ "audio_filepath"
467
+ )
468
+
469
+ text = item.get(
470
+ "text"
471
+ )
472
+
473
+ if not audio_path:
474
+ raise RuntimeError(
475
+ f"{manifest_path}: line {line_number} "
476
+ "has no audio_filepath."
477
+ )
478
+
479
+ if text is None:
480
+ raise RuntimeError(
481
+ f"{manifest_path}: line {line_number} "
482
+ "has no text."
483
+ )
484
+
485
+ language = item.get("lang")
486
+
487
+ if language != LANGUAGE_CODE:
488
+ raise RuntimeError(
489
+ f"{manifest_path}: line {line_number} "
490
+ f"must have lang='{LANGUAGE_CODE}', got {language!r}."
491
+ )
492
+
493
+ samples.append(
494
+ {
495
+ "audio_filepath": str(audio_path),
496
+ "text": " ".join(
497
+ str(text).strip().split()
498
+ ),
499
+ "lang": language,
500
+ }
501
+ )
502
+
503
+ if not samples:
504
+ raise RuntimeError(
505
+ f"Validation manifest is empty: {manifest_path}"
506
+ )
507
+
508
+ return samples
509
+
510
+
511
+
512
+ def gpu_safe_transcribe(
513
+ model,
514
+ audio_paths,
515
+ batch_size: int,
516
+ verbose: bool,
517
+ ):
518
+ """
519
+ Explicit transcription helper.
520
+
521
+ The model is moved to CUDA before the pre-train health check. The patched
522
+ AI4Bharat hybrid _transcribe_forward() moves file-dataloader audio tensors
523
+ onto the same model device before forward(), so no runtime monkey-patching
524
+ is needed here.
525
+ """
526
+ return model.transcribe(
527
+ audio_paths,
528
+ batch_size=batch_size,
529
+ return_hypotheses=False,
530
+ verbose=verbose,
531
+ language_id=LANGUAGE_CODE,
532
+ )
533
+
534
+ def score_validation_manifest(
535
+ model,
536
+ manifest_path: Path,
537
+ batch_size: int,
538
+ ):
539
+ """
540
+ Explicitly transcribe one validation manifest and return STRICT
541
+ word-level WER and character-level CER.
542
+
543
+ Validation is forced onto one decoder (CTC) for every epoch so a hybrid
544
+ RNNT+CTC model cannot silently switch decoding branches between calls.
545
+ The model stays on its existing device (normally CUDA) and its training/eval
546
+ state and previous decoder are restored even if validation raises.
547
+
548
+ Spaces are excluded from CER.
549
+ """
550
+
551
+ samples = load_validation_manifest(manifest_path)
552
+
553
+ total_word_substitutions = 0
554
+ total_word_deletions = 0
555
+ total_word_insertions = 0
556
+ total_reference_words = 0
557
+ total_predicted_words = 0
558
+
559
+ total_char_substitutions = 0
560
+ total_char_deletions = 0
561
+ total_char_insertions = 0
562
+ total_reference_chars = 0
563
+ total_predicted_chars = 0
564
+
565
+ special_or_empty_outputs = 0
566
+ checked_outputs = 0
567
+
568
+ was_training = model.training
569
+ previous_decoder = getattr(model, "cur_decoder", None)
570
+
571
+ model.eval()
572
+
573
+ if not hasattr(model, "cur_decoder"):
574
+ raise RuntimeError(
575
+ "Hybrid validation expected model.cur_decoder, but the restored "
576
+ "model does not expose it. Refusing to compute an ambiguous WER."
577
+ )
578
+
579
+ model.cur_decoder = VALIDATION_DECODER
580
+
581
+ try:
582
+ with torch.no_grad():
583
+ for start in range(0, len(samples), batch_size):
584
+ batch = samples[start:start + batch_size]
585
+
586
+ audio_paths = [
587
+ item["audio_filepath"]
588
+ for item in batch
589
+ ]
590
+
591
+ outputs = gpu_safe_transcribe(
592
+ model=model,
593
+ audio_paths=audio_paths,
594
+ batch_size=batch_size,
595
+ verbose=True,
596
+ )
597
+
598
+ hypotheses = select_primary_transcriptions(
599
+ outputs,
600
+ expected_count=len(batch),
601
+ )
602
+
603
+ normalized_batch = [
604
+ " ".join(str(value).strip().split())
605
+ for value in hypotheses
606
+ ]
607
+
608
+ checked_outputs += len(normalized_batch)
609
+ special_or_empty_outputs += sum(
610
+ value in {"<unk>", "<blank>", ""}
611
+ for value in normalized_batch
612
+ )
613
+
614
+ if start == 0:
615
+ print("\nVALIDATION DEBUG")
616
+ print(f"Manifest: {manifest_path}")
617
+ print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}")
618
+ print(f"Device: {next(model.parameters()).device}")
619
+ print(f"Outputs type: {type(outputs)}")
620
+
621
+ if normalized_batch and all(
622
+ value in {"<unk>", "<blank>", ""}
623
+ for value in normalized_batch
624
+ ):
625
+ raise RuntimeError(
626
+ "Validation decoder returned only special/empty "
627
+ f"tokens for {manifest_path}: "
628
+ f"{normalized_batch[:5]}. "
629
+ "Stopping instead of recording a false WER."
630
+ )
631
+
632
+ for batch_index, (sample, hypothesis) in enumerate(
633
+ zip(batch, hypotheses),
634
+ ):
635
+ reference = " ".join(
636
+ sample["text"].strip().split()
637
+ )
638
+ hypothesis = " ".join(
639
+ hypothesis.strip().split()
640
+ )
641
+
642
+ validation_index = start + batch_index + 1
643
+ print(f" [{validation_index}] REF : {reference}")
644
+ print(f" [{validation_index}] PRED: {hypothesis}")
645
+
646
+ ref_words = reference.split()
647
+ hyp_words = hypothesis.split()
648
+
649
+ word_s, word_d, word_i = levenshtein_ops(
650
+ ref_words,
651
+ hyp_words,
652
+ )
653
+
654
+ total_word_substitutions += word_s
655
+ total_word_deletions += word_d
656
+ total_word_insertions += word_i
657
+ total_reference_words += len(ref_words)
658
+ total_predicted_words += len(hyp_words)
659
+
660
+ ref_chars = list(reference.replace(" ", ""))
661
+ hyp_chars = list(hypothesis.replace(" ", ""))
662
+
663
+ char_s, char_d, char_i = levenshtein_ops(
664
+ ref_chars,
665
+ hyp_chars,
666
+ )
667
+
668
+ total_char_substitutions += char_s
669
+ total_char_deletions += char_d
670
+ total_char_insertions += char_i
671
+ total_reference_chars += len(ref_chars)
672
+ total_predicted_chars += len(hyp_chars)
673
+
674
+ finally:
675
+ model.cur_decoder = previous_decoder
676
+
677
+ if was_training:
678
+ model.train()
679
+ else:
680
+ model.eval()
681
+
682
+ special_ratio = (
683
+ special_or_empty_outputs / checked_outputs
684
+ if checked_outputs
685
+ else 1.0
686
+ )
687
+
688
+ if checked_outputs == 0:
689
+ raise RuntimeError(
690
+ f"Validation produced zero hypotheses for {manifest_path}."
691
+ )
692
+
693
+ if special_ratio >= 0.95:
694
+ raise RuntimeError(
695
+ "CTC VALIDATION COLLAPSE DETECTED: "
696
+ f"{special_or_empty_outputs}/{checked_outputs} "
697
+ f"({special_ratio * 100.0:.2f}%) hypotheses were "
698
+ f"<unk>/<blank>/empty for {manifest_path}. "
699
+ "Training is being aborted. No checkpoint from this epoch "
700
+ "will be promoted or uploaded."
701
+ )
702
+
703
+ word_errors = (
704
+ total_word_substitutions
705
+ + total_word_deletions
706
+ + total_word_insertions
707
+ )
708
+
709
+ char_errors = (
710
+ total_char_substitutions
711
+ + total_char_deletions
712
+ + total_char_insertions
713
+ )
714
+
715
+ wer = (
716
+ word_errors / total_reference_words
717
+ if total_reference_words
718
+ else 0.0
719
+ )
720
+
721
+ cer = (
722
+ char_errors / total_reference_chars
723
+ if total_reference_chars
724
+ else 0.0
725
+ )
726
+
727
+ return {
728
+ "samples": len(samples),
729
+ "ctc_special_or_empty_outputs": special_or_empty_outputs,
730
+ "ctc_checked_outputs": checked_outputs,
731
+ "ctc_special_or_empty_ratio": special_ratio,
732
+ "wer": wer,
733
+ "wer_percent": wer * 100.0,
734
+ "word_errors": word_errors,
735
+ "total_reference_words": total_reference_words,
736
+ "total_predicted_words": total_predicted_words,
737
+ "word_substitutions": total_word_substitutions,
738
+ "word_deletions": total_word_deletions,
739
+ "word_insertions": total_word_insertions,
740
+ "cer": cer,
741
+ "cer_percent": cer * 100.0,
742
+ "char_errors": char_errors,
743
+ "total_reference_characters": total_reference_chars,
744
+ "total_predicted_characters": total_predicted_chars,
745
+ "char_substitutions": total_char_substitutions,
746
+ "char_deletions": total_char_deletions,
747
+ "char_insertions": total_char_insertions,
748
+ }
749
+
750
+
751
+ ###############################################################################
752
+ # PRE-TRAIN CTC HEALTH CHECK
753
+ ###############################################################################
754
+
755
+ def run_pretrain_ctc_health_check(model, batch_size: int) -> None:
756
+ """
757
+ Refuse to begin training unless the clean base model can successfully
758
+ decode BOTH full validation manifests through the exact same CTC path
759
+ used after every epoch.
760
+ """
761
+
762
+ print("\n======================================")
763
+ print("PRE-TRAIN CTC HEALTH CHECK")
764
+ print("======================================")
765
+ print("No training has happened yet.")
766
+ print("Kirtan and Sehaj must both decode successfully before trainer.fit().")
767
+
768
+ print("\nPre-train KIRTAN CTC validation...")
769
+ kirtan = score_validation_manifest(
770
+ model=model,
771
+ manifest_path=KIRTAN_VAL_MANIFEST,
772
+ batch_size=batch_size,
773
+ )
774
+
775
+ print("\nPre-train SEHAJ PAATH CTC validation...")
776
+ sehaj = score_validation_manifest(
777
+ model=model,
778
+ manifest_path=SEHAJ_VAL_MANIFEST,
779
+ batch_size=batch_size,
780
+ )
781
+
782
+ print("\nPRE-TRAIN CTC HEALTH CHECK PASSED")
783
+ print(
784
+ f"Kirtan WER: {kirtan['wer']:.6f} "
785
+ f"({kirtan['wer_percent']:.3f}%)"
786
+ )
787
+ print(
788
+ f"Kirtan CTC special/empty: "
789
+ f"{kirtan['ctc_special_or_empty_outputs']}/"
790
+ f"{kirtan['ctc_checked_outputs']}"
791
+ )
792
+ print(
793
+ f"Sehaj WER: {sehaj['wer']:.6f} "
794
+ f"({sehaj['wer_percent']:.3f}%)"
795
+ )
796
+ print(
797
+ f"Sehaj CTC special/empty: "
798
+ f"{sehaj['ctc_special_or_empty_outputs']}/"
799
+ f"{sehaj['ctc_checked_outputs']}"
800
+ )
801
+ print("✓ Safe to begin training")
802
+
803
+
804
+ ###############################################################################
805
+ # CLOUDFLARE R2 HELPERS
806
+ ###############################################################################
807
+
808
+ def get_r2_config():
809
+ """Read and validate Cloudflare R2 connection settings."""
810
+ account_id = os.environ.get("R2_ACCOUNT_ID")
811
+ access_key_id = os.environ.get("R2_ACCESS_KEY_ID")
812
+ secret_access_key = os.environ.get("R2_SECRET_ACCESS_KEY")
813
+ bucket = os.environ.get("R2_BUCKET")
814
+
815
+ missing = [
816
+ name
817
+ for name, value in (
818
+ ("R2_ACCOUNT_ID", account_id),
819
+ ("R2_ACCESS_KEY_ID", access_key_id),
820
+ ("R2_SECRET_ACCESS_KEY", secret_access_key),
821
+ ("R2_BUCKET", bucket),
822
+ )
823
+ if not value
824
+ ]
825
+
826
+ if missing:
827
+ raise RuntimeError(
828
+ "R2 upload is enabled but these environment variables are "
829
+ f"missing: {', '.join(missing)}"
830
+ )
831
+
832
+ return {
833
+ "account_id": account_id,
834
+ "access_key_id": access_key_id,
835
+ "secret_access_key": secret_access_key,
836
+ "bucket": bucket,
837
+ "endpoint_url": (
838
+ f"https://{account_id}.r2.cloudflarestorage.com"
839
+ ),
840
+ }
841
+
842
+
843
+ def upload_best_checkpoint_to_r2(checkpoint_path: Path) -> None:
844
+ """Upload the completed local best.ckpt to Cloudflare R2."""
845
+ if not R2_UPLOAD_ENABLED:
846
+ return
847
+
848
+ checkpoint_path = Path(checkpoint_path)
849
+
850
+ if not checkpoint_path.is_file():
851
+ raise FileNotFoundError(
852
+ f"Cannot upload missing checkpoint: {checkpoint_path}"
853
+ )
854
+
855
+ try:
856
+ import boto3
857
+ except ImportError as exc:
858
+ raise RuntimeError(
859
+ "R2 upload requires boto3. Install it with: pip install boto3"
860
+ ) from exc
861
+
862
+ config = get_r2_config()
863
+
864
+ client = boto3.client(
865
+ "s3",
866
+ endpoint_url=config["endpoint_url"],
867
+ aws_access_key_id=config["access_key_id"],
868
+ aws_secret_access_key=config["secret_access_key"],
869
+ region_name="auto",
870
+ )
871
+
872
+ last_error = None
873
+
874
+ for attempt in range(1, R2_UPLOAD_RETRIES + 1):
875
+ try:
876
+ print(
877
+ f"Uploading best checkpoint to R2 "
878
+ f"(attempt {attempt}/{R2_UPLOAD_RETRIES})..."
879
+ )
880
+
881
+ client.upload_file(
882
+ str(checkpoint_path),
883
+ config["bucket"],
884
+ R2_OBJECT_KEY,
885
+ )
886
+
887
+ print(
888
+ "✓ R2 upload complete: "
889
+ f"r2://{config['bucket']}/{R2_OBJECT_KEY}"
890
+ )
891
+ return
892
+
893
+ except Exception as exc:
894
+ last_error = exc
895
+ print(
896
+ f"R2 upload attempt {attempt} failed: {exc}"
897
+ )
898
+
899
+ if attempt < R2_UPLOAD_RETRIES:
900
+ time.sleep(R2_RETRY_DELAY_SECONDS)
901
+
902
+ raise RuntimeError(
903
+ "best.ckpt was saved locally, but R2 upload failed after "
904
+ f"{R2_UPLOAD_RETRIES} attempts."
905
+ ) from last_error
906
+
907
+
908
+ ###############################################################################
909
+ # VAST.AI AUTO-DESTROY HELPERS
910
+ ###############################################################################
911
+
912
+ def get_vast_instance_id():
913
+ """
914
+ Return the current Vast instance ID.
915
+
916
+ Vast may expose CONTAINER_ID directly. Older/current environments may
917
+ instead expose VAST_CONTAINERLABEL in the form C.123456.
918
+ """
919
+ container_id = os.environ.get("CONTAINER_ID")
920
+
921
+ if container_id:
922
+ value = str(container_id).strip()
923
+ if value.isdigit():
924
+ return value
925
+
926
+ label = os.environ.get("VAST_CONTAINERLABEL")
927
+
928
+ if label:
929
+ value = str(label).strip()
930
+
931
+ if value.startswith("C."):
932
+ value = value[2:]
933
+
934
+ if value.isdigit():
935
+ return value
936
+
937
+ return None
938
+
939
+
940
+ def validate_vast_auto_destroy_config(test_mode: bool) -> None:
941
+ """
942
+ Fail before a FULL training run if auto-destroy cannot be attempted.
943
+
944
+ Test mode deliberately skips this because --test never destroys.
945
+ """
946
+ if test_mode or not AUTO_DESTROY_VAST:
947
+ return
948
+
949
+ if shutil.which("vastai") is None:
950
+ raise RuntimeError(
951
+ "AUTO_DESTROY_VAST is enabled, but the Vast CLI is not installed. "
952
+ "Install it before the full run with: pip install vastai"
953
+ )
954
+
955
+ instance_id = get_vast_instance_id()
956
+
957
+ if instance_id is None:
958
+ raise RuntimeError(
959
+ "AUTO_DESTROY_VAST is enabled, but the current Vast instance ID "
960
+ "could not be determined from CONTAINER_ID or VAST_CONTAINERLABEL."
961
+ )
962
+
963
+
964
+ def destroy_current_vast_instance() -> None:
965
+ """
966
+ Permanently destroy this Vast instance.
967
+
968
+ This is intentionally called only at the very end of a successful FULL
969
+ run and only after best.ckpt has already been uploaded successfully to R2.
970
+ """
971
+ if not AUTO_DESTROY_VAST:
972
+ print("\nVast auto-destroy is disabled.")
973
+ return
974
+
975
+ instance_id = get_vast_instance_id()
976
+
977
+ if instance_id is None:
978
+ raise RuntimeError(
979
+ "Cannot auto-destroy Vast instance: instance ID is unavailable."
980
+ )
981
+
982
+ command = [
983
+ "vastai",
984
+ "destroy",
985
+ "instance",
986
+ instance_id,
987
+ "-y", # non-interactive confirmation
988
+ ]
989
+
990
+ # Vast images may expose a per-instance API key. If it is present,
991
+ # pass it explicitly. Otherwise the Vast CLI uses its configured key.
992
+ container_api_key = os.environ.get("CONTAINER_API_KEY")
993
+
994
+ if container_api_key:
995
+ command.extend(
996
+ [
997
+ "--api-key",
998
+ container_api_key,
999
+ ]
1000
+ )
1001
+
1002
+ print(
1003
+ "\n======================================"
1004
+ )
1005
+ print(
1006
+ "AUTO-DESTROYING VAST INSTANCE"
1007
+ )
1008
+ print(
1009
+ "======================================"
1010
+ )
1011
+ print(
1012
+ f"Instance ID: {instance_id}"
1013
+ )
1014
+ print(
1015
+ "best.ckpt has already been uploaded successfully to R2."
1016
+ )
1017
+ print(
1018
+ "This instance and its local files will now be permanently destroyed."
1019
+ )
1020
+
1021
+ # Make sure the final messages are visible before the container disappears.
1022
+ import sys
1023
+ sys.stdout.flush()
1024
+ sys.stderr.flush()
1025
+
1026
+ try:
1027
+ result = subprocess.run(
1028
+ command,
1029
+ check=False,
1030
+ text=True,
1031
+ capture_output=True,
1032
+ timeout=60,
1033
+ )
1034
+ except Exception as exc:
1035
+ raise RuntimeError(
1036
+ f"Failed to execute Vast destroy command: {exc}"
1037
+ ) from exc
1038
+
1039
+ if result.stdout:
1040
+ print(result.stdout.strip())
1041
+
1042
+ if result.returncode != 0:
1043
+ if result.stderr:
1044
+ print(result.stderr.strip())
1045
+
1046
+ raise RuntimeError(
1047
+ "Vast auto-destroy command failed. "
1048
+ "The instance was NOT intentionally destroyed by this script."
1049
+ )
1050
+
1051
+ print(
1052
+ f"✓ Vast destroy request accepted for instance {instance_id}"
1053
+ )
1054
+
1055
+
1056
+
1057
+ ###############################################################################
1058
+ # DURING-TRAINING CTC HEALTH PROBE
1059
+ ###############################################################################
1060
+
1061
+ class CTCHealthProbe(Callback):
1062
+ """Run a fixed CTC probe and overwrite one last-known-good checkpoint."""
1063
+
1064
+ def __init__(
1065
+ self,
1066
+ manifest_path: Path,
1067
+ stable_checkpoint_path: Path,
1068
+ every_optimizer_steps: int = 500,
1069
+ save_every_optimizer_steps: int = 2000,
1070
+ sample_count: int = 4,
1071
+ ):
1072
+ super().__init__()
1073
+ self.manifest_path = Path(manifest_path)
1074
+ self.stable_checkpoint_path = Path(stable_checkpoint_path)
1075
+ self.every_optimizer_steps = int(every_optimizer_steps)
1076
+ self.save_every_optimizer_steps = int(save_every_optimizer_steps)
1077
+ self.sample_count = int(sample_count)
1078
+ self.probe_samples = None
1079
+ self.last_probed_global_step = -1
1080
+
1081
+ if self.every_optimizer_steps <= 0:
1082
+ raise ValueError("CTC probe interval must be > 0")
1083
+ if self.save_every_optimizer_steps <= 0:
1084
+ raise ValueError("Stable checkpoint interval must be > 0")
1085
+ if self.save_every_optimizer_steps % self.every_optimizer_steps != 0:
1086
+ raise ValueError(
1087
+ "Stable checkpoint interval must be a multiple of the CTC probe interval."
1088
+ )
1089
+ if self.sample_count <= 0:
1090
+ raise ValueError("CTC probe sample_count must be > 0")
1091
+
1092
+ def setup(self, trainer, pl_module, stage=None):
1093
+ samples = load_validation_manifest(self.manifest_path)
1094
+ if len(samples) < self.sample_count:
1095
+ raise RuntimeError(
1096
+ f"CTC probe requested {self.sample_count} samples but only "
1097
+ f"{len(samples)} are available."
1098
+ )
1099
+
1100
+ self.probe_samples = samples[:self.sample_count]
1101
+
1102
+ print("\n======================================")
1103
+ print("CTC DURING-TRAINING PROBE ENABLED")
1104
+ print("======================================")
1105
+ print(f"Probe interval: every {self.every_optimizer_steps} optimizer steps")
1106
+ print(
1107
+ f"Stable checkpoint interval: every "
1108
+ f"{self.save_every_optimizer_steps} optimizer steps, after a healthy probe"
1109
+ )
1110
+ print(f"Fixed probe samples: {self.sample_count}")
1111
+ print(f"Rolling stable checkpoint: {self.stable_checkpoint_path}")
1112
+ for i, sample in enumerate(self.probe_samples, 1):
1113
+ print(f" Probe {i}: {sample['audio_filepath']}")
1114
+
1115
+ def _run_probe(
1116
+ self,
1117
+ trainer,
1118
+ pl_module,
1119
+ global_step: int,
1120
+ ):
1121
+ if not self.probe_samples:
1122
+ raise RuntimeError(
1123
+ "CTC probe samples were not initialized."
1124
+ )
1125
+
1126
+ if not hasattr(pl_module, "cur_decoder"):
1127
+ raise RuntimeError(
1128
+ "CTC probe expected model.cur_decoder."
1129
+ )
1130
+
1131
+ was_training = pl_module.training
1132
+ previous_decoder = getattr(
1133
+ pl_module,
1134
+ "cur_decoder",
1135
+ None,
1136
+ )
1137
+
1138
+ audio_paths = [
1139
+ sample["audio_filepath"]
1140
+ for sample in self.probe_samples
1141
+ ]
1142
+
1143
+ references = [
1144
+ sample["text"]
1145
+ for sample in self.probe_samples
1146
+ ]
1147
+
1148
+ # Keep the training model on CUDA. gpu_safe_transcribe() moves only
1149
+ # transcription-batch tensors to the model device before NeMo forward.
1150
+ pl_module.eval()
1151
+ pl_module.cur_decoder = VALIDATION_DECODER
1152
+
1153
+ try:
1154
+ with torch.no_grad():
1155
+ outputs = gpu_safe_transcribe(
1156
+ model=pl_module,
1157
+ audio_paths=audio_paths,
1158
+ batch_size=len(audio_paths),
1159
+ verbose=False,
1160
+ )
1161
+
1162
+ hypotheses = select_primary_transcriptions(
1163
+ outputs,
1164
+ expected_count=len(audio_paths),
1165
+ )
1166
+
1167
+ normalized = [
1168
+ " ".join(str(value).strip().split())
1169
+ for value in hypotheses
1170
+ ]
1171
+
1172
+ finally:
1173
+ pl_module.cur_decoder = previous_decoder
1174
+
1175
+ if was_training:
1176
+ pl_module.train()
1177
+ else:
1178
+ pl_module.eval()
1179
+
1180
+ special_values = {"<unk>", "<blank>", ""}
1181
+ special_count = sum(
1182
+ value in special_values
1183
+ for value in normalized
1184
+ )
1185
+
1186
+ epoch_number = trainer.current_epoch + 1
1187
+
1188
+ print("\n======================================")
1189
+ print(
1190
+ f"EPOCH {epoch_number} - "
1191
+ f"CTC PROBE @ OPTIMIZER STEP {global_step}"
1192
+ )
1193
+ print("======================================")
1194
+ print(f"CTC probe device: {next(pl_module.parameters()).device}")
1195
+
1196
+ for i, (reference, hypothesis) in enumerate(
1197
+ zip(references, normalized),
1198
+ 1,
1199
+ ):
1200
+ print(f" [{i}] REF : {reference}")
1201
+ print(f" [{i}] PRED: {hypothesis}")
1202
+
1203
+ print(
1204
+ f"CTC probe special/empty: "
1205
+ f"{special_count}/{len(normalized)}"
1206
+ )
1207
+
1208
+ if normalized and special_count == len(normalized):
1209
+ raise RuntimeError(
1210
+ "CTC TRAINING COLLAPSE DETECTED at optimizer step "
1211
+ f"{global_step}: all {len(normalized)} fixed probe "
1212
+ f"hypotheses were <unk>/<blank>/empty: {normalized}."
1213
+ )
1214
+
1215
+ print(
1216
+ f"CTC probe HEALTHY at optimizer step {global_step}"
1217
+ )
1218
+
1219
+ if global_step % self.save_every_optimizer_steps != 0:
1220
+ print(
1221
+ f"No checkpoint save at step {global_step}; "
1222
+ f"next stable save is on a multiple of "
1223
+ f"{self.save_every_optimizer_steps} optimizer steps."
1224
+ )
1225
+ return
1226
+
1227
+ self.stable_checkpoint_path.parent.mkdir(
1228
+ parents=True,
1229
+ exist_ok=True,
1230
+ )
1231
+
1232
+ temp_path = self.stable_checkpoint_path.with_suffix(
1233
+ self.stable_checkpoint_path.suffix + ".tmp"
1234
+ )
1235
+
1236
+ trainer.save_checkpoint(str(temp_path))
1237
+ os.replace(temp_path, self.stable_checkpoint_path)
1238
+
1239
+ print(
1240
+ f"✓ Updated last stable checkpoint at optimizer step "
1241
+ f"{global_step}: {self.stable_checkpoint_path}"
1242
+ )
1243
+
1244
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
1245
+ global_step = int(trainer.global_step)
1246
+
1247
+ if global_step <= 0:
1248
+ return
1249
+ if global_step % self.every_optimizer_steps != 0:
1250
+ return
1251
+ if global_step == self.last_probed_global_step:
1252
+ return
1253
+
1254
+ self.last_probed_global_step = global_step
1255
+ self._run_probe(trainer, pl_module, global_step)
1256
+
1257
+
1258
+ ###############################################################################
1259
+ # POST-EPOCH KIRTAN + SEHAJ WER/CER + BEST CHECKPOINT + EARLY STOPPING
1260
+ ###############################################################################
1261
+
1262
+ class DomainValidationAndEarlyStopping(Callback):
1263
+ """
1264
+ After every TRAINING epoch:
1265
+
1266
+ 1. Explicitly transcribe Kirtan validation data.
1267
+ 2. Explicitly transcribe Sehaj Paath validation data.
1268
+ 3. Save BOTH WER and CER to epoch_metrics.json.
1269
+ 4. Promote the epoch to best.ckpt if ANY of these improves by min_delta:
1270
+ - Kirtan CER
1271
+ - Kirtan WER
1272
+ - Sehaj WER
1273
+ 5. Kirtan CER remains a first-class selection metric: any new lower Kirtan
1274
+ CER always promotes the new epoch even if either WER is worse.
1275
+ 6. Keep independent best-ever baselines for all three metrics so a checkpoint
1276
+ selected for one metric never makes another metric's baseline worse.
1277
+ 7. Preserve callback state across Lightning resumes, and seed from the existing
1278
+ epoch_metrics.json when resuming from an older checkpoint that did not yet
1279
+ contain callback state.
1280
+ """
1281
+
1282
+ def __init__(
1283
+ self,
1284
+ metrics_path: Path,
1285
+ best_checkpoint_path: Path,
1286
+ kirtan_manifest: Path,
1287
+ sehaj_manifest: Path,
1288
+ batch_size: int,
1289
+ patience: int = 5,
1290
+ min_delta: float = 0.0001,
1291
+ ):
1292
+ super().__init__()
1293
+ self.metrics_path = Path(metrics_path)
1294
+ self.best_checkpoint_path = Path(best_checkpoint_path)
1295
+ self.kirtan_manifest = Path(kirtan_manifest)
1296
+ self.sehaj_manifest = Path(sehaj_manifest)
1297
+ self.batch_size = int(batch_size)
1298
+ self.patience = int(patience)
1299
+ self.min_delta = float(min_delta)
1300
+
1301
+ # Independent BEST-EVER baselines. Do not overwrite a metric just because
1302
+ # some other metric caused the current epoch to be selected.
1303
+ self.best_kirtan_cer = float("inf")
1304
+ self.best_kirtan_wer = float("inf")
1305
+ self.best_sehaj_wer = float("inf")
1306
+
1307
+ # Metrics belonging specifically to the checkpoint currently stored as best.ckpt.
1308
+ self.selected_kirtan_cer = float("inf")
1309
+ self.selected_kirtan_wer = float("inf")
1310
+ self.selected_sehaj_wer = float("inf")
1311
+
1312
+ self.best_epoch = None
1313
+ self.bad_epochs = 0
1314
+ self.history = []
1315
+ self.r2_best_uploaded = False
1316
+
1317
+ # This matters for the FIRST restart with the newly updated callback:
1318
+ # On a restart, seed metric baselines/history from the existing JSON before
1319
+ # trainer.fit(). The rolling [202,100] checkpoint also carries state_dict()
1320
+ # below, so Lightning will restore the authoritative callback state.
1321
+ self._seed_from_existing_metrics_json()
1322
+
1323
+ @staticmethod
1324
+ def _finite_or_inf(value):
1325
+ if value is None:
1326
+ return float("inf")
1327
+ try:
1328
+ return float(value)
1329
+ except (TypeError, ValueError):
1330
+ return float("inf")
1331
+
1332
+ def _seed_from_existing_metrics_json(self):
1333
+ if not self.metrics_path.is_file():
1334
+ return
1335
+
1336
+ try:
1337
+ with self.metrics_path.open("r", encoding="utf-8") as handle:
1338
+ data = json.load(handle)
1339
+ except Exception as exc:
1340
+ print(
1341
+ f"WARNING: could not seed validation callback from "
1342
+ f"{self.metrics_path}: {exc}"
1343
+ )
1344
+ return
1345
+
1346
+ history = data.get("history")
1347
+ if not isinstance(history, list):
1348
+ history = []
1349
+
1350
+ self.history = history
1351
+
1352
+ # Derive independent best-ever metric values from complete epoch records.
1353
+ kirtan_cers = []
1354
+ kirtan_wers = []
1355
+ sehaj_wers = []
1356
+ for record in history:
1357
+ try:
1358
+ kirtan = record.get("kirtan", {})
1359
+ sehaj = record.get("sehaj", {})
1360
+ if kirtan.get("cer") is not None:
1361
+ kirtan_cers.append(float(kirtan["cer"]))
1362
+ if kirtan.get("wer") is not None:
1363
+ kirtan_wers.append(float(kirtan["wer"]))
1364
+ if sehaj.get("wer") is not None:
1365
+ sehaj_wers.append(float(sehaj["wer"]))
1366
+ except (TypeError, ValueError, AttributeError):
1367
+ continue
1368
+
1369
+ if kirtan_cers:
1370
+ self.best_kirtan_cer = min(kirtan_cers)
1371
+ else:
1372
+ self.best_kirtan_cer = self._finite_or_inf(data.get("best_kirtan_cer"))
1373
+
1374
+ if kirtan_wers:
1375
+ self.best_kirtan_wer = min(kirtan_wers)
1376
+ else:
1377
+ self.best_kirtan_wer = self._finite_or_inf(data.get("best_kirtan_wer"))
1378
+
1379
+ if sehaj_wers:
1380
+ self.best_sehaj_wer = min(sehaj_wers)
1381
+ else:
1382
+ self.best_sehaj_wer = self._finite_or_inf(data.get("best_sehaj_wer"))
1383
+
1384
+ self.best_epoch = data.get("best_epoch")
1385
+ self.bad_epochs = int(data.get("epochs_without_improvement", 0) or 0)
1386
+
1387
+ # Recover metrics for the checkpoint that was selected by the old logic,
1388
+ # when that epoch is present in history.
1389
+ for record in reversed(history):
1390
+ if record.get("epoch") == self.best_epoch:
1391
+ kirtan = record.get("kirtan", {})
1392
+ sehaj = record.get("sehaj", {})
1393
+ self.selected_kirtan_cer = self._finite_or_inf(kirtan.get("cer"))
1394
+ self.selected_kirtan_wer = self._finite_or_inf(kirtan.get("wer"))
1395
+ self.selected_sehaj_wer = self._finite_or_inf(sehaj.get("wer"))
1396
+ break
1397
+
1398
+ print("\nRestored validation-selection history from existing metrics JSON:")
1399
+ print(self.metrics_path)
1400
+ print(f" best-ever Kirtan CER: {self.best_kirtan_cer}")
1401
+ print(f" best-ever Kirtan WER: {self.best_kirtan_wer}")
1402
+ print(f" best-ever Sehaj WER: {self.best_sehaj_wer}")
1403
+ print(f" selected best epoch: {self.best_epoch}")
1404
+ print(f" epochs without improvement: {self.bad_epochs}")
1405
+
1406
+ def state_dict(self):
1407
+ """Persist selection/early-stop state inside full Lightning checkpoints."""
1408
+ return {
1409
+ "best_kirtan_cer": self.best_kirtan_cer,
1410
+ "best_kirtan_wer": self.best_kirtan_wer,
1411
+ "best_sehaj_wer": self.best_sehaj_wer,
1412
+ "selected_kirtan_cer": self.selected_kirtan_cer,
1413
+ "selected_kirtan_wer": self.selected_kirtan_wer,
1414
+ "selected_sehaj_wer": self.selected_sehaj_wer,
1415
+ "best_epoch": self.best_epoch,
1416
+ "bad_epochs": self.bad_epochs,
1417
+ "history": self.history,
1418
+ "r2_best_uploaded": self.r2_best_uploaded,
1419
+ }
1420
+
1421
+ def load_state_dict(self, state_dict):
1422
+ """Restore selection/early-stop state on a true Lightning resume."""
1423
+ if not state_dict:
1424
+ return
1425
+
1426
+ self.best_kirtan_cer = self._finite_or_inf(
1427
+ state_dict.get("best_kirtan_cer", self.best_kirtan_cer)
1428
+ )
1429
+ self.best_kirtan_wer = self._finite_or_inf(
1430
+ state_dict.get("best_kirtan_wer", self.best_kirtan_wer)
1431
+ )
1432
+ self.best_sehaj_wer = self._finite_or_inf(
1433
+ state_dict.get("best_sehaj_wer", self.best_sehaj_wer)
1434
+ )
1435
+ self.selected_kirtan_cer = self._finite_or_inf(
1436
+ state_dict.get("selected_kirtan_cer", self.selected_kirtan_cer)
1437
+ )
1438
+ self.selected_kirtan_wer = self._finite_or_inf(
1439
+ state_dict.get("selected_kirtan_wer", self.selected_kirtan_wer)
1440
+ )
1441
+ self.selected_sehaj_wer = self._finite_or_inf(
1442
+ state_dict.get("selected_sehaj_wer", self.selected_sehaj_wer)
1443
+ )
1444
+ self.best_epoch = state_dict.get("best_epoch", self.best_epoch)
1445
+ self.bad_epochs = int(state_dict.get("bad_epochs", self.bad_epochs) or 0)
1446
+ restored_history = state_dict.get("history")
1447
+ if isinstance(restored_history, list):
1448
+ self.history = restored_history
1449
+ self.r2_best_uploaded = bool(
1450
+ state_dict.get("r2_best_uploaded", self.r2_best_uploaded)
1451
+ )
1452
+
1453
+ print("\n✓ Restored validation callback state from Lightning checkpoint")
1454
+ print(f" best-ever Kirtan CER: {self.best_kirtan_cer}")
1455
+ print(f" best-ever Kirtan WER: {self.best_kirtan_wer}")
1456
+ print(f" best-ever Sehaj WER: {self.best_sehaj_wer}")
1457
+ print(f" selected best epoch: {self.best_epoch}")
1458
+ print(f" epochs without improvement: {self.bad_epochs}")
1459
+
1460
+ def write_history(self):
1461
+ def optional(value):
1462
+ return None if value == float("inf") else value
1463
+
1464
+ best_kirtan_cer = optional(self.best_kirtan_cer)
1465
+ best_kirtan_wer = optional(self.best_kirtan_wer)
1466
+ best_sehaj_wer = optional(self.best_sehaj_wer)
1467
+ selected_kirtan_cer = optional(self.selected_kirtan_cer)
1468
+ selected_kirtan_wer = optional(self.selected_kirtan_wer)
1469
+ selected_sehaj_wer = optional(self.selected_sehaj_wer)
1470
+
1471
+ data = {
1472
+ "selection_metric": "any_improvement_kirtan_cer_or_kirtan_wer_or_sehaj_wer",
1473
+ "best_epoch": self.best_epoch,
1474
+ "best_kirtan_cer_percent": (
1475
+ None if best_kirtan_cer is None else best_kirtan_cer * 100.0
1476
+ ),
1477
+ "best_kirtan_wer_percent": (
1478
+ None if best_kirtan_wer is None else best_kirtan_wer * 100.0
1479
+ ),
1480
+ "best_sehaj_wer_percent": (
1481
+ None if best_sehaj_wer is None else best_sehaj_wer * 100.0
1482
+ ),
1483
+ "best_kirtan_cer": best_kirtan_cer,
1484
+ "best_kirtan_wer": best_kirtan_wer,
1485
+ "best_sehaj_wer": best_sehaj_wer,
1486
+ "selected_checkpoint_kirtan_cer": selected_kirtan_cer,
1487
+ "selected_checkpoint_kirtan_wer": selected_kirtan_wer,
1488
+ "selected_checkpoint_sehaj_wer": selected_sehaj_wer,
1489
+ "patience": self.patience,
1490
+ "min_metric_improvement": self.min_delta,
1491
+ "epochs_without_improvement": self.bad_epochs,
1492
+ "history": self.history,
1493
+ }
1494
+
1495
+ self.metrics_path.parent.mkdir(parents=True, exist_ok=True)
1496
+ temp_path = self.metrics_path.with_suffix(self.metrics_path.suffix + ".tmp")
1497
+ with temp_path.open("w", encoding="utf-8") as handle:
1498
+ json.dump(data, handle, indent=2, ensure_ascii=False)
1499
+ temp_path.replace(self.metrics_path)
1500
+
1501
+ def on_train_epoch_end(self, trainer, pl_module):
1502
+ epoch_number = trainer.current_epoch + 1
1503
+
1504
+ print("\n======================================")
1505
+ print("EXPLICIT DOMAIN VALIDATION")
1506
+ print("======================================")
1507
+ print("Scoring KIRTAN validation (CER + WER can promote best.ckpt)...")
1508
+
1509
+ kirtan = score_validation_manifest(
1510
+ model=pl_module,
1511
+ manifest_path=self.kirtan_manifest,
1512
+ batch_size=self.batch_size,
1513
+ )
1514
+
1515
+ print("Scoring SEHAJ PAATH validation (WER can promote best.ckpt)...")
1516
+ sehaj = score_validation_manifest(
1517
+ model=pl_module,
1518
+ manifest_path=self.sehaj_manifest,
1519
+ batch_size=self.batch_size,
1520
+ )
1521
+
1522
+ previous_best_kirtan_cer = self.best_kirtan_cer
1523
+ previous_best_kirtan_wer = self.best_kirtan_wer
1524
+ previous_best_sehaj_wer = self.best_sehaj_wer
1525
+
1526
+ kirtan_cer_improved = (
1527
+ kirtan["cer"] < previous_best_kirtan_cer - self.min_delta
1528
+ )
1529
+ kirtan_wer_improved = (
1530
+ kirtan["wer"] < previous_best_kirtan_wer - self.min_delta
1531
+ )
1532
+ sehaj_wer_improved = (
1533
+ sehaj["wer"] < previous_best_sehaj_wer - self.min_delta
1534
+ )
1535
+
1536
+ # Any one of the three metrics can promote this epoch.
1537
+ improved = (
1538
+ kirtan_cer_improved
1539
+ or kirtan_wer_improved
1540
+ or sehaj_wer_improved
1541
+ )
1542
+
1543
+ reasons = []
1544
+ if kirtan_cer_improved:
1545
+ reasons.append("kirtan_cer")
1546
+ if kirtan_wer_improved:
1547
+ reasons.append("kirtan_wer")
1548
+ if sehaj_wer_improved:
1549
+ reasons.append("sehaj_wer")
1550
+ improvement_reason = "+".join(reasons) if reasons else None
1551
+
1552
+ # Update each best-ever baseline independently.
1553
+ if kirtan_cer_improved:
1554
+ self.best_kirtan_cer = kirtan["cer"]
1555
+ if kirtan_wer_improved:
1556
+ self.best_kirtan_wer = kirtan["wer"]
1557
+ if sehaj_wer_improved:
1558
+ self.best_sehaj_wer = sehaj["wer"]
1559
+
1560
+ if improved:
1561
+ self.best_epoch = epoch_number
1562
+ self.bad_epochs = 0
1563
+
1564
+ # Record the actual metrics of the checkpoint being promoted now.
1565
+ self.selected_kirtan_cer = kirtan["cer"]
1566
+ self.selected_kirtan_wer = kirtan["wer"]
1567
+ self.selected_sehaj_wer = sehaj["wer"]
1568
+
1569
+ self.best_checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
1570
+ pl_module.train()
1571
+ trainer.save_checkpoint(str(self.best_checkpoint_path))
1572
+ upload_best_checkpoint_to_r2(self.best_checkpoint_path)
1573
+
1574
+ if R2_UPLOAD_ENABLED:
1575
+ self.r2_best_uploaded = True
1576
+ else:
1577
+ print("R2 upload skipped: offline test mode.")
1578
+
1579
+ print("\nNEW BEST CHECKPOINT — ACCEPTED METRIC IMPROVEMENT")
1580
+ print(f"Epoch: {epoch_number}")
1581
+ print(
1582
+ f"Kirtan CER: {kirtan['cer']:.6f} "
1583
+ f"({kirtan['cer_percent']:.3f}%)"
1584
+ )
1585
+ print(
1586
+ f"Kirtan WER: {kirtan['wer']:.6f} "
1587
+ f"({kirtan['wer_percent']:.3f}%)"
1588
+ )
1589
+ print(
1590
+ f"Sehaj WER: {sehaj['wer']:.6f} "
1591
+ f"({sehaj['wer_percent']:.3f}%)"
1592
+ )
1593
+ print(f"Selection reason: {improvement_reason}")
1594
+ print("Saved best checkpoint:")
1595
+ print(self.best_checkpoint_path)
1596
+ else:
1597
+ self.bad_epochs += 1
1598
+ print("\nNo Kirtan CER / Kirtan WER / Sehaj WER improvement.")
1599
+ print(
1600
+ f"Current Kirtan CER: {kirtan['cer']:.6f} "
1601
+ f"({kirtan['cer_percent']:.3f}%)"
1602
+ )
1603
+ print(
1604
+ f"Best-ever Kirtan CER: {self.best_kirtan_cer:.6f} "
1605
+ f"({self.best_kirtan_cer * 100:.3f}%)"
1606
+ )
1607
+ print(
1608
+ f"Current Kirtan WER: {kirtan['wer']:.6f} "
1609
+ f"({kirtan['wer_percent']:.3f}%)"
1610
+ )
1611
+ print(
1612
+ f"Best-ever Kirtan WER: {self.best_kirtan_wer:.6f} "
1613
+ f"({self.best_kirtan_wer * 100:.3f}%)"
1614
+ )
1615
+ print(
1616
+ f"Current Sehaj WER: {sehaj['wer']:.6f} "
1617
+ f"({sehaj['wer_percent']:.3f}%)"
1618
+ )
1619
+ print(
1620
+ f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} "
1621
+ f"({self.best_sehaj_wer * 100:.3f}%)"
1622
+ )
1623
+ print(
1624
+ f"Epochs without improvement: {self.bad_epochs}/{self.patience}"
1625
+ )
1626
+
1627
+ epoch_record = {
1628
+ "epoch": epoch_number,
1629
+ "kirtan": kirtan,
1630
+ "sehaj": sehaj,
1631
+ "selection_metric": "any_improvement_kirtan_cer_or_kirtan_wer_or_sehaj_wer",
1632
+ "improved": improved,
1633
+ "improvement_reason": improvement_reason,
1634
+ "kirtan_cer_improved": kirtan_cer_improved,
1635
+ "kirtan_wer_improved": kirtan_wer_improved,
1636
+ "sehaj_wer_improved": sehaj_wer_improved,
1637
+ "best_epoch": self.best_epoch,
1638
+ "best_kirtan_cer": self.best_kirtan_cer,
1639
+ "best_kirtan_cer_percent": self.best_kirtan_cer * 100.0,
1640
+ "best_kirtan_wer": self.best_kirtan_wer,
1641
+ "best_kirtan_wer_percent": self.best_kirtan_wer * 100.0,
1642
+ "best_sehaj_wer": self.best_sehaj_wer,
1643
+ "best_sehaj_wer_percent": self.best_sehaj_wer * 100.0,
1644
+ "selected_checkpoint_kirtan_cer": self.selected_kirtan_cer,
1645
+ "selected_checkpoint_kirtan_wer": self.selected_kirtan_wer,
1646
+ "selected_checkpoint_sehaj_wer": self.selected_sehaj_wer,
1647
+ "epochs_without_improvement": self.bad_epochs,
1648
+ }
1649
+
1650
+ self.history.append(epoch_record)
1651
+ self.write_history()
1652
+
1653
+ print("\n--------------------------------------")
1654
+ print(
1655
+ f"Epoch {epoch_number} KIRTAN: "
1656
+ f"CER {kirtan['cer_percent']:.3f}% | "
1657
+ f"WER {kirtan['wer_percent']:.3f}%"
1658
+ )
1659
+ print(
1660
+ f"Epoch {epoch_number} SEHAJ: "
1661
+ f"WER {sehaj['wer_percent']:.3f}% | "
1662
+ f"CER {sehaj['cer_percent']:.3f}%"
1663
+ )
1664
+ print(
1665
+ "Checkpoint / early-stop rule: promote when ANY improves — "
1666
+ "Kirtan CER OR Kirtan WER OR Sehaj WER."
1667
+ )
1668
+ print(f"Minimum required improvement: {self.min_delta}")
1669
+ print(f"Metrics JSON: {self.metrics_path}")
1670
+ print("--------------------------------------")
1671
+
1672
+ if self.bad_epochs >= self.patience:
1673
+ print("\n########################################")
1674
+ print("EARLY STOPPING: NO ACCEPTED METRIC IMPROVEMENT")
1675
+ print("########################################")
1676
+ print(
1677
+ f"No Kirtan CER / Kirtan WER / Sehaj WER improvement for "
1678
+ f"{self.bad_epochs} epochs."
1679
+ )
1680
+ print(f"Selected best epoch: {self.best_epoch}")
1681
+ print(
1682
+ f"Best-ever Kirtan CER: {self.best_kirtan_cer:.6f} "
1683
+ f"({self.best_kirtan_cer * 100:.3f}%)"
1684
+ )
1685
+ print(
1686
+ f"Best-ever Kirtan WER: {self.best_kirtan_wer:.6f} "
1687
+ f"({self.best_kirtan_wer * 100:.3f}%)"
1688
+ )
1689
+ print(
1690
+ f"Best-ever Sehaj WER: {self.best_sehaj_wer:.6f} "
1691
+ f"({self.best_sehaj_wer * 100:.3f}%)"
1692
+ )
1693
+ trainer.should_stop = True
1694
+
1695
+
1696
+ ###############################################################################
1697
+ # POST-EPOCH: KEEP LAST TWO EPOCH CHECKPOINTS
1698
+ ###############################################################################
1699
+
1700
+ class LastTwoEpochCheckpoints(Callback):
1701
+ """
1702
+ Save one checkpoint after every completed training epoch.
1703
+
1704
+ Keep only the latest two:
1705
+
1706
+ epoch_004.ckpt
1707
+ epoch_005.ckpt
1708
+
1709
+ When epoch 6 finishes:
1710
+
1711
+ epoch_004.ckpt -> deleted
1712
+ epoch_005.ckpt -> kept
1713
+ epoch_006.ckpt -> saved
1714
+
1715
+ best.ckpt is NOT deleted by this callback.
1716
+ """
1717
+
1718
+ def __init__(
1719
+ self,
1720
+ dirpath: Path,
1721
+ ):
1722
+ super().__init__()
1723
+
1724
+ self.dirpath = Path(
1725
+ dirpath
1726
+ )
1727
+
1728
+ def on_train_epoch_end(
1729
+ self,
1730
+ trainer,
1731
+ pl_module,
1732
+ ):
1733
+
1734
+ self.dirpath.mkdir(
1735
+ parents=True,
1736
+ exist_ok=True,
1737
+ )
1738
+
1739
+ epoch_number = (
1740
+ trainer.current_epoch + 1
1741
+ )
1742
+
1743
+ checkpoint_path = (
1744
+ self.dirpath
1745
+ / f"epoch_{epoch_number:03d}.ckpt"
1746
+ )
1747
+
1748
+ trainer.save_checkpoint(
1749
+ str(checkpoint_path)
1750
+ )
1751
+
1752
+ print(
1753
+ "\nSaved epoch checkpoint:"
1754
+ )
1755
+
1756
+ print(
1757
+ checkpoint_path
1758
+ )
1759
+
1760
+ # Only look at epoch_XXX.ckpt files.
1761
+ # best.ckpt will therefore never be removed.
1762
+ checkpoints = sorted(
1763
+ self.dirpath.glob(
1764
+ "epoch_*.ckpt"
1765
+ )
1766
+ )
1767
+
1768
+ while len(checkpoints) > 2:
1769
+
1770
+ oldest_checkpoint = (
1771
+ checkpoints.pop(0)
1772
+ )
1773
+
1774
+ try:
1775
+ oldest_checkpoint.unlink()
1776
+
1777
+ print(
1778
+ "Removed old epoch checkpoint:"
1779
+ )
1780
+
1781
+ print(
1782
+ oldest_checkpoint
1783
+ )
1784
+
1785
+ except FileNotFoundError:
1786
+ pass
1787
+
1788
+
1789
+ ###############################################################################
1790
+ # DATASET CONFIGURATION
1791
+ ###############################################################################
1792
+
1793
+ def make_dataset_config(
1794
+ manifest_path: Path,
1795
+ shuffle: bool,
1796
+ ):
1797
+ """
1798
+ Build a fresh NeMo dataset configuration for Punjabi ('pa') fine-tuning
1799
+ of the multilingual Gurbani model.
1800
+
1801
+ Fresh train_ds and validation_ds configs are created here at fine-tuning
1802
+ time. The manifests provide lang='pa' and NeMo is asked to return the
1803
+ language ID so the multilingual model uses the Punjabi path.
1804
+ """
1805
+
1806
+ return OmegaConf.create({
1807
+ "manifest_filepath": [
1808
+ str(manifest_path)
1809
+ ],
1810
+ "sample_rate": EXPECTED_SAMPLE_RATE,
1811
+ "batch_size": BATCH_SIZE,
1812
+ "shuffle": shuffle,
1813
+ "num_workers": 2,
1814
+ "pin_memory": False,
1815
+ "persistent_workers": False,
1816
+ "max_duration": None,
1817
+ "min_duration": 0.0,
1818
+ "is_tarred": False,
1819
+ "tarred_audio_filepaths": None,
1820
+ "use_start_end_token": False,
1821
+
1822
+ # IMPORTANT: this is a multilingual model. The manifests contain
1823
+ # lang="pa", and the dataset must return the language ID.
1824
+ "return_language_id": True,
1825
+ })
1826
+
1827
+
1828
+
1829
+ ###############################################################################
1830
+ # PATH VALIDATION
1831
+ ###############################################################################
1832
+
1833
+ def validate_paths() -> None:
1834
+
1835
+ if not DATA_ROOT.exists():
1836
+ raise FileNotFoundError(
1837
+ f"DATA_ROOT does not exist: "
1838
+ f"{DATA_ROOT}"
1839
+ )
1840
+
1841
+ if not DATA_ROOT.is_dir():
1842
+ raise ValueError(
1843
+ f"DATA_ROOT is not a directory: "
1844
+ f"{DATA_ROOT}"
1845
+ )
1846
+
1847
+ if not TRAIN_MANIFEST.exists():
1848
+ raise FileNotFoundError(
1849
+ "Training manifest not found: "
1850
+ f"{TRAIN_MANIFEST}"
1851
+ )
1852
+
1853
+ if not KIRTAN_VAL_MANIFEST.exists():
1854
+ raise FileNotFoundError(
1855
+ "Kirtan validation manifest not found: "
1856
+ f"{KIRTAN_VAL_MANIFEST}"
1857
+ )
1858
+
1859
+ if not SEHAJ_VAL_MANIFEST.exists():
1860
+ raise FileNotFoundError(
1861
+ "Sehaj validation manifest not found: "
1862
+ f"{SEHAJ_VAL_MANIFEST}"
1863
+ )
1864
+
1865
+ if not MODEL_PATH.exists():
1866
+ raise FileNotFoundError(
1867
+ "NeMo model not found: "
1868
+ f"{MODEL_PATH}"
1869
+ )
1870
+
1871
+ # A brand-new run starts from MODEL_PATH. A restarted [202,100] run resumes
1872
+ # from its own rolling stable checkpoint and does not need another checkpoint.
1873
+ if not LAST_STABLE_CHECKPOINT_PATH.exists():
1874
+ if (
1875
+ START_CHECKPOINT_PATH is not None
1876
+ and not START_CHECKPOINT_PATH.exists()
1877
+ ):
1878
+ raise FileNotFoundError(
1879
+ "Optional initialization checkpoint not found: "
1880
+ f"{START_CHECKPOINT_PATH}"
1881
+ )
1882
+
1883
+ if R2_UPLOAD_ENABLED:
1884
+ # Validate required R2 environment variables before long training starts.
1885
+ get_r2_config()
1886
+
1887
+
1888
+ ###############################################################################
1889
+ # LOAD STAGE-2 BEST CHECKPOINT WEIGHTS ONLY
1890
+ ###############################################################################
1891
+
1892
+ def load_start_checkpoint_weights(model) -> None:
1893
+ """Optionally load checkpoint model weights without optimizer state."""
1894
+
1895
+ if START_CHECKPOINT_PATH is None:
1896
+ print(
1897
+ "\nNo starting checkpoint configured. "
1898
+ "Using MODEL_PATH weights directly."
1899
+ )
1900
+ return
1901
+
1902
+ print("\n======================================")
1903
+ print("LOADING OPTIONAL START CHECKPOINT WEIGHTS")
1904
+ print("======================================")
1905
+ print(START_CHECKPOINT_PATH)
1906
+
1907
+ checkpoint = torch.load(
1908
+ str(START_CHECKPOINT_PATH),
1909
+ map_location="cpu",
1910
+ )
1911
+
1912
+ state_dict = checkpoint.get(
1913
+ "state_dict",
1914
+ checkpoint,
1915
+ )
1916
+
1917
+ result = model.load_state_dict(
1918
+ state_dict,
1919
+ strict=False,
1920
+ )
1921
+
1922
+ missing = list(result.missing_keys)
1923
+ unexpected = list(result.unexpected_keys)
1924
+
1925
+ print(f"Missing keys: {len(missing)}")
1926
+ print(f"Unexpected keys: {len(unexpected)}")
1927
+
1928
+ if missing:
1929
+ for key in missing[:30]:
1930
+ print(" MISSING:", key)
1931
+
1932
+ if unexpected:
1933
+ for key in unexpected[:30]:
1934
+ print(" UNEXPECTED:", key)
1935
+
1936
+ if missing or unexpected:
1937
+ raise RuntimeError(
1938
+ "Starting checkpoint does not cleanly match "
1939
+ "the restored .nemo model."
1940
+ )
1941
+
1942
+ print("✓ Starting checkpoint weights loaded cleanly")
1943
+ print("✓ Old optimizer state NOT restored")
1944
+ print("✓ Old scheduler state NOT restored")
1945
+
1946
+
1947
+ ###############################################################################
1948
+ # CACHE-AWARE ENCODER CONVERSION
1949
+ ###############################################################################
1950
+
1951
+ def rebuild_encoder_cache_aware(model, attention_context) -> None:
1952
+ """
1953
+ Rebuild the existing Conformer encoder for one cache-aware/chunked-limited
1954
+ attention context while preserving all learned encoder weights.
1955
+
1956
+ This helper rebuilds the encoder for the requested cache-aware context
1957
+ while preserving the learned encoder weights.
1958
+ """
1959
+
1960
+ attention_context = list(attention_context)
1961
+
1962
+ print("\n======================================")
1963
+ print("CACHE-AWARE ENCODER CONVERSION")
1964
+ print("======================================")
1965
+
1966
+ old_cfg = copy.deepcopy(model.cfg.encoder)
1967
+
1968
+ print("Original attention context:", old_cfg.get("att_context_size"))
1969
+ print("Original attention probabilities:", old_cfg.get("att_context_probs", None))
1970
+ print("Original attention style:", old_cfg.get("att_context_style", "regular"))
1971
+ print("Original convolution context:", old_cfg.get("conv_context_size", None))
1972
+
1973
+ old_state = copy.deepcopy(model.encoder.state_dict())
1974
+ new_cfg = copy.deepcopy(old_cfg)
1975
+
1976
+ with open_dict(new_cfg):
1977
+ new_cfg.att_context_size = attention_context
1978
+ new_cfg.att_context_probs = None
1979
+ new_cfg.att_context_style = "chunked_limited"
1980
+ new_cfg.conv_context_size = CAUSAL_CONV_CONTEXT
1981
+
1982
+ print("\nRebuilding encoder...")
1983
+ print("Attention context:", attention_context)
1984
+ print("Attention style: chunked_limited")
1985
+ print("Convolution context:", CAUSAL_CONV_CONTEXT)
1986
+
1987
+ new_encoder = instantiate(new_cfg)
1988
+ new_encoder.load_state_dict(old_state, strict=True)
1989
+
1990
+ model.encoder = new_encoder
1991
+
1992
+ with open_dict(model.cfg):
1993
+ model.cfg.encoder = new_cfg
1994
+
1995
+ print("✓ Existing encoder weights loaded strict=True")
1996
+ print(f"✓ Full-data streaming context: {attention_context}")
1997
+ print("✓ Causal convolution: [30,0]")
1998
+ print("======================================\n")
1999
+
2000
+
2001
+ ###############################################################################
2002
+ # MODEL INFORMATION
2003
+ ###############################################################################
2004
+
2005
+ def print_model_information(
2006
+ model,
2007
+ ) -> None:
2008
+
2009
+ total_parameters = sum(
2010
+ parameter.numel()
2011
+ for parameter
2012
+ in model.parameters()
2013
+ )
2014
+
2015
+ trainable_parameters = sum(
2016
+ parameter.numel()
2017
+ for parameter
2018
+ in model.parameters()
2019
+ if parameter.requires_grad
2020
+ )
2021
+
2022
+ frozen_parameters = (
2023
+ total_parameters
2024
+ - trainable_parameters
2025
+ )
2026
+
2027
+ print(
2028
+ "\n======================================"
2029
+ )
2030
+
2031
+ print(
2032
+ "MODEL INFORMATION"
2033
+ )
2034
+
2035
+ print(
2036
+ "======================================"
2037
+ )
2038
+
2039
+ print(
2040
+ f"Total parameters: "
2041
+ f"{total_parameters:,}"
2042
+ )
2043
+
2044
+ print(
2045
+ f"Trainable parameters: "
2046
+ f"{trainable_parameters:,}"
2047
+ )
2048
+
2049
+ print(
2050
+ f"Frozen parameters: "
2051
+ f"{frozen_parameters:,}"
2052
+ )
2053
+
2054
+ print(
2055
+ "======================================"
2056
+ )
2057
+
2058
+
2059
+ ###############################################################################
2060
+ # COMMAND LINE
2061
+ ###############################################################################
2062
+
2063
+ def parse_args():
2064
+ parser = argparse.ArgumentParser(
2065
+ description="Fine-tune the Gurbani/Punjabi NeMo ASR model."
2066
+ )
2067
+ parser.add_argument(
2068
+ "--test",
2069
+ action="store_true",
2070
+ help=(
2071
+ "Use the small *-test.json manifests for an infrastructure "
2072
+ "test run. Test artifacts are written under "
2073
+ "/workspace/asr_training_test."
2074
+ ),
2075
+ )
2076
+ parser.add_argument(
2077
+ "--offline",
2078
+ action="store_true",
2079
+ help=(
2080
+ "TEST MODE ONLY: disable all Cloudflare R2 validation/uploads. "
2081
+ "Use as: python train.py --test --offline"
2082
+ ),
2083
+ )
2084
+
2085
+ args = parser.parse_args()
2086
+
2087
+ if args.offline and not args.test:
2088
+ parser.error("--offline is only allowed together with --test")
2089
+
2090
+ return args
2091
+
2092
+
2093
+ ###############################################################################
2094
+ # MAIN
2095
+ ###############################################################################
2096
+
2097
+ def main() -> None:
2098
+
2099
+ args = parse_args()
2100
+ configure_manifests(test_mode=args.test)
2101
+ configure_outputs(
2102
+ test_mode=args.test,
2103
+ offline=args.offline,
2104
+ )
2105
+
2106
+ # Test mode runs only 2 epochs.
2107
+ max_epochs = 2 if args.test else MAX_EPOCHS
2108
+
2109
+ if args.test and args.offline:
2110
+ run_mode = "TEST OFFLINE (*-test.json manifests, 2 epochs, NO R2)"
2111
+ elif args.test:
2112
+ run_mode = "TEST (*-test.json manifests, 2 epochs, separate R2 test checkpoint)"
2113
+ else:
2114
+ run_mode = "FULL"
2115
+
2116
+ print(
2117
+ "\nRUN MODE:",
2118
+ run_mode,
2119
+ )
2120
+
2121
+ validate_vast_auto_destroy_config(
2122
+ test_mode=args.test
2123
+ )
2124
+ validate_paths()
2125
+
2126
+ if not torch.cuda.is_available():
2127
+ raise RuntimeError(
2128
+ "CUDA GPU is not available. This script is configured for Vast GPU training."
2129
+ )
2130
+
2131
+ print("\nGPU:", torch.cuda.get_device_name(0))
2132
+ print("CUDA version:", torch.version.cuda)
2133
+
2134
+ # Create all output directories under /workspace.
2135
+ OUTPUT_ROOT.mkdir(
2136
+ parents=True,
2137
+ exist_ok=True,
2138
+ )
2139
+
2140
+ CHECKPOINT_DIR.mkdir(
2141
+ parents=True,
2142
+ exist_ok=True,
2143
+ )
2144
+
2145
+ print(
2146
+ "======================================"
2147
+ )
2148
+
2149
+ print(
2150
+ "GURBANI PUNJABI (pa) STREAMING FINE-TUNING"
2151
+ )
2152
+
2153
+ print(
2154
+ "======================================"
2155
+ )
2156
+
2157
+ print(
2158
+ f"Training manifest:"
2159
+ )
2160
+
2161
+ print(
2162
+ TRAIN_MANIFEST
2163
+ )
2164
+
2165
+ print(
2166
+ f"\nKirtan validation manifest:"
2167
+ )
2168
+
2169
+ print(
2170
+ KIRTAN_VAL_MANIFEST
2171
+ )
2172
+
2173
+ print(
2174
+ f"\nSehaj validation manifest:"
2175
+ )
2176
+
2177
+ print(
2178
+ SEHAJ_VAL_MANIFEST
2179
+ )
2180
+
2181
+ print(
2182
+ f"\nBase model:"
2183
+ )
2184
+
2185
+ print(
2186
+ MODEL_PATH
2187
+ )
2188
+
2189
+ print(
2190
+ f"\nStarting checkpoint:"
2191
+ )
2192
+
2193
+ print(
2194
+ START_CHECKPOINT_PATH
2195
+ if START_CHECKPOINT_PATH is not None
2196
+ else "None — using MODEL_PATH only"
2197
+ )
2198
+
2199
+ print(
2200
+ f"\nOutput model:"
2201
+ )
2202
+
2203
+ print(
2204
+ OUTPUT_MODEL
2205
+ )
2206
+
2207
+ print(
2208
+ f"\nEpoch metrics JSON:"
2209
+ )
2210
+
2211
+ print(
2212
+ EPOCH_METRICS_PATH
2213
+ )
2214
+
2215
+ print(
2216
+ f"\nOutput root:"
2217
+ )
2218
+
2219
+ print(
2220
+ OUTPUT_ROOT
2221
+ )
2222
+
2223
+ print(
2224
+ f"\nCheckpoint directory:"
2225
+ )
2226
+
2227
+ print(
2228
+ CHECKPOINT_DIR
2229
+ )
2230
+
2231
+ if R2_UPLOAD_ENABLED:
2232
+ r2_config = get_r2_config()
2233
+ print(
2234
+ f"\nR2 best-checkpoint backup: "
2235
+ f"r2://{r2_config['bucket']}/{R2_OBJECT_KEY}"
2236
+ )
2237
+ else:
2238
+ print(
2239
+ "\nR2 backup: DISABLED (--test --offline)"
2240
+ )
2241
+
2242
+ print(
2243
+ "\nLoading Gurbani/Punjabi multilingual model..."
2244
+ )
2245
+
2246
+ model = (
2247
+ nemo_asr.models.ASRModel.restore_from(
2248
+ restore_path=str(
2249
+ MODEL_PATH
2250
+ )
2251
+ )
2252
+ )
2253
+
2254
+ # Fail early if the downloaded starting model is not the expected export.
2255
+ # The encoder will later be rebuilt to [202,100] for the new training run.
2256
+ loaded_context = model.cfg.encoder.get("att_context_size", None)
2257
+ if loaded_context is None:
2258
+ raise RuntimeError(
2259
+ "Starting model does not specify encoder.att_context_size; "
2260
+ f"expected {SOURCE_MODEL_ATT_CONTEXT} from {MODEL_PATH}."
2261
+ )
2262
+ loaded_context = [int(value) for value in loaded_context]
2263
+ print("Starting model attention context:", loaded_context)
2264
+ if loaded_context != SOURCE_MODEL_ATT_CONTEXT:
2265
+ raise RuntimeError(
2266
+ "Wrong starting model context: "
2267
+ f"expected {SOURCE_MODEL_ATT_CONTEXT}, got {loaded_context}. "
2268
+ f"Model path: {MODEL_PATH}"
2269
+ )
2270
+
2271
+ # Decide whether this is the first [202,100] run or a restart of
2272
+ # an already-running [202,100] job.
2273
+ resume_ckpt = (
2274
+ LAST_STABLE_CHECKPOINT_PATH
2275
+ if LAST_STABLE_CHECKPOINT_PATH.exists()
2276
+ else None
2277
+ )
2278
+
2279
+ if resume_ckpt is None:
2280
+ print(
2281
+ "\nNo [202,100] stable checkpoint exists. "
2282
+ "This is the FIRST [202,100] run; initializing from the exported model."
2283
+ )
2284
+ load_start_checkpoint_weights(model)
2285
+ else:
2286
+ print(
2287
+ "\nFound [202,100] rolling stable checkpoint. "
2288
+ "Lightning will restore the full [202,100] training state."
2289
+ )
2290
+ print(resume_ckpt)
2291
+
2292
+ # --------------------------------------------------------
2293
+ # Verify that the restored multilingual model supports Punjabi ('pa').
2294
+ # Keep the original multilingual vocabulary and language masks intact.
2295
+ # --------------------------------------------------------
2296
+
2297
+ tokenizer_vocab_size = getattr(
2298
+ model.tokenizer,
2299
+ "vocab_size",
2300
+ None,
2301
+ )
2302
+
2303
+ print(
2304
+ "\nLoaded tokenizer vocabulary:",
2305
+ tokenizer_vocab_size,
2306
+ )
2307
+
2308
+ if tokenizer_vocab_size is None:
2309
+ raise RuntimeError(
2310
+ "Could not determine tokenizer vocabulary size."
2311
+ )
2312
+
2313
+ tokenizer_langs = getattr(
2314
+ model.tokenizer,
2315
+ "langs",
2316
+ None,
2317
+ )
2318
+
2319
+ print(
2320
+ "Tokenizer languages:",
2321
+ tokenizer_langs,
2322
+ )
2323
+
2324
+ if tokenizer_langs is None or LANGUAGE_CODE not in tokenizer_langs:
2325
+ raise RuntimeError(
2326
+ f"Restored multilingual tokenizer does not contain "
2327
+ f"Punjabi ({LANGUAGE_CODE!r})."
2328
+ )
2329
+
2330
+ rnnt_vocab_size = getattr(
2331
+ model.decoder,
2332
+ "vocab_size",
2333
+ None,
2334
+ )
2335
+
2336
+ print(
2337
+ "RNNT decoder vocabulary:",
2338
+ rnnt_vocab_size,
2339
+ )
2340
+
2341
+ if rnnt_vocab_size is None:
2342
+ raise RuntimeError(
2343
+ "Could not determine RNNT decoder vocabulary size."
2344
+ )
2345
+
2346
+ if hasattr(model, "ctc_decoder"):
2347
+ ctc_vocab_size = len(
2348
+ getattr(
2349
+ model.ctc_decoder,
2350
+ "vocabulary",
2351
+ [],
2352
+ )
2353
+ )
2354
+
2355
+ print(
2356
+ "CTC decoder vocabulary:",
2357
+ ctc_vocab_size,
2358
+ )
2359
+
2360
+ language_masks = getattr(
2361
+ model.ctc_decoder,
2362
+ "language_masks",
2363
+ None,
2364
+ )
2365
+
2366
+ print(
2367
+ "CTC language masks present:",
2368
+ language_masks is not None,
2369
+ )
2370
+
2371
+ print(
2372
+ f"✓ Multilingual model with Punjabi ({LANGUAGE_CODE!r}) support verified"
2373
+ )
2374
+
2375
+ print_model_information(
2376
+ model
2377
+ )
2378
+
2379
+ print(
2380
+ "\nCreating fresh Punjabi (pa) training "
2381
+ "and validation dataset configs..."
2382
+ )
2383
+
2384
+ train_cfg = make_dataset_config(
2385
+ manifest_path=TRAIN_MANIFEST,
2386
+ shuffle=True,
2387
+ )
2388
+
2389
+ # Validation is performed explicitly by DomainValidationAndEarlyStopping
2390
+ # at on_train_epoch_end().
2391
+ #
2392
+ # IMPORTANT:
2393
+ # NeMo's model.transcribe() still reads model.cfg.validation_ds internally
2394
+ # (for fields such as use_start_end_token), so validation_ds must NOT be None.
2395
+ # We keep a valid Kirtan validation config here, but Lightning's built-in
2396
+ # validation loop remains disabled with limit_val_batches=0 below.
2397
+ validation_cfg = make_dataset_config(
2398
+ manifest_path=KIRTAN_VAL_MANIFEST,
2399
+ shuffle=False,
2400
+ )
2401
+
2402
+ OmegaConf.set_struct(
2403
+ train_cfg,
2404
+ False,
2405
+ )
2406
+
2407
+ OmegaConf.set_struct(
2408
+ validation_cfg,
2409
+ False,
2410
+ )
2411
+
2412
+ with open_dict(
2413
+ model.cfg
2414
+ ):
2415
+
2416
+ model.cfg.train_ds = train_cfg
2417
+ model.cfg.validation_ds = validation_cfg
2418
+ model.cfg.test_ds = None
2419
+
2420
+ # Keep the conservative fine-tuning LR.
2421
+ model.cfg.optim.lr = (
2422
+ LEARNING_RATE
2423
+ )
2424
+
2425
+ print(
2426
+ "\nTraining dataset config:"
2427
+ )
2428
+ print(
2429
+ OmegaConf.to_yaml(
2430
+ model.cfg.train_ds
2431
+ )
2432
+ )
2433
+
2434
+ print(
2435
+ "\nValidation mode: explicit post-epoch transcription "
2436
+ "(Lightning validation disabled)"
2437
+ )
2438
+ print(
2439
+ f"Kirtan validation: {KIRTAN_VAL_MANIFEST}"
2440
+ )
2441
+ print(
2442
+ f"Sehaj validation: {SEHAJ_VAL_MANIFEST}"
2443
+ )
2444
+
2445
+ print(
2446
+ "\nTraining configuration:"
2447
+ )
2448
+
2449
+ print(
2450
+ f"Batch size: "
2451
+ f"{BATCH_SIZE}"
2452
+ )
2453
+
2454
+ print(
2455
+ f"Gradient accumulation: "
2456
+ f"{ACCUMULATE_GRAD_BATCHES}"
2457
+ )
2458
+
2459
+ print(
2460
+ f"Effective batch size: "
2461
+ f"{BATCH_SIZE * ACCUMULATE_GRAD_BATCHES}"
2462
+ )
2463
+
2464
+ print(
2465
+ f"Learning rate: "
2466
+ f"{LEARNING_RATE}"
2467
+ )
2468
+
2469
+ print(
2470
+ f"Maximum epochs: "
2471
+ f"{max_epochs}"
2472
+ )
2473
+
2474
+ print(
2475
+ f"Early-stop patience: "
2476
+ f"{EARLY_STOP_PATIENCE}"
2477
+ )
2478
+
2479
+ print(
2480
+ f"Minimum WER improvement: "
2481
+ f"{MIN_WER_IMPROVEMENT}"
2482
+ )
2483
+
2484
+ print(
2485
+ f"Streaming attention context (full data): "
2486
+ f"{STREAM_ATT_CONTEXTS}"
2487
+ )
2488
+
2489
+ print(
2490
+ f"Causal convolution context: "
2491
+ f"{CAUSAL_CONV_CONTEXT}"
2492
+ )
2493
+
2494
+ # ------------------------------------------------------------------
2495
+ # Full-data streaming training
2496
+ # ------------------------------------------------------------------
2497
+ # Train the complete selected manifest using the configured [202,100]
2498
+ # streaming attention context.
2499
+ # ------------------------------------------------------------------
2500
+
2501
+ for stage_index, attention_context in enumerate(STREAM_ATT_CONTEXTS, start=1):
2502
+ context_tag = f"{attention_context[0]}_{attention_context[1]}"
2503
+ stage_root = OUTPUT_ROOT
2504
+ stage_checkpoint_dir = stage_root / "checkpoints"
2505
+ stage_best_checkpoint = stage_checkpoint_dir / "best.ckpt"
2506
+ stage_metrics_path = stage_root / "epoch_metrics.json"
2507
+ stage_stable_checkpoint = LAST_STABLE_CHECKPOINT_PATH
2508
+
2509
+ stage_root.mkdir(parents=True, exist_ok=True)
2510
+ stage_checkpoint_dir.mkdir(parents=True, exist_ok=True)
2511
+
2512
+ print("\n############################################################")
2513
+ print(
2514
+ f"FULL-DATA STREAMING TRAINING - ATTENTION {attention_context}"
2515
+ )
2516
+ print("############################################################")
2517
+
2518
+ rebuild_encoder_cache_aware(
2519
+ model,
2520
+ attention_context=attention_context,
2521
+ )
2522
+
2523
+ # Keep the dataset config unchanged, so this stage consumes the entire
2524
+ # selected training manifest once per epoch.
2525
+ model.setup_training_data(
2526
+ model.cfg.train_ds
2527
+ )
2528
+
2529
+ # The pre-train transcription health check runs before trainer.fit().
2530
+ # Lightning has therefore not yet moved the model to the GPU. Move the
2531
+ # full hybrid model explicitly so model parameters, preprocessor/STFT
2532
+ # buffers, and the patched transcribe input tensors all use cuda:0.
2533
+ model.to(torch.device("cuda:0"))
2534
+ print(f"Pre-train health-check model device: {next(model.parameters()).device}")
2535
+
2536
+ # Verify CTC after changing the streaming attention context and before
2537
+ # the first optimizer step of this stage.
2538
+ run_pretrain_ctc_health_check(
2539
+ model=model,
2540
+ batch_size=BATCH_SIZE,
2541
+ )
2542
+
2543
+ stage_domain_validation_callback = DomainValidationAndEarlyStopping(
2544
+ metrics_path=stage_metrics_path,
2545
+ best_checkpoint_path=stage_best_checkpoint,
2546
+ kirtan_manifest=KIRTAN_VAL_MANIFEST,
2547
+ sehaj_manifest=SEHAJ_VAL_MANIFEST,
2548
+ batch_size=BATCH_SIZE,
2549
+ patience=EARLY_STOP_PATIENCE,
2550
+ min_delta=MIN_WER_IMPROVEMENT,
2551
+ )
2552
+
2553
+ stage_checkpoint_callback = LastTwoEpochCheckpoints(
2554
+ dirpath=stage_checkpoint_dir
2555
+ )
2556
+
2557
+ stage_ctc_probe_callback = CTCHealthProbe(
2558
+ manifest_path=KIRTAN_VAL_MANIFEST,
2559
+ stable_checkpoint_path=stage_stable_checkpoint,
2560
+ every_optimizer_steps=CTC_PROBE_EVERY_OPTIMIZER_STEPS,
2561
+ save_every_optimizer_steps=CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS,
2562
+ sample_count=CTC_PROBE_SAMPLE_COUNT,
2563
+ )
2564
+
2565
+ trainer = pl.Trainer(
2566
+ accelerator="gpu",
2567
+ devices=1,
2568
+ max_epochs=max_epochs,
2569
+ precision=16,
2570
+ accumulate_grad_batches=ACCUMULATE_GRAD_BATCHES,
2571
+ log_every_n_steps=100,
2572
+ limit_val_batches=0,
2573
+ default_root_dir=str(stage_root / "lightning"),
2574
+ enable_checkpointing=False,
2575
+ callbacks=[
2576
+ EpochProgressBar(),
2577
+ EpochTimer(),
2578
+ stage_ctc_probe_callback,
2579
+ stage_domain_validation_callback,
2580
+ stage_checkpoint_callback,
2581
+ ],
2582
+ )
2583
+
2584
+ model.set_trainer(trainer)
2585
+
2586
+ print("\n======================================")
2587
+ print(
2588
+ f"STARTING FULL-DATA STREAM TRAINING "
2589
+ f"FOR ATTENTION {attention_context}"
2590
+ )
2591
+ print("======================================")
2592
+
2593
+ if resume_ckpt is not None:
2594
+ print(
2595
+ "\nResuming FULL [202,100] Lightning state from: "
2596
+ f"{resume_ckpt}"
2597
+ )
2598
+ else:
2599
+ print(
2600
+ "\nStarting fresh [202,100] training from exported model weights: "
2601
+ f"{MODEL_PATH}"
2602
+ )
2603
+ print("Optimizer/scheduler state: FRESH")
2604
+
2605
+ try:
2606
+ trainer.fit(
2607
+ model,
2608
+ ckpt_path=str(resume_ckpt)
2609
+ if resume_ckpt is not None
2610
+ else None,
2611
+ )
2612
+ except Exception:
2613
+ print("\n======================================")
2614
+ print("STREAM TRAINING STOPPED / FAILED")
2615
+ print("======================================")
2616
+ print("Attention context:", attention_context)
2617
+ print("Last CTC-verified stable checkpoint:")
2618
+ print(stage_stable_checkpoint)
2619
+ raise
2620
+
2621
+ print(
2622
+ f"\n✓ Completed full-data streaming training: "
2623
+ f"attention {attention_context}"
2624
+ )
2625
+
2626
+ # Restore the best streaming weights before final export.
2627
+ if stage_best_checkpoint.exists():
2628
+ print("Loading best streaming checkpoint before continuing:")
2629
+ print(stage_best_checkpoint)
2630
+ checkpoint = torch.load(
2631
+ str(stage_best_checkpoint),
2632
+ map_location="cpu",
2633
+ )
2634
+ state_dict = checkpoint.get("state_dict", checkpoint)
2635
+ result = model.load_state_dict(state_dict, strict=False)
2636
+
2637
+ missing = list(result.missing_keys)
2638
+ unexpected = list(result.unexpected_keys)
2639
+
2640
+ if missing or unexpected:
2641
+ print("Missing keys:", missing[:30])
2642
+ print("Unexpected keys:", unexpected[:30])
2643
+ raise RuntimeError(
2644
+ "Best streaming checkpoint did not cleanly reload."
2645
+ )
2646
+
2647
+ print("✓ Best streaming weights restored")
2648
+
2649
+ print(
2650
+ "\n======================================"
2651
+ )
2652
+
2653
+ print(
2654
+ "TRAINING FINISHED"
2655
+ )
2656
+
2657
+ print(
2658
+ "======================================"
2659
+ )
2660
+
2661
+ print("Last CTC-verified stable checkpoint:")
2662
+ print(LAST_STABLE_CHECKPOINT_PATH)
2663
+ print("This checkpoint resumes the full [202,100] Lightning training state.")
2664
+
2665
+ if (
2666
+ stage_domain_validation_callback.best_epoch
2667
+ is not None
2668
+ ):
2669
+
2670
+ print(
2671
+ f"Best epoch: "
2672
+ f"{stage_domain_validation_callback.best_epoch}"
2673
+ )
2674
+
2675
+ print(
2676
+ f"Best Kirtan validation WER: "
2677
+ f"{stage_domain_validation_callback.best_kirtan_wer:.6f} "
2678
+ f"({stage_domain_validation_callback.best_kirtan_wer * 100:.3f}%)"
2679
+ )
2680
+
2681
+ print(
2682
+ f"Best checkpoint Sehaj validation WER: "
2683
+ f"{stage_domain_validation_callback.best_sehaj_wer:.6f} "
2684
+ f"({stage_domain_validation_callback.best_sehaj_wer * 100:.3f}%)"
2685
+ )
2686
+
2687
+ print(
2688
+ f"Best checkpoint: "
2689
+ f"{BEST_CHECKPOINT_PATH}"
2690
+ )
2691
+
2692
+ print(
2693
+ "\nLast two epoch checkpoints:"
2694
+ )
2695
+
2696
+ last_checkpoints = sorted(
2697
+ CHECKPOINT_DIR.glob(
2698
+ "epoch_*.ckpt"
2699
+ )
2700
+ )
2701
+
2702
+ for checkpoint in last_checkpoints:
2703
+ print(
2704
+ f" {checkpoint}"
2705
+ )
2706
+
2707
+ print(
2708
+ "\nSaving final training-state "
2709
+ ".nemo model to:"
2710
+ )
2711
+
2712
+ print(
2713
+ OUTPUT_MODEL
2714
+ )
2715
+
2716
+ model.save_to(
2717
+ str(
2718
+ OUTPUT_MODEL
2719
+ )
2720
+ )
2721
+
2722
+ print(
2723
+ "\n======================================"
2724
+ )
2725
+
2726
+ print(
2727
+ "COMPLETE"
2728
+ )
2729
+
2730
+ print(
2731
+ "======================================"
2732
+ )
2733
+
2734
+ print(
2735
+ f"Final model: "
2736
+ f"{OUTPUT_MODEL}"
2737
+ )
2738
+
2739
+ print(
2740
+ f"Best checkpoint: "
2741
+ f"{BEST_CHECKPOINT_PATH}"
2742
+ )
2743
+
2744
+ print(
2745
+ f"Epoch metrics: "
2746
+ f"{EPOCH_METRICS_PATH}"
2747
+ )
2748
+
2749
+ # Never destroy during infrastructure testing.
2750
+ if args.test:
2751
+ if args.offline:
2752
+ print(
2753
+ "\nTEST OFFLINE MODE: no R2 upload was attempted."
2754
+ )
2755
+ print(
2756
+ "TEST MODE: Vast instance will NOT be destroyed."
2757
+ )
2758
+
2759
+ elif not AUTO_DESTROY_VAST:
2760
+ print(
2761
+ "\nAUTO_DESTROY_VAST is disabled; instance will remain running."
2762
+ )
2763
+
2764
+ elif stage_domain_validation_callback.best_epoch is None:
2765
+ print(
2766
+ "\nVast instance NOT destroyed: no best checkpoint was produced."
2767
+ )
2768
+
2769
+ elif not stage_domain_validation_callback.r2_best_uploaded:
2770
+ print(
2771
+ "\nVast instance NOT destroyed: best.ckpt was not confirmed "
2772
+ "uploaded to R2."
2773
+ )
2774
+
2775
+ else:
2776
+ destroy_current_vast_instance()
2777
+
2778
+
2779
+ ###############################################################################
2780
+ # ENTRY POINT
2781
+ ###############################################################################
2782
+
2783
+ if __name__ == "__main__":
2784
+ main()
train.py ADDED
@@ -0,0 +1,2446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ import pytorch_lightning as pl
13
+ from omegaconf import OmegaConf, open_dict
14
+ from pytorch_lightning.callbacks import Callback, TQDMProgressBar
15
+
16
+ import nemo.collections.asr as nemo_asr
17
+
18
+
19
+ ###############################################################################
20
+ # DATASET CONFIGURATION
21
+ ###############################################################################
22
+
23
+ # train.py is intended to live directly inside the training-data folder.
24
+ # This makes the whole training-data directory portable as one upload.
25
+ DATA_ROOT = Path(__file__).resolve().parent
26
+
27
+ # Manifest paths are selected at startup.
28
+ #
29
+ # Normal:
30
+ # train_manifest.json
31
+ # kirtan_val_manifest.json
32
+ # sehaj_paath_val_manifest.json
33
+ #
34
+ # --test:
35
+ # train_manifest-test.json
36
+ # kirtan_val_manifest.json (FULL validation)
37
+ # sehaj_paath_val_manifest.json (FULL validation)
38
+ #
39
+ # Audio paths inside the manifests are used exactly as written.
40
+ TRAIN_MANIFEST = None
41
+ KIRTAN_VAL_MANIFEST = None
42
+ SEHAJ_VAL_MANIFEST = None
43
+
44
+
45
+ def configure_manifests(test_mode: bool) -> None:
46
+ """Use small training data in --test, but always use full validation."""
47
+ global TRAIN_MANIFEST
48
+ global KIRTAN_VAL_MANIFEST
49
+ global SEHAJ_VAL_MANIFEST
50
+
51
+ if test_mode:
52
+ TRAIN_MANIFEST = DATA_ROOT / "train_manifest-test.json"
53
+ else:
54
+ TRAIN_MANIFEST = DATA_ROOT / "train_manifest_max30s.json"
55
+
56
+ # Always score the real/full validation sets, including --test.
57
+ KIRTAN_VAL_MANIFEST = DATA_ROOT / "kirtan_val_manifest.json"
58
+ SEHAJ_VAL_MANIFEST = DATA_ROOT / "sehaj_paath_val_manifest.json"
59
+
60
+ EXPECTED_SAMPLE_RATE = 16_000
61
+ LANGUAGE_CODE = "pa"
62
+
63
+ # Use one explicit decoder for validation so the metric is stable across epochs.
64
+ # The model is hybrid RNNT+CTC; CTC is used here only for explicit WER/CER scoring.
65
+ VALIDATION_DECODER = "ctc"
66
+
67
+
68
+ ###############################################################################
69
+ # MODEL CONFIGURATION
70
+ ###############################################################################
71
+
72
+ # Restore the multilingual AI4Bharat base model with Punjabi ('pa') support.
73
+ MODEL_PATH = Path(
74
+ "/workspace/resume_checkpoint/baniguru_kirtan_v2_best.nemo"
75
+ ).expanduser().resolve()
76
+
77
+ # Optional checkpoint overlay.
78
+ # Set to None to train directly from MODEL_PATH only.
79
+ # Example:
80
+ LAST_STABLE_CHECKPOINT_PATH = Path(
81
+ "/workspace/resume_checkpoint/last_stable.ckpt"
82
+ ).expanduser().resolve()
83
+
84
+ # Resume from the latest CTC-verified stable checkpoint.
85
+ START_CHECKPOINT_PATH = LAST_STABLE_CHECKPOINT_PATH
86
+ # START_CHECKPOINT_PATH = None
87
+
88
+ ###############################################################################
89
+ # TRAINING CONFIGURATION
90
+ ###############################################################################
91
+
92
+ BATCH_SIZE = 8
93
+
94
+ # Conservative full-model fine-tuning rate after Stage-2 adaptation.
95
+ LEARNING_RATE = 1e-5
96
+
97
+ # Upper limit.
98
+ # Early stopping can stop training before reaching this.
99
+ MAX_EPOCHS = 50
100
+
101
+ # Effective batch size:
102
+ #
103
+ # BATCH_SIZE * ACCUMULATE_GRAD_BATCHES
104
+ #
105
+ # 4 * 2 = 8
106
+ ACCUMULATE_GRAD_BATCHES = 1
107
+
108
+ # Tiny fixed CTC probe during training.
109
+ CTC_PROBE_EVERY_OPTIMIZER_STEPS = 1000
110
+ CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS = 2000
111
+ CTC_PROBE_SAMPLE_COUNT = 2
112
+
113
+
114
+ ###############################################################################
115
+ # EARLY STOPPING CONFIGURATION
116
+ ###############################################################################
117
+
118
+ # Stop after this many consecutive validation epochs without improvement.
119
+ EARLY_STOP_PATIENCE = 10
120
+
121
+ # WER needs to improve by at least this much to count as an improvement.
122
+ #
123
+ # Example:
124
+ # old WER = 0.1000
125
+ # new WER = 0.09995
126
+ #
127
+ # Difference = 0.00005
128
+ #
129
+ # With MIN_WER_IMPROVEMENT = 0.0001,
130
+ # that would NOT count as an improvement.
131
+ MIN_WER_IMPROVEMENT = 0.0001
132
+
133
+ # Kirtan CER is the primary checkpoint metric. Sehaj WER may also promote
134
+ # a checkpoint when it improves by at least MIN_WER_IMPROVEMENT and Kirtan
135
+ # CER is no more than 0.5 percentage points worse than the currently selected
136
+ # best checkpoint. CER is stored as a fraction, so 0.005 == 0.5 points.
137
+ KIRTAN_CER_TOLERANCE_FOR_SEHAJ = 0.005
138
+
139
+
140
+ ###############################################################################
141
+ # CLOUDFLARE R2 BACKUP CONFIGURATION
142
+ ###############################################################################
143
+
144
+ # Upload ONLY best.ckpt when the Kirtan-primary / Sehaj-tie-break rule improves.
145
+ # Credentials are read from environment variables so secrets are not stored
146
+ # inside this training script.
147
+ R2_UPLOAD_ENABLED = True
148
+ R2_OBJECT_KEY = os.environ.get(
149
+ "R2_OBJECT_KEY",
150
+ "checkpoints/best.ckpt",
151
+ )
152
+ R2_UPLOAD_RETRIES = 3
153
+ R2_RETRY_DELAY_SECONDS = 10
154
+
155
+
156
+ ###############################################################################
157
+ # VAST.AI AUTO-DESTROY CONFIGURATION
158
+ ###############################################################################
159
+
160
+ # Full runs automatically destroy the current Vast instance only after:
161
+ # 1. training has finished (early stopping or max epochs), AND
162
+ # 2. a best.ckpt was successfully uploaded to R2.
163
+ #
164
+ # --test NEVER destroys the instance.
165
+ AUTO_DESTROY_VAST = False
166
+
167
+
168
+ ###############################################################################
169
+ # OUTPUT / CHECKPOINT / LOG CONFIGURATION
170
+ ###############################################################################
171
+
172
+ # Put large/persistent training outputs under this directory.
173
+ #
174
+ # Vast.ai workspace output directory.
175
+ #
176
+ # Checkpoints, metrics, and the final model stay under OUTPUT_ROOT.
177
+ #
178
+ # OUTPUT_ROOT/
179
+ # ├── checkpoints/
180
+ # │ ├── best.ckpt
181
+ # │ ├── epoch_XXX.ckpt
182
+ # │ └── epoch_YYY.ckpt
183
+ # ├── wer_history.json
184
+ # └── gurbani_sehaj_paath_v1_base_indicconformer_stt_multi_hybrid_rnnt_600m.nemo
185
+ #
186
+ OUTPUT_ROOT = Path(
187
+ "/workspace/asr_training"
188
+ ).expanduser().resolve()
189
+
190
+ # Final .nemo model saved when training finishes / early-stops.
191
+ OUTPUT_MODEL = (
192
+ OUTPUT_ROOT
193
+ / "baniguru_kirtan_v3.nemo"
194
+ )
195
+
196
+ # Best checkpoint + last two epoch checkpoints.
197
+ CHECKPOINT_DIR = (
198
+ OUTPUT_ROOT / "checkpoints"
199
+ )
200
+
201
+ BEST_CHECKPOINT_PATH = (
202
+ CHECKPOINT_DIR / "best.ckpt"
203
+ )
204
+
205
+ # Per-epoch validation metrics for BOTH domains.
206
+ # Contains kirtan WER/CER + sehaj WER/CER.
207
+ EPOCH_METRICS_PATH = (
208
+ OUTPUT_ROOT / "epoch_metrics.json"
209
+ )
210
+
211
+
212
+ def configure_outputs(test_mode: bool, offline: bool = False) -> None:
213
+ """Keep test artifacts separate and optionally disable R2 for test runs."""
214
+ global OUTPUT_ROOT
215
+ global OUTPUT_MODEL
216
+ global CHECKPOINT_DIR
217
+ global BEST_CHECKPOINT_PATH
218
+ global EPOCH_METRICS_PATH
219
+ global R2_OBJECT_KEY
220
+ global R2_UPLOAD_ENABLED
221
+
222
+ if test_mode:
223
+ OUTPUT_ROOT = Path("/workspace/asr_training_test").expanduser().resolve()
224
+ OUTPUT_MODEL = OUTPUT_ROOT / "baniguru_kirtan_v3.nemo"
225
+ CHECKPOINT_DIR = OUTPUT_ROOT / "checkpoints"
226
+ BEST_CHECKPOINT_PATH = CHECKPOINT_DIR / "best.ckpt"
227
+ EPOCH_METRICS_PATH = OUTPUT_ROOT / "epoch_metrics.json"
228
+
229
+ # Online test runs use a separate R2 object and never overwrite
230
+ # the full-run best checkpoint.
231
+ R2_OBJECT_KEY = "checkpoints/test-best.ckpt"
232
+
233
+ if offline:
234
+ # --offline is intentionally restricted to --test in parse_args().
235
+ R2_UPLOAD_ENABLED = False
236
+
237
+ ###############################################################################
238
+ # CALLBACK: PROGRESS BAR WITH HUMAN-READABLE EPOCH NUMBER
239
+ ###############################################################################
240
+
241
+ class EpochProgressBar(TQDMProgressBar):
242
+ def get_metrics(self, trainer, pl_module):
243
+ items = super().get_metrics(trainer, pl_module)
244
+ items["epoch"] = trainer.current_epoch + 1
245
+ return items
246
+
247
+
248
+ ###############################################################################
249
+ # CALLBACK: EPOCH TIMER
250
+ ###############################################################################
251
+
252
+ class EpochTimer(Callback):
253
+ def __init__(self):
254
+ super().__init__()
255
+ self.start_time = None
256
+
257
+ def on_train_epoch_start(
258
+ self,
259
+ trainer,
260
+ pl_module,
261
+ ):
262
+ self.start_time = time.time()
263
+
264
+ def on_train_epoch_end(
265
+ self,
266
+ trainer,
267
+ pl_module,
268
+ ):
269
+ if self.start_time is None:
270
+ print(
271
+ f"\nEpoch {trainer.current_epoch + 1} completed "
272
+ "(timer unavailable because training resumed mid-epoch)"
273
+ )
274
+ return
275
+
276
+ elapsed = time.time() - self.start_time
277
+
278
+ print(
279
+ f"\nEpoch {trainer.current_epoch + 1} "
280
+ f"completed in {elapsed / 60:.2f} minutes"
281
+ )
282
+
283
+
284
+ ###############################################################################
285
+ # VALIDATION METRICS HELPERS
286
+ ###############################################################################
287
+
288
+ def levenshtein_ops(reference, hypothesis):
289
+ """
290
+ Return (substitutions, deletions, insertions) for two sequences.
291
+ """
292
+ n = len(reference)
293
+ m = len(hypothesis)
294
+
295
+ # dp[i][j] = (cost, S, D, I)
296
+ dp = [[None] * (m + 1) for _ in range(n + 1)]
297
+
298
+ dp[0][0] = (0, 0, 0, 0)
299
+
300
+ for i in range(1, n + 1):
301
+ dp[i][0] = (i, 0, i, 0)
302
+
303
+ for j in range(1, m + 1):
304
+ dp[0][j] = (j, 0, 0, j)
305
+
306
+ for i in range(1, n + 1):
307
+ for j in range(1, m + 1):
308
+
309
+ if reference[i - 1] == hypothesis[j - 1]:
310
+ dp[i][j] = dp[i - 1][j - 1]
311
+ continue
312
+
313
+ sub_prev = dp[i - 1][j - 1]
314
+ del_prev = dp[i - 1][j]
315
+ ins_prev = dp[i][j - 1]
316
+
317
+ candidates = [
318
+ (
319
+ sub_prev[0] + 1,
320
+ sub_prev[1] + 1,
321
+ sub_prev[2],
322
+ sub_prev[3],
323
+ ),
324
+ (
325
+ del_prev[0] + 1,
326
+ del_prev[1],
327
+ del_prev[2] + 1,
328
+ del_prev[3],
329
+ ),
330
+ (
331
+ ins_prev[0] + 1,
332
+ ins_prev[1],
333
+ ins_prev[2],
334
+ ins_prev[3] + 1,
335
+ ),
336
+ ]
337
+
338
+ dp[i][j] = min(
339
+ candidates,
340
+ key=lambda item: (
341
+ item[0],
342
+ item[2], # prefer fewer deletions on ties
343
+ item[3],
344
+ item[1],
345
+ ),
346
+ )
347
+
348
+ _, substitutions, deletions, insertions = dp[n][m]
349
+
350
+ return substitutions, deletions, insertions
351
+
352
+
353
+ def extract_text_from_hypothesis(item):
354
+ if isinstance(item, str):
355
+ return item
356
+
357
+ if hasattr(item, "text"):
358
+ return str(item.text)
359
+
360
+ if isinstance(item, dict):
361
+ if "text" in item:
362
+ return str(item["text"])
363
+
364
+ if "pred_text" in item:
365
+ return str(item["pred_text"])
366
+
367
+ return str(item)
368
+
369
+
370
+ def select_primary_transcriptions(outputs, expected_count):
371
+ """
372
+ Normalize NeMo transcribe() output.
373
+
374
+ Hybrid RNNT+CTC models can return more than one decoding branch.
375
+ We select the first complete branch, which is treated here as the
376
+ primary transcription stream for BOTH domains and all epochs.
377
+ """
378
+ if isinstance(outputs, tuple):
379
+ outputs = list(outputs)
380
+
381
+ if isinstance(outputs, list):
382
+
383
+ # Normal case: one hypothesis per input.
384
+ if len(outputs) == expected_count and (
385
+ expected_count == 0
386
+ or not isinstance(outputs[0], (list, tuple))
387
+ ):
388
+ return [
389
+ extract_text_from_hypothesis(item)
390
+ for item in outputs
391
+ ]
392
+
393
+ # Hybrid case: [rnnt_outputs, ctc_outputs, ...]
394
+ for branch in outputs:
395
+ if (
396
+ isinstance(branch, (list, tuple))
397
+ and len(branch) == expected_count
398
+ ):
399
+ return [
400
+ extract_text_from_hypothesis(item)
401
+ for item in branch
402
+ ]
403
+
404
+ raise RuntimeError(
405
+ "Could not identify the primary transcribe() output branch. "
406
+ f"Expected {expected_count} predictions; got type={type(outputs)}"
407
+ )
408
+
409
+
410
+ def load_validation_manifest(manifest_path: Path):
411
+ samples = []
412
+
413
+ with Path(manifest_path).open(
414
+ "r",
415
+ encoding="utf-8",
416
+ ) as handle:
417
+
418
+ for line_number, line in enumerate(
419
+ handle,
420
+ start=1,
421
+ ):
422
+ line = line.strip()
423
+
424
+ if not line:
425
+ continue
426
+
427
+ item = json.loads(line)
428
+
429
+ audio_path = item.get(
430
+ "audio_filepath"
431
+ )
432
+
433
+ text = item.get(
434
+ "text"
435
+ )
436
+
437
+ if not audio_path:
438
+ raise RuntimeError(
439
+ f"{manifest_path}: line {line_number} "
440
+ "has no audio_filepath."
441
+ )
442
+
443
+ if text is None:
444
+ raise RuntimeError(
445
+ f"{manifest_path}: line {line_number} "
446
+ "has no text."
447
+ )
448
+
449
+ language = item.get("lang")
450
+
451
+ if language != LANGUAGE_CODE:
452
+ raise RuntimeError(
453
+ f"{manifest_path}: line {line_number} "
454
+ f"must have lang='{LANGUAGE_CODE}', got {language!r}."
455
+ )
456
+
457
+ samples.append(
458
+ {
459
+ "audio_filepath": str(audio_path),
460
+ "text": " ".join(
461
+ str(text).strip().split()
462
+ ),
463
+ "lang": language,
464
+ }
465
+ )
466
+
467
+ if not samples:
468
+ raise RuntimeError(
469
+ f"Validation manifest is empty: {manifest_path}"
470
+ )
471
+
472
+ return samples
473
+
474
+
475
+ def score_validation_manifest(
476
+ model,
477
+ manifest_path: Path,
478
+ batch_size: int,
479
+ ):
480
+ """
481
+ Explicitly transcribe one validation manifest and return STRICT
482
+ word-level WER and character-level CER.
483
+
484
+ Validation is forced onto one decoder (CTC) for every epoch so a hybrid
485
+ RNNT+CTC model cannot silently switch decoding branches between calls.
486
+ The model's training/eval state and previous decoder are restored even if
487
+ validation raises an exception.
488
+
489
+ Spaces are excluded from CER.
490
+ """
491
+
492
+ samples = load_validation_manifest(
493
+ manifest_path
494
+ )
495
+
496
+ total_word_substitutions = 0
497
+ total_word_deletions = 0
498
+ total_word_insertions = 0
499
+ total_reference_words = 0
500
+ total_predicted_words = 0
501
+
502
+ total_char_substitutions = 0
503
+ total_char_deletions = 0
504
+ total_char_insertions = 0
505
+ total_reference_chars = 0
506
+ total_predicted_chars = 0
507
+
508
+ # CTC health guard. A catastrophic decoder collapse must never be turned
509
+ # into a fake WER, checkpoint, R2 upload, or early-stop event.
510
+ special_or_empty_outputs = 0
511
+ checked_outputs = 0
512
+
513
+ was_training = model.training
514
+ previous_decoder = getattr(
515
+ model,
516
+ "cur_decoder",
517
+ None,
518
+ )
519
+
520
+ model.eval()
521
+
522
+ # Hybrid RNNT+CTC models keep a current decoder. Force validation to use
523
+ # exactly the same branch every time. The AI4Bharat/NeMo hybrid model
524
+ # exposes cur_decoder; fail loudly if that contract is unavailable.
525
+ if not hasattr(model, "cur_decoder"):
526
+ raise RuntimeError(
527
+ "Hybrid validation expected model.cur_decoder, but the restored "
528
+ "model does not expose it. Refusing to compute an ambiguous WER."
529
+ )
530
+
531
+ model.cur_decoder = VALIDATION_DECODER
532
+
533
+ try:
534
+ with torch.no_grad():
535
+
536
+ for start in range(
537
+ 0,
538
+ len(samples),
539
+ batch_size,
540
+ ):
541
+
542
+ batch = samples[
543
+ start:
544
+ start + batch_size
545
+ ]
546
+
547
+ audio_paths = [
548
+ item["audio_filepath"]
549
+ for item in batch
550
+ ]
551
+
552
+ outputs = model.transcribe(
553
+ audio_paths,
554
+ batch_size=batch_size,
555
+ return_hypotheses=False,
556
+ verbose=True,
557
+ language_id=LANGUAGE_CODE,
558
+ )
559
+
560
+ hypotheses = select_primary_transcriptions(
561
+ outputs,
562
+ expected_count=len(batch),
563
+ )
564
+
565
+ normalized_batch = [
566
+ " ".join(str(value).strip().split())
567
+ for value in hypotheses
568
+ ]
569
+ checked_outputs += len(normalized_batch)
570
+ special_or_empty_outputs += sum(
571
+ value in {"<unk>", "<blank>", ""}
572
+ for value in normalized_batch
573
+ )
574
+
575
+ # Print one compact diagnostic batch per validation manifest.
576
+ # This is intentionally kept in the normal log so a future
577
+ # decoder regression can be diagnosed without another rerun.
578
+ if start == 0:
579
+ print("\nVALIDATION DEBUG")
580
+ print(f"Manifest: {manifest_path}")
581
+ print(f"Decoder: {getattr(model, 'cur_decoder', None)!r}")
582
+ print(f"Outputs type: {type(outputs)}")
583
+ normalized_debug = normalized_batch
584
+
585
+ # The failure observed previously produced one special token
586
+ # (for example <unk>) for every sample. Never turn that
587
+ # decoder failure into a fake 100% WER / early-stop event.
588
+ if normalized_debug and all(
589
+ value in {"<unk>", "<blank>", ""}
590
+ for value in normalized_debug
591
+ ):
592
+ raise RuntimeError(
593
+ "Validation decoder returned only special/empty "
594
+ f"tokens for {manifest_path}: "
595
+ f"{normalized_debug[:5]}. "
596
+ "Stopping instead of recording a false WER."
597
+ )
598
+
599
+ for batch_index, (sample, hypothesis) in enumerate(
600
+ zip(batch, hypotheses),
601
+ ):
602
+
603
+ reference = " ".join(
604
+ sample["text"].strip().split()
605
+ )
606
+
607
+ hypothesis = " ".join(
608
+ hypothesis.strip().split()
609
+ )
610
+
611
+ validation_index = start + batch_index + 1
612
+ print(
613
+ f" [{validation_index}] REF : {reference}"
614
+ )
615
+ print(
616
+ f" [{validation_index}] PRED: {hypothesis}"
617
+ )
618
+
619
+ ref_words = reference.split()
620
+ hyp_words = hypothesis.split()
621
+
622
+ (
623
+ word_s,
624
+ word_d,
625
+ word_i,
626
+ ) = levenshtein_ops(
627
+ ref_words,
628
+ hyp_words,
629
+ )
630
+
631
+ total_word_substitutions += word_s
632
+ total_word_deletions += word_d
633
+ total_word_insertions += word_i
634
+ total_reference_words += len(
635
+ ref_words
636
+ )
637
+ total_predicted_words += len(
638
+ hyp_words
639
+ )
640
+
641
+ # CER excludes spaces.
642
+ ref_chars = list(
643
+ reference.replace(" ", "")
644
+ )
645
+
646
+ hyp_chars = list(
647
+ hypothesis.replace(" ", "")
648
+ )
649
+
650
+ (
651
+ char_s,
652
+ char_d,
653
+ char_i,
654
+ ) = levenshtein_ops(
655
+ ref_chars,
656
+ hyp_chars,
657
+ )
658
+
659
+ total_char_substitutions += char_s
660
+ total_char_deletions += char_d
661
+ total_char_insertions += char_i
662
+ total_reference_chars += len(
663
+ ref_chars
664
+ )
665
+ total_predicted_chars += len(
666
+ hyp_chars
667
+ )
668
+
669
+ finally:
670
+ # Restore decoder state before handing the model back to Lightning.
671
+ model.cur_decoder = previous_decoder
672
+
673
+ if was_training:
674
+ model.train()
675
+ else:
676
+ model.eval()
677
+
678
+ # Full-manifest protection as a second line of defense. The historical
679
+ # failure returned <unk> for essentially every sample. Abort before any
680
+ # metric/checkpoint action if >=95% of outputs are special/empty.
681
+ special_ratio = (
682
+ special_or_empty_outputs / checked_outputs
683
+ if checked_outputs
684
+ else 1.0
685
+ )
686
+
687
+ if checked_outputs == 0:
688
+ raise RuntimeError(
689
+ f"Validation produced zero hypotheses for {manifest_path}."
690
+ )
691
+
692
+ if special_ratio >= 0.95:
693
+ raise RuntimeError(
694
+ "CTC VALIDATION COLLAPSE DETECTED: "
695
+ f"{special_or_empty_outputs}/{checked_outputs} "
696
+ f"({special_ratio * 100.0:.2f}%) hypotheses were "
697
+ f"<unk>/<blank>/empty for {manifest_path}. "
698
+ "Training is being aborted. No checkpoint from this epoch "
699
+ "will be promoted or uploaded."
700
+ )
701
+
702
+ word_errors = (
703
+ total_word_substitutions
704
+ + total_word_deletions
705
+ + total_word_insertions
706
+ )
707
+
708
+ char_errors = (
709
+ total_char_substitutions
710
+ + total_char_deletions
711
+ + total_char_insertions
712
+ )
713
+
714
+ wer = (
715
+ word_errors / total_reference_words
716
+ if total_reference_words
717
+ else 0.0
718
+ )
719
+
720
+ cer = (
721
+ char_errors / total_reference_chars
722
+ if total_reference_chars
723
+ else 0.0
724
+ )
725
+
726
+ return {
727
+ "samples": len(samples),
728
+ "ctc_special_or_empty_outputs": special_or_empty_outputs,
729
+ "ctc_checked_outputs": checked_outputs,
730
+ "ctc_special_or_empty_ratio": special_ratio,
731
+
732
+ "wer": wer,
733
+ "wer_percent": wer * 100.0,
734
+ "word_errors": word_errors,
735
+ "total_reference_words": total_reference_words,
736
+ "total_predicted_words": total_predicted_words,
737
+ "word_substitutions": total_word_substitutions,
738
+ "word_deletions": total_word_deletions,
739
+ "word_insertions": total_word_insertions,
740
+
741
+ "cer": cer,
742
+ "cer_percent": cer * 100.0,
743
+ "char_errors": char_errors,
744
+ "total_reference_characters": total_reference_chars,
745
+ "total_predicted_characters": total_predicted_chars,
746
+ "char_substitutions": total_char_substitutions,
747
+ "char_deletions": total_char_deletions,
748
+ "char_insertions": total_char_insertions,
749
+ }
750
+
751
+
752
+ ###############################################################################
753
+ # PRE-TRAIN CTC HEALTH CHECK
754
+ ###############################################################################
755
+
756
+ def run_pretrain_ctc_health_check(model, batch_size: int) -> None:
757
+ """
758
+ Refuse to begin training unless the clean base model can successfully
759
+ decode BOTH full validation manifests through the exact same CTC path
760
+ used after every epoch.
761
+ """
762
+
763
+ print("\n======================================")
764
+ print("PRE-TRAIN CTC HEALTH CHECK")
765
+ print("======================================")
766
+ print("No training has happened yet.")
767
+ print("Kirtan and Sehaj must both decode successfully before trainer.fit().")
768
+
769
+ print("\nPre-train KIRTAN CTC validation...")
770
+ kirtan = score_validation_manifest(
771
+ model=model,
772
+ manifest_path=KIRTAN_VAL_MANIFEST,
773
+ batch_size=batch_size,
774
+ )
775
+
776
+ print("\nPre-train SEHAJ PAATH CTC validation...")
777
+ sehaj = score_validation_manifest(
778
+ model=model,
779
+ manifest_path=SEHAJ_VAL_MANIFEST,
780
+ batch_size=batch_size,
781
+ )
782
+
783
+ print("\nPRE-TRAIN CTC HEALTH CHECK PASSED")
784
+ print(
785
+ f"Kirtan WER: {kirtan['wer']:.6f} "
786
+ f"({kirtan['wer_percent']:.3f}%)"
787
+ )
788
+ print(
789
+ f"Kirtan CTC special/empty: "
790
+ f"{kirtan['ctc_special_or_empty_outputs']}/"
791
+ f"{kirtan['ctc_checked_outputs']}"
792
+ )
793
+ print(
794
+ f"Sehaj WER: {sehaj['wer']:.6f} "
795
+ f"({sehaj['wer_percent']:.3f}%)"
796
+ )
797
+ print(
798
+ f"Sehaj CTC special/empty: "
799
+ f"{sehaj['ctc_special_or_empty_outputs']}/"
800
+ f"{sehaj['ctc_checked_outputs']}"
801
+ )
802
+ print("✓ Safe to begin training")
803
+
804
+
805
+ ###############################################################################
806
+ # CLOUDFLARE R2 HELPERS
807
+ ###############################################################################
808
+
809
+ def get_r2_config():
810
+ """Read and validate Cloudflare R2 connection settings."""
811
+ account_id = os.environ.get("R2_ACCOUNT_ID")
812
+ access_key_id = os.environ.get("R2_ACCESS_KEY_ID")
813
+ secret_access_key = os.environ.get("R2_SECRET_ACCESS_KEY")
814
+ bucket = os.environ.get("R2_BUCKET")
815
+
816
+ missing = [
817
+ name
818
+ for name, value in (
819
+ ("R2_ACCOUNT_ID", account_id),
820
+ ("R2_ACCESS_KEY_ID", access_key_id),
821
+ ("R2_SECRET_ACCESS_KEY", secret_access_key),
822
+ ("R2_BUCKET", bucket),
823
+ )
824
+ if not value
825
+ ]
826
+
827
+ if missing:
828
+ raise RuntimeError(
829
+ "R2 upload is enabled but these environment variables are "
830
+ f"missing: {', '.join(missing)}"
831
+ )
832
+
833
+ return {
834
+ "account_id": account_id,
835
+ "access_key_id": access_key_id,
836
+ "secret_access_key": secret_access_key,
837
+ "bucket": bucket,
838
+ "endpoint_url": (
839
+ f"https://{account_id}.r2.cloudflarestorage.com"
840
+ ),
841
+ }
842
+
843
+
844
+ def upload_best_checkpoint_to_r2(checkpoint_path: Path) -> None:
845
+ """Upload the completed local best.ckpt to Cloudflare R2."""
846
+ if not R2_UPLOAD_ENABLED:
847
+ return
848
+
849
+ checkpoint_path = Path(checkpoint_path)
850
+
851
+ if not checkpoint_path.is_file():
852
+ raise FileNotFoundError(
853
+ f"Cannot upload missing checkpoint: {checkpoint_path}"
854
+ )
855
+
856
+ try:
857
+ import boto3
858
+ except ImportError as exc:
859
+ raise RuntimeError(
860
+ "R2 upload requires boto3. Install it with: pip install boto3"
861
+ ) from exc
862
+
863
+ config = get_r2_config()
864
+
865
+ client = boto3.client(
866
+ "s3",
867
+ endpoint_url=config["endpoint_url"],
868
+ aws_access_key_id=config["access_key_id"],
869
+ aws_secret_access_key=config["secret_access_key"],
870
+ region_name="auto",
871
+ )
872
+
873
+ last_error = None
874
+
875
+ for attempt in range(1, R2_UPLOAD_RETRIES + 1):
876
+ try:
877
+ print(
878
+ f"Uploading best checkpoint to R2 "
879
+ f"(attempt {attempt}/{R2_UPLOAD_RETRIES})..."
880
+ )
881
+
882
+ client.upload_file(
883
+ str(checkpoint_path),
884
+ config["bucket"],
885
+ R2_OBJECT_KEY,
886
+ )
887
+
888
+ print(
889
+ "✓ R2 upload complete: "
890
+ f"r2://{config['bucket']}/{R2_OBJECT_KEY}"
891
+ )
892
+ return
893
+
894
+ except Exception as exc:
895
+ last_error = exc
896
+ print(
897
+ f"R2 upload attempt {attempt} failed: {exc}"
898
+ )
899
+
900
+ if attempt < R2_UPLOAD_RETRIES:
901
+ time.sleep(R2_RETRY_DELAY_SECONDS)
902
+
903
+ raise RuntimeError(
904
+ "best.ckpt was saved locally, but R2 upload failed after "
905
+ f"{R2_UPLOAD_RETRIES} attempts."
906
+ ) from last_error
907
+
908
+
909
+ ###############################################################################
910
+ # VAST.AI AUTO-DESTROY HELPERS
911
+ ###############################################################################
912
+
913
+ def get_vast_instance_id():
914
+ """
915
+ Return the current Vast instance ID.
916
+
917
+ Vast may expose CONTAINER_ID directly. Older/current environments may
918
+ instead expose VAST_CONTAINERLABEL in the form C.123456.
919
+ """
920
+ container_id = os.environ.get("CONTAINER_ID")
921
+
922
+ if container_id:
923
+ value = str(container_id).strip()
924
+ if value.isdigit():
925
+ return value
926
+
927
+ label = os.environ.get("VAST_CONTAINERLABEL")
928
+
929
+ if label:
930
+ value = str(label).strip()
931
+
932
+ if value.startswith("C."):
933
+ value = value[2:]
934
+
935
+ if value.isdigit():
936
+ return value
937
+
938
+ return None
939
+
940
+
941
+ def validate_vast_auto_destroy_config(test_mode: bool) -> None:
942
+ """
943
+ Fail before a FULL training run if auto-destroy cannot be attempted.
944
+
945
+ Test mode deliberately skips this because --test never destroys.
946
+ """
947
+ if test_mode or not AUTO_DESTROY_VAST:
948
+ return
949
+
950
+ if shutil.which("vastai") is None:
951
+ raise RuntimeError(
952
+ "AUTO_DESTROY_VAST is enabled, but the Vast CLI is not installed. "
953
+ "Install it before the full run with: pip install vastai"
954
+ )
955
+
956
+ instance_id = get_vast_instance_id()
957
+
958
+ if instance_id is None:
959
+ raise RuntimeError(
960
+ "AUTO_DESTROY_VAST is enabled, but the current Vast instance ID "
961
+ "could not be determined from CONTAINER_ID or VAST_CONTAINERLABEL."
962
+ )
963
+
964
+
965
+ def destroy_current_vast_instance() -> None:
966
+ """
967
+ Permanently destroy this Vast instance.
968
+
969
+ This is intentionally called only at the very end of a successful FULL
970
+ run and only after best.ckpt has already been uploaded successfully to R2.
971
+ """
972
+ if not AUTO_DESTROY_VAST:
973
+ print("\nVast auto-destroy is disabled.")
974
+ return
975
+
976
+ instance_id = get_vast_instance_id()
977
+
978
+ if instance_id is None:
979
+ raise RuntimeError(
980
+ "Cannot auto-destroy Vast instance: instance ID is unavailable."
981
+ )
982
+
983
+ command = [
984
+ "vastai",
985
+ "destroy",
986
+ "instance",
987
+ instance_id,
988
+ "-y", # non-interactive confirmation
989
+ ]
990
+
991
+ # Vast images may expose a per-instance API key. If it is present,
992
+ # pass it explicitly. Otherwise the Vast CLI uses its configured key.
993
+ container_api_key = os.environ.get("CONTAINER_API_KEY")
994
+
995
+ if container_api_key:
996
+ command.extend(
997
+ [
998
+ "--api-key",
999
+ container_api_key,
1000
+ ]
1001
+ )
1002
+
1003
+ print(
1004
+ "\n======================================"
1005
+ )
1006
+ print(
1007
+ "AUTO-DESTROYING VAST INSTANCE"
1008
+ )
1009
+ print(
1010
+ "======================================"
1011
+ )
1012
+ print(
1013
+ f"Instance ID: {instance_id}"
1014
+ )
1015
+ print(
1016
+ "best.ckpt has already been uploaded successfully to R2."
1017
+ )
1018
+ print(
1019
+ "This instance and its local files will now be permanently destroyed."
1020
+ )
1021
+
1022
+ # Make sure the final messages are visible before the container disappears.
1023
+ import sys
1024
+ sys.stdout.flush()
1025
+ sys.stderr.flush()
1026
+
1027
+ try:
1028
+ result = subprocess.run(
1029
+ command,
1030
+ check=False,
1031
+ text=True,
1032
+ capture_output=True,
1033
+ timeout=60,
1034
+ )
1035
+ except Exception as exc:
1036
+ raise RuntimeError(
1037
+ f"Failed to execute Vast destroy command: {exc}"
1038
+ ) from exc
1039
+
1040
+ if result.stdout:
1041
+ print(result.stdout.strip())
1042
+
1043
+ if result.returncode != 0:
1044
+ if result.stderr:
1045
+ print(result.stderr.strip())
1046
+
1047
+ raise RuntimeError(
1048
+ "Vast auto-destroy command failed. "
1049
+ "The instance was NOT intentionally destroyed by this script."
1050
+ )
1051
+
1052
+ print(
1053
+ f"✓ Vast destroy request accepted for instance {instance_id}"
1054
+ )
1055
+
1056
+
1057
+
1058
+ ###############################################################################
1059
+ # DURING-TRAINING CTC HEALTH PROBE
1060
+ ###############################################################################
1061
+
1062
+ class CTCHealthProbe(Callback):
1063
+ """Run a fixed CTC probe and overwrite one last-known-good checkpoint."""
1064
+
1065
+ def __init__(
1066
+ self,
1067
+ manifest_path: Path,
1068
+ stable_checkpoint_path: Path,
1069
+ every_optimizer_steps: int = 500,
1070
+ save_every_optimizer_steps: int = 2000,
1071
+ sample_count: int = 4,
1072
+ ):
1073
+ super().__init__()
1074
+ self.manifest_path = Path(manifest_path)
1075
+ self.stable_checkpoint_path = Path(stable_checkpoint_path)
1076
+ self.every_optimizer_steps = int(every_optimizer_steps)
1077
+ self.save_every_optimizer_steps = int(save_every_optimizer_steps)
1078
+ self.sample_count = int(sample_count)
1079
+ self.probe_samples = None
1080
+ self.last_probed_global_step = -1
1081
+
1082
+ if self.every_optimizer_steps <= 0:
1083
+ raise ValueError("CTC probe interval must be > 0")
1084
+ if self.save_every_optimizer_steps <= 0:
1085
+ raise ValueError("Stable checkpoint interval must be > 0")
1086
+ if self.save_every_optimizer_steps % self.every_optimizer_steps != 0:
1087
+ raise ValueError(
1088
+ "Stable checkpoint interval must be a multiple of the CTC probe interval."
1089
+ )
1090
+ if self.sample_count <= 0:
1091
+ raise ValueError("CTC probe sample_count must be > 0")
1092
+
1093
+ def setup(self, trainer, pl_module, stage=None):
1094
+ samples = load_validation_manifest(self.manifest_path)
1095
+ if len(samples) < self.sample_count:
1096
+ raise RuntimeError(
1097
+ f"CTC probe requested {self.sample_count} samples but only "
1098
+ f"{len(samples)} are available."
1099
+ )
1100
+
1101
+ self.probe_samples = samples[:self.sample_count]
1102
+
1103
+ print("\n======================================")
1104
+ print("CTC DURING-TRAINING PROBE ENABLED")
1105
+ print("======================================")
1106
+ print(f"Probe interval: every {self.every_optimizer_steps} optimizer steps")
1107
+ print(
1108
+ f"Stable checkpoint interval: every "
1109
+ f"{self.save_every_optimizer_steps} optimizer steps, after a healthy probe"
1110
+ )
1111
+ print(f"Fixed probe samples: {self.sample_count}")
1112
+ print(f"Rolling stable checkpoint: {self.stable_checkpoint_path}")
1113
+ for i, sample in enumerate(self.probe_samples, 1):
1114
+ print(f" Probe {i}: {sample['audio_filepath']}")
1115
+
1116
+ def _run_probe(self, trainer, pl_module, global_step: int):
1117
+ if not self.probe_samples:
1118
+ raise RuntimeError("CTC probe samples were not initialized.")
1119
+
1120
+ if not hasattr(pl_module, "cur_decoder"):
1121
+ raise RuntimeError("CTC probe expected model.cur_decoder.")
1122
+
1123
+ was_training = pl_module.training
1124
+ previous_decoder = getattr(pl_module, "cur_decoder", None)
1125
+
1126
+ audio_paths = [s["audio_filepath"] for s in self.probe_samples]
1127
+ references = [s["text"] for s in self.probe_samples]
1128
+
1129
+ pl_module.eval()
1130
+ pl_module.cur_decoder = VALIDATION_DECODER
1131
+
1132
+ try:
1133
+ with torch.no_grad():
1134
+ outputs = pl_module.transcribe(
1135
+ audio_paths,
1136
+ batch_size=len(audio_paths),
1137
+ return_hypotheses=False,
1138
+ verbose=False,
1139
+ language_id=LANGUAGE_CODE,
1140
+ )
1141
+ hypotheses = select_primary_transcriptions(
1142
+ outputs,
1143
+ expected_count=len(audio_paths),
1144
+ )
1145
+ normalized = [
1146
+ " ".join(str(v).strip().split())
1147
+ for v in hypotheses
1148
+ ]
1149
+ finally:
1150
+ pl_module.cur_decoder = previous_decoder
1151
+ if was_training:
1152
+ pl_module.train()
1153
+ else:
1154
+ pl_module.eval()
1155
+
1156
+ special_values = {"<unk>", "<blank>", ""}
1157
+ special_count = sum(v in special_values for v in normalized)
1158
+
1159
+ epoch_number = trainer.current_epoch + 1
1160
+ print("\n======================================")
1161
+ print(f"EPOCH {epoch_number} - CTC PROBE @ OPTIMIZER STEP {global_step}")
1162
+ print("======================================")
1163
+ for i, (ref, hyp) in enumerate(zip(references, normalized), 1):
1164
+ print(f" [{i}] REF : {ref}")
1165
+ print(f" [{i}] PRED: {hyp}")
1166
+ print(f"CTC probe special/empty: {special_count}/{len(normalized)}")
1167
+
1168
+ if normalized and special_count == len(normalized):
1169
+ raise RuntimeError(
1170
+ "CTC TRAINING COLLAPSE DETECTED at optimizer step "
1171
+ f"{global_step}: all {len(normalized)} fixed probe hypotheses "
1172
+ f"were <unk>/<blank>/empty: {normalized}."
1173
+ )
1174
+
1175
+ print(f"CTC probe HEALTHY at optimizer step {global_step}")
1176
+
1177
+ # Probe every 500 optimizer steps, but only write the rolling full
1178
+ # Lightning checkpoint every 2000 optimizer steps. A checkpoint is
1179
+ # written only after the probe at that exact step has passed.
1180
+ if global_step % self.save_every_optimizer_steps != 0:
1181
+ print(
1182
+ f"No checkpoint save at step {global_step}; next stable save is "
1183
+ f"on a multiple of {self.save_every_optimizer_steps} optimizer steps."
1184
+ )
1185
+ return
1186
+
1187
+ # Save to a temporary file first, then replace atomically so an
1188
+ # interrupted write does not destroy the previous known-good checkpoint.
1189
+ self.stable_checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
1190
+ temp_path = self.stable_checkpoint_path.with_suffix(
1191
+ self.stable_checkpoint_path.suffix + ".tmp"
1192
+ )
1193
+ trainer.save_checkpoint(str(temp_path))
1194
+ os.replace(temp_path, self.stable_checkpoint_path)
1195
+ print(
1196
+ f"✓ Updated last stable checkpoint at optimizer step {global_step}: "
1197
+ f"{self.stable_checkpoint_path}"
1198
+ )
1199
+
1200
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
1201
+ global_step = int(trainer.global_step)
1202
+
1203
+ if global_step <= 0:
1204
+ return
1205
+ if global_step % self.every_optimizer_steps != 0:
1206
+ return
1207
+ if global_step == self.last_probed_global_step:
1208
+ return
1209
+
1210
+ self.last_probed_global_step = global_step
1211
+ self._run_probe(trainer, pl_module, global_step)
1212
+
1213
+
1214
+ ###############################################################################
1215
+ # POST-EPOCH KIRTAN + SEHAJ WER/CER + BEST CHECKPOINT + EARLY STOPPING
1216
+ ###############################################################################
1217
+
1218
+ class DomainValidationAndEarlyStopping(Callback):
1219
+ """
1220
+ After every TRAINING epoch:
1221
+
1222
+ 1. Explicitly transcribe kirtan validation data.
1223
+ 2. Explicitly transcribe Sehaj Paath validation data.
1224
+ 3. Save BOTH WER and CER to epoch_metrics.json.
1225
+ 4. Use Kirtan CER as the PRIMARY best.ckpt metric.
1226
+ 5. Also accept a Sehaj WER improvement when Kirtan CER is within the
1227
+ configured tolerance of the currently selected best checkpoint.
1228
+ 6. Reset early-stopping patience for either kind of accepted improvement.
1229
+ """
1230
+
1231
+ def __init__(
1232
+ self,
1233
+ metrics_path: Path,
1234
+ best_checkpoint_path: Path,
1235
+ kirtan_manifest: Path,
1236
+ sehaj_manifest: Path,
1237
+ batch_size: int,
1238
+ patience: int = 3,
1239
+ min_delta: float = 0.0001,
1240
+ kirtan_cer_tolerance_for_sehaj: float = 0.005,
1241
+ ):
1242
+ super().__init__()
1243
+ self.metrics_path = Path(metrics_path)
1244
+ self.best_checkpoint_path = Path(best_checkpoint_path)
1245
+ self.kirtan_manifest = Path(kirtan_manifest)
1246
+ self.sehaj_manifest = Path(sehaj_manifest)
1247
+ self.batch_size = int(batch_size)
1248
+ self.patience = patience
1249
+ self.min_delta = min_delta
1250
+ self.kirtan_cer_tolerance_for_sehaj = float(
1251
+ kirtan_cer_tolerance_for_sehaj
1252
+ )
1253
+
1254
+ self.best_kirtan_cer = float("inf")
1255
+ self.best_kirtan_wer = float("inf")
1256
+ self.best_sehaj_wer = float("inf")
1257
+ self.best_epoch = None
1258
+ self.bad_epochs = 0
1259
+ self.history = []
1260
+ self.r2_best_uploaded = False
1261
+
1262
+ def write_history(self):
1263
+ best_kirtan_cer = (
1264
+ None if self.best_kirtan_cer == float("inf") else self.best_kirtan_cer
1265
+ )
1266
+ best_kirtan_wer = (
1267
+ None if self.best_kirtan_wer == float("inf") else self.best_kirtan_wer
1268
+ )
1269
+ best_sehaj_wer = (
1270
+ None if self.best_sehaj_wer == float("inf") else self.best_sehaj_wer
1271
+ )
1272
+
1273
+ data = {
1274
+ "selection_metric": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance",
1275
+ "best_epoch": self.best_epoch,
1276
+ "best_kirtan_cer": best_kirtan_cer,
1277
+ "best_kirtan_cer_percent": (
1278
+ None if best_kirtan_cer is None else best_kirtan_cer * 100.0
1279
+ ),
1280
+ "best_kirtan_wer": best_kirtan_wer,
1281
+ "best_kirtan_wer_percent": (
1282
+ None if best_kirtan_wer is None else best_kirtan_wer * 100.0
1283
+ ),
1284
+ "best_sehaj_wer": best_sehaj_wer,
1285
+ "best_sehaj_wer_percent": (
1286
+ None if best_sehaj_wer is None else best_sehaj_wer * 100.0
1287
+ ),
1288
+ "patience": self.patience,
1289
+ "min_metric_improvement": self.min_delta,
1290
+ "kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj,
1291
+ "kirtan_cer_tolerance_for_sehaj_percent_points": (
1292
+ self.kirtan_cer_tolerance_for_sehaj * 100.0
1293
+ ),
1294
+ "epochs_without_improvement": self.bad_epochs,
1295
+ "history": self.history,
1296
+ }
1297
+
1298
+ self.metrics_path.parent.mkdir(parents=True, exist_ok=True)
1299
+ temp_path = self.metrics_path.with_suffix(self.metrics_path.suffix + ".tmp")
1300
+ with temp_path.open("w", encoding="utf-8") as handle:
1301
+ json.dump(data, handle, indent=2, ensure_ascii=False)
1302
+ temp_path.replace(self.metrics_path)
1303
+
1304
+ def on_train_epoch_end(self, trainer, pl_module):
1305
+ epoch_number = trainer.current_epoch + 1
1306
+
1307
+ print("\n======================================")
1308
+ print("EXPLICIT DOMAIN VALIDATION")
1309
+ print("======================================")
1310
+ print("Scoring KIRTAN validation (CER is primary checkpoint metric)...")
1311
+
1312
+ kirtan = score_validation_manifest(
1313
+ model=pl_module,
1314
+ manifest_path=self.kirtan_manifest,
1315
+ batch_size=self.batch_size,
1316
+ )
1317
+
1318
+ print("Scoring SEHAJ PAATH validation (WER secondary metric)...")
1319
+ sehaj = score_validation_manifest(
1320
+ model=pl_module,
1321
+ manifest_path=self.sehaj_manifest,
1322
+ batch_size=self.batch_size,
1323
+ )
1324
+
1325
+ previous_best_kirtan_cer = self.best_kirtan_cer
1326
+ previous_best_sehaj_wer = self.best_sehaj_wer
1327
+
1328
+ # Selection rule:
1329
+ # 1. Kirtan CER is primary. Improvement >= min_delta always wins.
1330
+ # 2. Sehaj WER may also win when it improves >= min_delta and Kirtan CER
1331
+ # is no more than the configured tolerance worse than the selected best.
1332
+ primary_improved = (
1333
+ kirtan["cer"] < previous_best_kirtan_cer - self.min_delta
1334
+ )
1335
+ sehaj_improved = (
1336
+ sehaj["wer"] < previous_best_sehaj_wer - self.min_delta
1337
+ )
1338
+ kirtan_within_sehaj_tolerance = (
1339
+ kirtan["cer"]
1340
+ <= previous_best_kirtan_cer + self.kirtan_cer_tolerance_for_sehaj
1341
+ )
1342
+ sehaj_tiebreak_improved = (
1343
+ sehaj_improved and kirtan_within_sehaj_tolerance
1344
+ )
1345
+ improved = primary_improved or sehaj_tiebreak_improved
1346
+
1347
+ if primary_improved:
1348
+ improvement_reason = "kirtan_cer_primary"
1349
+ elif sehaj_tiebreak_improved:
1350
+ improvement_reason = "sehaj_wer_with_kirtan_cer_tolerance"
1351
+ else:
1352
+ improvement_reason = None
1353
+
1354
+ if improved:
1355
+ self.best_kirtan_cer = kirtan["cer"]
1356
+ self.best_kirtan_wer = kirtan["wer"]
1357
+ self.best_sehaj_wer = sehaj["wer"]
1358
+ self.best_epoch = epoch_number
1359
+ self.bad_epochs = 0
1360
+
1361
+ self.best_checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
1362
+ pl_module.train()
1363
+ trainer.save_checkpoint(str(self.best_checkpoint_path))
1364
+ upload_best_checkpoint_to_r2(self.best_checkpoint_path)
1365
+
1366
+ if R2_UPLOAD_ENABLED:
1367
+ self.r2_best_uploaded = True
1368
+ else:
1369
+ print("R2 upload skipped: offline test mode.")
1370
+
1371
+ if improvement_reason == "kirtan_cer_primary":
1372
+ print("\nNEW BEST — KIRTAN CER IMPROVED")
1373
+ else:
1374
+ print("\nNEW BEST — SEHAJ WER IMPROVED WITH KIRTAN CER WITHIN TOLERANCE")
1375
+ print(
1376
+ "Kirtan CER is within the allowed "
1377
+ f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} "
1378
+ "percentage-point tolerance."
1379
+ )
1380
+
1381
+ print(f"Epoch: {epoch_number}")
1382
+ print(
1383
+ f"Kirtan CER: {kirtan['cer']:.6f} "
1384
+ f"({kirtan['cer_percent']:.3f}%)"
1385
+ )
1386
+ print(
1387
+ f"Kirtan WER: {kirtan['wer']:.6f} "
1388
+ f"({kirtan['wer_percent']:.3f}%)"
1389
+ )
1390
+ print(
1391
+ f"Sehaj WER: {sehaj['wer']:.6f} "
1392
+ f"({sehaj['wer_percent']:.3f}%)"
1393
+ )
1394
+ print(f"Selection reason: {improvement_reason}")
1395
+ print("Saved best checkpoint:")
1396
+ print(self.best_checkpoint_path)
1397
+ else:
1398
+ self.bad_epochs += 1
1399
+ print("\nNo accepted validation improvement.")
1400
+ print(
1401
+ f"Current Kirtan CER: {kirtan['cer']:.6f} "
1402
+ f"({kirtan['cer_percent']:.3f}%)"
1403
+ )
1404
+ print(
1405
+ f"Best Kirtan CER: {self.best_kirtan_cer:.6f} "
1406
+ f"({self.best_kirtan_cer * 100:.3f}%)"
1407
+ )
1408
+ print(
1409
+ f"Current Kirtan WER: {kirtan['wer']:.6f} "
1410
+ f"({kirtan['wer_percent']:.3f}%)"
1411
+ )
1412
+ print(
1413
+ f"Current Sehaj WER: {sehaj['wer']:.6f} "
1414
+ f"({sehaj['wer_percent']:.3f}%)"
1415
+ )
1416
+ print(
1417
+ f"Best Sehaj WER for selected checkpoint: {self.best_sehaj_wer:.6f} "
1418
+ f"({self.best_sehaj_wer * 100:.3f}%)"
1419
+ )
1420
+ print(
1421
+ f"Epochs without improvement: {self.bad_epochs}/{self.patience}"
1422
+ )
1423
+
1424
+ epoch_record = {
1425
+ "epoch": epoch_number,
1426
+ "kirtan": kirtan,
1427
+ "sehaj": sehaj,
1428
+ "selection_metric": "kirtan_cer_primary_sehaj_wer_with_kirtan_cer_tolerance",
1429
+ "improved": improved,
1430
+ "improvement_reason": improvement_reason,
1431
+ "primary_kirtan_cer_improved": primary_improved,
1432
+ "sehaj_tiebreak_improved": sehaj_tiebreak_improved,
1433
+ "sehaj_wer_improved": sehaj_improved,
1434
+ "kirtan_cer_within_sehaj_tolerance": kirtan_within_sehaj_tolerance,
1435
+ "kirtan_cer_tolerance_for_sehaj": self.kirtan_cer_tolerance_for_sehaj,
1436
+ "best_epoch": self.best_epoch,
1437
+ "best_kirtan_cer": self.best_kirtan_cer,
1438
+ "best_kirtan_cer_percent": self.best_kirtan_cer * 100.0,
1439
+ "best_kirtan_wer": self.best_kirtan_wer,
1440
+ "best_kirtan_wer_percent": self.best_kirtan_wer * 100.0,
1441
+ "best_sehaj_wer": self.best_sehaj_wer,
1442
+ "best_sehaj_wer_percent": self.best_sehaj_wer * 100.0,
1443
+ "epochs_without_improvement": self.bad_epochs,
1444
+ }
1445
+
1446
+ self.history.append(epoch_record)
1447
+ self.write_history()
1448
+
1449
+ print("\n--------------------------------------")
1450
+ print(
1451
+ f"Epoch {epoch_number} KIRTAN: "
1452
+ f"CER {kirtan['cer_percent']:.3f}% | "
1453
+ f"WER {kirtan['wer_percent']:.3f}%"
1454
+ )
1455
+ print(
1456
+ f"Epoch {epoch_number} SEHAJ: "
1457
+ f"WER {sehaj['wer_percent']:.3f}% | "
1458
+ f"CER {sehaj['cer_percent']:.3f}%"
1459
+ )
1460
+ print(
1461
+ "Checkpoint / early-stop rule: KIRTAN CER primary; "
1462
+ "SEHAJ WER can also win when it improves and Kirtan CER is within +"
1463
+ f"{self.kirtan_cer_tolerance_for_sehaj * 100.0:.3f} percentage points "
1464
+ "of the selected best Kirtan CER"
1465
+ )
1466
+ print(f"Metrics JSON: {self.metrics_path}")
1467
+ print("--------------------------------------")
1468
+
1469
+ if self.bad_epochs >= self.patience:
1470
+ print("\n########################################")
1471
+ print("EARLY STOPPING: NO ACCEPTED KIRTAN/SEHAJ IMPROVEMENT")
1472
+ print("########################################")
1473
+ print(
1474
+ f"No accepted primary/secondary improvement for "
1475
+ f"{self.bad_epochs} epochs."
1476
+ )
1477
+ print(f"Best epoch: {self.best_epoch}")
1478
+ print(
1479
+ f"Best Kirtan CER: {self.best_kirtan_cer:.6f} "
1480
+ f"({self.best_kirtan_cer * 100:.3f}%)"
1481
+ )
1482
+ print(
1483
+ f"Best Kirtan WER at selected checkpoint: {self.best_kirtan_wer:.6f} "
1484
+ f"({self.best_kirtan_wer * 100:.3f}%)"
1485
+ )
1486
+ trainer.should_stop = True
1487
+
1488
+
1489
+ ###############################################################################
1490
+ # POST-EPOCH: KEEP LAST TWO EPOCH CHECKPOINTS
1491
+ ###############################################################################
1492
+
1493
+ class LastTwoEpochCheckpoints(Callback):
1494
+ """
1495
+ Save one checkpoint after every completed training epoch.
1496
+
1497
+ Keep only the latest two:
1498
+
1499
+ epoch_004.ckpt
1500
+ epoch_005.ckpt
1501
+
1502
+ When epoch 6 finishes:
1503
+
1504
+ epoch_004.ckpt -> deleted
1505
+ epoch_005.ckpt -> kept
1506
+ epoch_006.ckpt -> saved
1507
+
1508
+ best.ckpt is NOT deleted by this callback.
1509
+ """
1510
+
1511
+ def __init__(
1512
+ self,
1513
+ dirpath: Path,
1514
+ ):
1515
+ super().__init__()
1516
+
1517
+ self.dirpath = Path(
1518
+ dirpath
1519
+ )
1520
+
1521
+ def on_train_epoch_end(
1522
+ self,
1523
+ trainer,
1524
+ pl_module,
1525
+ ):
1526
+
1527
+ self.dirpath.mkdir(
1528
+ parents=True,
1529
+ exist_ok=True,
1530
+ )
1531
+
1532
+ epoch_number = (
1533
+ trainer.current_epoch + 1
1534
+ )
1535
+
1536
+ checkpoint_path = (
1537
+ self.dirpath
1538
+ / f"epoch_{epoch_number:03d}.ckpt"
1539
+ )
1540
+
1541
+ trainer.save_checkpoint(
1542
+ str(checkpoint_path)
1543
+ )
1544
+
1545
+ print(
1546
+ "\nSaved epoch checkpoint:"
1547
+ )
1548
+
1549
+ print(
1550
+ checkpoint_path
1551
+ )
1552
+
1553
+ # Only look at epoch_XXX.ckpt files.
1554
+ # best.ckpt will therefore never be removed.
1555
+ checkpoints = sorted(
1556
+ self.dirpath.glob(
1557
+ "epoch_*.ckpt"
1558
+ )
1559
+ )
1560
+
1561
+ while len(checkpoints) > 2:
1562
+
1563
+ oldest_checkpoint = (
1564
+ checkpoints.pop(0)
1565
+ )
1566
+
1567
+ try:
1568
+ oldest_checkpoint.unlink()
1569
+
1570
+ print(
1571
+ "Removed old epoch checkpoint:"
1572
+ )
1573
+
1574
+ print(
1575
+ oldest_checkpoint
1576
+ )
1577
+
1578
+ except FileNotFoundError:
1579
+ pass
1580
+
1581
+
1582
+ ###############################################################################
1583
+ # DATASET CONFIGURATION
1584
+ ###############################################################################
1585
+
1586
+ def make_dataset_config(
1587
+ manifest_path: Path,
1588
+ shuffle: bool,
1589
+ ):
1590
+ """
1591
+ Build a fresh NeMo dataset configuration for Punjabi ('pa') fine-tuning
1592
+ of the multilingual Gurbani model.
1593
+
1594
+ Fresh train_ds and validation_ds configs are created here at fine-tuning
1595
+ time. The manifests provide lang='pa' and NeMo is asked to return the
1596
+ language ID so the multilingual model uses the Punjabi path.
1597
+ """
1598
+
1599
+ return OmegaConf.create({
1600
+ "manifest_filepath": [
1601
+ str(manifest_path)
1602
+ ],
1603
+ "sample_rate": EXPECTED_SAMPLE_RATE,
1604
+ "batch_size": BATCH_SIZE,
1605
+ "shuffle": shuffle,
1606
+ "num_workers": 2,
1607
+ "pin_memory": False,
1608
+ "persistent_workers": False,
1609
+ "max_duration": None,
1610
+ "min_duration": 0.0,
1611
+ "is_tarred": False,
1612
+ "tarred_audio_filepaths": None,
1613
+ "use_start_end_token": False,
1614
+
1615
+ # IMPORTANT: this is a multilingual model. The manifests contain
1616
+ # lang="pa", and the dataset must return the language ID.
1617
+ "return_language_id": True,
1618
+ })
1619
+
1620
+
1621
+
1622
+ ###############################################################################
1623
+ # PATH VALIDATION
1624
+ ###############################################################################
1625
+
1626
+ def validate_paths() -> None:
1627
+
1628
+ if not DATA_ROOT.exists():
1629
+ raise FileNotFoundError(
1630
+ f"DATA_ROOT does not exist: "
1631
+ f"{DATA_ROOT}"
1632
+ )
1633
+
1634
+ if not DATA_ROOT.is_dir():
1635
+ raise ValueError(
1636
+ f"DATA_ROOT is not a directory: "
1637
+ f"{DATA_ROOT}"
1638
+ )
1639
+
1640
+ if not TRAIN_MANIFEST.exists():
1641
+ raise FileNotFoundError(
1642
+ "Training manifest not found: "
1643
+ f"{TRAIN_MANIFEST}"
1644
+ )
1645
+
1646
+ if not KIRTAN_VAL_MANIFEST.exists():
1647
+ raise FileNotFoundError(
1648
+ "Kirtan validation manifest not found: "
1649
+ f"{KIRTAN_VAL_MANIFEST}"
1650
+ )
1651
+
1652
+ if not SEHAJ_VAL_MANIFEST.exists():
1653
+ raise FileNotFoundError(
1654
+ "Sehaj validation manifest not found: "
1655
+ f"{SEHAJ_VAL_MANIFEST}"
1656
+ )
1657
+
1658
+ if not MODEL_PATH.exists():
1659
+ raise FileNotFoundError(
1660
+ "NeMo model not found: "
1661
+ f"{MODEL_PATH}"
1662
+ )
1663
+
1664
+ if (
1665
+ START_CHECKPOINT_PATH is not None
1666
+ and not START_CHECKPOINT_PATH.exists()
1667
+ ):
1668
+ raise FileNotFoundError(
1669
+ "Starting checkpoint not found: "
1670
+ f"{START_CHECKPOINT_PATH}"
1671
+ )
1672
+
1673
+ if R2_UPLOAD_ENABLED:
1674
+ # Validate required R2 environment variables before long training starts.
1675
+ get_r2_config()
1676
+
1677
+
1678
+ ###############################################################################
1679
+ # LOAD STAGE-2 BEST CHECKPOINT WEIGHTS ONLY
1680
+ ###############################################################################
1681
+
1682
+ def load_start_checkpoint_weights(model) -> None:
1683
+ """Optionally load checkpoint model weights without optimizer state."""
1684
+
1685
+ if START_CHECKPOINT_PATH is None:
1686
+ print(
1687
+ "\nNo starting checkpoint configured. "
1688
+ "Using MODEL_PATH weights directly."
1689
+ )
1690
+ return
1691
+
1692
+ print("\n======================================")
1693
+ print("LOADING OPTIONAL START CHECKPOINT WEIGHTS")
1694
+ print("======================================")
1695
+ print(START_CHECKPOINT_PATH)
1696
+
1697
+ checkpoint = torch.load(
1698
+ str(START_CHECKPOINT_PATH),
1699
+ map_location="cpu",
1700
+ )
1701
+
1702
+ state_dict = checkpoint.get(
1703
+ "state_dict",
1704
+ checkpoint,
1705
+ )
1706
+
1707
+ result = model.load_state_dict(
1708
+ state_dict,
1709
+ strict=False,
1710
+ )
1711
+
1712
+ missing = list(result.missing_keys)
1713
+ unexpected = list(result.unexpected_keys)
1714
+
1715
+ print(f"Missing keys: {len(missing)}")
1716
+ print(f"Unexpected keys: {len(unexpected)}")
1717
+
1718
+ if missing:
1719
+ for key in missing[:30]:
1720
+ print(" MISSING:", key)
1721
+
1722
+ if unexpected:
1723
+ for key in unexpected[:30]:
1724
+ print(" UNEXPECTED:", key)
1725
+
1726
+ if missing or unexpected:
1727
+ raise RuntimeError(
1728
+ "Starting checkpoint does not cleanly match "
1729
+ "the restored .nemo model."
1730
+ )
1731
+
1732
+ print("✓ Starting checkpoint weights loaded cleanly")
1733
+ print("✓ Old optimizer state NOT restored")
1734
+ print("✓ Old scheduler state NOT restored")
1735
+
1736
+
1737
+ ###############################################################################
1738
+ # MODEL INFORMATION
1739
+ ###############################################################################
1740
+
1741
+ def print_model_information(
1742
+ model,
1743
+ ) -> None:
1744
+
1745
+ total_parameters = sum(
1746
+ parameter.numel()
1747
+ for parameter
1748
+ in model.parameters()
1749
+ )
1750
+
1751
+ trainable_parameters = sum(
1752
+ parameter.numel()
1753
+ for parameter
1754
+ in model.parameters()
1755
+ if parameter.requires_grad
1756
+ )
1757
+
1758
+ frozen_parameters = (
1759
+ total_parameters
1760
+ - trainable_parameters
1761
+ )
1762
+
1763
+ print(
1764
+ "\n======================================"
1765
+ )
1766
+
1767
+ print(
1768
+ "MODEL INFORMATION"
1769
+ )
1770
+
1771
+ print(
1772
+ "======================================"
1773
+ )
1774
+
1775
+ print(
1776
+ f"Total parameters: "
1777
+ f"{total_parameters:,}"
1778
+ )
1779
+
1780
+ print(
1781
+ f"Trainable parameters: "
1782
+ f"{trainable_parameters:,}"
1783
+ )
1784
+
1785
+ print(
1786
+ f"Frozen parameters: "
1787
+ f"{frozen_parameters:,}"
1788
+ )
1789
+
1790
+ print(
1791
+ "======================================"
1792
+ )
1793
+
1794
+
1795
+ ###############################################################################
1796
+ # COMMAND LINE
1797
+ ###############################################################################
1798
+
1799
+ def parse_args():
1800
+ parser = argparse.ArgumentParser(
1801
+ description="Fine-tune the Gurbani/Punjabi NeMo ASR model."
1802
+ )
1803
+ parser.add_argument(
1804
+ "--test",
1805
+ action="store_true",
1806
+ help=(
1807
+ "Use the small *-test.json manifests for an infrastructure "
1808
+ "test run. Test artifacts are written under "
1809
+ "/workspace/asr_training_test."
1810
+ ),
1811
+ )
1812
+ parser.add_argument(
1813
+ "--offline",
1814
+ action="store_true",
1815
+ help=(
1816
+ "TEST MODE ONLY: disable all Cloudflare R2 validation/uploads. "
1817
+ "Use as: python train.py --test --offline"
1818
+ ),
1819
+ )
1820
+
1821
+ args = parser.parse_args()
1822
+
1823
+ if args.offline and not args.test:
1824
+ parser.error("--offline is only allowed together with --test")
1825
+
1826
+ return args
1827
+
1828
+
1829
+ ###############################################################################
1830
+ # MAIN
1831
+ ###############################################################################
1832
+
1833
+ def main() -> None:
1834
+
1835
+ args = parse_args()
1836
+ configure_manifests(test_mode=args.test)
1837
+ configure_outputs(
1838
+ test_mode=args.test,
1839
+ offline=args.offline,
1840
+ )
1841
+
1842
+ # Test mode runs only 2 epochs.
1843
+ max_epochs = 2 if args.test else MAX_EPOCHS
1844
+
1845
+ if args.test and args.offline:
1846
+ run_mode = "TEST OFFLINE (*-test.json manifests, 2 epochs, NO R2)"
1847
+ elif args.test:
1848
+ run_mode = "TEST (*-test.json manifests, 2 epochs, separate R2 test checkpoint)"
1849
+ else:
1850
+ run_mode = "FULL"
1851
+
1852
+ print(
1853
+ "\nRUN MODE:",
1854
+ run_mode,
1855
+ )
1856
+
1857
+ validate_vast_auto_destroy_config(
1858
+ test_mode=args.test
1859
+ )
1860
+ validate_paths()
1861
+
1862
+ if not torch.cuda.is_available():
1863
+ raise RuntimeError(
1864
+ "CUDA GPU is not available. This script is configured for Vast GPU training."
1865
+ )
1866
+
1867
+ print("\nGPU:", torch.cuda.get_device_name(0))
1868
+ print("CUDA version:", torch.version.cuda)
1869
+
1870
+ # Create all output directories under /workspace.
1871
+ OUTPUT_ROOT.mkdir(
1872
+ parents=True,
1873
+ exist_ok=True,
1874
+ )
1875
+
1876
+ CHECKPOINT_DIR.mkdir(
1877
+ parents=True,
1878
+ exist_ok=True,
1879
+ )
1880
+
1881
+ print(
1882
+ "======================================"
1883
+ )
1884
+
1885
+ print(
1886
+ "GURBANI PUNJABI (pa) MULTILINGUAL FINE-TUNING"
1887
+ )
1888
+
1889
+ print(
1890
+ "======================================"
1891
+ )
1892
+
1893
+ print(
1894
+ f"Training manifest:"
1895
+ )
1896
+
1897
+ print(
1898
+ TRAIN_MANIFEST
1899
+ )
1900
+
1901
+ print(
1902
+ f"\nKirtan validation manifest:"
1903
+ )
1904
+
1905
+ print(
1906
+ KIRTAN_VAL_MANIFEST
1907
+ )
1908
+
1909
+ print(
1910
+ f"\nSehaj validation manifest:"
1911
+ )
1912
+
1913
+ print(
1914
+ SEHAJ_VAL_MANIFEST
1915
+ )
1916
+
1917
+ print(
1918
+ f"\nBase model:"
1919
+ )
1920
+
1921
+ print(
1922
+ MODEL_PATH
1923
+ )
1924
+
1925
+ print(
1926
+ f"\nStarting checkpoint:"
1927
+ )
1928
+
1929
+ print(
1930
+ START_CHECKPOINT_PATH
1931
+ if START_CHECKPOINT_PATH is not None
1932
+ else "None — using MODEL_PATH only"
1933
+ )
1934
+
1935
+ print(
1936
+ f"\nOutput model:"
1937
+ )
1938
+
1939
+ print(
1940
+ OUTPUT_MODEL
1941
+ )
1942
+
1943
+ print(
1944
+ f"\nEpoch metrics JSON:"
1945
+ )
1946
+
1947
+ print(
1948
+ EPOCH_METRICS_PATH
1949
+ )
1950
+
1951
+ print(
1952
+ f"\nOutput root:"
1953
+ )
1954
+
1955
+ print(
1956
+ OUTPUT_ROOT
1957
+ )
1958
+
1959
+ print(
1960
+ f"\nCheckpoint directory:"
1961
+ )
1962
+
1963
+ print(
1964
+ CHECKPOINT_DIR
1965
+ )
1966
+
1967
+ if R2_UPLOAD_ENABLED:
1968
+ r2_config = get_r2_config()
1969
+ print(
1970
+ f"\nR2 best-checkpoint backup: "
1971
+ f"r2://{r2_config['bucket']}/{R2_OBJECT_KEY}"
1972
+ )
1973
+ else:
1974
+ print(
1975
+ "\nR2 backup: DISABLED (--test --offline)"
1976
+ )
1977
+
1978
+ print(
1979
+ "\nLoading Gurbani/Punjabi multilingual model..."
1980
+ )
1981
+
1982
+ model = (
1983
+ nemo_asr.models.ASRModel.restore_from(
1984
+ restore_path=str(
1985
+ MODEL_PATH
1986
+ )
1987
+ )
1988
+ )
1989
+
1990
+ # Overlay the best Stage-2 learned weights only.
1991
+ load_start_checkpoint_weights(
1992
+ model
1993
+ )
1994
+
1995
+ # --------------------------------------------------------
1996
+ # Verify that the restored multilingual model supports Punjabi ('pa').
1997
+ # Keep the original multilingual vocabulary and language masks intact.
1998
+ # --------------------------------------------------------
1999
+
2000
+ tokenizer_vocab_size = getattr(
2001
+ model.tokenizer,
2002
+ "vocab_size",
2003
+ None,
2004
+ )
2005
+
2006
+ print(
2007
+ "\nLoaded tokenizer vocabulary:",
2008
+ tokenizer_vocab_size,
2009
+ )
2010
+
2011
+ if tokenizer_vocab_size is None:
2012
+ raise RuntimeError(
2013
+ "Could not determine tokenizer vocabulary size."
2014
+ )
2015
+
2016
+ tokenizer_langs = getattr(
2017
+ model.tokenizer,
2018
+ "langs",
2019
+ None,
2020
+ )
2021
+
2022
+ print(
2023
+ "Tokenizer languages:",
2024
+ tokenizer_langs,
2025
+ )
2026
+
2027
+ if tokenizer_langs is None or LANGUAGE_CODE not in tokenizer_langs:
2028
+ raise RuntimeError(
2029
+ f"Restored multilingual tokenizer does not contain "
2030
+ f"Punjabi ({LANGUAGE_CODE!r})."
2031
+ )
2032
+
2033
+ rnnt_vocab_size = getattr(
2034
+ model.decoder,
2035
+ "vocab_size",
2036
+ None,
2037
+ )
2038
+
2039
+ print(
2040
+ "RNNT decoder vocabulary:",
2041
+ rnnt_vocab_size,
2042
+ )
2043
+
2044
+ if rnnt_vocab_size is None:
2045
+ raise RuntimeError(
2046
+ "Could not determine RNNT decoder vocabulary size."
2047
+ )
2048
+
2049
+ if hasattr(model, "ctc_decoder"):
2050
+ ctc_vocab_size = len(
2051
+ getattr(
2052
+ model.ctc_decoder,
2053
+ "vocabulary",
2054
+ [],
2055
+ )
2056
+ )
2057
+
2058
+ print(
2059
+ "CTC decoder vocabulary:",
2060
+ ctc_vocab_size,
2061
+ )
2062
+
2063
+ language_masks = getattr(
2064
+ model.ctc_decoder,
2065
+ "language_masks",
2066
+ None,
2067
+ )
2068
+
2069
+ print(
2070
+ "CTC language masks present:",
2071
+ language_masks is not None,
2072
+ )
2073
+
2074
+ print(
2075
+ f"✓ Multilingual model with Punjabi ({LANGUAGE_CODE!r}) support verified"
2076
+ )
2077
+
2078
+ print_model_information(
2079
+ model
2080
+ )
2081
+
2082
+ print(
2083
+ "\nCreating fresh Punjabi (pa) training "
2084
+ "and validation dataset configs..."
2085
+ )
2086
+
2087
+ train_cfg = make_dataset_config(
2088
+ manifest_path=TRAIN_MANIFEST,
2089
+ shuffle=True,
2090
+ )
2091
+
2092
+ # Validation is performed explicitly by DomainValidationAndEarlyStopping
2093
+ # at on_train_epoch_end().
2094
+ #
2095
+ # IMPORTANT:
2096
+ # NeMo's model.transcribe() still reads model.cfg.validation_ds internally
2097
+ # (for fields such as use_start_end_token), so validation_ds must NOT be None.
2098
+ # We keep a valid Kirtan validation config here, but Lightning's built-in
2099
+ # validation loop remains disabled with limit_val_batches=0 below.
2100
+ validation_cfg = make_dataset_config(
2101
+ manifest_path=KIRTAN_VAL_MANIFEST,
2102
+ shuffle=False,
2103
+ )
2104
+
2105
+ OmegaConf.set_struct(
2106
+ train_cfg,
2107
+ False,
2108
+ )
2109
+
2110
+ OmegaConf.set_struct(
2111
+ validation_cfg,
2112
+ False,
2113
+ )
2114
+
2115
+ with open_dict(
2116
+ model.cfg
2117
+ ):
2118
+
2119
+ model.cfg.train_ds = train_cfg
2120
+ model.cfg.validation_ds = validation_cfg
2121
+ model.cfg.test_ds = None
2122
+
2123
+ # Keep the conservative fine-tuning LR.
2124
+ model.cfg.optim.lr = (
2125
+ LEARNING_RATE
2126
+ )
2127
+
2128
+ print(
2129
+ "\nTraining dataset config:"
2130
+ )
2131
+ print(
2132
+ OmegaConf.to_yaml(
2133
+ model.cfg.train_ds
2134
+ )
2135
+ )
2136
+
2137
+ print(
2138
+ "\nValidation mode: explicit post-epoch transcription "
2139
+ "(Lightning validation disabled)"
2140
+ )
2141
+ print(
2142
+ f"Kirtan validation: {KIRTAN_VAL_MANIFEST}"
2143
+ )
2144
+ print(
2145
+ f"Sehaj validation: {SEHAJ_VAL_MANIFEST}"
2146
+ )
2147
+
2148
+ domain_validation_callback = (
2149
+ DomainValidationAndEarlyStopping(
2150
+ metrics_path=(
2151
+ EPOCH_METRICS_PATH
2152
+ ),
2153
+ best_checkpoint_path=(
2154
+ BEST_CHECKPOINT_PATH
2155
+ ),
2156
+ kirtan_manifest=(
2157
+ KIRTAN_VAL_MANIFEST
2158
+ ),
2159
+ sehaj_manifest=(
2160
+ SEHAJ_VAL_MANIFEST
2161
+ ),
2162
+ batch_size=(
2163
+ BATCH_SIZE
2164
+ ),
2165
+ patience=(
2166
+ EARLY_STOP_PATIENCE
2167
+ ),
2168
+ min_delta=(
2169
+ MIN_WER_IMPROVEMENT
2170
+ ),
2171
+ kirtan_cer_tolerance_for_sehaj=(
2172
+ KIRTAN_CER_TOLERANCE_FOR_SEHAJ
2173
+ ),
2174
+ )
2175
+ )
2176
+
2177
+ checkpoint_callback = (
2178
+ LastTwoEpochCheckpoints(
2179
+ dirpath=(
2180
+ CHECKPOINT_DIR
2181
+ )
2182
+ )
2183
+ )
2184
+
2185
+ print(
2186
+ "\nTraining configuration:"
2187
+ )
2188
+
2189
+ print(
2190
+ f"Batch size: "
2191
+ f"{BATCH_SIZE}"
2192
+ )
2193
+
2194
+ print(
2195
+ f"Gradient accumulation: "
2196
+ f"{ACCUMULATE_GRAD_BATCHES}"
2197
+ )
2198
+
2199
+ print(
2200
+ f"Effective batch size: "
2201
+ f"{BATCH_SIZE * ACCUMULATE_GRAD_BATCHES}"
2202
+ )
2203
+
2204
+ print(
2205
+ f"Learning rate: "
2206
+ f"{LEARNING_RATE}"
2207
+ )
2208
+
2209
+ print(
2210
+ f"Maximum epochs: "
2211
+ f"{max_epochs}"
2212
+ )
2213
+
2214
+ print(
2215
+ f"Early-stop patience: "
2216
+ f"{EARLY_STOP_PATIENCE}"
2217
+ )
2218
+
2219
+ print(
2220
+ f"Minimum WER improvement: "
2221
+ f"{MIN_WER_IMPROVEMENT}"
2222
+ )
2223
+
2224
+ ctc_probe_callback = CTCHealthProbe(
2225
+ manifest_path=KIRTAN_VAL_MANIFEST,
2226
+ stable_checkpoint_path=LAST_STABLE_CHECKPOINT_PATH,
2227
+ every_optimizer_steps=CTC_PROBE_EVERY_OPTIMIZER_STEPS,
2228
+ save_every_optimizer_steps=CTC_STABLE_CHECKPOINT_EVERY_OPTIMIZER_STEPS,
2229
+ sample_count=CTC_PROBE_SAMPLE_COUNT,
2230
+ )
2231
+
2232
+ trainer = pl.Trainer(
2233
+ accelerator="gpu",
2234
+ devices=1,
2235
+ max_epochs=max_epochs,
2236
+ precision=16,
2237
+ accumulate_grad_batches=ACCUMULATE_GRAD_BATCHES,
2238
+ log_every_n_steps=100,
2239
+
2240
+ # IMPORTANT:
2241
+ # Validation is done explicitly in the domain callback after each
2242
+ # training epoch. Disable Lightning's built-in validation loop so
2243
+ # kirtan is not evaluated twice.
2244
+ limit_val_batches=0,
2245
+
2246
+ # Keep Lightning logs under the Vast workspace too.
2247
+ default_root_dir=str(OUTPUT_ROOT / "lightning"),
2248
+
2249
+ # Checkpoints are managed manually by the callbacks below.
2250
+ enable_checkpointing=False,
2251
+
2252
+ callbacks=[
2253
+ EpochProgressBar(),
2254
+ EpochTimer(),
2255
+ ctc_probe_callback,
2256
+ domain_validation_callback,
2257
+ checkpoint_callback,
2258
+ ],
2259
+ )
2260
+
2261
+ model.set_trainer(
2262
+ trainer
2263
+ )
2264
+
2265
+ print(
2266
+ "\nSetting up training dataset..."
2267
+ )
2268
+
2269
+ model.setup_training_data(
2270
+ model.cfg.train_ds
2271
+ )
2272
+
2273
+ # Critical safety gate: verify CTC BEFORE the first optimizer step.
2274
+ # If this raises, trainer.fit() is never entered.
2275
+ run_pretrain_ctc_health_check(
2276
+ model=model,
2277
+ batch_size=BATCH_SIZE,
2278
+ )
2279
+
2280
+ print(
2281
+ "\n======================================"
2282
+ )
2283
+
2284
+ print(
2285
+ "STARTING GURBANI PUNJABI (pa) FINE-TUNING"
2286
+ )
2287
+
2288
+ print(
2289
+ "======================================"
2290
+ )
2291
+
2292
+ try:
2293
+ trainer.fit(
2294
+ model,
2295
+ ckpt_path=(
2296
+ str(START_CHECKPOINT_PATH)
2297
+ if START_CHECKPOINT_PATH is not None
2298
+ else None
2299
+ ),
2300
+ )
2301
+ except Exception:
2302
+ print("\n======================================")
2303
+ print("TRAINING STOPPED / FAILED")
2304
+ print("======================================")
2305
+ print("Last CTC-verified stable checkpoint:")
2306
+ print(LAST_STABLE_CHECKPOINT_PATH)
2307
+ print("\nRestart with the same train.py.")
2308
+ print("It will resume model + optimizer + scheduler state from last_stable.ckpt.")
2309
+ raise
2310
+
2311
+ print(
2312
+ "\n======================================"
2313
+ )
2314
+
2315
+ print(
2316
+ "TRAINING FINISHED"
2317
+ )
2318
+
2319
+ print(
2320
+ "======================================"
2321
+ )
2322
+
2323
+ print("Last CTC-verified stable checkpoint:")
2324
+ print(LAST_STABLE_CHECKPOINT_PATH)
2325
+ print("This same train.py resumes full Lightning state from that checkpoint.")
2326
+
2327
+ if (
2328
+ domain_validation_callback.best_epoch
2329
+ is not None
2330
+ ):
2331
+
2332
+ print(
2333
+ f"Best epoch: "
2334
+ f"{domain_validation_callback.best_epoch}"
2335
+ )
2336
+
2337
+ print(
2338
+ f"Best Kirtan validation WER: "
2339
+ f"{domain_validation_callback.best_kirtan_wer:.6f} "
2340
+ f"({domain_validation_callback.best_kirtan_wer * 100:.3f}%)"
2341
+ )
2342
+
2343
+ print(
2344
+ f"Best checkpoint Sehaj validation WER: "
2345
+ f"{domain_validation_callback.best_sehaj_wer:.6f} "
2346
+ f"({domain_validation_callback.best_sehaj_wer * 100:.3f}%)"
2347
+ )
2348
+
2349
+ print(
2350
+ f"Best checkpoint: "
2351
+ f"{BEST_CHECKPOINT_PATH}"
2352
+ )
2353
+
2354
+ print(
2355
+ "\nLast two epoch checkpoints:"
2356
+ )
2357
+
2358
+ last_checkpoints = sorted(
2359
+ CHECKPOINT_DIR.glob(
2360
+ "epoch_*.ckpt"
2361
+ )
2362
+ )
2363
+
2364
+ for checkpoint in last_checkpoints:
2365
+ print(
2366
+ f" {checkpoint}"
2367
+ )
2368
+
2369
+ print(
2370
+ "\nSaving final training-state "
2371
+ ".nemo model to:"
2372
+ )
2373
+
2374
+ print(
2375
+ OUTPUT_MODEL
2376
+ )
2377
+
2378
+ model.save_to(
2379
+ str(
2380
+ OUTPUT_MODEL
2381
+ )
2382
+ )
2383
+
2384
+ print(
2385
+ "\n======================================"
2386
+ )
2387
+
2388
+ print(
2389
+ "COMPLETE"
2390
+ )
2391
+
2392
+ print(
2393
+ "======================================"
2394
+ )
2395
+
2396
+ print(
2397
+ f"Final model: "
2398
+ f"{OUTPUT_MODEL}"
2399
+ )
2400
+
2401
+ print(
2402
+ f"Best checkpoint: "
2403
+ f"{BEST_CHECKPOINT_PATH}"
2404
+ )
2405
+
2406
+ print(
2407
+ f"Epoch metrics: "
2408
+ f"{EPOCH_METRICS_PATH}"
2409
+ )
2410
+
2411
+ # Never destroy during infrastructure testing.
2412
+ if args.test:
2413
+ if args.offline:
2414
+ print(
2415
+ "\nTEST OFFLINE MODE: no R2 upload was attempted."
2416
+ )
2417
+ print(
2418
+ "TEST MODE: Vast instance will NOT be destroyed."
2419
+ )
2420
+
2421
+ elif not AUTO_DESTROY_VAST:
2422
+ print(
2423
+ "\nAUTO_DESTROY_VAST is disabled; instance will remain running."
2424
+ )
2425
+
2426
+ elif domain_validation_callback.best_epoch is None:
2427
+ print(
2428
+ "\nVast instance NOT destroyed: no best checkpoint was produced."
2429
+ )
2430
+
2431
+ elif not domain_validation_callback.r2_best_uploaded:
2432
+ print(
2433
+ "\nVast instance NOT destroyed: best.ckpt was not confirmed "
2434
+ "uploaded to R2."
2435
+ )
2436
+
2437
+ else:
2438
+ destroy_current_vast_instance()
2439
+
2440
+
2441
+ ###############################################################################
2442
+ # ENTRY POINT
2443
+ ###############################################################################
2444
+
2445
+ if __name__ == "__main__":
2446
+ main()