Sukhpal Singh commited on
Commit
287e52d
·
verified ·
1 Parent(s): 2ede4d3

Added sehaj paath train stream nemo

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