{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e7c6c0dc",
   "metadata": {},
   "source": [
    "# 01 · LoRA vs QLoRA for invoice extraction\n",
    "\n",
    "[Open Chapter 1 in local Recohut Docs](http://localhost:3020/courses/advanced-llm-fine-tuning/01-port-a-training-recipe)\n",
    "\n",
    "Which fine-tuning method extracts invoices more accurately, and how much GPU memory does each use?\n",
    "\n",
    "Fit the same adapter twice on synthetic invoices. One arm keeps the base weights in FP16.\n",
    "The other loads a frozen NF4 base with double quantisation and uses FP16 compute.\n",
    "Both use the same labelled completion, adapter rank, optimiser and update budget."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4464bf8",
   "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": "44873976",
   "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', 'bitsandbytes==0.50.2'], 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', 'bitsandbytes==0.50.2']], check=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8013fec8",
   "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": "markdown",
   "id": "5263181a",
   "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": 3,
   "id": "94901265",
   "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": "6c649a43",
   "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": 4,
   "id": "f6e2e595",
   "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": "998a1b2b",
   "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": 5,
   "id": "69b1f362",
   "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": 6,
   "id": "224edffd",
   "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": "a397f203",
   "metadata": {},
   "source": [
    "## One update schedule\n",
    "\n",
    "The frozen base and its quantised counterpart share an instruction checkpoint but do\n",
    "not necessarily produce identical predictions. Save both unadapted results before fitting.\n",
    "The rules baseline recognises the canonical register layout from visible text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e9af8f3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training rows: 192 Planned updates per arm: 96\n"
     ]
    }
   ],
   "source": [
    "chosen = training_items[:192]\n",
    "examples = [\n",
    "    encode_supervision(tokenizer, invoice, canonical_json(invoice_record(invoice)), exemplar)\n",
    "    for invoice in chosen\n",
    "]\n",
    "schedule = make_schedule(examples)\n",
    "scores = {\"Register-layout rules\": rules_predictions(evaluation_items)}\n",
    "training = {}\n",
    "print(\"Training rows:\", len(examples), \"Planned updates per arm:\", len(schedule))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a6101fb",
   "metadata": {},
   "source": [
    "## FP16 reference\n",
    "\n",
    "Measure the frozen checkpoint under the same prompt used for the adapter.\n",
    "The data and rank are fixed before either weight encoding is trained."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ec28866f",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = load_model(\"fp16\")\n",
    "scores[\"FP16 prompted\"] = predictions(model, tokenizer, evaluation_items, exemplar)\n",
    "del model\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "74aa61c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = load_model(\"fp16\", trainable=True)\n",
    "training[\"FP16 LoRA\"] = adapter_train(\n",
    "    model, schedule, sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "    learning_rate=2e-4, use_cuda=True,\n",
    ")\n",
    "scores[\"FP16 LoRA\"] = predictions(model, tokenizer, evaluation_items, exemplar)\n",
    "model.save_pretrained(\"results/01-fp16-adapter\")\n",
    "del model\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2847f64",
   "metadata": {},
   "source": [
    "## NF4 comparison\n",
    "\n",
    "Quantise the bases only for the NF4 arm. Measure NF4 prompting to separate the\n",
    "checkpoint's inference change from the subsequent adapter fit. The reported peak\n",
    "is allocated GPU memory over optimisation and includes the resident model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ad324016",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = load_model(\"nf4\")\n",
    "scores[\"NF4 prompted\"] = predictions(model, tokenizer, evaluation_items, exemplar)\n",
    "del model\n",
    "free_gpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f188bf7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = load_model(\"nf4\", trainable=True)\n",
    "training[\"NF4 QLoRA\"] = adapter_train(\n",
    "    model, schedule, sft_objective(tokenizer.pad_token_id, \"cuda\"),\n",
    "    learning_rate=2e-4, use_cuda=True,\n",
    ")\n",
    "scores[\"NF4 QLoRA\"] = predictions(model, tokenizer, evaluation_items, exemplar)\n",
    "model.save_pretrained(\"results/01-nf4-adapter\")\n",
    "del model\n",
    "free_gpu()\n",
    "for metric in (\"updates\", \"supervised_response_tokens\", \"unpadded_input_tokens\", \"trainable_parameters\"):\n",
    "    if training[\"FP16 LoRA\"][metric] != training[\"NF4 QLoRA\"][metric]:\n",
    "        raise RuntimeError(f\"The training arms did not stay matched on {metric}.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f28c34a0",
   "metadata": {},
   "source": [
    "## Compare accuracy and cost\n",
    "\n",
    "The FP16 and NF4 adapters share a dataset and schedule, so compare quality against\n",
    "the paired starting points. Report time, memory and supervised token throughput\n",
    "alongside exact-record accuracy rather than inferring accuracy from a memory gain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "65bf0774",
   "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",
      "    \"FP16 LoRA\": {\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.5833333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.8571428571428571,\n",
      "        \"row_f1\": 0.9375\n",
      "      }\n",
      "    },\n",
      "    \"NF4 prompted\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.25,\n",
      "        \"exact\": 0.08333333333333333,\n",
      "        \"completed\": 0.9583333333333334,\n",
      "        \"fields\": 0.23511904761904762,\n",
      "        \"row_f1\": 0.1753472222222222\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.2708333333333333,\n",
      "        \"exact\": 0.0,\n",
      "        \"completed\": 0.75,\n",
      "        \"fields\": 0.25595238095238093,\n",
      "        \"row_f1\": 0.0\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.22916666666666666,\n",
      "        \"exact\": 0.0625,\n",
      "        \"completed\": 0.7916666666666666,\n",
      "        \"fields\": 0.17857142857142858,\n",
      "        \"row_f1\": 0.20833333333333334\n",
      "      }\n",
      "    },\n",
      "    \"NF4 QLoRA\": {\n",
      "      \"familiar\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.9895833333333334,\n",
      "        \"exact\": 0.9583333333333334,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9895833333333334,\n",
      "        \"row_f1\": 0.9635416666666666\n",
      "      },\n",
      "      \"novel\": {\n",
      "        \"n\": 96,\n",
      "        \"valid\": 0.96875,\n",
      "        \"exact\": 0.5,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9181547619047619,\n",
      "        \"row_f1\": 0.6840277777777778\n",
      "      },\n",
      "      \"independent\": {\n",
      "        \"n\": 48,\n",
      "        \"valid\": 0.9583333333333334,\n",
      "        \"exact\": 0.8541666666666666,\n",
      "        \"completed\": 1.0,\n",
      "        \"fields\": 0.9315476190476191,\n",
      "        \"row_f1\": 0.9583333333333334\n",
      "      }\n",
      "    }\n",
      "  },\n",
      "  \"paired_family_intervals\": {\n",
      "    \"FP16 LoRA minus FP16 prompted\": {\n",
      "      \"familiar\": [\n",
      "        0.6458333333333334,\n",
      "        1.0\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        0.28125,\n",
      "        0.7916666666666666\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        0.3125,\n",
      "        0.6041666666666666\n",
      "      ]\n",
      "    },\n",
      "    \"NF4 QLoRA minus NF4 prompted\": {\n",
      "      \"familiar\": [\n",
      "        0.7291666666666666,\n",
      "        0.9791666666666666\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        0.25,\n",
      "        0.7395833333333334\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        0.75,\n",
      "        0.8333333333333334\n",
      "      ]\n",
      "    },\n",
      "    \"NF4 QLoRA minus FP16 LoRA\": {\n",
      "      \"familiar\": [\n",
      "        -0.0625,\n",
      "        -0.010416666666666666\n",
      "      ],\n",
      "      \"novel\": [\n",
      "        -0.34375,\n",
      "        0.22916666666666666\n",
      "      ],\n",
      "      \"independent\": [\n",
      "        0.14583333333333334,\n",
      "        0.375\n",
      "      ]\n",
      "    }\n",
      "  },\n",
      "  \"diagnostics\": {\n",
      "    \"catalogue_version\": \"course-invoice-v1\",\n",
      "    \"training_keys\": [\n",
      "      \"SF-460242\",\n",
      "      \"SF-957778\",\n",
      "      \"SF-260556\",\n",
      "      \"SF-397858\",\n",
      "      \"SF-600245\",\n",
      "      \"SF-921659\",\n",
      "      \"SF-783565\",\n",
      "      \"SF-174897\",\n",
      "      \"SF-229805\",\n",
      "      \"SF-280550\",\n",
      "      \"SF-531542\",\n",
      "      \"SF-279605\",\n",
      "      \"SF-411860\",\n",
      "      \"SF-219059\",\n",
      "      \"SF-463978\",\n",
      "      \"SF-626332\",\n",
      "      \"SF-644023\",\n",
      "      \"SF-332209\",\n",
      "      \"SF-415645\",\n",
      "      \"SF-939833\",\n",
      "      \"SF-999146\",\n",
      "      \"SF-563210\",\n",
      "      \"SF-422935\",\n",
      "      \"SF-912644\",\n",
      "      \"SF-455114\",\n",
      "      \"SF-372440\",\n",
      "      \"SF-645757\",\n",
      "      \"SF-939601\",\n",
      "      \"SF-963495\",\n",
      "      \"SF-790226\",\n",
      "      \"SF-382917\",\n",
      "      \"SF-689260\",\n",
      "      \"SF-441515\",\n",
      "      \"SF-370306\",\n",
      "      \"SF-424194\",\n",
      "      \"SF-652092\",\n",
      "      \"SF-407094\",\n",
      "      \"SF-629378\",\n",
      "      \"SF-919659\",\n",
      "      \"SF-885222\",\n",
      "      \"SF-463320\",\n",
      "      \"SF-365741\",\n",
      "      \"SF-779471\",\n",
      "      \"SF-913480\",\n",
      "      \"SF-832858\",\n",
      "      \"SF-556618\",\n",
      "      \"SF-409733\",\n",
      "      \"SF-931691\",\n",
      "      \"SF-616570\",\n",
      "      \"SF-458686\",\n",
      "      \"SF-277352\",\n",
      "      \"SF-460078\",\n",
      "      \"SF-406567\",\n",
      "      \"SF-329071\",\n",
      "      \"SF-273171\",\n",
      "      \"SF-475519\",\n",
      "      \"SF-278613\",\n",
      "      \"SF-828548\",\n",
      "      \"SF-918875\",\n",
      "      \"SF-652695\",\n",
      "      \"SF-231789\",\n",
      "      \"SF-767582\",\n",
      "      \"SF-120329\",\n",
      "      \"SF-272691\",\n",
      "      \"SF-539732\",\n",
      "      \"SF-350981\",\n",
      "      \"SF-278819\",\n",
      "      \"SF-231446\",\n",
      "      \"SF-157375\",\n",
      "      \"SF-637261\",\n",
      "      \"SF-475319\",\n",
      "      \"SF-807448\",\n",
      "      \"SF-824103\",\n",
      "      \"SF-401354\",\n",
      "      \"SF-232799\",\n",
      "      \"SF-302305\",\n",
      "      \"SF-568718\",\n",
      "      \"SF-469507\",\n",
      "      \"SF-715260\",\n",
      "      \"SF-358345\",\n",
      "      \"SF-701137\",\n",
      "      \"SF-460472\",\n",
      "      \"SF-202696\",\n",
      "      \"SF-163812\",\n",
      "      \"SF-799076\",\n",
      "      \"SF-652885\",\n",
      "      \"SF-680003\",\n",
      "      \"SF-315349\",\n",
      "      \"SF-110618\",\n",
      "      \"SF-458807\",\n",
      "      \"SF-962495\",\n",
      "      \"SF-762616\",\n",
      "      \"SF-574810\",\n",
      "      \"SF-779735\",\n",
      "      \"SF-229561\",\n",
      "      \"SF-616152\",\n",
      "      \"SF-648455\",\n",
      "      \"SF-540623\",\n",
      "      \"SF-387217\",\n",
      "      \"SF-816846\",\n",
      "      \"SF-669723\",\n",
      "      \"SF-625099\",\n",
      "      \"SF-349372\",\n",
      "      \"SF-519457\",\n",
      "      \"SF-355937\",\n",
      "      \"SF-158596\",\n",
      "      \"SF-507012\",\n",
      "      \"SF-159606\",\n",
      "      \"SF-275635\",\n",
      "      \"SF-485982\",\n",
      "      \"SF-815017\",\n",
      "      \"SF-294698\",\n",
      "      \"SF-923986\",\n",
      "      \"SF-527427\",\n",
      "      \"SF-569622\",\n",
      "      \"SF-409809\",\n",
      "      \"SF-730575\",\n",
      "      \"SF-633896\",\n",
      "      \"SF-800980\",\n",
      "      \"SF-428057\",\n",
      "      \"SF-944410\",\n",
      "      \"SF-947071\",\n",
      "      \"SF-748164\",\n",
      "      \"SF-471917\",\n",
      "      \"SF-669120\",\n",
      "      \"SF-664941\",\n",
      "      \"SF-721421\",\n",
      "      \"SF-902388\",\n",
      "      \"SF-748453\",\n",
      "      \"SF-850619\",\n",
      "      \"SF-770304\",\n",
      "      \"SF-129547\",\n",
      "      \"SF-109206\",\n",
      "      \"SF-191073\",\n",
      "      \"SF-960465\",\n",
      "      \"SF-834749\",\n",
      "      \"SF-765828\",\n",
      "      \"SF-644547\",\n",
      "      \"SF-236695\",\n",
      "      \"SF-907941\",\n",
      "      \"SF-322124\",\n",
      "      \"SF-995414\",\n",
      "      \"SF-642032\",\n",
      "      \"SF-942300\",\n",
      "      \"SF-606165\",\n",
      "      \"SF-854497\",\n",
      "      \"SF-325675\",\n",
      "      \"SF-488356\",\n",
      "      \"SF-128446\",\n",
      "      \"SF-323078\",\n",
      "      \"SF-428317\",\n",
      "      \"SF-746585\",\n",
      "      \"SF-308989\",\n",
      "      \"SF-729479\",\n",
      "      \"SF-666823\",\n",
      "      \"SF-425310\",\n",
      "      \"SF-287134\",\n",
      "      \"SF-299244\",\n",
      "      \"SF-719829\",\n",
      "      \"SF-518848\",\n",
      "      \"SF-204891\",\n",
      "      \"SF-577519\",\n",
      "      \"SF-340283\",\n",
      "      \"SF-212544\",\n",
      "      \"SF-993877\",\n",
      "      \"SF-583748\",\n",
      "      \"SF-348113\",\n",
      "      \"SF-992196\",\n",
      "      \"SF-993678\",\n",
      "      \"SF-291811\",\n",
      "      \"SF-781457\",\n",
      "      \"SF-153095\",\n",
      "      \"SF-406553\",\n",
      "      \"SF-931622\",\n",
      "      \"SF-915678\",\n",
      "      \"SF-842479\",\n",
      "      \"SF-371721\",\n",
      "      \"SF-550701\",\n",
      "      \"SF-541015\",\n",
      "      \"SF-492841\",\n",
      "      \"SF-698995\",\n",
      "      \"SF-954931\",\n",
      "      \"SF-327852\",\n",
      "      \"SF-399624\",\n",
      "      \"SF-705959\",\n",
      "      \"SF-266450\",\n",
      "      \"SF-740586\",\n",
      "      \"SF-536066\",\n",
      "      \"SF-144214\",\n",
      "      \"SF-955241\",\n",
      "      \"SF-837068\",\n",
      "      \"SF-747324\"\n",
      "    ]\n",
      "  }\n",
      "}\n",
      "{\n",
      "  \"FP16 LoRA\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 21378,\n",
      "    \"unpadded_input_tokens\": 100690,\n",
      "    \"seconds\": 21.311002146999954,\n",
      "    \"supervised_tokens_per_second\": 1003.1438152245448,\n",
      "    \"peak_gib\": 4.131346225738525,\n",
      "    \"trainable_parameters\": 540672\n",
      "  },\n",
      "  \"NF4 QLoRA\": {\n",
      "    \"attempted_updates\": 96,\n",
      "    \"updates\": 96,\n",
      "    \"supervised_response_tokens\": 21378,\n",
      "    \"unpadded_input_tokens\": 100690,\n",
      "    \"seconds\": 34.82223728700001,\n",
      "    \"supervised_tokens_per_second\": 613.9180496590589,\n",
      "    \"peak_gib\": 4.928420066833496,\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-26T13:05:47.343509</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(#p8e5443743e)\" 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(#p8e5443743e)\" 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(#p8e5443743e)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 117.310938 171.984545  L 133.958993 171.984545  L 133.958993 201.590606  L 117.310938 201.590606  z \" clip-path=\"url(#p8e5443743e)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 117.310938 208.992121  L 308.763576 208.992121  L 308.763576 238.598182  L 117.310938 238.598182  z \" clip-path=\"url(#p8e5443743e)\" 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(#p8e5443743e)\" 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=\"m3b2b24f6fc\" d=\"M 0 0  L 0 3.5  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3b2b24f6fc\" 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(#p8e5443743e)\" 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=\"#m3b2b24f6fc\" 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(#p8e5443743e)\" 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=\"#m3b2b24f6fc\" 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(#p8e5443743e)\" 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=\"#m3b2b24f6fc\" 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(#p8e5443743e)\" 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=\"#m3b2b24f6fc\" 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(#p8e5443743e)\" 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=\"#m3b2b24f6fc\" 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=\"mc31b560ca4\" d=\"M 0 0  L -3.5 0  \" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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)\">FP16 LoRA</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mc31b560ca4\" 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)\">NF4 prompted</text>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mc31b560ca4\" 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)\">NF4 QLoRA</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(#pf52e5c343e)\" 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(#pf52e5c343e)\" 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(#pf52e5c343e)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_16\">\n",
       "    <path d=\"M 343.682604 171.984545  L 343.682604 171.984545  L 343.682604 201.590606  L 343.682604 201.590606  z \" clip-path=\"url(#pf52e5c343e)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_17\">\n",
       "    <path d=\"M 343.682604 208.992121  L 443.570938 208.992121  L 443.570938 238.598182  L 343.682604 238.598182  z \" clip-path=\"url(#pf52e5c343e)\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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(#pf52e5c343e)\" 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=\"#m3b2b24f6fc\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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(#p93f6a31ab1)\" 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(#p93f6a31ab1)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_25\">\n",
       "    <path d=\"M 570.054271 134.97697  L 686.59066 134.97697  L 686.59066 164.58303  L 570.054271 164.58303  z \" clip-path=\"url(#p93f6a31ab1)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_26\">\n",
       "    <path d=\"M 570.054271 171.984545  L 582.540312 171.984545  L 582.540312 201.590606  L 570.054271 201.590606  z \" clip-path=\"url(#p93f6a31ab1)\" style=\"fill: #357e72\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_27\">\n",
       "    <path d=\"M 570.054271 208.992121  L 740.69684 208.992121  L 740.69684 238.598182  L 570.054271 238.598182  z \" clip-path=\"url(#p93f6a31ab1)\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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(#p93f6a31ab1)\" 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=\"#m3b2b24f6fc\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"#mc31b560ca4\" 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=\"p8e5443743e\">\n",
       "   <rect x=\"117.310938\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"pf52e5c343e\">\n",
       "   <rect x=\"343.682604\" y=\"52.08\" width=\"199.776667\" height=\"195.4\"/>\n",
       "  </clipPath>\n",
       "  <clipPath id=\"p93f6a31ab1\">\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": [
      "Result files: results/01-report.json, results/01-predictions.json, results/01-exact.svg\n"
     ]
    }
   ],
   "source": [
    "report = save_results(\"01\", scores, training, [\n",
    "    (\"FP16 prompted\", \"FP16 LoRA\"),\n",
    "    (\"NF4 prompted\", \"NF4 QLoRA\"),\n",
    "    (\"FP16 LoRA\", \"NF4 QLoRA\"),\n",
    "], catalogue_version=CATALOG_VERSION, training_keys=[row.key for row in chosen])\n",
    "print(\"Result files: results/01-report.json, results/01-predictions.json, results/01-exact.svg\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15058ac8",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "[Return to Chapter 1 in local Recohut Docs](http://localhost:3020/courses/advanced-llm-fine-tuning/01-port-a-training-recipe) to compare exact records by layout and peak memory on the T4.\n",
    "\n",
    "### Further reading\n",
    "\n",
    "The [QLoRA paper](https://arxiv.org/abs/2305.14314) studies the memory trade-off at\n",
    "substantially larger sizes. Early [instruction tuning](https://arxiv.org/abs/2109.01652),\n",
    "[PPO-based alignment](https://arxiv.org/abs/2203.02155), and\n",
    "[FSDP](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html)\n",
    "explain related choices but do not form extra arms in this lab."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
