{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4dd69fb7",
   "metadata": {},
   "source": [
    "# 11 · Adapt expressive speech\n",
    "\n",
    "Generate a short spoken message with a prescribed delivery. Freeze the text\n",
    "encoder and codec, and train low-rank updates to decoder cross-attention.\n",
    "Assess whether the new decoder preserves the message and moves the delivery\n",
    "rate toward the held-out reference. Use identical text and descriptions on\n",
    "the frozen and adapted sides.\n",
    "\n",
    "## 1. Start with a T4 profile\n",
    "\n",
    "The default profile trains on four short clips and synthesizes two paired\n",
    "examples in full precision. It is a compatibility and measurement run.\n",
    "The full profile increases the sample and optimizer budgets. The notebook\n",
    "records timings and peak allocation for the actual run.\n",
    "\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/11-adapt-expressive-speech)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed5ac0e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import subprocess\n",
    "import sys\n",
    "import torch\n",
    "\n",
    "# Parler and Whisper run in PyTorch on this runtime.\n",
    "os.environ[\"USE_TF\"] = \"0\"\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",
    "PARLER_CODE = \"d108732cd57788ec86bc857d99a6cabd66663d68\"\n",
    "AUDIOTOOLS_CODE = \"348ebf2034ce24e2a91a553e3171cb00c0c71678\"\n",
    "subprocess.run(\n",
    "    [sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n",
    "     \"transformers==4.46.1\", \"datasets==3.6.0\", \"sentencepiece==0.2.1\",\n",
    "     \"soundfile==0.13.1\", \"jiwer==4.0.0\", \"descript-audio-codec==1.0.0\",\n",
    "     f\"descript-audiotools @ https://github.com/descriptinc/audiotools/archive/{AUDIOTOOLS_CODE}.tar.gz\",\n",
    "     \"protobuf==4.25.8\"],\n",
    "    check=True,\n",
    ")\n",
    "subprocess.run(\n",
    "    [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"--no-deps\",\n",
    "     f\"https://github.com/huggingface/parler-tts/archive/{PARLER_CODE}.tar.gz\"],\n",
    "    check=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3c3e4c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter, defaultdict\n",
    "from io import BytesIO\n",
    "from math import gcd, sqrt\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "import csv\n",
    "import gc\n",
    "import importlib.metadata\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "\n",
    "import jiwer\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import soundfile as sf\n",
    "from datasets import Audio, load_dataset\n",
    "from IPython.display import FileLink, display\n",
    "from parler_tts import ParlerTTSForConditionalGeneration\n",
    "from parler_tts.modeling_parler_tts import build_delay_pattern_mask\n",
    "from scipy.signal import resample_poly\n",
    "from torch import nn\n",
    "from transformers import AutoTokenizer, WhisperForConditionalGeneration, WhisperProcessor\n",
    "\n",
    "MODEL_ID = \"parler-tts/parler-tts-mini-v1\"\n",
    "REVISION = \"0392b9451a601e528fd863bbb0598431fee810d9\"\n",
    "AUDIO_ID = \"parler-tts/libritts_r_filtered\"\n",
    "AUDIO_REVISION = \"8980d6531fa6404290be3ff52aeb55b95b9c8c93\"\n",
    "DESC_ID = \"parler-tts/libritts-r-filtered-speaker-descriptions\"\n",
    "DESC_REVISION = \"0ffbb79e07eaea6d9b191ac93a430f9264b3131d\"\n",
    "ASR_ID = \"openai/whisper-base\"\n",
    "ASR_REVISION = \"e37978b90ca9030d5170a5c07aadb050351a65bb\"\n",
    "PROFILE = os.environ.get(\"COURSE_PROFILE\", \"profile\")\n",
    "LIMITS = {\n",
    "    \"profile\": {\"train\": 4, \"test\": 2, \"steps\": 4, \"max_new_tokens\": 340, \"scan\": 512},\n",
    "    \"full\": {\"train\": 32, \"test\": 12, \"steps\": 64, \"max_new_tokens\": 390, \"scan\": 4096},\n",
    "}[PROFILE]\n",
    "SEED = 411\n",
    "MAX_SECONDS = 3.1\n",
    "MIN_SECONDS = 1.0\n",
    "OUT = Path(\"results\")\n",
    "AUDIO_OUT = OUT / \"audio\"\n",
    "AUDIO_OUT.mkdir(parents=True, exist_ok=True)\n",
    "device = torch.device(\"cuda\")\n",
    "random.seed(SEED)\n",
    "torch.manual_seed(SEED)\n",
    "get_ipython().run_line_magic(\"config\", \"InlineBackend.figure_formats = ['svg']\")\n",
    "free_bytes, _ = torch.cuda.mem_get_info()\n",
    "if free_bytes < 12 * 2**30:\n",
    "    raise RuntimeError(\"The FP32 Parler-TTS profile needs at least 12 GiB free on T4.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fd90300",
   "metadata": {},
   "source": [
    "## 2. Join the text, audio and delivery description\n",
    "\n",
    "Use the published train.clean.100 and test.clean partitions of LibriTTS-R\n",
    "filtered. Stream a bounded prefix and join descriptions by exact utterance\n",
    "ID. Use no more than two clips per training speaker and one per test speaker;\n",
    "assert the speaker populations are disjoint. Keep each held-out description\n",
    "fixed across both decoders.\n",
    "\n",
    "The checkpoint's training data includes LibriTTS-R. This split measures\n",
    "what changes during our adapter stage. It cannot establish whether the\n",
    "checkpoint saw a recording at pretraining time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7472421",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SMOKE LIBRARY START\n",
    "def canonical_text(text):\n",
    "    return \" \".join(re.findall(r\"[a-z0-9]+\", text.lower()))\n",
    "\n",
    "\n",
    "def at_rate(wave, before, after):\n",
    "    if before == after:\n",
    "        return wave\n",
    "    divisor = gcd(before, after)\n",
    "    return resample_poly(wave, after // divisor, before // divisor).astype(np.float32)\n",
    "\n",
    "\n",
    "def label_audio_codes(codes, bos, eos, delay_pattern):\n",
    "    if codes.ndim != 4 or codes.shape[0] != 1:\n",
    "        raise ValueError(f\"Expected one codec frame group, got {tuple(codes.shape)}\")\n",
    "    tokens = codes[0].long()\n",
    "    batch, codebooks, _ = tokens.shape\n",
    "    first = torch.full((batch, codebooks, 1), bos, device=tokens.device, dtype=torch.long)\n",
    "    inputs = torch.cat([first, tokens], dim=-1)\n",
    "    _, pattern = delay_pattern(\n",
    "        inputs, bos_token_id=bos, pad_token_id=eos,\n",
    "        max_length=inputs.shape[-1] + codebooks, num_codebooks=codebooks,\n",
    "    )\n",
    "    filled = torch.where(pattern == -1, eos, pattern)\n",
    "    return filled[:, 1:].reshape(batch, codebooks, -1).transpose(1, 2).contiguous()\n",
    "\n",
    "\n",
    "class LinearLoRA(nn.Module):\n",
    "    def __init__(self, base, rank=8, alpha=16):\n",
    "        super().__init__()\n",
    "        self.base = base\n",
    "        self.down = nn.Linear(base.in_features, rank, bias=False, device=base.weight.device, dtype=base.weight.dtype)\n",
    "        self.up = nn.Linear(rank, base.out_features, bias=False, device=base.weight.device, dtype=base.weight.dtype)\n",
    "        nn.init.kaiming_uniform_(self.down.weight, a=sqrt(5))\n",
    "        nn.init.zeros_(self.up.weight)\n",
    "        self.scale = alpha / rank\n",
    "\n",
    "    @property\n",
    "    def weight(self):\n",
    "        return self.base.weight\n",
    "\n",
    "    def forward(self, hidden):\n",
    "        return self.base(hidden) + self.scale * self.up(self.down(hidden))\n",
    "\n",
    "\n",
    "def attach_decoder_lora(model, rank, alpha):\n",
    "    model.requires_grad_(False)\n",
    "    targets = [\n",
    "        (name, layer) for name, layer in model.named_modules()\n",
    "        if isinstance(layer, nn.Linear) and name.startswith(\"decoder.\")\n",
    "        and \".encoder_attn.\" in name and name.endswith((\".q_proj\", \".v_proj\"))\n",
    "    ]\n",
    "    if not targets:\n",
    "        raise RuntimeError(\"No decoder cross-attention query or value projections found.\")\n",
    "    for name, layer in targets:\n",
    "        parent, _, field = name.rpartition(\".\")\n",
    "        setattr(model.get_submodule(parent), field, LinearLoRA(layer, rank, alpha))\n",
    "    return [name for name, _ in targets]\n",
    "\n",
    "\n",
    "def update_decoder(model, fields, labels, trainable, optimizer):\n",
    "    optimizer.zero_grad(set_to_none=True)\n",
    "    loss = model(**fields, labels=labels, use_cache=False).loss\n",
    "    if not torch.isfinite(loss):\n",
    "        raise RuntimeError(\"Nonfinite Parler codec loss.\")\n",
    "    loss.backward()\n",
    "    norm = nn.utils.clip_grad_norm_(list(trainable.values()), max_norm=1.0, error_if_nonfinite=True)\n",
    "    optimizer.step()\n",
    "    return {\"loss\": loss.item(), \"gradient_norm\": norm.item()}\n",
    "\n",
    "\n",
    "def restore_profile_weights(trainable, initial):\n",
    "    with torch.no_grad():\n",
    "        for name, parameter in trainable.items():\n",
    "            parameter.copy_(initial[name])\n",
    "            parameter.grad = None\n",
    "# SMOKE LIBRARY END"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b23bcdb3",
   "metadata": {},
   "source": [
    "### What makes an audio example eligible?\n",
    "\n",
    "Use one admissible clip per selected test speaker, and preserve the annotated source\n",
    "and text in the input manifest. Reject mismatched descriptions before creating labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8075bdd6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_aligned(split, count, cap_per_speaker):\n",
    "    audio_stream = load_dataset(AUDIO_ID, \"clean\", split=split, revision=AUDIO_REVISION, streaming=True)\n",
    "    desc_stream = load_dataset(DESC_ID, \"clean\", split=split, revision=DESC_REVISION, streaming=True)\n",
    "    audio_stream = audio_stream.cast_column(\"audio\", Audio(decode=False))\n",
    "    clips = {}\n",
    "    speaker_counts = Counter()\n",
    "    for raw in audio_stream.take(LIMITS[\"scan\"]):\n",
    "        speaker = str(raw[\"speaker_id\"])\n",
    "        text = raw[\"text_normalized\"].strip()\n",
    "        if speaker_counts[speaker] >= cap_per_speaker or not (4 <= len(canonical_text(text).split()) <= 14):\n",
    "            continue\n",
    "        content = raw[\"audio\"][\"bytes\"]\n",
    "        if content is None:\n",
    "            raise RuntimeError(\"The pinned stream did not include audio bytes.\")\n",
    "        wave, rate = sf.read(BytesIO(content), dtype=\"float32\")\n",
    "        if wave.ndim != 1 or not MIN_SECONDS <= len(wave) / rate <= MAX_SECONDS or not np.isfinite(wave).all():\n",
    "            continue\n",
    "        clip_id = str(raw[\"id\"])\n",
    "        assert clip_id not in clips\n",
    "        clips[clip_id] = {\"id\": clip_id, \"speaker\": speaker, \"text\": text, \"wave\": wave, \"rate\": rate}\n",
    "        speaker_counts[speaker] += 1\n",
    "        if len(clips) == count:\n",
    "            break\n",
    "    if len(clips) != count:\n",
    "        raise RuntimeError(f\"{split}: found only {len(clips)} admissible audio clips in the bounded stream.\")\n",
    "\n",
    "    remaining = set(clips)\n",
    "    for meta in desc_stream.take(20000):\n",
    "        clip_id = str(meta[\"id\"])\n",
    "        if clip_id in remaining:\n",
    "            description = (meta[\"text_description\"] or \"\").strip()\n",
    "            if (str(meta[\"speaker_id\"]) != clips[clip_id][\"speaker\"] or not description\n",
    "                    or canonical_text(meta[\"text\"]) != canonical_text(clips[clip_id][\"text\"])):\n",
    "                raise RuntimeError(f\"Invalid metadata join for {clip_id}\")\n",
    "            clips[clip_id][\"description\"] = description\n",
    "            remaining.remove(clip_id)\n",
    "            if not remaining:\n",
    "                break\n",
    "    if remaining:\n",
    "        raise RuntimeError(f\"{split}: no matching metadata for {sorted(remaining)} in the bounded stream.\")\n",
    "    return list(clips.values())\n",
    "\n",
    "\n",
    "train = load_aligned(\"train.clean.100\", LIMITS[\"train\"], cap_per_speaker=2)\n",
    "test = load_aligned(\"test.clean\", LIMITS[\"test\"], cap_per_speaker=1)\n",
    "assert {clip[\"speaker\"] for clip in train}.isdisjoint(clip[\"speaker\"] for clip in test)\n",
    "clip_manifest = {\n",
    "    split: [{k: clip[k] for k in (\"id\", \"speaker\", \"text\", \"description\")} for clip in rows]\n",
    "    for split, rows in ((\"train\", train), (\"test\", test))\n",
    "}\n",
    "(OUT / \"input-manifest.json\").write_text(json.dumps(clip_manifest, indent=2), encoding=\"utf-8\")\n",
    "print({split: len(rows) for split, rows in clip_manifest.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4bc3a79",
   "metadata": {},
   "source": [
    "## 3. Encode the training targets once\n",
    "\n",
    "The DAC encoder turns a waveform into nine codebook streams. The next-token\n",
    "target offsets each stream by one more position than its predecessor. Use\n",
    "the official delay-mask routine and save the cached CPU labels. Keep the\n",
    "codec and text encoder in evaluation mode for every training step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9927a5b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)\n",
    "model = ParlerTTSForConditionalGeneration.from_pretrained(\n",
    "    MODEL_ID, revision=REVISION, torch_dtype=torch.float32, attn_implementation=\"eager\",\n",
    "    use_safetensors=True,\n",
    ").eval().requires_grad_(False).to(device)\n",
    "sample_rate = model.audio_encoder.config.sampling_rate\n",
    "codebooks = model.decoder.num_codebooks\n",
    "bos_token = model.config.decoder_start_token_id\n",
    "eos_token = model.config.decoder.eos_token_id\n",
    "assert codebooks == 9 and bos_token == 1025 and eos_token == 1024\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "codec_start = perf_counter()\n",
    "with torch.no_grad():\n",
    "    for clip in train + test:\n",
    "        samples = at_rate(clip[\"wave\"], clip[\"rate\"], sample_rate)\n",
    "        tensor = torch.from_numpy(samples)[None, None, :].to(device)\n",
    "        codec = model.audio_encoder.encode(\n",
    "            input_values=tensor, n_quantizers=codebooks, sample_rate=sample_rate, return_dict=True,\n",
    "        )\n",
    "        clip[\"labels\"] = label_audio_codes(codec.audio_codes, bos_token, eos_token, build_delay_pattern_mask).cpu()\n",
    "        assert clip[\"labels\"].shape[-1] == codebooks\n",
    "torch.cuda.synchronize()\n",
    "codec_seconds = perf_counter() - codec_start\n",
    "torch.save({clip[\"id\"]: clip[\"labels\"] for clip in train + test}, OUT / \"codec-labels.pt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1b827f4",
   "metadata": {},
   "source": [
    "### Where do the descriptions and target text go?\n",
    "\n",
    "The free-text description conditions the encoder. The words to pronounce enter through\n",
    "the prompt input. Cache the audio targets before either decoder is scored."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3ad9ea5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def prompt_fields(clip):\n",
    "    description = tokenizer(clip[\"description\"], return_tensors=\"pt\").to(device)\n",
    "    prompt = tokenizer(clip[\"text\"], return_tensors=\"pt\").to(device)\n",
    "    return {\"input_ids\": description.input_ids, \"attention_mask\": description.attention_mask,\n",
    "            \"prompt_input_ids\": prompt.input_ids, \"prompt_attention_mask\": prompt.attention_mask}\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def heldout_losses():\n",
    "    model.eval()\n",
    "    return {clip[\"id\"]: model(**prompt_fields(clip), labels=clip[\"labels\"].to(device), use_cache=False).loss.item()\n",
    "            for clip in test}\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def synthesize(arm):\n",
    "    model.eval()\n",
    "    rows = []\n",
    "    for clip in test:\n",
    "        fields = prompt_fields(clip)\n",
    "        torch.cuda.synchronize()\n",
    "        start = perf_counter()\n",
    "        generated = model.generate(\n",
    "            **fields, do_sample=False, max_new_tokens=LIMITS[\"max_new_tokens\"],\n",
    "            return_dict_in_generate=True, output_scores=True,\n",
    "        )\n",
    "        torch.cuda.synchronize()\n",
    "        seconds = perf_counter() - start\n",
    "        duration_samples = int(generated.audios_length[0])\n",
    "        wave = generated.sequences[0, :duration_samples].float().cpu().numpy()\n",
    "        if not len(wave) or not np.isfinite(wave).all():\n",
    "            raise RuntimeError(f\"Synthesis returned invalid samples for {clip['id']}\")\n",
    "        path = AUDIO_OUT / f\"{clip['id']}-{arm}.wav\"\n",
    "        sf.write(path, wave, sample_rate, subtype=\"FLOAT\")\n",
    "        rows.append({\"id\": clip[\"id\"], \"arm\": arm, \"audio_path\": str(path), \"synthesis_seconds\": seconds,\n",
    "                     \"generation_steps\": len(generated.scores),\n",
    "                     \"hit_token_cap\": len(generated.scores) >= LIMITS[\"max_new_tokens\"]})\n",
    "    return rows"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb1acc23",
   "metadata": {},
   "source": [
    "### Will the longest prepared update fit on T4?\n",
    "\n",
    "Perform one real decoder update before the scored run. Measure the synchronised step\n",
    "and its allocator peaks. Restore the initial adapter weights and discard the optimiser\n",
    "state so the profile does not contribute to the scored update budget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b47f1d75",
   "metadata": {},
   "outputs": [],
   "source": [
    "rank, alpha = 8, 16\n",
    "targets = attach_decoder_lora(model, rank, alpha)\n",
    "trainable = {name: parameter for name, parameter in model.named_parameters() if parameter.requires_grad}\n",
    "assert len(trainable) == 2 * len(targets)\n",
    "assert all(\".encoder_attn.\" in name and name.endswith((\"down.weight\", \"up.weight\")) for name in trainable)\n",
    "initial_weights = {name: parameter.detach().cpu().clone() for name, parameter in trainable.items()}\n",
    "probe_optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5)\n",
    "probe = max(train, key=lambda clip: (clip[\"labels\"].shape[1], len(clip[\"description\"])))\n",
    "model.train()\n",
    "model.audio_encoder.eval()\n",
    "model.text_encoder.eval()\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "torch.cuda.synchronize()\n",
    "started = perf_counter()\n",
    "probe_metrics = update_decoder(model, prompt_fields(probe), probe[\"labels\"].to(device), trainable, probe_optimizer)\n",
    "torch.cuda.synchronize()\n",
    "t4_profile = {\n",
    "    \"utterance_id\": probe[\"id\"], \"codec_sequence_length\": probe[\"labels\"].shape[1],\n",
    "    \"seconds\": perf_counter() - started,\n",
    "    \"peak_allocated_gib\": torch.cuda.max_memory_allocated() / 2**30,\n",
    "    \"peak_reserved_gib\": torch.cuda.max_memory_reserved() / 2**30,\n",
    "    **probe_metrics,\n",
    "}\n",
    "restore_profile_weights(trainable, initial_weights)\n",
    "del probe_optimizer, initial_weights\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()\n",
    "torch.manual_seed(SEED)\n",
    "(OUT / \"11-t4-profile.json\").write_text(json.dumps(t4_profile, indent=2), encoding=\"utf-8\")\n",
    "print(json.dumps(t4_profile, indent=2))\n",
    "if (t4_profile[\"seconds\"] > 50 or t4_profile[\"peak_allocated_gib\"] > 11\n",
    "        or t4_profile[\"peak_reserved_gib\"] > min(13, free_bytes / 2**30 - 1)):\n",
    "    raise RuntimeError(\"T4 training profile exceeds its registered limits.\")\n",
    "torch.cuda.reset_peak_memory_stats()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f71b0fdd",
   "metadata": {},
   "source": [
    "### What does the frozen decoder sound like?\n",
    "\n",
    "The initial adapters add zero to the frozen model's projections. Synthesize on the common\n",
    "inputs before fitting the restored weights and save the original recordings for comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7b3bc4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "for clip in test:\n",
    "    path = AUDIO_OUT / f\"{clip['id']}-reference.wav\"\n",
    "    sf.write(path, clip[\"wave\"], clip[\"rate\"], subtype=\"FLOAT\")\n",
    "\n",
    "torch.cuda.synchronize()\n",
    "teacher_forced_frozen = heldout_losses()\n",
    "rows = synthesize(\"frozen\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2e15dc",
   "metadata": {},
   "source": [
    "## 4. Adapt how the decoder reads its conditioning\n",
    "\n",
    "Add low-rank matrices to query and value projections in decoder\n",
    "cross-attention. The zero-initialized output matrix leaves the original\n",
    "function unchanged before training. Optimize codec token likelihood under\n",
    "the original delivery description and text. Keep one utterance per step\n",
    "and train in FP32 to avoid FP16 overflow in the frozen text encoder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "beb6577f",
   "metadata": {},
   "outputs": [],
   "source": [
    "optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5)\n",
    "train_rows = []\n",
    "schedule = list(train)\n",
    "random.Random(SEED).shuffle(schedule)\n",
    "model.train()\n",
    "model.audio_encoder.eval()\n",
    "model.text_encoder.eval()\n",
    "train_start = perf_counter()\n",
    "for step in range(LIMITS[\"steps\"]):\n",
    "    clip = schedule[step % len(schedule)]\n",
    "    metrics = update_decoder(model, prompt_fields(clip), clip[\"labels\"].to(device), trainable, optimizer)\n",
    "    train_rows.append({\"step\": step + 1, \"id\": clip[\"id\"], **metrics})\n",
    "torch.cuda.synchronize()\n",
    "training_seconds = perf_counter() - train_start\n",
    "assert any(p.detach().count_nonzero().item() for name, p in trainable.items() if name.endswith(\"up.weight\"))\n",
    "\n",
    "parameter_count = sum(p.numel() for p in trainable.values())\n",
    "torch.save(\n",
    "    {\"rank\": rank, \"alpha\": alpha, \"targets\": targets, \"model\": MODEL_ID, \"revision\": REVISION,\n",
    "     \"weights\": {name: p.detach().cpu() for name, p in trainable.items()}},\n",
    "    OUT / \"decoder-cross-attention-lora.pt\",\n",
    ")\n",
    "teacher_forced_adapted = heldout_losses()\n",
    "rows.extend(synthesize(\"adapted\"))\n",
    "tts_peak = torch.cuda.max_memory_allocated()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aac3f51d",
   "metadata": {},
   "source": [
    "## 5. Score intelligibility and timing separately\n",
    "\n",
    "Release Parler-TTS from the GPU before loading Whisper. Transcribe every\n",
    "generated and recorded clip with the same frozen settings. ASR error is an\n",
    "intelligibility proxy subject to the recognizer's own mistakes. Compare\n",
    "absolute error in expected words per minute against the recorded reference.\n",
    "Duration and rate do not certify fidelity to the entire style description."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6ec2a3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "del model, optimizer, trainable, codec, tensor\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "\n",
    "asr_processor = WhisperProcessor.from_pretrained(ASR_ID, revision=ASR_REVISION)\n",
    "asr = WhisperForConditionalGeneration.from_pretrained(\n",
    "    ASR_ID, revision=ASR_REVISION, torch_dtype=torch.float16,\n",
    ").eval().requires_grad_(False).to(device)\n",
    "asr.generation_config.forced_decoder_ids = None\n",
    "asr_rate = asr_processor.feature_extractor.sampling_rate\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def transcribe(wave, rate):\n",
    "    seconds = len(wave) / rate\n",
    "    if seconds < 0.1:\n",
    "        return \"\"\n",
    "    inputs = asr_processor(\n",
    "        at_rate(wave, rate, asr_rate), sampling_rate=asr_rate, return_tensors=\"pt\",\n",
    "        return_attention_mask=True,\n",
    "    ).to(device, dtype=torch.float16)\n",
    "    tokens = asr.generate(**inputs, language=\"en\", task=\"transcribe\", do_sample=False,\n",
    "                          num_beams=1, max_new_tokens=72)\n",
    "    return asr_processor.batch_decode(tokens, skip_special_tokens=True)[0]\n",
    "\n",
    "\n",
    "test_by_id = {clip[\"id\"]: clip for clip in test}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e69f9120",
   "metadata": {},
   "source": [
    "### What changed on the same utterance?\n",
    "\n",
    "Preserve each utterance ID across the frozen, adapted and recorded arms. Log transcript,\n",
    "approximate rate, duration and generation-cap status for individual comparisons."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54c6c4fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "for clip in test:\n",
    "    rows.append({\"id\": clip[\"id\"], \"arm\": \"recorded-reference\",\n",
    "                 \"audio_path\": str(AUDIO_OUT / f\"{clip['id']}-reference.wav\"),\n",
    "                 \"synthesis_seconds\": None, \"generation_steps\": None, \"hit_token_cap\": None})\n",
    "\n",
    "losses = {\"frozen\": teacher_forced_frozen, \"adapted\": teacher_forced_adapted}\n",
    "for row in rows:\n",
    "    clip = test_by_id[row[\"id\"]]\n",
    "    wave, rate = sf.read(row[\"audio_path\"], dtype=\"float32\")\n",
    "    transcript = transcribe(wave, rate)\n",
    "    reference = canonical_text(clip[\"text\"])\n",
    "    found = jiwer.process_words(reference, canonical_text(transcript))\n",
    "    ref_duration = len(clip[\"wave\"]) / clip[\"rate\"]\n",
    "    duration = len(wave) / rate\n",
    "    words = len(reference.split())\n",
    "    words_per_minute = 60 * words / duration if duration >= .1 else None\n",
    "    ref_words_per_minute = 60 * words / ref_duration\n",
    "    row.update({\n",
    "        \"text\": clip[\"text\"], \"description\": clip[\"description\"], \"asr\": transcript,\n",
    "        \"reference_words\": words, \"word_edits\": found.substitutions + found.deletions + found.insertions,\n",
    "        \"audio_seconds\": duration, \"reference_seconds\": ref_duration,\n",
    "        \"absolute_duration_error\": abs(duration - ref_duration),\n",
    "        \"words_per_minute\": words_per_minute,\n",
    "        \"absolute_rate_error\": abs(words_per_minute - ref_words_per_minute) if words_per_minute is not None else None,\n",
    "        \"real_time_factor\": row[\"synthesis_seconds\"] / duration if row[\"synthesis_seconds\"] is not None else None,\n",
    "        \"teacher_forced_codec_loss\": losses.get(row[\"arm\"], {}).get(row[\"id\"]),\n",
    "    })\n",
    "\n",
    "\n",
    "def summarize(arm_rows):\n",
    "    rates = [row[\"absolute_rate_error\"] for row in arm_rows if row[\"absolute_rate_error\"] is not None]\n",
    "    factors = [row[\"real_time_factor\"] for row in arm_rows if row[\"real_time_factor\"] is not None]\n",
    "    return {\n",
    "        \"clips\": len(arm_rows),\n",
    "        \"asr_wer\": sum(r[\"word_edits\"] for r in arm_rows) / sum(r[\"reference_words\"] for r in arm_rows),\n",
    "        \"mean_absolute_duration_error\": float(np.mean([r[\"absolute_duration_error\"] for r in arm_rows])),\n",
    "        \"median_absolute_rate_error\": float(np.median(rates)) if rates else None,\n",
    "        \"rate_examples\": len(rates),\n",
    "        \"median_synthesis_real_time_factor\": float(np.median(factors)) if factors else None,\n",
    "        \"clips_at_token_cap\": sum(r[\"hit_token_cap\"] is True for r in arm_rows),\n",
    "        \"clips_under_100ms\": sum(r[\"audio_seconds\"] < .1 for r in arm_rows),\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} == set(test_by_id) for arm in by_arm.values())\n",
    "scores = {arm: summarize(arm_rows) for arm, arm_rows in by_arm.items()}\n",
    "report = {\n",
    "    \"gpu\": torch.cuda.get_device_name(), \"cuda\": torch.version.cuda, \"profile\": PROFILE, \"limits\": LIMITS,\n",
    "    \"checkpoint\": [MODEL_ID, REVISION], \"asr_checkpoint\": [ASR_ID, ASR_REVISION],\n",
    "    \"audio_data\": [AUDIO_ID, AUDIO_REVISION], \"descriptions\": [DESC_ID, DESC_REVISION],\n",
    "    \"parler_code\": PARLER_CODE, \"audiotools_code\": AUDIOTOOLS_CODE,\n",
    "    \"seed\": SEED, \"codec_seconds\": codec_seconds, \"training_seconds\": training_seconds,\n",
    "    \"training_parameters\": parameter_count, \"adapter_targets\": targets, \"t4_profile\": t4_profile,\n",
    "    \"tts_peak_allocated_bytes\": tts_peak, \"asr_peak_allocated_bytes\": torch.cuda.max_memory_allocated(),\n",
    "    \"packages\": {p: importlib.metadata.version(p) for p in\n",
    "                 (\"torch\", \"transformers\", \"datasets\", \"parler-tts\", \"descript-audio-codec\", \"descript-audiotools\", \"jiwer\")},\n",
    "    \"scores\": scores,\n",
    "}\n",
    "(OUT / \"report.json\").write_text(json.dumps(report, indent=2), encoding=\"utf-8\")\n",
    "(OUT / \"train.jsonl\").write_text(\"\".join(json.dumps(r) + \"\\n\" for r in train_rows), encoding=\"utf-8\")\n",
    "with (OUT / \"clips.csv\").open(\"w\", newline=\"\", encoding=\"utf-8\") as f:\n",
    "    csv_writer = csv.DictWriter(f, fieldnames=list(rows[0]))\n",
    "    csv_writer.writeheader()\n",
    "    csv_writer.writerows(rows)\n",
    "print(json.dumps(report, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ada90ebc",
   "metadata": {},
   "source": [
    "### Which findings should you take into a listening review?\n",
    "\n",
    "Start with the intended words. Listen across all three WAV files for pacing and\n",
    "intelligibility. At two held-out examples, describe each utterance alongside the aggregate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2d848b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), layout=\"constrained\")\n",
    "names = [\"Recorded\", \"Frozen\", \"Adapted\"]\n",
    "keys = [\"recorded-reference\", \"frozen\", \"adapted\"]\n",
    "colors = [\"#6b7c74\", \"#bb7754\", \"#257560\"]\n",
    "axes[0].bar(names, [scores[key][\"asr_wer\"] for key in keys], color=colors)\n",
    "axes[0].set_ylabel(\"Word error rate from frozen ASR\")\n",
    "axes[1].bar(names, [scores[key][\"mean_absolute_duration_error\"] for key in keys], color=colors)\n",
    "axes[1].set_ylabel(\"Mean absolute duration error (seconds)\")\n",
    "fig.savefig(OUT / \"speech-comparison.svg\")\n",
    "plt.show()\n",
    "\n",
    "case_id = test[0][\"id\"]\n",
    "print(test[0][\"text\"])\n",
    "print(test[0][\"description\"])\n",
    "for arm in keys:\n",
    "    example = next(row for row in by_arm[arm] if row[\"id\"] == case_id)\n",
    "    print(arm, example[\"audio_seconds\"], example[\"asr\"])\n",
    "    display(FileLink(example[\"audio_path\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3f92d9e",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Listen to both synthetic clips beside the recording. Check text fidelity,\n",
    "pacing and whether audio stopped at the token budget. If the two generated\n",
    "voices differ in rate, confirm that closeness to the reference coincides with\n",
    "the intended delivery. A short run with public audiobook clips demonstrates\n",
    "the measurement setup. Release confidence would require representative\n",
    "licensed recordings, more speakers and independent listening ratings.\n",
    "\n",
    "[Parler-TTS model card](https://huggingface.co/parler-tts/parler-tts-mini-v1) ·\n",
    "[Official training guide](https://github.com/huggingface/parler-tts/tree/d108732cd57788ec86bc857d99a6cabd66663d68/training) ·\n",
    "[LibriTTS-R paper](https://arxiv.org/abs/2305.18802) ·\n",
    "[Course lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/11-adapt-expressive-speech)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
