{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "# 10 · Adapt speech recognition\n",
    "\n",
    "Can an adapter improve recognition under a known acoustic shift and keep clean\n",
    "speech accuracy? Compare the same Whisper checkpoint on clean, channel-corrupted\n",
    "and deterministically conditioned audio. Train a small adapter on the\n",
    "unconditioned corruptions, then test it on the same untouched speakers.\n",
    "\n",
    "Audiobook passages stand in for spoken invoice instructions. This lab tests\n",
    "an acoustic change in English. It makes no claim about call-centre audio,\n",
    "measurements on real invoices, or transfer to other languages."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-02",
   "metadata": {},
   "source": [
    "## 1. Choose the runtime\n",
    "\n",
    "Select a T4 in Colab. The default profile bounds downloads and training. Set\n",
    "COURSE_PROFILE to full before starting the kernel to use the larger profile.\n",
    "Profile names denote workload sizes. Run time and peak memory are measured\n",
    "from the actual execution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import subprocess\n",
    "import sys\n",
    "import torch\n",
    "\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name():\n",
    "    raise RuntimeError(\"Select a Colab T4 for this notebook.\")\n",
    "\n",
    "subprocess.run(\n",
    "    [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"transformers==4.57.1\",\n",
    "     \"datasets==3.6.0\", \"peft==0.17.1\", \"jiwer==4.0.0\", \"soundfile==0.13.1\"],\n",
    "    check=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-04",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter, defaultdict\n",
    "from hashlib import sha256\n",
    "from io import BytesIO\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "import importlib.metadata\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "\n",
    "import jiwer\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib_inline.backend_inline import set_matplotlib_formats\n",
    "import numpy as np\n",
    "import soundfile as sf\n",
    "from datasets import Audio, load_dataset\n",
    "from peft import LoraConfig, get_peft_model\n",
    "from scipy.signal import butter, resample_poly, sosfiltfilt\n",
    "from transformers import WhisperForConditionalGeneration, WhisperProcessor\n",
    "\n",
    "MODEL_ID = \"openai/whisper-base\"\n",
    "MODEL_REVISION = \"e37978b90ca9030d5170a5c07aadb050351a65bb\"\n",
    "DATA_ID = \"openslr/librispeech_asr\"\n",
    "DATA_REVISION = \"71cacbfb7e2354c4226d01e70d77d5fca3d04ba1\"\n",
    "PROFILE = os.environ.get(\"COURSE_PROFILE\", \"profile\")\n",
    "PROFILES = {\n",
    "    \"profile\": {\"train_cap\": 32, \"test_cap\": 24, \"steps\": 16},\n",
    "    \"full\": {\"train_cap\": 128, \"test_cap\": 72, \"steps\": 64},\n",
    "}\n",
    "LIMITS = PROFILES[PROFILE]\n",
    "SEED = 391\n",
    "SAMPLE_RATE = 16_000\n",
    "SNR_DB = 8.0\n",
    "MAX_SECONDS = 12\n",
    "OUT = Path(\"outputs\")\n",
    "OUT.mkdir(exist_ok=True)\n",
    "random.seed(SEED)\n",
    "torch.manual_seed(SEED)\n",
    "set_matplotlib_formats(\"svg\")\n",
    "plt.rcParams[\"svg.fonttype\"] = \"none\"\n",
    "device = torch.device(\"cuda\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-05",
   "metadata": {},
   "source": [
    "## 2. Put one channel on two clean splits\n",
    "\n",
    "Use the published train.100 and test splits of LibriSpeech clean. Stream a\n",
    "bounded prefix with a per-speaker cap and log the selected IDs. This is a\n",
    "deterministic teaching subset rather than a population sample. Test speakers\n",
    "never contribute training clips. Each test clip is used in all five arms.\n",
    "\n",
    "Downsample to 8 kHz, upsample to 16 kHz and then add deterministic noise at\n",
    "a fixed signal-to-noise ratio. The fixed input-conditioning arm applies a\n",
    "speech-band filter without training. It cannot restore discarded frequencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-06",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SMOKE LIBRARY START\n",
    "NUMBER = re.compile(\n",
    "    r\"\\b(?:\\d+(?:\\.\\d+)?|zero|one|two|three|four|five|six|seven|eight|nine|ten|\"\n",
    "    r\"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|\"\n",
    "    r\"nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|\"\n",
    "    r\"hundred|thousand|million)\\b\"\n",
    ")\n",
    "SINGLE_NUMBERS = dict(zip(\n",
    "    \"zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty\".split(),\n",
    "    map(str, range(21)),\n",
    "))\n",
    "SINGLE_NUMBERS.update(dict(zip(\n",
    "    \"thirty forty fifty sixty seventy eighty ninety\".split(), map(str, range(30, 100, 10)),\n",
    ")))\n",
    "\n",
    "\n",
    "def channel_corruption(wave, key, snr_db):\n",
    "    reduced = resample_poly(wave, 1, 2)\n",
    "    restored = resample_poly(reduced, 2, 1)[:len(wave)]\n",
    "    seed = int.from_bytes(sha256(key.encode()).digest()[:8], \"big\")\n",
    "    noise = np.random.default_rng(seed).standard_normal(len(wave))\n",
    "    noise_power = np.mean(noise ** 2)\n",
    "    signal_power = np.mean(restored ** 2)\n",
    "    weight = np.sqrt(signal_power / (10 ** (snr_db / 10) * noise_power))\n",
    "    mixed = restored + weight * noise\n",
    "    # Scale all samples together only when needed, retaining the SNR.\n",
    "    return (mixed / max(1.0, float(np.max(np.abs(mixed))))).astype(np.float32)\n",
    "\n",
    "\n",
    "def conditioned(wave, rate):\n",
    "    sos = butter(4, (300, 3400), btype=\"bandpass\", fs=rate, output=\"sos\")\n",
    "    return sosfiltfilt(sos, wave).astype(np.float32)\n",
    "\n",
    "\n",
    "def normalize(text):\n",
    "    return \" \".join(re.findall(r\"[a-z0-9]+\", text.lower()))\n",
    "\n",
    "\n",
    "def numeric_tokens(text):\n",
    "    return [SINGLE_NUMBERS.get(token, token) for token in NUMBER.findall(text.lower())]\n",
    "# SMOKE LIBRARY END\n",
    "\n",
    "\n",
    "def load_clips(split, cap, per_speaker):\n",
    "    stream = load_dataset(DATA_ID, \"clean\", split=split, revision=DATA_REVISION, streaming=True)\n",
    "    stream = stream.cast_column(\"audio\", Audio(decode=False))\n",
    "    counts = Counter()\n",
    "    clips = []\n",
    "    for raw in stream:\n",
    "        speaker = int(raw[\"speaker_id\"])\n",
    "        if counts[speaker] >= per_speaker:\n",
    "            continue\n",
    "        audio = raw[\"audio\"]\n",
    "        if not audio[\"bytes\"]:\n",
    "            raise RuntimeError(\"The pinned stream did not include audio bytes.\")\n",
    "        wave, rate = sf.read(BytesIO(audio[\"bytes\"]), dtype=\"float32\")\n",
    "        if rate != SAMPLE_RATE or wave.ndim != 1 or not np.isfinite(wave).all():\n",
    "            raise ValueError(f\"Unexpected audio for {raw['id']}\")\n",
    "        if not 1 <= len(wave) / rate <= MAX_SECONDS or not normalize(raw[\"text\"]):\n",
    "            continue\n",
    "        item = {\n",
    "            \"id\": raw[\"id\"], \"speaker\": speaker, \"reference\": raw[\"text\"], \"wave\": wave,\n",
    "            \"shifted\": channel_corruption(wave, raw[\"id\"], SNR_DB),\n",
    "        }\n",
    "        clips.append(item)\n",
    "        counts[speaker] += 1\n",
    "        if len(clips) == cap:\n",
    "            break\n",
    "    if len(clips) != cap:\n",
    "        raise RuntimeError(f\"{split} provided only {len(clips)} matching clips\")\n",
    "    return clips\n",
    "\n",
    "\n",
    "train_clips = load_clips(\"train.100\", LIMITS[\"train_cap\"], per_speaker=8)\n",
    "test_clips = load_clips(\"test\", LIMITS[\"test_cap\"], per_speaker=6)\n",
    "assert {row[\"speaker\"] for row in train_clips}.isdisjoint(row[\"speaker\"] for row in test_clips)\n",
    "print(\"Selected training and test clips:\", len(train_clips), len(test_clips))\n",
    "print(\"Distinct test speakers:\", len({row[\"speaker\"] for row in test_clips}))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-07",
   "metadata": {},
   "source": [
    "## 3. Measure the frozen controls\n",
    "\n",
    "Use greedy English transcription for all arms. Compare the original clean\n",
    "waveform, the degraded channel and the same degraded waveform after applying\n",
    "the fixed filter. The waveform is the only thing that changes in these arms.\n",
    "Report inference time as a ratio of audio duration, excluding waveform prep and\n",
    "feature extraction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-08",
   "metadata": {},
   "outputs": [],
   "source": [
    "processor = WhisperProcessor.from_pretrained(MODEL_ID, revision=MODEL_REVISION)\n",
    "model = WhisperForConditionalGeneration.from_pretrained(\n",
    "    MODEL_ID, revision=MODEL_REVISION, attn_implementation=\"eager\",\n",
    ").to(device)\n",
    "model.eval()\n",
    "\n",
    "\n",
    "def to_features(wave):\n",
    "    return processor.feature_extractor(\n",
    "        wave, sampling_rate=SAMPLE_RATE, return_tensors=\"pt\", return_attention_mask=True,\n",
    "    ).to(device)\n",
    "\n",
    "\n",
    "@torch.inference_mode()\n",
    "def transcribe(model_to_read, wave):\n",
    "    features = to_features(wave)\n",
    "    torch.cuda.synchronize()\n",
    "    start = perf_counter()\n",
    "    token_ids = model_to_read.generate(\n",
    "        **features, language=\"en\", task=\"transcribe\", do_sample=False, num_beams=1,\n",
    "        max_new_tokens=144, return_timestamps=False,\n",
    "    )\n",
    "    torch.cuda.synchronize()\n",
    "    elapsed = perf_counter() - start\n",
    "    return processor.batch_decode(token_ids, skip_special_tokens=True)[0], elapsed\n",
    "\n",
    "\n",
    "def test_arm(model_to_read, arm, waveform):\n",
    "    model_to_read.eval()\n",
    "    transcribe(model_to_read, waveform(test_clips[0]))  # warm up all arms alike\n",
    "    rows = []\n",
    "    for clip in test_clips:\n",
    "        wave = waveform(clip)\n",
    "        prediction, seconds = transcribe(model_to_read, wave)\n",
    "        words = jiwer.process_words(normalize(clip[\"reference\"]), normalize(prediction))\n",
    "        chars = jiwer.process_characters(normalize(clip[\"reference\"]), normalize(prediction))\n",
    "        numbers = numeric_tokens(clip[\"reference\"])\n",
    "        rows.append({\n",
    "            \"arm\": arm, \"id\": clip[\"id\"], \"speaker\": clip[\"speaker\"],\n",
    "            \"reference\": clip[\"reference\"], \"prediction\": prediction,\n",
    "            \"word_edits\": words.substitutions + words.deletions + words.insertions,\n",
    "            \"word_total\": len(normalize(clip[\"reference\"]).split()),\n",
    "            \"char_edits\": chars.substitutions + chars.deletions + chars.insertions,\n",
    "            \"char_total\": len(normalize(clip[\"reference\"])),\n",
    "            \"numeric_exact\": numeric_tokens(prediction) == numbers if numbers else None,\n",
    "            \"decode_seconds\": seconds, \"audio_seconds\": len(wave) / SAMPLE_RATE,\n",
    "        })\n",
    "    return rows\n",
    "\n",
    "\n",
    "rows = []\n",
    "rows += test_arm(model, \"frozen-clean\", lambda c: c[\"wave\"])\n",
    "rows += test_arm(model, \"frozen-corrupted\", lambda c: c[\"shifted\"])\n",
    "rows += test_arm(model, \"frozen-conditioned\", lambda c: conditioned(c[\"shifted\"], SAMPLE_RATE))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-09",
   "metadata": {},
   "source": [
    "## 4. Fit an encoder-decoder adapter\n",
    "\n",
    "Add low-rank updates to query and value projections of the existing attention\n",
    "layers. Keep the base weights and waveform feature extractor fixed. Train on\n",
    "corrupted waveforms and the original supervised transcripts. Trainability is\n",
    "checked before the first step. The optimizer sees only adapter parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-10",
   "metadata": {},
   "outputs": [],
   "source": [
    "adapter = get_peft_model(\n",
    "    model, LoraConfig(r=8, lora_alpha=16, target_modules=[\"q_proj\", \"v_proj\"], lora_dropout=0.05),\n",
    ")\n",
    "trainable = [(name, param) for name, param in adapter.named_parameters() if param.requires_grad]\n",
    "assert trainable and all(\"lora_\" in name for name, _ in trainable)\n",
    "processor.tokenizer.set_prefix_tokens(language=\"en\", task=\"transcribe\", predict_timestamps=False)\n",
    "adapter.train()\n",
    "adapter.config.use_cache = False\n",
    "trainable_parameters = [parameter for _, parameter in trainable]\n",
    "\n",
    "\n",
    "def train_step(clip, optimiser, scaler):\n",
    "    features = to_features(clip[\"shifted\"])\n",
    "    labels = processor.tokenizer(clip[\"reference\"].lower(), return_tensors=\"pt\").input_ids.to(device)\n",
    "    if labels[0, 0].item() == model.config.decoder_start_token_id:\n",
    "        labels = labels[:, 1:]\n",
    "    optimiser.zero_grad(set_to_none=True)\n",
    "    with torch.autocast(device_type=\"cuda\", dtype=torch.float16):\n",
    "        loss = adapter(**features, labels=labels, use_cache=False).loss\n",
    "    if not torch.isfinite(loss):\n",
    "        raise FloatingPointError(f\"Nonfinite ASR loss for {clip['id']}\")\n",
    "    scaler.scale(loss).backward()\n",
    "    scaler.unscale_(optimiser)\n",
    "    torch.nn.utils.clip_grad_norm_(trainable_parameters, 1.0)\n",
    "    previous_scale = scaler.get_scale()\n",
    "    scaler.step(optimiser)\n",
    "    scaler.update()\n",
    "    return loss.item(), scaler.get_scale() >= previous_scale\n",
    "\n",
    "\n",
    "# Run one real update before the scored fit and restore adapter tensors and RNG.\n",
    "initial_trainable = [parameter.detach().cpu().clone() for parameter in trainable_parameters]\n",
    "longest = max(train_clips, key=lambda clip: len(clip[\"reference\"]))\n",
    "probe_optim = torch.optim.AdamW(trainable_parameters, lr=1e-4)\n",
    "torch.cuda.synchronize()\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "profile_started = perf_counter()\n",
    "with torch.random.fork_rng(devices=[torch.cuda.current_device()]):\n",
    "    probe_loss, probe_updated = train_step(longest, probe_optim, torch.amp.GradScaler(\"cuda\", init_scale=1024))\n",
    "torch.cuda.synchronize()\n",
    "preflight = {\n",
    "    \"clip\": longest[\"id\"], \"seconds\": perf_counter() - profile_started,\n",
    "    \"peak_reserved_bytes\": torch.cuda.max_memory_reserved(),\n",
    "    \"peak_allocated_bytes\": torch.cuda.max_memory_allocated(),\n",
    "    \"updated\": probe_updated, \"loss\": probe_loss,\n",
    "}\n",
    "(OUT / \"t4-profile.json\").write_text(json.dumps(preflight, indent=2), encoding=\"utf-8\")\n",
    "print(\"T4 preflight:\", preflight)\n",
    "if not probe_updated or preflight[\"seconds\"] > 30 or preflight[\"peak_reserved_bytes\"] > 12 * 1024**3:\n",
    "    raise RuntimeError(\"Whisper adapter preflight exceeds its update, time or T4 memory guard.\")\n",
    "with torch.no_grad():\n",
    "    for parameter, initial in zip(trainable_parameters, initial_trainable, strict=True):\n",
    "        parameter.copy_(initial)\n",
    "del probe_optim, initial_trainable\n",
    "adapter.zero_grad(set_to_none=True)\n",
    "torch.cuda.empty_cache()\n",
    "\n",
    "optim = torch.optim.AdamW(trainable_parameters, lr=1e-4)\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "scaler = torch.amp.GradScaler(\"cuda\", init_scale=1024)\n",
    "started = perf_counter()\n",
    "history = []\n",
    "rng = random.Random(SEED)\n",
    "order = list(range(len(train_clips)))\n",
    "rng.shuffle(order)\n",
    "for step in range(LIMITS[\"steps\"]):\n",
    "    clip = train_clips[order[step % len(order)]]\n",
    "    loss, updated = train_step(clip, optim, scaler)\n",
    "    history.append({\"step\": step + 1, \"loss\": loss, \"id\": clip[\"id\"], \"optimizer_updated\": updated})\n",
    "torch.cuda.synchronize()\n",
    "training_seconds = perf_counter() - started\n",
    "peak_allocated = torch.cuda.max_memory_allocated()\n",
    "assert any(parameter.detach().count_nonzero().item() for name, parameter in trainable if \".lora_B.\" in name)\n",
    "adapter.save_pretrained(OUT / \"whisper-lora\")\n",
    "adapter.config.use_cache = True\n",
    "rows += test_arm(adapter, \"adapted-clean\", lambda c: c[\"wave\"])\n",
    "rows += test_arm(adapter, \"adapted-corrupted\", lambda c: c[\"shifted\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-11",
   "metadata": {},
   "source": [
    "## 5. Compare paired retention and adaptation\n",
    "\n",
    "Word and character error rates divide all edits by their respective reference\n",
    "token totals. Numeric exactness is a separate restricted diagnostic and reports\n",
    "its own denominator. It folds only single number words such as \"six\" into an\n",
    "equivalent digit. It does not infer that a multiword number phrase and a\n",
    "formatted amount express the same value. Inspect the paired raw transcripts\n",
    "for the failures that would change a financial instruction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-12",
   "metadata": {},
   "outputs": [],
   "source": [
    "def aggregate(records):\n",
    "    numeric = [r[\"numeric_exact\"] for r in records if r[\"numeric_exact\"] is not None]\n",
    "    return {\n",
    "        \"clips\": len(records),\n",
    "        \"wer\": sum(r[\"word_edits\"] for r in records) / sum(r[\"word_total\"] for r in records),\n",
    "        \"cer\": sum(r[\"char_edits\"] for r in records) / sum(r[\"char_total\"] for r in records),\n",
    "        \"numeric_exact\": sum(numeric) / len(numeric) if numeric else None,\n",
    "        \"numeric_denominator\": len(numeric),\n",
    "        \"decode_real_time_factor\": sum(r[\"decode_seconds\"] for r in records) / sum(r[\"audio_seconds\"] for r in records),\n",
    "    }\n",
    "\n",
    "\n",
    "by_arm = defaultdict(list)\n",
    "for row in rows:\n",
    "    by_arm[row[\"arm\"]].append(row)\n",
    "assert all({r[\"id\"] for r in arm} == {c[\"id\"] for c in test_clips} for arm in by_arm.values())\n",
    "scores = {arm: aggregate(records) for arm, records in by_arm.items()}\n",
    "\n",
    "def paired_wer_delta(treatment, control):\n",
    "    treated = {r[\"id\"]: r for r in by_arm[treatment]}\n",
    "    controls = {r[\"id\"]: r for r in by_arm[control]}\n",
    "    speaker_for = {clip[\"id\"]: clip[\"speaker\"] for clip in test_clips}\n",
    "    per_speaker = defaultdict(lambda: [0, 0])\n",
    "    for key, row in treated.items():\n",
    "        edits_words = per_speaker[speaker_for[key]]\n",
    "        edits_words[0] += row[\"word_edits\"] - controls[key][\"word_edits\"]\n",
    "        edits_words[1] += row[\"word_total\"]\n",
    "    deltas, counts = np.asarray([per_speaker[k] for k in sorted(per_speaker)]).T\n",
    "    rng = np.random.default_rng(SEED)\n",
    "    picks = rng.integers(0, len(deltas), size=(2000, len(deltas)))\n",
    "    boot = deltas[picks].sum(axis=1) / counts[picks].sum(axis=1)\n",
    "    return {\"delta\": float(deltas.sum() / counts.sum()),\n",
    "            \"p025\": float(np.percentile(boot, 2.5)), \"p975\": float(np.percentile(boot, 97.5)),\n",
    "            \"speakers\": len(deltas)}\n",
    "\n",
    "\n",
    "paired = {f\"{a}_minus_{b}\": paired_wer_delta(a, b) for a, b in (\n",
    "    (\"frozen-conditioned\", \"frozen-corrupted\"),\n",
    "    (\"adapted-corrupted\", \"frozen-corrupted\"),\n",
    "    (\"adapted-clean\", \"frozen-clean\"),\n",
    ")}\n",
    "\n",
    "report = {\n",
    "    \"gpu\": torch.cuda.get_device_name(), \"cuda\": torch.version.cuda, \"profile\": PROFILE, \"limits\": LIMITS,\n",
    "    \"model\": MODEL_ID, \"model_revision\": MODEL_REVISION, \"data\": DATA_ID, \"data_revision\": DATA_REVISION,\n",
    "    \"seed\": SEED, \"sample_rate\": SAMPLE_RATE, \"snr_db\": SNR_DB, \"training_seconds\": training_seconds,\n",
    "    \"peak_allocated_bytes\": peak_allocated, \"trainable_parameters\": sum(p.numel() for _, p in trainable),\n",
    "    \"optimizer_updates\": sum(r[\"optimizer_updated\"] for r in history),\n",
    "    \"train_ids\": [r[\"id\"] for r in train_clips], \"test_ids\": [r[\"id\"] for r in test_clips],\n",
    "    \"packages\": {package: importlib.metadata.version(package) for package in (\"torch\", \"datasets\", \"transformers\", \"peft\", \"jiwer\")},\n",
    "    \"scores\": scores, \"paired_wer_difference\": paired, \"t4_preflight\": preflight,\n",
    "}\n",
    "(OUT / \"report.json\").write_text(json.dumps(report, indent=2), encoding=\"utf-8\")\n",
    "(OUT / \"examples.jsonl\").write_text(\"\".join(json.dumps(r) + \"\\n\" for r in rows), encoding=\"utf-8\")\n",
    "(OUT / \"train.jsonl\").write_text(\"\".join(json.dumps(r) + \"\\n\" for r in history), encoding=\"utf-8\")\n",
    "print(json.dumps(report, indent=2))\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(9, 4), layout=\"constrained\")\n",
    "ax.bar(list(scores), [v[\"wer\"] for v in scores.values()], color=[\"#6b7c74\", \"#bb7754\", \"#bb7754\", \"#257560\", \"#257560\"])\n",
    "ax.set_ylabel(\"Word error rate\")\n",
    "ax.tick_params(axis=\"x\", rotation=20)\n",
    "fig.savefig(OUT / \"word-errors.svg\")\n",
    "plt.show()\n",
    "\n",
    "corrupted = {item[\"id\"]: item for item in by_arm[\"frozen-corrupted\"]}\n",
    "adapted = {item[\"id\"]: item for item in by_arm[\"adapted-corrupted\"]}\n",
    "worst_for_adapter = max(adapted, key=lambda key: adapted[key][\"word_edits\"] - corrupted[key][\"word_edits\"])\n",
    "print(\"Largest observed word-edit delta, adapted minus frozen, on the corrupted test slice:\")\n",
    "print(json.dumps({\"frozen\": corrupted[worst_for_adapter], \"adapted\": adapted[worst_for_adapter]}, indent=2))\n",
    "example = next(row for row in test_clips if row[\"id\"] == worst_for_adapter)\n",
    "def export_audio_example(clip, name):\n",
    "    waves = {\n",
    "        \"clean\": clip[\"wave\"], \"corrupted\": clip[\"shifted\"],\n",
    "        \"conditioned\": conditioned(clip[\"shifted\"], SAMPLE_RATE),\n",
    "    }\n",
    "    for condition, wave in waves.items():\n",
    "        sf.write(OUT / f\"{name}-{condition}.wav\", wave, SAMPLE_RATE, subtype=\"FLOAT\")\n",
    "    matches = [row for row in rows if row[\"id\"] == clip[\"id\"]]\n",
    "    (OUT / f\"{name}.json\").write_text(json.dumps(matches, indent=2), encoding=\"utf-8\")\n",
    "\n",
    "\n",
    "export_audio_example(test_clips[0], \"opening\")\n",
    "export_audio_example(example, \"regression\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-13",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Open report.json and examples.jsonl together. Compare corrupted frozen with\n",
    "corrupted adapted for the intended improvement, and clean frozen with clean\n",
    "adapted for retention. Conditioning only changes the waveform. Review the\n",
    "transcript where the adapter lost most ground before promoting the adapter.\n",
    "The report uses a paired bootstrap over speakers to keep each speaker’s\n",
    "utterances together. The small profile yields a coarse uncertainty estimate.\n",
    "This small speaker subset, synthetic channel and single training seed\n",
    "provide teaching evidence for these arms rather than a production threshold.\n",
    "\n",
    "[Whisper paper](https://arxiv.org/abs/2212.04356) ·\n",
    "[Whisper API](https://huggingface.co/docs/transformers/v4.57.1/model_doc/whisper) ·\n",
    "[LibriSpeech data](https://www.openslr.org/12/) (CC BY 4.0) ·\n",
    "[Course lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/10-adapt-speech-recognition)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
