{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2347eb49",
   "metadata": {},
   "source": [
    "# Advanced LLM Fine Tuning · Lesson 03 · Audit preference pairs\n",
    "\n",
    "How much of Direct Preference Optimisation's value comes from the quality of its labels?\n",
    "\n",
    "You review records before they enter an accounts-payable queue. The synthetic remittance\n",
    "advice below carries a printed total that differs from its arithmetic sum. Which of two\n",
    "valid records should the model learn to prefer? Check the document, then compare that\n",
    "decision with what the same model can extract from scratch.\n",
    "\n",
    "**Run it.** Select a Tesla T4 and allow up to 30 minutes for setup, training and evaluation\n",
    "(planning estimate). [Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/2-compare-training-stages/03-audit-preference-pairs)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4e73d9c",
   "metadata": {},
   "source": [
    "## Runtime\n",
    "\n",
    "Select a Tesla T4 in Colab. Each branch runs in sequence. Model downloads use the\n",
    "public Hugging Face checkpoint, pinned by revision. The shared runtime can reuse\n",
    "its weight cache. The material below embeds the invoice fixtures and training code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4314f6b6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CompletedProcess(args=['/usr/bin/python3', '-m', 'pip', 'install', '-q', 'transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0'], returncode=0)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import subprocess\n",
    "import sys\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *['transformers==4.51.3', 'peft==0.15.2', 'accelerate==1.6.0']], check=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "16b31ea3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GPU: Tesla T4\n",
      "PyTorch: 2.14.1+cu130\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name(0):\n",
    "    raise RuntimeError(\"Select a Tesla T4 runtime in Colab before running this notebook.\")\n",
    "print(\"GPU:\", torch.cuda.get_device_name(0))\n",
    "print(\"PyTorch:\", torch.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1344a7f2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training packages: {'transformers': '4.51.3', 'peft': '0.15.2', 'accelerate': '1.6.0'}\n"
     ]
    }
   ],
   "source": [
    "from importlib.metadata import version\n",
    "\n",
    "expected_versions = {\"transformers\": \"4.51.3\", \"peft\": \"0.15.2\", \"accelerate\": \"1.6.0\"}\n",
    "versions = {name: version(name) for name in expected_versions}\n",
    "if versions != expected_versions:\n",
    "    raise RuntimeError(f\"Restart the kernel with the pinned training stack. Found {versions}.\")\n",
    "print(\"Training packages:\", versions)\n",
    "get_ipython().run_line_magic(\"config\", \"InlineBackend.figure_formats = ['svg']\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f53eab75",
   "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": 4,
   "id": "b707c8e0",
   "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": "9b38b311",
   "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": 5,
   "id": "a86bf23a",
   "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": "07079399",
   "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": 6,
   "id": "6218b729",
   "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": 7,
   "id": "064ac222",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Teaching evaluation counts: {'familiar': 96, 'novel': 96, 'independent': 48}\n",
      "One train-only prompt exemplar: SF-898991\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoTokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)\n",
    "if tokenizer.pad_token_id is None or tokenizer.eos_token_id is None:\n",
    "    raise ValueError(\"The pinned tokenizer must supply padding and completion markers.\")\n",
    "catalogue = make_catalog()\n",
    "exemplar, training_items, evaluation_items = lesson_prompts(catalogue)\n",
    "print(\"Teaching evaluation counts:\", dict(Counter(x.split for x in evaluation_items)))\n",
    "print(\"One train-only prompt exemplar:\", exemplar.key)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4896c82c",
   "metadata": {},
   "source": [
    "## What makes a valid counterexample?\n",
    "\n",
    "The verified response preserves the printed invoice. Each counterexample changes one\n",
    "scalar and retains the same JSON structure, key order and token count. The invoice\n",
    "scorer checks both branches of the pair. A corrupted number can still pass the schema.\n",
    "\n",
    "Training, the prompt exemplar and teaching evaluation use different invoices. The\n",
    "teaching layouts include familiar formats from unseen suppliers, unfamiliar formats,\n",
    "and an independent synthetic layout. The release set is reserved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "77d0ad18",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Length-matched preferences and a local response-masked DPO objective.\"\"\"\n",
    "\n",
    "import math\n",
    "from collections import Counter\n",
    "from copy import deepcopy\n",
    "from dataclasses import dataclass\n",
    "\n",
    "\n",
    "WORKED_INVOICE = \"SF-235300\"\n",
    "BETA = 0.1\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Preference:\n",
    "    key: str\n",
    "    chosen: MaskedSequence\n",
    "    rejected: MaskedSequence\n",
    "    changed_field: str\n",
    "    chosen_text: str\n",
    "    rejected_text: str\n",
    "\n",
    "\n",
    "def equally_long_pairs(tokenizer, rows, exemplar):\n",
    "    pairs, excluded = [], []\n",
    "    for invoice in rows:\n",
    "        gold = invoice_record(invoice)\n",
    "        gold_text = canonical_json(gold)\n",
    "        preferred = encode_supervision(tokenizer, invoice, gold_text, exemplar)\n",
    "        if not score_record(gold_text, invoice)[\"exact\"]:\n",
    "            raise ValueError(f\"Expected a valid exact record for {invoice.key}.\")\n",
    "\n",
    "        def errors():\n",
    "            for field in (\"total_minor\", \"tax_minor\", \"subtotal_minor\"):\n",
    "                value = gold[field]\n",
    "                if value is None:\n",
    "                    continue\n",
    "                for digit in range(10):\n",
    "                    changed = value // 10 * 10 + digit\n",
    "                    if changed != value and len(str(changed)) == len(str(value)):\n",
    "                        yield field, changed\n",
    "            for currency in (\"USD\", \"EUR\", \"GBP\", \"CAD\", \"CHF\"):\n",
    "                if currency != gold[\"currency\"]:\n",
    "                    yield \"currency\", currency\n",
    "\n",
    "        for field, value in errors():\n",
    "            corrupted = deepcopy(gold)\n",
    "            corrupted[field] = value\n",
    "            corrupted_text = canonical_json(corrupted)\n",
    "            dispreferred = encode_supervision(tokenizer, invoice, corrupted_text, exemplar)\n",
    "            if len(preferred.input_ids) != len(dispreferred.input_ids):\n",
    "                continue\n",
    "            check = score_record(corrupted_text, invoice)\n",
    "            wrong_fields = {key for key, correct in check[\"field_correct\"].items() if not correct}\n",
    "            if not check[\"valid\"] or wrong_fields != {field} or check[\"row_f1\"] != 1:\n",
    "                raise ValueError(\"A rejected candidate must change exactly one verified scalar.\")\n",
    "            count = sum(preferred.completion_mask)\n",
    "            prompt_tokens = len(preferred.input_ids) - count\n",
    "            if not (\n",
    "                prompt_tokens > 0 and count > 1\n",
    "                and preferred.completion_mask == dispreferred.completion_mask\n",
    "                and preferred.completion_mask == [0] * prompt_tokens + [1] * count\n",
    "                and preferred.input_ids[:prompt_tokens] == dispreferred.input_ids[:prompt_tokens]\n",
    "                and preferred.input_ids[prompt_tokens:] != dispreferred.input_ids[prompt_tokens:]\n",
    "                and preferred.input_ids[-1] == dispreferred.input_ids[-1] == tokenizer.eos_token_id\n",
    "            ):\n",
    "                raise ValueError(\"Both candidates need the same prompt and causal target boundaries.\")\n",
    "            pairs.append(Preference(invoice.key, preferred, dispreferred, field, gold_text, corrupted_text))\n",
    "            break\n",
    "        else:\n",
    "            excluded.append(invoice.key)\n",
    "    return pairs, excluded\n",
    "\n",
    "\n",
    "def fingerprint(payload):\n",
    "    return hashlib.sha256(canonical_json(payload).encode(\"utf-8\")).hexdigest()\n",
    "\n",
    "\n",
    "def split_manifest(exemplar, anchor_items, pair_items, evaluation_items):\n",
    "    cohorts = {\n",
    "        \"exemplar\": [exemplar], \"sft_anchor\": anchor_items,\n",
    "        \"dpo_candidates\": pair_items, \"held_out\": evaluation_items,\n",
    "    }\n",
    "    training = [exemplar, *anchor_items, *pair_items]\n",
    "    expected_splits = (\"familiar\", \"novel\", \"independent\")\n",
    "    if any(row.split != \"train\" for row in training):\n",
    "        raise ValueError(\"Training or prompt example leaks a held-out source.\")\n",
    "    if dict(Counter(row.split for row in evaluation_items)) != {\n",
    "        split: SPLIT_SIZES[split] for split in expected_splits\n",
    "    }:\n",
    "        raise ValueError(\"The fixed teaching roster changed.\")\n",
    "    rows = [*training, *evaluation_items]\n",
    "    if len({row.key for row in rows}) != len(rows) or len({invoice_text(row) for row in rows}) != len(rows):\n",
    "        raise ValueError(\"An invoice key or visible source is repeated across cohorts.\")\n",
    "    for attr in (\"family\", \"supplier\"):\n",
    "        if {getattr(row, attr) for row in training} & {getattr(row, attr) for row in evaluation_items}:\n",
    "            raise ValueError(f\"Teaching evaluation shares a {attr} with training.\")\n",
    "    manifest = {\n",
    "        name: [{\n",
    "            \"key\": row.key, \"split\": row.split, \"family\": row.family, \"layout\": row.layout,\n",
    "            \"input_sha256\": fingerprint(invoice_text(row)), \"gold_sha256\": fingerprint(invoice_record(row)),\n",
    "        } for row in group]\n",
    "        for name, group in cohorts.items()\n",
    "    }\n",
    "    return {\"sha256\": fingerprint(manifest), \"cohorts\": manifest}\n",
    "\n",
    "\n",
    "def pair_audit(rows, pairs, excluded, flipped):\n",
    "    by_key = {pair.key: pair for pair in pairs}\n",
    "    if len(by_key) != len(pairs) or len(set(excluded)) != len(excluded):\n",
    "        raise ValueError(\"An invoice can enter the pair audit only once.\")\n",
    "    if set(by_key) & set(excluded) or set(by_key) | set(excluded) != {row.key for row in rows}:\n",
    "        raise ValueError(\"The pair audit must account for all and only the supplied invoices.\")\n",
    "    records = []\n",
    "    for row in rows:\n",
    "        record = {\"key\": row.key, \"family\": row.family, \"split\": row.split, \"layout\": row.layout}\n",
    "        if row.key in by_key:\n",
    "            pair = by_key[row.key]\n",
    "            response_tokens = sum(pair.chosen.completion_mask)\n",
    "            records.append({\n",
    "                **record, \"status\": \"accepted\", \"changed_field\": pair.changed_field,\n",
    "                \"flipped_in_noisy_arm\": row.key in flipped, \"input\": invoice_text(row),\n",
    "                \"verified\": pair.chosen_text, \"counterexample\": pair.rejected_text,\n",
    "                \"prompt_tokens\": len(pair.chosen.input_ids) - response_tokens,\n",
    "                \"verified_response_tokens\": response_tokens,\n",
    "                \"counterexample_response_tokens\": sum(pair.rejected.completion_mask),\n",
    "                \"token_pair_sha256\": fingerprint([pair.chosen.input_ids, pair.rejected.input_ids,\n",
    "                                                  pair.chosen.completion_mask]),\n",
    "            })\n",
    "        else:\n",
    "            records.append({**record, \"status\": \"excluded\", \"reason\": \"no valid length-matched mutation\"})\n",
    "    return records\n",
    "\n",
    "\n",
    "def response_logprobs(logits, targets):\n",
    "    \"\"\"Gather aligned response targets, with no direct prompt or padding loss.\"\"\"\n",
    "    active = targets.ne(-100)\n",
    "    counts = active.sum(dim=1).tolist()\n",
    "    if not all(counts):\n",
    "        raise ValueError(\"Every sequence needs at least one response target.\")\n",
    "    values = logits[active].float()\n",
    "    selected = targets[active]\n",
    "    logprobs = values.gather(dim=1, index=selected[:, None]).squeeze(1) - values.logsumexp(dim=1)\n",
    "    return logprobs.split(counts)\n",
    "\n",
    "\n",
    "def policy_slots(model, pairs, pad_id, device):\n",
    "    \"\"\"Project only the Qwen2 logit positions that can hold a response target.\"\"\"\n",
    "    sequences = [seq for pair in pairs for seq in (pair.chosen, pair.rejected)]\n",
    "    batch = right_pad(sequences, pad_id, device)\n",
    "    # The last prompt position predicts the first response token.\n",
    "    start = min(len(seq.input_ids) - sum(seq.completion_mask) for seq in sequences) - 1\n",
    "    last = batch[\"input_ids\"].shape[1] - 1\n",
    "    keep = torch.arange(start, last, device=device)\n",
    "    outputs = model(input_ids=batch[\"input_ids\"], attention_mask=batch[\"attention_mask\"],\n",
    "                    logits_to_keep=keep, use_cache=False)\n",
    "    slots = response_logprobs(outputs.logits, batch[\"labels\"][:, start + 1:])\n",
    "    return slots, sum(slot.numel() for slot in slots), int(batch[\"attention_mask\"].sum().item())\n",
    "\n",
    "\n",
    "def shifted_gradient_evidence():\n",
    "    \"\"\"Differentiate a miniature example with a prompt, response, EOS and padding.\"\"\"\n",
    "    labels = torch.tensor([[-100, -100, -100, 2, 3, 1, -100]])\n",
    "    logits = torch.zeros(1, labels.shape[1], 4, requires_grad=True)\n",
    "    slots = response_logprobs(logits[:, :-1, :], labels[:, 1:])\n",
    "    (-slots[0].sum()).backward()\n",
    "    causal_targets = labels[0, 1:].ne(-100).tolist()\n",
    "    nonzero = logits.grad[0].abs().sum(dim=-1).ne(0).tolist()\n",
    "    if nonzero != causal_targets + [False]:\n",
    "        raise RuntimeError(\"Direct logit gradients must coincide with shifted response targets.\")\n",
    "    return {\n",
    "        \"roles_by_input_position\": [\"prompt\", \"prompt\", \"prompt\", \"response\", \"response\", \"EOS\", \"padding\"],\n",
    "        \"labels_by_input_position\": labels[0].tolist(),\n",
    "        \"nonzero_logit_gradient_by_position\": nonzero,\n",
    "    }\n",
    "\n",
    "\n",
    "def reference_logps(model, pairs, pad_id, device):\n",
    "    model.eval()\n",
    "    result = {}\n",
    "    with torch.inference_mode(), torch.autocast(device_type=\"cuda\", dtype=torch.float16, enabled=device == \"cuda\"):\n",
    "        for batch in make_schedule(pairs):\n",
    "            slots, _, _ = policy_slots(model, batch, pad_id, device)\n",
    "            sums = [float(slot.sum()) for slot in slots]\n",
    "            for index, pair in enumerate(batch):\n",
    "                result[pair.key] = (sums[2 * index], sums[2 * index + 1])\n",
    "    if len(result) != len(pairs) or any(not math.isfinite(value) for pair in result.values() for value in pair):\n",
    "        raise ValueError(\"Each pair must have two finite log probabilities.\")\n",
    "    return result\n",
    "\n",
    "\n",
    "def dpo_objective(ref_sums, flipped_keys, pad_id, device, *, beta=BETA):\n",
    "    def loss_for(model, pairs):\n",
    "        slots, count, unpadded = policy_slots(model, pairs, pad_id, device)\n",
    "        ordered_slots, references = [], []\n",
    "        for index, pair in enumerate(pairs):\n",
    "            left, right = 2 * index, 2 * index + 1\n",
    "            ref_chosen, ref_rejected = ref_sums[pair.key]\n",
    "            if pair.key in flipped_keys:\n",
    "                left, right = right, left\n",
    "                ref_chosen, ref_rejected = ref_rejected, ref_chosen\n",
    "            ordered_slots.extend((slots[left], slots[right]))\n",
    "            references.extend((ref_chosen, ref_rejected))\n",
    "        # All remaining positions already predict the response.\n",
    "        masks = [[1.0] * slot.numel() for slot in ordered_slots]\n",
    "        return make_dpo_loss(references, masks, beta=beta)(ordered_slots), count, unpadded\n",
    "    return loss_for\n",
    "\n",
    "\n",
    "def verify_initial_dpo(model, objective, first_batch, device):\n",
    "    model.eval()\n",
    "    with torch.inference_mode(), torch.autocast(device_type=\"cuda\", dtype=torch.float16, enabled=device == \"cuda\"):\n",
    "        initial_loss = float(objective(model, first_batch)[0])\n",
    "    if not math.isclose(initial_loss, math.log(2), abs_tol=1e-2):\n",
    "        raise RuntimeError(\"The initial policy does not match its frozen SFT reference.\")\n",
    "    return initial_loss\n",
    "\n",
    "\n",
    "def assert_matched_exposure(training, schedule):\n",
    "    budget = {\n",
    "        \"attempted_updates\": len(schedule),\n",
    "        \"updates\": len(schedule),\n",
    "        \"supervised_response_tokens\": sum(\n",
    "            sum(seq.completion_mask) for batch in schedule for pair in batch for seq in (pair.chosen, pair.rejected)\n",
    "        ),\n",
    "        \"unpadded_input_tokens\": sum(\n",
    "            len(seq.input_ids) for batch in schedule for pair in batch for seq in (pair.chosen, pair.rejected)\n",
    "        ),\n",
    "    }\n",
    "    for name in (\"Checked DPO\", \"Flipped-label DPO\"):\n",
    "        for metric, expected in budget.items():\n",
    "            if training[name][metric] != expected:\n",
    "                raise RuntimeError(f\"{name} differs from the shared schedule on {metric}.\")\n",
    "    if training[\"Checked DPO\"][\"trainable_parameters\"] != training[\"Flipped-label DPO\"][\"trainable_parameters\"]:\n",
    "        raise RuntimeError(\"DPO policies have different trainable parameter counts.\")\n",
    "    return budget\n",
    "\n",
    "\n",
    "def measure_preferences(items, pair_logps, comparisons):\n",
    "    expected_keys = {item.key for item in items}\n",
    "    records = {}\n",
    "    for name, logps in pair_logps.items():\n",
    "        if set(logps) != expected_keys or len(logps) != len(items):\n",
    "            raise ValueError(f\"{name} must rank the same held-out pairs.\")\n",
    "        records[name] = [{\n",
    "            \"key\": item.key, \"split\": item.split, \"family\": item.family,\n",
    "            \"verified_logp\": logps[item.key][0], \"counterexample_logp\": logps[item.key][1],\n",
    "            \"margin\": logps[item.key][0] - logps[item.key][1],\n",
    "            \"winner\": (\"verified\" if logps[item.key][0] > logps[item.key][1] else\n",
    "                       \"counterexample\" if logps[item.key][0] < logps[item.key][1] else \"tie\"),\n",
    "        } for item in items]\n",
    "    slices = [(\"all\", expected_keys)] + [\n",
    "        (split, {item.key for item in items if item.split == split})\n",
    "        for split in (\"familiar\", \"novel\", \"independent\")\n",
    "    ]\n",
    "    summary = {}\n",
    "    for label, keys in slices:\n",
    "        if not keys:\n",
    "            raise ValueError(f\"Missing held-out matched pairs for {label}.\")\n",
    "        rankings = {\n",
    "            name: [{**row, \"exact\": row[\"winner\"] == \"verified\"} for row in rows if row[\"key\"] in keys]\n",
    "            for name, rows in records.items()\n",
    "        }\n",
    "        summary[label] = {\n",
    "            \"n\": len(keys),\n",
    "            \"arms\": {name: dict(Counter(row[\"winner\"] for row in rows)) for name, rows in rankings.items()},\n",
    "            \"paired_family_intervals\": {\n",
    "                f\"{candidate} minus {baseline}\": paired_family_interval(rankings[baseline], rankings[candidate])\n",
    "                for baseline, candidate in comparisons\n",
    "            },\n",
    "        }\n",
    "    return records, summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6d2a27fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "training {('accepted', 'total_minor'): 192}\n",
      "held_out {('accepted', 'total_minor'): 228, ('accepted', 'subtotal_minor'): 12}\n",
      "Excluded training and held-out pairs: 0 0\n",
      "Flipped labels: 48\n",
      "Split manifest SHA-256: 82efcac13359d5eeb3b1dc3bdcc74466e972aa7d8d004148e459f55c9a0738c2\n",
      "Worked remittance and length-matched candidates:\n",
      "{\n",
      "  \"key\": \"SF-235300\",\n",
      "  \"family\": \"novel-01\",\n",
      "  \"split\": \"novel\",\n",
      "  \"layout\": \"remittance\",\n",
      "  \"status\": \"accepted\",\n",
      "  \"changed_field\": \"total_minor\",\n",
      "  \"flipped_in_noisy_arm\": false,\n",
      "  \"input\": \"Remittance advice for SF-235300 (GBP)\\nSample Supplier 3219 / Document issued 2025-02-20\\nPay this amount 1,243.11\\n8 x Rack inspection @ 137.40 per unit\\nNet charges 1,099.20 / Tax 142.90\",\n",
      "  \"verified\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[{\\\"description\\\":\\\"Rack inspection\\\",\\\"quantity\\\":8,\\\"unit_minor\\\":13740}],\\\"subtotal_minor\\\":109920,\\\"tax_minor\\\":14290,\\\"total_minor\\\":124311}\",\n",
      "  \"counterexample\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[{\\\"description\\\":\\\"Rack inspection\\\",\\\"quantity\\\":8,\\\"unit_minor\\\":13740}],\\\"subtotal_minor\\\":109920,\\\"tax_minor\\\":14290,\\\"total_minor\\\":124310}\",\n",
      "  \"prompt_tokens\": 396,\n",
      "  \"verified_response_tokens\": 94,\n",
      "  \"counterexample_response_tokens\": 94,\n",
      "  \"token_pair_sha256\": \"4888379b6cecfc8f952f8c932736b5576c6829e3bbb730da292eb87a6f2cd722\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "ANCHOR_ROWS, CANDIDATE_ROWS = 192, 192\n",
    "NOISE_FRACTION = 0.25\n",
    "ANCHOR_LR, DPO_LR = 2e-4, 1e-5\n",
    "DEVICE = \"cuda\"\n",
    "RESULTS = Path(\"results\")\n",
    "RESULTS.mkdir(exist_ok=True)\n",
    "\n",
    "anchor_items = training_items[:ANCHOR_ROWS]\n",
    "pair_items = training_items[ANCHOR_ROWS:ANCHOR_ROWS + CANDIDATE_ROWS]\n",
    "manifest = split_manifest(exemplar, anchor_items, pair_items, evaluation_items)\n",
    "pairs, excluded_train = equally_long_pairs(tokenizer, pair_items, exemplar)\n",
    "held_pairs, excluded_held = equally_long_pairs(tokenizer, evaluation_items, exemplar)\n",
    "if len(anchor_items) != ANCHOR_ROWS or len(pair_items) != CANDIDATE_ROWS or len(pairs) < 4 or not held_pairs:\n",
    "    raise ValueError(\"The lesson requires the fixed fit cohorts and a nonempty held-out pair set.\")\n",
    "held_keys = {pair.key for pair in held_pairs}\n",
    "held_pair_items = [row for row in evaluation_items if row.key in held_keys]\n",
    "flipped = set(random.Random(SEED).sample(\n",
    "    sorted(pair.key for pair in pairs), int(len(pairs) * NOISE_FRACTION),\n",
    "))\n",
    "audits = {\n",
    "    \"training\": pair_audit(pair_items, pairs, excluded_train, flipped),\n",
    "    \"held_out\": pair_audit(evaluation_items, held_pairs, excluded_held, set()),\n",
    "}\n",
    "worked = next(row for row in audits[\"held_out\"] if row[\"key\"] == WORKED_INVOICE)\n",
    "if worked[\"status\"] != \"accepted\" or worked[\"changed_field\"] != \"total_minor\":\n",
    "    raise ValueError(\"The worked remittance advice must retain its matched total-field pair.\")\n",
    "(RESULTS / \"03-split-manifest.json\").write_text(json.dumps(manifest, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "(RESULTS / \"03-pair-audit.json\").write_text(json.dumps(audits, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "for name, rows in audits.items():\n",
    "    print(name, dict(Counter((row[\"status\"], row.get(\"changed_field\", row.get(\"reason\"))) for row in rows)))\n",
    "print(\"Excluded training and held-out pairs:\", len(excluded_train), len(excluded_held))\n",
    "print(\"Flipped labels:\", len(flipped))\n",
    "print(\"Split manifest SHA-256:\", manifest[\"sha256\"])\n",
    "print(\"Worked remittance and length-matched candidates:\")\n",
    "print(json.dumps(worked, indent=2, ensure_ascii=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff328c30",
   "metadata": {},
   "source": [
    "## Which positions receive a direct loss?\n",
    "\n",
    "Each output logit predicts the next token. The first response target therefore\n",
    "uses the logit at the last prompt position. Predicting the earlier prompt tokens\n",
    "and padding adds no direct loss. The prompt still conditions the response; this\n",
    "mask does not block gradients through the prompt as context.\n",
    "\n",
    "The compact example below differentiates the selected log probabilities to show the\n",
    "shift. The Qwen forward pass limits vocabulary projection to the response-bearing span."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1fd1323b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"roles_by_input_position\": [\n",
      "    \"prompt\",\n",
      "    \"prompt\",\n",
      "    \"prompt\",\n",
      "    \"response\",\n",
      "    \"response\",\n",
      "    \"EOS\",\n",
      "    \"padding\"\n",
      "  ],\n",
      "  \"labels_by_input_position\": [\n",
      "    -100,\n",
      "    -100,\n",
      "    -100,\n",
      "    2,\n",
      "    3,\n",
      "    1,\n",
      "    -100\n",
      "  ],\n",
      "  \"nonzero_logit_gradient_by_position\": [\n",
      "    false,\n",
      "    false,\n",
      "    true,\n",
      "    true,\n",
      "    true,\n",
      "    false,\n",
      "    false\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "mask_evidence = shifted_gradient_evidence()\n",
    "print(json.dumps(mask_evidence, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fd17007",
   "metadata": {},
   "source": [
    "## Why start both branches from one adapter?\n",
    "\n",
    "First generate the prompted baseline, then fit the shared supervised adapter.\n",
    "Freeze its weights and cache the two reference log-probability sums for each\n",
    "training pair. Both DPO branches reload that adapter and start fresh optimisers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b180cb8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "scores = {\"Register-layout rules\": rules_predictions(evaluation_items)}\n",
    "training, evaluation_seconds = {}, {}\n",
    "anchor = load_model(\"fp16\")\n",
    "started = time.perf_counter()\n",
    "scores[\"FP16 prompted\"] = predictions(anchor, tokenizer, evaluation_items, exemplar)\n",
    "evaluation_seconds[\"FP16 prompted\"] = time.perf_counter() - started\n",
    "del anchor\n",
    "free_gpu()\n",
    "\n",
    "anchor = load_model(\"fp16\", trainable=True)\n",
    "anchor_schedule = make_schedule([\n",
    "    encode_supervision(tokenizer, item, canonical_json(invoice_record(item)), exemplar)\n",
    "    for item in anchor_items\n",
    "])\n",
    "training[\"SFT anchor\"] = adapter_train(\n",
    "    anchor, anchor_schedule, sft_objective(tokenizer.pad_token_id, DEVICE),\n",
    "    learning_rate=ANCHOR_LR, use_cuda=DEVICE == \"cuda\",\n",
    ")\n",
    "if training[\"SFT anchor\"][\"updates\"] != len(anchor_schedule):\n",
    "    raise RuntimeError(\"The common SFT anchor missed an optimiser update.\")\n",
    "anchor_path = RESULTS / \"03-sft-anchor\"\n",
    "anchor.save_pretrained(anchor_path)\n",
    "anchor_weights = anchor_path / \"adapter_model.safetensors\"\n",
    "anchor_digest = hashlib.sha256(anchor_weights.read_bytes()).hexdigest()\n",
    "anchor.requires_grad_(False)\n",
    "started = time.perf_counter()\n",
    "scores[\"SFT anchor\"] = predictions(anchor, tokenizer, evaluation_items, exemplar)\n",
    "evaluation_seconds[\"SFT anchor\"] = time.perf_counter() - started\n",
    "started = time.perf_counter()\n",
    "references = reference_logps(anchor, pairs, tokenizer.pad_token_id, DEVICE)\n",
    "held_logps = {\"SFT anchor\": reference_logps(anchor, held_pairs, tokenizer.pad_token_id, DEVICE)}\n",
    "reference_seconds = time.perf_counter() - started\n",
    "reference_digest = fingerprint(references)\n",
    "(RESULTS / \"03-reference-logps.json\").write_text(\n",
    "    json.dumps({\"anchor_sha256\": anchor_digest, \"sha256\": reference_digest,\n",
    "                \"candidate_order\": [\"verified\", \"counterexample\"], \"training_logps\": references}, indent=2) + \"\\n\",\n",
    "    encoding=\"utf-8\",\n",
    ")\n",
    "del anchor\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f5d0010",
   "metadata": {},
   "source": [
    "## What changes when a preference label flips?\n",
    "\n",
    "The loss compares the policy's chosen-minus-rejected log-probability margin with\n",
    "the same margin under the frozen reference. Flip the signed ordering of both\n",
    "quantities together. The inputs, response masks, update order and independent\n",
    "evaluation labels stay fixed. A freshly reloaded branch should begin at the loss\n",
    "expected when the policy margin equals the reference margin."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f82354bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "schedule = make_schedule(pairs)\n",
    "schedule_sha256 = fingerprint([[pair.key for pair in batch] for batch in schedule])\n",
    "initial_losses, adapters = {}, {}\n",
    "for name, noise in ((\"Checked DPO\", set()), (\"Flipped-label DPO\", flipped)):\n",
    "    if hashlib.sha256(anchor_weights.read_bytes()).hexdigest() != anchor_digest:\n",
    "        raise RuntimeError(\"The shared anchor changed after reference scoring.\")\n",
    "    policy = load_model(\"fp16\", adapter=anchor_path, trainable=True)\n",
    "    objective = dpo_objective(references, noise, tokenizer.pad_token_id, DEVICE)\n",
    "    initial_losses[name] = verify_initial_dpo(policy, objective, schedule[0], DEVICE)\n",
    "    training[name] = adapter_train(\n",
    "        policy, schedule, objective, learning_rate=DPO_LR, use_cuda=DEVICE == \"cuda\",\n",
    "    )\n",
    "    started = time.perf_counter()\n",
    "    scores[name] = predictions(policy, tokenizer, evaluation_items, exemplar)\n",
    "    held_logps[name] = reference_logps(policy, held_pairs, tokenizer.pad_token_id, DEVICE)\n",
    "    evaluation_seconds[name] = time.perf_counter() - started\n",
    "    adapter_path = RESULTS / (\"03-\" + name.lower().replace(\" \", \"-\"))\n",
    "    policy.save_pretrained(adapter_path)\n",
    "    adapters[name] = {\n",
    "        \"parent_sha256\": anchor_digest, \"reference_sha256\": reference_digest, \"schedule_sha256\": schedule_sha256,\n",
    "        \"adapter_sha256\": hashlib.sha256((adapter_path / \"adapter_model.safetensors\").read_bytes()).hexdigest(),\n",
    "    }\n",
    "    del policy\n",
    "    free_gpu()\n",
    "matched_exposure = assert_matched_exposure(training, schedule)\n",
    "if fingerprint(references) != reference_digest:\n",
    "    raise RuntimeError(\"The frozen reference values changed.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50f8a804",
   "metadata": {},
   "source": [
    "## Does a better ranking produce a better invoice?\n",
    "\n",
    "Ranking judges a fixed pair of supplied candidates. Greedy generation instead gives\n",
    "the model the invoice prompt and scores the full record it returns. The paired\n",
    "comparison resamples families, and the report retains ties and completion outcomes.\n",
    "Check the raw output for the opening invoice before drawing a conclusion from totals."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0a833400",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"model_id\": \"Qwen/Qwen2.5-0.5B-Instruct\",\n",
      "  \"model_revision\": \"7ae557604adf67be50417f59c2c2f167def9a775\",\n",
      "  \"seed\": 42,\n",
      "  \"versions\": {\n",
      "    \"torch\": \"2.14.1+cu130\",\n",
      "    \"transformers\": \"4.51.3\",\n",
      "    \"peft\": \"0.15.2\"\n",
      "  },\n",
      "  \"hardware\": \"Tesla T4\",\n",
      "  \"held_out_roster_sha256\": \"08d508621745254e22a48017d6c826fb58310adec0604290fbe8f07e4db1af55\",\n",
      "  \"scores\": {\n",
      "    \"Register-layout rules\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.25,\n",
      "        \"exact\": 0.25,\n",
      "        \"completed\": 0.25,\n",
      "        \"fields\": 0.25,\n",
      "        \"row_f1\": 0.25\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.0,\n",
      "        \"exact\": 0.0,\n",
      "        \"completed\": 0.0,\n",
      "        \"fields\": 0.0,\n",
      "        \"row_f1\": 0.0\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.0,\n",
      "        \"exact\": 0.0,\n",
      "        \"completed\": 0.0,\n",
      "        \"fields\": 0.0,\n",
      "        \"row_f1\": 0.0\n",
      "      }\n",
      "    },\n",
      "    \"FP16 prompted\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.5833333333333334,\n",
      "        \"exact\": 0.14583333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.5163690476190477,\n",
      "        \"row_f1\": 0.359375\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.8229166666666666,\n",
      "        \"exact\": 0.010416666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.7410714285714286,\n",
      "        \"row_f1\": 0.04965277777777778\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.75,\n",
      "        \"exact\": 0.125,\n",
      "        \"completed\": 0.9791666666666666,\n",
      "        \"fields\": 0.6309523809523809,\n",
      "        \"row_f1\": 0.4722222222222222\n",
      "      }\n",
      "    },\n",
      "    \"SFT anchor\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 1.0,\n",
      "        \"exact\": 0.9895833333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9985119047619048,\n",
      "        \"row_f1\": 1.0\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9583333333333334,\n",
      "        \"exact\": 0.5625,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9136904761904762,\n",
      "        \"row_f1\": 0.71875\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.9375,\n",
      "        \"exact\": 0.6041666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.8630952380952381,\n",
      "        \"row_f1\": 0.9375\n",
      "      }\n",
      "    },\n",
      "    \"Checked DPO\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9895833333333334,\n",
      "        \"exact\": 0.9791666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9895833333333334,\n",
      "        \"row_f1\": 0.9861111111111112\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9479166666666666,\n",
      "        \"exact\": 0.5208333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9047619047619048,\n",
      "        \"row_f1\": 0.6875\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.8958333333333334,\n",
      "        \"exact\": 0.25,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.7142857142857143,\n",
      "        \"row_f1\": 0.8958333333333334\n",
      "      }\n",
      "    },\n",
      "    \"Flipped-label DPO\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9895833333333334,\n",
      "        \"exact\": 0.9791666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9895833333333334,\n",
      "        \"row_f1\": 0.984375\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9583333333333334,\n",
      "        \"exact\": 0.5729166666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9151785714285714,\n",
      "        \"row_f1\": 0.71875\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.9375,\n",
      "        \"exact\": 0.4583333333333333,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.8065476190476191,\n",
      "        \"row_f1\": 0.9375\n",
      "      }\n",
      "    }\n",
      "  },\n",
      "  \"paired_family_intervals\": {\n",
      "    \"Checked DPO minus SFT anchor\": {\n",
      "      \"familiar\": [\n",
      "        -0.03125,\n",
      "        0.0\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        -0.07291666666666667,\n",
      "        -0.010416666666666666\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        -0.5208333333333334,\n",
      "        -0.16666666666666666\n",
      "      ]\n",
      "    },\n",
      "    \"Flipped-label DPO minus SFT anchor\": {\n",
      "      \"familiar\": [\n",
      "        -0.03125,\n",
      "        0.0\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        -0.020833333333333332,\n",
      "        0.041666666666666664\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        -0.20833333333333334,\n",
      "        -0.08333333333333333\n",
      "      ]\n",
      "    },\n",
      "    \"Checked DPO minus Flipped-label DPO\": {\n",
      "      \"familiar\": [\n",
      "        0.0,\n",
      "        0.0\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        -0.09375,\n",
      "        -0.010416666666666666\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        -0.3541666666666667,\n",
      "        -0.0625\n",
      "      ]\n",
      "    }\n",
      "  },\n",
      "  \"diagnostics\": {\n",
      "    \"catalogue_version\": \"course-invoice-v1\",\n",
      "    \"packages\": {\n",
      "      \"transformers\": \"4.51.3\",\n",
      "      \"peft\": \"0.15.2\",\n",
      "      \"accelerate\": \"1.6.0\"\n",
      "    },\n",
      "    \"anchor_sha256\": \"dee36879595ac3a447cfcea10cc9e93bdd162e638c8af4df769228168c81ac21\",\n",
      "    \"reference_sha256\": \"98f30f5944ef7e086cb0848f4263c026feee9a1dea5cfcfd7714b2ffc54d1a86\",\n",
      "    \"split_sha256\": \"82efcac13359d5eeb3b1dc3bdcc74466e972aa7d8d004148e459f55c9a0738c2\",\n",
      "    \"pair_audit_sha256\": \"606339664c77fa2fb2b9b72d33596e2faf48c520e2678d69b208664211408402\",\n",
      "    \"schedule_sha256\": \"5f667dff4213cd39f19f87d6709a158e2c99c7b776aff3e1d6b14eade6d30d55\",\n",
      "    \"adapters\": {\n",
      "      \"Checked DPO\": {\n",
      "        \"parent_sha256\": \"dee36879595ac3a447cfcea10cc9e93bdd162e638c8af4df769228168c81ac21\",\n",
      "        \"reference_sha256\": \"98f30f5944ef7e086cb0848f4263c026feee9a1dea5cfcfd7714b2ffc54d1a86\",\n",
      "        \"schedule_sha256\": \"5f667dff4213cd39f19f87d6709a158e2c99c7b776aff3e1d6b14eade6d30d55\",\n",
      "        \"adapter_sha256\": \"e570a97085e9db339a08ef8c8e9068f51507af8ebe69694c6468139e82679819\"\n",
      "      },\n",
      "      \"Flipped-label DPO\": {\n",
      "        \"parent_sha256\": \"dee36879595ac3a447cfcea10cc9e93bdd162e638c8af4df769228168c81ac21\",\n",
      "        \"reference_sha256\": \"98f30f5944ef7e086cb0848f4263c026feee9a1dea5cfcfd7714b2ffc54d1a86\",\n",
      "        \"schedule_sha256\": \"5f667dff4213cd39f19f87d6709a158e2c99c7b776aff3e1d6b14eade6d30d55\",\n",
      "        \"adapter_sha256\": \"178e8338e7155fa14fc2da6dc99c713e54c910c9935d6a104fe72971b84fc992\"\n",
      "      }\n",
      "    },\n",
      "    \"initial_dpo_losses\": {\n",
      "      \"Checked DPO\": 0.6931471824645996,\n",
      "      \"Flipped-label DPO\": 0.6931471824645996\n",
      "    },\n",
      "    \"matched_exposure\": {\n",
      "      \"attempted_updates\": 96,\n",
      "      \"updates\": 96,\n",
      "      \"supervised_response_tokens\": 42384,\n",
      "      \"unpadded_input_tokens\": 200696\n",
      "    },\n",
      "    \"settings\": {\n",
      "      \"batch_size\": 2,\n",
      "      \"max_tokens\": 1536,\n",
      "      \"max_new_tokens\": 384,\n",
      "      \"beta\": 0.1,\n",
      "      \"noise_fraction\": 0.25,\n",
      "      \"anchor_lr\": 0.0002,\n",
      "      \"dpo_lr\": 1e-05,\n",
      "      \"adapter_rank\": 8,\n",
      "      \"adapter_alpha\": 16,\n",
      "      \"adapter_targets\": [\n",
      "        \"q_proj\",\n",
      "        \"v_proj\"\n",
      "      ],\n",
      "      \"sample\": false,\n",
      "      \"beams\": 1,\n",
      "      \"dtype\": \"fp16\"\n",
      "    },\n",
      "    \"actual_flips\": [\n",
      "      \"SF-128983\",\n",
      "      \"SF-169838\",\n",
      "      \"SF-177975\",\n",
      "      \"SF-181050\",\n",
      "      \"SF-196133\",\n",
      "      \"SF-234277\",\n",
      "      \"SF-235614\",\n",
      "      \"SF-237194\",\n",
      "      \"SF-240903\",\n",
      "      \"SF-246594\",\n",
      "      \"SF-278734\",\n",
      "      \"SF-299223\",\n",
      "      \"SF-302292\",\n",
      "      \"SF-366204\",\n",
      "      \"SF-393890\",\n",
      "      \"SF-394802\",\n",
      "      \"SF-396874\",\n",
      "      \"SF-400509\",\n",
      "      \"SF-409458\",\n",
      "      \"SF-421980\",\n",
      "      \"SF-428518\",\n",
      "      \"SF-428921\",\n",
      "      \"SF-500930\",\n",
      "      \"SF-501056\",\n",
      "      \"SF-513412\",\n",
      "      \"SF-523401\",\n",
      "      \"SF-573548\",\n",
      "      \"SF-617742\",\n",
      "      \"SF-621041\",\n",
      "      \"SF-653181\",\n",
      "      \"SF-660620\",\n",
      "      \"SF-720523\",\n",
      "      \"SF-771322\",\n",
      "      \"SF-773278\",\n",
      "      \"SF-796866\",\n",
      "      \"SF-835115\",\n",
      "      \"SF-847065\",\n",
      "      \"SF-852113\",\n",
      "      \"SF-878021\",\n",
      "      \"SF-880157\",\n",
      "      \"SF-906769\",\n",
      "      \"SF-935074\",\n",
      "      \"SF-946338\",\n",
      "      \"SF-948847\",\n",
      "      \"SF-953140\",\n",
      "      \"SF-970938\",\n",
      "      \"SF-975629\",\n",
      "      \"SF-987675\"\n",
      "    ],\n",
      "    \"excluded_train\": [],\n",
      "    \"excluded_held\": [],\n",
      "    \"held_out_preference\": {\n",
      "      \"all\": {\n",
      "        \"n\": 240,\n",
      "        \"arms\": {\n",
      "          \"SFT anchor\": {\n",
      "            \"verified\": 240\n",
      "          },\n",
      "          \"Checked DPO\": {\n",
      "            \"verified\": 240\n",
      "          },\n",
      "          \"Flipped-label DPO\": {\n",
      "            \"verified\": 240\n",
      "          }\n",
      "        },\n",
      "        \"paired_family_intervals\": {\n",
      "          \"Checked DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Flipped-label DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Checked DPO minus Flipped-label DPO\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ]\n",
      "        }\n",
      "      },\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"arms\": {\n",
      "          \"SFT anchor\": {\n",
      "            \"verified\": 96\n",
      "          },\n",
      "          \"Checked DPO\": {\n",
      "            \"verified\": 96\n",
      "          },\n",
      "          \"Flipped-label DPO\": {\n",
      "            \"verified\": 96\n",
      "          }\n",
      "        },\n",
      "        \"paired_family_intervals\": {\n",
      "          \"Checked DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Flipped-label DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Checked DPO minus Flipped-label DPO\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ]\n",
      "        }\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"arms\": {\n",
      "          \"SFT anchor\": {\n",
      "            \"verified\": 96\n",
      "          },\n",
      "          \"Checked DPO\": {\n",
      "            \"verified\": 96\n",
      "          },\n",
      "          \"Flipped-label DPO\": {\n",
      "            \"verified\": 96\n",
      "          }\n",
      "        },\n",
      "        \"paired_family_intervals\": {\n",
      "          \"Checked DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Flipped-label DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Checked DPO minus Flipped-label DPO\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ]\n",
      "        }\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"arms\": {\n",
      "          \"SFT anchor\": {\n",
      "            \"verified\": 48\n",
      "          },\n",
      "          \"Checked DPO\": {\n",
      "            \"verified\": 48\n",
      "          },\n",
      "          \"Flipped-label DPO\": {\n",
      "            \"verified\": 48\n",
      "          }\n",
      "        },\n",
      "        \"paired_family_intervals\": {\n",
      "          \"Checked DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Flipped-label DPO minus SFT anchor\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ],\n",
      "          \"Checked DPO minus Flipped-label DPO\": [\n",
      "            0.0,\n",
      "            0.0\n",
      "          ]\n",
      "        }\n",
      "      }\n",
      "    },\n",
      "    \"generation_exact_on_matched_pairs\": {\n",
      "      \"Register-layout rules\": {\n",
      "        \"exact\": 24,\n",
      "        \"n\": 240\n",
      "      },\n",
      "      \"FP16 prompted\": {\n",
      "        \"exact\": 21,\n",
      "        \"n\": 240\n",
      "      },\n",
      "      \"SFT anchor\": {\n",
      "        \"exact\": 178,\n",
      "        \"n\": 240\n",
      "      },\n",
      "      \"Checked DPO\": {\n",
      "        \"exact\": 156,\n",
      "        \"n\": 240\n",
      "      },\n",
      "      \"Flipped-label DPO\": {\n",
      "        \"exact\": 171,\n",
      "        \"n\": 240\n",
      "      }\n",
      "    },\n",
      "    \"matched_generation_intervals\": {\n",
      "      \"Checked DPO minus SFT anchor\": [\n",
      "        -0.175,\n",
      "        -0.029166666666666667\n",
      "      ],\n",
      "      \"Flipped-label DPO minus SFT anchor\": [\n",
      "        -0.06666666666666667,\n",
      "        0.0\n",
      "      ],\n",
      "      \"Checked DPO minus Flipped-label DPO\": [\n",
      "        -0.1125,\n",
      "        -0.020833333333333332\n",
      "      ]\n",
      "    },\n",
      "    \"shifted_gradient_evidence\": {\n",
      "      \"roles_by_input_position\": [\n",
      "        \"prompt\",\n",
      "        \"prompt\",\n",
      "        \"prompt\",\n",
      "        \"response\",\n",
      "        \"response\",\n",
      "        \"EOS\",\n",
      "        \"padding\"\n",
      "      ],\n",
      "      \"labels_by_input_position\": [\n",
      "        -100,\n",
      "        -100,\n",
      "        -100,\n",
      "        2,\n",
      "        3,\n",
      "        1,\n",
      "        -100\n",
      "      ],\n",
      "      \"nonzero_logit_gradient_by_position\": [\n",
      "        false,\n",
      "        false,\n",
      "        true,\n",
      "        true,\n",
      "        true,\n",
      "        false,\n",
      "        false\n",
      "      ]\n",
      "    },\n",
      "    \"worked_invoice\": \"SF-235300\",\n",
      "    \"evaluation_seconds\": {\n",
      "      \"FP16 prompted\": 124.86661302699997,\n",
      "      \"SFT anchor\": 100.97549178199984,\n",
      "      \"Checked DPO\": 117.96084274999998,\n",
      "      \"Flipped-label DPO\": 114.827473134\n",
      "    },\n",
      "    \"reference_scoring_seconds\": 33.897563826999885\n",
      "  }\n",
      "}\n",
      "{\n",
      "  \"SFT anchor\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 21378,\n",
      "    \"unpadded_input_tokens\": 100690,\n",
      "    \"seconds\": 23.56155131799983,\n",
      "    \"supervised_tokens_per_second\": 907.3256557461177,\n",
      "    \"peak_gib\": 4.131346225738525,\n",
      "    \"trainable_parameters\": 540672\n",
      "  },\n",
      "  \"Checked DPO\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 42384,\n",
      "    \"unpadded_input_tokens\": 200696,\n",
      "    \"seconds\": 36.922442849999925,\n",
      "    \"supervised_tokens_per_second\": 1147.919713009999,\n",
      "    \"peak_gib\": 4.6147847175598145,\n",
      "    \"trainable_parameters\": 540672\n",
      "  },\n",
      "  \"Flipped-label DPO\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 42384,\n",
      "    \"unpadded_input_tokens\": 200696,\n",
      "    \"seconds\": 35.433422488999895,\n",
      "    \"supervised_tokens_per_second\": 1196.1587964910211,\n",
      "    \"peak_gib\": 4.6147847175598145,\n",
      "    \"trainable_parameters\": 540672\n",
      "  }\n",
      "}\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns=\"http://www.w3.org/2000/svg\" width=\"784.9825pt\" height=\"285.03625pt\" viewBox=\"0 0 784.9825 285.03625\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2026-11-27T06:37:12.669197</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.10.0, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 285.03625  L 784.9825 285.03625  L 784.9825 0  L 0 0  z \" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 117.310938 247.48  L 317.087604 247.48  L 317.087604 52.08  L 117.310938 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 117.310938 60.961818  L 167.255104 60.961818  L 167.255104 90.567879  L 117.310938 90.567879  z \" clip-path=\"url(#pc41269738b)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 117.310938 97.969394  L 146.445035 97.969394  L 146.445035 127.575455  L 117.310938 127.575455  z \" clip-path=\"url(#pc41269738b)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 117.310938 134.97697  L 315.006597 134.97697  L 315.006597 164.58303  L 117.310938 164.58303  z \" clip-path=\"url(#pc41269738b)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 117.310938 171.984545  L 312.92559 171.984545  L 312.92559 201.590606  L 117.310938 201.590606  z \" clip-path=\"url(#pc41269738b)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 117.310938 208.992121  L 312.92559 208.992121  L 312.92559 238.598182  L 117.310938 238.598182  z \" clip-path=\"url(#pc41269738b)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 117.310938 247.48  L 117.310938 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"mbf194eed37\" d=\"M 0 0  L 0 3.5  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"117.310938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"117.310938\" y=\"262.078437\" transform=\"rotate(-0 117.310938 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 157.266271 247.48  L 157.266271 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"157.266271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"157.266271\" y=\"262.078437\" transform=\"rotate(-0 157.266271 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 197.221604 247.48  L 197.221604 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"197.221604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"197.221604\" y=\"262.078437\" transform=\"rotate(-0 197.221604 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 237.176937 247.48  L 237.176937 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"237.176937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"237.176937\" y=\"262.078437\" transform=\"rotate(-0 237.176937 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 277.132271 247.48  L 277.132271 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"277.132271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"277.132271\" y=\"262.078437\" transform=\"rotate(-0 277.132271 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 317.087604 247.48  L 317.087604 52.08  \" clip-path=\"url(#pc41269738b)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"317.087604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"317.087604\" y=\"262.078437\" transform=\"rotate(-0 317.087604 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_7\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"217.199271\" y=\"275.756562\" transform=\"rotate(-0 217.199271 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <defs>\n",
       "       <path id=\"meafeb57f4f\" d=\"M 0 0  L -3.5 0  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"117.310938\" y=\"75.764848\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"79.564067\" transform=\"rotate(-0 110.310938 79.564067)\">Register-layout rules</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"117.310938\" y=\"112.772424\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"116.571643\" transform=\"rotate(-0 110.310938 116.571643)\">FP16 prompted</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"117.310938\" y=\"149.78\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"153.579219\" transform=\"rotate(-0 110.310938 153.579219)\">SFT anchor</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"117.310938\" y=\"186.787576\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"190.586795\" transform=\"rotate(-0 110.310938 190.586795)\">Checked DPO</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"117.310938\" y=\"223.795152\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_12\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: end\" x=\"110.310938\" y=\"227.59437\" transform=\"rotate(-0 110.310938 227.59437)\">Flipped-label DPO</text>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_8\">\n",
       "    <path d=\"M 117.310938 247.48  L 117.310938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_9\">\n",
       "    <path d=\"M 317.087604 247.48  L 317.087604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_10\">\n",
       "    <path d=\"M 117.310938 247.48  L 317.087604 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_11\">\n",
       "    <path d=\"M 117.310938 52.08  L 317.087604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_13\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"217.199271\" y=\"46.08\" transform=\"rotate(-0 217.199271 46.08)\">Familiar</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"axes_2\">\n",
       "   <g id=\"patch_12\">\n",
       "    <path d=\"M 343.682604 247.48  L 543.459271 247.48  L 543.459271 52.08  L 343.682604 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_13\">\n",
       "    <path d=\"M 343.682604 60.961818  L 343.682604 60.961818  L 343.682604 90.567879  L 343.682604 90.567879  z \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_14\">\n",
       "    <path d=\"M 343.682604 97.969394  L 345.763611 97.969394  L 345.763611 127.575455  L 343.682604 127.575455  z \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_15\">\n",
       "    <path d=\"M 343.682604 134.97697  L 456.056979 134.97697  L 456.056979 164.58303  L 343.682604 164.58303  z \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_16\">\n",
       "    <path d=\"M 343.682604 171.984545  L 447.732951 171.984545  L 447.732951 201.590606  L 343.682604 201.590606  z \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_17\">\n",
       "    <path d=\"M 343.682604 208.992121  L 458.137986 208.992121  L 458.137986 238.598182  L 343.682604 238.598182  z \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_3\">\n",
       "    <g id=\"xtick_7\">\n",
       "     <g id=\"line2d_18\">\n",
       "      <path d=\"M 343.682604 247.48  L 343.682604 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_19\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"343.682604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_14\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"343.682604\" y=\"262.078437\" transform=\"rotate(-0 343.682604 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_8\">\n",
       "     <g id=\"line2d_20\">\n",
       "      <path d=\"M 383.637937 247.48  L 383.637937 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_21\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"383.637937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_15\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"383.637937\" y=\"262.078437\" transform=\"rotate(-0 383.637937 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_9\">\n",
       "     <g id=\"line2d_22\">\n",
       "      <path d=\"M 423.593271 247.48  L 423.593271 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_23\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"423.593271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_16\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"423.593271\" y=\"262.078437\" transform=\"rotate(-0 423.593271 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_10\">\n",
       "     <g id=\"line2d_24\">\n",
       "      <path d=\"M 463.548604 247.48  L 463.548604 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_25\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"463.548604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_17\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"463.548604\" y=\"262.078437\" transform=\"rotate(-0 463.548604 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_11\">\n",
       "     <g id=\"line2d_26\">\n",
       "      <path d=\"M 503.503938 247.48  L 503.503938 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_27\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"503.503938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_18\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"503.503938\" y=\"262.078437\" transform=\"rotate(-0 503.503938 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_12\">\n",
       "     <g id=\"line2d_28\">\n",
       "      <path d=\"M 543.459271 247.48  L 543.459271 52.08  \" clip-path=\"url(#p5bf8147f01)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_29\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"543.459271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_19\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"543.459271\" y=\"262.078437\" transform=\"rotate(-0 543.459271 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_20\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"443.570938\" y=\"275.756562\" transform=\"rotate(-0 443.570938 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_4\">\n",
       "    <g id=\"ytick_6\">\n",
       "     <g id=\"line2d_30\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"343.682604\" y=\"75.764848\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_7\">\n",
       "     <g id=\"line2d_31\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"343.682604\" y=\"112.772424\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_8\">\n",
       "     <g id=\"line2d_32\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"343.682604\" y=\"149.78\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_9\">\n",
       "     <g id=\"line2d_33\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"343.682604\" y=\"186.787576\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_10\">\n",
       "     <g id=\"line2d_34\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"343.682604\" y=\"223.795152\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_18\">\n",
       "    <path d=\"M 343.682604 247.48  L 343.682604 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_19\">\n",
       "    <path d=\"M 543.459271 247.48  L 543.459271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_20\">\n",
       "    <path d=\"M 343.682604 247.48  L 543.459271 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_21\">\n",
       "    <path d=\"M 343.682604 52.08  L 543.459271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_21\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"443.570938\" y=\"46.08\" transform=\"rotate(-0 443.570938 46.08)\">Novel</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"axes_3\">\n",
       "   <g id=\"patch_22\">\n",
       "    <path d=\"M 570.054271 247.48  L 769.830938 247.48  L 769.830938 52.08  L 570.054271 52.08  z \" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_23\">\n",
       "    <path d=\"M 570.054271 60.961818  L 570.054271 60.961818  L 570.054271 90.567879  L 570.054271 90.567879  z \" clip-path=\"url(#p5997b322df)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_24\">\n",
       "    <path d=\"M 570.054271 97.969394  L 595.026354 97.969394  L 595.026354 127.575455  L 570.054271 127.575455  z \" clip-path=\"url(#p5997b322df)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_25\">\n",
       "    <path d=\"M 570.054271 134.97697  L 690.752674 134.97697  L 690.752674 164.58303  L 570.054271 164.58303  z \" clip-path=\"url(#p5997b322df)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_26\">\n",
       "    <path d=\"M 570.054271 171.984545  L 619.998437 171.984545  L 619.998437 201.590606  L 570.054271 201.590606  z \" clip-path=\"url(#p5997b322df)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_27\">\n",
       "    <path d=\"M 570.054271 208.992121  L 661.618576 208.992121  L 661.618576 238.598182  L 570.054271 238.598182  z \" clip-path=\"url(#p5997b322df)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_5\">\n",
       "    <g id=\"xtick_13\">\n",
       "     <g id=\"line2d_35\">\n",
       "      <path d=\"M 570.054271 247.48  L 570.054271 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_36\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"570.054271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_22\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"570.054271\" y=\"262.078437\" transform=\"rotate(-0 570.054271 262.078437)\">0.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_14\">\n",
       "     <g id=\"line2d_37\">\n",
       "      <path d=\"M 610.009604 247.48  L 610.009604 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_38\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"610.009604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_23\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"610.009604\" y=\"262.078437\" transform=\"rotate(-0 610.009604 262.078437)\">0.2</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_15\">\n",
       "     <g id=\"line2d_39\">\n",
       "      <path d=\"M 649.964937 247.48  L 649.964937 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_40\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"649.964937\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_24\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"649.964937\" y=\"262.078437\" transform=\"rotate(-0 649.964937 262.078437)\">0.4</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_16\">\n",
       "     <g id=\"line2d_41\">\n",
       "      <path d=\"M 689.920271 247.48  L 689.920271 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_42\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"689.920271\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_25\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"689.920271\" y=\"262.078437\" transform=\"rotate(-0 689.920271 262.078437)\">0.6</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_17\">\n",
       "     <g id=\"line2d_43\">\n",
       "      <path d=\"M 729.875604 247.48  L 729.875604 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_44\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"729.875604\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_26\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"729.875604\" y=\"262.078437\" transform=\"rotate(-0 729.875604 262.078437)\">0.8</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_18\">\n",
       "     <g id=\"line2d_45\">\n",
       "      <path d=\"M 769.830938 247.48  L 769.830938 52.08  \" clip-path=\"url(#p5997b322df)\" style=\"fill: none; stroke: #b0b0b0; stroke-opacity: 0.2; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_46\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mbf194eed37\" x=\"769.830938\" y=\"247.48\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_27\">\n",
       "      <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"769.830938\" y=\"262.078437\" transform=\"rotate(-0 769.830938 262.078437)\">1.0</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_28\">\n",
       "     <text style=\"font-size: 10px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"669.942604\" y=\"275.756562\" transform=\"rotate(-0 669.942604 275.756562)\">Exact record rate</text>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_6\">\n",
       "    <g id=\"ytick_11\">\n",
       "     <g id=\"line2d_47\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"570.054271\" y=\"75.764848\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_12\">\n",
       "     <g id=\"line2d_48\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"570.054271\" y=\"112.772424\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_13\">\n",
       "     <g id=\"line2d_49\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"570.054271\" y=\"149.78\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_14\">\n",
       "     <g id=\"line2d_50\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"570.054271\" y=\"186.787576\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_15\">\n",
       "     <g id=\"line2d_51\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meafeb57f4f\" x=\"570.054271\" y=\"223.795152\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_28\">\n",
       "    <path d=\"M 570.054271 247.48  L 570.054271 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_29\">\n",
       "    <path d=\"M 769.830938 247.48  L 769.830938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_30\">\n",
       "    <path d=\"M 570.054271 247.48  L 769.830938 247.48  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_31\">\n",
       "    <path d=\"M 570.054271 52.08  L 769.830938 52.08  \" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"text_29\">\n",
       "    <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"669.942604\" y=\"46.08\" transform=\"rotate(-0 669.942604 46.08)\">Independent</text>\n",
       "   </g>\n",
       "  </g>\n",
       "  <g id=\"text_30\">\n",
       "   <text style=\"font-size: 12px; font-family: 'DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', sans-serif; text-anchor: middle\" x=\"392.550937\" y=\"16.318125\" transform=\"rotate(-0 392.550937 16.318125)\">Complete-record accuracy on the held-out invoice slices</text>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"pc41269738b\">\n",
       "   <rect x=\"117.310938\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"p5bf8147f01\">\n",
       "   <rect x=\"343.682604\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"p5997b322df\">\n",
       "   <rect x=\"570.054271\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>"
      ],
      "text/plain": [
       "<IPython.core.display.SVG object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"arm\": \"Register-layout rules\", \"generation\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"completed\": false, \"answer\": null, \"reference\": {\"invoice_id\": \"SF-235300\", \"issued_on\": \"2025-02-20\", \"supplier\": \"Sample Supplier 3219\", \"currency\": \"GBP\", \"line_items\": [{\"description\": \"Rack inspection\", \"quantity\": 8, \"unit_minor\": 13740}], \"subtotal_minor\": 109920, \"tax_minor\": 14290, \"total_minor\": 124311}, \"valid\": false, \"exact\": false, \"fields\": 0.0, \"field_correct\": {\"invoice_id\": false, \"issued_on\": false, \"supplier\": false, \"currency\": false, \"subtotal_minor\": false, \"tax_minor\": false, \"total_minor\": false}, \"row_f1\": 0.0}, \"pair_ranking\": null}\n",
      "{\"arm\": \"FP16 prompted\", \"generation\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"completed\": true, \"answer\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[],\\\"subtotal_minor\\\":124311,\\\"tax_minor\\\":109920,\\\"total_minor\\\":115363}\", \"reference\": {\"invoice_id\": \"SF-235300\", \"issued_on\": \"2025-02-20\", \"supplier\": \"Sample Supplier 3219\", \"currency\": \"GBP\", \"line_items\": [{\"description\": \"Rack inspection\", \"quantity\": 8, \"unit_minor\": 13740}], \"subtotal_minor\": 109920, \"tax_minor\": 14290, \"total_minor\": 124311}, \"completion_tokens\": 75, \"valid\": true, \"exact\": false, \"fields\": 0.5714285714285714, \"field_correct\": {\"invoice_id\": true, \"issued_on\": true, \"supplier\": true, \"currency\": true, \"subtotal_minor\": false, \"tax_minor\": false, \"total_minor\": false}, \"row_f1\": 0.0}, \"pair_ranking\": null}\n",
      "{\"arm\": \"SFT anchor\", \"generation\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"completed\": true, \"answer\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[{\\\"description\\\":\\\"Rack inspection\\\",\\\"quantity\\\":8,\\\"unit_minor\\\":13740}],\\\"subtotal_minor\\\":109920,\\\"tax_minor\\\":14290,\\\"total_minor\\\":124311}\", \"reference\": {\"invoice_id\": \"SF-235300\", \"issued_on\": \"2025-02-20\", \"supplier\": \"Sample Supplier 3219\", \"currency\": \"GBP\", \"line_items\": [{\"description\": \"Rack inspection\", \"quantity\": 8, \"unit_minor\": 13740}], \"subtotal_minor\": 109920, \"tax_minor\": 14290, \"total_minor\": 124311}, \"completion_tokens\": 93, \"valid\": true, \"exact\": true, \"fields\": 1.0, \"field_correct\": {\"invoice_id\": true, \"issued_on\": true, \"supplier\": true, \"currency\": true, \"subtotal_minor\": true, \"tax_minor\": true, \"total_minor\": true}, \"row_f1\": 1.0}, \"pair_ranking\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"verified_logp\": -0.8045692443847656, \"counterexample_logp\": -13.507793426513672, \"margin\": 12.703224182128906, \"winner\": \"verified\"}}\n",
      "{\"arm\": \"Checked DPO\", \"generation\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"completed\": true, \"answer\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[{\\\"description\\\":\\\"Rack inspection\\\",\\\"quantity\\\":8,\\\"unit_minor\\\":13740}],\\\"subtotal_minor\\\":109920,\\\"tax_minor\\\":14290,\\\"total_minor\\\":124311}\", \"reference\": {\"invoice_id\": \"SF-235300\", \"issued_on\": \"2025-02-20\", \"supplier\": \"Sample Supplier 3219\", \"currency\": \"GBP\", \"line_items\": [{\"description\": \"Rack inspection\", \"quantity\": 8, \"unit_minor\": 13740}], \"subtotal_minor\": 109920, \"tax_minor\": 14290, \"total_minor\": 124311}, \"completion_tokens\": 93, \"valid\": true, \"exact\": true, \"fields\": 1.0, \"field_correct\": {\"invoice_id\": true, \"issued_on\": true, \"supplier\": true, \"currency\": true, \"subtotal_minor\": true, \"tax_minor\": true, \"total_minor\": true}, \"row_f1\": 1.0}, \"pair_ranking\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"verified_logp\": -0.6029186248779297, \"counterexample_logp\": -23.72714614868164, \"margin\": 23.12422752380371, \"winner\": \"verified\"}}\n",
      "{\"arm\": \"Flipped-label DPO\", \"generation\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"completed\": true, \"answer\": \"{\\\"invoice_id\\\":\\\"SF-235300\\\",\\\"issued_on\\\":\\\"2025-02-20\\\",\\\"supplier\\\":\\\"Sample Supplier 3219\\\",\\\"currency\\\":\\\"GBP\\\",\\\"line_items\\\":[{\\\"description\\\":\\\"Rack inspection\\\",\\\"quantity\\\":8,\\\"unit_minor\\\":13740}],\\\"subtotal_minor\\\":109920,\\\"tax_minor\\\":14290,\\\"total_minor\\\":124311}\", \"reference\": {\"invoice_id\": \"SF-235300\", \"issued_on\": \"2025-02-20\", \"supplier\": \"Sample Supplier 3219\", \"currency\": \"GBP\", \"line_items\": [{\"description\": \"Rack inspection\", \"quantity\": 8, \"unit_minor\": 13740}], \"subtotal_minor\": 109920, \"tax_minor\": 14290, \"total_minor\": 124311}, \"completion_tokens\": 93, \"valid\": true, \"exact\": true, \"fields\": 1.0, \"field_correct\": {\"invoice_id\": true, \"issued_on\": true, \"supplier\": true, \"currency\": true, \"subtotal_minor\": true, \"tax_minor\": true, \"total_minor\": true}, \"row_f1\": 1.0}, \"pair_ranking\": {\"key\": \"SF-235300\", \"split\": \"novel\", \"family\": \"novel-01\", \"verified_logp\": -0.6000270843505859, \"counterexample_logp\": -18.34998321533203, \"margin\": 17.749956130981445, \"winner\": \"verified\"}}\n",
      "Evidence files: results/03-exact.svg, results/03-held-rankings.json, results/03-pair-audit.json, results/03-predictions.json, results/03-reference-logps.json, results/03-report.json, results/03-split-manifest.json\n"
     ]
    }
   ],
   "source": [
    "comparisons = [\n",
    "    (\"SFT anchor\", \"Checked DPO\"),\n",
    "    (\"SFT anchor\", \"Flipped-label DPO\"),\n",
    "    (\"Flipped-label DPO\", \"Checked DPO\"),\n",
    "]\n",
    "held_rankings, preference_summary = measure_preferences(held_pair_items, held_logps, comparisons)\n",
    "(RESULTS / \"03-held-rankings.json\").write_text(\n",
    "    json.dumps(held_rankings, indent=2) + \"\\n\", encoding=\"utf-8\",\n",
    ")\n",
    "expected_roster = [(row.key, row.split, row.family) for row in evaluation_items]\n",
    "for name, observed in scores.items():\n",
    "    if [(row[\"key\"], row[\"split\"], row[\"family\"]) for row in observed] != expected_roster:\n",
    "        raise RuntimeError(f\"{name} did not generate on the fixed evaluation roster.\")\n",
    "matched_rows = {name: [row for row in rows if row[\"key\"] in held_keys] for name, rows in scores.items()}\n",
    "matched_generation = {\n",
    "    name: {\"exact\": sum(row[\"exact\"] for row in rows), \"n\": len(rows)} for name, rows in matched_rows.items()\n",
    "}\n",
    "matched_generation_intervals = {\n",
    "    f\"{candidate} minus {baseline}\": paired_family_interval(matched_rows[baseline], matched_rows[candidate])\n",
    "    for baseline, candidate in comparisons\n",
    "}\n",
    "report = save_results(\n",
    "    \"03\", scores, training, comparisons, catalogue_version=CATALOG_VERSION, packages=versions,\n",
    "    anchor_sha256=anchor_digest, reference_sha256=reference_digest, split_sha256=manifest[\"sha256\"],\n",
    "    pair_audit_sha256=fingerprint(audits), schedule_sha256=schedule_sha256,\n",
    "    adapters=adapters, initial_dpo_losses=initial_losses, matched_exposure=matched_exposure,\n",
    "    settings={\"batch_size\": BATCH, \"max_tokens\": MAX_TOKENS, \"max_new_tokens\": MAX_NEW_TOKENS,\n",
    "              \"beta\": BETA, \"noise_fraction\": NOISE_FRACTION, \"anchor_lr\": ANCHOR_LR, \"dpo_lr\": DPO_LR,\n",
    "              \"adapter_rank\": 8, \"adapter_alpha\": 16, \"adapter_targets\": [\"q_proj\", \"v_proj\"],\n",
    "              \"sample\": False, \"beams\": 1, \"dtype\": \"fp16\" if DEVICE == \"cuda\" else \"float32\"},\n",
    "    actual_flips=sorted(flipped), excluded_train=excluded_train, excluded_held=excluded_held,\n",
    "    held_out_preference=preference_summary, generation_exact_on_matched_pairs=matched_generation,\n",
    "    matched_generation_intervals=matched_generation_intervals,\n",
    "    shifted_gradient_evidence=mask_evidence, worked_invoice=WORKED_INVOICE,\n",
    "    evaluation_seconds=evaluation_seconds, reference_scoring_seconds=reference_seconds,\n",
    ")\n",
    "for name, rows in scores.items():\n",
    "    example = next(row for row in rows if row[\"key\"] == WORKED_INVOICE)\n",
    "    rank = next((row for row in held_rankings.get(name, []) if row[\"key\"] == WORKED_INVOICE), None)\n",
    "    print(json.dumps({\"arm\": name, \"generation\": example, \"pair_ranking\": rank}, ensure_ascii=False))\n",
    "print(\"Evidence files:\", \", \".join(str(path) for path in sorted(RESULTS.glob(\"03-*.*\"))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3e3dd5c",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "First compare verified-candidate wins and exact generated records. Check whether the\n",
    "arms differ across held-out slices and whether a change coincides with invalid JSON\n",
    "or missing end markers. Then trace the remittance example from the input to the raw outputs.\n",
    "\n",
    "The [DPO paper](https://arxiv.org/abs/2305.18290) derives the objective. The\n",
    "[Together Cookbook](https://github.com/togethercomputer/post-training-cookbook/blob/226e03ca225d6f13434047cf0f45ab3070a29801/post_training_cookbook/dpo/loss.py)\n",
    "informed the local response-masked implementation. [Read the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/2-compare-training-stages/03-audit-preference-pairs)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
