{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "831c7226",
   "metadata": {},
   "source": [
    "# Lesson 14 extension · Train inside the ledger harness\n",
    "\n",
    "An analyst asks you to check an invoice's payable amount. Their notes mention a\n",
    "second invoice. The model must decide what to call, read the ledger's response\n",
    "and return an answer tied to the requested invoice. What happens if training\n",
    "scores those decisions as they happen and deployment wraps each tool reply?\n",
    "\n",
    "[Read Lesson 14](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/14-train-on-verified-tool-calls)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b61f7eb",
   "metadata": {},
   "source": [
    "## Runtime\n",
    "\n",
    "Select a Tesla T4 in Colab. Each branch runs in sequence. Model downloads use the\n",
    "public Hugging Face checkpoint, pinned by revision. The shared runtime can reuse\n",
    "its weight cache. The material below embeds the invoice fixtures and training code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41d8cd1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import subprocess\n",
    "import sys\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *['transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0']], check=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c74811",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name(0):\n",
    "    raise RuntimeError(\"Select a Tesla T4 runtime in Colab before running this notebook.\")\n",
    "print(\"GPU:\", torch.cuda.get_device_name(0))\n",
    "print(\"PyTorch:\", torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66aad49d",
   "metadata": {},
   "source": [
    "## Invoice fixtures\n",
    "\n",
    "The synthetic input and gold record come from a versioned scenario. The scorer compares\n",
    "generated JSON with the gold record independently of model training. The release set stays\n",
    "out of this lesson."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e526306b",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Versioned synthetic invoices and independent record scoring for the course.\"\"\"\n",
    "\n",
    "from __future__ import annotations\n",
    "\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "from collections import Counter\n",
    "from dataclasses import dataclass\n",
    "from datetime import date, timedelta\n",
    "from typing import Any\n",
    "\n",
    "CATALOG_VERSION = \"course-invoice-v1\"\n",
    "SPLIT_SIZES = {\"train\": 576, \"dev\": 72, \"familiar\": 96, \"novel\": 96, \"independent\": 48, \"release\": 120}\n",
    "VISIBLE_CONTRACT = (\n",
    "    \"Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, \"\n",
    "    \"currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, \"\n",
    "    \"tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. \"\n",
    "    \"Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.\"\n",
    ")\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Line:\n",
    "    description: str\n",
    "    quantity: int\n",
    "    unit_minor: int\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Invoice:\n",
    "    key: str\n",
    "    family: str\n",
    "    supplier: str\n",
    "    issued_on: str\n",
    "    currency: str\n",
    "    items: tuple[Line, ...]\n",
    "    tax_minor: int | None\n",
    "    locale: str\n",
    "    split: str\n",
    "    layout: str = \"register\"\n",
    "    printed_total_minor: int | None = None\n",
    "\n",
    "\n",
    "def invoice_record(invoice: Invoice) -> dict[str, Any]:\n",
    "    subtotal = sum(line.quantity * line.unit_minor for line in invoice.items)\n",
    "    total = subtotal + invoice.tax_minor if invoice.tax_minor is not None else None\n",
    "    if invoice.printed_total_minor is not None:\n",
    "        total = invoice.printed_total_minor\n",
    "    return {\n",
    "        \"invoice_id\": invoice.key,\n",
    "        \"issued_on\": invoice.issued_on,\n",
    "        \"supplier\": invoice.supplier,\n",
    "        \"currency\": invoice.currency,\n",
    "        \"line_items\": [\n",
    "            {\"description\": item.description, \"quantity\": item.quantity, \"unit_minor\": item.unit_minor}\n",
    "            for item in invoice.items\n",
    "        ],\n",
    "        \"subtotal_minor\": subtotal,\n",
    "        \"tax_minor\": invoice.tax_minor,\n",
    "        \"total_minor\": total,\n",
    "    }\n",
    "\n",
    "\n",
    "def make_catalog() -> list[Invoice]:\n",
    "    rng = random.Random(20261126)\n",
    "    sources = {\n",
    "        \"train\": (24, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"dev\": (6, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"familiar\": (8, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"novel\": (8, (\"packing\", \"remittance\", \"service\", \"notice\")),\n",
    "        \"independent\": (4, (\"separate\",)),\n",
    "        \"release\": (10, (\"packing\", \"remittance\", \"service\", \"notice\", \"separate\")),\n",
    "    }\n",
    "    locales = ((\"en-US\", \"USD\"), (\"en-GB\", \"GBP\"), (\"de-DE\", \"EUR\"), (\"fr-FR\", \"EUR\"), (\"en-US\", \"CAD\"))\n",
    "    services = (\"Cooling filter\", \"Cable sleeve\", \"Bench calibration\", \"Door seal\", \"Grounding clip\",\n",
    "                \"Rack inspection\", \"Meter label\", \"Packing insert\", \"Carrier adjustment\", \"Mounting plate\")\n",
    "    catalog = []\n",
    "    seen_keys = set()\n",
    "    supplier_codes = rng.sample(range(1000, 9999), sum(n for n, _ in sources.values()))\n",
    "    supplier_index = 0\n",
    "    for split, (family_count, layouts) in sources.items():\n",
    "        for family_number in range(family_count):\n",
    "            supplier_code = supplier_codes[supplier_index]\n",
    "            supplier_index += 1\n",
    "            layout = layouts[family_number % len(layouts)]\n",
    "            family = f\"{split}-{family_number:02d}\"\n",
    "            locale, currency = locales[family_number % len(locales)]\n",
    "            for row in range(SPLIT_SIZES[split] // family_count):\n",
    "                code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                while code in seen_keys:\n",
    "                    code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                seen_keys.add(code)\n",
    "                items = tuple(\n",
    "                    Line(kind, rng.randint(1, 9), rng.randrange(200, 24800))\n",
    "                    for kind in rng.sample(services, rng.randrange(1, 4))\n",
    "                )\n",
    "                subtotal = sum(x.quantity * x.unit_minor for x in items)\n",
    "                tax = (subtotal * (7 if currency == \"USD\" else 13) + 50) // 100\n",
    "                if split in {\"novel\", \"independent\", \"release\"} and row % 12 == 4:\n",
    "                    tax = None\n",
    "                displayed = subtotal + tax + 101 if tax is not None and row % 12 == 7 else None\n",
    "                issued_on = (date(2025, 1, 1) + timedelta(days=rng.randint(0, 590))).isoformat()\n",
    "                catalog.append(Invoice(code, family, f\"Sample Supplier {supplier_code}\", issued_on,\n",
    "                                       currency, items, tax, locale, split, layout, displayed))\n",
    "    return catalog\n",
    "\n",
    "\n",
    "def formatted_money(minor: int | None, locale: str) -> str:\n",
    "    if minor is None:\n",
    "        return \"-\"\n",
    "    dollars, cents = divmod(minor, 100)\n",
    "    number = f\"{dollars:,}.{cents:02d}\"\n",
    "    if locale == \"de-DE\":\n",
    "        return number.replace(\",\", \"_\").replace(\".\", \",\").replace(\"_\", \".\")\n",
    "    if locale == \"fr-FR\":\n",
    "        return number.replace(\",\", \" \").replace(\".\", \",\")\n",
    "    return number\n",
    "\n",
    "\n",
    "def invoice_text(invoice: Invoice) -> str:\n",
    "    gold = invoice_record(invoice)\n",
    "    money = lambda value: formatted_money(value, invoice.locale)\n",
    "    identifier = f\"{invoice.key}\"\n",
    "    supplier = invoice.supplier\n",
    "    issued = invoice.issued_on\n",
    "    currency = invoice.currency\n",
    "    subtotal = money(gold[\"subtotal_minor\"])\n",
    "    tax = money(gold[\"tax_minor\"])\n",
    "    total = money(gold[\"total_minor\"])\n",
    "    register = [f\"{row.description} | {row.quantity} | {money(row.unit_minor)}\" for row in invoice.items]\n",
    "    inline = [f\"{row.quantity} x {row.description} @ {money(row.unit_minor)} per unit\" for row in invoice.items]\n",
    "    service = [f\"{row.description}: {money(row.unit_minor)} each for {row.quantity} units\" for row in invoice.items]\n",
    "    if invoice.layout == \"register\":\n",
    "        return \"\\n\".join([f\"Supplier: {supplier}\", f\"Invoice: {identifier}\", f\"Issued: {issued}\", f\"Currency: {currency}\",\n",
    "                          \"Description | Quantity | Unit price\", *register,\n",
    "                          f\"Subtotal: {subtotal}\", f\"Tax: {tax}\", f\"Amount due: {total}\"])\n",
    "    if invoice.layout == \"memo\":\n",
    "        return \"\\n\".join([f\"{supplier} billing memo / {issued}\", f\"Account invoice {identifier} [{currency}]\",\n",
    "                          *inline, f\"Total due {total} including tax {tax}; net amount {subtotal}.\"])\n",
    "    if invoice.layout == \"checkout\":\n",
    "        return \"\\n\".join([f\"{identifier} / supplier {supplier}\", f\"Date of issue {issued} / All amounts {currency}\",\n",
    "                          *service, f\"Net {subtotal}\", f\"Sales tax {tax}\", f\"Payable {total}\"])\n",
    "    if invoice.layout == \"ledger\":\n",
    "        return \"\\n\".join([f\"{supplier} | issued {issued} | invoice {identifier}\", f\"Ledger in {currency}\",\n",
    "                          \"Service | Count | Per unit\", *register, f\"Before tax {subtotal}\",\n",
    "                          f\"Tax charged {tax}\", f\"Balance {total}\"])\n",
    "    if invoice.layout == \"packing\":\n",
    "        return \"\\n\".join([f\"Billing details / {identifier}\", f\"Sold by {supplier}\", f\"Document date {issued}\",\n",
    "                          f\"Invoice currency {currency}\", f\"Balance payable {total}\", *service,\n",
    "                          f\"Merchandise {subtotal}\", f\"Tax {tax}\"])\n",
    "    if invoice.layout == \"remittance\":\n",
    "        return \"\\n\".join([f\"Remittance advice for {identifier} ({currency})\", f\"{supplier} / Document issued {issued}\",\n",
    "                          f\"Pay this amount {total}\", *inline, f\"Net charges {subtotal} / Tax {tax}\"])\n",
    "    if invoice.layout == \"service\":\n",
    "        return \"\\n\".join([f\"Ref {identifier} / {currency}\", f\"Service fee notice, {issued}\", supplier,\n",
    "                          *[f\"Unit {money(row.unit_minor)} / {row.quantity} times / {row.description}\" for row in invoice.items],\n",
    "                          f\"Fee subtotal {subtotal}\", f\"Plus tax {tax}\", f\"Amount requested {total}\"])\n",
    "    if invoice.layout == \"notice\":\n",
    "        return \"\\n\".join([f\"{supplier} / statement {identifier}\", f\"Issued on {issued}\",\n",
    "                          f\"Invoice denomination {currency}\", \"One-off charges\", *service,\n",
    "                          f\"Pre-tax {subtotal} / Tax assessment {tax} / Final bill {total}\"])\n",
    "    return \"\\n\".join([f\"Document {identifier}\", f\"Biller {supplier} / As of {issued} / {currency}\", *inline,\n",
    "                      f\"Gross {total}\", f\"Breakdown: net {subtotal} and taxes {tax}.\"])\n",
    "\n",
    "\n",
    "def _strict_dict(pairs: list[tuple[str, Any]]) -> dict[str, Any]:\n",
    "    result: dict[str, Any] = {}\n",
    "    for key, value in pairs:\n",
    "        if key in result:\n",
    "            raise ValueError(f\"Duplicate JSON key {key!r}\")\n",
    "        result[key] = value\n",
    "    return result\n",
    "\n",
    "\n",
    "def parse_record(completion: str | dict[str, Any]) -> dict[str, Any] | None:\n",
    "    if isinstance(completion, str):\n",
    "        try:\n",
    "            data = json.loads(completion, object_pairs_hook=_strict_dict)\n",
    "        except (ValueError, TypeError, RecursionError):\n",
    "            return None\n",
    "    else:\n",
    "        data = completion\n",
    "    keys = {\"invoice_id\", \"issued_on\", \"supplier\", \"currency\", \"line_items\", \"subtotal_minor\", \"tax_minor\", \"total_minor\"}\n",
    "    if not isinstance(data, dict) or set(data) != keys:\n",
    "        return None\n",
    "    for name in (\"invoice_id\", \"supplier\", \"issued_on\", \"currency\"):\n",
    "        value = data[name]\n",
    "        if value is not None and (not isinstance(value, str) or not value.strip()):\n",
    "            return None\n",
    "    try:\n",
    "        if data[\"issued_on\"] is not None and date.fromisoformat(data[\"issued_on\"]).isoformat() != data[\"issued_on\"]:\n",
    "            return None\n",
    "    except ValueError:\n",
    "        return None\n",
    "    if data[\"currency\"] is not None and re.fullmatch(\"[A-Z]{3}\", data[\"currency\"]) is None:\n",
    "        return None\n",
    "    for name in (\"subtotal_minor\", \"tax_minor\", \"total_minor\"):\n",
    "        if data[name] is not None and type(data[name]) is not int:\n",
    "            return None\n",
    "    if not isinstance(data[\"line_items\"], list):\n",
    "        return None\n",
    "    for row in data[\"line_items\"]:\n",
    "        if not isinstance(row, dict) or set(row) != {\"description\", \"quantity\", \"unit_minor\"}:\n",
    "            return None\n",
    "        if type(row[\"description\"]) is not str or type(row[\"quantity\"]) is not int or type(row[\"unit_minor\"]) is not int:\n",
    "            return None\n",
    "        if not row[\"description\"].strip() or row[\"quantity\"] <= 0:\n",
    "            return None\n",
    "    return data\n",
    "\n",
    "\n",
    "def score_record(completion: str | dict[str, Any], invoice: Invoice) -> dict[str, Any]:\n",
    "    truth = invoice_record(invoice)\n",
    "    observed = parse_record(completion)\n",
    "    field_correct = {key: observed is not None and observed.get(key) == value\n",
    "                     for key, value in truth.items() if key != \"line_items\"}\n",
    "    keys = (\"description\", \"quantity\", \"unit_minor\")\n",
    "    expected = Counter(tuple(r[k] for k in keys) for r in truth[\"line_items\"])\n",
    "    predicted = Counter(tuple(r[k] for k in keys) for r in observed[\"line_items\"]) if observed is not None else Counter()\n",
    "    matches = (expected & predicted).total()\n",
    "    row_count = expected.total() + predicted.total()\n",
    "    return {\"valid\": observed is not None, \"exact\": observed == truth,\n",
    "            \"fields\": sum(field_correct.values()) / len(field_correct), \"field_correct\": field_correct,\n",
    "            \"row_f1\": 2 * matches / row_count if row_count else 1.0}\n",
    "\n",
    "\n",
    "def rules_extract(text: str) -> dict[str, Any] | None:\n",
    "    lines = text.splitlines()\n",
    "    if len(lines) < 9 or lines[4] != \"Description | Quantity | Unit price\":\n",
    "        return None\n",
    "    property_names = (\"supplier\", \"invoice_id\", \"issued_on\", \"currency\")\n",
    "    headers = (\"Supplier: \", \"Invoice: \", \"Issued: \", \"Currency: \")\n",
    "    if any(not line.startswith(header) for line, header in zip(lines, headers)):\n",
    "        return None\n",
    "    data = {name: line.removeprefix(header) for name, line, header in zip(property_names, lines, headers)}\n",
    "\n",
    "    def minor(text_amount: str) -> int | None:\n",
    "        if text_amount == \"-\":\n",
    "            return None\n",
    "        if re.fullmatch(r\"(?:\\d+|\\d{1,3}(?:[., ]\\d{3})+)[.,]\\d{2}\", text_amount) is None:\n",
    "            raise ValueError(\"Unsupported amount format\")\n",
    "        units, frac = text_amount[:-3], text_amount[-2:]\n",
    "        return int(re.sub(r\"\\D\", \"\", units)) * 100 + int(frac)\n",
    "\n",
    "    try:\n",
    "        rows = [line.split(\" | \") for line in lines[5:-3]]\n",
    "        data[\"line_items\"] = [{\"description\": desc, \"quantity\": int(qty), \"unit_minor\": minor(unit)}\n",
    "                              for desc, qty, unit in rows]\n",
    "        data[\"subtotal_minor\"] = minor(lines[-3].removeprefix(\"Subtotal: \"))\n",
    "        data[\"tax_minor\"] = minor(lines[-2].removeprefix(\"Tax: \"))\n",
    "        data[\"total_minor\"] = minor(lines[-1].removeprefix(\"Amount due: \"))\n",
    "    except ValueError:\n",
    "        return None\n",
    "    return parse_record(data)\n",
    "\n",
    "\n",
    "def examples_for(split: str, limit: int | None = None) -> list[Invoice]:\n",
    "    found = [invoice for invoice in make_catalog() if invoice.split == split]\n",
    "    if not found:\n",
    "        raise ValueError(f\"Unknown invoice split {split!r}\")\n",
    "    if limit is None or limit >= len(found):\n",
    "        return found\n",
    "    if limit <= 0:\n",
    "        raise ValueError(\"Limit must be positive\")\n",
    "    groups: dict[str, list[Invoice]] = {}\n",
    "    for invoice in found:\n",
    "        groups.setdefault(invoice.family, []).append(invoice)\n",
    "    balanced = [invoice for group_rows in zip(*groups.values(), strict=True) for invoice in group_rows]\n",
    "    return balanced[:limit]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92aeaae9",
   "metadata": {},
   "source": [
    "## Completion masking\n",
    "\n",
    "The prefix-stable masking and preference helpers below adapt Apache-2.0 recipe code from\n",
    "the Together Post-Training Cookbook. The shared helpers build a causal training sequence\n",
    "while marking just the answer tokens and end marker as targets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60fca6fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SPDX-License-Identifier: Apache-2.0\n",
    "\"\"\"Portable training functions from the Together Post-Training Cookbook.\n",
    "\n",
    "Adapted from togethercomputer/post-training-cookbook at\n",
    "226e03ca225d6f13434047cf0f45ab3070a29801. See third_party for the Apache licence\n",
    "and the original paths. The hosted training and provisioning code is replaced\n",
    "by notebook-local PyTorch and typed fixtures.\n",
    "\"\"\"\n",
    "\n",
    "from __future__ import annotations\n",
    "\n",
    "import random\n",
    "from collections import Counter\n",
    "from collections.abc import Callable, Iterable, Sequence\n",
    "from dataclasses import dataclass, field\n",
    "from typing import NamedTuple, TypeVar\n",
    "\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class Turn(NamedTuple):\n",
    "    prompt: list[int]\n",
    "    completion: list[int]\n",
    "\n",
    "\n",
    "class MaskedSequence(NamedTuple):\n",
    "    input_ids: list[int]\n",
    "    completion_mask: list[int]\n",
    "\n",
    "\n",
    "def split_turns(turns: Iterable[Turn]) -> list[MaskedSequence]:\n",
    "    \"\"\"Build prefix-stable sequences with a token-aligned completion mask.\"\"\"\n",
    "    sequences: list[MaskedSequence] = []\n",
    "    emitted: list[int] = []\n",
    "    mask: list[int] = []\n",
    "    for prompt, completion in turns:\n",
    "        if len(prompt) < len(emitted) or prompt[: len(emitted)] != emitted:\n",
    "            if emitted:\n",
    "                sequences.append(MaskedSequence(emitted, mask))\n",
    "            mask = [0] * len(prompt)\n",
    "        else:\n",
    "            mask = mask + [0] * (len(prompt) - len(emitted))\n",
    "        emitted = prompt + completion\n",
    "        mask = mask + [1] * len(completion)\n",
    "    if emitted:\n",
    "        sequences.append(MaskedSequence(emitted, mask))\n",
    "    return sequences\n",
    "\n",
    "\n",
    "def masked_logp_sum(logprobs: torch.Tensor, mask: Sequence[float]) -> torch.Tensor:\n",
    "    \"\"\"Sum target-aligned response log probabilities and retain gradients.\"\"\"\n",
    "    if logprobs.ndim != 1 or len(mask) != logprobs.shape[0]:\n",
    "        raise ValueError(\"The response mask must match the one-dimensional target log probabilities.\")\n",
    "    weights = torch.as_tensor(mask, dtype=logprobs.dtype, device=logprobs.device)\n",
    "    return (logprobs * weights).sum()\n",
    "\n",
    "\n",
    "def make_dpo_loss(\n",
    "    ref_sums: Sequence[float],\n",
    "    masks: Sequence[Sequence[float]],\n",
    "    *,\n",
    "    beta: float,\n",
    "    label_smoothing: float = 0.0,\n",
    ") -> Callable[[Sequence[torch.Tensor]], torch.Tensor]:\n",
    "    \"\"\"Close over fixed reference scores and response masks for chosen/rejected pairs.\"\"\"\n",
    "    if not ref_sums or len(ref_sums) != len(masks) or len(ref_sums) % 2:\n",
    "        raise ValueError(\"Supply at least one complete pair and one mask for each reference score.\")\n",
    "    if beta <= 0.0 or not 0.0 <= label_smoothing <= 0.5:\n",
    "        raise ValueError(\"Beta must be positive and label smoothing must be between 0 and 0.5.\")\n",
    "    branch_size = len(ref_sums)\n",
    "\n",
    "    def loss_fn(policy_logprobs: Sequence[torch.Tensor]) -> torch.Tensor:\n",
    "        if len(policy_logprobs) != branch_size:\n",
    "            raise ValueError(f\"Expected {branch_size} policy log-probability tensors.\")\n",
    "        policy = torch.stack([masked_logp_sum(values, mask) for values, mask in zip(policy_logprobs, masks, strict=True)])\n",
    "        reference = policy.new_tensor(ref_sums)\n",
    "        delta = policy - reference\n",
    "        margin = beta * (delta[0::2] - delta[1::2])\n",
    "        return (-(1.0 - label_smoothing) * F.logsigmoid(margin) - label_smoothing * F.logsigmoid(-margin)).mean()\n",
    "\n",
    "    return loss_fn\n",
    "\n",
    "\n",
    "def compute_overlong_penalty(\n",
    "    response_length: int,\n",
    "    max_response_length: int,\n",
    "    overlong_buffer_len: int,\n",
    "    penalty_factor: float = 1.0,\n",
    ") -> float:\n",
    "    \"\"\"Apply the cookbook's DAPO soft penalty near a generation cap.\"\"\"\n",
    "    if overlong_buffer_len <= 0:\n",
    "        return 0.0\n",
    "    expected_len = max_response_length - overlong_buffer_len\n",
    "    exceed_len = response_length - expected_len\n",
    "    return min(-exceed_len / overlong_buffer_len * penalty_factor, 0.0)\n",
    "\n",
    "\n",
    "Item = TypeVar(\"Item\")\n",
    "\n",
    "\n",
    "def oversample_until_kept(\n",
    "    draw_batch: Callable[[], Iterable[Item]],\n",
    "    *,\n",
    "    is_kept: Callable[[Item], bool],\n",
    "    target: int,\n",
    "    max_attempts: int,\n",
    ") -> tuple[list[Item], int]:\n",
    "    \"\"\"Keep rejected groups in the audit trail while bounding draws.\"\"\"\n",
    "    if target <= 0 or max_attempts <= 0:\n",
    "        raise ValueError(\"Target and maximum attempts must be positive.\")\n",
    "    items: list[Item] = []\n",
    "    kept = 0\n",
    "    for attempts in range(1, max_attempts + 1):\n",
    "        for item in draw_batch():\n",
    "            items.append(item)\n",
    "            if is_kept(item):\n",
    "                kept += 1\n",
    "                if kept >= target:\n",
    "                    return items, attempts\n",
    "    return items, max_attempts\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class TeacherRequest:\n",
    "    key: str\n",
    "    messages: Sequence[dict[str, str]]\n",
    "    meta: dict[str, object] = field(default_factory=dict)\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class TeacherOutput:\n",
    "    content: str\n",
    "    ok: bool = True\n",
    "    truncated: bool = False\n",
    "\n",
    "\n",
    "def sft_rows(\n",
    "    requests: Sequence[TeacherRequest],\n",
    "    outputs: dict[str, TeacherOutput],\n",
    "    *,\n",
    "    reject_reason: Callable[[TeacherRequest, TeacherOutput], str | None] | None = None,\n",
    ") -> tuple[list[dict[str, object]], Counter[str]]:\n",
    "    \"\"\"Convert verified procedural teacher outputs to SFT rows and count exclusions.\"\"\"\n",
    "    rows: list[dict[str, object]] = []\n",
    "    dropped: Counter[str] = Counter()\n",
    "    for request in requests:\n",
    "        output = outputs.get(request.key)\n",
    "        if output is None:\n",
    "            dropped[\"missing\"] += 1\n",
    "            continue\n",
    "        if not output.ok:\n",
    "            dropped[\"failed\"] += 1\n",
    "            continue\n",
    "        if output.truncated:\n",
    "            dropped[\"truncated\"] += 1\n",
    "            continue\n",
    "        content = output.content.strip()\n",
    "        if not content:\n",
    "            dropped[\"empty\"] += 1\n",
    "            continue\n",
    "        reason = reject_reason(request, output) if reject_reason is not None else None\n",
    "        if reason is not None:\n",
    "            dropped[reason] += 1\n",
    "            continue\n",
    "        assistant = {\"role\": \"assistant\", \"content\": content}\n",
    "        rows.append({\"id\": request.key, \"messages\": [*request.messages, assistant], \"meta\": dict(request.meta)})\n",
    "    return rows, dropped\n",
    "\n",
    "\n",
    "def mix(*groups: Sequence[Item], seed: int = 0) -> list[Item]:\n",
    "    \"\"\"Concatenate row groups and shuffle them deterministically.\"\"\"\n",
    "    rows = [row for group in groups for row in group]\n",
    "    random.Random(seed).shuffle(rows)\n",
    "    return rows"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f4204b5",
   "metadata": {},
   "source": [
    "## Training and scoring\n",
    "\n",
    "A common prompt, batch schedule and scorer make each comparison interpretable. The paired\n",
    "uncertainty calculation resamples whole layout families, so repeated layouts do not count\n",
    "as independent evidence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c983b0f",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Shared notebook-local text training and measurement for lessons 01–03.\"\"\"\n",
    "from __future__ import annotations\n",
    "\n",
    "import gc\n",
    "import hashlib\n",
    "import importlib.metadata\n",
    "import json\n",
    "import random\n",
    "import statistics\n",
    "import time\n",
    "from collections import defaultdict\n",
    "from pathlib import Path\n",
    "\n",
    "import torch\n",
    "\n",
    "MODEL = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
    "REVISION = \"7ae557604adf67be50417f59c2c2f167def9a775\"\n",
    "SEED = 42\n",
    "MAX_TOKENS = 1536\n",
    "MAX_NEW_TOKENS = 384\n",
    "BATCH = 2\n",
    "\n",
    "\n",
    "\n",
    "def canonical_json(record):\n",
    "    return json.dumps(record, ensure_ascii=False, separators=(\",\", \":\"))\n",
    "\n",
    "\n",
    "def ordered_by_family(items):\n",
    "    by_family = defaultdict(list)\n",
    "    for invoice in items:\n",
    "        by_family[invoice.family].append(invoice)\n",
    "    randomizer = random.Random(SEED)\n",
    "    families = list(by_family)\n",
    "    randomizer.shuffle(families)\n",
    "    for rows in by_family.values():\n",
    "        randomizer.shuffle(rows)\n",
    "    return [\n",
    "        by_family[family][offset]\n",
    "        for offset in range(max(map(len, by_family.values()), default=0))\n",
    "        for family in families\n",
    "        if offset < len(by_family[family])\n",
    "    ]\n",
    "\n",
    "\n",
    "def lesson_prompts(catalog):\n",
    "    \"\"\"Choose one training exemplar and preserve dataset order after seeded sampling.\"\"\"\n",
    "    train = ordered_by_family([invoice for invoice in catalog if invoice.split == \"train\"])\n",
    "    if len(train) < 3:\n",
    "        raise ValueError(\"The shared catalogue must contain at least three training invoices.\")\n",
    "    exemplar, *train = train\n",
    "    teach_splits = {\"familiar\", \"novel\", \"independent\"}\n",
    "    evaluation = [invoice for invoice in catalog if invoice.split in teach_splits]\n",
    "    if not evaluation or set(item.split for item in evaluation) != teach_splits:\n",
    "        raise ValueError(\"The three fixed teaching slices must be present.\")\n",
    "    return exemplar, train, evaluation\n",
    "\n",
    "\n",
    "def prompt_messages(invoice, exemplar):\n",
    "    return [\n",
    "        {\"role\": \"system\", \"content\": VISIBLE_CONTRACT},\n",
    "        {\"role\": \"user\", \"content\": invoice_text(exemplar)},\n",
    "        {\"role\": \"assistant\", \"content\": canonical_json(invoice_record(exemplar))},\n",
    "        {\"role\": \"user\", \"content\": invoice_text(invoice)},\n",
    "    ]\n",
    "\n",
    "\n",
    "def encode_prompt(tokenizer, invoice, exemplar):\n",
    "    return tokenizer.apply_chat_template(\n",
    "        prompt_messages(invoice, exemplar), tokenize=True, add_generation_prompt=True,\n",
    "    )\n",
    "\n",
    "\n",
    "def encode_supervision(tokenizer, invoice, answer, exemplar):\n",
    "    prompt = encode_prompt(tokenizer, invoice, exemplar)\n",
    "    completion = tokenizer.encode(answer, add_special_tokens=False) + [tokenizer.eos_token_id]\n",
    "    sequence, = split_turns([Turn(prompt, completion)])\n",
    "    if len(sequence.input_ids) > MAX_TOKENS or len(completion) + 1 > MAX_NEW_TOKENS:\n",
    "        raise ValueError(f\"Invoice {invoice.key} exceeds the fixed token budget.\")\n",
    "    return sequence\n",
    "\n",
    "\n",
    "def right_pad(examples, pad_id, device):\n",
    "    width = max(len(example.input_ids) for example in examples)\n",
    "    ids, attention, labels = [], [], []\n",
    "    for example in examples:\n",
    "        n_pad = width - len(example.input_ids)\n",
    "        ids.append(example.input_ids + [pad_id] * n_pad)\n",
    "        attention.append([1] * len(example.input_ids) + [0] * n_pad)\n",
    "        labels.append([token if mask else -100 for token, mask in zip(\n",
    "            example.input_ids, example.completion_mask, strict=True,\n",
    "        )] + [-100] * n_pad)\n",
    "    return {\n",
    "        key: torch.tensor(rows, dtype=torch.long, device=device)\n",
    "        for key, rows in ((\"input_ids\", ids), (\"attention_mask\", attention), (\"labels\", labels))\n",
    "    }\n",
    "\n",
    "\n",
    "def load_model(encoding, *, adapter=None, trainable=False):\n",
    "    from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training\n",
    "    from transformers import AutoModelForCausalLM, BitsAndBytesConfig\n",
    "\n",
    "    torch.manual_seed(SEED)\n",
    "    if encoding == \"nf4\":\n",
    "        quant = BitsAndBytesConfig(\n",
    "            load_in_4bit=True, bnb_4bit_quant_type=\"nf4\",\n",
    "            bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16,\n",
    "        )\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            MODEL, revision=REVISION, quantization_config=quant, torch_dtype=torch.float16,\n",
    "            device_map={\"\": 0}, attn_implementation=\"sdpa\",\n",
    "        )\n",
    "    elif encoding == \"fp16\":\n",
    "        model = AutoModelForCausalLM.from_pretrained(\n",
    "            MODEL, revision=REVISION, torch_dtype=torch.float16, attn_implementation=\"sdpa\",\n",
    "        ).to(\"cuda\")\n",
    "    else:\n",
    "        raise ValueError(f\"Unsupported weight encoding {encoding!r}.\")\n",
    "    if not trainable and adapter is None:\n",
    "        return model\n",
    "    if trainable and encoding == \"nf4\":\n",
    "        model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=False)\n",
    "    if adapter is not None:\n",
    "        return PeftModel.from_pretrained(model, str(adapter), is_trainable=trainable)\n",
    "    if not trainable:\n",
    "        raise ValueError(\"An adapter is required for evaluating a trained arm.\")\n",
    "    return get_peft_model(model, LoraConfig(\n",
    "        r=8, lora_alpha=16, lora_dropout=0.0, bias=\"none\",\n",
    "        task_type=\"CAUSAL_LM\", target_modules=[\"q_proj\", \"v_proj\"],\n",
    "    ))\n",
    "\n",
    "\n",
    "def adapter_train(model, schedule, objective, *, learning_rate, use_cuda):\n",
    "    \"\"\"Both arms share the same schedule, optimiser and gradient policy.\"\"\"\n",
    "    params = [param for param in model.parameters() if param.requires_grad]\n",
    "    if not params or not schedule:\n",
    "        raise ValueError(\"Expected trainable parameters and a nonempty update schedule.\")\n",
    "    optimiser = torch.optim.AdamW(params, lr=learning_rate)\n",
    "    scaler = torch.amp.GradScaler(\"cuda\", enabled=use_cuda, init_scale=512, growth_interval=10_000)\n",
    "    torch.manual_seed(SEED)\n",
    "    model.train()\n",
    "    model.config.use_cache = False\n",
    "    if use_cuda:\n",
    "        torch.cuda.synchronize()\n",
    "        torch.cuda.reset_peak_memory_stats()\n",
    "    started = time.perf_counter()\n",
    "    losses, supervised_count, batch_token_count, skipped = [], 0, 0, 0\n",
    "    for batch in schedule:\n",
    "        optimiser.zero_grad(set_to_none=True)\n",
    "        with torch.autocast(device_type=\"cuda\", dtype=torch.float16, enabled=use_cuda):\n",
    "            loss, supervised, batch_tokens = objective(model, batch)\n",
    "        if not torch.isfinite(loss).item():\n",
    "            raise FloatingPointError(\"A non-finite training loss invalidates the comparison.\")\n",
    "        scaler.scale(loss).backward()\n",
    "        scaler.unscale_(optimiser)\n",
    "        torch.nn.utils.clip_grad_norm_(params, 1.0)\n",
    "        previous_scale = scaler.get_scale()\n",
    "        scaler.step(optimiser)\n",
    "        scaler.update()\n",
    "        skipped += int(scaler.get_scale() < previous_scale)\n",
    "        losses.append(float(loss.detach().cpu()))\n",
    "        supervised_count += supervised\n",
    "        batch_token_count += batch_tokens\n",
    "    if use_cuda:\n",
    "        torch.cuda.synchronize()\n",
    "    elapsed = time.perf_counter() - started\n",
    "    return {\n",
    "        \"attempted_updates\": len(schedule),\n",
    "        \"updates\": len(schedule) - skipped,\n",
    "        \"supervised_response_tokens\": supervised_count,\n",
    "        \"unpadded_input_tokens\": batch_token_count,\n",
    "        \"seconds\": elapsed,\n",
    "        \"supervised_tokens_per_second\": supervised_count / max(elapsed, 1e-9),\n",
    "        \"peak_gib\": torch.cuda.max_memory_allocated() / 2**30 if use_cuda else None,\n",
    "        \"losses\": losses,\n",
    "        \"trainable_parameters\": sum(parameter.numel() for parameter in params),\n",
    "    }\n",
    "\n",
    "\n",
    "def sft_objective(pad_id, device):\n",
    "    def loss_for(model, examples):\n",
    "        batch = right_pad(examples, pad_id, device)\n",
    "        loss = model(**batch).loss\n",
    "        supervised = int(batch[\"labels\"][:, 1:].ne(-100).sum().item())\n",
    "        if not supervised:\n",
    "            raise ValueError(\"An update needs at least one response token.\")\n",
    "        unpadded = int(batch[\"attention_mask\"].sum().item())\n",
    "        return loss, supervised, unpadded\n",
    "    return loss_for\n",
    "\n",
    "\n",
    "def make_schedule(examples, batch_size=BATCH):\n",
    "    if not examples or batch_size <= 0:\n",
    "        raise ValueError(\"Expected training examples and a positive batch size.\")\n",
    "    return [examples[start : start + batch_size] for start in range(0, len(examples), batch_size)]\n",
    "\n",
    "\n",
    "def predictions(model, tokenizer, eval_items, exemplar, batch_size=16):\n",
    "    model.eval()\n",
    "    device = model.get_input_embeddings().weight.device\n",
    "    outputs = []\n",
    "    for start in range(0, len(eval_items), batch_size):\n",
    "        group = eval_items[start : start + batch_size]\n",
    "        prompts = [encode_prompt(tokenizer, item, exemplar) for item in group]\n",
    "        width = max(map(len, prompts))\n",
    "        if width + MAX_NEW_TOKENS > MAX_TOKENS:\n",
    "            raise ValueError(\"Evaluation prompt and fixed decode cap exceed the token budget.\")\n",
    "        ids = torch.tensor([[tokenizer.pad_token_id] * (width - len(p)) + p for p in prompts], device=device)\n",
    "        mask = torch.tensor([[0] * (width - len(p)) + [1] * len(p) for p in prompts], device=device)\n",
    "        with torch.inference_mode():\n",
    "            generated = model.generate(\n",
    "                input_ids=ids, attention_mask=mask,\n",
    "                do_sample=False, num_beams=1, max_new_tokens=MAX_NEW_TOKENS,\n",
    "                pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,\n",
    "                use_cache=True, temperature=None, top_p=None, top_k=None,\n",
    "            )\n",
    "        for item, tokens in zip(group, generated[:, width:].tolist(), strict=True):\n",
    "            stopped = tokenizer.eos_token_id in tokens\n",
    "            if stopped:\n",
    "                tokens = tokens[:tokens.index(tokenizer.eos_token_id)]\n",
    "            answer = tokenizer.decode(tokens, skip_special_tokens=True)\n",
    "            outputs.append({\n",
    "                \"key\": item.key, \"split\": item.split, \"family\": item.family,\n",
    "                \"completed\": stopped, \"answer\": answer, \"reference\": invoice_record(item),\n",
    "                \"completion_tokens\": len(tokens), **score_record(answer, item),\n",
    "            })\n",
    "    return outputs\n",
    "\n",
    "\n",
    "def rules_predictions(items):\n",
    "    rows = []\n",
    "    for item in items:\n",
    "        result = rules_extract(invoice_text(item))\n",
    "        rows.append({\n",
    "            \"key\": item.key, \"split\": item.split, \"family\": item.family,\n",
    "            \"completed\": result is not None, \"answer\": result, \"reference\": invoice_record(item),\n",
    "            **score_record(result if result is not None else \"\", item),\n",
    "        })\n",
    "    return rows\n",
    "\n",
    "\n",
    "def paired_family_interval(reference, candidate, repeats=1000):\n",
    "    \"\"\"Pair by invoice, then resample whole layout families within a slice.\"\"\"\n",
    "    deltas = defaultdict(list)\n",
    "    old_by_key = {row[\"key\"]: row for row in reference}\n",
    "    if set(old_by_key) != {row[\"key\"] for row in candidate}:\n",
    "        raise ValueError(\"Paired comparisons require the same unique invoice keys.\")\n",
    "    for row in candidate:\n",
    "        old = old_by_key[row[\"key\"]]\n",
    "        if (old[\"family\"], old[\"split\"]) != (row[\"family\"], row[\"split\"]):\n",
    "            raise ValueError(\"An invoice moved family or split.\")\n",
    "        deltas[row[\"family\"]].append(int(row[\"exact\"]) - int(old[\"exact\"]))\n",
    "    groups = list(deltas.values())\n",
    "    if len(groups) < 2:\n",
    "        return None\n",
    "    randomizer = random.Random(SEED)\n",
    "    draws = []\n",
    "    for _ in range(repeats):\n",
    "        sampled_groups = randomizer.choices(groups, k=len(groups))\n",
    "        draws.append(sum(map(sum, sampled_groups)) / sum(map(len, sampled_groups)))\n",
    "    draws.sort()\n",
    "    return [draws[int(0.025 * (repeats - 1))], draws[int(0.975 * (repeats - 1))]]\n",
    "\n",
    "\n",
    "def free_gpu():\n",
    "    \"\"\"Collect dropped references between sequential Colab arms.\"\"\"\n",
    "    gc.collect()\n",
    "    if torch.cuda.is_available():\n",
    "        torch.cuda.empty_cache()\n",
    "\n",
    "\n",
    "def save_results(lesson, scores, training, comparisons, **diagnostics):\n",
    "    import matplotlib\n",
    "    import matplotlib.pyplot as plt\n",
    "\n",
    "    seed = SEED\n",
    "    grouped = {\n",
    "        name: {\n",
    "            split: {\n",
    "                \"n\": len(rows_in_split),\n",
    "                **{\n",
    "                    metric: statistics.mean(float(row[metric]) for row in rows_in_split)\n",
    "                    for metric in (\"valid\", \"exact\", \"completed\", \"fields\", \"row_f1\")\n",
    "                },\n",
    "            }\n",
    "            for split in (\"familiar\", \"novel\", \"independent\")\n",
    "            if (rows_in_split := [row for row in rows if row[\"split\"] == split])\n",
    "        }\n",
    "        for name, rows in scores.items()\n",
    "    }\n",
    "    intervals = {}\n",
    "    for baseline, candidate in comparisons:\n",
    "        intervals[f\"{candidate} minus {baseline}\"] = {\n",
    "            split: interval\n",
    "            for split in (\"familiar\", \"novel\", \"independent\")\n",
    "            if (interval := paired_family_interval(\n",
    "                [row for row in scores[baseline] if row[\"split\"] == split],\n",
    "                [row for row in scores[candidate] if row[\"split\"] == split],\n",
    "            )) is not None\n",
    "        }\n",
    "    roster = {\n",
    "        row[\"key\"]: {\"split\": row[\"split\"], \"family\": row[\"family\"]}\n",
    "        for row in next(iter(scores.values()))\n",
    "    }\n",
    "    report = {\n",
    "        \"model_id\": MODEL, \"model_revision\": REVISION, \"seed\": seed,\n",
    "        \"versions\": {name: importlib.metadata.version(name) for name in (\"torch\", \"transformers\", \"peft\")},\n",
    "        \"hardware\": torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"CPU smoke\",\n",
    "        \"held_out_roster_sha256\": hashlib.sha256(\n",
    "            json.dumps(roster, sort_keys=True, separators=(\",\", \":\")).encode()\n",
    "        ).hexdigest(),\n",
    "        \"scores\": grouped, \"paired_family_intervals\": intervals, \"training\": training,\n",
    "        \"diagnostics\": diagnostics,\n",
    "    }\n",
    "    payload = Path(\"results\")\n",
    "    payload.mkdir(exist_ok=True)\n",
    "    (payload / f\"{lesson}-report.json\").write_text(json.dumps(report, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "    (payload / f\"{lesson}-predictions.json\").write_text(json.dumps(scores, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "    print(json.dumps({key: value for key, value in report.items() if key != \"training\"}, indent=2))\n",
    "    print(json.dumps({\n",
    "        arm: {key: value for key, value in metrics.items() if key != \"losses\"}\n",
    "        for arm, metrics in training.items()\n",
    "    }, indent=2))\n",
    "\n",
    "    matplotlib.rcParams[\"svg.fonttype\"] = \"none\"\n",
    "    fig, axes = plt.subplots(1, len(grouped[next(iter(grouped))]), figsize=(11, 4), squeeze=False, sharey=True)\n",
    "    for axis, split in zip(axes[0], grouped[next(iter(grouped))], strict=True):\n",
    "        names = list(grouped)\n",
    "        values = [grouped[name][split][\"exact\"] for name in names]\n",
    "        axis.barh(names, values, color=\"#357e72\")\n",
    "        axis.set_title(split.title())\n",
    "        axis.set_xlim(0, 1)\n",
    "        axis.set_xlabel(\"Exact record rate\")\n",
    "        axis.grid(axis=\"x\", alpha=0.2)\n",
    "    axes[0, 0].invert_yaxis()\n",
    "    fig.suptitle(\"Complete-record accuracy on the held-out invoice slices\")\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(payload / f\"{lesson}-exact.svg\", bbox_inches=\"tight\")\n",
    "    from IPython.display import SVG, display\n",
    "    display(SVG(filename=str(payload / f\"{lesson}-exact.svg\")))\n",
    "    plt.close(fig)\n",
    "    return report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eef50ec6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)\n",
    "if tokenizer.pad_token_id is None or tokenizer.eos_token_id is None:\n",
    "    raise ValueError(\"The pinned tokenizer must supply padding and completion markers.\")\n",
    "catalogue = make_catalog()\n",
    "exemplar, training_items, evaluation_items = lesson_prompts(catalogue)\n",
    "print(\"Teaching evaluation counts:\", dict(Counter(x.split for x in evaluation_items)))\n",
    "print(\"One train-only prompt exemplar:\", exemplar.key)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd9366cd",
   "metadata": {},
   "source": [
    "## Load the same ledger and verifier\n",
    "\n",
    "Each rollout uses a fresh read-only ledger and the Lesson 14 scorer. Greedy\n",
    "evaluation keeps the same requests, tool catalogue, stopping rule and token\n",
    "budget. The wrapped format changes only what the model sees after each call."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd69cff9",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Typed offline invoice tools and a bounded multi-turn execution harness.\"\"\"\n",
    "from __future__ import annotations\n",
    "\n",
    "import hashlib\n",
    "import re\n",
    "from dataclasses import asdict, dataclass\n",
    "from types import MappingProxyType\n",
    "\n",
    "TOOL_CONTRACTS = {\n",
    "    \"lookup_invoice\": ({\"invoice_id\": str}, \"Read one invoice before comparing a value.\"),\n",
    "    \"match_amount\": (\n",
    "        {\"invoice_id\": str, \"expected_minor\": int, \"currency\": str},\n",
    "        \"Compare the printed total to the amount and currency in the request.\",\n",
    "    ),\n",
    "    \"match_purchase_order\": (\n",
    "        {\"invoice_id\": str, \"purchase_order\": str},\n",
    "        \"Compare the ledger purchase-order reference with the request.\",\n",
    "    ),\n",
    "    \"match_tax\": (\n",
    "        {\"invoice_id\": str, \"expected_tax_minor\": int},\n",
    "        \"Compare the printed tax to the tax amount in the request.\",\n",
    "    ),\n",
    "    \"match_currency\": (\n",
    "        {\"invoice_id\": str, \"expected_currency\": str},\n",
    "        \"Compare the invoice currency code to the currency code in the request.\",\n",
    "    ),\n",
    "}\n",
    "TRAIN_TOOLS = (\"lookup_invoice\", \"match_amount\", \"match_purchase_order\")\n",
    "HELD_TOOLS = (\"match_tax\", \"match_currency\")\n",
    "# Two calls and a final decision fit the full three-turn budget.\n",
    "TURN_LIMIT = 3\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Entry:\n",
    "    invoice_id: str\n",
    "    currency: str\n",
    "    total_minor: int | None\n",
    "    tax_minor: int | None\n",
    "    purchase_order: str\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Case:\n",
    "    key: str\n",
    "    family: str\n",
    "    split: str\n",
    "    kind: str\n",
    "    request: str\n",
    "    target: Entry\n",
    "    decoy: Entry\n",
    "    requested_value: int | str | None = None\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Episode:\n",
    "    actions: tuple\n",
    "    observations: tuple\n",
    "    final: dict | None\n",
    "    malformed: bool = False\n",
    "\n",
    "\n",
    "def to_entry(invoice):\n",
    "    gold = invoice_record(invoice)\n",
    "    # Use a namespace disjoint from invoice and vendor identifiers.\n",
    "    suffix = hashlib.sha256((\"purchase-order:\" + invoice.key).encode()).hexdigest()[:9].upper()\n",
    "    return Entry(invoice.key, invoice.currency, gold[\"total_minor\"], gold[\"tax_minor\"], f\"PO-{suffix}\")\n",
    "\n",
    "\n",
    "def case_for(invoice, decoy, kind, *, mismatch=False):\n",
    "    target, distracting = to_entry(invoice), to_entry(decoy)\n",
    "    misleading_context = f\"The notes also mention {distracting.invoice_id}. That is a different invoice.\"\n",
    "    requests = {\n",
    "        \"lookup\": f\"Check whether the ledger contains {target.invoice_id}.\",\n",
    "        \"clarification\": \"Check the invoice amount against 1240 minor units in USD. The invoice identifier is missing.\",\n",
    "        \"no call\": \"Explain in general what an invoice identifier is. There is no record to check.\",\n",
    "    }\n",
    "    requested = None\n",
    "    if kind == \"amount\":\n",
    "        requested = target.total_minor + (101 if mismatch else 0) if target.total_minor is not None else 1240\n",
    "        request = (\n",
    "            f\"Check that {target.invoice_id} has a printed total of {requested} minor units in \"\n",
    "            f\"{target.currency}. {misleading_context}\"\n",
    "        )\n",
    "    elif kind == \"purchase order\":\n",
    "        requested = distracting.purchase_order if mismatch else target.purchase_order\n",
    "        request = f\"Verify whether {target.invoice_id} belongs to {requested}. {misleading_context}\"\n",
    "    elif kind == \"tax\":\n",
    "        requested = target.tax_minor + (10 if mismatch else 0) if target.tax_minor is not None else 120\n",
    "        request = f\"Check the printed tax on {target.invoice_id} against {requested} minor units. {misleading_context}\"\n",
    "    elif kind == \"currency\":\n",
    "        requested = {\"USD\": \"EUR\", \"EUR\": \"GBP\", \"GBP\": \"USD\"}.get(target.currency, \"USD\") if mismatch else target.currency\n",
    "        request = f\"Check whether {target.invoice_id} is denominated in {requested}. {misleading_context}\"\n",
    "    else:\n",
    "        request = requests[kind]\n",
    "        if kind == \"lookup\":\n",
    "            request += \" \" + misleading_context\n",
    "    return Case(invoice.key, invoice.family, invoice.split, kind, request, target, distracting, requested)\n",
    "\n",
    "\n",
    "def cases_for(items, *, unseen_tool=False):\n",
    "    kinds = [\"lookup\", \"amount\", \"purchase order\", \"clarification\", \"no call\"]\n",
    "    if unseen_tool:\n",
    "        kinds += [\"tax\", \"currency\", \"tax\", \"currency\"]\n",
    "    next_by_split = defaultdict(list)\n",
    "    for invoice in items:\n",
    "        next_by_split[invoice.split].append(invoice)\n",
    "    cases = []\n",
    "    for group in next_by_split.values():\n",
    "        if len(group) < 2:\n",
    "            raise ValueError(\"A split needs distinct target and decoy invoices.\")\n",
    "        for index, invoice in enumerate(group):\n",
    "            kind = kinds[index % len(kinds)]\n",
    "            cases.append(case_for(\n",
    "                invoice, group[(index + 1) % len(group)], kind,\n",
    "                mismatch=(index // len(kinds)) % 2 == 1,\n",
    "            ))\n",
    "    return cases\n",
    "\n",
    "\n",
    "def wire_call(tool, **args):\n",
    "    return {\"call\": tool, \"args\": args}\n",
    "\n",
    "\n",
    "def wire_final(decision, invoice_id=None, value=None):\n",
    "    return {\"final\": decision, \"invoice_id\": invoice_id, \"value\": value}\n",
    "\n",
    "\n",
    "def parse_wire(payload):\n",
    "    try:\n",
    "        action = json.loads(payload, object_pairs_hook=_strict_dict) if isinstance(payload, str) else payload\n",
    "    except (TypeError, ValueError, RecursionError):\n",
    "        return None\n",
    "    if not isinstance(action, dict):\n",
    "        return None\n",
    "    fields = set(action)\n",
    "    if fields == {\"call\", \"args\"} and type(action[\"call\"]) is str and isinstance(action[\"args\"], dict):\n",
    "        return action\n",
    "    if fields != {\"final\", \"invoice_id\", \"value\"}:\n",
    "        return None\n",
    "    if (\n",
    "        not isinstance(action[\"final\"], str)\n",
    "        or action[\"final\"] not in {\"found\", \"match\", \"mismatch\", \"clarify\", \"no_call\"}\n",
    "        or type(action[\"invoice_id\"]) not in {str, type(None)}\n",
    "        or type(action[\"value\"]) not in {int, str, type(None)}\n",
    "    ):\n",
    "        return None\n",
    "    return action\n",
    "\n",
    "\n",
    "class Ledger:\n",
    "    \"\"\"The backing records are immutable and the runtime scope is case-local.\"\"\"\n",
    "\n",
    "    def __init__(self, case, allowed):\n",
    "        self.entries = MappingProxyType({entry.invoice_id: entry for entry in (case.target, case.decoy)})\n",
    "        self.allowed = frozenset(allowed)\n",
    "        self.looked_up = set()\n",
    "\n",
    "    def execute(self, action):\n",
    "        name, args = action[\"call\"], action[\"args\"]\n",
    "        if name not in self.allowed:\n",
    "            return {\"ok\": False, \"error\": \"unknown_tool\"}\n",
    "        schema, _ = TOOL_CONTRACTS[name]\n",
    "        if set(args) != set(schema) or any(type(args[key]) is not t for key, t in schema.items()):\n",
    "            return {\"ok\": False, \"error\": \"invalid_arguments\"}\n",
    "        entry = self.entries.get(args[\"invoice_id\"])\n",
    "        if entry is None:\n",
    "            return {\"ok\": False, \"error\": \"unknown_invoice\"}\n",
    "        if name == \"lookup_invoice\":\n",
    "            self.looked_up.add(entry.invoice_id)\n",
    "            return {\"ok\": True, \"invoice_id\": entry.invoice_id, \"retrieved\": True}\n",
    "        if entry.invoice_id not in self.looked_up:\n",
    "            return {\"ok\": False, \"error\": \"lookup_required\"}\n",
    "        if name == \"match_amount\":\n",
    "            observed = entry.total_minor\n",
    "            matches = observed is not None and observed == args[\"expected_minor\"] and entry.currency == args[\"currency\"]\n",
    "        elif name == \"match_purchase_order\":\n",
    "            observed = entry.purchase_order\n",
    "            matches = observed == args[\"purchase_order\"]\n",
    "        elif name == \"match_tax\":\n",
    "            observed = entry.tax_minor\n",
    "            matches = observed is not None and observed == args[\"expected_tax_minor\"]\n",
    "        else:\n",
    "            observed = entry.currency\n",
    "            matches = observed == args[\"expected_currency\"]\n",
    "        return {\"ok\": True, \"invoice_id\": entry.invoice_id, \"match\": matches, \"value\": observed}\n",
    "\n",
    "\n",
    "def execute_episode(case, allowed, choose):\n",
    "    \"\"\"Execute the model's decision, feed the actual observation back, and stop on a final.\"\"\"\n",
    "    ledger = Ledger(case, allowed)\n",
    "    actions, observations = [], []\n",
    "    for _ in range(TURN_LIMIT):\n",
    "        decision = parse_wire(choose(tuple(actions), tuple(observations)))\n",
    "        if decision is None:\n",
    "            return Episode(tuple(actions), tuple(observations), None, malformed=True)\n",
    "        if \"final\" in decision:\n",
    "            return Episode(tuple(actions), tuple(observations), decision)\n",
    "        actions.append(decision)\n",
    "        observations.append(ledger.execute(decision))\n",
    "    return Episode(tuple(actions), tuple(observations), None)\n",
    "\n",
    "\n",
    "def wanted_calls(case):\n",
    "    invoice_id = case.target.invoice_id\n",
    "    lookup = wire_call(\"lookup_invoice\", invoice_id=invoice_id)\n",
    "    if case.kind == \"lookup\":\n",
    "        return [lookup]\n",
    "    if case.kind == \"amount\":\n",
    "        return [lookup, wire_call(\n",
    "            \"match_amount\", invoice_id=invoice_id,\n",
    "            expected_minor=case.requested_value, currency=case.target.currency,\n",
    "        )]\n",
    "    if case.kind == \"purchase order\":\n",
    "        return [lookup, wire_call(\"match_purchase_order\", invoice_id=invoice_id, purchase_order=case.requested_value)]\n",
    "    if case.kind == \"tax\":\n",
    "        return [lookup, wire_call(\"match_tax\", invoice_id=invoice_id, expected_tax_minor=case.requested_value)]\n",
    "    if case.kind == \"currency\":\n",
    "        return [lookup, wire_call(\"match_currency\", invoice_id=invoice_id, expected_currency=case.requested_value)]\n",
    "    return []\n",
    "\n",
    "\n",
    "def evidence_summary(case, actions, observations):\n",
    "    \"\"\"Make the rule teacher's terminal response from the observations.\"\"\"\n",
    "    if case.kind == \"clarification\":\n",
    "        return wire_final(\"clarify\")\n",
    "    if case.kind == \"no call\":\n",
    "        return wire_final(\"no_call\")\n",
    "    if not actions or not all(result[\"ok\"] for result in observations):\n",
    "        return wire_final(\"clarify\")\n",
    "    if case.kind == \"lookup\":\n",
    "        return wire_final(\"found\", observations[-1][\"invoice_id\"])\n",
    "    outcome = observations[-1]\n",
    "    return wire_final(\"match\" if outcome[\"match\"] else \"mismatch\", outcome[\"invoice_id\"], outcome[\"value\"])\n",
    "\n",
    "\n",
    "def accepted_final(case):\n",
    "    \"\"\"Build the expected terminal record without executing the rollout.\"\"\"\n",
    "    if case.kind == \"clarification\":\n",
    "        return wire_final(\"clarify\")\n",
    "    if case.kind == \"no call\":\n",
    "        return wire_final(\"no_call\")\n",
    "    if case.kind == \"lookup\":\n",
    "        return wire_final(\"found\", case.target.invoice_id)\n",
    "    actual = {\n",
    "        \"amount\": case.target.total_minor, \"purchase order\": case.target.purchase_order,\n",
    "        \"tax\": case.target.tax_minor, \"currency\": case.target.currency,\n",
    "    }[case.kind]\n",
    "    decision = \"match\" if actual is not None and actual == case.requested_value else \"mismatch\"\n",
    "    return wire_final(decision, case.target.invoice_id, actual)\n",
    "\n",
    "\n",
    "def score_episode(case, episode):\n",
    "    expected = wanted_calls(case)\n",
    "    tools_right = [a[\"call\"] for a in episode.actions] == [a[\"call\"] for a in expected]\n",
    "    exact_calls = list(episode.actions) == expected\n",
    "    valid_exec = (bool(episode.observations) or not expected) and all(\n",
    "        observation[\"ok\"] for observation in episode.observations\n",
    "    )\n",
    "    terminal = episode.final == accepted_final(case)\n",
    "    safe_abstention = (not episode.actions and terminal) if not expected else None\n",
    "    return {\n",
    "        \"structured\": not episode.malformed and episode.final is not None,\n",
    "        \"tool_selection\": tools_right,\n",
    "        \"arguments_exact\": exact_calls,\n",
    "        \"execution_ok\": valid_exec,\n",
    "        \"terminal_exact\": terminal,\n",
    "        \"abstention_exact\": safe_abstention,\n",
    "        \"success\": not episode.malformed and exact_calls and valid_exec and terminal,\n",
    "        \"turns\": len(episode.actions) + int(episode.final is not None),\n",
    "    }\n",
    "\n",
    "\n",
    "def teacher_episode(case, allowed, *, corrupt=False):\n",
    "    planned = wanted_calls(case)\n",
    "    if corrupt and planned:\n",
    "        planned = [wire_call(a[\"call\"], **{**a[\"args\"], \"invoice_id\": case.decoy.invoice_id}) for a in planned]\n",
    "\n",
    "    def choose(actions, observations):\n",
    "        if len(actions) < len(planned):\n",
    "            return planned[len(actions)]\n",
    "        if corrupt and not planned:\n",
    "            return wire_final(\"no_call\" if case.kind == \"clarification\" else \"clarify\")\n",
    "        return evidence_summary(case, actions, observations)\n",
    "\n",
    "    return execute_episode(case, allowed, choose)\n",
    "\n",
    "\n",
    "def rules_episode(case, allowed):\n",
    "    \"\"\"Parse the fixture's canonical utterances and derive a decision from the tool result.\"\"\"\n",
    "    patterns = (\n",
    "        (r\"Check whether the ledger contains (\\S+)\\.\", \"lookup_invoice\", ()),\n",
    "        (r\"Check that (\\S+) has a printed total of (\\d+) minor units in ([A-Z]{3})\\.\", \"match_amount\",\n",
    "         ((\"expected_minor\", int), (\"currency\", str))),\n",
    "        (r\"Verify whether (\\S+) belongs to (PO-[A-F0-9]+)\\.\", \"match_purchase_order\", ((\"purchase_order\", str),)),\n",
    "        (r\"Check the printed tax on (\\S+) against (\\d+) minor units\\.\", \"match_tax\", ((\"expected_tax_minor\", int),)),\n",
    "        (r\"Check whether (\\S+) is denominated in ([A-Z]{3})\\.\", \"match_currency\", ((\"expected_currency\", str),)),\n",
    "    )\n",
    "    plan = []\n",
    "    for pattern, name, fields in patterns:\n",
    "        match = re.match(pattern, case.request)\n",
    "        if match is None or name not in allowed:\n",
    "            continue\n",
    "        invoice_id, *values = match.groups()\n",
    "        plan.append(wire_call(\"lookup_invoice\", invoice_id=invoice_id))\n",
    "        if fields:\n",
    "            args = {key: parse(value) for (key, parse), value in zip(fields, values, strict=True)}\n",
    "            plan.append(wire_call(name, invoice_id=invoice_id, **args))\n",
    "        break\n",
    "\n",
    "    def choose(actions, observations):\n",
    "        if not plan:\n",
    "            return wire_final(\"no_call\" if case.request.startswith(\"Explain in general\") else \"clarify\")\n",
    "        if observations and not observations[-1][\"ok\"]:\n",
    "            return wire_final(\"clarify\")\n",
    "        if len(actions) < len(plan):\n",
    "            return plan[len(actions)]\n",
    "        last = observations[-1]\n",
    "        if len(plan) == 1:\n",
    "            return wire_final(\"found\", last[\"invoice_id\"])\n",
    "        return wire_final(\"match\" if last[\"match\"] else \"mismatch\", last[\"invoice_id\"], last[\"value\"])\n",
    "\n",
    "    return execute_episode(case, allowed, choose)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bdd575e",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Encode assistant actions and evaluate a real read-only tool loop.\"\"\"\n",
    "from __future__ import annotations\n",
    "\n",
    "TOOL_OUTPUT_LIMIT = 96\n",
    "TOOL_SYSTEM = \"\"\"\n",
    "Check the invoice ledger only when the user has requested a lookup or a comparison and\n",
    "provided a target invoice identifier. Mentioned alternate identifiers are different invoices.\n",
    "A comparison requires a successful lookup for the target followed by a comparison tool.\n",
    "Reply with one JSON object per turn. To call a tool use {\"call\":\"tool_name\",\"args\":{...}}.\n",
    "After lookup alone use {\"final\":\"found\",\"invoice_id\":\"the target identifier\",\"value\":null}.\n",
    "After comparison use {\"final\":\"match\" or \"mismatch\",\"invoice_id\":\"the target identifier\",\"value\":the observed value}.\n",
    "Read the actual comparison outcome and value from the tool response. Use\n",
    "{\"final\":\"clarify\",\"invoice_id\":null,\"value\":null} for a check with no invoice identifier.\n",
    "Use {\"final\":\"no_call\",\"invoice_id\":null,\"value\":null} for general questions. No prose or fences.\n",
    "\"\"\".strip()\n",
    "\n",
    "\n",
    "def tool_schema(allowed):\n",
    "    wire_types = {str: \"string\", int: \"integer\"}\n",
    "    schemas = []\n",
    "    for name in allowed:\n",
    "        fields, description = TOOL_CONTRACTS[name]\n",
    "        schemas.append({\n",
    "            \"name\": name, \"description\": description,\n",
    "            \"args\": {key: wire_types[python_type] for key, python_type in fields.items()},\n",
    "        })\n",
    "    return schemas\n",
    "\n",
    "\n",
    "def tool_messages(case, allowed, actions, observations, *, wrap_result=False):\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": TOOL_SYSTEM + \"\\nAvailable read-only tools:\\n\" + canonical_json(tool_schema(allowed))},\n",
    "        {\"role\": \"user\", \"content\": case.request},\n",
    "    ]\n",
    "    for action, observation in zip(actions, observations, strict=True):\n",
    "        messages.append({\"role\": \"assistant\", \"content\": canonical_json(action)})\n",
    "        messages.append({\"role\": \"tool\", \"content\": canonical_json({\"result\": observation} if wrap_result else observation)})\n",
    "    return messages\n",
    "\n",
    "\n",
    "def encode_episode(tokenizer, case, allowed, episode):\n",
    "    turns = []\n",
    "    for index, response in enumerate((*episode.actions, episode.final)):\n",
    "        if response is None:\n",
    "            raise ValueError(f\"Trace {case.key} has no terminal response.\")\n",
    "        messages = tool_messages(case, allowed, episode.actions[:index], episode.observations[:index])\n",
    "        prompt = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)\n",
    "        completion = tokenizer.encode(canonical_json(response), add_special_tokens=False) + [tokenizer.eos_token_id]\n",
    "        if len(completion) > TOOL_OUTPUT_LIMIT or len(prompt) + len(completion) > MAX_TOKENS:\n",
    "            raise ValueError(f\"Trace {case.key} exceeds the fixed token budget.\")\n",
    "        turns.append(Turn(prompt, completion))\n",
    "    sequences = split_turns(turns)\n",
    "    if sum(sum(sequence.completion_mask) for sequence in sequences) != sum(len(turn.completion) for turn in turns):\n",
    "        raise ValueError(f\"Trace {case.key} lost supervised response tokens.\")\n",
    "    return sequences\n",
    "\n",
    "\n",
    "def paired_tool_schedules(tokenizer, cases):\n",
    "    examples = {\"raw\": [], \"verified\": []}\n",
    "    audit = []\n",
    "    for index, case in enumerate(cases):\n",
    "        raw = teacher_episode(case, TRAIN_TOOLS, corrupt=index % 3 == 0)\n",
    "        verified = teacher_episode(case, TRAIN_TOOLS)\n",
    "        raw_score = score_episode(case, raw)\n",
    "        verified_score = score_episode(case, verified)\n",
    "        if not verified_score[\"success\"] or raw_score[\"turns\"] != verified_score[\"turns\"]:\n",
    "            raise ValueError(f\"Training traces differ in required structure or verification failed for {case.key}.\")\n",
    "        if raw_score[\"success\"] != (index % 3 != 0):\n",
    "            raise ValueError(f\"Training corruption did not match the audit for {case.key}.\")\n",
    "        examples[\"raw\"].append(encode_episode(tokenizer, case, TRAIN_TOOLS, raw))\n",
    "        examples[\"verified\"].append(encode_episode(tokenizer, case, TRAIN_TOOLS, verified))\n",
    "        audit.append({\n",
    "            \"case\": case.key, \"kind\": case.kind, \"raw\": raw_score, \"verified\": verified_score,\n",
    "        })\n",
    "    schedules = {\n",
    "        name: [[sequence for trace in update for sequence in trace] for update in make_schedule(traces)]\n",
    "        for name, traces in examples.items()\n",
    "    }\n",
    "    return schedules, audit\n",
    "\n",
    "\n",
    "def model_episode(model, tokenizer, case, allowed, *, wrap_result=False):\n",
    "    device = model.get_input_embeddings().weight.device\n",
    "    completions = []\n",
    "\n",
    "    def choose(actions, observations):\n",
    "        messages = tool_messages(case, allowed, actions, observations, wrap_result=wrap_result)\n",
    "        prompt = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)\n",
    "        if len(prompt) + TOOL_OUTPUT_LIMIT > MAX_TOKENS:\n",
    "            raise ValueError(f\"Evaluation trace {case.key} exceeds the fixed token budget.\")\n",
    "        ids = torch.tensor([prompt], dtype=torch.long, device=device)\n",
    "        with torch.inference_mode():\n",
    "            generated = model.generate(\n",
    "                input_ids=ids, attention_mask=torch.ones_like(ids), do_sample=False, num_beams=1,\n",
    "                max_new_tokens=TOOL_OUTPUT_LIMIT, pad_token_id=tokenizer.pad_token_id,\n",
    "                eos_token_id=tokenizer.eos_token_id, use_cache=True,\n",
    "                temperature=None, top_p=None, top_k=None,\n",
    "            )\n",
    "        tokens = generated[0, len(prompt):].tolist()\n",
    "        eos = tokenizer.eos_token_id\n",
    "        if eos in tokens:\n",
    "            tokens = tokens[:tokens.index(eos)]\n",
    "        response = tokenizer.decode(tokens, skip_special_tokens=False).strip()\n",
    "        completions.append(response)\n",
    "        return response\n",
    "\n",
    "    return execute_episode(case, allowed, choose), completions\n",
    "\n",
    "\n",
    "def ledger_predictions(predict, cases):\n",
    "    results = []\n",
    "    for case in cases:\n",
    "        allowed = (*TRAIN_TOOLS, *HELD_TOOLS)\n",
    "        episode, completions = predict(case, allowed)\n",
    "        results.append({\n",
    "            \"case\": case.key, \"split\": case.split, \"family\": case.family, \"kind\": case.kind, \"request\": case.request,\n",
    "            \"actions\": episode.actions, \"observations\": episode.observations, \"final\": episode.final,\n",
    "            \"completions\": completions, \"expected_calls\": wanted_calls(case), \"expected_final\": accepted_final(case),\n",
    "            **score_episode(case, episode),\n",
    "        })\n",
    "    return results\n",
    "\n",
    "\n",
    "def ledger_summary(results):\n",
    "    slices = {\n",
    "        \"seen_operations\": [row for row in results if row[\"kind\"] in {\"lookup\", \"amount\", \"purchase order\"}],\n",
    "        \"unseen_tax_operation\": [row for row in results if row[\"kind\"] == \"tax\"],\n",
    "        \"unseen_currency_operation\": [row for row in results if row[\"kind\"] == \"currency\"],\n",
    "        \"clarification\": [row for row in results if row[\"kind\"] == \"clarification\"],\n",
    "        \"no_call\": [row for row in results if row[\"kind\"] == \"no call\"],\n",
    "    }\n",
    "    metrics = (\"structured\", \"tool_selection\", \"arguments_exact\", \"execution_ok\", \"terminal_exact\", \"success\")\n",
    "    return {\n",
    "        name: {\n",
    "            \"n\": len(rows),\n",
    "            \"count\": {metric: sum(row[metric] for row in rows) for metric in metrics},\n",
    "            \"fraction\": {metric: sum(row[metric] for row in rows) / len(rows) for metric in metrics},\n",
    "        }\n",
    "        for name, rows in slices.items() if rows\n",
    "    }\n",
    "\n",
    "\n",
    "def paired_tool_changes(raw, verified):\n",
    "    def to_rows(rows):\n",
    "        return [{\"key\": row[\"case\"], \"split\": row[\"split\"], \"family\": row[\"family\"], \"exact\": row[\"success\"]} for row in rows]\n",
    "\n",
    "    by_kind = {}\n",
    "    for kind in (\"lookup\", \"amount\", \"purchase order\", \"tax\", \"currency\", \"clarification\", \"no call\"):\n",
    "        old = to_rows(row for row in raw if row[\"kind\"] == kind)\n",
    "        new = to_rows(row for row in verified if row[\"kind\"] == kind)\n",
    "        by_kind[kind] = {\n",
    "            \"n\": len(old),\n",
    "            \"gain\": (sum(row[\"exact\"] for row in new) - sum(row[\"exact\"] for row in old)) / len(old),\n",
    "            \"paired_family_interval\": paired_family_interval(old, new),\n",
    "        }\n",
    "    return by_kind\n",
    "\n",
    "\n",
    "def check_tool_rosters(train, held):\n",
    "    seen_kinds = {\"lookup\", \"amount\", \"purchase order\", \"clarification\", \"no call\"}\n",
    "    held_kinds = seen_kinds | {\"tax\", \"currency\"}\n",
    "    for rows, expected in ((train, seen_kinds), (held, held_kinds)):\n",
    "        if set(row.kind for row in rows) != expected or len({row.key for row in rows}) != len(rows):\n",
    "            raise ValueError(\"Expected each question type and unique cases within each roster.\")\n",
    "    if ({row.key for row in train} & {row.key for row in held}\n",
    "            or {row.family for row in train} & {row.family for row in held}):\n",
    "        raise ValueError(\"Training and evaluation contain overlapping cases or families.\")\n",
    "    if set(HELD_TOOLS) & set(TRAIN_TOOLS):\n",
    "        raise ValueError(\"Held-out tool schemas appear in the training tool pack.\")\n",
    "    return {\"train\": dict(Counter(row.kind for row in train)),\n",
    "            \"held\": dict(Counter(row.kind for row in held))}\n",
    "\n",
    "\n",
    "def tool_trace_audit_by_kind(audit):\n",
    "    totals = defaultdict(lambda: {\"count\": 0, \"raw_execution_ok\": 0, \"raw_success\": 0, \"verified_success\": 0})\n",
    "    for row in audit:\n",
    "        bucket = totals[row[\"kind\"]]\n",
    "        bucket[\"count\"] += 1\n",
    "        bucket[\"raw_execution_ok\"] += int(row[\"raw\"][\"execution_ok\"])\n",
    "        bucket[\"raw_success\"] += int(row[\"raw\"][\"success\"])\n",
    "        bucket[\"verified_success\"] += int(row[\"verified\"][\"success\"])\n",
    "    return dict(totals)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a0cfb68",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Bounded policy-gradient comparison on the synthetic invoice ledger.\"\"\"\n",
    "\n",
    "GROUP_SIZE = 4\n",
    "SCREEN_CASES = 12\n",
    "MAX_GROUPS = 8\n",
    "ROLLOUT_LR = 2e-5\n",
    "\n",
    "\n",
    "def assistant_episode(model, tokenizer, case, allowed, *, sample=False, wrapped=False):\n",
    "    \"\"\"Retain exactly the sampled continuation for each model decision.\"\"\"\n",
    "    device = model.get_input_embeddings().weight.device\n",
    "    turns, texts = [], []\n",
    "\n",
    "    def choose(actions, observations):\n",
    "        prompt = tokenizer.apply_chat_template(\n",
    "            tool_messages(case, allowed, actions, observations, wrap_result=wrapped),\n",
    "            tokenize=True, add_generation_prompt=True,\n",
    "        )\n",
    "        if len(prompt) + TOOL_OUTPUT_LIMIT > MAX_TOKENS:\n",
    "            raise ValueError(f\"{case.key} exceeds the fixed context budget.\")\n",
    "        ids = torch.tensor([prompt], dtype=torch.long, device=device)\n",
    "        with torch.no_grad():\n",
    "            generated = model.generate(\n",
    "                input_ids=ids, attention_mask=torch.ones_like(ids), do_sample=sample,\n",
    "                temperature=1.0 if sample else None, top_k=0 if sample else None,\n",
    "                top_p=1.0 if sample else None, repetition_penalty=1.0 if sample else 1.1,\n",
    "                num_beams=1, max_new_tokens=TOOL_OUTPUT_LIMIT,\n",
    "                pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, use_cache=True,\n",
    "            )[0, len(prompt):].tolist()\n",
    "        visible = generated\n",
    "        if tokenizer.eos_token_id in generated:\n",
    "            visible = generated[:generated.index(tokenizer.eos_token_id)]\n",
    "        response = tokenizer.decode(visible, skip_special_tokens=False).strip()\n",
    "        turns.append((prompt, generated))\n",
    "        texts.append(response)\n",
    "        return response\n",
    "\n",
    "    episode = execute_episode(case, allowed, choose)\n",
    "    return episode, texts, turns\n",
    "\n",
    "\n",
    "def sample_group(model, tokenizer, case):\n",
    "    model.eval()\n",
    "    group = []\n",
    "    for _ in range(GROUP_SIZE):\n",
    "        episode, texts, turns = assistant_episode(model, tokenizer, case, TRAIN_TOOLS, sample=True)\n",
    "        group.append({\n",
    "            \"reward\": int(score_episode(case, episode)[\"success\"]),\n",
    "            \"turns\": turns,\n",
    "            \"replay\": {\"completions\": texts, **asdict(episode)},\n",
    "        })\n",
    "    return group\n",
    "\n",
    "\n",
    "def reinforce_group(model, group, optimiser):\n",
    "    \"\"\"Single on-policy step with leave-one-out baselines and per-turn microbatches.\"\"\"\n",
    "    rewards = [item[\"reward\"] for item in group]\n",
    "    advantages = [(len(group) * r - sum(rewards)) / (len(group) - 1) for r in rewards]\n",
    "    if not any(advantages):\n",
    "        return None\n",
    "    device = model.get_input_embeddings().weight.device\n",
    "    parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]\n",
    "    optimiser.zero_grad(set_to_none=True)\n",
    "    # Keep the rollout policy unchanged while accumulating gradients across turns.\n",
    "    model.eval()\n",
    "    loss_sum = 0.0\n",
    "    for item, advantage in zip(group, advantages, strict=True):\n",
    "        for prompt, completion in item[\"turns\"]:\n",
    "            ids = torch.tensor([prompt + completion], dtype=torch.long, device=device)\n",
    "            logits = model(input_ids=ids, use_cache=False).logits[0, len(prompt) - 1:-1].float()\n",
    "            token_loss = torch.nn.functional.cross_entropy(logits, ids[0, len(prompt):], reduction=\"sum\")\n",
    "            loss = token_loss * advantage / len(group)\n",
    "            if not torch.isfinite(loss).item():\n",
    "                raise FloatingPointError(\"Nonfinite response loss.\")\n",
    "            loss.backward()\n",
    "            loss_sum += float(loss.detach().cpu())\n",
    "    gradient_norm = torch.nn.utils.clip_grad_norm_(parameters, 1.0, error_if_nonfinite=True)\n",
    "    if gradient_norm.item() == 0:\n",
    "        return None\n",
    "    optimiser.step()\n",
    "    return {\"loss\": loss_sum, \"gradient_norm\": float(gradient_norm), \"rewards\": rewards}\n",
    "\n",
    "\n",
    "def assess_policy(model, tokenizer, cases, *, wrapped):\n",
    "    model.eval()\n",
    "    token_counts = {}\n",
    "\n",
    "    def predict(case, allowed):\n",
    "        episode, texts, turns = assistant_episode(model, tokenizer, case, allowed, wrapped=wrapped)\n",
    "        token_counts[case.key] = sum(len(tokens) for _, tokens in turns)\n",
    "        return episode, texts\n",
    "\n",
    "    rows = ledger_predictions(predict, cases)\n",
    "    return [\n",
    "        {**row, \"generated_tokens\": token_counts[row[\"case\"]], \"tool_calls\": len(row[\"actions\"]),\n",
    "         \"model_visible_observations\": [{\"result\": obs} if wrapped else obs for obs in row[\"observations\"][:len(row[\"completions\"]) - 1]]}\n",
    "        for row in rows\n",
    "    ]\n",
    "\n",
    "\n",
    "def matched_metrics(before, after):\n",
    "    pairs = list(zip(before, after, strict=True))\n",
    "    if any(a[\"case\"] != b[\"case\"] for a, b in pairs):\n",
    "        raise ValueError(\"Mismatch in paired roster.\")\n",
    "    joint = [(a, b) for a, b in pairs if a[\"success\"] and b[\"success\"]]\n",
    "    score_columns = lambda rows: [\n",
    "        {\"key\": row[\"case\"], \"family\": row[\"family\"], \"split\": row[\"split\"], \"exact\": row[\"success\"]}\n",
    "        for row in rows\n",
    "    ]\n",
    "    return {\n",
    "        \"n\": len(pairs),\n",
    "        \"before_passes\": sum(a[\"success\"] for a, _ in pairs),\n",
    "        \"after_passes\": sum(b[\"success\"] for _, b in pairs),\n",
    "        \"paired_family_interval\": paired_family_interval(score_columns(before), score_columns(after)),\n",
    "        \"gained\": [b[\"case\"] for a, b in pairs if not a[\"success\"] and b[\"success\"]],\n",
    "        \"lost\": [b[\"case\"] for a, b in pairs if a[\"success\"] and not b[\"success\"]],\n",
    "        \"jointly_solved\": [a[\"case\"] for a, _ in joint],\n",
    "        \"joint_mean_cost\": {\n",
    "            key: {\n",
    "                \"before\": sum(a[key] for a, _ in joint) / len(joint),\n",
    "                \"after\": sum(b[key] for _, b in joint) / len(joint),\n",
    "            } if joint else None\n",
    "            for key in (\"tool_calls\", \"generated_tokens\")\n",
    "        },\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69239d78",
   "metadata": {},
   "source": [
    "## Freeze the training and evaluation cases\n",
    "\n",
    "Reuse both Lesson 14 rosters. Test cases and families stay outside training\n",
    "and task selection. Screen a bounded, fixed subset of training requests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf8949d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "output = Path(\"results\")\n",
    "output.mkdir(exist_ok=True)\n",
    "train_cases = cases_for(examples_for(\"train\", 90))\n",
    "held_items = [item for split in (\"familiar\", \"novel\", \"independent\") for item in examples_for(split, 18)]\n",
    "held_cases = cases_for(held_items, unseen_tool=True)\n",
    "roster = check_tool_rosters(train_cases, held_cases)\n",
    "grading_case = next(case for case in train_cases if case.kind == \"amount\")\n",
    "grading_audit = {}\n",
    "for name, corrupt, expected in ((\"correct\", False, True), (\"wrong_invoice\", True, False)):\n",
    "    episode = teacher_episode(grading_case, TRAIN_TOOLS, corrupt=corrupt)\n",
    "    score = score_episode(grading_case, episode)\n",
    "    if not score[\"execution_ok\"] or score[\"success\"] != expected:\n",
    "        raise RuntimeError(f\"The verifier failed its deterministic {name} check.\")\n",
    "    grading_audit[name] = {\"expected_pass\": expected, \"observed_pass\": score[\"success\"],\n",
    "                           \"execution_ok\": score[\"execution_ok\"], \"replay\": asdict(episode)}\n",
    "print(\"Verifier controls:\", json.dumps(grading_audit, indent=2))\n",
    "screen_cases = random.Random(SEED).sample(train_cases, SCREEN_CASES)\n",
    "schedules, _ = paired_tool_schedules(tokenizer, train_cases)\n",
    "print(\"Training and held-out coverage:\", roster)\n",
    "print(\"Screen cases:\", [case.key for case in screen_cases])\n",
    "print(\"CUDA:\", torch.version.cuda)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df204deb",
   "metadata": {},
   "source": [
    "## Check the resource budget and screen the frozen model\n",
    "\n",
    "Profile one supervised update on the widest scheduled batch. Then let the\n",
    "frozen model choose its actions in the canonical ledger. Count how often\n",
    "the binary verifier passes and fails on each repeated case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4cebf0ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "free, _ = torch.cuda.mem_get_info()\n",
    "if free < 10 * 2**30:\n",
    "    raise RuntimeError(\"At least 10 GiB must be free before profiling.\")\n",
    "wide = max(schedules[\"verified\"], key=lambda batch: max(len(s.input_ids) for s in batch) * len(batch))\n",
    "model = load_model(\"fp16\", trainable=True)\n",
    "profile = adapter_train(model, [wide], sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "                        learning_rate=2e-4, use_cuda=True)\n",
    "profile[\"reserved_gib\"] = torch.cuda.max_memory_reserved() / 2**30\n",
    "(output / \"14-rollout-profile.json\").write_text(json.dumps(profile, indent=2))\n",
    "if (profile[\"updates\"] != 1 or profile[\"seconds\"] > 45 or profile[\"peak_gib\"] > 9\n",
    "        or profile[\"reserved_gib\"] > min(11, free / 2**30 - 1)):\n",
    "    raise RuntimeError(\"The widest supervised update exceeded the T4 budget.\")\n",
    "del model\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f92efd5",
   "metadata": {},
   "source": [
    "## Hold the frozen and supervised references fixed\n",
    "\n",
    "Compare both references on the canonical and wrapped formats. Independently\n",
    "screen the supervised checkpoint on the same training requests. The\n",
    "rollout-trained branch starts from this supervised checkpoint by design.\n",
    "Its difference from the supervised reference isolates the additional updates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a65bb83",
   "metadata": {},
   "outputs": [],
   "source": [
    "formats = {\"canonical\": False, \"wrapped\": True}\n",
    "report = {\"model\": MODEL, \"revision\": REVISION, \"seed\": SEED, \"coverage\": roster,\n",
    "          \"grader_checks\": grading_audit,\n",
    "          \"gpu\": torch.cuda.get_device_name(0), \"torch\": torch.__version__, \"cuda\": torch.version.cuda,\n",
    "          \"settings\": {\"group_size\": GROUP_SIZE, \"screen_cases\": SCREEN_CASES, \"group_limit\": MAX_GROUPS,\n",
    "                       \"turn_limit\": TURN_LIMIT, \"tokens_per_turn\": TOOL_OUTPUT_LIMIT,\n",
    "                       \"temperature\": 1.0, \"rollout_lr\": ROLLOUT_LR},\n",
    "          \"screen\": {}, \"updates\": [], \"evaluation\": {}}\n",
    "\n",
    "def evaluate_formats(model):\n",
    "    return {name: assess_policy(model, tokenizer, held_cases, wrapped=wrapped)\n",
    "            for name, wrapped in formats.items()}\n",
    "\n",
    "def screen(model):\n",
    "    torch.manual_seed(SEED)\n",
    "    results = {}\n",
    "    for case in screen_cases:\n",
    "        group = sample_group(model, tokenizer, case)\n",
    "        results[case.key] = [\n",
    "            {\"reward\": item[\"reward\"], **item[\"replay\"]} for item in group\n",
    "        ]\n",
    "    return results\n",
    "\n",
    "def screen_summary(rows):\n",
    "    return {key: [attempt[\"reward\"] for attempt in attempts] for key, attempts in rows.items()}\n",
    "\n",
    "model = load_model(\"fp16\")\n",
    "report[\"screen\"][\"frozen\"] = screen(model)\n",
    "print(\"Frozen training-case rewards:\", screen_summary(report[\"screen\"][\"frozen\"]))\n",
    "report[\"evaluation\"][\"frozen\"] = evaluate_formats(model)\n",
    "del model\n",
    "free_gpu()\n",
    "\n",
    "model = load_model(\"fp16\", trainable=True)\n",
    "report[\"sft\"] = adapter_train(model, schedules[\"verified\"], sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "                              learning_rate=2e-4, use_cuda=True)\n",
    "if report[\"sft\"][\"updates\"] != len(schedules[\"verified\"]):\n",
    "    raise RuntimeError(\"The supervised reference missed scheduled updates.\")\n",
    "report[\"evaluation\"][\"verified_sft\"] = evaluate_formats(model)\n",
    "report[\"screen\"][\"verified_sft\"] = screen(model)\n",
    "print(\"Verified SFT training-case rewards:\", screen_summary(report[\"screen\"][\"verified_sft\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cf19821",
   "metadata": {},
   "source": [
    "## Update only when the reward can distinguish attempts\n",
    "\n",
    "Use exact task success as the binary reward. Each rollout's advantage is its\n",
    "reward minus the mean reward of the other attempts. Sample new groups on the\n",
    "current policy so assistant-token log probabilities match the sampled policy.\n",
    "If a fresh group ties, skip the update and record the attempt. An all-tied\n",
    "screen or training pass produces no rollout-trained checkpoint to compare.\n",
    "\n",
    "This single-GPU demonstration uses a synchronous REINFORCE update. The\n",
    "[Hugging Face report](https://huggingface.co/blog/harness-adapters-at-scale)\n",
    "uses AsyncGRPO to overlap rollout generation and optimisation at larger scale."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b1c5618",
   "metadata": {},
   "outputs": [],
   "source": [
    "sft_screen = screen_summary(report[\"screen\"][\"verified_sft\"])\n",
    "selected = [case for case in screen_cases if 0 < sum(sft_screen[case.key]) < GROUP_SIZE][:MAX_GROUPS]\n",
    "report[\"selected_training_cases\"] = [case.key for case in selected]\n",
    "report[\"screen_zero_variance\"] = {\n",
    "    name: sum(len(set(rewards)) == 1 for rewards in screen_summary(rows).values())\n",
    "    for name, rows in report[\"screen\"].items()\n",
    "}\n",
    "optimiser = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=ROLLOUT_LR)\n",
    "torch.manual_seed(SEED + 1)\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "for case in selected:\n",
    "    torch.cuda.synchronize()\n",
    "    started = time.perf_counter()\n",
    "    group = sample_group(model, tokenizer, case)\n",
    "    update = reinforce_group(model, group, optimiser)\n",
    "    torch.cuda.synchronize()\n",
    "    elapsed = time.perf_counter() - started\n",
    "    reserved = torch.cuda.max_memory_reserved() / 2**30\n",
    "    report[\"updates\"].append({\n",
    "        \"case\": case.key, \"rewards\": [item[\"reward\"] for item in group],\n",
    "        \"update\": update, \"seconds\": elapsed, \"peak_reserved_gib\": reserved,\n",
    "        \"replays\": [item[\"replay\"] for item in group],\n",
    "    })\n",
    "    if elapsed > 60 or reserved > min(11, free / 2**30 - 1):\n",
    "        raise RuntimeError(\"The rollout group exceeded the T4 resource budget.\")\n",
    "successful_updates = sum(row[\"update\"] is not None for row in report[\"updates\"])\n",
    "report[\"rollout_status\"] = \"trained\" if successful_updates else \"no_signal\"\n",
    "print(\"Rollout updates:\", successful_updates, \"of\", len(selected), \"attempted groups\")\n",
    "if successful_updates:\n",
    "    report[\"evaluation\"][\"rollout\"] = evaluate_formats(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b894d46a",
   "metadata": {},
   "source": [
    "## Compare the same held-out requests\n",
    "\n",
    "Report gains and losses on paired cases. For efficiency, compare calls and\n",
    "generated tokens only on cases both policies solve, and show the denominator.\n",
    "The exact verifier fixes the accepted call sequence per case, so joint\n",
    "successes cannot differ in tool-call count here. Generated tokens can differ.\n",
    "Inspect the recorded tool outputs and model text before attributing any\n",
    "difference to adaptation or to the new wrapper."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45aaac75",
   "metadata": {},
   "outputs": [],
   "source": [
    "evaluated = report[\"evaluation\"]\n",
    "paired = {\"format\": {}, \"policy\": {}}\n",
    "for name, formats_results in evaluated.items():\n",
    "    paired[\"format\"][name] = matched_metrics(formats_results[\"canonical\"], formats_results[\"wrapped\"])\n",
    "for before, after in ((\"frozen\", \"verified_sft\"), (\"frozen\", \"rollout\"), (\"verified_sft\", \"rollout\")):\n",
    "    if after in evaluated:\n",
    "        paired[\"policy\"][f\"{before}_to_{after}\"] = {\n",
    "            fmt: matched_metrics(evaluated[before][fmt], evaluated[after][fmt]) for fmt in formats\n",
    "        }\n",
    "report[\"paired\"] = paired\n",
    "(output / \"14-rollout-results.json\").write_text(json.dumps(report, indent=2))\n",
    "print(json.dumps(paired, indent=2))\n",
    "for name, arms in evaluated.items():\n",
    "    print(name, json.dumps([row for row in arms[\"canonical\"] if row[\"case\"] == \"SF-429916\"], indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c799c89",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Compare the frozen and supervised references first. If rollout updates\n",
    "occurred, compare the trained branch against both references. Keep the result\n",
    "of task screening separate from held-out pass rates and keep any observed\n",
    "transfer scoped to the result wrapper tested here.\n",
    "\n",
    "[Read Lesson 14](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/14-train-on-verified-tool-calls)\n",
    "\n",
    "All ledger records are synthetic. The multi-turn masking helper adapts Apache-2.0\n",
    "[Together Post-Training Cookbook code](https://github.com/togethercomputer/post-training-cookbook/tree/226e03ca225d6f13434047cf0f45ab3070a29801)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
