{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "78589f93",
   "metadata": {},
   "source": [
    "# Advanced LLM Fine Tuning · Lesson 2 · Audit synthetic training data\n",
    "\n",
    "You maintain an invoice parser for accounts payable. An invoice says USD, but a proposed\n",
    "training target says GBP. Both currencies fit the schema. If that mismatch reaches the\n",
    "next fine-tune, the parser can learn to send a correct-looking amount in the wrong currency.\n",
    "\n",
    "What does fixing noisy labels buy when the inputs and training budget stay fixed?\n",
    "Run on a Colab T4. Budget about 25–35 minutes, including setup and evaluation.\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/1-build-the-data/02-audit-synthetic-data)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "462111b2",
   "metadata": {},
   "source": [
    "## Runtime\n",
    "\n",
    "Select a Tesla T4 in Colab. Each branch runs in sequence. Model downloads use the\n",
    "public Hugging Face checkpoint, pinned by revision. The shared runtime can reuse\n",
    "its weight cache. The material below embeds the invoice fixtures and training code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1a4446a0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CompletedProcess(args=['/usr/bin/python3', '-m', 'pip', 'install', '-q', 'transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0'], returncode=0)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import subprocess\n",
    "import sys\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *['transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0']], check=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bbc0d4b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GPU: Tesla T4\n",
      "PyTorch: 2.14.1+cu130\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name(0):\n",
    "    raise RuntimeError(\"Select a Tesla T4 runtime in Colab before running this notebook.\")\n",
    "print(\"GPU:\", torch.cuda.get_device_name(0))\n",
    "print(\"PyTorch:\", torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f19b4ce",
   "metadata": {},
   "source": [
    "## Invoice fixtures\n",
    "\n",
    "The synthetic input and gold record come from a versioned scenario. The scorer compares\n",
    "generated JSON with the gold record independently of model training. The release set stays\n",
    "out of this lesson."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "48147493",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Versioned synthetic invoices and independent record scoring for the course.\"\"\"\n",
    "\n",
    "from __future__ import annotations\n",
    "\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "from collections import Counter\n",
    "from dataclasses import dataclass\n",
    "from datetime import date, timedelta\n",
    "from typing import Any\n",
    "\n",
    "CATALOG_VERSION = \"course-invoice-v1\"\n",
    "SPLIT_SIZES = {\"train\": 576, \"dev\": 72, \"familiar\": 96, \"novel\": 96, \"independent\": 48, \"release\": 120}\n",
    "VISIBLE_CONTRACT = (\n",
    "    \"Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, \"\n",
    "    \"currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, \"\n",
    "    \"tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. \"\n",
    "    \"Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.\"\n",
    ")\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Line:\n",
    "    description: str\n",
    "    quantity: int\n",
    "    unit_minor: int\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Invoice:\n",
    "    key: str\n",
    "    family: str\n",
    "    supplier: str\n",
    "    issued_on: str\n",
    "    currency: str\n",
    "    items: tuple[Line, ...]\n",
    "    tax_minor: int | None\n",
    "    locale: str\n",
    "    split: str\n",
    "    layout: str = \"register\"\n",
    "    printed_total_minor: int | None = None\n",
    "\n",
    "\n",
    "def invoice_record(invoice: Invoice) -> dict[str, Any]:\n",
    "    subtotal = sum(line.quantity * line.unit_minor for line in invoice.items)\n",
    "    total = subtotal + invoice.tax_minor if invoice.tax_minor is not None else None\n",
    "    if invoice.printed_total_minor is not None:\n",
    "        total = invoice.printed_total_minor\n",
    "    return {\n",
    "        \"invoice_id\": invoice.key,\n",
    "        \"issued_on\": invoice.issued_on,\n",
    "        \"supplier\": invoice.supplier,\n",
    "        \"currency\": invoice.currency,\n",
    "        \"line_items\": [\n",
    "            {\"description\": item.description, \"quantity\": item.quantity, \"unit_minor\": item.unit_minor}\n",
    "            for item in invoice.items\n",
    "        ],\n",
    "        \"subtotal_minor\": subtotal,\n",
    "        \"tax_minor\": invoice.tax_minor,\n",
    "        \"total_minor\": total,\n",
    "    }\n",
    "\n",
    "\n",
    "def make_catalog() -> list[Invoice]:\n",
    "    rng = random.Random(20261126)\n",
    "    sources = {\n",
    "        \"train\": (24, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"dev\": (6, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"familiar\": (8, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"novel\": (8, (\"packing\", \"remittance\", \"service\", \"notice\")),\n",
    "        \"independent\": (4, (\"separate\",)),\n",
    "        \"release\": (10, (\"packing\", \"remittance\", \"service\", \"notice\", \"separate\")),\n",
    "    }\n",
    "    locales = ((\"en-US\", \"USD\"), (\"en-GB\", \"GBP\"), (\"de-DE\", \"EUR\"), (\"fr-FR\", \"EUR\"), (\"en-US\", \"CAD\"))\n",
    "    services = (\"Cooling filter\", \"Cable sleeve\", \"Bench calibration\", \"Door seal\", \"Grounding clip\",\n",
    "                \"Rack inspection\", \"Meter label\", \"Packing insert\", \"Carrier adjustment\", \"Mounting plate\")\n",
    "    catalog = []\n",
    "    seen_keys = set()\n",
    "    supplier_codes = rng.sample(range(1000, 9999), sum(n for n, _ in sources.values()))\n",
    "    supplier_index = 0\n",
    "    for split, (family_count, layouts) in sources.items():\n",
    "        for family_number in range(family_count):\n",
    "            supplier_code = supplier_codes[supplier_index]\n",
    "            supplier_index += 1\n",
    "            layout = layouts[family_number % len(layouts)]\n",
    "            family = f\"{split}-{family_number:02d}\"\n",
    "            locale, currency = locales[family_number % len(locales)]\n",
    "            for row in range(SPLIT_SIZES[split] // family_count):\n",
    "                code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                while code in seen_keys:\n",
    "                    code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                seen_keys.add(code)\n",
    "                items = tuple(\n",
    "                    Line(kind, rng.randint(1, 9), rng.randrange(200, 24800))\n",
    "                    for kind in rng.sample(services, rng.randrange(1, 4))\n",
    "                )\n",
    "                subtotal = sum(x.quantity * x.unit_minor for x in items)\n",
    "                tax = (subtotal * (7 if currency == \"USD\" else 13) + 50) // 100\n",
    "                if split in {\"novel\", \"independent\", \"release\"} and row % 12 == 4:\n",
    "                    tax = None\n",
    "                displayed = subtotal + tax + 101 if tax is not None and row % 12 == 7 else None\n",
    "                issued_on = (date(2025, 1, 1) + timedelta(days=rng.randint(0, 590))).isoformat()\n",
    "                catalog.append(Invoice(code, family, f\"Sample Supplier {supplier_code}\", issued_on,\n",
    "                                       currency, items, tax, locale, split, layout, displayed))\n",
    "    return catalog\n",
    "\n",
    "\n",
    "def formatted_money(minor: int | None, locale: str) -> str:\n",
    "    if minor is None:\n",
    "        return \"-\"\n",
    "    dollars, cents = divmod(minor, 100)\n",
    "    number = f\"{dollars:,}.{cents:02d}\"\n",
    "    if locale == \"de-DE\":\n",
    "        return number.replace(\",\", \"_\").replace(\".\", \",\").replace(\"_\", \".\")\n",
    "    if locale == \"fr-FR\":\n",
    "        return number.replace(\",\", \" \").replace(\".\", \",\")\n",
    "    return number\n",
    "\n",
    "\n",
    "def invoice_text(invoice: Invoice) -> str:\n",
    "    gold = invoice_record(invoice)\n",
    "    money = lambda value: formatted_money(value, invoice.locale)\n",
    "    identifier = f\"{invoice.key}\"\n",
    "    supplier = invoice.supplier\n",
    "    issued = invoice.issued_on\n",
    "    currency = invoice.currency\n",
    "    subtotal = money(gold[\"subtotal_minor\"])\n",
    "    tax = money(gold[\"tax_minor\"])\n",
    "    total = money(gold[\"total_minor\"])\n",
    "    register = [f\"{row.description} | {row.quantity} | {money(row.unit_minor)}\" for row in invoice.items]\n",
    "    inline = [f\"{row.quantity} x {row.description} @ {money(row.unit_minor)} per unit\" for row in invoice.items]\n",
    "    service = [f\"{row.description}: {money(row.unit_minor)} each for {row.quantity} units\" for row in invoice.items]\n",
    "    if invoice.layout == \"register\":\n",
    "        return \"\\n\".join([f\"Supplier: {supplier}\", f\"Invoice: {identifier}\", f\"Issued: {issued}\", f\"Currency: {currency}\",\n",
    "                          \"Description | Quantity | Unit price\", *register,\n",
    "                          f\"Subtotal: {subtotal}\", f\"Tax: {tax}\", f\"Amount due: {total}\"])\n",
    "    if invoice.layout == \"memo\":\n",
    "        return \"\\n\".join([f\"{supplier} billing memo / {issued}\", f\"Account invoice {identifier} [{currency}]\",\n",
    "                          *inline, f\"Total due {total} including tax {tax}; net amount {subtotal}.\"])\n",
    "    if invoice.layout == \"checkout\":\n",
    "        return \"\\n\".join([f\"{identifier} / supplier {supplier}\", f\"Date of issue {issued} / All amounts {currency}\",\n",
    "                          *service, f\"Net {subtotal}\", f\"Sales tax {tax}\", f\"Payable {total}\"])\n",
    "    if invoice.layout == \"ledger\":\n",
    "        return \"\\n\".join([f\"{supplier} | issued {issued} | invoice {identifier}\", f\"Ledger in {currency}\",\n",
    "                          \"Service | Count | Per unit\", *register, f\"Before tax {subtotal}\",\n",
    "                          f\"Tax charged {tax}\", f\"Balance {total}\"])\n",
    "    if invoice.layout == \"packing\":\n",
    "        return \"\\n\".join([f\"Billing details / {identifier}\", f\"Sold by {supplier}\", f\"Document date {issued}\",\n",
    "                          f\"Invoice currency {currency}\", f\"Balance payable {total}\", *service,\n",
    "                          f\"Merchandise {subtotal}\", f\"Tax {tax}\"])\n",
    "    if invoice.layout == \"remittance\":\n",
    "        return \"\\n\".join([f\"Remittance advice for {identifier} ({currency})\", f\"{supplier} / Document issued {issued}\",\n",
    "                          f\"Pay this amount {total}\", *inline, f\"Net charges {subtotal} / Tax {tax}\"])\n",
    "    if invoice.layout == \"service\":\n",
    "        return \"\\n\".join([f\"Ref {identifier} / {currency}\", f\"Service fee notice, {issued}\", supplier,\n",
    "                          *[f\"Unit {money(row.unit_minor)} / {row.quantity} times / {row.description}\" for row in invoice.items],\n",
    "                          f\"Fee subtotal {subtotal}\", f\"Plus tax {tax}\", f\"Amount requested {total}\"])\n",
    "    if invoice.layout == \"notice\":\n",
    "        return \"\\n\".join([f\"{supplier} / statement {identifier}\", f\"Issued on {issued}\",\n",
    "                          f\"Invoice denomination {currency}\", \"One-off charges\", *service,\n",
    "                          f\"Pre-tax {subtotal} / Tax assessment {tax} / Final bill {total}\"])\n",
    "    return \"\\n\".join([f\"Document {identifier}\", f\"Biller {supplier} / As of {issued} / {currency}\", *inline,\n",
    "                      f\"Gross {total}\", f\"Breakdown: net {subtotal} and taxes {tax}.\"])\n",
    "\n",
    "\n",
    "def _strict_dict(pairs: list[tuple[str, Any]]) -> dict[str, Any]:\n",
    "    result: dict[str, Any] = {}\n",
    "    for key, value in pairs:\n",
    "        if key in result:\n",
    "            raise ValueError(f\"Duplicate JSON key {key!r}\")\n",
    "        result[key] = value\n",
    "    return result\n",
    "\n",
    "\n",
    "def parse_record(completion: str | dict[str, Any]) -> dict[str, Any] | None:\n",
    "    if isinstance(completion, str):\n",
    "        try:\n",
    "            data = json.loads(completion, object_pairs_hook=_strict_dict)\n",
    "        except (ValueError, TypeError, RecursionError):\n",
    "            return None\n",
    "    else:\n",
    "        data = completion\n",
    "    keys = {\"invoice_id\", \"issued_on\", \"supplier\", \"currency\", \"line_items\", \"subtotal_minor\", \"tax_minor\", \"total_minor\"}\n",
    "    if not isinstance(data, dict) or set(data) != keys:\n",
    "        return None\n",
    "    for name in (\"invoice_id\", \"supplier\", \"issued_on\", \"currency\"):\n",
    "        value = data[name]\n",
    "        if value is not None and (not isinstance(value, str) or not value.strip()):\n",
    "            return None\n",
    "    try:\n",
    "        if data[\"issued_on\"] is not None and date.fromisoformat(data[\"issued_on\"]).isoformat() != data[\"issued_on\"]:\n",
    "            return None\n",
    "    except ValueError:\n",
    "        return None\n",
    "    if data[\"currency\"] is not None and re.fullmatch(\"[A-Z]{3}\", data[\"currency\"]) is None:\n",
    "        return None\n",
    "    for name in (\"subtotal_minor\", \"tax_minor\", \"total_minor\"):\n",
    "        if data[name] is not None and type(data[name]) is not int:\n",
    "            return None\n",
    "    if not isinstance(data[\"line_items\"], list):\n",
    "        return None\n",
    "    for row in data[\"line_items\"]:\n",
    "        if not isinstance(row, dict) or set(row) != {\"description\", \"quantity\", \"unit_minor\"}:\n",
    "            return None\n",
    "        if type(row[\"description\"]) is not str or type(row[\"quantity\"]) is not int or type(row[\"unit_minor\"]) is not int:\n",
    "            return None\n",
    "        if not row[\"description\"].strip() or row[\"quantity\"] <= 0:\n",
    "            return None\n",
    "    return data\n",
    "\n",
    "\n",
    "def score_record(completion: str | dict[str, Any], invoice: Invoice) -> dict[str, Any]:\n",
    "    truth = invoice_record(invoice)\n",
    "    observed = parse_record(completion)\n",
    "    field_correct = {key: observed is not None and observed.get(key) == value\n",
    "                     for key, value in truth.items() if key != \"line_items\"}\n",
    "    keys = (\"description\", \"quantity\", \"unit_minor\")\n",
    "    expected = Counter(tuple(r[k] for k in keys) for r in truth[\"line_items\"])\n",
    "    predicted = Counter(tuple(r[k] for k in keys) for r in observed[\"line_items\"]) if observed is not None else Counter()\n",
    "    matches = (expected & predicted).total()\n",
    "    row_count = expected.total() + predicted.total()\n",
    "    return {\"valid\": observed is not None, \"exact\": observed == truth,\n",
    "            \"fields\": sum(field_correct.values()) / len(field_correct), \"field_correct\": field_correct,\n",
    "            \"row_f1\": 2 * matches / row_count if row_count else 1.0}\n",
    "\n",
    "\n",
    "def rules_extract(text: str) -> dict[str, Any] | None:\n",
    "    lines = text.splitlines()\n",
    "    if len(lines) < 9 or lines[4] != \"Description | Quantity | Unit price\":\n",
    "        return None\n",
    "    property_names = (\"supplier\", \"invoice_id\", \"issued_on\", \"currency\")\n",
    "    headers = (\"Supplier: \", \"Invoice: \", \"Issued: \", \"Currency: \")\n",
    "    if any(not line.startswith(header) for line, header in zip(lines, headers)):\n",
    "        return None\n",
    "    data = {name: line.removeprefix(header) for name, line, header in zip(property_names, lines, headers)}\n",
    "\n",
    "    def minor(text_amount: str) -> int | None:\n",
    "        if text_amount == \"-\":\n",
    "            return None\n",
    "        if re.fullmatch(r\"(?:\\d+|\\d{1,3}(?:[., ]\\d{3})+)[.,]\\d{2}\", text_amount) is None:\n",
    "            raise ValueError(\"Unsupported amount format\")\n",
    "        units, frac = text_amount[:-3], text_amount[-2:]\n",
    "        return int(re.sub(r\"\\D\", \"\", units)) * 100 + int(frac)\n",
    "\n",
    "    try:\n",
    "        rows = [line.split(\" | \") for line in lines[5:-3]]\n",
    "        data[\"line_items\"] = [{\"description\": desc, \"quantity\": int(qty), \"unit_minor\": minor(unit)}\n",
    "                              for desc, qty, unit in rows]\n",
    "        data[\"subtotal_minor\"] = minor(lines[-3].removeprefix(\"Subtotal: \"))\n",
    "        data[\"tax_minor\"] = minor(lines[-2].removeprefix(\"Tax: \"))\n",
    "        data[\"total_minor\"] = minor(lines[-1].removeprefix(\"Amount due: \"))\n",
    "    except ValueError:\n",
    "        return None\n",
    "    return parse_record(data)\n",
    "\n",
    "\n",
    "def examples_for(split: str, limit: int | None = None) -> list[Invoice]:\n",
    "    found = [invoice for invoice in make_catalog() if invoice.split == split]\n",
    "    if not found:\n",
    "        raise ValueError(f\"Unknown invoice split {split!r}\")\n",
    "    if limit is None or limit >= len(found):\n",
    "        return found\n",
    "    if limit <= 0:\n",
    "        raise ValueError(\"Limit must be positive\")\n",
    "    groups: dict[str, list[Invoice]] = {}\n",
    "    for invoice in found:\n",
    "        groups.setdefault(invoice.family, []).append(invoice)\n",
    "    balanced = [invoice for group_rows in zip(*groups.values(), strict=True) for invoice in group_rows]\n",
    "    return balanced[:limit]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db575c72",
   "metadata": {},
   "source": [
    "## Completion masking\n",
    "\n",
    "The prefix-stable masking and preference helpers below adapt Apache-2.0 recipe code from\n",
    "the Together Post-Training Cookbook. The shared helpers build a causal training sequence\n",
    "while marking just the answer tokens and end marker as targets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5a320264",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SPDX-License-Identifier: Apache-2.0\n",
    "\"\"\"Portable training functions from the Together Post-Training Cookbook.\n",
    "\n",
    "Adapted from togethercomputer/post-training-cookbook at\n",
    "226e03ca225d6f13434047cf0f45ab3070a29801. See third_party for the Apache licence\n",
    "and the original paths. The hosted training and provisioning code is replaced\n",
    "by notebook-local PyTorch and typed fixtures.\n",
    "\"\"\"\n",
    "\n",
    "from __future__ import annotations\n",
    "\n",
    "import random\n",
    "from collections import Counter\n",
    "from collections.abc import Callable, Iterable, Sequence\n",
    "from dataclasses import dataclass, field\n",
    "from typing import NamedTuple, TypeVar\n",
    "\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class Turn(NamedTuple):\n",
    "    prompt: list[int]\n",
    "    completion: list[int]\n",
    "\n",
    "\n",
    "class MaskedSequence(NamedTuple):\n",
    "    input_ids: list[int]\n",
    "    completion_mask: list[int]\n",
    "\n",
    "\n",
    "def split_turns(turns: Iterable[Turn]) -> list[MaskedSequence]:\n",
    "    \"\"\"Build prefix-stable sequences with a token-aligned completion mask.\"\"\"\n",
    "    sequences: list[MaskedSequence] = []\n",
    "    emitted: list[int] = []\n",
    "    mask: list[int] = []\n",
    "    for prompt, completion in turns:\n",
    "        if len(prompt) < len(emitted) or prompt[: len(emitted)] != emitted:\n",
    "            if emitted:\n",
    "                sequences.append(MaskedSequence(emitted, mask))\n",
    "            mask = [0] * len(prompt)\n",
    "        else:\n",
    "            mask = mask + [0] * (len(prompt) - len(emitted))\n",
    "        emitted = prompt + completion\n",
    "        mask = mask + [1] * len(completion)\n",
    "    if emitted:\n",
    "        sequences.append(MaskedSequence(emitted, mask))\n",
    "    return sequences\n",
    "\n",
    "\n",
    "def masked_logp_sum(logprobs: torch.Tensor, mask: Sequence[float]) -> torch.Tensor:\n",
    "    \"\"\"Sum target-aligned response log probabilities and retain gradients.\"\"\"\n",
    "    if logprobs.ndim != 1 or len(mask) != logprobs.shape[0]:\n",
    "        raise ValueError(\"The response mask must match the one-dimensional target log probabilities.\")\n",
    "    weights = torch.as_tensor(mask, dtype=logprobs.dtype, device=logprobs.device)\n",
    "    return (logprobs * weights).sum()\n",
    "\n",
    "\n",
    "def make_dpo_loss(\n",
    "    ref_sums: Sequence[float],\n",
    "    masks: Sequence[Sequence[float]],\n",
    "    *,\n",
    "    beta: float,\n",
    "    label_smoothing: float = 0.0,\n",
    ") -> Callable[[Sequence[torch.Tensor]], torch.Tensor]:\n",
    "    \"\"\"Close over fixed reference scores and response masks for chosen/rejected pairs.\"\"\"\n",
    "    if not ref_sums or len(ref_sums) != len(masks) or len(ref_sums) % 2:\n",
    "        raise ValueError(\"Supply at least one complete pair and one mask for each reference score.\")\n",
    "    if beta <= 0.0 or not 0.0 <= label_smoothing <= 0.5:\n",
    "        raise ValueError(\"Beta must be positive and label smoothing must be between 0 and 0.5.\")\n",
    "    branch_size = len(ref_sums)\n",
    "\n",
    "    def loss_fn(policy_logprobs: Sequence[torch.Tensor]) -> torch.Tensor:\n",
    "        if len(policy_logprobs) != branch_size:\n",
    "            raise ValueError(f\"Expected {branch_size} policy log-probability tensors.\")\n",
    "        policy = torch.stack([masked_logp_sum(values, mask) for values, mask in zip(policy_logprobs, masks, strict=True)])\n",
    "        reference = policy.new_tensor(ref_sums)\n",
    "        delta = policy - reference\n",
    "        margin = beta * (delta[0::2] - delta[1::2])\n",
    "        return (-(1.0 - label_smoothing) * F.logsigmoid(margin) - label_smoothing * F.logsigmoid(-margin)).mean()\n",
    "\n",
    "    return loss_fn\n",
    "\n",
    "\n",
    "def compute_overlong_penalty(\n",
    "    response_length: int,\n",
    "    max_response_length: int,\n",
    "    overlong_buffer_len: int,\n",
    "    penalty_factor: float = 1.0,\n",
    ") -> float:\n",
    "    \"\"\"Apply the cookbook's DAPO soft penalty near a generation cap.\"\"\"\n",
    "    if overlong_buffer_len <= 0:\n",
    "        return 0.0\n",
    "    expected_len = max_response_length - overlong_buffer_len\n",
    "    exceed_len = response_length - expected_len\n",
    "    return min(-exceed_len / overlong_buffer_len * penalty_factor, 0.0)\n",
    "\n",
    "\n",
    "Item = TypeVar(\"Item\")\n",
    "\n",
    "\n",
    "def oversample_until_kept(\n",
    "    draw_batch: Callable[[], Iterable[Item]],\n",
    "    *,\n",
    "    is_kept: Callable[[Item], bool],\n",
    "    target: int,\n",
    "    max_attempts: int,\n",
    ") -> tuple[list[Item], int]:\n",
    "    \"\"\"Keep rejected groups in the audit trail while bounding draws.\"\"\"\n",
    "    if target <= 0 or max_attempts <= 0:\n",
    "        raise ValueError(\"Target and maximum attempts must be positive.\")\n",
    "    items: list[Item] = []\n",
    "    kept = 0\n",
    "    for attempts in range(1, max_attempts + 1):\n",
    "        for item in draw_batch():\n",
    "            items.append(item)\n",
    "            if is_kept(item):\n",
    "                kept += 1\n",
    "                if kept >= target:\n",
    "                    return items, attempts\n",
    "    return items, max_attempts\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class TeacherRequest:\n",
    "    key: str\n",
    "    messages: Sequence[dict[str, str]]\n",
    "    meta: dict[str, object] = field(default_factory=dict)\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class TeacherOutput:\n",
    "    content: str\n",
    "    ok: bool = True\n",
    "    truncated: bool = False\n",
    "\n",
    "\n",
    "def sft_rows(\n",
    "    requests: Sequence[TeacherRequest],\n",
    "    outputs: dict[str, TeacherOutput],\n",
    "    *,\n",
    "    reject_reason: Callable[[TeacherRequest, TeacherOutput], str | None] | None = None,\n",
    ") -> tuple[list[dict[str, object]], Counter[str]]:\n",
    "    \"\"\"Convert verified procedural teacher outputs to SFT rows and count exclusions.\"\"\"\n",
    "    rows: list[dict[str, object]] = []\n",
    "    dropped: Counter[str] = Counter()\n",
    "    for request in requests:\n",
    "        output = outputs.get(request.key)\n",
    "        if output is None:\n",
    "            dropped[\"missing\"] += 1\n",
    "            continue\n",
    "        if not output.ok:\n",
    "            dropped[\"failed\"] += 1\n",
    "            continue\n",
    "        if output.truncated:\n",
    "            dropped[\"truncated\"] += 1\n",
    "            continue\n",
    "        content = output.content.strip()\n",
    "        if not content:\n",
    "            dropped[\"empty\"] += 1\n",
    "            continue\n",
    "        reason = reject_reason(request, output) if reject_reason is not None else None\n",
    "        if reason is not None:\n",
    "            dropped[reason] += 1\n",
    "            continue\n",
    "        assistant = {\"role\": \"assistant\", \"content\": content}\n",
    "        rows.append({\"id\": request.key, \"messages\": [*request.messages, assistant], \"meta\": dict(request.meta)})\n",
    "    return rows, dropped\n",
    "\n",
    "\n",
    "def mix(*groups: Sequence[Item], seed: int = 0) -> list[Item]:\n",
    "    \"\"\"Concatenate row groups and shuffle them deterministically.\"\"\"\n",
    "    rows = [row for group in groups for row in group]\n",
    "    random.Random(seed).shuffle(rows)\n",
    "    return rows"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27e1afc9",
   "metadata": {},
   "source": [
    "## Training and scoring\n",
    "\n",
    "A common prompt, batch schedule and scorer make each comparison interpretable. The paired\n",
    "uncertainty calculation resamples whole layout families, so repeated layouts do not count\n",
    "as independent evidence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "37433034",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Shared notebook-local text training and measurement for lessons 01–03.\"\"\"\n",
    "from __future__ import annotations\n",
    "\n",
    "import gc\n",
    "import hashlib\n",
    "import importlib.metadata\n",
    "import json\n",
    "import random\n",
    "import statistics\n",
    "import time\n",
    "from collections import defaultdict\n",
    "from pathlib import Path\n",
    "\n",
    "import torch\n",
    "\n",
    "MODEL = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
    "REVISION = \"7ae557604adf67be50417f59c2c2f167def9a775\"\n",
    "SEED = 42\n",
    "MAX_TOKENS = 1536\n",
    "MAX_NEW_TOKENS = 384\n",
    "BATCH = 2\n",
    "\n",
    "\n",
    "\n",
    "def canonical_json(record):\n",
    "    return json.dumps(record, ensure_ascii=False, separators=(\",\", \":\"))\n",
    "\n",
    "\n",
    "def ordered_by_family(items):\n",
    "    by_family = defaultdict(list)\n",
    "    for invoice in items:\n",
    "        by_family[invoice.family].append(invoice)\n",
    "    randomizer = random.Random(SEED)\n",
    "    families = list(by_family)\n",
    "    randomizer.shuffle(families)\n",
    "    for rows in by_family.values():\n",
    "        randomizer.shuffle(rows)\n",
    "    return [\n",
    "        by_family[family][offset]\n",
    "        for offset in range(max(map(len, by_family.values()), default=0))\n",
    "        for family in families\n",
    "        if offset < len(by_family[family])\n",
    "    ]\n",
    "\n",
    "\n",
    "def lesson_prompts(catalog):\n",
    "    \"\"\"Choose one training exemplar and preserve dataset order after seeded sampling.\"\"\"\n",
    "    train = ordered_by_family([invoice for invoice in catalog if invoice.split == \"train\"])\n",
    "    if len(train) < 3:\n",
    "        raise ValueError(\"The shared catalogue must contain at least three training invoices.\")\n",
    "    exemplar, *train = train\n",
    "    teach_splits = {\"familiar\", \"novel\", \"independent\"}\n",
    "    evaluation = [invoice for invoice in catalog if invoice.split in teach_splits]\n",
    "    if not evaluation or set(item.split for item in evaluation) != teach_splits:\n",
    "        raise ValueError(\"The three fixed teaching slices must be present.\")\n",
    "    return exemplar, train, evaluation\n",
    "\n",
    "\n",
    "def prompt_messages(invoice, exemplar):\n",
    "    return [\n",
    "        {\"role\": \"system\", \"content\": VISIBLE_CONTRACT},\n",
    "        {\"role\": \"user\", \"content\": invoice_text(exemplar)},\n",
    "        {\"role\": \"assistant\", \"content\": canonical_json(invoice_record(exemplar))},\n",
    "        {\"role\": \"user\", \"content\": invoice_text(invoice)},\n",
    "    ]\n",
    "\n",
    "\n",
    "def encode_prompt(tokenizer, invoice, exemplar):\n",
    "    return tokenizer.apply_chat_template(\n",
    "        prompt_messages(invoice, exemplar), tokenize=True, add_generation_prompt=True,\n",
    "    )\n",
    "\n",
    "\n",
    "def encode_supervision(tokenizer, invoice, answer, exemplar):\n",
    "    prompt = encode_prompt(tokenizer, invoice, exemplar)\n",
    "    completion = tokenizer.encode(answer, add_special_tokens=False) + [tokenizer.eos_token_id]\n",
    "    sequence, = split_turns([Turn(prompt, completion)])\n",
    "    if len(sequence.input_ids) > MAX_TOKENS or len(completion) + 1 > MAX_NEW_TOKENS:\n",
    "        raise ValueError(f\"Invoice {invoice.key} exceeds the fixed token budget.\")\n",
    "    return sequence\n",
    "\n",
    "\n",
    "def right_pad(examples, pad_id, device):\n",
    "    width = max(len(example.input_ids) for example in examples)\n",
    "    ids, attention, labels = [], [], []\n",
    "    for example in examples:\n",
    "        n_pad = width - len(example.input_ids)\n",
    "        ids.append(example.input_ids + [pad_id] * n_pad)\n",
    "        attention.append([1] * len(example.input_ids) + [0] * n_pad)\n",
    "        labels.append([token if mask else -100 for token, mask in zip(\n",
    "            example.input_ids, example.completion_mask, strict=True,\n",
    "        )] + [-100] * n_pad)\n",
    "    return {\n",
    "        key: torch.tensor(rows, dtype=torch.long, device=device)\n",
    "        for key, rows in ((\"input_ids\", ids), (\"attention_mask\", attention), (\"labels\", labels))\n",
    "    }\n",
    "\n",
    "\n",
    "def load_model(encoding, *, adapter=None, trainable=False):\n",
    "    from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training\n",
    "    from transformers import AutoModelForCausalLM, BitsAndBytesConfig\n",
    "\n",
    "    torch.manual_seed(SEED)\n",
    "    if encoding == \"nf4\":\n",
    "        quant = BitsAndBytesConfig(\n",
    "            load_in_4bit=True, bnb_4bit_quant_type=\"nf4\",\n",
    "            bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16,\n",
    "        )\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            MODEL, revision=REVISION, quantization_config=quant, torch_dtype=torch.float16,\n",
    "            device_map={\"\": 0}, attn_implementation=\"sdpa\",\n",
    "        )\n",
    "    elif encoding == \"fp16\":\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            MODEL, revision=REVISION, torch_dtype=torch.float16, attn_implementation=\"sdpa\",\n",
    "        ).to(\"cuda\")\n",
    "    else:\n",
    "        raise ValueError(f\"Unsupported weight encoding {encoding!r}.\")\n",
    "    if not trainable and adapter is None:\n",
    "        return model\n",
    "    if trainable and encoding == \"nf4\":\n",
    "        model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False)\n",
    "    if adapter is not None:\n",
    "        return PeftModel.from_pretrained(model, str(adapter), is_trainable=trainable)\n",
    "    if not trainable:\n",
    "        raise ValueError(\"An adapter is required for evaluating a trained arm.\")\n",
    "    return get_peft_model(model, LoraConfig(\n",
    "        r=8, lora_alpha=16, lora_dropout=0.0, bias=\"none\",\n",
    "        task_type=\"CAUSAL_LM\", target_modules=[\"q_proj\", \"v_proj\"],\n",
    "    ))\n",
    "\n",
    "\n",
    "def adapter_train(model, schedule, objective, *, learning_rate, use_cuda):\n",
    "    \"\"\"Both arms share the same schedule, optimiser and gradient policy.\"\"\"\n",
    "    params = [param for param in model.parameters() if param.requires_grad]\n",
    "    if not params or not schedule:\n",
    "        raise ValueError(\"Expected trainable parameters and a nonempty update schedule.\")\n",
    "    optimiser = torch.optim.AdamW(params, lr=learning_rate)\n",
    "    scaler = torch.amp.GradScaler(\"cuda\", enabled=use_cuda, init_scale=512, growth_interval=10_000)\n",
    "    torch.manual_seed(SEED)\n",
    "    model.train()\n",
    "    model.config.use_cache = False\n",
    "    if use_cuda:\n",
    "        torch.cuda.synchronize()\n",
    "        torch.cuda.reset_peak_memory_stats()\n",
    "    started = time.perf_counter()\n",
    "    losses, supervised_count, batch_token_count, skipped = [], 0, 0, 0\n",
    "    for batch in schedule:\n",
    "        optimiser.zero_grad(set_to_none=True)\n",
    "        with torch.autocast(device_type=\"cuda\", dtype=torch.float16, enabled=use_cuda):\n",
    "            loss, supervised, batch_tokens = objective(model, batch)\n",
    "        if not torch.isfinite(loss).item():\n",
    "            raise FloatingPointError(\"A non-finite training loss invalidates the comparison.\")\n",
    "        scaler.scale(loss).backward()\n",
    "        scaler.unscale_(optimiser)\n",
    "        torch.nn.utils.clip_grad_norm_(params, 1.0)\n",
    "        previous_scale = scaler.get_scale()\n",
    "        scaler.step(optimiser)\n",
    "        scaler.update()\n",
    "        skipped += int(scaler.get_scale() < previous_scale)\n",
    "        losses.append(float(loss.detach().cpu()))\n",
    "        supervised_count += supervised\n",
    "        batch_token_count += batch_tokens\n",
    "    if use_cuda:\n",
    "        torch.cuda.synchronize()\n",
    "    elapsed = time.perf_counter() - started\n",
    "    return {\n",
    "        \"attempted_updates\": len(schedule),\n",
    "        \"updates\": len(schedule) - skipped,\n",
    "        \"supervised_response_tokens\": supervised_count,\n",
    "        \"unpadded_input_tokens\": batch_token_count,\n",
    "        \"seconds\": elapsed,\n",
    "        \"supervised_tokens_per_second\": supervised_count / max(elapsed, 1e-9),\n",
    "        \"peak_gib\": torch.cuda.max_memory_allocated() / 2**30 if use_cuda else None,\n",
    "        \"losses\": losses,\n",
    "        \"trainable_parameters\": sum(parameter.numel() for parameter in params),\n",
    "    }\n",
    "\n",
    "\n",
    "def sft_objective(pad_id, device):\n",
    "    def loss_for(model, examples):\n",
    "        batch = right_pad(examples, pad_id, device)\n",
    "        loss = model(**batch).loss\n",
    "        supervised = int(batch[\"labels\"][:, 1:].ne(-100).sum().item())\n",
    "        if not supervised:\n",
    "            raise ValueError(\"An update needs at least one response token.\")\n",
    "        unpadded = int(batch[\"attention_mask\"].sum().item())\n",
    "        return loss, supervised, unpadded\n",
    "    return loss_for\n",
    "\n",
    "\n",
    "def make_schedule(examples, batch_size=BATCH):\n",
    "    if not examples or batch_size <= 0:\n",
    "        raise ValueError(\"Expected training examples and a positive batch size.\")\n",
    "    return [examples[start : start + batch_size] for start in range(0, len(examples), batch_size)]\n",
    "\n",
    "\n",
    "def predictions(model, tokenizer, eval_items, exemplar, batch_size=16):\n",
    "    model.eval()\n",
    "    device = model.get_input_embeddings().weight.device\n",
    "    outputs = []\n",
    "    for start in range(0, len(eval_items), batch_size):\n",
    "        group = eval_items[start : start + batch_size]\n",
    "        prompts = [encode_prompt(tokenizer, item, exemplar) for item in group]\n",
    "        width = max(map(len, prompts))\n",
    "        if width + MAX_NEW_TOKENS > MAX_TOKENS:\n",
    "            raise ValueError(\"Evaluation prompt and fixed decode cap exceed the token budget.\")\n",
    "        ids = torch.tensor([[tokenizer.pad_token_id] * (width - len(p)) + p for p in prompts], device=device)\n",
    "        mask = torch.tensor([[0] * (width - len(p)) + [1] * len(p) for p in prompts], device=device)\n",
    "        with torch.inference_mode():\n",
    "            generated = model.generate(\n",
    "                input_ids=ids, attention_mask=mask,\n",
    "                do_sample=False, num_beams=1, max_new_tokens=MAX_NEW_TOKENS,\n",
    "                pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,\n",
    "                use_cache=True, temperature=None, top_p=None, top_k=None,\n",
    "            )\n",
    "        for item, tokens in zip(group, generated[:, width:].tolist(), strict=True):\n",
    "            stopped = tokenizer.eos_token_id in tokens\n",
    "            if stopped:\n",
    "                tokens = tokens[:tokens.index(tokenizer.eos_token_id)]\n",
    "            answer = tokenizer.decode(tokens, skip_special_tokens=True)\n",
    "            outputs.append({\n",
    "                \"key\": item.key, \"split\": item.split, \"family\": item.family,\n",
    "                \"completed\": stopped, \"answer\": answer, \"reference\": invoice_record(item),\n",
    "                \"completion_tokens\": len(tokens), **score_record(answer, item),\n",
    "            })\n",
    "    return outputs\n",
    "\n",
    "\n",
    "def rules_predictions(items):\n",
    "    rows = []\n",
    "    for item in items:\n",
    "        result = rules_extract(invoice_text(item))\n",
    "        rows.append({\n",
    "            \"key\": item.key, \"split\": item.split, \"family\": item.family,\n",
    "            \"completed\": result is not None, \"answer\": result, \"reference\": invoice_record(item),\n",
    "            **score_record(result if result is not None else \"\", item),\n",
    "        })\n",
    "    return rows\n",
    "\n",
    "\n",
    "def paired_family_interval(reference, candidate, repeats=1000):\n",
    "    \"\"\"Pair by invoice, then resample whole layout families within a slice.\"\"\"\n",
    "    deltas = defaultdict(list)\n",
    "    old_by_key = {row[\"key\"]: row for row in reference}\n",
    "    if set(old_by_key) != {row[\"key\"] for row in candidate}:\n",
    "        raise ValueError(\"Paired comparisons require the same unique invoice keys.\")\n",
    "    for row in candidate:\n",
    "        old = old_by_key[row[\"key\"]]\n",
    "        if (old[\"family\"], old[\"split\"]) != (row[\"family\"], row[\"split\"]):\n",
    "            raise ValueError(\"An invoice moved family or split.\")\n",
    "        deltas[row[\"family\"]].append(int(row[\"exact\"]) - int(old[\"exact\"]))\n",
    "    groups = list(deltas.values())\n",
    "    if len(groups) < 2:\n",
    "        return None\n",
    "    randomizer = random.Random(SEED)\n",
    "    draws = []\n",
    "    for _ in range(repeats):\n",
    "        sampled_groups = randomizer.choices(groups, k=len(groups))\n",
    "        draws.append(sum(map(sum, sampled_groups)) / sum(map(len, sampled_groups)))\n",
    "    draws.sort()\n",
    "    return [draws[int(0.025 * (repeats - 1))], draws[int(0.975 * (repeats - 1))]]\n",
    "\n",
    "\n",
    "def free_gpu():\n",
    "    \"\"\"Collect dropped references between sequential Colab arms.\"\"\"\n",
    "    gc.collect()\n",
    "    if torch.cuda.is_available():\n",
    "        torch.cuda.empty_cache()\n",
    "\n",
    "\n",
    "def save_results(lesson, scores, training, comparisons, **diagnostics):\n",
    "    import matplotlib\n",
    "    import matplotlib.pyplot as plt\n",
    "\n",
    "    seed = SEED\n",
    "    grouped = {\n",
    "        name: {\n",
    "            split: {\n",
    "                \"n\": len(rows_in_split),\n",
    "                **{\n",
    "                    metric: statistics.mean(float(row[metric]) for row in rows_in_split)\n",
    "                    for metric in (\"valid\", \"exact\", \"completed\", \"fields\", \"row_f1\")\n",
    "                },\n",
    "            }\n",
    "            for split in (\"familiar\", \"novel\", \"independent\")\n",
    "            if (rows_in_split := [row for row in rows if row[\"split\"] == split])\n",
    "        }\n",
    "        for name, rows in scores.items()\n",
    "    }\n",
    "    intervals = {}\n",
    "    for baseline, candidate in comparisons:\n",
    "        intervals[f\"{candidate} minus {baseline}\"] = {\n",
    "            split: interval\n",
    "            for split in (\"familiar\", \"novel\", \"independent\")\n",
    "            if (interval := paired_family_interval(\n",
    "                [row for row in scores[baseline] if row[\"split\"] == split],\n",
    "                [row for row in scores[candidate] if row[\"split\"] == split],\n",
    "            )) is not None\n",
    "        }\n",
    "    roster = {\n",
    "        row[\"key\"]: {\"split\": row[\"split\"], \"family\": row[\"family\"]}\n",
    "        for row in next(iter(scores.values()))\n",
    "    }\n",
    "    report = {\n",
    "        \"model_id\": MODEL, \"model_revision\": REVISION, \"seed\": seed,\n",
    "        \"versions\": {name: importlib.metadata.version(name) for name in (\"torch\", \"transformers\", \"peft\")},\n",
    "        \"hardware\": torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"CPU smoke\",\n",
    "        \"held_out_roster_sha256\": hashlib.sha256(\n",
    "            json.dumps(roster, sort_keys=True, separators=(\",\", \":\")).encode()\n",
    "        ).hexdigest(),\n",
    "        \"scores\": grouped, \"paired_family_intervals\": intervals, \"training\": training,\n",
    "        \"diagnostics\": diagnostics,\n",
    "    }\n",
    "    payload = Path(\"results\")\n",
    "    payload.mkdir(exist_ok=True)\n",
    "    (payload / f\"{lesson}-report.json\").write_text(json.dumps(report, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "    (payload / f\"{lesson}-predictions.json\").write_text(json.dumps(scores, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "    print(json.dumps({key: value for key, value in report.items() if key != \"training\"}, indent=2))\n",
    "    print(json.dumps({\n",
    "        arm: {key: value for key, value in metrics.items() if key != \"losses\"}\n",
    "        for arm, metrics in training.items()\n",
    "    }, indent=2))\n",
    "\n",
    "    matplotlib.rcParams[\"svg.fonttype\"] = \"none\"\n",
    "    fig, axes = plt.subplots(1, len(grouped[next(iter(grouped))]), figsize=(11, 4), squeeze=False, sharey=True)\n",
    "    for axis, split in zip(axes[0], grouped[next(iter(grouped))], strict=True):\n",
    "        names = list(grouped)\n",
    "        values = [grouped[name][split][\"exact\"] for name in names]\n",
    "        axis.barh(names, values, color=\"#357e72\")\n",
    "        axis.set_title(split.title())\n",
    "        axis.set_xlim(0, 1)\n",
    "        axis.set_xlabel(\"Exact record rate\")\n",
    "        axis.grid(axis=\"x\", alpha=0.2)\n",
    "    axes[0, 0].invert_yaxis()\n",
    "    fig.suptitle(\"Complete-record accuracy on the held-out invoice slices\")\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(payload / f\"{lesson}-exact.svg\", bbox_inches=\"tight\")\n",
    "    from IPython.display import SVG, display\n",
    "    display(SVG(filename=str(payload / f\"{lesson}-exact.svg\")))\n",
    "    plt.close(fig)\n",
    "    return report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ed7015c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Teaching evaluation counts: {'familiar': 96, 'novel': 96, 'independent': 48}\n",
      "One train-only prompt exemplar: SF-898991\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoTokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)\n",
    "if tokenizer.pad_token_id is None or tokenizer.eos_token_id is None:\n",
    "    raise ValueError(\"The pinned tokenizer must supply padding and completion markers.\")\n",
    "catalogue = make_catalog()\n",
    "exemplar, training_items, evaluation_items = lesson_prompts(catalogue)\n",
    "print(\"Teaching evaluation counts:\", dict(Counter(x.split for x in evaluation_items)))\n",
    "print(\"One train-only prompt exemplar:\", exemplar.key)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d05d8b8",
   "metadata": {},
   "source": [
    "## Which documents can the model see?\n",
    "\n",
    "Reserve the exemplar, then draw a balanced training sample from every training family.\n",
    "The familiar evaluation families have known layouts and new suppliers. Novel and\n",
    "independent slices have new layouts. All are synthetic. The release split stays reserved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "dd4c02f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib_inline.backend_inline import set_matplotlib_formats\n",
    "\n",
    "set_matplotlib_formats(\"svg\")\n",
    "TRAIN_ROWS = 192\n",
    "FAULT_PERIOD = 3\n",
    "EVAL_BATCH = 16\n",
    "LEARNING_RATE = 2e-4\n",
    "DEVICE = \"cuda\"\n",
    "chosen = training_items[:TRAIN_ROWS]\n",
    "reserved = [invoice for invoice in catalogue if invoice.split != \"train\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "993b2c75",
   "metadata": {},
   "source": [
    "## Why keep two records for one invoice?\n",
    "\n",
    "Offset the faults within each supplier family so no training family lies entirely outside\n",
    "the corruption schedule. Hash the visible invoice independently of its answer. Drop exact\n",
    "duplicate documents once. Compare each remaining candidate with the source record, and\n",
    "correct the label on the verified arm. The raw arm retains the original candidate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "92b80926",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Deduplicate visible invoices and verify each retained training target.\"\"\"\n",
    "\n",
    "import hashlib\n",
    "from collections import Counter\n",
    "from copy import deepcopy\n",
    "\n",
    "\n",
    "RAW = \"Raw labels\"\n",
    "VERIFIED = \"Verified labels\"\n",
    "FAULTS = (\"wrong currency\", \"dropped row\", \"wrong total\")\n",
    "DUPLICATE = \"duplicate visible invoice\"\n",
    "TEACHING_SPLITS = (\"familiar\", \"novel\", \"independent\")\n",
    "\n",
    "\n",
    "def visible_hash(invoice):\n",
    "    return hashlib.sha256(invoice_text(invoice).encode(\"utf-8\")).hexdigest()\n",
    "\n",
    "\n",
    "def assert_split_lineage(catalogue, chosen, exemplar, held):\n",
    "    split_counts = Counter(row.split for row in catalogue)\n",
    "    if split_counts != SPLIT_SIZES:\n",
    "        raise AssertionError(\"The catalogue split counts changed.\")\n",
    "    if len({row.key for row in catalogue}) != len(catalogue):\n",
    "        raise AssertionError(\"Invoice identifiers must be unique in the catalogue.\")\n",
    "    if len({visible_hash(row) for row in catalogue}) != len(catalogue):\n",
    "        raise AssertionError(\"The catalogue contains an unexpected visible duplicate.\")\n",
    "    for key in (\"supplier\", \"family\"):\n",
    "        splits_by_group = {}\n",
    "        for row in catalogue:\n",
    "            group = getattr(row, key)\n",
    "            if splits_by_group.setdefault(group, row.split) != row.split:\n",
    "                raise AssertionError(f\"A {key} appears in more than one split.\")\n",
    "    training = {row.key: row for row in catalogue if row.split == \"train\"}\n",
    "    selected = [exemplar, *chosen]\n",
    "    if len({row.key for row in selected}) != len(selected):\n",
    "        raise AssertionError(\"The training inputs must be unique and exclude the exemplar.\")\n",
    "    if any(training.get(row.key) != row for row in selected):\n",
    "        raise AssertionError(\"A training input or exemplar lacks training-split lineage.\")\n",
    "    expected_eval = [row for row in catalogue if row.split in TEACHING_SPLITS]\n",
    "    if held != expected_eval:\n",
    "        raise AssertionError(\"The evaluation roster must contain the locked teaching splits in order.\")\n",
    "    return dict(split_counts)\n",
    "\n",
    "\n",
    "def corrupt_record(gold, mode):\n",
    "    edited = deepcopy(gold)\n",
    "    if mode == \"wrong currency\":\n",
    "        edited[\"currency\"] = \"GBP\" if edited[\"currency\"] != \"GBP\" else \"USD\"\n",
    "    elif mode == \"dropped row\":\n",
    "        edited[\"line_items\"].pop()\n",
    "    elif mode == \"wrong total\":\n",
    "        if edited[\"total_minor\"] is None:\n",
    "            raise ValueError(\"The wrong-total operation requires a visible total.\")\n",
    "        edited[\"total_minor\"] += 101\n",
    "    elif mode != \"none\":\n",
    "        raise ValueError(f\"Unknown corruption {mode!r}.\")\n",
    "    return edited\n",
    "\n",
    "\n",
    "def audit_labels(train_items, forbidden_items, *, fault_period=3):\n",
    "    \"\"\"Record candidate lineage before running a separate check on retained labels.\"\"\"\n",
    "    if fault_period < 1:\n",
    "        raise ValueError(\"Fault period must be a positive number of examples.\")\n",
    "    forbidden = {visible_hash(row) for row in forbidden_items}\n",
    "    family_offsets, family_order = Counter(), {}\n",
    "    pool = []\n",
    "    for position, row in enumerate(train_items):\n",
    "        offset = family_offsets[row.family]\n",
    "        order = family_order.setdefault(row.family, len(family_order))\n",
    "        phase = offset - order % fault_period\n",
    "        mode = \"none\"\n",
    "        if phase >= 0 and phase % fault_period == 0:\n",
    "            mode = FAULTS[(phase // fault_period + order // fault_period) % len(FAULTS)]\n",
    "        family_offsets[row.family] += 1\n",
    "        pool.append((row, mode))\n",
    "        if position % 11 == 0:\n",
    "            pool.append((row, mode))\n",
    "\n",
    "    raw, verified, lineage, seen = [], [], [], {}\n",
    "    reasons = Counter()\n",
    "    for position, (row, mode) in enumerate(pool, start=1):\n",
    "        digest = visible_hash(row)\n",
    "        if digest in forbidden:\n",
    "            raise ValueError(\"A candidate prompt duplicates a held-out invoice or the prompt exemplar.\")\n",
    "        first = seen.setdefault(digest, position)\n",
    "        detail = {\n",
    "            \"candidate\": position, \"kept_candidate\": first, \"invoice_key\": row.key,\n",
    "            \"family\": row.family, \"layout\": row.layout, \"visible_sha256\": digest, \"injected_fault\": mode,\n",
    "        }\n",
    "        lineage.append(detail)\n",
    "        if first != position:\n",
    "            detail[\"disposition\"] = \"duplicate\"\n",
    "            reasons[DUPLICATE] += 1\n",
    "            continue\n",
    "\n",
    "        gold = invoice_record(row)\n",
    "        candidate = corrupt_record(gold, mode)\n",
    "        observed = score_record(candidate, row)\n",
    "        exact = observed[\"exact\"]\n",
    "        if not observed[\"valid\"] or exact != (mode == \"none\"):\n",
    "            raise AssertionError(\"The fault must change exactness without breaking the schema.\")\n",
    "        if not exact:\n",
    "            reasons[mode] += 1\n",
    "        corrected = candidate if exact else gold\n",
    "        if not score_record(corrected, row)[\"exact\"]:\n",
    "            raise AssertionError(\"A corrected record still disagrees with the fixture.\")\n",
    "        detail[\"disposition\"] = \"unchanged\" if exact else \"corrected\"\n",
    "        raw.append((row, canonical_json(candidate)))\n",
    "        verified.append((row, canonical_json(corrected)))\n",
    "\n",
    "    assert len(pool) == len(raw) + reasons[DUPLICATE]\n",
    "    assert sum(entry[\"disposition\"] == \"corrected\" for entry in lineage) == sum(reasons[mode] for mode in FAULTS)\n",
    "    return raw, verified, reasons, lineage\n",
    "\n",
    "\n",
    "def prepared_labels(train_items, forbidden_items):\n",
    "    \"\"\"Preserve the shared lesson smoke's compact return shape.\"\"\"\n",
    "    raw, verified, reasons, _ = audit_labels(train_items, forbidden_items)\n",
    "    return raw, verified, reasons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "97cb8f75",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Check the matched comparison and export evidence for each teaching decision.\"\"\"\n",
    "\n",
    "\n",
    "def checked_schedule(tokenizer, raw, verified, exemplar):\n",
    "    schedules, expected = {}, {}\n",
    "    expected_documents = [row for row, _ in raw]\n",
    "    if expected_documents != [row for row, _ in verified]:\n",
    "        raise AssertionError(\"Both arms must retain the same ordered invoice records.\")\n",
    "\n",
    "    prompts = [encode_prompt(tokenizer, row, exemplar) for row in expected_documents]\n",
    "    for name, rows in ((RAW, raw), (VERIFIED, verified)):\n",
    "        examples = []\n",
    "        for index, (invoice, answer) in enumerate(rows):\n",
    "            prompt = prompts[index]\n",
    "            response = tokenizer.encode(answer, add_special_tokens=False) + [tokenizer.eos_token_id]\n",
    "            example = encode_supervision(tokenizer, invoice, answer, exemplar)\n",
    "            if example.input_ids != prompt + response:\n",
    "                raise AssertionError(f\"Unexpected token lineage for {invoice.key}.\")\n",
    "            if example.completion_mask != [0] * len(prompt) + [1] * len(response):\n",
    "                raise AssertionError(f\"Unexpected response mask for {invoice.key}.\")\n",
    "            examples.append(example)\n",
    "        schedule = make_schedule(examples)\n",
    "        for group in schedule:\n",
    "            batch = right_pad(group, tokenizer.pad_token_id, \"cpu\")\n",
    "            for index, example in enumerate(group):\n",
    "                width = batch[\"labels\"].shape[1]\n",
    "                padding = width - len(example.input_ids)\n",
    "                expected_mask = [bool(value) for value in example.completion_mask] + [False] * padding\n",
    "                if batch[\"labels\"][index].ne(-100).tolist() != expected_mask:\n",
    "                    raise AssertionError(\"Prompt and padding tokens must be excluded from the loss.\")\n",
    "        schedules[name] = schedule\n",
    "        expected[name] = {\n",
    "            \"rows\": len(rows),\n",
    "            \"updates\": len(schedule),\n",
    "            \"prompt_tokens\": sum(map(len, prompts)),\n",
    "            \"supervised_response_tokens\": sum(sum(example.completion_mask) for example in examples),\n",
    "        }\n",
    "\n",
    "    if [len(batch) for batch in schedules[RAW]] != [len(batch) for batch in schedules[VERIFIED]]:\n",
    "        raise AssertionError(\"The batch schedule changed between arms.\")\n",
    "    return schedules, expected\n",
    "\n",
    "\n",
    "def adapter_digest(model):\n",
    "    digest = hashlib.sha256()\n",
    "    for name, parameter in model.named_parameters():\n",
    "        if not parameter.requires_grad:\n",
    "            continue\n",
    "        if \".lora_\" not in name:\n",
    "            raise AssertionError(f\"Unexpected trainable weight {name}.\")\n",
    "        digest.update(name.encode(\"utf-8\"))\n",
    "        digest.update(parameter.detach().cpu().contiguous().numpy().tobytes())\n",
    "    return digest.hexdigest()\n",
    "\n",
    "\n",
    "def assert_fit_budget(training, expected):\n",
    "    baseline, corrected = training[RAW], training[VERIFIED]\n",
    "    for name, stats in training.items():\n",
    "        plan = expected[name]\n",
    "        if stats[\"attempted_updates\"] != plan[\"updates\"] or stats[\"updates\"] != plan[\"updates\"]:\n",
    "            raise AssertionError(f\"{name} skipped a scheduled update.\")\n",
    "        if stats[\"supervised_response_tokens\"] != plan[\"supervised_response_tokens\"]:\n",
    "            raise AssertionError(f\"{name} saw an unexpected number of supervised tokens.\")\n",
    "        if stats[\"unpadded_input_tokens\"] != plan[\"prompt_tokens\"] + plan[\"supervised_response_tokens\"]:\n",
    "            raise AssertionError(f\"{name} saw an unexpected number of unpadded tokens.\")\n",
    "        if stats[\"initial_adapter_sha256\"] == stats[\"trained_adapter_sha256\"]:\n",
    "            raise AssertionError(f\"{name} adapter did not change during training.\")\n",
    "    for metric in (\"initial_adapter_sha256\", \"base_revision\", \"updates\", \"trainable_parameters\"):\n",
    "        if baseline[metric] != corrected[metric]:\n",
    "            raise AssertionError(f\"{metric} differs between matched arms.\")\n",
    "\n",
    "\n",
    "def paired_evidence(scores, evaluation_items):\n",
    "    roster = [(row.key, row.family, row.split) for row in evaluation_items]\n",
    "    for name, rows in scores.items():\n",
    "        if [(row[\"key\"], row[\"family\"], row[\"split\"]) for row in rows] != roster:\n",
    "            raise AssertionError(f\"{name} returned predictions on a different evaluation roster.\")\n",
    "\n",
    "    transitions = {split: Counter(fixed=0, regressed=0, both_exact=0, both_wrong=0) for split in TEACHING_SPLITS}\n",
    "    examples = {}\n",
    "    for item, raw, verified in zip(evaluation_items, scores[RAW], scores[VERIFIED], strict=True):\n",
    "        if raw[\"exact\"] == verified[\"exact\"]:\n",
    "            outcome = \"both_exact\" if raw[\"exact\"] else \"both_wrong\"\n",
    "        else:\n",
    "            outcome = \"fixed\" if verified[\"exact\"] else \"regressed\"\n",
    "        transitions[item.split][outcome] += 1\n",
    "        if outcome != \"both_exact\" and item.split in (\"novel\", \"independent\"):\n",
    "            examples.setdefault(outcome, {\n",
    "                \"invoice_key\": item.key, \"split\": item.split, \"visible_invoice\": invoice_text(item),\n",
    "                \"reference\": invoice_record(item), RAW: raw[\"answer\"], VERIFIED: verified[\"answer\"],\n",
    "            })\n",
    "    return {\n",
    "        split: {\"n\": sum(counts.values()), **dict(counts)}\n",
    "        for split, counts in transitions.items()\n",
    "    }, examples\n",
    "\n",
    "\n",
    "def write_audit_evidence(raw, verified, lineage, evaluation_items, paired_examples):\n",
    "    evidence = {\n",
    "        \"candidate_lineage\": lineage,\n",
    "        \"changed_labels\": [\n",
    "            {\n",
    "                \"invoice_key\": invoice.key, \"visible_invoice\": invoice_text(invoice),\n",
    "                RAW: json.loads(raw_answer), VERIFIED: json.loads(verified_answer),\n",
    "            }\n",
    "            for (invoice, raw_answer), (_, verified_answer) in zip(raw, verified, strict=True)\n",
    "            if raw_answer != verified_answer\n",
    "        ],\n",
    "        \"held_out_documents\": {invoice.key: invoice_text(invoice) for invoice in evaluation_items},\n",
    "        \"held_out_examples\": paired_examples,\n",
    "    }\n",
    "    Path(\"results/02-audit.json\").write_text(json.dumps(evidence, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "    return evidence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e6ae56d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Catalogue split counts {'train': 576, 'dev': 72, 'familiar': 96, 'novel': 96, 'independent': 48, 'release': 120}\n",
      "Candidate and retained rows 210 192\n",
      "Audit ledger {'wrong currency': 21, 'duplicate visible invoice': 18, 'dropped row': 22, 'wrong total': 21}\n",
      "Retained and corrected by family {'train-05': Counter({'retained': 8, 'corrected': 3}), 'train-18': Counter({'retained': 8, 'corrected': 3}), 'train-23': Counter({'retained': 8, 'corrected': 2}), 'train-13': Counter({'retained': 8, 'corrected': 3}), 'train-10': Counter({'retained': 8, 'corrected': 3}), 'train-17': Counter({'retained': 8, 'corrected': 2}), 'train-11': Counter({'retained': 8, 'corrected': 3}), 'train-14': Counter({'retained': 8, 'corrected': 3}), 'train-16': Counter({'retained': 8, 'corrected': 2}), 'train-01': Counter({'retained': 8, 'corrected': 3}), 'train-12': Counter({'retained': 8, 'corrected': 3}), 'train-21': Counter({'retained': 8, 'corrected': 2}), 'train-06': Counter({'retained': 8, 'corrected': 3}), 'train-09': Counter({'retained': 8, 'corrected': 3}), 'train-02': Counter({'retained': 8, 'corrected': 2}), 'train-22': Counter({'retained': 8, 'corrected': 3}), 'train-04': Counter({'retained': 8, 'corrected': 3}), 'train-19': Counter({'retained': 8, 'corrected': 2}), 'train-07': Counter({'retained': 8, 'corrected': 3}), 'train-08': Counter({'retained': 8, 'corrected': 3}), 'train-00': Counter({'retained': 8, 'corrected': 2}), 'train-03': Counter({'retained': 8, 'corrected': 3}), 'train-20': Counter({'retained': 8, 'corrected': 3}), 'train-15': Counter({'retained': 8, 'corrected': 2})}\n",
      "Planned training exposure {'Raw labels': {'rows': 192, 'updates': 96, 'prompt_tokens': 79312, 'supervised_response_tokens': 20976}, 'Verified labels': {'rows': 192, 'updates': 96, 'prompt_tokens': 79312, 'supervised_response_tokens': 21378}}\n"
     ]
    }
   ],
   "source": [
    "split_counts = assert_split_lineage(catalogue, chosen, exemplar, evaluation_items)\n",
    "if len(chosen) != TRAIN_ROWS:\n",
    "    raise AssertionError(\"The requested training roster is unavailable.\")\n",
    "retained_per_family = Counter(row.family for row in chosen)\n",
    "train_families = {row.family for row in catalogue if row.split == \"train\"}\n",
    "if set(retained_per_family) != train_families or len(set(retained_per_family.values())) != 1:\n",
    "    raise AssertionError(\"Choose a whole number of balanced training-family rounds.\")\n",
    "\n",
    "raw, verified, ledger, lineage = audit_labels(\n",
    "    chosen, [*reserved, exemplar], fault_period=FAULT_PERIOD,\n",
    ")\n",
    "coverage = {}\n",
    "for entry in lineage:\n",
    "    if entry[\"disposition\"] == \"duplicate\":\n",
    "        continue\n",
    "    counts = coverage.setdefault(entry[\"family\"], Counter(retained=0, corrected=0))\n",
    "    counts[\"retained\"] += 1\n",
    "    counts[\"corrected\"] += entry[\"disposition\"] == \"corrected\"\n",
    "\n",
    "schedules, expected_budget = checked_schedule(tokenizer, raw, verified, exemplar)\n",
    "print(\"Catalogue split counts\", split_counts)\n",
    "print(\"Candidate and retained rows\", len(lineage), len(raw))\n",
    "print(\"Audit ledger\", dict(ledger))\n",
    "print(\"Retained and corrected by family\", coverage)\n",
    "print(\"Planned training exposure\", expected_budget)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3aaed37a",
   "metadata": {},
   "source": [
    "## Can a valid record still be wrong?\n",
    "\n",
    "Read the currency in the visible invoice. Decide which target you would keep before\n",
    "looking at the exact check. Both targets parse. The check compares the contents\n",
    "with the fixture and therefore sees the difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7b41151b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample Supplier 6320 billing memo / 2026-03-15\n",
      "Account invoice SF-460242 [USD]\n",
      "8 x Door seal @ 232.41 per unit\n",
      "5 x Grounding clip @ 81.05 per unit\n",
      "9 x Bench calibration @ 23.19 per unit\n",
      "Total due 2,646.37 including tax 173.13; net amount 2,473.24.\n",
      "Raw labels currency GBP schema valid True exact record False\n",
      "Verified labels currency USD schema valid True exact record True\n"
     ]
    }
   ],
   "source": [
    "invoice, raw_answer = raw[0]\n",
    "_, verified_answer = verified[0]\n",
    "print(invoice_text(invoice))\n",
    "for name, answer in ((RAW, raw_answer), (VERIFIED, verified_answer)):\n",
    "    check = score_record(answer, invoice)\n",
    "    print(name, \"currency\", json.loads(answer)[\"currency\"],\n",
    "          \"schema valid\", check[\"valid\"], \"exact record\", check[\"exact\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "398a7787",
   "metadata": {},
   "source": [
    "## What do the baselines extract?\n",
    "\n",
    "Evaluate the register-layout rules and the prompted checkpoint on the same documents\n",
    "before fitting either adapter. The prompted baseline uses the same training exemplar\n",
    "and greedy generation cap as the adapters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1a4f5311",
   "metadata": {},
   "outputs": [],
   "source": [
    "for item in evaluation_items:\n",
    "    if len(encode_prompt(tokenizer, item, exemplar)) + MAX_NEW_TOKENS > MAX_TOKENS:\n",
    "        raise AssertionError(f\"Evaluation token budget exceeded for {item.key}.\")\n",
    "\n",
    "evaluation_layout_counts = {\n",
    "    split: dict(Counter(row.layout for row in evaluation_items if row.split == split))\n",
    "    for split in TEACHING_SPLITS\n",
    "}\n",
    "scores = {\"Register-layout rules\": rules_predictions(evaluation_items)}\n",
    "base = load_model(\"fp16\")\n",
    "scores[\"FP16 prompted\"] = predictions(base, tokenizer, evaluation_items, exemplar, batch_size=EVAL_BATCH)\n",
    "del base\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "485a6ae3",
   "metadata": {},
   "source": [
    "## Which exposure differs between branches?\n",
    "\n",
    "Reload the pinned parent and reset adapter initialisation and optimiser state for each\n",
    "arm. Both arms see the same documents, prompt tokens and updates. A dropped row can change\n",
    "answer length, so report supervised response tokens separately. The check rejects skipped\n",
    "optimiser steps rather than treating equal attempted counts as an equal fit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c8e8a9b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "result_dir = Path(\"results\")\n",
    "result_dir.mkdir(exist_ok=True)\n",
    "training = {}\n",
    "for name, schedule in schedules.items():\n",
    "    model = load_model(\"fp16\", trainable=True)\n",
    "    base_revision = model.get_base_model().config._commit_hash\n",
    "    if DEVICE == \"cuda\" and base_revision != REVISION:\n",
    "        raise AssertionError(\"The loaded base model revision differs from the course pin.\")\n",
    "    initial_digest = adapter_digest(model)\n",
    "    training[name] = adapter_train(\n",
    "        model, schedule, sft_objective(tokenizer.pad_token_id, DEVICE),\n",
    "        learning_rate=LEARNING_RATE, use_cuda=DEVICE == \"cuda\",\n",
    "    )\n",
    "    training[name].update(\n",
    "        base_revision=base_revision, initial_adapter_sha256=initial_digest,\n",
    "        trained_adapter_sha256=adapter_digest(model),\n",
    "    )\n",
    "    scores[name] = predictions(model, tokenizer, evaluation_items, exemplar, batch_size=EVAL_BATCH)\n",
    "    slug = name.lower().replace(\" \", \"-\")\n",
    "    model.save_pretrained(result_dir / f\"02-{slug}-adapter\")\n",
    "    del model\n",
    "    free_gpu()\n",
    "assert_fit_budget(training, expected_budget)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf973d9b",
   "metadata": {},
   "source": [
    "## Did the corrections transfer?\n",
    "\n",
    "Count records fixed and records made worse on the same held-out invoices. Resample\n",
    "entire supplier families for the paired interval. If that interval includes zero,\n",
    "these data leave the direction uncertain. Examine a representative failure alongside\n",
    "its invoice and reference even when the average barely moves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "64b2d7e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"model_id\": \"Qwen/Qwen2.5-0.5B-Instruct\",\n",
      "  \"model_revision\": \"7ae557604adf67be50417f59c2c2f167def9a775\",\n",
      "  \"seed\": 42,\n",
      "  \"versions\": {\n",
      "    \"torch\": \"2.14.1+cu130\",\n",
      "    \"transformers\": \"4.51.3\",\n",
      "    \"peft\": \"0.15.2\"\n",
      "  },\n",
      "  \"hardware\": \"Tesla T4\",\n",
      "  \"held_out_roster_sha256\": \"08d508621745254e22a48017d6c826fb58310adec0604290fbe8f07e4db1af55\",\n",
      "  \"scores\": {\n",
      "    \"Register-layout rules\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.25,\n",
      "        \"exact\": 0.25,\n",
      "        \"completed\": 0.25,\n",
      "        \"fields\": 0.25,\n",
      "        \"row_f1\": 0.25\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.0,\n",
      "        \"exact\": 0.0,\n",
      "        \"completed\": 0.0,\n",
      "        \"fields\": 0.0,\n",
      "        \"row_f1\": 0.0\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.0,\n",
      "        \"exact\": 0.0,\n",
      "        \"completed\": 0.0,\n",
      "        \"fields\": 0.0,\n",
      "        \"row_f1\": 0.0\n",
      "      }\n",
      "    },\n",
      "    \"FP16 prompted\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.5833333333333334,\n",
      "        \"exact\": 0.14583333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.5163690476190477,\n",
      "        \"row_f1\": 0.359375\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.8229166666666666,\n",
      "        \"exact\": 0.010416666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.7410714285714286,\n",
      "        \"row_f1\": 0.04965277777777778\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.75,\n",
      "        \"exact\": 0.125,\n",
      "        \"completed\": 0.9791666666666666,\n",
      "        \"fields\": 0.6309523809523809,\n",
      "        \"row_f1\": 0.4722222222222222\n",
      "      }\n",
      "    },\n",
      "    \"Raw labels\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 1.0,\n",
      "        \"exact\": 0.875,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9821428571428571,\n",
      "        \"row_f1\": 1.0\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.96875,\n",
      "        \"exact\": 0.4895833333333333,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9226190476190476,\n",
      "        \"row_f1\": 0.70625\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.9166666666666666,\n",
      "        \"exact\": 0.6458333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.8660714285714286,\n",
      "        \"row_f1\": 0.8472222222222222\n",
      "      }\n",
      "    },\n",
      "    \"Verified labels\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 1.0,\n",
      "        \"exact\": 0.9895833333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9985119047619048,\n",
      "        \"row_f1\": 1.0\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9583333333333334,\n",
      "        \"exact\": 0.5729166666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9151785714285714,\n",
      "        \"row_f1\": 0.71875\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.9375,\n",
      "        \"exact\": 0.5416666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.8452380952380952,\n",
      "        \"row_f1\": 0.9375\n",
      "      }\n",
      "    }\n",
      "  },\n",
      "  \"paired_family_intervals\": {\n",
      "    \"Verified labels minus Raw labels\": {\n",
      "      \"familiar\": [\n",
      "        -0.020833333333333332,\n",
      "        0.375\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        -0.08333333333333333,\n",
      "        0.2708333333333333\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        -0.2916666666666667,\n",
      "        0.14583333333333334\n",
      "      ]\n",
      "    }\n",
      "  },\n",
      "  \"diagnostics\": {\n",
      "    \"catalogue_version\": \"course-invoice-v1\",\n",
      "    \"split_counts\": {\n",
      "      \"train\": 576,\n",
      "      \"dev\": 72,\n",
      "      \"familiar\": 96,\n",
      "      \"novel\": 96,\n",
      "      \"independent\": 48,\n",
      "      \"release\": 120\n",
      "    },\n",
      "    \"label_audit\": {\n",
      "      \"wrong currency\": 21,\n",
      "      \"duplicate visible invoice\": 18,\n",
      "      \"dropped row\": 22,\n",
      "      \"wrong total\": 21\n",
      "    },\n",
      "    \"candidate_rows\": 210,\n",
      "    \"matched_rows\": 192,\n",
      "    \"exemplar_key\": \"SF-898991\",\n",
      "    \"family_coverage\": {\n",
      "      \"train-05\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-18\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-23\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-13\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-10\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-17\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-11\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-14\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-16\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-01\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-12\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-21\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-06\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-09\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-02\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-22\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-04\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-19\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-07\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-08\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-00\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      },\n",
      "      \"train-03\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-20\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 3\n",
      "      },\n",
      "      \"train-15\": {\n",
      "        \"retained\": 8,\n",
      "        \"corrected\": 2\n",
      "      }\n",
      "    },\n",
      "    \"planned_exposure\": {\n",
      "      \"Raw labels\": {\n",
      "        \"rows\": 192,\n",
      "        \"updates\": 96,\n",
      "        \"prompt_tokens\": 79312,\n",
      "        \"supervised_response_tokens\": 20976\n",
      "      },\n",
      "      \"Verified labels\": {\n",
      "        \"rows\": 192,\n",
      "        \"updates\": 96,\n",
      "        \"prompt_tokens\": 79312,\n",
      "        \"supervised_response_tokens\": 21378\n",
      "      }\n",
      "    },\n",
      "    \"evaluation_layout_counts\": {\n",
      "      \"familiar\": {\n",
      "        \"register\": 24,\n",
      "        \"memo\": 24,\n",
      "        \"checkout\": 24,\n",
      "        \"ledger\": 24\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"packing\": 24,\n",
      "        \"remittance\": 24,\n",
      "        \"service\": 24,\n",
      "        \"notice\": 24\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"separate\": 48\n",
      "      }\n",
      "    },\n",
      "    \"paired_exact_counts\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"fixed\": 12,\n",
      "        \"regressed\": 1,\n",
      "        \"both_exact\": 83,\n",
      "        \"both_wrong\": 0\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"fixed\": 15,\n",
      "        \"regressed\": 7,\n",
      "        \"both_exact\": 40,\n",
      "        \"both_wrong\": 34\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"fixed\": 6,\n",
      "        \"regressed\": 11,\n",
      "        \"both_exact\": 20,\n",
      "        \"both_wrong\": 11\n",
      "      }\n",
      "    },\n",
      "    \"batch_size\": 2,\n",
      "    \"learning_rate\": 0.0002,\n",
      "    \"fault_period\": 3,\n",
      "    \"max_new_tokens\": 384,\n",
      "    \"accelerate_version\": \"1.6.0\"\n",
      "  }\n",
      "}\n",
      "{\n",
      "  \"Raw labels\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 20976,\n",
      "    \"unpadded_input_tokens\": 100288,\n",
      "    \"seconds\": 26.893052922000038,\n",
      "    \"supervised_tokens_per_second\": 779.978385527232,\n",
      "    \"peak_gib\": 4.131346225738525,\n",
      "    \"trainable_parameters\": 540672,\n",
      "    \"base_revision\": \"7ae557604adf67be50417f59c2c2f167def9a775\",\n",
      "    \"initial_adapter_sha256\": \"6179c9628d836aa224240cf360178225cf25340b476b6701c2fa3d685d794234\",\n",
      "    \"trained_adapter_sha256\": \"7af011fff1f675d8d9dffd5bc0e084b60e7182438d2971c579a633c7105441bd\"\n",
      "  },\n",
      "  \"Verified labels\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 21378,\n",
      "    \"unpadded_input_tokens\": 100690,\n",
      "    \"seconds\": 31.985744952000005,\n",
      "    \"supervised_tokens_per_second\": 668.3602346007975,\n",
      "    \"peak_gib\": 4.131834506988525,\n",
      "    \"trainable_parameters\": 540672,\n",
      "    \"base_revision\": \"7ae557604adf67be50417f59c2c2f167def9a775\",\n",
      "    \"initial_adapter_sha256\": \"6179c9628d836aa224240cf360178225cf25340b476b6701c2fa3d685d794234\",\n",
      "    \"trained_adapter_sha256\": \"1948ad8fa3bd41b3f55a84468f9fb324f71c94ac4c72a7e33876cab970b2be04\"\n",
      "  }\n",
      "}\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" width=\"784.9825pt\" height=\"285.03625pt\" viewBox=\"0 0 784.9825 285.03625\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2026-11-27T06:26:19.960167</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.10.0, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 285.03625  L 784.9825 285.03625  L 784.9825 0  L 0 0  z \" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 117.310938 247.48  L 317.087604 247.48  L 317.087604 52.08  L 117.310938 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 117.310938 60.961818  L 167.255104 60.961818  L 167.255104 98.358947  L 117.310938 98.358947  z \" clip-path=\"url(#paeb654309f)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 117.310938 107.70823  L 146.445035 107.70823  L 146.445035 145.105359  L 117.310938 145.105359  z \" clip-path=\"url(#paeb654309f)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 117.310938 154.454641  L 292.115521 154.454641  L 292.115521 191.85177  L 117.310938 191.85177  z \" clip-path=\"url(#paeb654309f)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 117.310938 201.201053  L 315.006597 201.201053  L 315.006597 238.598182  L 117.310938 238.598182  z \" clip-path=\"url(#paeb654309f)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 117.310938 247.48  L 117.310938 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"mb9d4e2a5b9\" d=\"M 0 0  L 0 3.5  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"117.310938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"117.310938\" y=\"262.078437\" transform=\"rotate(-0 117.310938 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 157.266271 247.48  L 157.266271 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"157.266271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"157.266271\" y=\"262.078437\" transform=\"rotate(-0 157.266271 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 197.221604 247.48  L 197.221604 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"197.221604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"197.221604\" y=\"262.078437\" transform=\"rotate(-0 197.221604 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 237.176937 247.48  L 237.176937 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"237.176937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"237.176937\" y=\"262.078437\" transform=\"rotate(-0 237.176937 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 277.132271 247.48  L 277.132271 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"277.132271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"277.132271\" y=\"262.078437\" transform=\"rotate(-0 277.132271 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 317.087604 247.48  L 317.087604 52.08  \" clip-path=\"url(#paeb654309f)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"317.087604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"317.087604\" y=\"262.078437\" transform=\"rotate(-0 317.087604 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_7\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"217.199271\" y=\"275.756562\" transform=\"rotate(-0 217.199271 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <defs>\n",
       "       <path id=\"md0e429fa02\" d=\"M 0 0  L -3.5 0  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"117.310938\" y=\"79.660383\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"83.459602\" transform=\"rotate(-0 110.310938 83.459602)\">Register-layout rules</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"117.310938\" y=\"126.406794\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"130.206013\" transform=\"rotate(-0 110.310938 130.206013)\">FP16 prompted</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"117.310938\" y=\"173.153206\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"176.952424\" transform=\"rotate(-0 110.310938 176.952424)\">Raw labels</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"117.310938\" y=\"219.899617\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"223.698836\" transform=\"rotate(-0 110.310938 223.698836)\">Verified labels</text>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 117.310938 247.48  L 117.310938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_8\">\n",
       "    <path d=\"M 317.087604 247.48  L 317.087604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_9\">\n",
       "    <path d=\"M 117.310938 247.48  L 317.087604 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_10\">\n",
       "    <path d=\"M 117.310938 52.08  L 317.087604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_12\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"217.199271\" y=\"46.08\" transform=\"rotate(-0 217.199271 46.08)\">Familiar</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"axes_2\">\n",
       "   <g id=\"patch_11\">\n",
       "    <path d=\"M 343.682604 247.48  L 543.459271 247.48  L 543.459271 52.08  L 343.682604 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_12\">\n",
       "    <path d=\"M 343.682604 60.961818  L 343.682604 60.961818  L 343.682604 98.358947  L 343.682604 98.358947  z \" clip-path=\"url(#p23d5154504)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_13\">\n",
       "    <path d=\"M 343.682604 107.70823  L 345.763611 107.70823  L 345.763611 145.105359  L 343.682604 145.105359  z \" clip-path=\"url(#p23d5154504)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_14\">\n",
       "    <path d=\"M 343.682604 154.454641  L 441.489931 154.454641  L 441.489931 191.85177  L 343.682604 191.85177  z \" clip-path=\"url(#p23d5154504)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_15\">\n",
       "    <path d=\"M 343.682604 201.201053  L 458.137986 201.201053  L 458.137986 238.598182  L 343.682604 238.598182  z \" clip-path=\"url(#p23d5154504)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_3\">\n",
       "    <g id=\"xtick_7\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <path d=\"M 343.682604 247.48  L 343.682604 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_18\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"343.682604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_13\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"343.682604\" y=\"262.078437\" transform=\"rotate(-0 343.682604 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_8\">\n",
       "     <g id=\"line2d_19\">\n",
       "      <path d=\"M 383.637937 247.48  L 383.637937 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_20\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"383.637937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_14\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"383.637937\" y=\"262.078437\" transform=\"rotate(-0 383.637937 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_9\">\n",
       "     <g id=\"line2d_21\">\n",
       "      <path d=\"M 423.593271 247.48  L 423.593271 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_22\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"423.593271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_15\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"423.593271\" y=\"262.078437\" transform=\"rotate(-0 423.593271 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_10\">\n",
       "     <g id=\"line2d_23\">\n",
       "      <path d=\"M 463.548604 247.48  L 463.548604 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_24\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"463.548604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_16\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"463.548604\" y=\"262.078437\" transform=\"rotate(-0 463.548604 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_11\">\n",
       "     <g id=\"line2d_25\">\n",
       "      <path d=\"M 503.503938 247.48  L 503.503938 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_26\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"503.503938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_17\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"503.503938\" y=\"262.078437\" transform=\"rotate(-0 503.503938 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_12\">\n",
       "     <g id=\"line2d_27\">\n",
       "      <path d=\"M 543.459271 247.48  L 543.459271 52.08  \" clip-path=\"url(#p23d5154504)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_28\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"543.459271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_18\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"543.459271\" y=\"262.078437\" transform=\"rotate(-0 543.459271 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_19\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"443.570938\" y=\"275.756562\" transform=\"rotate(-0 443.570938 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_4\">\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_29\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"343.682604\" y=\"79.660383\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_6\">\n",
       "     <g id=\"line2d_30\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"343.682604\" y=\"126.406794\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_7\">\n",
       "     <g id=\"line2d_31\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"343.682604\" y=\"173.153206\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_8\">\n",
       "     <g id=\"line2d_32\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"343.682604\" y=\"219.899617\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_16\">\n",
       "    <path d=\"M 343.682604 247.48  L 343.682604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_17\">\n",
       "    <path d=\"M 543.459271 247.48  L 543.459271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_18\">\n",
       "    <path d=\"M 343.682604 247.48  L 543.459271 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_19\">\n",
       "    <path d=\"M 343.682604 52.08  L 543.459271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_20\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"443.570938\" y=\"46.08\" transform=\"rotate(-0 443.570938 46.08)\">Novel</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"axes_3\">\n",
       "   <g id=\"patch_20\">\n",
       "    <path d=\"M 570.054271 247.48  L 769.830938 247.48  L 769.830938 52.08  L 570.054271 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_21\">\n",
       "    <path d=\"M 570.054271 60.961818  L 570.054271 60.961818  L 570.054271 98.358947  L 570.054271 98.358947  z \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_22\">\n",
       "    <path d=\"M 570.054271 107.70823  L 595.026354 107.70823  L 595.026354 145.105359  L 570.054271 145.105359  z \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_23\">\n",
       "    <path d=\"M 570.054271 154.454641  L 699.076701 154.454641  L 699.076701 191.85177  L 570.054271 191.85177  z \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_24\">\n",
       "    <path d=\"M 570.054271 201.201053  L 678.266632 201.201053  L 678.266632 238.598182  L 570.054271 238.598182  z \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_5\">\n",
       "    <g id=\"xtick_13\">\n",
       "     <g id=\"line2d_33\">\n",
       "      <path d=\"M 570.054271 247.48  L 570.054271 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_34\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"570.054271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_21\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"570.054271\" y=\"262.078437\" transform=\"rotate(-0 570.054271 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_14\">\n",
       "     <g id=\"line2d_35\">\n",
       "      <path d=\"M 610.009604 247.48  L 610.009604 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_36\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"610.009604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_22\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"610.009604\" y=\"262.078437\" transform=\"rotate(-0 610.009604 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_15\">\n",
       "     <g id=\"line2d_37\">\n",
       "      <path d=\"M 649.964937 247.48  L 649.964937 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_38\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"649.964937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_23\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"649.964937\" y=\"262.078437\" transform=\"rotate(-0 649.964937 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_16\">\n",
       "     <g id=\"line2d_39\">\n",
       "      <path d=\"M 689.920271 247.48  L 689.920271 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_40\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"689.920271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_24\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"689.920271\" y=\"262.078437\" transform=\"rotate(-0 689.920271 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_17\">\n",
       "     <g id=\"line2d_41\">\n",
       "      <path d=\"M 729.875604 247.48  L 729.875604 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_42\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"729.875604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_25\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"729.875604\" y=\"262.078437\" transform=\"rotate(-0 729.875604 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_18\">\n",
       "     <g id=\"line2d_43\">\n",
       "      <path d=\"M 769.830938 247.48  L 769.830938 52.08  \" clip-path=\"url(#pf9ea191ca7)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_44\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb9d4e2a5b9\" x=\"769.830938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_26\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"769.830938\" y=\"262.078437\" transform=\"rotate(-0 769.830938 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_27\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"669.942604\" y=\"275.756562\" transform=\"rotate(-0 669.942604 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_6\">\n",
       "    <g id=\"ytick_9\">\n",
       "     <g id=\"line2d_45\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"570.054271\" y=\"79.660383\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_10\">\n",
       "     <g id=\"line2d_46\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"570.054271\" y=\"126.406794\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_11\">\n",
       "     <g id=\"line2d_47\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"570.054271\" y=\"173.153206\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_12\">\n",
       "     <g id=\"line2d_48\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md0e429fa02\" x=\"570.054271\" y=\"219.899617\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_25\">\n",
       "    <path d=\"M 570.054271 247.48  L 570.054271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_26\">\n",
       "    <path d=\"M 769.830938 247.48  L 769.830938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_27\">\n",
       "    <path d=\"M 570.054271 247.48  L 769.830938 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_28\">\n",
       "    <path d=\"M 570.054271 52.08  L 769.830938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_28\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"669.942604\" y=\"46.08\" transform=\"rotate(-0 669.942604 46.08)\">Independent</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"text_29\">\n",
       "   <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"392.550937\" y=\"16.318125\" transform=\"rotate(-0 392.550937 16.318125)\">Complete-record accuracy on the held-out invoice slices</text>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"paeb654309f\">\n",
       "   <rect x=\"117.310938\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"p23d5154504\">\n",
       "   <rect x=\"343.682604\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"pf9ea191ca7\">\n",
       "   <rect x=\"570.054271\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>"
      ],
      "text/plain": [
       "<IPython.core.display.SVG object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Worked training record SF-460242\n",
      "both_wrong SF-265176 novel\n",
      "fixed SF-797533 novel\n",
      "regressed SF-781239 novel\n",
      "Result files: 02-report.json, 02-predictions.json, 02-audit.json, 02-exact.svg in results/\n"
     ]
    }
   ],
   "source": [
    "paired_counts, paired_examples = paired_evidence(scores, evaluation_items)\n",
    "report = save_results(\n",
    "    \"02\", scores, training, [(RAW, VERIFIED)],\n",
    "    catalogue_version=CATALOG_VERSION, split_counts=split_counts,\n",
    "    label_audit=dict(ledger), candidate_rows=len(lineage), matched_rows=len(raw),\n",
    "    exemplar_key=exemplar.key, family_coverage=coverage, planned_exposure=expected_budget,\n",
    "    evaluation_layout_counts=evaluation_layout_counts,\n",
    "    paired_exact_counts=paired_counts, batch_size=BATCH, learning_rate=LEARNING_RATE,\n",
    "    fault_period=FAULT_PERIOD, max_new_tokens=MAX_NEW_TOKENS,\n",
    "    accelerate_version=importlib.metadata.version(\"accelerate\"),\n",
    ")\n",
    "evidence = write_audit_evidence(raw, verified, lineage, evaluation_items, paired_examples)\n",
    "print(\"Worked training record\", evidence[\"changed_labels\"][0][\"invoice_key\"])\n",
    "for outcome, example in paired_examples.items():\n",
    "    print(outcome, example[\"invoice_key\"], example[\"split\"])\n",
    "print(\"Result files: 02-report.json, 02-predictions.json, 02-audit.json, 02-exact.svg in results/\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4642f095",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Compare the paired exact counts first, then inspect field and row metrics to see what\n",
    "changed. Follow the worked training invoice into the audit file. For a follow-up,\n",
    "change `FAULT_PERIOD` and rerun both arms on the original held-out roster.\n",
    "\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/1-build-the-data/02-audit-synthetic-data) for the full interpretation.\n",
    "[Self-Instruct](https://aclanthology.org/2023.acl-long.754/) documents a generated\n",
    "instruction pipeline and a manual audit of its remaining label errors."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
