LogosAccessibleExpression commited on
Commit
86286d1
Β·
verified Β·
1 Parent(s): 8103614

Upload xlsr1b_optuna_job.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. xlsr1b_optuna_job.py +263 -0
xlsr1b_optuna_job.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch", "transformers", "datasets", "peft", "accelerate",
5
+ # "jiwer", "evaluate", "optuna", "pyctcdecode",
6
+ # "soundfile", "librosa", "huggingface_hub", "requests", "numpy",
7
+ # ]
8
+ # ///
9
+ """
10
+ Optuna LoRA search for XLS-R 1B (CTC) + an n-gram LM decoder.
11
+
12
+ Same recipe as wav2vec2_optuna_job.py β€” same data, same fixed 50-rec val split,
13
+ same KenLM domain decoder, same objective (word accuracy with LM decoding) β€” on
14
+ a 3x larger encoder. wav2vec2-large-960h-lv60-self is 317M and got WER 0.24;
15
+ xls-r-1b is 965M. This is the "does scale help" experiment, run so the ONLY
16
+ variable is the base model.
17
+
18
+ THREE things make this more than a BASE_MODEL swap:
19
+
20
+ 1. XLS-R ships no tokenizer and no CTC head. It is a pretrained encoder only β€”
21
+ 960 hours of nothing, in 128 languages. So the head is randomly initialised
22
+ here and MUST be trained: `modules_to_save=["lm_head"]` puts it alongside the
23
+ LoRA weights in the adapter. The vocab is lifted verbatim from the 960h model
24
+ so every downstream stage (clean(), the tokenizer, the pyctcdecode labels)
25
+ behaves exactly as it did in the run we're comparing against.
26
+
27
+ 2. A randomly initialised head is a real risk to this whole experiment. In the
28
+ 317M run LoRA nudged a head that already knew English; here it has to teach
29
+ one from 255 clips. If XLS-R underperforms, "the head never converged" and
30
+ "the model is wrong for dysarthric speech" look identical from the outside β€”
31
+ so the search space goes up to r=64, and the final run gets more steps.
32
+
33
+ 3. Memory. 965M params in fp32 (CTC's log-sum-exp overflows in fp16, measured in
34
+ the 317M run) does not train on a T4's 16GB. Gradient checkpointing, batch 1
35
+ x accum 16, and a 24GB flavor.
36
+
37
+ SpecAugment is OFF. It cost us NaNs in the 317M search, and masking augmentation
38
+ earns its keep on large corpora, not on 255 recordings from one speaker.
39
+
40
+ Output: best LoRA adapter (with the trained lm_head) + the LM -> HF_PUSH_REPO.
41
+ """
42
+ import os, re, gc, sys, random, subprocess, tempfile, logging
43
+ import numpy as np
44
+ import requests, soundfile as sf, librosa, torch
45
+ from pathlib import Path
46
+ import evaluate
47
+ from datasets import Dataset
48
+ from transformers import (Wav2Vec2ForCTC, Wav2Vec2Processor, Wav2Vec2CTCTokenizer,
49
+ Wav2Vec2FeatureExtractor, Trainer, TrainingArguments)
50
+ from peft import LoraConfig, get_peft_model
51
+ import optuna
52
+ from huggingface_hub import HfApi, login
53
+
54
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
55
+ log = logging.getLogger(__name__)
56
+ subprocess.run(["apt-get", "update", "-q"], check=True)
57
+ subprocess.run(["apt-get", "install", "-y", "-q", "ffmpeg"], check=True)
58
+
59
+ HF_TOKEN = os.environ["HF_TOKEN"]
60
+ HF_PUSH_REPO = os.environ.get("HF_PUSH_REPO", "logosaccessibleexpression/training-scripts")
61
+ HF_PUSH_SUBFOLDER = os.environ.get("HF_PUSH_SUBFOLDER", "xlsr1b-lora-d43df745")
62
+ SUPABASE_URL = os.environ["SUPABASE_URL"]
63
+ SERVICE_ROLE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]
64
+ USER_ID = os.environ["USER_ID"]
65
+ BASE_MODEL = os.environ.get("BASE_MODEL", "facebook/wav2vec2-xls-r-1b")
66
+ # Where the character vocab comes from. Keeping the 960h vocab means the LM
67
+ # decoder, the label cleaning and the reported WER are all directly comparable
68
+ # with the 317M run β€” the point of the experiment.
69
+ VOCAB_MODEL = os.environ.get("VOCAB_MODEL", "facebook/wav2vec2-large-960h-lv60-self")
70
+ # Fewer, longer trials than the 317M search: a 1B step costs ~3x, and an
71
+ # undertrained random head is the failure mode we most need to rule out.
72
+ N_TRIALS = int(os.environ.get("N_TRIALS", "8"))
73
+ TRIAL_STEPS = int(os.environ.get("TRIAL_STEPS", "400"))
74
+ FINAL_STEPS = int(os.environ.get("FINAL_STEPS", "4000"))
75
+ N_VAL = int(os.environ.get("N_VAL", "50"))
76
+ LM_ORDER = int(os.environ.get("LM_ORDER", "3"))
77
+
78
+ TARGET_PRESETS = {
79
+ "minimal": ["q_proj", "v_proj"],
80
+ "attention": ["q_proj", "k_proj", "v_proj", "out_proj"],
81
+ "full": ["q_proj", "k_proj", "v_proj", "out_proj", "intermediate_dense", "output_dense"],
82
+ }
83
+
84
+ login(token=HF_TOKEN)
85
+ # XLS-R's own feature extractor (it normalises and returns an attention mask,
86
+ # which the layer-norm architecture needs); the 960h tokenizer for the vocab.
87
+ processor = Wav2Vec2Processor(
88
+ feature_extractor=Wav2Vec2FeatureExtractor.from_pretrained(BASE_MODEL),
89
+ tokenizer=Wav2Vec2CTCTokenizer.from_pretrained(VOCAB_MODEL),
90
+ )
91
+ log.info(f"base={BASE_MODEL} vocab={len(processor.tokenizer)} from {VOCAB_MODEL}")
92
+ wer_metric = evaluate.load("wer")
93
+
94
+ # ── Data ──────────────────────────────────────────────────────────────────────
95
+ hdrs = {"apikey": SERVICE_ROLE_KEY, "Authorization": f"Bearer {SERVICE_ROLE_KEY}"}
96
+ def sb_get(table, select, filters=None):
97
+ p = {"select": select}; p.update(filters or {})
98
+ r = requests.get(f"{SUPABASE_URL}/rest/v1/{table}", headers=hdrs, params=p); r.raise_for_status()
99
+ return r.json()
100
+
101
+ recs = sb_get("training_recordings", "audio_url,phrase_id", {"user_id": f"eq.{USER_ID}"})
102
+ pmap = {p["id"]: p["text"] for p in sb_get("training_phrases", "id,text")}
103
+ rows = [{"audio_url": r["audio_url"], "text": pmap[r["phrase_id"]]} for r in recs if r["phrase_id"] in pmap]
104
+ log.info(f"Found {len(rows)} recordings")
105
+
106
+ WAV_DIR = Path(tempfile.mkdtemp())
107
+ def download_audio(url, idx):
108
+ r = requests.get(url.replace("/object/public/", "/object/"), headers=hdrs)
109
+ if not r.ok: return None
110
+ ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
111
+ raw = WAV_DIR / f"{idx}.{ext}"; raw.write_bytes(r.content)
112
+ if ext != "wav":
113
+ wav = WAV_DIR / f"{idx}.wav"
114
+ if subprocess.run(["ffmpeg","-y","-i",str(raw),"-ac","1","-ar","16000","-sample_fmt","s16",str(wav)],
115
+ capture_output=True).returncode != 0: return None
116
+ raw = wav
117
+ try: audio, sr = sf.read(str(raw))
118
+ except Exception: return None
119
+ if audio.ndim > 1: audio = audio.mean(axis=1)
120
+ if sr != 16000: audio = librosa.resample(audio, orig_sr=sr, target_sr=16000)
121
+ return audio.astype(np.float32)
122
+
123
+ clean = lambda t: re.sub(r"[^A-Z' ]", "", t.upper()).strip() # 960h vocab is uppercase A-Z + |
124
+ data = []
125
+ for i, row in enumerate(rows):
126
+ a = download_audio(row["audio_url"], i); txt = clean(row["text"])
127
+ if a is None or len(a) < 800 or not txt: continue
128
+ data.append({"audio": a, "ref": txt})
129
+ log.info(f"Usable: {len(data)}")
130
+
131
+ random.seed(42); random.shuffle(data) # same seed as the 317M run == same split
132
+ val_data, train_raw = data[:N_VAL], data[N_VAL:]
133
+ def featurize(d):
134
+ return {"input_values": processor(d["audio"], sampling_rate=16000).input_values[0],
135
+ "labels": processor.tokenizer(d["ref"]).input_ids}
136
+ train_ds = Dataset.from_list([featurize(d) for d in train_raw])
137
+ log.info(f"Train {len(train_ds)} Val {len(val_data)}")
138
+
139
+ # ── Build the domain n-gram LM decoder (KenLM + pyctcdecode) ───────────────────
140
+ def build_lm_decoder():
141
+ texts = set()
142
+ for p in pmap.values():
143
+ c = clean(p).lower()
144
+ if c: texts.add(c)
145
+ try:
146
+ for h in sb_get("transcription_history", "transcript", {"user_id": f"eq.{USER_ID}"}):
147
+ c = clean(h.get("transcript", "")).lower()
148
+ if len(c.split()) >= 2: texts.add(c) # skip 1-word interim-flush fragments
149
+ except Exception as e:
150
+ log.info(f"history fetch skipped: {e}")
151
+ Path("/tmp/corpus.txt").write_text("\n".join(sorted(texts)))
152
+ log.info(f"LM corpus: {len(texts)} lines, {LM_ORDER}-gram")
153
+ subprocess.run("apt-get install -y -q build-essential cmake git "
154
+ "libboost-all-dev libbz2-dev liblzma-dev zlib1g-dev", shell=True, check=True)
155
+ subprocess.run("git clone --depth 1 https://github.com/kpu/kenlm.git /tmp/klm", shell=True, check=True)
156
+ subprocess.run("cmake -S /tmp/klm -B /tmp/klm/build -DCMAKE_BUILD_TYPE=Release && "
157
+ "cmake --build /tmp/klm/build -j4 --target lmplz build_binary", shell=True, check=True)
158
+ subprocess.run(["uv", "pip", "install", "--python", sys.executable,
159
+ "https://github.com/kpu/kenlm/archive/master.zip"], check=True)
160
+ subprocess.run(f"/tmp/klm/build/bin/lmplz -o {LM_ORDER} --discount_fallback "
161
+ f"< /tmp/corpus.txt > /tmp/lm.arpa", shell=True, check=True)
162
+ from pyctcdecode import build_ctcdecoder
163
+ vocab = {k.lower(): v for k, v in sorted(processor.tokenizer.get_vocab().items(), key=lambda x: x[1])}
164
+ return build_ctcdecoder(labels=list(vocab.keys()), kenlm_model_path="/tmp/lm.arpa")
165
+
166
+ decoder = build_lm_decoder()
167
+
168
+ class CTCCollator:
169
+ def __call__(self, feats):
170
+ inp = processor.feature_extractor.pad([{"input_values": f["input_values"]} for f in feats], return_tensors="pt")
171
+ lab = processor.tokenizer.pad([{"input_ids": f["labels"]} for f in feats], return_tensors="pt")
172
+ inp["labels"] = lab["input_ids"].masked_fill(lab.attention_mask.ne(1), -100)
173
+ return inp
174
+ collator = CTCCollator()
175
+
176
+ def score(model):
177
+ """Word accuracy (0-1) on the fixed val set, decoded WITH the n-gram LM."""
178
+ model.eval(); preds, refs = [], []
179
+ dev = next(model.parameters()).device
180
+ with torch.no_grad():
181
+ for d in val_data:
182
+ iv = processor(d["audio"], sampling_rate=16000, return_tensors="pt").input_values.to(dev)
183
+ logits = model(iv).logits[0].cpu().numpy().astype("float32")
184
+ preds.append(decoder.decode(logits).lower().strip())
185
+ refs.append(d["ref"].lower())
186
+ w = wer_metric.compute(predictions=preds, references=refs)
187
+ return max(0.0, 1.0 - w), w
188
+
189
+ def build(r, dropout, modules_key):
190
+ m = Wav2Vec2ForCTC.from_pretrained(
191
+ BASE_MODEL,
192
+ vocab_size=len(processor.tokenizer), # XLS-R has no head; this makes one
193
+ ctc_loss_reduction="mean",
194
+ # Long input, short label -> infinite loss. Zeroing those keeps one bad
195
+ # clip from poisoning the whole run, which matters more here because a
196
+ # random head produces garbage alignments for the first few hundred steps.
197
+ ctc_zero_infinity=True,
198
+ apply_spec_augment=False, # cost us NaNs at 317M; useless at n=255
199
+ pad_token_id=processor.tokenizer.pad_token_id,
200
+ ignore_mismatched_sizes=True,
201
+ )
202
+ m.freeze_feature_encoder()
203
+ m.config.ctc_zero_infinity = True
204
+ peft = get_peft_model(m, LoraConfig(
205
+ r=r, lora_alpha=r * 2, lora_dropout=dropout,
206
+ target_modules=TARGET_PRESETS[modules_key], bias="none",
207
+ # The head is randomly initialised, so it is not a thing LoRA can adapt β€”
208
+ # it has to be trained and saved outright, or the adapter is useless on
209
+ # its own.
210
+ modules_to_save=["lm_head"],
211
+ ))
212
+ # Gradient checkpointing needs an input that requires grad, and a frozen
213
+ # feature encoder doesn't give it one.
214
+ peft.enable_input_require_grads()
215
+ return peft
216
+
217
+ def train_args(out, lr, warmup, wd, steps):
218
+ # fp32 (CTC overflows in fp16). 965M params only fits with checkpointing and
219
+ # batch 1; accum 16 keeps the effective batch at the 317M run's 16.
220
+ return TrainingArguments(out, per_device_train_batch_size=1, gradient_accumulation_steps=16,
221
+ learning_rate=lr, warmup_steps=warmup, weight_decay=wd, max_steps=steps,
222
+ fp16=False, gradient_checkpointing=True, logging_steps=100, save_strategy="no",
223
+ report_to=[], remove_unused_columns=False, label_names=["labels"])
224
+
225
+ # ── Optuna ────────────────────────────────────────────────────────────────────
226
+ def objective(trial):
227
+ # r goes to 64 here: the 317M search liked r=32 with an English head already
228
+ # in place, and this one is also paying for a head from scratch.
229
+ r = trial.suggest_categorical("r", [16, 32, 64])
230
+ dropout = trial.suggest_categorical("lora_dropout", [0.0, 0.05])
231
+ lr = trial.suggest_float("learning_rate", 5e-5, 5e-4, log=True)
232
+ modules = trial.suggest_categorical("target_modules", ["attention", "full"])
233
+ warmup = trial.suggest_categorical("warmup_steps", [50, 100])
234
+ wd = trial.suggest_categorical("weight_decay", [0.0, 0.01])
235
+ log.info(f"=== Trial {trial.number} r={r} drop={dropout} lr={lr:.2e} mods={modules} warm={warmup} wd={wd}")
236
+ m = build(r, dropout, modules)
237
+ Trainer(model=m, args=train_args(f"/tmp/t{trial.number}", lr, warmup, wd, TRIAL_STEPS),
238
+ train_dataset=train_ds, data_collator=collator).train()
239
+ acc, w = score(m)
240
+ log.info(f"Trial {trial.number} -> acc={acc:.3f} WER={w:.3f} (n-gram LM)")
241
+ del m; gc.collect(); torch.cuda.empty_cache()
242
+ return acc
243
+
244
+ optuna.logging.set_verbosity(optuna.logging.WARNING)
245
+ study = optuna.create_study(direction="maximize", study_name="xlsr1b_lora_ngram")
246
+ study.optimize(objective, n_trials=N_TRIALS)
247
+ best = study.best_params
248
+ log.info(f"BEST acc={study.best_value:.3f} params={best}")
249
+
250
+ # ── Final: best config, FINAL_STEPS on ALL data; push adapter + LM ────────────
251
+ full_ds = Dataset.from_list([featurize(d) for d in data])
252
+ m = build(best["r"], best["lora_dropout"], best["target_modules"])
253
+ Trainer(model=m, args=train_args("/tmp/xlsr_best", best["learning_rate"], best["warmup_steps"],
254
+ best["weight_decay"], FINAL_STEPS), train_dataset=full_ds, data_collator=collator).train()
255
+ acc, w = score(m)
256
+ log.info(f"final acc={acc:.3f} WER={w:.3f} (317M reference: WER 0.24)")
257
+
258
+ SAVE = "/tmp/xlsr_adapter"
259
+ m.save_pretrained(SAVE); processor.save_pretrained(SAVE)
260
+ import shutil; shutil.copy("/tmp/lm.arpa", f"{SAVE}/lm.arpa") # ship the LM with the adapter
261
+ HfApi(token=HF_TOKEN).upload_folder(folder_path=SAVE, repo_id=HF_PUSH_REPO,
262
+ repo_type="dataset", path_in_repo=HF_PUSH_SUBFOLDER)
263
+ log.info(f"Pushed adapter + LM to {HF_PUSH_REPO}/{HF_PUSH_SUBFOLDER} (val acc {acc:.3f} WER {w:.3f})")