{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3f5d8ac2",
   "metadata": {},
   "source": [
    "# 15 · Release a document parser\n",
    "\n",
    "**Question.** Which training and serving changes meet a predeclared release gate?\n",
    "\n",
    "Rebuild the supervised invoice parser on the same catalogue and base revision. Compare the rules baseline, prompted vision model, supervised adapter and verifiable-reward adapter. Then benchmark generation separately and restore the incumbent.\n",
    "\n",
    "[Open the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/4-release/15-release-a-document-parser)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fafc1d49",
   "metadata": {},
   "source": [
    "## Which software and hardware does this lab use?\n",
    "\n",
    "The same quantised base and processor serve every branch. Only language-backbone adapters train. The notebook stops early if CUDA is unavailable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdcfaf14",
   "metadata": {},
   "outputs": [],
   "source": [
    "import subprocess, sys\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n",
    "                \"transformers==4.51.3\", \"peft==0.15.2\", \"accelerate==1.6.0\",\n",
    "                \"bitsandbytes==0.50.2\", \"pillow==11.3.0\", \"datasets==3.6.0\",\n",
    "                \"pypdfium2==4.30.0\"], check=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e09d6ae0",
   "metadata": {},
   "source": [
    "## How are invoice families held out?\n",
    "\n",
    "Original synthetic records are split by supplier-and-layout family before rendering. The same example retains its family identifier across image derivatives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02f56540",
   "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": "code",
   "execution_count": null,
   "id": "4a0e3879",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Original invoice page and chart rendering for the document notebooks.\"\"\"\n",
    "\n",
    "from PIL import Image, ImageDraw, ImageFont\n",
    "\n",
    "# The notebooks inline this file after the fixture contract. The fallback import\n",
    "# keeps the same functions usable in ordinary Python.\n",
    "if \"invoice_text\" not in globals():\n",
    "    from invoice_fixtures import Invoice, invoice_record, invoice_text\n",
    "\n",
    "\n",
    "def _font(size: int, bold: bool = False):\n",
    "    name = \"DejaVuSans-Bold.ttf\" if bold else \"DejaVuSans.ttf\"\n",
    "    try:\n",
    "        return ImageFont.truetype(name, size)\n",
    "    except OSError:\n",
    "        return ImageFont.load_default(size=size)\n",
    "\n",
    "\n",
    "def invoice_image(invoice: Invoice) -> Image.Image:\n",
    "    image = Image.new(\"RGB\", (896, 624), \"#faf9f5\")\n",
    "    draw = ImageDraw.Draw(image)\n",
    "    fields = invoice_text(invoice).splitlines()\n",
    "    accents = {\n",
    "        \"register\": \"#245067\", \"memo\": \"#732f41\", \"checkout\": \"#30614e\", \"ledger\": \"#2a3e72\",\n",
    "        \"packing\": \"#31535c\", \"remittance\": \"#694323\", \"service\": \"#4b3f65\", \"notice\": \"#73422d\",\n",
    "    }\n",
    "    accent = accents.get(invoice.layout, \"#4a5744\")\n",
    "    draw.rounded_rectangle((32, 29, 864, 595), 11, fill=\"white\", outline=\"#d9dad8\", width=2)\n",
    "    draw.rectangle((33, 34, 863, 42), fill=accent)\n",
    "    draw.text((64, 63), \"Supplier billing\", font=_font(28, bold=True), fill=accent)\n",
    "    draw.text((64, 102), \"Original synthetic course fixture\", font=_font(15), fill=\"#5b6462\")\n",
    "    draw.line((61, 134, 835, 134), fill=\"#d5dad8\", width=2)\n",
    "    for i, line in enumerate(fields):\n",
    "        y = 153 + 35 * i\n",
    "        if i % 2:\n",
    "            draw.rectangle((58, y - 3, 837, y + 28), fill=\"#f5f7f6\")\n",
    "        is_heading = line.startswith((\"Description |\", \"Service |\", \"One-off charges\"))\n",
    "        draw.text((65, y), line, fill=\"#233034\", font=_font(20, bold=is_heading))\n",
    "        if draw.textbbox((65, y), line, font=_font(20, bold=is_heading))[2] >= 837:\n",
    "            raise ValueError(f\"Invoice field did not fit the page: {line!r}\")\n",
    "    return image\n",
    "\n",
    "\n",
    "def spend_chart(invoice: Invoice, *, varied: bool = False):\n",
    "    \"\"\"Render line-item spending as labelled bars with separately known cents.\"\"\"\n",
    "    gold = invoice_record(invoice)\n",
    "    values = [row[\"quantity\"] * row[\"unit_minor\"] for row in gold[\"line_items\"]]\n",
    "    image = Image.new(\"RGB\", (896, 512), \"#ffffff\")\n",
    "    draw = ImageDraw.Draw(image)\n",
    "    accent = \"#266978\" if varied else \"#27598b\"\n",
    "    order = list(reversed(range(len(values)))) if varied else list(range(len(values)))\n",
    "    draw.text((48, 39), f\"Line item spending · {invoice.currency}\", fill=accent, font=_font(28, bold=True))\n",
    "    draw.text((48, 80), \"Total before tax per line item\", fill=\"#53575b\", font=_font(17))\n",
    "    largest = max(values)\n",
    "    rows = []\n",
    "    for position, index in enumerate(order):\n",
    "        row = gold[\"line_items\"][index]\n",
    "        value = values[index]\n",
    "        y = 141 + 86 * position\n",
    "        draw.text((51, y), row[\"description\"], font=_font(19), fill=\"#222222\")\n",
    "        money = f\"{value / 100:,.2f}\"\n",
    "        draw.text((734, y), money, font=_font(19, bold=True), fill=\"#222222\")\n",
    "        draw.rounded_rectangle((51, y + 34, 51 + int(value / largest * 650), y + 55), 4, fill=accent)\n",
    "        rows.append({\"description\": row[\"description\"], \"line_total_minor\": value})\n",
    "    return image, {\"currency\": invoice.currency, \"rows\": rows}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "815212a1",
   "metadata": {},
   "source": [
    "## Which tokens receive a loss?\n",
    "\n",
    "Both renders use the same image tokens. The prompt prefix must match the full rendered sequence exactly before the mask removes it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b81ddb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Bounded Qwen2-VL training and evaluation shared by the document notebooks.\"\"\"\n",
    "\n",
    "from dataclasses import dataclass\n",
    "from pathlib import Path\n",
    "import random\n",
    "from time import perf_counter\n",
    "\n",
    "import torch\n",
    "from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training\n",
    "from transformers import AutoProcessor, BitsAndBytesConfig, Qwen2VLForConditionalGeneration\n",
    "\n",
    "VISION_MODEL = \"Qwen/Qwen2-VL-2B-Instruct\"\n",
    "VISION_REV = \"1860c46f12b7449d0f5b426a7474ab715342bc65\"\n",
    "VISION_SEED = 42\n",
    "VISION_MAX_PIXELS = 576 * 28 * 28\n",
    "VISION_MAX_OUTPUT = 220\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class DocumentExample:\n",
    "    key: str\n",
    "    image: object\n",
    "    instruction: str\n",
    "    answer: str\n",
    "    group: str\n",
    "\n",
    "\n",
    "def processor_for_vision():\n",
    "    return AutoProcessor.from_pretrained(\n",
    "        VISION_MODEL, revision=VISION_REV, trust_remote_code=False,\n",
    "        min_pixels=4 * 28 * 28, max_pixels=VISION_MAX_PIXELS,\n",
    "    )\n",
    "\n",
    "\n",
    "def load_vision_base(trainable: bool = False):\n",
    "    if not torch.cuda.is_available():\n",
    "        raise RuntimeError(\"Select a GPU runtime. This vision lab uses CUDA.\")\n",
    "    quantisation = BitsAndBytesConfig(\n",
    "        load_in_4bit=True, bnb_4bit_quant_type=\"nf4\",\n",
    "        bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True,\n",
    "    )\n",
    "    base = Qwen2VLForConditionalGeneration.from_pretrained(\n",
    "        VISION_MODEL, revision=VISION_REV, trust_remote_code=False, use_safetensors=True,\n",
    "        torch_dtype=torch.float16, device_map={\"\": 0}, quantization_config=quantisation,\n",
    "        attn_implementation=\"sdpa\",\n",
    "    )\n",
    "    if trainable:\n",
    "        return prepare_model_for_kbit_training(base, gradient_checkpointing_kwargs={\"use_reentrant\": False})\n",
    "    return base.eval()\n",
    "\n",
    "\n",
    "def adapter_for_vision(base):\n",
    "    adapter = get_peft_model(\n",
    "        base, LoraConfig(r=8, lora_alpha=16, target_modules=[\"q_proj\", \"v_proj\"],\n",
    "                         lora_dropout=0.0, task_type=\"CAUSAL_LM\"),\n",
    "    )\n",
    "    trainable = [name for name, value in adapter.named_parameters() if value.requires_grad]\n",
    "    if not trainable or any(\".visual.\" in name or \"lora\" not in name for name in trainable):\n",
    "        raise RuntimeError(\"Expected language-backbone LoRA parameters only.\")\n",
    "    return adapter\n",
    "\n",
    "\n",
    "def encode_image(processor, item: DocumentExample, assistant: str | None = None):\n",
    "    chat = [{\"role\": \"user\", \"content\": [{\"type\": \"image\"}, {\"type\": \"text\", \"text\": item.instruction}]}]\n",
    "    if assistant is not None:\n",
    "        chat.append({\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": assistant}]})\n",
    "    template = processor.apply_chat_template(chat, tokenize=False, add_generation_prompt=assistant is None)\n",
    "    # Use the exact same pixels and processor settings in the prompt and full sequence.\n",
    "    inputs = processor(text=[template], images=[item.image], padding=False, return_tensors=\"pt\")\n",
    "    return inputs.to(\"cuda\")\n",
    "\n",
    "\n",
    "def sft_feature(processor, item: DocumentExample):\n",
    "    prompt = encode_image(processor, item)\n",
    "    full = encode_image(processor, item, item.answer)\n",
    "    labels = full[\"input_ids\"].clone()\n",
    "    prefix = prompt[\"input_ids\"]\n",
    "    width = prefix.shape[1]\n",
    "    if width >= labels.shape[1] or not torch.equal(labels[:, :width], prefix):\n",
    "        raise ValueError(f\"Chat template changed its expanded image prefix for {item.key}.\")\n",
    "    labels[:, :width] = -100\n",
    "    if not torch.any(labels[:, width:] != -100):\n",
    "        raise ValueError(\"The prompt mask removed the entire target.\")\n",
    "    return full, labels\n",
    "\n",
    "\n",
    "def fit_vision(adapter, processor, items, *, updates: int, accumulation: int = 2):\n",
    "    random.seed(VISION_SEED)\n",
    "    order = list(items)\n",
    "    random.shuffle(order)\n",
    "    if updates <= 0 or not order:\n",
    "        raise ValueError(\"Vision training needs a positive update budget and at least one example.\")\n",
    "    adapter.train()\n",
    "    optimiser = torch.optim.AdamW((p for p in adapter.parameters() if p.requires_grad), lr=1e-4)\n",
    "    torch.cuda.reset_peak_memory_stats()\n",
    "    torch.cuda.synchronize()\n",
    "    started = perf_counter()\n",
    "    history = []\n",
    "    for update in range(updates):\n",
    "        optimiser.zero_grad(set_to_none=True)\n",
    "        step_loss = 0.0\n",
    "        for j in range(accumulation):\n",
    "            features, labels = sft_feature(processor, order[(update * accumulation + j) % len(order)])\n",
    "            scalar = adapter(**features, labels=labels, use_cache=False).loss\n",
    "            if not torch.isfinite(scalar):\n",
    "                raise RuntimeError(f\"Non-finite vision SFT loss at step {update}.\")\n",
    "            (scalar / accumulation).backward()\n",
    "            step_loss += scalar.detach().item() / accumulation\n",
    "        norm = torch.nn.utils.clip_grad_norm_(adapter.parameters(), 1.0)\n",
    "        if not torch.isfinite(norm):\n",
    "            raise RuntimeError(\"Non-finite adapter gradient.\")\n",
    "        optimiser.step()\n",
    "        history.append(step_loss)\n",
    "    torch.cuda.synchronize()\n",
    "    adapter.eval()\n",
    "    return {\"updates\": updates, \"examples_seen\": updates * accumulation, \"seconds\": perf_counter() - started,\n",
    "            \"peak_gib\": torch.cuda.max_memory_allocated() / 2**30, \"loss\": history}\n",
    "\n",
    "\n",
    "@torch.inference_mode()\n",
    "def generate_vision(model, processor, example, *, max_new_tokens=VISION_MAX_OUTPUT, **options):\n",
    "    inputs = encode_image(processor, example)\n",
    "    output = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False, **options)\n",
    "    ids = output[0, inputs[\"input_ids\"].shape[1]:]\n",
    "    value = processor.tokenizer.decode(ids, skip_special_tokens=True).strip()\n",
    "    stops = model.generation_config.eos_token_id\n",
    "    eos = stops if isinstance(stops, (list, tuple)) else [stops]\n",
    "    return {\"text\": value, \"tokens\": ids.cpu().tolist(), \"complete\": bool(len(ids) and ids[-1].item() in eos)}\n",
    "\n",
    "\n",
    "def save_vision_adapter(model, path: str) -> Path:\n",
    "    target = Path(path)\n",
    "    model.save_pretrained(target, safe_serialization=True)\n",
    "    if not (target / \"adapter_model.safetensors\").is_file():\n",
    "        raise RuntimeError(f\"Missing adapter weights at {target}\")\n",
    "    return target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a220bfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from dataclasses import asdict\n",
    "from importlib.metadata import version\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "import hashlib\n",
    "import random\n",
    "import shutil\n",
    "\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name(0):\n",
    "    raise RuntimeError(\"This notebook needs a Colab T4 runtime.\")\n",
    "torch.manual_seed(VISION_SEED)\n",
    "START = perf_counter()\n",
    "print(\"GPU\", torch.cuda.get_device_name(0))\n",
    "for package in (\"torch\", \"transformers\", \"peft\", \"bitsandbytes\", \"Pillow\"):\n",
    "    print(package, version(package))\n",
    "\n",
    "def paired_family_exact(before, after, get_exact, seed=42):\n",
    "    baseline = {row[\"key\"]: row for row in before}\n",
    "    assert len(baseline) == len(before) == len(after)\n",
    "    assert set(baseline) == {row[\"key\"] for row in after}\n",
    "    deltas = {}\n",
    "    for current in after:\n",
    "        previous = baseline[current[\"key\"]]\n",
    "        assert previous[\"family\"] == current[\"family\"]\n",
    "        deltas.setdefault(current[\"family\"], []).append(get_exact(current) - get_exact(previous))\n",
    "    families = sorted(deltas)\n",
    "    if len(families) < 2:\n",
    "        return {\"families\":len(families),\"interval_pp\":None}\n",
    "    rng = random.Random(seed)\n",
    "    draws = []\n",
    "    for _ in range(2000):\n",
    "        rows = [delta for family in rng.choices(families, k=len(families)) for delta in deltas[family]]\n",
    "        draws.append(100 * sum(rows) / len(rows))\n",
    "    draws.sort()\n",
    "    return {\"families\":len(families),\n",
    "            \"delta_pp\":100 * sum(sum(values) for values in deltas.values()) / len(after),\n",
    "            \"interval_pp\":[draws[49],draws[1949]]}\n",
    "\n",
    "def feature_manifest(items, updates, accumulation):\n",
    "    return {\n",
    "        \"model\":VISION_MODEL, \"revision\":VISION_REV, \"catalogue\":CATALOG_VERSION,\n",
    "        \"updates\":updates, \"accumulation\":accumulation, \"seed\":VISION_SEED,\n",
    "        \"features_sha256\":hashlib.sha256(json.dumps([\n",
    "            [item.key, item.group, item.instruction, item.answer,\n",
    "             hashlib.sha256(item.image.tobytes()).hexdigest()] for item in items\n",
    "        ],ensure_ascii=False).encode()).hexdigest(),\n",
    "    }\n",
    "\n",
    "def write_results(filename, payload):\n",
    "    model = {\"id\": VISION_MODEL, \"revision\": VISION_REV}\n",
    "    versions = {p: version(p) for p in (\"torch\",\"transformers\",\"peft\",\"bitsandbytes\",\"Pillow\",\"datasets\")}\n",
    "    experiment = {\"elapsed_seconds\": round(perf_counter()-START, 3),\n",
    "                  \"gpu\": torch.cuda.get_device_name(0), \"model\": model,\n",
    "                  \"packages\": versions, \"catalogue\": CATALOG_VERSION, \"seed\": VISION_SEED}\n",
    "    with open(filename, \"w\", encoding=\"utf-8\") as handle:\n",
    "        json.dump({**experiment, **payload}, handle, indent=2, ensure_ascii=False)\n",
    "    print(json.dumps({**experiment, **payload}, ensure_ascii=False))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64320aa4",
   "metadata": {},
   "source": [
    "## What would warrant a release?\n",
    "\n",
    "Freeze quality gates and output contracts before training. Count missing fields and rows, unparseable responses, and premature termination. Use an independent external invoice benchmark for header fields only."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "628622c9",
   "metadata": {},
   "outputs": [],
   "source": [
    "GATES={\"valid\":0.98,\"complete\":0.98,\"exact_complete\":0.90,\"slice_regression_pp\":3.0}\n",
    "TASK = VISIBLE_CONTRACT\n",
    "TRAIN_UPDATES=32\n",
    "RL_GROUPS=8\n",
    "ROLLOUTS=3\n",
    "MAX_TOKENS=220\n",
    "SEED=42\n",
    "EXTERNAL_REV=\"446bab08662790cb39457792243bff5704373b95\"\n",
    "\n",
    "def cap_item(row):\n",
    "    return DocumentExample(row.key,invoice_image(row),TASK,json.dumps(invoice_record(row),ensure_ascii=False),row.family)\n",
    "\n",
    "def cap_chart_item(row):\n",
    "    image,target=spend_chart(row)\n",
    "    prompt=\"Read the bar chart. Return exactly one JSON object with currency and rows. Each row must contain description and line_total_minor in cents. Preserve visual row order.\"\n",
    "    return DocumentExample(row.key,image,prompt,json.dumps(target,ensure_ascii=False),row.family)\n",
    "\n",
    "training=[cap_item(row) for row in examples_for(\"train\",72)]+[\n",
    "    cap_chart_item(row) for row in examples_for(\"train\",24)]\n",
    "rollouts=examples_for(\"dev\",RL_GROUPS)\n",
    "benchmark=examples_for(\"release\",84)\n",
    "assert len({row.family for row in benchmark})==10\n",
    "assert sum(row.locale in {\"de-DE\",\"fr-FR\"} for row in benchmark) >= 30\n",
    "assert sum(row.locale not in {\"de-DE\",\"fr-FR\"} for row in benchmark) >= 30\n",
    "assert {item.group for item in training}.isdisjoint(row.family for row in rollouts+benchmark)\n",
    "test_hash=hashlib.sha256(\"\\n\".join(row.key for row in benchmark).encode()).hexdigest()\n",
    "print(\"Release gates:\",GATES,\"cases:\",len(benchmark),\"release split SHA256:\",test_hash)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a0083da",
   "metadata": {},
   "source": [
    "## Which Lab 08 artefact is the incumbent?\n",
    "\n",
    "Verify the checked notebook and adapter files before spending T4 time. The paired course run requires the exported Lab 08 adapter. Explicit standalone runs record a separate refit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72155185",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Read a passed Lesson 08 export and verify the capstone's input contract.\"\"\"\n",
    "\n",
    "import hashlib\n",
    "import json\n",
    "import os\n",
    "from pathlib import Path\n",
    "import re\n",
    "\n",
    "\n",
    "def sha256_file(path):\n",
    "    with Path(path).open(\"rb\") as stream:\n",
    "        return hashlib.file_digest(stream, \"sha256\").hexdigest()\n",
    "\n",
    "\n",
    "def read_prior_handoff(expected_features, output_root=None, explicit_dir=None):\n",
    "    root = Path(output_root or Path.cwd().parent).resolve()\n",
    "    explicit = explicit_dir or os.environ.get(\"LAB08_HANDOFF_DIR\")\n",
    "    if explicit:\n",
    "        candidates = [Path(explicit).resolve()]\n",
    "    else:\n",
    "        candidates = [\n",
    "            folder for folder in root.glob(\"08-extract-tables-and-charts-*\")\n",
    "            if (folder / \"receipt.json\").is_file()\n",
    "            and json.loads((folder / \"receipt.json\").read_text())[\"status\"] == \"passed\"\n",
    "        ]\n",
    "    if not candidates:\n",
    "        return None\n",
    "    if len(candidates) != 1:\n",
    "        raise ValueError(\"Set LAB08_HANDOFF_DIR to select the approved Lab 08 job.\")\n",
    "    folder = candidates[0]\n",
    "    receipt = json.loads((folder / \"receipt.json\").read_text())\n",
    "    source = \"08-extract-tables-and-charts.ipynb\"\n",
    "    if receipt.get(\"status\") != \"passed\" or receipt.get(\"return_code\") != 0 or receipt.get(\"source\") != source:\n",
    "        raise ValueError(\"The Lab 08 receipt must name a successful run of the structure notebook.\")\n",
    "    if receipt[\"source_sha256\"] != sha256_file(folder / source):\n",
    "        raise ValueError(\"Lab 08 source notebook does not match its receipt.\")\n",
    "    if receipt[\"executed_sha256\"] != sha256_file(folder / \"executed.ipynb\"):\n",
    "        raise ValueError(\"Lab 08 executed notebook does not match its receipt.\")\n",
    "    payload = json.loads((folder / \"08_handoff.json\").read_text())\n",
    "    if payload[\"features\"] != expected_features:\n",
    "        raise ValueError(\"The Lab 08 feature recipe differs from the capstone recipe.\")\n",
    "    weights = folder / \"08_structure_adapter\"\n",
    "    adapter_config = json.loads((weights / \"adapter_config.json\").read_text())\n",
    "    if (adapter_config.get(\"base_model_name_or_path\") != expected_features[\"model\"]\n",
    "            or adapter_config.get(\"r\") != 8 or adapter_config.get(\"lora_alpha\") != 16\n",
    "            or set(adapter_config.get(\"target_modules\", [])) != {\"q_proj\", \"v_proj\"}):\n",
    "        raise ValueError(\"The Lab 08 adapter configuration differs from the capstone recipe.\")\n",
    "    digest = sha256_file(weights / \"adapter_model.safetensors\")\n",
    "    if payload[\"adapter_sha256\"] != digest:\n",
    "        raise ValueError(\"Lab 08 adapter bytes differ from the handoff.\")\n",
    "    if (not re.fullmatch(r\"SF-\\d+\", payload[\"parity_key\"])\n",
    "            or not payload[\"parity_tokens\"]\n",
    "            or any(type(token) is not int or token < 0 for token in payload[\"parity_tokens\"])):\n",
    "        raise ValueError(\"The Lab 08 handoff has no valid greedy-token parity case.\")\n",
    "    return weights, payload, receipt\n",
    "\n",
    "\n",
    "def require_token_parity(item, saved_key, saved_tokens, observed_tokens):\n",
    "    if item.key != saved_key or list(observed_tokens) != list(saved_tokens):\n",
    "        raise ValueError(\"The restored adapter changed the fixed-case greedy tokens.\")\n",
    "\n",
    "pins = {\"transformers\": \"4.51.3\", \"peft\": \"0.15.2\", \"accelerate\": \"1.6.0\",\n",
    "        \"bitsandbytes\": \"0.50.2\", \"pillow\": \"11.3.0\", \"pypdfium2\": \"4.30.0\"}\n",
    "for package, wanted in pins.items():\n",
    "    if version(package) != wanted:\n",
    "        raise RuntimeError(f\"Expected {package}=={wanted}, got {version(package)}\")\n",
    "get_ipython().run_line_magic(\"config\", \"InlineBackend.figure_formats = ['svg']\")\n",
    "expected_features=feature_manifest(training,TRAIN_UPDATES,2)\n",
    "prior_handoff=read_prior_handoff(expected_features)\n",
    "if not prior_handoff and os.environ.get(\"LAB15_STANDALONE_REFIT\") != \"1\":\n",
    "    raise RuntimeError(\"Stage the verified Lab 08 export or explicitly enable standalone refit.\")\n",
    "assert len({item.key for item in benchmark}) == len(benchmark)\n",
    "assert {item.key for item in training}.isdisjoint(row.key for row in rollouts+benchmark)\n",
    "assert {row.family for row in rollouts}.isdisjoint(row.family for row in benchmark)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d25dc5f",
   "metadata": {},
   "source": [
    "## Which outputs fool a usable-looking verifier?\n",
    "\n",
    "The training reward prefers schema-valid responses whose row content, currency and totals match the printed values. The offline release guard checks currency and row identities using an independent verified text view of the same fixture. A production document with only a page image would require its own trusted text path before using this guard."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c2ce31b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter\n",
    "from copy import deepcopy\n",
    "from gc import collect\n",
    "\n",
    "SOURCE_ROW = re.compile(\n",
    "    r\"^(?:([A-Za-z ]+): .* each for [0-9]+ units|\"\n",
    "    r\"[0-9]+ x ([A-Za-z ]+) @ .* per unit|\"\n",
    "    r\"Unit .* / [0-9]+ times / ([A-Za-z ]+))$\",\n",
    "    re.MULTILINE,\n",
    ")\n",
    "\n",
    "def verified_source_guard(text, source_text):\n",
    "    value=parse_record(text)\n",
    "    if value is None or not all(value[name] is not None for name in (\"invoice_id\",\"currency\",\"supplier\")):\n",
    "        return False\n",
    "    currencies=set(re.findall(r\"\\b(?:USD|GBP|EUR|CAD)\\b\",source_text))\n",
    "    expected=Counter(next(part for part in match.groups() if part is not None)\n",
    "                     for match in SOURCE_ROW.finditer(source_text))\n",
    "    observed=Counter(item[\"description\"] for item in value[\"line_items\"])\n",
    "    return currencies=={value[\"currency\"]} and bool(expected) and observed==expected\n",
    "\n",
    "def training_reward(text, expected, complete):\n",
    "    observed=parse_record(text)\n",
    "    if observed is None:\n",
    "        return -0.5\n",
    "    scalar_fields=(\"invoice_id\",\"issued_on\",\"supplier\",\"currency\",\"subtotal_minor\",\"tax_minor\",\"total_minor\")\n",
    "    field_score=sum(observed[k]==expected[k] for k in scalar_fields)/len(scalar_fields)\n",
    "    keys=(\"description\",\"quantity\",\"unit_minor\")\n",
    "    rows=lambda r:Counter(tuple(item[k] for k in keys) for item in r[\"line_items\"])\n",
    "    predicted,target=rows(observed),rows(expected)\n",
    "    f1=2*(predicted&target).total()/max(1,predicted.total()+target.total())\n",
    "    return 0.30*field_score+0.55*f1+0.15*int(complete)\n",
    "\n",
    "control_invoice=next(row for row in benchmark if len(row.items)>=2)\n",
    "control_source=invoice_text(control_invoice)\n",
    "check=invoice_record(control_invoice)\n",
    "wrong_currency=deepcopy(check)\n",
    "wrong_currency[\"currency\"]=\"GBP\" if check[\"currency\"]==\"USD\" else \"USD\"\n",
    "missing_row=deepcopy(check)\n",
    "missing_row[\"line_items\"].pop()\n",
    "assert training_reward(json.dumps(check),check,True)==1\n",
    "assert training_reward(json.dumps(wrong_currency),check,True)<1\n",
    "assert training_reward(json.dumps(missing_row),check,True)<1\n",
    "assert training_reward(json.dumps(check)[:-1],check,False)<0\n",
    "controls={\"grounded_record_accepted\":verified_source_guard(json.dumps(check),control_source),\n",
    "          \"wrong_currency_rejected\":not verified_source_guard(json.dumps(wrong_currency),control_source),\n",
    "          \"missing_row_rejected\":not verified_source_guard(json.dumps(missing_row),control_source),\n",
    "          \"truncated_record_rejected\":not verified_source_guard(json.dumps(check)[:-1],control_source)}\n",
    "assert all(controls.values()), controls\n",
    "print(\"Verified source controls:\",controls)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da156963",
   "metadata": {},
   "source": [
    "## Does one full-width policy update fit on the T4?\n",
    "\n",
    "Run one real update on a development invoice with three sampled completions forced to the generation cap. Diagnostic advantages guarantee backward passes. These diagnostic weights and rewards never enter the scored comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e93e834",
   "metadata": {},
   "outputs": [],
   "source": [
    "def rollout_for(model, processor, item, completion_width, temperature, force_width=False):\n",
    "    inputs=encode_image(processor,item)\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        result=model.generate(**inputs,max_new_tokens=completion_width,do_sample=True,\n",
    "                              temperature=temperature,top_k=0,top_p=1.0,\n",
    "                              min_new_tokens=completion_width if force_width else 0)\n",
    "    generated=result[:,inputs[\"input_ids\"].shape[1]:].clone()\n",
    "    eos=model.generation_config.eos_token_id\n",
    "    stops=eos if isinstance(eos,(tuple,list)) else [eos]\n",
    "    done=bool(generated.numel() and generated[0,-1].item() in stops)\n",
    "    return generated,processor.tokenizer.decode(generated[0],skip_special_tokens=True),done\n",
    "\n",
    "def sampled_logs(model,inputs,tokens,temperature):\n",
    "    n=inputs[\"input_ids\"].shape[1]\n",
    "    ids=torch.cat((inputs[\"input_ids\"],tokens),dim=1)\n",
    "    kwargs={key:value for key,value in inputs.items() if key not in {\"input_ids\",\"attention_mask\"}}\n",
    "    output=model(input_ids=ids,attention_mask=torch.ones_like(ids),use_cache=False,**kwargs)\n",
    "    logits=output.logits[:,n-1:-1,:].float()/temperature\n",
    "    return torch.log_softmax(logits,dim=-1).gather(-1,tokens[...,None]).squeeze(-1)\n",
    "\n",
    "def optimise_with_rewards(model,processor,training_invoices, *, profile_only=False):\n",
    "    optimiser=torch.optim.AdamW((p for p in model.parameters() if p.requires_grad),lr=1e-5)\n",
    "    history=[]\n",
    "    torch.manual_seed(SEED)\n",
    "    torch.cuda.reset_peak_memory_stats()\n",
    "    torch.cuda.synchronize()\n",
    "    started=perf_counter()\n",
    "    for row in training_invoices:\n",
    "        item=cap_item(row)\n",
    "        inputs=encode_image(processor,item)\n",
    "        generated=[rollout_for(model,processor,item,MAX_TOKENS,0.75,force_width=profile_only) for _ in range(ROLLOUTS)]\n",
    "        generated=[run for run in generated if run[0].numel()]\n",
    "        rewards=[training_reward(text,invoice_record(row),done) for _,text,done in generated]\n",
    "        if profile_only and any(run[0].shape[1] != MAX_TOKENS for run in generated):\n",
    "            raise RuntimeError(\"Profile completions did not reach the fixed token width.\")\n",
    "        profile_rewards=[-1.0,0.0,1.0] if profile_only else rewards\n",
    "        values=torch.tensor(profile_rewards,dtype=torch.float32)\n",
    "        spread=values.std(unbiased=False).item() if len(rewards)>1 else 0\n",
    "        losses=[]\n",
    "        if spread>1e-8:\n",
    "            normalised=((values-values.mean())/(spread+1e-6)).tolist()\n",
    "            model.eval()\n",
    "            with torch.no_grad():\n",
    "                old=[sampled_logs(model,inputs,tokens,0.75).detach() for tokens,_,_ in generated]\n",
    "            model.train()\n",
    "            for _ in range(1 if profile_only else 2):\n",
    "                optimiser.zero_grad(set_to_none=True)\n",
    "                group_loss=0.0\n",
    "                for (tokens,_,_),previous,advantage in zip(generated,old,normalised,strict=True):\n",
    "                    ratio=(sampled_logs(model,inputs,tokens,0.75)-previous).exp()\n",
    "                    loss=-torch.minimum(ratio*advantage,ratio.clamp(0.8,1.2)*advantage).mean()/len(old)\n",
    "                    if not torch.isfinite(loss):\n",
    "                        raise RuntimeError(\"Non-finite policy loss.\")\n",
    "                    loss.backward()\n",
    "                    group_loss+=loss.detach().item()\n",
    "                norm=torch.nn.utils.clip_grad_norm_(model.parameters(),1.0)\n",
    "                if not torch.isfinite(norm):\n",
    "                    raise RuntimeError(\"Non-finite reward gradient.\")\n",
    "                optimiser.step()\n",
    "                losses.append(group_loss)\n",
    "        history.append({\"key\":row.key,\"rewards\":rewards,\"objective_reward_spread\":spread,\"token_lengths\":[run[0].shape[1] for run in generated],\"losses\":losses})\n",
    "    torch.cuda.synchronize()\n",
    "    model.eval()\n",
    "    return {\"groups\":history,\"steps\":sum(len(x[\"losses\"]) for x in history),\n",
    "            \"elapsed_seconds\":perf_counter()-started,\"peak_gib\":torch.cuda.max_memory_allocated()/2**30}\n",
    "\n",
    "\n",
    "processor=processor_for_vision()\n",
    "entry_free,_=torch.cuda.mem_get_info()\n",
    "if entry_free < 12 * 2**30:\n",
    "    raise RuntimeError(\"Start the capstone profile with at least 12 GiB free on the T4.\")\n",
    "probe=max(rollouts,key=lambda row:encode_image(processor,cap_item(row))[\"input_ids\"].shape[1])\n",
    "torch.cuda.empty_cache()\n",
    "start_allocated=torch.cuda.memory_allocated()\n",
    "torch.manual_seed(SEED)\n",
    "probe_model=load_vision_base(trainable=True)\n",
    "if prior_handoff:\n",
    "    probe_model=PeftModel.from_pretrained(probe_model,prior_handoff[0],is_trainable=True)\n",
    "else:\n",
    "    probe_model=adapter_for_vision(probe_model)\n",
    "profile=optimise_with_rewards(probe_model,processor,[probe],profile_only=True)\n",
    "profile[\"entry_free_gib\"]=entry_free/2**30\n",
    "profile[\"peak_reserved_gib\"]=torch.cuda.max_memory_reserved()/2**30\n",
    "del probe_model\n",
    "collect()\n",
    "torch.cuda.empty_cache()\n",
    "profile[\"retained_bytes\"]=max(0,torch.cuda.memory_allocated()-start_allocated)\n",
    "Path(\"15_t4_profile.json\").write_text(json.dumps(profile,indent=2),encoding=\"utf-8\")\n",
    "print(json.dumps(profile,indent=2))\n",
    "if (profile[\"steps\"] != 1 or profile[\"elapsed_seconds\"] > 90 or profile[\"peak_gib\"] > 10\n",
    "        or profile[\"peak_reserved_gib\"] > 12 or profile[\"retained_bytes\"] > 128*2**20\n",
    "        or profile[\"peak_reserved_gib\"]*2**30 > entry_free-2*2**30):\n",
    "    raise RuntimeError(\"The one-update capstone profile exceeded the T4 limits.\")\n",
    "torch.manual_seed(SEED)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d6c39a1",
   "metadata": {},
   "source": [
    "## How good are the starting points?\n",
    "\n",
    "The rules see verified text. The model sees the rendered image. Evaluations use the same release rows and deterministic decoding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb1dc14a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mean_field(entries,key):\n",
    "    return sum(entry[key] for entry in entries)/len(entries)\n",
    "\n",
    "def evaluate_release(model):\n",
    "    scored=[]\n",
    "    for row in benchmark:\n",
    "        response=generate_vision(model,processor,cap_item(row),max_new_tokens=MAX_TOKENS)\n",
    "        raw=score_record(response[\"text\"],row)\n",
    "        scored.append({\"key\":row.key,\"family\":row.family,\"layout\":row.layout,\"locale\":row.locale,\n",
    "                       \"complete\":response[\"complete\"],\"guard\":verified_source_guard(response[\"text\"],invoice_text(row)),\n",
    "                       \"completion\":response[\"text\"],**raw})\n",
    "    return scored\n",
    "\n",
    "def compact(entries):\n",
    "    metrics={metric:mean_field(entries,metric) for metric in (\"valid\",\"exact\",\"fields\",\"row_f1\",\"complete\")}\n",
    "    metrics[\"exact_complete\"]=sum(row[\"exact\"] and row[\"complete\"] for row in entries)/len(entries)\n",
    "    return metrics\n",
    "\n",
    "baseline_model=load_vision_base()\n",
    "baseline=evaluate_release(baseline_model)\n",
    "rules=[score_record(rules_extract(invoice_text(row)),row) for row in benchmark]\n",
    "print(\"Rules exact:\",mean_field(rules,\"exact\"))\n",
    "print(\"Frozen VLM:\",compact(baseline))\n",
    "del baseline_model\n",
    "collect()\n",
    "torch.cuda.empty_cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69d8d6ee",
   "metadata": {},
   "source": [
    "## Can we recover the supervised incumbent?\n",
    "\n",
    "Use the completed lesson 8 adapter when the queue has its manifest. Check the features, adapter digest and fixed anchor output before training on rewards. A standalone run can rebuild the same recipe and records that path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2eb00ca0",
   "metadata": {},
   "outputs": [],
   "source": [
    "if prior_handoff:\n",
    "    weights,handoff,source_receipt=prior_handoff\n",
    "    model=PeftModel.from_pretrained(load_vision_base(trainable=True),weights,is_trainable=True).eval()\n",
    "    anchor=cap_item(examples_for(\"familiar\",1)[0])\n",
    "    require_token_parity(anchor,handoff[\"parity_key\"],handoff[\"parity_tokens\"],\n",
    "                         generate_vision(model,processor,anchor)[\"tokens\"])\n",
    "    sft_record={\"path\":\"lesson_08\",\"feature_manifest\":expected_features,\n",
    "                \"adapter_sha256\":handoff[\"adapter_sha256\"],\n",
    "                \"source_sha256\":source_receipt[\"source_sha256\"],\n",
    "                \"executed_sha256\":source_receipt[\"executed_sha256\"],\"anchor_token_parity\":True}\n",
    "else:\n",
    "    model=adapter_for_vision(load_vision_base(trainable=True))\n",
    "    sft_record={\"path\":\"standalone_refit\",\"feature_manifest\":expected_features,**fit_vision(\n",
    "        model,processor,training,updates=TRAIN_UPDATES,accumulation=2)}\n",
    "sft=evaluate_release(model)\n",
    "incumbent=save_vision_adapter(model,\"15_incumbent_adapter\")\n",
    "incumbent_sha=hashlib.sha256((incumbent/\"adapter_model.safetensors\").read_bytes()).hexdigest()\n",
    "fixture=cap_item(benchmark[0])\n",
    "incumbent_tokens=generate_vision(model,processor,fixture,max_new_tokens=MAX_TOKENS)[\"tokens\"]\n",
    "serving_config={\"model\":VISION_MODEL,\"revision\":VISION_REV,\"adapter_sha256\":incumbent_sha,\n",
    "                \"max_new_tokens\":MAX_TOKENS,\"decoding\":\"greedy\",\"max_pixels\":VISION_MAX_PIXELS}\n",
    "Path(\"15_incumbent_serving.json\").write_text(json.dumps(serving_config,indent=2),encoding=\"utf-8\")\n",
    "print(\"Supervised release set:\",compact(sft),\"adapter SHA256:\",incumbent_sha)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c91d2b4a",
   "metadata": {},
   "source": [
    "## Does an image-based reward help?\n",
    "\n",
    "Sample three completions per document. Score each independently, centre and scale the scores within a group, and skip groups with no reward variation. Re-evaluate token log probabilities under the frozen rollout policy and limit the ratio during two optimisation passes. This is a small reference-free GRPO comparison with a fixed generation budget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c06ef7a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "rl_record=optimise_with_rewards(model,processor,rollouts)\n",
    "rl=evaluate_release(model)\n",
    "candidate=save_vision_adapter(model,\"15_reward_adapter\")\n",
    "candidate_sha=hashlib.sha256((candidate/\"adapter_model.safetensors\").read_bytes()).hexdigest()\n",
    "print(\"Reward updates:\",rl_record[\"steps\"],\"candidate SHA256:\",candidate_sha)\n",
    "print(\"Reward-adapted release set:\",compact(rl))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fcfccc7",
   "metadata": {},
   "source": [
    "## How does the candidate handle an independent fixture source?\n",
    "\n",
    "Read four pinned, single-page synthetic invoices from an external benchmark. Its labels describe totals and line amounts rather than our quantity and unit-price contract, so compare only the documented overlapping header fields. Keep this slice separate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b3b8936",
   "metadata": {},
   "outputs": [],
   "source": [
    "from decimal import Decimal\n",
    "from huggingface_hub import hf_hub_download\n",
    "\n",
    "import pypdfium2\n",
    "\n",
    "EXTERNAL_DATA=\"drew-ipp/invoice-extraction-benchmark\"\n",
    "EXTERNAL_IDS=(\"clean-us-clean-simple\",\"clean-de-grid-eu-decimals\",\n",
    "              \"clean-fr-right-header\",\"clean-gb-mono-plain\")\n",
    "def download_external(path):\n",
    "    return Path(hf_hub_download(EXTERNAL_DATA,\"corpus/v1/\"+path,repo_type=\"dataset\",revision=EXTERNAL_REV))\n",
    "\n",
    "def external_headers(model):\n",
    "    rows=[]\n",
    "    for key in EXTERNAL_IDS:\n",
    "        label=json.loads(download_external(f\"answers/{key}.json\").read_text())\n",
    "        raw=download_external(label[\"file\"]).read_bytes()\n",
    "        if hashlib.sha256(raw).hexdigest()!=label[\"sha256\"]:\n",
    "            raise ValueError(f\"Benchmark bytes differ for {key}.\")\n",
    "        pdf=pypdfium2.PdfDocument(raw)\n",
    "        try:\n",
    "            image=pdf[0].render(scale=1.25).to_pil().convert(\"RGB\").copy()\n",
    "        finally:\n",
    "            pdf.close()\n",
    "        output=generate_vision(model,processor,DocumentExample(key,image,TASK,\"\",key),max_new_tokens=MAX_TOKENS)\n",
    "        gold=label[\"expected\"]\n",
    "        cents=lambda value:int((Decimal(str(value))*100).quantize(Decimal(\"1\"))) if value is not None else None\n",
    "        target={\"invoice_id\":gold[\"invoice_number\"],\"supplier\":gold[\"vendor_name\"],\n",
    "                \"currency\":gold[\"currency\"],\"total_minor\":cents(gold[\"total\"])}\n",
    "        observed=parse_record(output[\"text\"])\n",
    "        rows.append({\"key\":key,\"valid\":observed is not None,\n",
    "                     \"completion\":output[\"text\"],\"gold\":target,\"fields\":{name:observed is not None and observed.get(name)==truth for name,truth in target.items()}})\n",
    "    return rows\n",
    "\n",
    "external=external_headers(model)\n",
    "print(\"Independent header checks:\",external)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ca206bd",
   "metadata": {},
   "source": [
    "## Will speculative decoding preserve the answer?\n",
    "\n",
    "Benchmark ordinary greedy decoding and prompt lookup on interleaved runs with the same checkpoint. Refuse latency claims when the runtime cannot use the mode or when generated tokens differ."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9f43463",
   "metadata": {},
   "outputs": [],
   "source": [
    "import statistics\n",
    "Q=benchmark[:6]\n",
    "def latency_report(model):\n",
    "    jobs=[cap_item(row) for row in Q]\n",
    "    if rl_record[\"steps\"]==0:\n",
    "        disposition=\"no policy gradient signal\"\n",
    "    else:\n",
    "        disposition=\"completed\"\n",
    "    try:\n",
    "        generate_vision(model,processor,jobs[0],max_new_tokens=MAX_TOKENS)\n",
    "        generate_vision(model,processor,jobs[0],max_new_tokens=MAX_TOKENS,prompt_lookup_num_tokens=4)\n",
    "    except (AttributeError, TypeError, ValueError, NotImplementedError) as exc:\n",
    "        return {\"status\":\"unsupported\",\"reason\":str(exc),\"training\":disposition}\n",
    "    trial=[]\n",
    "    for index,item in enumerate(jobs):\n",
    "        results={}\n",
    "        settings=[(\"greedy\",{}),(\"lookup\",{\"prompt_lookup_num_tokens\":4})]\n",
    "        if index%2:\n",
    "            settings.reverse()\n",
    "        for label,kwargs in settings:\n",
    "            torch.cuda.synchronize()\n",
    "            started=perf_counter()\n",
    "            output=generate_vision(model,processor,item,max_new_tokens=MAX_TOKENS,**kwargs)\n",
    "            torch.cuda.synchronize()\n",
    "            results[label]={\"seconds\":perf_counter()-started,\"tokens\":output[\"tokens\"],\n",
    "                            \"complete\":output[\"complete\"]}\n",
    "        trial.append({\"key\":item.key,\"matches\":results[\"greedy\"][\"tokens\"]==results[\"lookup\"][\"tokens\"],\"results\":results})\n",
    "    if not all(r[\"matches\"] for r in trial):\n",
    "        return {\"status\":\"parity_failed\",\"pairs\":trial}\n",
    "    if not all(out[\"complete\"] for row in trial for out in row[\"results\"].values()):\n",
    "        return {\"status\":\"incomplete_output\",\"pairs\":trial}\n",
    "    durations={name: sorted(row[\"results\"][name][\"seconds\"] for row in trial) for name in (\"greedy\",\"lookup\")}\n",
    "    return {\"status\":\"parity_passed\",\"cases\":len(trial),\"pairs\":trial,\n",
    "            \"p50_seconds\":{k:statistics.median(a) for k,a in durations.items()},\n",
    "            \"p95_nearest_rank_seconds\":{k:a[-1] for k,a in durations.items()},\n",
    "            \"pages_per_gpu_second\":{k:len(a)/sum(a) for k,a in durations.items()}}\n",
    "\n",
    "serving=latency_report(model)\n",
    "print(\"Serving status:\",serving[\"status\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4bd4d64",
   "metadata": {},
   "source": [
    "## Can the earlier parser be restored?\n",
    "\n",
    "Release decisions use predeclared thresholds. If no group generated a useful reward gradient, record an inconclusive training result. Reload the saved supervised adapter from a fresh base and verify a documented request."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17803d6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "del model\n",
    "collect()\n",
    "torch.cuda.empty_cache()\n",
    "restored=PeftModel.from_pretrained(load_vision_base(trainable=True),incumbent,is_trainable=False).eval()\n",
    "restored_config=json.loads(Path(\"15_incumbent_serving.json\").read_text())\n",
    "assert restored_config[\"model\"]==VISION_MODEL and restored_config[\"revision\"]==VISION_REV\n",
    "assert restored_config[\"max_pixels\"]==VISION_MAX_PIXELS and restored_config[\"decoding\"]==\"greedy\"\n",
    "assert hashlib.sha256((incumbent/\"adapter_model.safetensors\").read_bytes()).hexdigest()==restored_config[\"adapter_sha256\"]\n",
    "restored_tokens=generate_vision(restored,processor,fixture,max_new_tokens=restored_config[\"max_new_tokens\"])[\"tokens\"]\n",
    "require_token_parity(fixture,fixture.key,incumbent_tokens,restored_tokens)\n",
    "scores=compact(rl)\n",
    "incumbent_scores=compact(sft)\n",
    "issues=[key for key,minimum in GATES.items() if key in scores and scores[key]<minimum]\n",
    "slice_deltas={}\n",
    "slice_checks={layout:(lambda r, layout=layout:r[\"layout\"]==layout) for layout in sorted({r[\"layout\"] for r in sft})}\n",
    "slice_checks.update({\"decimal_comma\":lambda r:r[\"locale\"] in {\"de-DE\",\"fr-FR\"},\n",
    "                     \"decimal_point\":lambda r:r[\"locale\"] not in {\"de-DE\",\"fr-FR\"}})\n",
    "for name, keep in slice_checks.items():\n",
    "    before=[r for r in sft if keep(r)]\n",
    "    after=[r for r in rl if keep(r)]\n",
    "    delta=100*(mean_field(after,\"exact\")-mean_field(before,\"exact\"))\n",
    "    applies=len(before)>=30\n",
    "    slice_deltas[name]={\"n\":len(before),\"delta_pp\":delta,\"gate_applied\":applies}\n",
    "    if applies and delta < -GATES[\"slice_regression_pp\"]:\n",
    "        issues.append(f\"slice regression: {name}\")\n",
    "if not rl_record[\"steps\"]:\n",
    "    issues.append(\"no nonzero rollout reward variation\")\n",
    "if not all(r[\"field_correct\"][\"currency\"] for r in rl if r[\"guard\"]):\n",
    "    issues.append(\"wrong currency escaped the fixture check\")\n",
    "if not all(r[\"row_f1\"] == 1 for r in rl if r[\"guard\"]):\n",
    "    issues.append(\"a missing or incorrect row escaped the fixture check\")\n",
    "decision=\"hold\" if issues else \"passes teaching quality gates\"\n",
    "write_results(\"15_release_results.json\",{\"decision\":decision,\"issues\":issues,\n",
    "    \"release_split_sha256\":test_hash,\"base\":baseline,\"rules\":rules,\"sft\":sft,\"reward_adapter\":rl,\n",
    "    \"paired_exact\":paired_family_exact(sft,rl,lambda row:row[\"exact\"]),\n",
    "    \"supervised_run\":sft_record,\"reward_run\":rl_record,\"external_headers\":external,\n",
    "    \"external_revision\":EXTERNAL_REV,\"serving\":serving,\"slice_deltas\":slice_deltas,\n",
    "    \"source_guard\":{\"controls\":controls,\"accepted\":sum(r[\"guard\"] for r in rl),\"total\":len(rl)},\n",
    "    \"candidate_sha256\":candidate_sha,\"incumbent_sha256\":incumbent_sha,\n",
    "    \"rollback\":{\"matches\":True,\"key\":fixture.key,\"configuration\":restored_config},\n",
    "    \"planned_thresholds\":GATES,\"t4_profile\":profile})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e39cc80",
   "metadata": {},
   "source": [
    "## Run it yourself\n",
    "\n",
    "Report the release decision, the evidence behind it, and one failure that matters for real invoice users. Keep any decoding speedup separate from the model quality change.\n",
    "\n",
    "Sources: [Qwen2-VL](https://huggingface.co/docs/transformers/v4.51.3/model_doc/qwen2_vl), [Generation strategies](https://huggingface.co/docs/transformers/v4.51.3/en/generation_strategies), [DeepSeekMath group-relative objective](https://arxiv.org/abs/2402.03300), [Invoice benchmark](https://huggingface.co/datasets/drew-ipp/invoice-extraction-benchmark).\n",
    "\n",
    "[Read the result and release decision](https://docs.recohut.com/courses/advanced-llm-fine-tuning/4-release/15-release-a-document-parser)."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
