{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "57e36ba1",
   "metadata": {},
   "source": [
    "# Distil traces and protect existing skills\n",
    "\n",
    "    You maintain an accounts-payable parser. Invoice **SF-157375** has three lines and a printed\n",
    "    amount due of **USD 1,158.82**. Its line quantities and prices yield a net of **USD 1,082.07**.\n",
    "    Adding the printed tax of **USD 75.74** gives **USD 1,157.81**. Which total should the assistant\n",
    "    put into the training record? Open the first example cell to check the source and grade the\n",
    "    candidate answers.\n",
    "\n",
    "    Your next adapter needs to handle invoices with several rows while preserving extraction on\n",
    "    familiar one-line invoices. The training batch has a fixed number of places. Decide whether to\n",
    "    reserve some for familiar examples, and whether to teach the calculation alongside the record.\n",
    "\n",
    "    Select a **Tesla T4** in Colab and run all cells in order. Allow **35–55 minutes** for the main\n",
    "    comparisons including setup. The optional diagnostic may need another **10–20 minutes**.\n",
    "    The inputs are synthetic invoices and the teacher runs locally. [Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/2-compare-training-stages/05-distil-verified-traces)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a41cb5db",
   "metadata": {},
   "source": [
    "## 0. Prepare the runtime\n",
    "\n",
    "    The public Qwen checkpoint is pinned by revision. The shared T4 runtime can reuse its cached\n",
    "    weights. Training uses the course's explicit assistant-token batching and loss loop with PEFT\n",
    "    LoRA. Evaluation generates one answer per invoice with a fixed greedy decoding budget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d958ebea",
   "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', 'matplotlib==3.10.8', 'pandas==2.3.3', 'numpy==2.2.6'], returncode=0)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import subprocess\n",
    "import sys\n",
    "\n",
    "PINS = ('transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0', 'matplotlib==3.10.8', 'pandas==2.3.3', 'numpy==2.2.6')\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *PINS], check=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a10cd2f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name(0):\n",
    "    raise RuntimeError(\"Select a Tesla T4 in Colab before running the fitted comparison.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e4afbcc",
   "metadata": {},
   "source": [
    "## 1. Read the fixture, contract and shared helpers\n",
    "\n",
    "    The independent parser checks JSON keys, types and every captured value. The catalogue supplies\n",
    "    visible text and reference records. Both the teacher and the scorer work on local data. The\n",
    "    teacher's calculation line is checked separately from the source fields in its final record."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "622bafb4",
   "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": "code",
   "execution_count": 4,
   "id": "08c645d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SPDX-License-Identifier: Apache-2.0\n",
    "# Adapted from the Together Post-Training Cookbook revision 226e03ca225d6f13434047cf0f45ab3070a29801.\n",
    "from collections.abc import Callable, Iterable, Sequence\n",
    "from dataclasses import field\n",
    "from typing import NamedTuple, TypeVar\n",
    "\n",
    "Item = TypeVar(\"Item\")\n",
    "\n",
    "class Turn(NamedTuple):\n",
    "    prompt: list[int]\n",
    "    completion: list[int]\n",
    "\n",
    "class MaskedSequence(NamedTuple):\n",
    "    input_ids: list[int]\n",
    "    completion_mask: list[int]\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",
    "@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",
    "@dataclass(frozen=True)\n",
    "class TeacherOutput:\n",
    "    content: str\n",
    "    ok: bool = True\n",
    "    truncated: bool = False\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",
    "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": "code",
   "execution_count": 5,
   "id": "96a5247f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gc\n",
    "import hashlib\n",
    "import time\n",
    "from collections import defaultdict\n",
    "from importlib.metadata import version\n",
    "from pathlib import Path\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from peft import LoraConfig, PeftModel, get_peft_model\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed\n",
    "\n",
    "MODEL_ID = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
    "MODEL_REV = \"7ae557604adf67be50417f59c2c2f167def9a775\"\n",
    "SEED = 42\n",
    "DEVICE = \"cuda\"\n",
    "DTYPE = torch.float16\n",
    "PROMPT_LIMIT = 512\n",
    "ANSWER_LIMIT = 256\n",
    "OUT = Path(\"lesson-results\")\n",
    "SYSTEM = VISIBLE_CONTRACT\n",
    "TRAINER_PINS = dict(pin.split(\"==\") for pin in ('transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0', 'matplotlib==3.10.8', 'pandas==2.3.3', 'numpy==2.2.6'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b9f92a24",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dialogs(invoice, system=SYSTEM):\n",
    "    return [{\"role\": \"system\", \"content\": system}, {\"role\": \"user\", \"content\": invoice_text(invoice)}]\n",
    "\n",
    "def packed(record):\n",
    "    return json.dumps(record, ensure_ascii=False, separators=(\",\", \":\"))\n",
    "\n",
    "def prepare_kernel():\n",
    "    pins = globals().get(\"TRAINER_PINS\", {})\n",
    "    installed = {name: version(name) for name in pins}\n",
    "    if installed != pins:\n",
    "        raise RuntimeError(f\"Restart the kernel and install the pinned training packages: {installed}\")\n",
    "    if not torch.cuda.is_available():\n",
    "        raise RuntimeError(\"Select a T4 GPU in Colab before running all cells.\")\n",
    "    name = torch.cuda.get_device_name(0)\n",
    "    if \"T4\" not in name:\n",
    "        raise RuntimeError(f\"Expected a Colab T4 for comparable timings; found {name}.\")\n",
    "    OUT.mkdir(exist_ok=True)\n",
    "    set_seed(SEED)\n",
    "    tok = AutoTokenizer.from_pretrained(MODEL_ID, revision=MODEL_REV, trust_remote_code=False)\n",
    "    tok.padding_side = \"left\"\n",
    "    if tok.pad_token is None:\n",
    "        tok.pad_token = tok.eos_token\n",
    "    print(name, \"|\", torch.__version__, \"| revision\", MODEL_REV[:12])\n",
    "    print(\"Trainer packages\", installed, \"| CUDA\", torch.version.cuda)\n",
    "    return tok\n",
    "\n",
    "def manifest(invoices):\n",
    "    rows = sorted(\n",
    "        (invoice.key, invoice.family, invoice.split, invoice_text(invoice), invoice_record(invoice))\n",
    "        for invoice in invoices\n",
    "    )\n",
    "    return hashlib.sha256(packed(rows).encode()).hexdigest()\n",
    "\n",
    "def model_at(source=MODEL_ID):\n",
    "    options = {\"revision\": MODEL_REV} if source == MODEL_ID else {}\n",
    "    model = AutoModelForCausalLM.from_pretrained(\n",
    "        source, **options, torch_dtype=DTYPE, device_map={\"\": DEVICE},\n",
    "        trust_remote_code=False, attn_implementation=\"sdpa\", use_safetensors=True,\n",
    "    )\n",
    "    if source == MODEL_ID and model.config._commit_hash != MODEL_REV:\n",
    "        raise RuntimeError(\"Loaded weights do not match the pinned revision.\")\n",
    "    return model\n",
    "\n",
    "def clean_memory():\n",
    "    gc.collect()\n",
    "    if DEVICE == \"cuda\":\n",
    "        torch.cuda.empty_cache()\n",
    "\n",
    "def lora():\n",
    "    return LoraConfig(\n",
    "        r=8, lora_alpha=16, lora_dropout=0.0,\n",
    "        target_modules=[\"q_proj\", \"v_proj\", \"o_proj\"], task_type=\"CAUSAL_LM\",\n",
    "    )\n",
    "\n",
    "def eos_ids(model, tok):\n",
    "    value = model.generation_config.eos_token_id\n",
    "    ids = value if isinstance(value, list) else [value]\n",
    "    return {token for token in [tok.eos_token_id, *ids] if token is not None}\n",
    "\n",
    "@torch.inference_mode()\n",
    "def evaluate(model, tok, invoices, *, system=SYSTEM, answer_limit=ANSWER_LIMIT, extract=lambda text: text):\n",
    "    model.eval()\n",
    "    model.config.use_cache = True\n",
    "    output = []\n",
    "    eos = eos_ids(model, tok)\n",
    "    for i in range(0, len(invoices), 8):\n",
    "        part = invoices[i:i + 8]\n",
    "        rendered = [tok.apply_chat_template(dialogs(invoice, system), tokenize=False, add_generation_prompt=True)\n",
    "                    for invoice in part]\n",
    "        batch = tok(rendered, add_special_tokens=False, return_tensors=\"pt\", padding=True).to(DEVICE)\n",
    "        if batch.input_ids.shape[1] > PROMPT_LIMIT:\n",
    "            raise ValueError(\"An evaluation prompt exceeded the declared token budget.\")\n",
    "        if DEVICE == \"cuda\":\n",
    "            torch.cuda.synchronize()\n",
    "        started = time.perf_counter()\n",
    "        tokens = model.generate(**batch, max_new_tokens=answer_limit, do_sample=False,\n",
    "                                pad_token_id=tok.pad_token_id)[:, batch.input_ids.shape[1]:]\n",
    "        if DEVICE == \"cuda\":\n",
    "            torch.cuda.synchronize()\n",
    "        latency = (time.perf_counter() - started) * 1000 / len(part)\n",
    "        texts = tok.batch_decode(tokens, skip_special_tokens=True)\n",
    "        for invoice, token_row, text in zip(part, tokens.tolist(), texts, strict=True):\n",
    "            boundary = next((index for index, token in enumerate(token_row) if token in eos), None)\n",
    "            record = score_record(extract(text), invoice)\n",
    "            output.append({\n",
    "                \"key\": invoice.key, \"family\": invoice.family, \"split\": invoice.split,\n",
    "                \"valid\": float(record[\"valid\"]), \"exact\": float(record[\"exact\"]),\n",
    "                \"fields\": record[\"fields\"], \"row_f1\": float(record[\"row_f1\"]),\n",
    "                \"natural_completion\": boundary is not None,\n",
    "                \"generated_tokens\": len(token_row) if boundary is None else boundary + 1,\n",
    "                \"ms_per_example_in_batch\": latency,\n",
    "                \"completion\": text,\n",
    "            })\n",
    "    return output\n",
    "\n",
    "def evaluate_at(source, tok, invoices, *, adapter=None, **kwargs):\n",
    "    base = model_at(source)\n",
    "    model = PeftModel.from_pretrained(base, adapter) if adapter else base\n",
    "    scores = evaluate(model, tok, invoices, **kwargs)\n",
    "    del model, base\n",
    "    clean_memory()\n",
    "    return scores\n",
    "\n",
    "def summary(scores):\n",
    "    mean = lambda key: sum(row[key] for row in scores) / len(scores)\n",
    "    return {\n",
    "        \"n\": len(scores), \"exact\": mean(\"exact\"), \"valid\": mean(\"valid\"),\n",
    "        \"row_f1\": mean(\"row_f1\"), \"natural_completion\": mean(\"natural_completion\"),\n",
    "        \"mean_generated_tokens\": mean(\"generated_tokens\"),\n",
    "        \"mean_ms_per_example_in_batch\": mean(\"ms_per_example_in_batch\"),\n",
    "    }\n",
    "\n",
    "def paired_change(before, after, *, score=\"exact\", seed=SEED):\n",
    "    left = {row[\"key\"]: row for row in before}\n",
    "    right = {row[\"key\"]: row for row in after}\n",
    "    assert set(left) == set(right) and len(left) == len(before) == len(after)\n",
    "    by_family = defaultdict(list)\n",
    "    for key, row in sorted(left.items()):\n",
    "        by_family[row[\"family\"]].append(right[key][score] - row[score])\n",
    "    changes = [value for values in by_family.values() for value in values]\n",
    "    groups = list(by_family.values())\n",
    "    rng = random.Random(seed)\n",
    "    boot = []\n",
    "    if len(groups) >= 2:\n",
    "        for _ in range(2000):\n",
    "            sampled = [value for group in rng.choices(groups, k=len(groups)) for value in group]\n",
    "            boot.append(sum(sampled) / len(sampled))\n",
    "    return {\n",
    "        \"delta\": sum(changes) / len(changes), \"n\": len(changes), \"families\": len(groups),\n",
    "        \"improved\": sum(change > 0 for change in changes),\n",
    "        \"regressed\": sum(change < 0 for change in changes),\n",
    "        \"tied\": sum(change == 0 for change in changes),\n",
    "        \"paired_family_bootstrap_95\": np.quantile(boot, [0.025, 0.975]).tolist() if boot else None,\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8cd282db",
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_schedule(examples, batch_size=4):\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",
    "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",
    "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",
    "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",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0e4c26af",
   "metadata": {},
   "outputs": [],
   "source": [
    "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()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b99ee891",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Build and audit procedural teacher labels from training invoices.\"\"\"\n",
    "\n",
    "BASE = \"Prompted base\"\n",
    "DIRECT = \"Direct answers\"\n",
    "TARGET = \"Target-only traces\"\n",
    "MIXED = \"Mixed traces\"\n",
    "EQUAL = \"Equal-target diagnostic\"\n",
    "OPENING_ID = \"SF-157375\"\n",
    "\n",
    "TRACE_SYSTEM = (\n",
    "    VISIBLE_CONTRACT.replace(\"Extract exactly one JSON object\", \"Return one final JSON object\").removesuffix(\n",
    "        \" Do not rewrite printed amounts, invent fields, or add explanations.\"\n",
    "    )\n",
    "    + \" Do not rewrite printed amounts or invent fields. A bare JSON object is allowed. \"\n",
    "      \"For a worked answer use CALC quantity * unit_minor + ... = net_minor, a newline, \"\n",
    "      \"then RECORD and one space before the JSON.\"\n",
    ")\n",
    "RECORD_MARKER = \"\\nRECORD \"\n",
    "CALC_LINE = re.compile(r\"CALC [0-9]+ \\* [0-9]+(?: \\+ [0-9]+ \\* [0-9]+)* = [0-9]+\")\n",
    "\n",
    "\n",
    "def extract_record(text):\n",
    "    text = text.strip()\n",
    "    prefix, marker, record = text.partition(RECORD_MARKER)\n",
    "    if marker and CALC_LINE.fullmatch(prefix):\n",
    "        return record.strip()\n",
    "    return text\n",
    "\n",
    "\n",
    "def calculation(invoice):\n",
    "    terms = \" + \".join(f\"{row.quantity} * {row.unit_minor}\" for row in invoice.items)\n",
    "    net = sum(row.quantity * row.unit_minor for row in invoice.items)\n",
    "    return f\"CALC {terms} = {net}\"\n",
    "\n",
    "\n",
    "def teacher_outputs(invoices):\n",
    "    \"\"\"Generate and reconcile an accepted and rejected candidate ledger.\"\"\"\n",
    "    requests, outputs = [], {}\n",
    "    fixture_map = {invoice.key: invoice for invoice in invoices}\n",
    "    if len(fixture_map) != len(invoices) or any(invoice.split != \"train\" for invoice in invoices):\n",
    "        raise ValueError(\"The teacher requires distinct training invoices.\")\n",
    "\n",
    "    for position, invoice in enumerate(invoices):\n",
    "        record = invoice_record(invoice)\n",
    "        trace = calculation(invoice)\n",
    "        correct = trace + RECORD_MARKER + packed(record)\n",
    "        origin = {\"invoice_key\": invoice.key, \"group\": \"target\" if len(invoice.items) == 3 else \"retention\"}\n",
    "        prompts = dialogs(invoice, TRACE_SYSTEM)\n",
    "        variants = {\"verified\": TeacherOutput(correct)}\n",
    "        if position % 17 == 0:\n",
    "            variants[\"truncated\"] = TeacherOutput(correct[:-8], truncated=True)\n",
    "        if position % 19 == 0:\n",
    "            inferred_total = record[\"subtotal_minor\"] + record[\"tax_minor\"]\n",
    "            if inferred_total == record[\"total_minor\"]:\n",
    "                inferred_total += 1\n",
    "            wrong_record = {**record, \"total_minor\": inferred_total}\n",
    "            variants[\"wrong-record\"] = TeacherOutput(trace + RECORD_MARKER + packed(wrong_record))\n",
    "        if position % 23 == 0:\n",
    "            before, _, net = trace.rpartition(\" = \")\n",
    "            variants[\"wrong-trace\"] = TeacherOutput(f\"{before} = {int(net) + 1}{RECORD_MARKER}{packed(record)}\")\n",
    "        for variant, output in variants.items():\n",
    "            key = f\"{invoice.key}/{variant}\"\n",
    "            requests.append(TeacherRequest(key, prompts, {**origin, \"variant\": variant}))\n",
    "            outputs[key] = output\n",
    "\n",
    "    def reject(request, output):\n",
    "        invoice = fixture_map[request.meta[\"invoice_key\"]]\n",
    "        prefix, marker, record = output.content.partition(RECORD_MARKER)\n",
    "        if prefix != calculation(invoice) or not marker:\n",
    "            return \"arithmetic_trace\"\n",
    "        if not score_record(record, invoice)[\"exact\"]:\n",
    "            return \"record_verifier\"\n",
    "        return None\n",
    "\n",
    "    verified, rejects = sft_rows(requests, outputs, reject_reason=reject)\n",
    "    accepted_ids = {row[\"id\"] for row in verified}\n",
    "    if len(verified) != len(invoices) or accepted_ids != {f\"{row.key}/verified\" for row in invoices}:\n",
    "        raise AssertionError(\"Every train invoice needs exactly one accepted trace.\")\n",
    "    ledger = [\n",
    "        {\n",
    "            \"candidate_id\": request.key,\n",
    "            **request.meta,\n",
    "            \"decision\": \"accepted\" if request.key in accepted_ids else (\n",
    "                \"truncated\" if outputs[request.key].truncated else reject(request, outputs[request.key])\n",
    "            ),\n",
    "            \"completion\": outputs[request.key].content,\n",
    "        }\n",
    "        for request in requests\n",
    "    ]\n",
    "    if Counter(row[\"decision\"] for row in ledger) != Counter(accepted=len(verified), **rejects):\n",
    "        raise AssertionError(\"Teacher ledger does not reconcile with filtering totals.\")\n",
    "    return verified, ledger\n",
    "\n",
    "\n",
    "def locked_slices(catalog):\n",
    "    \"\"\"Check fit, development and teaching groups before generating any labels.\"\"\"\n",
    "    all_keys = {invoice.key for invoice in catalog}\n",
    "    if len(all_keys) != len(catalog):\n",
    "        raise ValueError(\"Duplicate invoice keys in the catalogue.\")\n",
    "    eligible = [invoice for invoice in catalog if invoice.split != \"release\"]\n",
    "    known = {\"train\", \"dev\", \"familiar\", \"novel\", \"independent\"}\n",
    "    if {row.split for row in eligible} != known:\n",
    "        raise ValueError(\"The catalogue must contain exactly the declared lesson splits.\")\n",
    "    for field in (lambda row: row.family, lambda row: row.supplier, invoice_text):\n",
    "        seen = {}\n",
    "        for invoice in eligible:\n",
    "            value = field(invoice)\n",
    "            previous = seen.setdefault(value, invoice.split)\n",
    "            if previous != invoice.split:\n",
    "                raise ValueError(f\"Overlap between {previous} and {invoice.split}.\")\n",
    "    train = [row for row in eligible if row.split == \"train\" and len(row.items) in (1, 3)]\n",
    "    dev = {\n",
    "        name: [row for row in eligible if row.split == \"dev\" and len(row.items) == line_count]\n",
    "        for name, line_count in ((\"one line\", 1), (\"three lines\", 3))\n",
    "    }\n",
    "    heldout = {\n",
    "        \"Difficult\": [row for row in eligible if row.split in (\"novel\", \"independent\") and len(row.items) == 3],\n",
    "        \"Familiar\": [row for row in eligible if row.split == \"familiar\" and len(row.items) == 1],\n",
    "    }\n",
    "    if not train or not all(dev.values()) or not all(heldout.values()):\n",
    "        raise ValueError(\"Every declared group needs examples.\")\n",
    "    train_layouts = {row.layout for row in train}\n",
    "    if train_layouts.intersection(row.layout for row in heldout[\"Difficult\"]):\n",
    "        raise ValueError(\"Difficult test layouts must be held out from training.\")\n",
    "    if any(row.layout not in train_layouts for row in heldout[\"Familiar\"]):\n",
    "        raise ValueError(\"Familiar test layouts must occur in training.\")\n",
    "    return train, dev, heldout\n",
    "\n",
    "\n",
    "def matched_teacher_arms(train, size=128, batch_size=4, seed=SEED):\n",
    "    \"\"\"Match total updates in the main arms and expose one optional diagnostic schedule.\"\"\"\n",
    "    if size <= 0 or batch_size <= 0 or batch_size % 2 or size % batch_size:\n",
    "        raise ValueError(\"The positive train size must divide into full, even batches.\")\n",
    "    order = list(train)\n",
    "    random.Random(seed).shuffle(order)\n",
    "    opening = next(row for row in order if row.key == OPENING_ID)\n",
    "    order.remove(opening)\n",
    "    order.insert(0, opening)\n",
    "    verified, ledger = teacher_outputs(order)\n",
    "    groups = {\n",
    "        name: [row for row in verified if row[\"meta\"][\"group\"] == name]\n",
    "        for name in (\"target\", \"retention\")\n",
    "    }\n",
    "    target, retention = groups[\"target\"][:size], groups[\"retention\"][:size // 2]\n",
    "    if len(target) != size or len(retention) != size // 2:\n",
    "        raise ValueError(\"The teacher returned too few labels to build matched arms.\")\n",
    "    half = batch_size // 2\n",
    "    mixed = []\n",
    "    for start in range(0, size // 2, half):\n",
    "        mixed.extend(mix(target[start:start + half], retention[start:start + half], seed=seed + start))\n",
    "    equal = [row for row in mixed if row[\"meta\"][\"group\"] == \"target\"]\n",
    "    selections = {DIRECT: mixed, TARGET: target, MIXED: mixed, EQUAL: equal}\n",
    "    return selections, ledger\n",
    "\n",
    "\n",
    "def completion(row, *, with_trace):\n",
    "    response = row[\"messages\"][-1][\"content\"]\n",
    "    return response if with_trace else extract_record(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6ccad902",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Build the masked update schedule and record the paired evidence.\"\"\"\n",
    "\n",
    "TRAIN_ROWS = 128\n",
    "TRAIN_BATCH = 4\n",
    "LEARNING_RATE = 2e-4\n",
    "SHORT_CAP = 128\n",
    "RUN_EQUAL_TARGET_DIAGNOSTIC = False\n",
    "\n",
    "\n",
    "def encode_schedule(selections, tok):\n",
    "    if tok.pad_token_id is None or tok.eos_token_id is None:\n",
    "        raise ValueError(\"The pinned tokenizer must supply padding and end markers.\")\n",
    "    schedules, exposure, lineage = {}, {}, {}\n",
    "    for arm, rows in selections.items():\n",
    "        examples, lineage[arm] = [], []\n",
    "        batch_size = TRAIN_BATCH // 2 if arm == EQUAL else TRAIN_BATCH\n",
    "        seen = set()\n",
    "        for position, row in enumerate(rows):\n",
    "            key = row[\"meta\"][\"invoice_key\"]\n",
    "            if key in seen:\n",
    "                raise ValueError(f\"{arm} repeats training invoice {key}.\")\n",
    "            seen.add(key)\n",
    "            prompt = tok.apply_chat_template(row[\"messages\"][:-1], tokenize=True, add_generation_prompt=True)\n",
    "            answer = completion(row, with_trace=arm != DIRECT)\n",
    "            response = tok.encode(answer, add_special_tokens=False) + [tok.eos_token_id]\n",
    "            if not prompt or len(response) <= 1 or len(prompt) > PROMPT_LIMIT or len(response) > ANSWER_LIMIT:\n",
    "                raise ValueError(f\"The prompt or supervised label for {key} exceeds the declared token contract.\")\n",
    "            sequence, = split_turns([Turn(prompt, response)])\n",
    "            if sequence.input_ids != prompt + response or sequence.completion_mask != [0] * len(prompt) + [1] * len(response):\n",
    "                raise AssertionError(f\"{key} lost its exact assistant-only token boundary.\")\n",
    "            examples.append(sequence)\n",
    "            lineage[arm].append({\n",
    "                \"invoice_key\": key, \"candidate_id\": row[\"id\"], \"group\": row[\"meta\"][\"group\"],\n",
    "                \"update\": position // batch_size + 1, \"prompt_tokens\": len(prompt),\n",
    "                \"response_tokens\": len(response), \"completion\": answer,\n",
    "            })\n",
    "        schedules[arm] = make_schedule(examples, batch_size=batch_size)\n",
    "        for batch in schedules[arm]:\n",
    "            masked = right_pad(batch, tok.pad_token_id, \"cpu\")[\"labels\"]\n",
    "            for index, row in enumerate(batch):\n",
    "                expected = [bool(weight) for weight in row.completion_mask]\n",
    "                expected += [False] * (masked.shape[1] - len(expected))\n",
    "                if masked[index].ne(-100).tolist() != expected:\n",
    "                    raise AssertionError(\"Prompt and padding tokens must be excluded from the loss.\")\n",
    "        exposure[arm] = {\n",
    "            \"rows\": len(rows), \"updates\": len(schedules[arm]), \"batch_size\": batch_size,\n",
    "            \"target_rows\": sum(row[\"group\"] == \"target\" for row in lineage[arm]),\n",
    "            \"retention_rows\": sum(row[\"group\"] == \"retention\" for row in lineage[arm]),\n",
    "            \"prompt_tokens\": sum(row[\"prompt_tokens\"] for row in lineage[arm]),\n",
    "            \"response_tokens\": sum(row[\"response_tokens\"] for row in lineage[arm]),\n",
    "            \"max_prompt_tokens\": max(row[\"prompt_tokens\"] for row in lineage[arm]),\n",
    "            \"max_response_tokens\": max(row[\"response_tokens\"] for row in lineage[arm]),\n",
    "        }\n",
    "\n",
    "    main_budget = (\"rows\", \"updates\", \"batch_size\")\n",
    "    if any(exposure[arm][name] != exposure[MIXED][name] for arm in (DIRECT, TARGET) for name in main_budget):\n",
    "        raise AssertionError(\"The main arms must match document and update counts.\")\n",
    "    if [row[\"messages\"][:-1] for row in selections[DIRECT]] != [row[\"messages\"][:-1] for row in selections[MIXED]]:\n",
    "        raise AssertionError(\"Direct and mixed must use the same prompts in the same order.\")\n",
    "    matched_targets = [row for row in lineage[MIXED] if row[\"group\"] == \"target\"]\n",
    "    if matched_targets != lineage[EQUAL]:\n",
    "        raise AssertionError(\"The diagnostic must see the identical target labels at each update.\")\n",
    "    return schedules, exposure, lineage\n",
    "\n",
    "\n",
    "def fit_trace_adapter(schedule, tok, name):\n",
    "    set_seed(SEED)\n",
    "    model = get_peft_model(model_at(), lora(), revision=MODEL_REV)\n",
    "    initial = adapter_digest(model)\n",
    "    stats = adapter_train(\n",
    "        model, schedule, sft_objective(tok.pad_token_id, DEVICE), learning_rate=LEARNING_RATE, use_cuda=True,\n",
    "    )\n",
    "    stats[\"initial_adapter_sha256\"] = initial\n",
    "    stats[\"trained_adapter_sha256\"] = adapter_digest(model)\n",
    "    checkpoint = OUT / name\n",
    "    model.save_pretrained(checkpoint, safe_serialization=True)\n",
    "    del model\n",
    "    clean_memory()\n",
    "    return str(checkpoint), stats\n",
    "\n",
    "\n",
    "def check_training_receipt(training, exposure):\n",
    "    if len({row[\"initial_adapter_sha256\"] for row in training.values()}) != 1:\n",
    "        raise AssertionError(\"All fitted adapters must use the same initial parameters.\")\n",
    "    for arm, stats in training.items():\n",
    "        plan = exposure[arm]\n",
    "        if stats[\"updates\"] != plan[\"updates\"] or stats[\"attempted_updates\"] != plan[\"updates\"]:\n",
    "            raise AssertionError(f\"{arm} skipped an optimiser update.\")\n",
    "        if stats[\"supervised_response_tokens\"] != plan[\"response_tokens\"]:\n",
    "            raise AssertionError(f\"{arm} saw an unexpected number of response tokens.\")\n",
    "        if stats[\"unpadded_input_tokens\"] != plan[\"prompt_tokens\"] + plan[\"response_tokens\"]:\n",
    "            raise AssertionError(f\"{arm} saw an unexpected number of input tokens.\")\n",
    "        if stats[\"initial_adapter_sha256\"] == stats[\"trained_adapter_sha256\"]:\n",
    "            raise AssertionError(f\"{arm} did not change its LoRA weights.\")\n",
    "\n",
    "\n",
    "def prepare_evaluation(scores, invoices):\n",
    "    roster = [(row.key, row.family, row.split) for row in invoices]\n",
    "    for arm, rows in scores.items():\n",
    "        if [(row[\"key\"], row[\"family\"], row[\"split\"]) for row in rows] != roster:\n",
    "            raise AssertionError(f\"{arm} returned different evaluation keys, families or ordering.\")\n",
    "        for row, invoice in zip(rows, invoices, strict=True):\n",
    "            prefix, marker, _ = row[\"completion\"].strip().partition(RECORD_MARKER)\n",
    "            score = score_record(extract_record(row[\"completion\"]), invoice)\n",
    "            row.update({\n",
    "                \"line_count\": len(invoice.items),\n",
    "                \"trace_present\": bool(marker and CALC_LINE.fullmatch(prefix)),\n",
    "                \"trace_correct\": bool(marker and prefix == calculation(invoice)),\n",
    "                \"field_correct\": score[\"field_correct\"],\n",
    "            })\n",
    "\n",
    "\n",
    "def measured_slices(heldout, predictions):\n",
    "    scores, paired = {}, {}\n",
    "    contrasts = {\n",
    "        \"mixed_minus_target\": (TARGET, MIXED),\n",
    "        \"mixed_minus_direct\": (DIRECT, MIXED),\n",
    "        \"mixed_minus_base\": (BASE, MIXED),\n",
    "    }\n",
    "    if EQUAL in predictions:\n",
    "        contrasts[\"mixed_minus_equal_target\"] = (EQUAL, MIXED)\n",
    "    for name, items in heldout.items():\n",
    "        keys = {row.key for row in items}\n",
    "        sliced = {arm: [row for row in values if row[\"key\"] in keys] for arm, values in predictions.items()}\n",
    "        scores[name] = {arm: {**summary(rows), \"families\": len({row[\"family\"] for row in rows})}\n",
    "                        for arm, rows in sliced.items()}\n",
    "        paired[name] = {}\n",
    "        for contrast, (before, after) in contrasts.items():\n",
    "            left, right = sliced[before], sliced[after]\n",
    "            changed = paired_change(left, right)\n",
    "            changed[\"both_exact\"] = sum(bool(x[\"exact\"] and y[\"exact\"]) for x, y in zip(left, right, strict=True))\n",
    "            changed[\"both_wrong\"] = changed[\"tied\"] - changed[\"both_exact\"]\n",
    "            paired[name][contrast] = changed\n",
    "    return scores, paired\n",
    "\n",
    "\n",
    "def write_evidence(report, audit, predictions, sensitivity):\n",
    "    payloads = {\"report\": report, \"audit\": audit, \"predictions\": predictions, \"cap-predictions\": sensitivity}\n",
    "    for suffix, payload in payloads.items():\n",
    "        path = OUT / f\"05-{suffix}.json\"\n",
    "        path.write_text(json.dumps(payload, indent=2, allow_nan=False) + \"\\n\", encoding=\"utf-8\")\n",
    "        print(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "1bcd0271",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Controlled probability distillation on held-out invoice line counts.\"\"\"\n",
    "\n",
    "\n",
    "def soft_cross_entropy(logits, target):\n",
    "    return -(target * torch.log_softmax(logits.float(), -1)).sum(-1).mean()\n",
    "\n",
    "\n",
    "def confidence_ece(probabilities, gold, bins=10):\n",
    "    confidence, prediction = probabilities.max(dim=-1)\n",
    "    correct = prediction.eq(gold).float()\n",
    "    error = torch.zeros(())\n",
    "    for index in range(bins):\n",
    "        lower, upper = index / bins, (index + 1) / bins\n",
    "        selected = (confidence >= lower) & ((confidence < upper) if index + 1 < bins else (confidence <= 1))\n",
    "        if selected.any():\n",
    "            error += selected.float().mean() * (correct[selected].mean() - confidence[selected].mean()).abs()\n",
    "    return float(error)\n",
    "\n",
    "\n",
    "def grade_classes(predicted, gold):\n",
    "    return {\n",
    "        str(label + 1): {\n",
    "            \"n\": int((gold == label).sum()),\n",
    "            \"correct\": int(((gold == label) & (predicted == gold)).sum()),\n",
    "        }\n",
    "        for label in range(3)\n",
    "    }\n",
    "\n",
    "\n",
    "def soft_split(items):\n",
    "    # This diagnostic isolates transfer of label noise, so the feature is a deterministic count\n",
    "    # of visible line-item rows. An end-to-end extraction score is measured separately.\n",
    "    labels = torch.tensor([len(invoice_record(item)[\"line_items\"]) - 1 for item in items])\n",
    "    visible_counts = [sum(bool(re.fullmatch(\n",
    "        r\"(?:[^|]+ \\| \\d+ \\| .+|\\d+ x .+ per unit|.+ each for \\d+ units|Unit .+ / \\d+ times / .+)\",\n",
    "        line,\n",
    "    )) for line in invoice_text(item).splitlines()) for item in items]\n",
    "    assert all(1 <= count <= 3 for count in visible_counts)\n",
    "    features = torch.nn.functional.one_hot(torch.tensor(visible_counts) - 1, num_classes=3).float()\n",
    "    teacher_classes = labels.clone()\n",
    "    teacher_classes[labels == 2] = 1\n",
    "    teacher = torch.full_like(features, 0.035)\n",
    "    teacher.scatter_(1, teacher_classes[:, None], 0.93)\n",
    "    return features, labels, teacher\n",
    "\n",
    "\n",
    "def run_soft_target_diagnostic(catalog, device):\n",
    "    groups = {\n",
    "        name: [row for row in catalog if row.split == split]\n",
    "        for name, split in ((\"train\", \"train\"), (\"gold_validation\", \"dev\"), (\"test\", \"novel\"))\n",
    "    }\n",
    "    # Keep whole families out of checkpoint selection when assigning calibration rows.\n",
    "    families = sorted({row.family for row in groups[\"gold_validation\"]})\n",
    "    calibration_families = set(families[::2])\n",
    "    groups[\"calibration\"] = [row for row in groups[\"gold_validation\"] if row.family in calibration_families]\n",
    "    groups[\"gold_validation\"] = [row for row in groups[\"gold_validation\"] if row.family not in calibration_families]\n",
    "    assert sum(len({row.key for row in group}) for group in groups.values()) == len({\n",
    "        row.key for group in groups.values() for row in group\n",
    "    })\n",
    "    assert sum(len({row.family for row in group}) for group in groups.values()) == len({\n",
    "        row.family for group in groups.values() for row in group\n",
    "    })\n",
    "    splits = {name: soft_split(rows) for name, rows in groups.items()}\n",
    "    audit = {name: grade_classes(teacher.argmax(-1), gold) for name, (_, gold, teacher) in splits.items()}\n",
    "    print(\"Teacher versus gold before fitting:\", audit)\n",
    "    absent = [label for label, row in audit[\"test\"].items() if row[\"n\"] == 0]\n",
    "    if absent:\n",
    "        print(\"Absent held-out classes:\", absent)\n",
    "    blind = [int(label) - 1 for label, row in audit[\"gold_validation\"].items() if row[\"n\"] and not row[\"correct\"]]\n",
    "    assert blind == [2], \"The declared teacher fault must be visible in gold validation.\"\n",
    "    train_x, train_y, train_teacher = splits[\"train\"]\n",
    "    val_x, val_y, val_teacher = splits[\"gold_validation\"]\n",
    "    dtype = torch.float16 if device == \"cuda\" else torch.float32\n",
    "    results = {}\n",
    "    for mode in (\"soft\", \"hybrid\"):\n",
    "        # A fixed gold warm start represents an incumbent student before distillation.\n",
    "        weight = torch.nn.Parameter(torch.eye(3, device=device) * 0.5)\n",
    "        bias = torch.nn.Parameter(torch.zeros(3, device=device))\n",
    "        optimiser = torch.optim.SGD((weight, bias), lr=1.0)\n",
    "        targets = train_teacher.clone()\n",
    "        if mode == \"hybrid\":\n",
    "            for label in blind:\n",
    "                selected = train_y == label\n",
    "                targets[selected] = torch.nn.functional.one_hot(train_y[selected], num_classes=3).float()\n",
    "        def logits(features):\n",
    "            return features.to(device=device, dtype=dtype) @ weight.to(dtype=dtype) + bias.to(dtype=dtype)\n",
    "        epochs, checkpoints = [], []\n",
    "        for epoch in range(21):\n",
    "            if epoch:\n",
    "                optimiser.zero_grad()\n",
    "                loss = soft_cross_entropy(logits(train_x), targets.to(device))\n",
    "                loss.backward()\n",
    "                optimiser.step()\n",
    "            with torch.no_grad():\n",
    "                prediction = logits(val_x).cpu().argmax(-1)\n",
    "                epochs.append({\n",
    "                    \"epoch\": epoch,\n",
    "                    \"gold_accuracy\": float(prediction.eq(val_y).float().mean()),\n",
    "                    \"teacher_agreement\": float(prediction.eq(val_teacher.argmax(-1)).float().mean()),\n",
    "                })\n",
    "                checkpoints.append((weight.detach().clone(), bias.detach().clone()))\n",
    "\n",
    "        selected = {}\n",
    "        for criterion in (\"teacher_agreement\", \"gold_accuracy\"):\n",
    "            epoch = max(epochs, key=lambda row: (row[criterion], row[\"epoch\"]))[\"epoch\"]\n",
    "            with torch.no_grad():\n",
    "                weight.copy_(checkpoints[epoch][0])\n",
    "                bias.copy_(checkpoints[epoch][1])\n",
    "                cal_x, cal_y, _ = splits[\"calibration\"]\n",
    "                cal_logits = logits(cal_x).float().cpu()\n",
    "                temperatures = torch.logspace(-1, 1, 81)\n",
    "                losses = [float(torch.nn.functional.cross_entropy(cal_logits / temp, cal_y)) for temp in temperatures]\n",
    "                temperature = float(temperatures[losses.index(min(losses))])\n",
    "                test_x, test_y, _ = splits[\"test\"]\n",
    "                test_logits = logits(test_x).float().cpu()\n",
    "                selected[criterion] = {\n",
    "                    **epochs[epoch],\n",
    "                    \"temperature\": temperature,\n",
    "                    \"calibration_examples\": len(cal_y),\n",
    "                    \"calibration_nll_before\": float(torch.nn.functional.cross_entropy(cal_logits, cal_y)),\n",
    "                    \"calibration_nll_after\": min(losses),\n",
    "                    \"test_gold_by_class\": grade_classes(test_logits.argmax(-1), test_y),\n",
    "                    \"test_ece_before\": confidence_ece(test_logits.softmax(-1), test_y),\n",
    "                    \"test_ece_after\": confidence_ece((test_logits / temperature).softmax(-1), test_y),\n",
    "                }\n",
    "        results[mode] = {\"epochs\": epochs, \"selected\": selected}\n",
    "    return {\"teacher_vs_gold\": audit, \"test_classes_absent\": absent, \"hybrid_override_classes\": [i+1 for i in blind],\n",
    "            \"fit_dtype\": str(dtype), \"arms\": results,\n",
    "            \"split_keys\": {name: [row.key for row in rows] for name, rows in groups.items()}}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd7946e2",
   "metadata": {},
   "source": [
    "## 2. Grade the teacher and freeze the comparison\n",
    "\n",
    "    Compare the worked trace to the invoice. A calculation that looks right can still accompany a\n",
    "    wrongly rewritten printed total. A correct record can also accompany bad arithmetic. The ledger\n",
    "    gives the outcome for each candidate, including a deliberately cut-off answer. Keep the source's\n",
    "    printed total in the record and let a separate downstream check flag the discrepancy.\n",
    "\n",
    "    The three-line target evaluation uses novel and independent layouts. The one-line retention\n",
    "    evaluation uses known layouts with unseen suppliers. The development split compares difficulty\n",
    "    within known layouts. Invoice keys, suppliers, families and visible inputs stay disjoint by split.\n",
    "    No release record enters the experiment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b05dca01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Supplier: Sample Supplier 8777\n",
      "Invoice: SF-157375\n",
      "Issued: 2026-06-12\n",
      "Currency: USD\n",
      "Description | Quantity | Unit price\n",
      "Cooling filter | 9 | 21.85\n",
      "Packing insert | 3 | 87.63\n",
      "Mounting plate | 3 | 207.51\n",
      "Subtotal: 1,082.07\n",
      "Tax: 75.74\n",
      "Amount due: 1,158.82\n",
      "\n",
      "accepted\n",
      "CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207\n",
      "RECORD {\"invoice_id\":\"SF-157375\",\"issued_on\":\"2026-06-12\",\"supplier\":\"Sample Supplier 8777\",\"currency\":\"USD\",\"line_items\":[{\"description\":\"Cooling filter\",\"quantity\":9,\"unit_minor\":2185},{\"description\":\"Packing insert\",\"quantity\":3,\"unit_minor\":8763},{\"description\":\"Mounting plate\",\"quantity\":3,\"unit_minor\":20751}],\"subtotal_minor\":108207,\"tax_minor\":7574,\"total_minor\":115882}\n",
      "\n",
      "truncated\n",
      "CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207\n",
      "RECORD {\"invoice_id\":\"SF-157375\",\"issued_on\":\"2026-06-12\",\"supplier\":\"Sample Supplier 8777\",\"currency\":\"USD\",\"line_items\":[{\"description\":\"Cooling filter\",\"quantity\":9,\"unit_minor\":2185},{\"description\":\"Packing insert\",\"quantity\":3,\"unit_minor\":8763},{\"description\":\"Mounting plate\",\"quantity\":3,\"unit_minor\":20751}],\"subtotal_minor\":108207,\"tax_minor\":7574,\"total_minor\"\n",
      "\n",
      "record_verifier\n",
      "CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108207\n",
      "RECORD {\"invoice_id\":\"SF-157375\",\"issued_on\":\"2026-06-12\",\"supplier\":\"Sample Supplier 8777\",\"currency\":\"USD\",\"line_items\":[{\"description\":\"Cooling filter\",\"quantity\":9,\"unit_minor\":2185},{\"description\":\"Packing insert\",\"quantity\":3,\"unit_minor\":8763},{\"description\":\"Mounting plate\",\"quantity\":3,\"unit_minor\":20751}],\"subtotal_minor\":108207,\"tax_minor\":7574,\"total_minor\":115781}\n",
      "\n",
      "arithmetic_trace\n",
      "CALC 9 * 2185 + 3 * 8763 + 3 * 20751 = 108208\n",
      "RECORD {\"invoice_id\":\"SF-157375\",\"issued_on\":\"2026-06-12\",\"supplier\":\"Sample Supplier 8777\",\"currency\":\"USD\",\"line_items\":[{\"description\":\"Cooling filter\",\"quantity\":9,\"unit_minor\":2185},{\"description\":\"Packing insert\",\"quantity\":3,\"unit_minor\":8763},{\"description\":\"Mounting plate\",\"quantity\":3,\"unit_minor\":20751}],\"subtotal_minor\":108207,\"tax_minor\":7574,\"total_minor\":115882}\n",
      "Teacher candidates by decision: {'accepted': 381, 'truncated': 23, 'record_verifier': 21, 'arithmetic_trace': 17}\n",
      "Development roster: {'one line': 19, 'three lines': 28}\n",
      "Locked evaluation roster: {'Difficult': 45, 'Familiar': 25}\n"
     ]
    }
   ],
   "source": [
    "catalog = make_catalog()\n",
    "train, dev, heldout = locked_slices(catalog)\n",
    "selections, ledger = matched_teacher_arms(train, TRAIN_ROWS, TRAIN_BATCH)\n",
    "opening = next(item for item in train if item.key == OPENING_ID)\n",
    "opening_candidates = [row for row in ledger if row[\"invoice_key\"] == OPENING_ID]\n",
    "print(invoice_text(opening))\n",
    "for candidate in opening_candidates:\n",
    "    print(\"\\n\" + candidate[\"decision\"] + \"\\n\" + candidate[\"completion\"])\n",
    "print(\"Teacher candidates by decision:\", dict(Counter(row[\"decision\"] for row in ledger)))\n",
    "print(\"Development roster:\", {name: len(rows) for name, rows in dev.items()})\n",
    "print(\"Locked evaluation roster:\", {name: len(rows) for name, rows in heldout.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de9ce700",
   "metadata": {},
   "source": [
    "## 3. Test probability targets with a deliberately biased teacher\n",
    "\n",
    "    This controlled classification diagnostic uses visible line counts as features. Its scripted\n",
    "    teacher scores every three-line invoice as two lines. The train, checkpoint validation, temperature\n",
    "    calibration and novel test groups are family-disjoint. Start both students from the same fixed gold\n",
    "    incumbent, then compare selection by teacher agreement and by gold validation accuracy. Break selection\n",
    "    ties towards the latest epoch. The hybrid\n",
    "    fit replaces only the blind class's training targets with gold labels. Fit temperature on its own\n",
    "    split by minimising gold cross-entropy and measure top-label ECE on the novel test split.\n",
    "    Temperature cannot repair an incorrect argmax. This diagnostic isolates label transfer. The\n",
    "    separate trace comparison measures whole-invoice extraction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ab0827d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Teacher versus gold before fitting: {'train': {'1': {'n': 187, 'correct': 187}, '2': {'n': 195, 'correct': 195}, '3': {'n': 194, 'correct': 0}}, 'gold_validation': {'1': {'n': 9, 'correct': 9}, '2': {'n': 9, 'correct': 9}, '3': {'n': 18, 'correct': 0}}, 'test': {'1': {'n': 37, 'correct': 37}, '2': {'n': 27, 'correct': 27}, '3': {'n': 32, 'correct': 0}}, 'calibration': {'1': {'n': 10, 'correct': 10}, '2': {'n': 16, 'correct': 16}, '3': {'n': 10, 'correct': 0}}}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Absent novel test classes: []\n",
      "soft {'teacher_agreement': {'epoch': 20, 'gold_accuracy': 0.5, 'teacher_agreement': 1.0, 'temperature': 1.8836491107940674, 'calibration_examples': 36, 'calibration_nll_before': 0.9556662440299988, 'calibration_nll_after': 0.8195742964744568, 'test_gold_by_class': {'1': {'n': 37, 'correct': 37}, '2': {'n': 27, 'correct': 27}, '3': {'n': 32, 'correct': 0}}, 'test_ece_before': 0.21369695663452148, 'test_ece_after': 0.1818317025899887}, 'gold_accuracy': {'epoch': 0, 'gold_accuracy': 1.0, 'teacher_agreement': 0.5, 'temperature': 0.10000000149011612, 'calibration_examples': 36, 'calibration_nll_before': 0.7943766713142395, 'calibration_nll_after': 0.01338590495288372, 'test_gold_by_class': {'1': {'n': 37, 'correct': 37}, '2': {'n': 27, 'correct': 27}, '3': {'n': 32, 'correct': 32}}, 'test_ece_before': 0.5481373071670532, 'test_ece_after': 0.013296782970428467}}\n",
      "hybrid {'teacher_agreement': {'epoch': 20, 'gold_accuracy': 1.0, 'teacher_agreement': 0.5, 'temperature': 0.10000000149011612, 'calibration_examples': 36, 'calibration_nll_before': 0.14147122204303741, 'calibration_nll_after': 0.0, 'test_gold_by_class': {'1': {'n': 37, 'correct': 37}, '2': {'n': 27, 'correct': 27}, '3': {'n': 32, 'correct': 32}}, 'test_ece_before': 0.1291651576757431, 'test_ece_after': 0.0}, 'gold_accuracy': {'epoch': 20, 'gold_accuracy': 1.0, 'teacher_agreement': 0.5, 'temperature': 0.10000000149011612, 'calibration_examples': 36, 'calibration_nll_before': 0.14147122204303741, 'calibration_nll_after': 0.0, 'test_gold_by_class': {'1': {'n': 37, 'correct': 37}, '2': {'n': 27, 'correct': 27}, '3': {'n': 32, 'correct': 32}}, 'test_ece_before': 0.1291651576757431, 'test_ece_after': 0.0}}\n"
     ]
    }
   ],
   "source": [
    "soft_result = run_soft_target_diagnostic(catalog, DEVICE)\n",
    "OUT.mkdir(parents=True, exist_ok=True)\n",
    "(OUT / \"05-soft-targets.json\").write_text(json.dumps(soft_result, indent=2) + \"\\n\")\n",
    "print(\"Absent novel test classes:\", soft_result[\"test_classes_absent\"])\n",
    "for arm, result in soft_result[\"arms\"].items():\n",
    "    print(arm, result[\"selected\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e61f18d",
   "metadata": {},
   "source": [
    "## 4. Verify the token budget and screen the difficulty gap\n",
    "\n",
    "    Direct answers and Mixed traces use the exact same ordered inputs. The other main arm spends\n",
    "    every position on a three-line invoice. All main runs use the same update count and batch size.\n",
    "    Direct-answer targets start at the JSON. Trace targets start at CALC. Prompt and padding tokens\n",
    "    have label `-100`, and the end marker is supervised. The development result is a descriptive\n",
    "    check of the assumed difficulty gap. It does not change the locked test roster or the training mix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d7564818",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tesla T4 | 2.14.1+cu130 | revision 7ae557604adf\n",
      "Trainer packages {'transformers': '4.51.3', 'peft': '0.15.2', 'accelerate': '1.6.0', 'matplotlib': '3.10.8', 'pandas': '2.3.3', 'numpy': '2.2.6'} | CUDA 13.0\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-3b24068c-ff54-42bc-bb67-6b761048fb7f\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>rows</th>\n",
       "      <th>updates</th>\n",
       "      <th>batch_size</th>\n",
       "      <th>target_rows</th>\n",
       "      <th>retention_rows</th>\n",
       "      <th>prompt_tokens</th>\n",
       "      <th>response_tokens</th>\n",
       "      <th>max_prompt_tokens</th>\n",
       "      <th>max_response_tokens</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Direct answers</th>\n",
       "      <td>128</td>\n",
       "      <td>32</td>\n",
       "      <td>4</td>\n",
       "      <td>64</td>\n",
       "      <td>64</td>\n",
       "      <td>28403</td>\n",
       "      <td>14102</td>\n",
       "      <td>247</td>\n",
       "      <td>132</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Target-only traces</th>\n",
       "      <td>128</td>\n",
       "      <td>32</td>\n",
       "      <td>4</td>\n",
       "      <td>128</td>\n",
       "      <td>0</td>\n",
       "      <td>30478</td>\n",
       "      <td>21739</td>\n",
       "      <td>248</td>\n",
       "      <td>174</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mixed traces</th>\n",
       "      <td>128</td>\n",
       "      <td>32</td>\n",
       "      <td>4</td>\n",
       "      <td>64</td>\n",
       "      <td>64</td>\n",
       "      <td>28403</td>\n",
       "      <td>18029</td>\n",
       "      <td>247</td>\n",
       "      <td>174</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Equal-target diagnostic</th>\n",
       "      <td>64</td>\n",
       "      <td>32</td>\n",
       "      <td>2</td>\n",
       "      <td>64</td>\n",
       "      <td>0</td>\n",
       "      <td>15199</td>\n",
       "      <td>10864</td>\n",
       "      <td>247</td>\n",
       "      <td>174</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-3b24068c-ff54-42bc-bb67-6b761048fb7f')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-3b24068c-ff54-42bc-bb67-6b761048fb7f button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-3b24068c-ff54-42bc-bb67-6b761048fb7f');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                         rows  updates  batch_size  target_rows  \\\n",
       "Direct answers            128       32           4           64   \n",
       "Target-only traces        128       32           4          128   \n",
       "Mixed traces              128       32           4           64   \n",
       "Equal-target diagnostic    64       32           2           64   \n",
       "\n",
       "                         retention_rows  prompt_tokens  response_tokens  \\\n",
       "Direct answers                       64          28403            14102   \n",
       "Target-only traces                    0          30478            21739   \n",
       "Mixed traces                         64          28403            18029   \n",
       "Equal-target diagnostic               0          15199            10864   \n",
       "\n",
       "                         max_prompt_tokens  max_response_tokens  \n",
       "Direct answers                         247                  132  \n",
       "Target-only traces                     248                  174  \n",
       "Mixed traces                           247                  174  \n",
       "Equal-target diagnostic                247                  174  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-7e8c0f4a-9db1-4852-9aa5-3ba75da910b3\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>exact</th>\n",
       "      <th>valid</th>\n",
       "      <th>row_f1</th>\n",
       "      <th>natural_completion</th>\n",
       "      <th>mean_generated_tokens</th>\n",
       "      <th>mean_ms_per_example_in_batch</th>\n",
       "      <th>families</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>one line</th>\n",
       "      <td>19.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>163.263158</td>\n",
       "      <td>871.645404</td>\n",
       "      <td>6.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>three lines</th>\n",
       "      <td>28.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.25</td>\n",
       "      <td>243.142857</td>\n",
       "      <td>1075.562424</td>\n",
       "      <td>6.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-7e8c0f4a-9db1-4852-9aa5-3ba75da910b3')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-7e8c0f4a-9db1-4852-9aa5-3ba75da910b3 button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-7e8c0f4a-9db1-4852-9aa5-3ba75da910b3');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                n  exact  valid  row_f1  natural_completion  \\\n",
       "one line     19.0    0.0    0.0     0.0                1.00   \n",
       "three lines  28.0    0.0    0.0     0.0                0.25   \n",
       "\n",
       "             mean_generated_tokens  mean_ms_per_example_in_batch  families  \n",
       "one line                163.263158                    871.645404       6.0  \n",
       "three lines             243.142857                   1075.562424       6.0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tok = prepare_kernel()\n",
    "schedules, exposure, train_lineage = encode_schedule(selections, tok)\n",
    "display(pd.DataFrame(exposure).T)\n",
    "dev_roster = [item for rows in dev.values() for item in rows]\n",
    "dev_run = evaluate_at(MODEL_ID, tok, dev_roster, system=TRACE_SYSTEM, extract=extract_record)\n",
    "prepare_evaluation({BASE: dev_run}, dev_roster)\n",
    "dev_scores = {\n",
    "    name: {**summary([row for row in dev_run if row[\"line_count\"] == count]),\n",
    "           \"families\": len({row.family for row in dev[name]})}\n",
    "    for name, count in ((\"one line\", 1), (\"three lines\", 3))\n",
    "}\n",
    "display(pd.DataFrame(dev_scores).T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7259b2c8",
   "metadata": {},
   "source": [
    "## 5. Spend a fixed number of updates\n",
    "\n",
    "    Train three rank-8 LoRA adapters from the same pinned base and initial seed. Mixed traces replaces\n",
    "    half of the difficult labels with retention labels. That comparison measures the full mix policy\n",
    "    at fixed documents and updates. Direct answers keeps those mixed prompts and drops the trace from\n",
    "    every answer, which isolates the label-format choice at fixed input exposure.\n",
    "\n",
    "    For an attribution follow-up, set `RUN_EQUAL_TARGET_DIAGNOSTIC = True` before this cell. The\n",
    "    extra arm removes familiar examples from each mixed batch. It keeps the exact difficult inputs\n",
    "    and labels at each update while changing the batch size and supervised-token distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "40557745",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-61454a56-e06f-412a-b92e-aa25276adadd\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>attempted_updates</th>\n",
       "      <th>updates</th>\n",
       "      <th>supervised_response_tokens</th>\n",
       "      <th>unpadded_input_tokens</th>\n",
       "      <th>seconds</th>\n",
       "      <th>supervised_tokens_per_second</th>\n",
       "      <th>peak_gib</th>\n",
       "      <th>trainable_parameters</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Direct answers</th>\n",
       "      <td>32</td>\n",
       "      <td>32</td>\n",
       "      <td>14102</td>\n",
       "      <td>42505</td>\n",
       "      <td>11.60574</td>\n",
       "      <td>1215.088434</td>\n",
       "      <td>5.22665</td>\n",
       "      <td>884736</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Target-only traces</th>\n",
       "      <td>32</td>\n",
       "      <td>32</td>\n",
       "      <td>21739</td>\n",
       "      <td>52217</td>\n",
       "      <td>12.137243</td>\n",
       "      <td>1791.098691</td>\n",
       "      <td>5.71985</td>\n",
       "      <td>884736</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mixed traces</th>\n",
       "      <td>32</td>\n",
       "      <td>32</td>\n",
       "      <td>18029</td>\n",
       "      <td>46432</td>\n",
       "      <td>11.331899</td>\n",
       "      <td>1590.995466</td>\n",
       "      <td>5.703119</td>\n",
       "      <td>884736</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-61454a56-e06f-412a-b92e-aa25276adadd')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-61454a56-e06f-412a-b92e-aa25276adadd button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-61454a56-e06f-412a-b92e-aa25276adadd');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                   attempted_updates updates supervised_response_tokens  \\\n",
       "Direct answers                    32      32                      14102   \n",
       "Target-only traces                32      32                      21739   \n",
       "Mixed traces                      32      32                      18029   \n",
       "\n",
       "                   unpadded_input_tokens    seconds  \\\n",
       "Direct answers                     42505   11.60574   \n",
       "Target-only traces                 52217  12.137243   \n",
       "Mixed traces                       46432  11.331899   \n",
       "\n",
       "                   supervised_tokens_per_second  peak_gib trainable_parameters  \n",
       "Direct answers                      1215.088434   5.22665               884736  \n",
       "Target-only traces                  1791.098691   5.71985               884736  \n",
       "Mixed traces                        1590.995466  5.703119               884736  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "names = [DIRECT, TARGET, MIXED]\n",
    "if RUN_EQUAL_TARGET_DIAGNOSTIC:\n",
    "    names.append(EQUAL)\n",
    "adapters, training = {}, {}\n",
    "for index, arm in enumerate(names):\n",
    "    adapters[arm], training[arm] = fit_trace_adapter(schedules[arm], tok, f\"05-arm-{index}\")\n",
    "check_training_receipt(training, exposure)\n",
    "display(pd.DataFrame(training).T.drop(columns=[\"losses\", \"initial_adapter_sha256\", \"trained_adapter_sha256\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebfe155d",
   "metadata": {},
   "source": [
    "## 6. Score the difficult and familiar slices\n",
    "\n",
    "    Every method sees the same invoice-only evaluation prompt. Strict exact record requires a parsed\n",
    "    object equal to the reference, including row order and printed amounts. A declared calculation\n",
    "    line may precede the record. Arithmetic agreement on that line and natural stopping are scored\n",
    "    separately. Draw paired intervals by resampling supplier families, and report denominators for\n",
    "    each slice. Assess retention relative to the prompted base as well as to Target-only traces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8648211a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Difficult\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-f3188593-cce2-44d7-9b02-399c5a9726ab\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>exact</th>\n",
       "      <th>valid</th>\n",
       "      <th>row_f1</th>\n",
       "      <th>natural_completion</th>\n",
       "      <th>mean_generated_tokens</th>\n",
       "      <th>mean_ms_per_example_in_batch</th>\n",
       "      <th>families</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Prompted base</th>\n",
       "      <td>45.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.111111</td>\n",
       "      <td>249.066667</td>\n",
       "      <td>1090.654483</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Direct answers</th>\n",
       "      <td>45.0</td>\n",
       "      <td>0.355556</td>\n",
       "      <td>0.666667</td>\n",
       "      <td>0.600000</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>127.066667</td>\n",
       "      <td>784.596408</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Target-only traces</th>\n",
       "      <td>45.0</td>\n",
       "      <td>0.400000</td>\n",
       "      <td>0.977778</td>\n",
       "      <td>0.866667</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>170.733333</td>\n",
       "      <td>1001.634781</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mixed traces</th>\n",
       "      <td>45.0</td>\n",
       "      <td>0.311111</td>\n",
       "      <td>0.844444</td>\n",
       "      <td>0.762963</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>169.266667</td>\n",
       "      <td>1081.175285</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-f3188593-cce2-44d7-9b02-399c5a9726ab')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-f3188593-cce2-44d7-9b02-399c5a9726ab button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-f3188593-cce2-44d7-9b02-399c5a9726ab');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                       n     exact     valid    row_f1  natural_completion  \\\n",
       "Prompted base       45.0  0.000000  0.000000  0.000000            0.111111   \n",
       "Direct answers      45.0  0.355556  0.666667  0.600000            1.000000   \n",
       "Target-only traces  45.0  0.400000  0.977778  0.866667            1.000000   \n",
       "Mixed traces        45.0  0.311111  0.844444  0.762963            1.000000   \n",
       "\n",
       "                    mean_generated_tokens  mean_ms_per_example_in_batch  \\\n",
       "Prompted base                  249.066667                   1090.654483   \n",
       "Direct answers                 127.066667                    784.596408   \n",
       "Target-only traces             170.733333                   1001.634781   \n",
       "Mixed traces                   169.266667                   1081.175285   \n",
       "\n",
       "                    families  \n",
       "Prompted base           12.0  \n",
       "Direct answers          12.0  \n",
       "Target-only traces      12.0  \n",
       "Mixed traces            12.0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-2361a319-7643-4bdd-ac0e-f7ed8d0034c0\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>delta</th>\n",
       "      <th>n</th>\n",
       "      <th>families</th>\n",
       "      <th>improved</th>\n",
       "      <th>regressed</th>\n",
       "      <th>tied</th>\n",
       "      <th>paired_family_bootstrap_95</th>\n",
       "      <th>both_exact</th>\n",
       "      <th>both_wrong</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>mixed_minus_target</th>\n",
       "      <td>-0.088889</td>\n",
       "      <td>45</td>\n",
       "      <td>12</td>\n",
       "      <td>2</td>\n",
       "      <td>6</td>\n",
       "      <td>37</td>\n",
       "      <td>[-0.24489795918367346, 0.07692307692307693]</td>\n",
       "      <td>12</td>\n",
       "      <td>25</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mixed_minus_direct</th>\n",
       "      <td>-0.044444</td>\n",
       "      <td>45</td>\n",
       "      <td>12</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "      <td>37</td>\n",
       "      <td>[-0.10205389848246992, 0.0]</td>\n",
       "      <td>11</td>\n",
       "      <td>26</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mixed_minus_base</th>\n",
       "      <td>0.311111</td>\n",
       "      <td>45</td>\n",
       "      <td>12</td>\n",
       "      <td>14</td>\n",
       "      <td>0</td>\n",
       "      <td>31</td>\n",
       "      <td>[0.10198979591836735, 0.5333333333333333]</td>\n",
       "      <td>0</td>\n",
       "      <td>31</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-2361a319-7643-4bdd-ac0e-f7ed8d0034c0')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-2361a319-7643-4bdd-ac0e-f7ed8d0034c0 button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-2361a319-7643-4bdd-ac0e-f7ed8d0034c0');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                       delta   n families improved regressed tied  \\\n",
       "mixed_minus_target -0.088889  45       12        2         6   37   \n",
       "mixed_minus_direct -0.044444  45       12        3         5   37   \n",
       "mixed_minus_base    0.311111  45       12       14         0   31   \n",
       "\n",
       "                                     paired_family_bootstrap_95 both_exact  \\\n",
       "mixed_minus_target  [-0.24489795918367346, 0.07692307692307693]         12   \n",
       "mixed_minus_direct                  [-0.10205389848246992, 0.0]         11   \n",
       "mixed_minus_base      [0.10198979591836735, 0.5333333333333333]          0   \n",
       "\n",
       "                   both_wrong  \n",
       "mixed_minus_target         25  \n",
       "mixed_minus_direct         26  \n",
       "mixed_minus_base           31  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Familiar\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-3e9d3645-09fb-452e-aff7-caa8a4955850\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>exact</th>\n",
       "      <th>valid</th>\n",
       "      <th>row_f1</th>\n",
       "      <th>natural_completion</th>\n",
       "      <th>mean_generated_tokens</th>\n",
       "      <th>mean_ms_per_example_in_batch</th>\n",
       "      <th>families</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Prompted base</th>\n",
       "      <td>25.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.00</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>158.96</td>\n",
       "      <td>874.141759</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Direct answers</th>\n",
       "      <td>25.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>90.00</td>\n",
       "      <td>609.557585</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Target-only traces</th>\n",
       "      <td>25.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.32</td>\n",
       "      <td>0.186667</td>\n",
       "      <td>1.0</td>\n",
       "      <td>128.72</td>\n",
       "      <td>921.155668</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mixed traces</th>\n",
       "      <td>25.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.00</td>\n",
       "      <td>1.000000</td>\n",
       "      <td>1.0</td>\n",
       "      <td>110.36</td>\n",
       "      <td>752.340231</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-3e9d3645-09fb-452e-aff7-caa8a4955850')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-3e9d3645-09fb-452e-aff7-caa8a4955850 button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-3e9d3645-09fb-452e-aff7-caa8a4955850');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                       n  exact  valid    row_f1  natural_completion  \\\n",
       "Prompted base       25.0    0.0   0.00  0.000000                 1.0   \n",
       "Direct answers      25.0    1.0   1.00  1.000000                 1.0   \n",
       "Target-only traces  25.0    0.0   0.32  0.186667                 1.0   \n",
       "Mixed traces        25.0    1.0   1.00  1.000000                 1.0   \n",
       "\n",
       "                    mean_generated_tokens  mean_ms_per_example_in_batch  \\\n",
       "Prompted base                      158.96                    874.141759   \n",
       "Direct answers                      90.00                    609.557585   \n",
       "Target-only traces                 128.72                    921.155668   \n",
       "Mixed traces                       110.36                    752.340231   \n",
       "\n",
       "                    families  \n",
       "Prompted base            8.0  \n",
       "Direct answers           8.0  \n",
       "Target-only traces       8.0  \n",
       "Mixed traces             8.0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-72cd955a-c7ba-4599-98b2-2ab920e90171\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>delta</th>\n",
       "      <th>n</th>\n",
       "      <th>families</th>\n",
       "      <th>improved</th>\n",
       "      <th>regressed</th>\n",
       "      <th>tied</th>\n",
       "      <th>paired_family_bootstrap_95</th>\n",
       "      <th>both_exact</th>\n",
       "      <th>both_wrong</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>mixed_minus_target</th>\n",
       "      <td>1.0</td>\n",
       "      <td>25</td>\n",
       "      <td>8</td>\n",
       "      <td>25</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>[1.0, 1.0]</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mixed_minus_direct</th>\n",
       "      <td>0.0</td>\n",
       "      <td>25</td>\n",
       "      <td>8</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>25</td>\n",
       "      <td>[0.0, 0.0]</td>\n",
       "      <td>25</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mixed_minus_base</th>\n",
       "      <td>1.0</td>\n",
       "      <td>25</td>\n",
       "      <td>8</td>\n",
       "      <td>25</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>[1.0, 1.0]</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-72cd955a-c7ba-4599-98b2-2ab920e90171')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-72cd955a-c7ba-4599-98b2-2ab920e90171 button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-72cd955a-c7ba-4599-98b2-2ab920e90171');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "                   delta   n families improved regressed tied  \\\n",
       "mixed_minus_target   1.0  25        8       25         0    0   \n",
       "mixed_minus_direct   0.0  25        8        0         0   25   \n",
       "mixed_minus_base     1.0  25        8       25         0    0   \n",
       "\n",
       "                   paired_family_bootstrap_95 both_exact both_wrong  \n",
       "mixed_minus_target                 [1.0, 1.0]          0          0  \n",
       "mixed_minus_direct                 [0.0, 0.0]         25          0  \n",
       "mixed_minus_base                   [1.0, 1.0]          0          0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "evaluation = [item for items in heldout.values() for item in items]\n",
    "heldout_predictions = {BASE: evaluate_at(MODEL_ID, tok, evaluation, system=TRACE_SYSTEM, extract=extract_record)}\n",
    "for arm, adapter in adapters.items():\n",
    "    heldout_predictions[arm] = evaluate_at(\n",
    "        MODEL_ID, tok, evaluation, adapter=adapter, system=TRACE_SYSTEM, extract=extract_record,\n",
    "    )\n",
    "prepare_evaluation(heldout_predictions, evaluation)\n",
    "slice_scores, paired = measured_slices(heldout, heldout_predictions)\n",
    "for name, values in slice_scores.items():\n",
    "    print(name)\n",
    "    display(pd.DataFrame(values).T)\n",
    "    display(pd.DataFrame(paired[name]).T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5cb35ad",
   "metadata": {},
   "source": [
    "## 7. Re-run the same invoices at two answer caps\n",
    "\n",
    "    Use Mixed traces for this independent sensitivity check. Evaluate identical examples in identical\n",
    "    batches at both caps. Count exact records, natural stops and mean generated tokens. Variations\n",
    "    here measure the decoding allowance. The primary comparison retains its original cap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "727fb2b7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "  <div id=\"df-5585d0d3-70e1-467a-a84e-6d28651a6a24\" class=\"colab-df-container\">\n",
       "    <div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>n</th>\n",
       "      <th>exact</th>\n",
       "      <th>valid</th>\n",
       "      <th>row_f1</th>\n",
       "      <th>natural_completion</th>\n",
       "      <th>mean_generated_tokens</th>\n",
       "      <th>mean_ms_per_example_in_batch</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>128</th>\n",
       "      <td>16.0</td>\n",
       "      <td>0.5000</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.500000</td>\n",
       "      <td>0.5</td>\n",
       "      <td>119.0625</td>\n",
       "      <td>688.432744</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>256</th>\n",
       "      <td>16.0</td>\n",
       "      <td>0.5625</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.854167</td>\n",
       "      <td>1.0</td>\n",
       "      <td>141.3750</td>\n",
       "      <td>878.738453</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>\n",
       "    <div class=\"colab-df-buttons\">\n",
       "      \n",
       "  <div class=\"colab-df-container\">\n",
       "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-5585d0d3-70e1-467a-a84e-6d28651a6a24')\"\n",
       "            title=\"Convert this dataframe to an interactive table.\"\n",
       "            style=\"display:none;\">\n",
       "      \n",
       "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
       "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
       "  </svg>\n",
       "    </button>\n",
       "    \n",
       "  <style>\n",
       "    .colab-df-container {\n",
       "      display:flex;\n",
       "      gap: 12px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert {\n",
       "      background-color: #E8F0FE;\n",
       "      border: none;\n",
       "      border-radius: 50%;\n",
       "      cursor: pointer;\n",
       "      display: none;\n",
       "      fill: #1967D2;\n",
       "      height: 32px;\n",
       "      padding: 0 0 0 0;\n",
       "      width: 32px;\n",
       "    }\n",
       "\n",
       "    .colab-df-convert:hover {\n",
       "      background-color: #E2EBFA;\n",
       "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
       "      fill: #174EA6;\n",
       "    }\n",
       "\n",
       "    .colab-df-buttons div {\n",
       "      margin-bottom: 4px;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert {\n",
       "      background-color: #3B4455;\n",
       "      fill: #D2E3FC;\n",
       "    }\n",
       "\n",
       "    [theme=dark] .colab-df-convert:hover {\n",
       "      background-color: #434B5C;\n",
       "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
       "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
       "      fill: #FFFFFF;\n",
       "    }\n",
       "  </style>\n",
       "\n",
       "    <script>\n",
       "      const buttonEl =\n",
       "        document.querySelector('#df-5585d0d3-70e1-467a-a84e-6d28651a6a24 button.colab-df-convert');\n",
       "      buttonEl.style.display =\n",
       "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
       "\n",
       "      async function convertToInteractive(key) {\n",
       "        const element = document.querySelector('#df-5585d0d3-70e1-467a-a84e-6d28651a6a24');\n",
       "        const dataTable =\n",
       "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
       "                                                    [key], {});\n",
       "        if (!dataTable) return;\n",
       "\n",
       "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
       "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
       "          + ' to learn more about interactive tables.';\n",
       "        element.innerHTML = '';\n",
       "        dataTable['output_type'] = 'display_data';\n",
       "        await google.colab.output.renderOutput(dataTable, element);\n",
       "        const docLink = document.createElement('div');\n",
       "        docLink.innerHTML = docLinkHtml;\n",
       "        element.appendChild(docLink);\n",
       "      }\n",
       "    </script>\n",
       "  </div>\n",
       "  \n",
       "    </div>\n",
       "  </div>\n",
       "  "
      ],
      "text/plain": [
       "        n   exact  valid    row_f1  natural_completion  mean_generated_tokens  \\\n",
       "128  16.0  0.5000    0.5  0.500000                 0.5               119.0625   \n",
       "256  16.0  0.5625    1.0  0.854167                 1.0               141.3750   \n",
       "\n",
       "     mean_ms_per_example_in_batch  \n",
       "128                    688.432744  \n",
       "256                    878.738453  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "cap_roster = [item for rows in heldout.values() for item in random.Random(SEED).sample(rows, 8)]\n",
    "cap_predictions = {\n",
    "    str(limit): evaluate_at(MODEL_ID, tok, cap_roster, adapter=adapters[MIXED],\n",
    "                            system=TRACE_SYSTEM, extract=extract_record, answer_limit=limit)\n",
    "    for limit in (SHORT_CAP, ANSWER_LIMIT)\n",
    "}\n",
    "prepare_evaluation(cap_predictions, cap_roster)\n",
    "cap_scores = {limit: summary(rows) for limit, rows in cap_predictions.items()}\n",
    "display(pd.DataFrame(cap_scores).T)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2db58a10",
   "metadata": {},
   "source": [
    "## 8. Save the decisions and evidence\n",
    "\n",
    "    The report records configuration, counts and comparisons. The audit ties each accepted answer\n",
    "    to its exact candidate, opening invoice and update. Predictions preserve the raw outputs and\n",
    "    the audit supplies the visible documents and reference records for individual checks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "5f3c3ecb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lesson-results/05-report.json\n",
      "lesson-results/05-audit.json\n",
      "lesson-results/05-predictions.json\n",
      "lesson-results/05-cap-predictions.json\n"
     ]
    }
   ],
   "source": [
    "report = {\n",
    "    \"model\": MODEL_ID, \"revision\": MODEL_REV, \"seed\": SEED, \"catalogue\": CATALOG_VERSION,\n",
    "    \"catalog_sha256\": manifest([item for item in catalog if item.split != \"release\"]),\n",
    "    \"hardware\": torch.cuda.get_device_name(0),\n",
    "    \"packages\": {name: version(name) for name in (\"torch\", *TRAINER_PINS)},\n",
    "    \"prompt_token_cap\": PROMPT_LIMIT, \"completion_token_cap\": ANSWER_LIMIT,\n",
    "    \"decoding\": {\"sample\": False, \"new_tokens\": ANSWER_LIMIT, \"batch_size\": 8},\n",
    "    \"learning_rate\": LEARNING_RATE, \"lora\": {\"rank\": 8, \"alpha\": 16, \"modules\": [\"q_proj\", \"v_proj\", \"o_proj\"]},\n",
    "    \"equal_target_diagnostic_run\": RUN_EQUAL_TARGET_DIAGNOSTIC,\n",
    "    \"teacher\": dict(Counter(row[\"decision\"] for row in ledger)),\n",
    "    \"development\": dev_scores, \"exposure\": exposure, \"training\": training,\n",
    "    \"slices\": slice_scores, \"paired\": paired, \"generation_cap_sensitivity\": cap_scores,\n",
    "}\n",
    "audit = {\n",
    "    \"opening_invoice_key\": OPENING_ID, \"candidate_ledger\": ledger, \"training_lineage\": train_lineage,\n",
    "    \"training_documents\": {item.key: invoice_text(item) for item in train},\n",
    "    \"held_out_documents\": {item.key: {\"visible\": invoice_text(item), \"reference\": invoice_record(item),\n",
    "                                      \"family\": item.family, \"split\": item.split}\n",
    "                           for item in evaluation},\n",
    "    \"held_out_rosters\": {name: [item.key for item in rows] for name, rows in heldout.items()},\n",
    "    \"development_documents\": {item.key: {\"visible\": invoice_text(item), \"reference\": invoice_record(item)}\n",
    "                              for item in dev_roster},\n",
    "    \"development_predictions\": dev_run,\n",
    "}\n",
    "write_evidence(report, audit, heldout_predictions, cap_predictions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1e34d615",
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_slices(summaries, title, filename=\"exact.svg\"):\n",
    "    plt.rcParams[\"svg.fonttype\"] = \"none\"\n",
    "    from IPython.display import SVG, display\n",
    "    fig, ax = plt.subplots(figsize=(9, 4))\n",
    "    keys = list(summaries)\n",
    "    values = [summaries[label][\"exact\"] for label in keys]\n",
    "    ax.barh(keys, values, color=[\"#74818c\", \"#2a78d6\", \"#eb6834\", \"#426a53\", \"#746296\"][:len(keys)])\n",
    "    ax.set(xlim=(0, 1.05), xlabel=\"Exact complete records, share\", title=title)\n",
    "    ax.bar_label(ax.containers[0], labels=[f\"{value:.1%}\" for value in values], padding=4)\n",
    "    ax.invert_yaxis()\n",
    "    ax.grid(axis=\"x\", alpha=0.22)\n",
    "    fig.tight_layout()\n",
    "    svg_path = OUT / filename\n",
    "    fig.savefig(svg_path, format=\"svg\")\n",
    "    plt.close(fig)\n",
    "    display(SVG(filename=str(svg_path)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "8c1a3b2a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" width=\"648pt\" height=\"288pt\" viewBox=\"0 0 648 288\" 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-27T08:40:33.721167</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 288  L 648 288  L 648 0  L 0 0  z \" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 107.98 246.04  L 637.2 246.04  L 637.2 26.88  L 107.98 26.88  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 107.98 36.841818  L 107.98 36.841818  L 107.98 78.786316  L 107.98 78.786316  z \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: #74818c\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 107.98 89.27244  L 287.186772 89.27244  L 287.186772 131.216938  L 107.98 131.216938  z \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: #2a78d6\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 107.98 141.703062  L 309.587619 141.703062  L 309.587619 183.64756  L 107.98 183.64756  z \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: #eb6834\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 107.98 194.133684  L 264.785926 194.133684  L 264.785926 236.078182  L 107.98 236.078182  z \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: #426a53\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 107.98 246.04  L 107.98 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"m14da4478d1\" d=\"M 0 0  L 0 3.5  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"107.98\" y=\"246.04\" 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=\"107.98\" y=\"260.638438\" transform=\"rotate(-0 107.98 260.638438)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 208.78381 246.04  L 208.78381 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"208.78381\" y=\"246.04\" 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=\"208.78381\" y=\"260.638438\" transform=\"rotate(-0 208.78381 260.638438)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 309.587619 246.04  L 309.587619 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"309.587619\" y=\"246.04\" 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=\"309.587619\" y=\"260.638438\" transform=\"rotate(-0 309.587619 260.638438)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 410.391429 246.04  L 410.391429 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"410.391429\" y=\"246.04\" 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=\"410.391429\" y=\"260.638438\" transform=\"rotate(-0 410.391429 260.638438)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 511.195238 246.04  L 511.195238 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"511.195238\" y=\"246.04\" 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=\"511.195238\" y=\"260.638438\" transform=\"rotate(-0 511.195238 260.638438)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 611.999048 246.04  L 611.999048 26.88  \" clip-path=\"url(#p9e13c277fe)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m14da4478d1\" x=\"611.999048\" y=\"246.04\" 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=\"611.999048\" y=\"260.638438\" transform=\"rotate(-0 611.999048 260.638438)\">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=\"372.59\" y=\"274.316562\" transform=\"rotate(-0 372.59 274.316562)\">Exact complete records, share</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=\"m54f092e0ed\" d=\"M 0 0  L -3.5 0  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m54f092e0ed\" x=\"107.98\" y=\"57.814067\" 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=\"100.98\" y=\"61.613286\" transform=\"rotate(-0 100.98 61.613286)\">Prompted base</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m54f092e0ed\" x=\"107.98\" y=\"110.244689\" 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=\"100.98\" y=\"114.043908\" transform=\"rotate(-0 100.98 114.043908)\">Direct answers</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m54f092e0ed\" x=\"107.98\" y=\"162.675311\" 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=\"100.98\" y=\"166.47453\" transform=\"rotate(-0 100.98 166.47453)\">Target-only traces</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m54f092e0ed\" x=\"107.98\" y=\"215.105933\" 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=\"100.98\" y=\"218.905152\" transform=\"rotate(-0 100.98 218.905152)\">Mixed traces</text>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 107.98 246.04  L 107.98 26.88  \" 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 637.2 246.04  L 637.2 26.88  \" 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 107.98 246.04  L 637.2 246.04  \" 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 107.98 26.88  L 637.2 26.88  \" 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: 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: start\" x=\"111.98\" y=\"60.573442\" transform=\"rotate(-0 111.98 60.573442)\">0.0%</text>\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: start\" x=\"291.186772\" y=\"113.004064\" transform=\"rotate(-0 291.186772 113.004064)\">35.6%</text>\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: start\" x=\"313.587619\" y=\"165.434686\" transform=\"rotate(-0 313.587619 165.434686)\">40.0%</text>\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: start\" x=\"268.785926\" y=\"217.865308\" transform=\"rotate(-0 268.785926 217.865308)\">31.1%</text>\n",
       "   </g>\n",
       "   <g id=\"text_16\">\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=\"372.59\" y=\"20.88\" transform=\"rotate(-0 372.59 20.88)\">Difficult strict invoice extraction</text>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p9e13c277fe\">\n",
       "   <rect x=\"107.98\" y=\"26.88\" width=\"529.22\" height=\"219.16\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>"
      ],
      "text/plain": [
       "<IPython.core.display.SVG object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" width=\"648pt\" height=\"288pt\" viewBox=\"0 0 648 288\" 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-27T08:40:33.818534</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 288  L 648 288  L 648 0  L 0 0  z \" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 107.98 246.04  L 619.224286 246.04  L 619.224286 26.88  L 107.98 26.88  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 107.98 36.841818  L 107.98 36.841818  L 107.98 78.786316  L 107.98 78.786316  z \" clip-path=\"url(#p350be56edf)\" style=\"fill: #74818c\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 107.98 89.27244  L 594.87932 89.27244  L 594.87932 131.216938  L 107.98 131.216938  z \" clip-path=\"url(#p350be56edf)\" style=\"fill: #2a78d6\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 107.98 141.703062  L 107.98 141.703062  L 107.98 183.64756  L 107.98 183.64756  z \" clip-path=\"url(#p350be56edf)\" style=\"fill: #eb6834\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 107.98 194.133684  L 594.87932 194.133684  L 594.87932 236.078182  L 107.98 236.078182  z \" clip-path=\"url(#p350be56edf)\" style=\"fill: #426a53\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 107.98 246.04  L 107.98 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"mba1f190053\" d=\"M 0 0  L 0 3.5  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"107.98\" y=\"246.04\" 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=\"107.98\" y=\"260.638438\" transform=\"rotate(-0 107.98 260.638438)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 205.359864 246.04  L 205.359864 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"205.359864\" y=\"246.04\" 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=\"205.359864\" y=\"260.638438\" transform=\"rotate(-0 205.359864 260.638438)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 302.739728 246.04  L 302.739728 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"302.739728\" y=\"246.04\" 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=\"302.739728\" y=\"260.638438\" transform=\"rotate(-0 302.739728 260.638438)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 400.119592 246.04  L 400.119592 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"400.119592\" y=\"246.04\" 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=\"400.119592\" y=\"260.638438\" transform=\"rotate(-0 400.119592 260.638438)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 497.499456 246.04  L 497.499456 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"497.499456\" y=\"246.04\" 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=\"497.499456\" y=\"260.638438\" transform=\"rotate(-0 497.499456 260.638438)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 594.87932 246.04  L 594.87932 26.88  \" clip-path=\"url(#p350be56edf)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.22; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mba1f190053\" x=\"594.87932\" y=\"246.04\" 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=\"594.87932\" y=\"260.638438\" transform=\"rotate(-0 594.87932 260.638438)\">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=\"363.602143\" y=\"274.316562\" transform=\"rotate(-0 363.602143 274.316562)\">Exact complete records, share</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=\"me9e2196881\" d=\"M 0 0  L -3.5 0  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#me9e2196881\" x=\"107.98\" y=\"57.814067\" 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=\"100.98\" y=\"61.613286\" transform=\"rotate(-0 100.98 61.613286)\">Prompted base</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me9e2196881\" x=\"107.98\" y=\"110.244689\" 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=\"100.98\" y=\"114.043908\" transform=\"rotate(-0 100.98 114.043908)\">Direct answers</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me9e2196881\" x=\"107.98\" y=\"162.675311\" 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=\"100.98\" y=\"166.47453\" transform=\"rotate(-0 100.98 166.47453)\">Target-only traces</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me9e2196881\" x=\"107.98\" y=\"215.105933\" 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=\"100.98\" y=\"218.905152\" transform=\"rotate(-0 100.98 218.905152)\">Mixed traces</text>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 107.98 246.04  L 107.98 26.88  \" 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 619.224286 246.04  L 619.224286 26.88  \" 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 107.98 246.04  L 619.224286 246.04  \" 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 107.98 26.88  L 619.224286 26.88  \" 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: 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: start\" x=\"111.98\" y=\"60.573442\" transform=\"rotate(-0 111.98 60.573442)\">0.0%</text>\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: start\" x=\"598.87932\" y=\"113.004064\" transform=\"rotate(-0 598.87932 113.004064)\">100.0%</text>\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: start\" x=\"111.98\" y=\"165.434686\" transform=\"rotate(-0 111.98 165.434686)\">0.0%</text>\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: start\" x=\"598.87932\" y=\"217.865308\" transform=\"rotate(-0 598.87932 217.865308)\">100.0%</text>\n",
       "   </g>\n",
       "   <g id=\"text_16\">\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=\"363.602143\" y=\"20.88\" transform=\"rotate(-0 363.602143 20.88)\">Familiar strict invoice extraction</text>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p350be56edf\">\n",
       "   <rect x=\"107.98\" y=\"26.88\" width=\"511.244286\" height=\"219.16\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>"
      ],
      "text/plain": [
       "<IPython.core.display.SVG object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "for name, values in slice_scores.items():\n",
    "    plot_slices(values, f\"{name} strict invoice extraction\", filename=f\"05-{name.lower()}-exact.svg\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a6f8212",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "    Return to SF-157375. Use the candidate ledger to explain why the label preserves the amount due.\n",
    "    Then compare raw held-out answers to decide whether to keep the trace, how many familiar cases\n",
    "    to reserve and whether the output cap is usable. Use the family intervals and single-fit scope\n",
    "    when describing the outcome.\n",
    "\n",
    "    [Return to the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/2-compare-training-stages/05-distil-verified-traces). [Together's Lao and Thai experiment](https://www.together.ai/blog/distilling-kimi-into-qwen).\n",
    "    [Together's filtering recipe, Apache 2.0](https://github.com/togethercomputer/post-training-cookbook/blob/226e03ca225d6f13434047cf0f45ab3070a29801/post_training_cookbook/distillation/data.py).\n",
    "    [Distilling Step-by-Step](https://aclanthology.org/2023.findings-acl.507/)."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
