{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "500fc49c",
   "metadata": {},
   "source": [
    "# 14 · Train on verified tool calls\n",
    "\n",
    "An analyst asks to check the printed total of invoice **SF-429916** against **GBP 2,349.76**.\n",
    "Their notes mention **SF-862527**. Both invoices exist. Which record should the ledger check,\n",
    "and can a successful response prove the right one was checked?\n",
    "\n",
    "Compare two small adapters trained on the same ledger requests. Separate JSON structure,\n",
    "successful execution, correct lookup, and the evidence in the terminal response.\n",
    "\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/14-train-on-verified-tool-calls)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45906e99",
   "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": "04b08b07",
   "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": "0d15315b",
   "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": "54bcd764",
   "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": "440092b0",
   "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": "b1dcfbe3",
   "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": "b51680f3",
   "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": "226d72b9",
   "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": "811f8ed4",
   "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": "a1d81ce0",
   "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": "49b36b49",
   "metadata": {},
   "source": [
    "## A read-only ledger with a decoy\n",
    "\n",
    "Each case contains an immutable target and decoy. Lookup is required before a match. Tool\n",
    "results contain observed values or errors and feed back into the next assistant turn. At\n",
    "most three assistant decisions fit in an episode. Ambiguous record checks require\n",
    "clarification, and conceptual questions score as successful only without a ledger call.\n",
    "The tool runtime and semantic verifier each have independent outcomes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2621bb8",
   "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": "790a7f2a",
   "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": "markdown",
   "id": "0ef82583",
   "metadata": {},
   "source": [
    "## Freeze the rosters\n",
    "\n",
    "The fit rows use the training split. All three learned and prompted arms see identical held\n",
    "families and schemas. Tax and currency checks appear only at evaluation. The original invoice extraction prompt\n",
    "gives a regression check alongside the tool task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01974794",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_cases = cases_for(examples_for(\"train\", 90))\n",
    "probe_items = [item for split in (\"familiar\", \"novel\", \"independent\") for item in examples_for(split, 18)]\n",
    "held_cases = cases_for(probe_items, unseen_tool=True)\n",
    "regression_items = [item for split in (\"familiar\", \"novel\", \"independent\") for item in examples_for(split, 4)]\n",
    "coverage = check_tool_rosters(train_cases, held_cases)\n",
    "print(\"Fit by question\", coverage[\"train\"])\n",
    "print(\"Evaluation by question\", coverage[\"held\"])\n",
    "print(\"Evaluation by slice and question\", dict(Counter((case.split, case.kind) for case in held_cases)))\n",
    "opening_case = next(case for case in held_cases if case.key == \"SF-429916\")\n",
    "opening_replays = {\n",
    "    \"request\": opening_case.request,\n",
    "    \"expected\": asdict(teacher_episode(opening_case, TRAIN_TOOLS)),\n",
    "    \"decoy\": asdict(teacher_episode(opening_case, TRAIN_TOOLS, corrupt=True)),\n",
    "}\n",
    "print(json.dumps(opening_replays, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcafd24a",
   "metadata": {},
   "source": [
    "## Train on raw and verified traces\n",
    "\n",
    "For a fixed third of the training roster, replace the correct record with the decoy, or swap\n",
    "the two no-call outcomes. The decoy can return a real value, so successful execution does\n",
    "not prove task correctness. Replay collects observations in both arms. The verified arm must\n",
    "also pass exact action, argument and terminal checks. The grouped optimizer batches preserve\n",
    "the same cases and assistant-turn count. Report actual token counts and successful updates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4272de0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "schedules, training_audit = paired_tool_schedules(tokenizer, train_cases)\n",
    "teacher_audit_by_kind = tool_trace_audit_by_kind(training_audit)\n",
    "print(\"Pre-fit teacher versus independent scorer\", json.dumps(teacher_audit_by_kind, indent=2))\n",
    "print(\"Updates per arm\", {name: len(schedule) for name, schedule in schedules.items()})\n",
    "example = next(case for case in train_cases if case.kind == \"amount\")\n",
    "replay = teacher_episode(example, TRAIN_TOOLS, corrupt=True)\n",
    "print(json.dumps({\n",
    "    \"request\": example.request, \"actions\": replay.actions, \"observations\": replay.observations,\n",
    "    \"final\": replay.final, \"score\": score_episode(example, replay),\n",
    "}, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c4e2adb",
   "metadata": {},
   "source": [
    "## Check one update on the longest training batch\n",
    "\n",
    "Use the widest padded training batch from either branch. Record the synchronised step and\n",
    "the allocator peaks. Free the profiling model before loading the models being compared."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18f4b1a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "output = Path(\"results\")\n",
    "output.mkdir(exist_ok=True)\n",
    "free, _ = torch.cuda.mem_get_info()\n",
    "if free < 10 * 2**30:\n",
    "    raise RuntimeError(\"The tool-call update profile needs at least 10 GiB free on T4.\")\n",
    "profile_arm, batch = max(\n",
    "    ((name, batch) for name, schedule in schedules.items() for batch in schedule),\n",
    "    key=lambda item: max(len(sequence.input_ids) for sequence in item[1]) * len(item[1]),\n",
    ")\n",
    "probe = load_model(\"fp16\", trainable=True)\n",
    "try:\n",
    "    probe_metrics = adapter_train(\n",
    "        probe, [batch], sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "        learning_rate=2e-4, use_cuda=True,\n",
    "    )\n",
    "    profile = {\n",
    "        \"arm\": profile_arm, \"sequences\": len(batch),\n",
    "        \"max_sequence_tokens\": max(len(sequence.input_ids) for sequence in batch),\n",
    "        \"peak_reserved_gib\": torch.cuda.max_memory_reserved() / 2**30,\n",
    "        **probe_metrics,\n",
    "    }\n",
    "finally:\n",
    "    del probe\n",
    "    free_gpu()\n",
    "(output / \"14-t4-profile.json\").write_text(json.dumps(profile, indent=2), encoding=\"utf-8\")\n",
    "print(\"T4 profile\", json.dumps(profile, indent=2))\n",
    "if (profile[\"updates\"] != 1 or profile[\"seconds\"] > 45 or profile[\"peak_gib\"] > 9\n",
    "        or profile[\"peak_reserved_gib\"] > min(11, free / 2**30 - 1)):\n",
    "    raise RuntimeError(\"The update profile exceeded the registered T4 budget.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a777d76",
   "metadata": {},
   "source": [
    "## Run all three arms on the same cases\n",
    "\n",
    "Local rules parse the canonical request wording, including explicitly programmed tax\n",
    "and currency comparators. The rules score provides a fixture diagnostic. The prompted arm starts from\n",
    "the pinned instruct checkpoint. The two LoRA arms begin from\n",
    "the same checkpoint and use the same configuration. Every evaluation turn generates a fresh\n",
    "assistant decision. The runtime executes parsed calls and adds the actual response to the\n",
    "next input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf7b2302",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = {\"local_rules\": ledger_predictions(lambda case, tools: (rules_episode(case, tools), []), held_cases)}\n",
    "extraction, training, harness_diagnostic = {}, {}, {}\n",
    "print(\"Canonical rules\", json.dumps(ledger_summary(results[\"local_rules\"]), indent=2))\n",
    "\n",
    "def evaluate_arm(name, model):\n",
    "    model.eval()\n",
    "    results[name] = ledger_predictions(lambda case, tools: model_episode(model, tokenizer, case, tools), held_cases)\n",
    "    extraction[name] = predictions(model, tokenizer, regression_items, exemplar)\n",
    "    print(name, json.dumps(ledger_summary(results[name]), indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66f99d94",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = load_model(\"fp16\")\n",
    "try:\n",
    "    evaluate_arm(\"prompted\", model)\n",
    "finally:\n",
    "    del model\n",
    "    free_gpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccf1e292",
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in (\"raw\", \"verified\"):\n",
    "    model = load_model(\"fp16\", trainable=True)\n",
    "    try:\n",
    "        training[name] = adapter_train(\n",
    "            model, schedules[name], sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "            learning_rate=2e-4, use_cuda=True,\n",
    "        )\n",
    "        evaluate_arm(name, model)\n",
    "        if name == \"verified\":\n",
    "            wrapped = ledger_predictions(\n",
    "                lambda case, tools: model_episode(model, tokenizer, case, tools, wrap_result=True), held_cases\n",
    "            )\n",
    "            canonical = results[name]\n",
    "            pairs = list(zip(canonical, wrapped, strict=True))\n",
    "            assert all(before[\"case\"] == after[\"case\"] for before, after in pairs)\n",
    "            harness_diagnostic = {\n",
    "                \"gained_case_ids\": [after[\"case\"] for before, after in pairs if after[\"success\"] and not before[\"success\"]],\n",
    "                \"lost_case_ids\": [after[\"case\"] for before, after in pairs if before[\"success\"] and not after[\"success\"]],\n",
    "                \"baseline_contract\": \"ledger-v1\", \"mutated_contract\": \"ledger-v2-result-envelope\",\n",
    "                \"mutation\": \"Wrap tool observations in a result object before the model sees them.\",\n",
    "                \"canonical_pass_at_1\": ledger_summary(results[name]),\n",
    "                \"wrapped_pass_at_1\": ledger_summary(wrapped),\n",
    "                \"paired_changes\": paired_tool_changes(results[name], wrapped),\n",
    "                \"wrapped_episodes\": wrapped,\n",
    "            }\n",
    "            print(\"Harness result envelope\", json.dumps({\n",
    "                key: value for key, value in harness_diagnostic.items() if key != \"wrapped_episodes\"\n",
    "            }, indent=2))\n",
    "    finally:\n",
    "        del model\n",
    "        free_gpu()\n",
    "for name, info in training.items():\n",
    "    if info[\"updates\"] != len(schedules[name]):\n",
    "        raise RuntimeError(f\"Unexpected skipped update in the {name} branch.\")\n",
    "print(\"Fit details\", {name: {key: value for key, value in info.items() if key != \"losses\"}\n",
    "                      for name, info in training.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd53fce6",
   "metadata": {},
   "source": [
    "## Read the measurements\n",
    "\n",
    "Exact trajectory success requires correct ordered calls, valid execution and the correct\n",
    "evidence-linked final record. Inspect arguments when execution exceeds end-to-end success.\n",
    "Compare held-out tax and currency separately from the trained operations. Check that new behavior does\n",
    "not come with worse extraction on the same original task. These synthetic counts are small,\n",
    "especially the no-call rails, and estimates are descriptive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed31c829",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "summaries = {name: ledger_summary(rows) for name, rows in results.items()}\n",
    "changes = paired_tool_changes(results[\"raw\"], results[\"verified\"])\n",
    "print(\"Verified minus raw trajectory success by question\", json.dumps(changes, indent=2))\n",
    "receipt = {\n",
    "    \"model\": MODEL, \"revision\": REVISION, \"seed\": SEED, \"gpu\": torch.cuda.get_device_name(0),\n",
    "    \"versions\": {package: importlib.metadata.version(package) for package in (\"torch\", \"transformers\", \"peft\", \"accelerate\")},\n",
    "    \"tool_turn_limit\": TURN_LIMIT, \"generated_tokens_per_turn\": TOOL_OUTPUT_LIMIT,\n",
    "    \"train_tools\": TRAIN_TOOLS, \"held_tools\": HELD_TOOLS, \"training_case_audit\": training_audit,\n",
    "    \"teacher_audit_by_kind\": teacher_audit_by_kind, \"coverage_by_kind\": coverage,\n",
    "    \"t4_profile\": profile, \"opening_replays\": opening_replays,\n",
    "    \"training\": training, \"metrics\": summaries, \"paired_raw_to_verified\": changes,\n",
    "    \"episodes\": results, \"extraction_regression\": extraction,\n",
    "    \"harness_version_diagnostic\": harness_diagnostic,\n",
    "}\n",
    "(output / \"14-tool-call-results.json\").write_text(json.dumps(receipt, indent=2), encoding=\"utf-8\")\n",
    "print(\"Extraction exact by arm\", {\n",
    "    name: (sum(row[\"exact\"] for row in rows), len(rows)) for name, rows in extraction.items()\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b59e0a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(10, 4.5), layout=\"constrained\")\n",
    "colors = {\"prompted\": \"#486782\", \"raw\": \"#C68143\", \"verified\": \"#156B62\"}\n",
    "slices = list(summaries[\"prompted\"])\n",
    "for offset, name in enumerate(colors):\n",
    "    summary = summaries[name]\n",
    "    positions = [index + 0.23 * (offset - 1) for index in range(len(slices))]\n",
    "    ax.bar(positions, [summary[k][\"fraction\"][\"success\"] for k in slices], width=0.21, label=name, color=colors[name])\n",
    "ax.set_title(\"Exact trajectory success by decision surface\", loc=\"left\")\n",
    "ax.set_ylim(0, 1.03)\n",
    "ax.set_ylabel(\"Fraction of cases\")\n",
    "labels = [\"Seen tools\", \"Unseen tax\", \"Unseen currency\", \"Clarification\", \"No call\"]\n",
    "ax.set_xticks(range(len(slices)), [\n",
    "    f\"{label}\\n(n={summaries['prompted'][key]['n']})\" for label, key in zip(labels, slices, strict=True)\n",
    "])\n",
    "ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "ax.grid(axis=\"y\", alpha=0.2)\n",
    "ax.set_axisbelow(True)\n",
    "ax.legend(loc=\"upper left\", bbox_to_anchor=(1, 1), frameon=False)\n",
    "fig.savefig(output / \"trajectory-success.svg\")\n",
    "plt.show()\n",
    "\n",
    "sample = next((row for row in results[\"verified\"] if not row[\"success\"]), None)\n",
    "if sample:\n",
    "    print(json.dumps(sample, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f2dfa81",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Review one replay where the tool executed and the request still failed. Identify the first\n",
    "wrong argument, then follow its observed value into the final response.\n",
    "\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/14-train-on-verified-tool-calls)\n",
    "\n",
    "## Sources\n",
    "\n",
    "The multi-turn masking helper adapts code from the Apache-2.0\n",
    "[Together Post-Training Cookbook](https://github.com/togethercomputer/post-training-cookbook/tree/226e03ca225d6f13434047cf0f45ab3070a29801).\n",
    "All invoice records, tool schemas, corruptions and evaluation cases in this lesson are synthetic.\n",
    "The experiment uses the pinned [Qwen2.5-0.5B-Instruct weights](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct/tree/7ae557604adf67be50417f59c2c2f167def9a775)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
