{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "# 13 · Adapt a model to a domain\n",
    "\n",
    "    **Question.** Does a remittance workflow need new vocabulary, better evidence use or both?\n",
    "\n",
    "    Compare a fixed evidence prompt, continued language modelling, reading-comprehension SFT and RAFT-style SFT on the same held-out documents. Keep an invoice extraction regression check beside the new task."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-02",
   "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": "cell-03",
   "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": "cell-04",
   "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": "cell-05",
   "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": "cell-06",
   "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": "cell-07",
   "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": "cell-08",
   "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": "cell-09",
   "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": "cell-10",
   "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": "cell-11",
   "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": "code",
   "execution_count": null,
   "id": "cell-12",
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib_inline.backend_inline import set_matplotlib_formats\n",
    "set_matplotlib_formats(\"svg\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-13",
   "metadata": {},
   "source": [
    "## How do we keep retrieval fixed?\n",
    "\n",
    "    A versioned procedure creates synthetic vendor policies and packs with current, superseded or unrelated codes.\n",
    "    Every evaluated arm receives exactly the same packs. Measure abstention separately where the current code is absent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-14",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Synthetic retrieval packs with known evidence and controlled distractors.\"\"\"\n",
    "\n",
    "from dataclasses import dataclass\n",
    "import hashlib\n",
    "import json\n",
    "import random\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class EvidenceCase:\n",
    "    key: str\n",
    "    family: str\n",
    "    slice: str\n",
    "    question: str\n",
    "    documents: tuple[tuple[str, str], ...]\n",
    "    target: dict\n",
    "\n",
    "\n",
    "def evidence_case(invoice, *, missing=False, conflicts=True):\n",
    "    digest = hashlib.sha256(invoice.key.encode()).hexdigest()\n",
    "    correct_code = f\"REMIT-{digest[:6].upper()}\"\n",
    "    main_source = f\"P-{digest[12:18]}\"\n",
    "    obsolete_source = f\"P-{digest[18:24]}\"\n",
    "    alternate_source = f\"P-{digest[24:30]}\"\n",
    "    source_text = f\"Current authorised remittance code for {invoice.key} is {correct_code}.\"\n",
    "    outdated = f\"Superseded remittance entry for {invoice.key}. Old code REMIT-{digest[6:12].upper()}.\"\n",
    "    unrelated = f\"Current remittance code for another invoice is REMIT-{digest[30:36].upper()}.\"\n",
    "    docs = [(main_source, source_text)] if not missing else []\n",
    "    if conflicts or missing:\n",
    "        docs.extend([(obsolete_source, outdated), (alternate_source, unrelated)])\n",
    "    random.Random(digest).shuffle(docs)\n",
    "    target = {\"answer\": correct_code, \"source_id\": main_source} if not missing else {\"answer\": None, \"source_id\": None}\n",
    "    return EvidenceCase(invoice.key, invoice.family, \"missing\" if missing else \"present\",\n",
    "                        f\"What is the current authorised remittance code for {invoice.key}?\",\n",
    "                        tuple(docs), target)\n",
    "\n",
    "\n",
    "def evidence_text(case):\n",
    "    return case.question + \"\\n\" + \"\\n\".join(f\"[{key}] {message}\" for key, message in case.documents)\n",
    "\n",
    "\n",
    "def evidence_score(text, case):\n",
    "    def unique_object(pairs):\n",
    "        out = {}\n",
    "        for key, value in pairs:\n",
    "            if key in out:\n",
    "                raise ValueError(\"duplicate keys\")\n",
    "            out[key] = value\n",
    "        return out\n",
    "    try:\n",
    "        value = json.loads(text, object_pairs_hook=unique_object)\n",
    "    except (ValueError, TypeError):\n",
    "        return {\"valid\": False, \"answer\": False, \"evidence\": False, \"exact\": False, \"abstained\": False}\n",
    "    valid = isinstance(value, dict) and set(value) == {\"answer\", \"source_id\"} and all(\n",
    "        item is None or isinstance(item, str) for item in value.values()\n",
    "    )\n",
    "    if not valid:\n",
    "        return {\"valid\": False, \"answer\": False, \"evidence\": False, \"exact\": False, \"abstained\": False}\n",
    "    return {\"valid\": True, \"answer\": value[\"answer\"] == case.target[\"answer\"],\n",
    "            \"evidence\": value[\"source_id\"] == case.target[\"source_id\"],\n",
    "            \"exact\": value == case.target, \"abstained\": value[\"answer\"] is None and value[\"source_id\"] is None}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-15",
   "metadata": {},
   "outputs": [],
   "source": [
    "DOMAIN_INSTRUCTION = (\n",
    "    \"Use the current authorised remittance entry for the named invoice in the provided documents. \"\n",
    "    \"Ignore superseded entries and other invoices. Return JSON with answer and source_id. \"\n",
    "    \"Use null for both fields if the current source is absent.\"\n",
    ")\n",
    "train_docs=examples_for(\"train\",96)\n",
    "test_docs=examples_for(\"novel\",32)+examples_for(\"independent\",16)\n",
    "regression=examples_for(\"familiar\",24)\n",
    "train_clean=[]\n",
    "train_packed=[]\n",
    "for index,row in enumerate(train_docs):\n",
    "    missing=index%4==3\n",
    "    train_clean.append(evidence_case(row,missing=missing,conflicts=False))\n",
    "    train_packed.append(evidence_case(row,missing=missing,conflicts=True))\n",
    "assert [x.target for x in train_clean]==[x.target for x in train_packed]\n",
    "fixed=[evidence_case(row,missing=index%3==0) for index,row in enumerate(test_docs)]\n",
    "for dimension in (\"key\", \"family\", \"supplier\"):\n",
    "    cohorts = [{getattr(row, dimension) for row in rows} for rows in (train_docs, test_docs, regression)]\n",
    "    assert sum(map(len, cohorts)) == len(set.union(*cohorts)), dimension\n",
    "assert exemplar.key not in {row.key for row in [*test_docs, *regression]}\n",
    "opening = next(case for case in fixed if case.slice == \"present\")\n",
    "print(\"Opening evidence card:\")\n",
    "print(evidence_text(opening))\n",
    "print(canonical_json(opening.target))\n",
    "print(\"Fixed evidence questions:\",dict(Counter(case.slice for case in fixed)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-16",
   "metadata": {},
   "source": [
    "## How does task supervision differ from continued pretraining?\n",
    "\n",
    "    For continued pretraining, predict the tokens in the training policy text itself. In the two supervised arms, predict a structured answer while masking the prompt. The supervised arms use the same answers and update counts. One sees the relevant evidence during training, and the other also sees distractors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-17",
   "metadata": {},
   "outputs": [],
   "source": [
    "def domain_prompt(case):\n",
    "    return tokenizer.apply_chat_template(\n",
    "        [{\"role\":\"system\",\"content\":DOMAIN_INSTRUCTION},{\"role\":\"user\",\"content\":evidence_text(case)}],\n",
    "        tokenize=True,add_generation_prompt=True,\n",
    "    )\n",
    "\n",
    "def domain_row(case):\n",
    "    prefix=domain_prompt(case)\n",
    "    response=tokenizer.encode(canonical_json(case.target),add_special_tokens=False)+[tokenizer.eos_token_id]\n",
    "    return split_turns([Turn(prefix,response)])[0]\n",
    "\n",
    "def cpt_row(invoice):\n",
    "    case=evidence_case(invoice,conflicts=True)\n",
    "    raw_text=\"\\\\n\".join(content for _,content in case.documents)\n",
    "    sequence=tokenizer.encode(raw_text,add_special_tokens=False)+[tokenizer.eos_token_id]\n",
    "    if len(sequence)<2:\n",
    "        raise ValueError(\"Expected more than one token in a policy continuation.\")\n",
    "    return MaskedSequence(sequence,[1]*len(sequence))\n",
    "\n",
    "def evaluate_domain(model):\n",
    "    model.eval()\n",
    "    scores=[]\n",
    "    for case in fixed:\n",
    "        ids=torch.tensor([domain_prompt(case)],device=\"cuda\")\n",
    "        with torch.inference_mode():\n",
    "            tokens=model.generate(input_ids=ids,attention_mask=torch.ones_like(ids),\n",
    "                max_new_tokens=96,do_sample=False,temperature=None,top_k=None,top_p=None,\n",
    "                pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id,use_cache=True)\n",
    "        answer=tokenizer.decode(tokens[0,ids.shape[1]:],skip_special_tokens=True)\n",
    "        scores.append({\"key\":case.key,\"family\":case.family,\"slice\":case.slice,\"split\":case.slice,\n",
    "                       \"prediction\":answer,\"gold\":case.target,**evidence_score(answer,case)})\n",
    "    return scores\n",
    "\n",
    "def policy_eval_loss(model):\n",
    "    model.eval()\n",
    "    batcher=sft_objective(tokenizer.pad_token_id,\"cuda\")\n",
    "    with torch.inference_mode():\n",
    "        total,count=0.0,0\n",
    "        for row in test_docs:\n",
    "            loss,supervised,_=batcher(model,[cpt_row(row)])\n",
    "            total+=float(loss.detach().cpu())*supervised\n",
    "            count+=supervised\n",
    "    return total/count"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-18",
   "metadata": {},
   "source": [
    "## Which baseline should the trained arms beat?\n",
    "\n",
    "    The base model receives exactly the evidence text used by the adapted models. Track language-model loss on the held-out policy text and compare each checkpoint on the separate extraction task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-19",
   "metadata": {},
   "outputs": [],
   "source": [
    "base=load_model(\"fp16\")\n",
    "scores={\"prompted\":{\"evidence\":evaluate_domain(base),\"extraction\":predictions(base,tokenizer,regression,exemplar),\n",
    "                   \"evidence_text_nll\":policy_eval_loss(base)}}\n",
    "del base\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-20",
   "metadata": {},
   "source": [
    "## What does each adaptation change?\n",
    "\n",
    "    Each branch starts from the same revision. Report the number of supervised and input tokens instead of assuming the training budgets are identical in tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-21",
   "metadata": {},
   "outputs": [],
   "source": [
    "runs={}\n",
    "for name, encoded in (\n",
    "    (\"continued_pretraining\",[cpt_row(i) for i in train_docs]),\n",
    "    (\"reading_comprehension\",[domain_row(case) for case in train_clean]),\n",
    "    (\"raft_style\",[domain_row(case) for case in train_packed]),\n",
    "):\n",
    "    model=load_model(\"fp16\",trainable=True)\n",
    "    fit=adapter_train(model,make_schedule(encoded),sft_objective(tokenizer.pad_token_id,\"cuda\"),\n",
    "                      learning_rate=1e-4,use_cuda=True)\n",
    "    if fit[\"updates\"] != fit[\"attempted_updates\"]:\n",
    "        raise RuntimeError(f\"{name} skipped an update.\")\n",
    "    scores[name]={\"evidence\":evaluate_domain(model),\"extraction\":predictions(model,tokenizer,regression,exemplar),\n",
    "                  \"evidence_text_nll\":policy_eval_loss(model)}\n",
    "    runs[name]=fit\n",
    "    model.save_pretrained(Path(\"results\") / f\"13-{name}-adapter\")\n",
    "    del model\n",
    "    free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-22",
   "metadata": {},
   "source": [
    "## How should we read the evidence scores?\n",
    "\n",
    "    Exact success requires the right answer and supporting source. A correct guess with a wrong source is a grounding error.\n",
    "    A score improvement on present cases can coexist with worse abstention or extraction retention."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-23",
   "metadata": {},
   "outputs": [],
   "source": [
    "summary={}\n",
    "for method,result in scores.items():\n",
    "    items=result[\"evidence\"]\n",
    "    summary[method]={}\n",
    "    for label in (\"present\",\"missing\"):\n",
    "        chosen=[item for item in items if item[\"slice\"]==label]\n",
    "        summary[method][label]={\"n\":len(chosen),**{\n",
    "            metric:sum(i[metric] for i in chosen)/len(chosen)\n",
    "            for metric in (\"valid\",\"answer\",\"evidence\",\"exact\",\"abstained\")}}\n",
    "    summary[method][\"evidence_text_nll\"]=result[\"evidence_text_nll\"]\n",
    "print(json.dumps(summary,indent=2))\n",
    "extraction={name:result[\"extraction\"] for name,result in scores.items()}\n",
    "save_results(13,extraction,runs,[(\"prompted\",name) for name in runs],\n",
    "             domain_summary=summary,\n",
    "             domain_paired={\n",
    "                 name: {\n",
    "                     label: paired_family_interval(\n",
    "                         [row for row in scores[\"prompted\"][\"evidence\"] if row[\"slice\"] == label],\n",
    "                         [row for row in scores[name][\"evidence\"] if row[\"slice\"] == label],\n",
    "                     )\n",
    "                     for label in (\"present\", \"missing\")\n",
    "                 }\n",
    "                 for name in runs\n",
    "             },\n",
    "             test_pack_sha=hashlib.sha256(json.dumps([evidence_text(c) for c in fixed]).encode()).hexdigest())\n",
    "(Path(\"results\") / \"13-evidence-packs.json\").write_text(json.dumps([\n",
    "    {\"key\": c.key, \"family\": c.family, \"slice\": c.slice, \"question\": c.question,\n",
    "     \"documents\": c.documents, \"gold\": c.target} for c in fixed\n",
    "], indent=2), encoding=\"utf-8\")\n",
    "(Path(\"results\") / \"13-evidence-predictions.json\").write_text(json.dumps({\n",
    "    name: result[\"evidence\"] for name, result in scores.items()\n",
    "}, indent=2), encoding=\"utf-8\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-24",
   "metadata": {},
   "source": [
    "## Run it yourself\n",
    "\n",
    "    Fix the question IDs and change the distractor source. Compare grounded exact and abstention separately, and read examples where at least one branch changed its source ID.\n",
    "\n",
    "    [AdaptLLM](https://arxiv.org/abs/2309.09530) · [RAFT](https://arxiv.org/abs/2403.10131)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
