Download code/asr_ft.py from phamhai/lifemate-data: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/datasets/phamhai/lifemate-data/resolve/main/code/asr_ft.py
- Command line
-
hf download hf://datasets/phamhai/lifemate-data/code/asr_ft.py
-
curl -L -o asr_ft.py https://huggingface.co/datasets/phamhai/lifemate-data/resolve/main/code/asr_ft.py
8.09 kB
| """Fine-tune a Whisper-family ASR (default PhoWhisper-medium) on train audio_text (final turn + history turns). | |
| Dev ids are excluded so asr_eval / agent dev scores stay honest. Light augmentation: speed perturb and additive noise. | |
| usage: python asr_ft.py --root DATA_ROOT --exclude dev300.txt --out ckpt/asr_phowm_ft [--model vinai/PhoWhisper-medium] [--epochs 5] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import time | |
| from pathlib import Path | |
| import librosa | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| from transformers import WhisperForConditionalGeneration, WhisperProcessor | |
| def is_batch_c(r: dict) -> bool: | |
| """generation batch C (dialects, foreign names: highest WER), from context only - see analysis/batches.py""" | |
| t = r["context"]["current_time"] | |
| if t[11:16] == "09:00" and t[5:7] in ("09", "10"): | |
| return False # batch B | |
| return int(r["id"].split("_")[1]) >= 900 | |
| def load_pairs(root: Path, exclude: set[str], oversample_c: int = 1, holdout_every: int = 0): | |
| """returns (train pairs, held-out pairs). holdout_every=N keeps every N-th batch-C sample out of training, as a | |
| guard set: when the whole train set is used, it is the only way to check the new model is not worse.""" | |
| pairs, held, nc = [], [], 0 | |
| for line in open(root / "train" / "train.jsonl", encoding="utf-8"): | |
| r = json.loads(line) | |
| if r["id"] in exclude: | |
| continue | |
| mine = [(root / "train" / r["audio"], r["audio_text"])] | |
| mine += [(root / "train" / t["audio"], t["audio_text"]) for t in r["history"] if t.get("audio")] | |
| if is_batch_c(r): | |
| nc += 1 | |
| if holdout_every and nc % holdout_every == 0: | |
| held += mine | |
| continue | |
| pairs += mine * (oversample_c if is_batch_c(r) else 1) | |
| return pairs, held | |
| def wer_of(model, proc, audio, refs, bs=8): | |
| import re | |
| import unicodedata | |
| norm = lambda t: re.findall(r"[^\W_]+", unicodedata.normalize("NFC", t.lower())) | |
| model.eval() | |
| errs = words = 0 | |
| for i in range(0, len(audio), bs): | |
| feats = proc.feature_extractor(audio[i:i + bs], sampling_rate=16000, return_tensors="pt").input_features.cuda().to(model.dtype) | |
| with torch.no_grad(): | |
| out = proc.batch_decode(model.generate(feats, num_beams=1, max_new_tokens=220), skip_special_tokens=True) | |
| for h, r in zip(out, refs[i:i + bs]): | |
| a, b = norm(r), norm(h) | |
| d = list(range(len(b) + 1)) | |
| for x in range(1, len(a) + 1): | |
| p, d[0] = d[0], x | |
| for y in range(1, len(b) + 1): | |
| p, d[y] = d[y], min(d[y] + 1, d[y - 1] + 1, p + (a[x - 1] != b[y - 1])) | |
| errs += d[-1] | |
| words += len(a) | |
| return errs / max(1, words) | |
| def augment(w: np.ndarray, rng: random.Random) -> np.ndarray: | |
| if rng.random() < 0.5: | |
| w = librosa.effects.time_stretch(w, rate=rng.uniform(0.9, 1.1)) | |
| if rng.random() < 0.4: | |
| snr = rng.uniform(10, 30) | |
| noise = np.random.default_rng(rng.randrange(1 << 30)).standard_normal(len(w)).astype(np.float32) | |
| w = w + noise * (np.sqrt(np.mean(w ** 2) + 1e-8) / 10 ** (snr / 20)) | |
| return w.astype(np.float32) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--root", required=True) | |
| ap.add_argument("--model", default="vinai/PhoWhisper-medium") | |
| ap.add_argument("--exclude", help="ids whose audio must not be used (dev)") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--epochs", type=int, default=5) | |
| ap.add_argument("--bs", type=int, default=16) | |
| ap.add_argument("--lr", type=float, default=1e-5) | |
| ap.add_argument("--oversample-c", type=int, default=1, help="repeat batch-C utterances (dialects, foreign names) this many times") | |
| ap.add_argument("--extra", help="jsonl {audio: abs wav path (16 kHz), text} added to training (TTS synthetic speech)") | |
| ap.add_argument("--holdout-every", type=int, default=20, help="keep every N-th batch-C sample out as a guard set (0 = none)") | |
| a = ap.parse_args() | |
| rng = random.Random(0) | |
| torch.manual_seed(0) | |
| exclude = {l.strip() for l in open(a.exclude)} if a.exclude else set() | |
| pairs, held = load_pairs(Path(a.root), exclude, a.oversample_c, a.holdout_every) | |
| if a.extra: | |
| ex = [json.loads(l) for l in open(a.extra, encoding="utf-8")] | |
| pairs += [(Path(r["audio"]), r["text"]) for r in ex] | |
| print(f"+ {len(ex)} extra (TTS) utterances") | |
| print(f"{len(pairs)} training utterances, {len(held)} held out (guard set)") | |
| audio = [sf.read(p, dtype="float32")[0] for p, _ in pairs] | |
| proc = WhisperProcessor.from_pretrained(a.model) | |
| model = WhisperForConditionalGeneration.from_pretrained(a.model, torch_dtype=torch.float32).cuda() | |
| model.config.forced_decoder_ids = None | |
| model.generation_config.forced_decoder_ids = None | |
| model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) | |
| opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01) | |
| steps = a.epochs * (len(pairs) // a.bs) | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / 100) * max(0.0, 1 - s / steps)) | |
| prefix = proc.tokenizer("", add_special_tokens=True).input_ids[:-1] # decoder start + task/lang tokens of this checkpoint | |
| step, t0 = 0, time.time() | |
| model.train() | |
| for ep in range(a.epochs): | |
| order = list(range(len(pairs))) | |
| rng.shuffle(order) | |
| for b in range(0, len(order) - a.bs + 1, a.bs): | |
| idx = order[b : b + a.bs] | |
| wavs = [augment(audio[i], rng) for i in idx] | |
| feats = proc.feature_extractor(wavs, sampling_rate=16000, return_tensors="pt").input_features.cuda() | |
| labels = [proc.tokenizer(pairs[i][1], add_special_tokens=True).input_ids for i in idx] | |
| n = max(map(len, labels)) | |
| lab = torch.full((len(labels), n), -100, dtype=torch.long) | |
| for j, l in enumerate(labels): | |
| lab[j, : len(l)] = torch.tensor(l) | |
| dec_in = lab[:, :-1].clone() | |
| dec_in[dec_in == -100] = proc.tokenizer.pad_token_id | |
| target = lab[:, 1:].clone() | |
| target[:, : max(0, len(prefix) - 1)] = -100 # do not train on the fixed prefix tokens | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| out = model(input_features=feats, decoder_input_ids=dec_in.cuda()) | |
| loss = torch.nn.functional.cross_entropy(out.logits.float().transpose(1, 2), target.cuda(), ignore_index=-100) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| sched.step() | |
| opt.zero_grad(set_to_none=True) | |
| step += 1 | |
| if step % 50 == 0: | |
| print(f"ep {ep} step {step}/{steps} loss {loss.item():.4f} {time.time() - t0:.0f}s", flush=True) | |
| model.save_pretrained(a.out) | |
| proc.save_pretrained(a.out) | |
| print("saved", a.out) | |
| # guard: never ship an ASR that is worse than the one we started from | |
| if held: | |
| held_audio = [sf.read(p, dtype="float32")[0] for p, _ in held] | |
| refs = [t for _, t in held] | |
| new_wer = wer_of(model.half(), proc, held_audio, refs) | |
| del model | |
| torch.cuda.empty_cache() | |
| base = WhisperForConditionalGeneration.from_pretrained(a.model, torch_dtype=torch.float16).cuda() | |
| base.generation_config.forced_decoder_ids = None | |
| base_wer = wer_of(base, proc, held_audio, refs) | |
| print(f"GUARD held-out batch C: start model WER {100 * base_wer:.2f}% -> new model WER {100 * new_wer:.2f}%", flush=True) | |
| if new_wer >= base_wer: | |
| print("GUARD: new model is not better -> keeping the start model", flush=True) | |
| base.save_pretrained(a.out) | |
| WhisperProcessor.from_pretrained(a.model).save_pretrained(a.out) | |
| open(Path(a.out) / "GUARD_KEPT_START_MODEL", "w").write(f"{base_wer} {new_wer}\n") | |
| if __name__ == "__main__": | |
| main() | |