{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4021b0b7",
   "metadata": {},
   "source": [
    "# 08 · Extract tables and charts\n",
    "\n",
    "**Question.** Can response-masked training preserve line items, totals and chart values on new layouts?\n",
    "\n",
    "Keep provenance, extraction fidelity and arithmetic agreement separate. A printed total can be inconsistent and still be read faithfully.\n",
    "\n",
    "[Open the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/08-extract-tables-and-charts)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfd7d40a",
   "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": "4ead1b4c",
   "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",
    "                \"jiwer==4.0.0\"], check=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9912b58",
   "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": "43d1c59e",
   "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": "925ef4f9",
   "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": "66d7bc6a",
   "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": "19819c91",
   "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": "eb2deeb8",
   "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": "cb7d29b9",
   "metadata": {},
   "source": [
    "## What counts as a correct extraction?\n",
    "\n",
    "Gold invoices use integer minor units and preserve row order. Chart answers use a separate schema and are scored as a transfer task. The same invoice lineage stays together across renders."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca0ae532",
   "metadata": {},
   "outputs": [],
   "source": [
    "CHART_PROMPT = (\n",
    "    \"Read the bar chart. Return exactly one JSON object with currency and rows. \"\n",
    "    \"Each row must contain description and line_total_minor in cents. Preserve visual row order.\"\n",
    ")\n",
    "def invoice_item(row):\n",
    "    return DocumentExample(row.key,invoice_image(row),VISIBLE_CONTRACT,\n",
    "                           json.dumps(invoice_record(row),ensure_ascii=False),row.family)\n",
    "\n",
    "def chart_item(row, varied=False):\n",
    "    image, answer=spend_chart(row,varied=varied)\n",
    "    return DocumentExample(row.key,image,CHART_PROMPT,json.dumps(answer,ensure_ascii=False),row.family)\n",
    "\n",
    "def chart_score(text, target):\n",
    "    gold=json.loads(target)\n",
    "    try:\n",
    "        value=json.loads(text,object_pairs_hook=_strict_dict)\n",
    "    except (TypeError,ValueError):\n",
    "        return {\"valid\":False,\"exact\":False,\"amount_error_minor\":None}\n",
    "    if (not isinstance(value,dict) or set(value)!={\"currency\",\"rows\"}\n",
    "            or type(value[\"currency\"]) is not str or not isinstance(value[\"rows\"],list)):\n",
    "        return {\"valid\":False,\"exact\":False,\"amount_error_minor\":None}\n",
    "    if any(not isinstance(row,dict) or set(row)!={\"description\",\"line_total_minor\"} or\n",
    "           type(row[\"line_total_minor\"]) is not int or type(row[\"description\"]) is not str for row in value[\"rows\"]):\n",
    "        return {\"valid\":False,\"exact\":False,\"amount_error_minor\":None}\n",
    "    descriptions = [row[\"description\"] for row in value[\"rows\"]]\n",
    "    if len(descriptions) != len(set(descriptions)):\n",
    "        return {\"valid\":False,\"exact\":False,\"amount_error_minor\":None}\n",
    "    by_name={row[\"description\"]:row[\"line_total_minor\"] for row in value[\"rows\"]}\n",
    "    errors=[abs(by_name[row[\"description\"]]-row[\"line_total_minor\"])\n",
    "            for row in gold[\"rows\"] if row[\"description\"] in by_name]\n",
    "    return {\"valid\":True,\"exact\":value==gold,\"matched_labels\":len(errors),\"amount_error_minor\":sum(errors)/len(errors) if errors else None}\n",
    "\n",
    "def invoice_metrics(text, invoice):\n",
    "    metrics = score_record(text, invoice)\n",
    "    observed = parse_record(text)\n",
    "    expected = invoice_record(invoice)[\"line_items\"]\n",
    "    predicted = observed[\"line_items\"] if observed else []\n",
    "    columns = (\"description\",\"quantity\",\"unit_minor\")\n",
    "    matches = sum(gold[name] == guess[name]\n",
    "                  for gold, guess in zip(expected, predicted) for name in columns)\n",
    "    metrics[\"cell_f1\"] = 2 * matches / (len(columns) * (len(expected) + len(predicted)))\n",
    "    return metrics\n",
    "\n",
    "train=[invoice_item(row) for row in examples_for(\"train\",72)]+[chart_item(row) for row in examples_for(\"train\",24)]\n",
    "locked={split:examples_for(split,24) for split in (\"familiar\",\"novel\",\"independent\")}\n",
    "assert {item.group for item in train}.isdisjoint(row.family for rows in locked.values() for row in rows)\n",
    "# Reserve one printed arithmetic discrepancy in each unfamiliar slice.\n",
    "for split in (\"novel\", \"independent\"):\n",
    "    probe = next(row for row in examples_for(split) if row.printed_total_minor is not None)\n",
    "    slice_rows = locked[split]\n",
    "    if probe not in slice_rows:\n",
    "        slot = next(i for i, row in enumerate(slice_rows) if row.family == probe.family)\n",
    "        slice_rows[slot] = probe\n",
    "chart_test=[chart_item(row,varied=True) for row in locked[\"novel\"]]\n",
    "print(\"Training examples, including one auxiliary chart slice:\",len(train))\n",
    "locked_keys = [row.key for rows in locked.values() for row in rows]\n",
    "assert len(locked_keys) == len(set(locked_keys)) == 72\n",
    "assert {item.key for item in train}.isdisjoint(locked_keys)\n",
    "assert len(chart_test) == len(locked[\"novel\"])\n",
    "print(\"Held-out invoice counts:\", {name:len(rows) for name,rows in locked.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a661a713",
   "metadata": {},
   "source": [
    "## Can one worst-width update fit on the T4?\n",
    "\n",
    "Screen the longest processed training sequence before running the measured comparisons. Discard its weights and reset the seed before the scored fit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8cd48a20",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gc import collect\n",
    "from importlib.metadata import version\n",
    "\n",
    "def profile_t4(processor, items):\n",
    "    free, _ = torch.cuda.mem_get_info()\n",
    "    if free < 12 * 2**30:\n",
    "        raise RuntimeError(\"The profile needs at least 12 GiB free on the T4.\")\n",
    "\n",
    "    def feature_width(item):\n",
    "        features, labels = sft_feature(processor, item)\n",
    "        return labels.shape[1], features[\"pixel_values\"].shape[0]\n",
    "\n",
    "    probe = max(items, key=feature_width)\n",
    "    widths = feature_width(probe)\n",
    "    torch.manual_seed(VISION_SEED)\n",
    "    torch.cuda.empty_cache()\n",
    "    starting_allocation = torch.cuda.memory_allocated()\n",
    "    probe_model = adapter_for_vision(load_vision_base(trainable=True))\n",
    "    fit = fit_vision(probe_model, processor, [probe], updates=1, accumulation=2)\n",
    "    reserved_gib = torch.cuda.max_memory_reserved() / 2**30\n",
    "    del probe_model\n",
    "    collect()\n",
    "    torch.cuda.empty_cache()\n",
    "    retained_bytes = max(0, torch.cuda.memory_allocated() - starting_allocation)\n",
    "    torch.cuda.reset_peak_memory_stats()\n",
    "    torch.manual_seed(VISION_SEED)\n",
    "    result = {\n",
    "        \"probe_key\": probe.key, \"sequence_tokens\": widths[0], \"image_patches\": widths[1],\n",
    "        \"entry_free_gib\": free / 2**30, \"peak_reserved_gib\": reserved_gib,\n",
    "        \"retained_bytes\": retained_bytes, **fit,\n",
    "    }\n",
    "    Path(\"08_t4_profile.json\").write_text(json.dumps(result, indent=2), encoding=\"utf-8\")\n",
    "    print(json.dumps(result, indent=2))\n",
    "    if (fit[\"seconds\"] > 45 or fit[\"peak_gib\"] > 10 or reserved_gib > 12\n",
    "            or free - reserved_gib * 2**30 < 2 * 2**30 or retained_bytes > 128 * 2**20):\n",
    "        raise RuntimeError(\"The profile exceeded its T4 time or memory budget.\")\n",
    "    return result\n",
    "\n",
    "pins = {\"transformers\": \"4.51.3\", \"peft\": \"0.15.2\", \"accelerate\": \"1.6.0\",\n",
    "        \"bitsandbytes\": \"0.50.2\", \"pillow\": \"11.3.0\"}\n",
    "for name, expected in pins.items():\n",
    "    if version(name) != expected:\n",
    "        raise RuntimeError(f\"Expected {name}=={expected}, got {version(name)}\")\n",
    "get_ipython().run_line_magic(\"config\", \"InlineBackend.figure_formats = ['svg']\")\n",
    "processor=processor_for_vision()\n",
    "t4_profile=profile_t4(processor,train)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e9518f8",
   "metadata": {},
   "source": [
    "## How strong are the two baselines?\n",
    "\n",
    "A rules baseline receives the verified visible text, an upper-bound input rather than noisy OCR. The frozen model receives pixels. Keep unmatched rules results in the denominator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b102f51",
   "metadata": {},
   "outputs": [],
   "source": [
    "def model_scores(model):\n",
    "    rows=[]\n",
    "    for split, invoices in locked.items():\n",
    "        for invoice in invoices:\n",
    "            output=generate_vision(model,processor,invoice_item(invoice))\n",
    "            rows.append({\"split\":split,\"key\":invoice.key,\"family\":invoice.family,\n",
    "                         \"metrics\":invoice_metrics(output[\"text\"],invoice),\"complete\":output[\"complete\"],\n",
    "                         \"prediction\":output[\"text\"],\"gold\":invoice_record(invoice)})\n",
    "    chart_rows=[]\n",
    "    for item in chart_test:\n",
    "        output=generate_vision(model,processor,item)\n",
    "        chart_rows.append({\"key\":item.key,\"metrics\":chart_score(output[\"text\"],item.answer),\n",
    "                           \"complete\":output[\"complete\"],\"prediction\":output[\"text\"],\"gold\":json.loads(item.answer),\"family\":item.group})\n",
    "    return {\"invoices\":rows,\"charts\":chart_rows}\n",
    "\n",
    "def summarise(rows):\n",
    "    result={}\n",
    "    for split in locked:\n",
    "        selected=[row for row in rows if row[\"split\"]==split]\n",
    "        result[split]={metric:sum(row[\"metrics\"][metric] for row in selected)/len(selected)\n",
    "                       for metric in (\"exact\",\"valid\",\"fields\",\"row_f1\",\"cell_f1\")}\n",
    "        result[split][\"count\"]=len(selected)\n",
    "    return result\n",
    "\n",
    "rules_rows=[{\"split\":split,\"key\":row.key,\"metrics\":invoice_metrics(rules_extract(invoice_text(row)),row)}\n",
    "            for split,invoices in locked.items() for row in invoices]\n",
    "base=load_vision_base()\n",
    "baseline=model_scores(base)\n",
    "print(\"Rules with oracle text:\",summarise(rules_rows))\n",
    "print(\"Frozen VLM:\",summarise(baseline[\"invoices\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcc42bc9",
   "metadata": {},
   "source": [
    "## What changed after supervised training?\n",
    "\n",
    "Train a language-backbone adapter on the invoice and chart batches. Keep the prompt, processor, decoding and evaluation cases fixed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c27937d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gc import collect\n",
    "del base\n",
    "collect()\n",
    "torch.cuda.empty_cache()\n",
    "model=adapter_for_vision(load_vision_base(trainable=True))\n",
    "training=fit_vision(model,processor,train,updates=32,accumulation=2)\n",
    "adapted=model_scores(model)\n",
    "save_dir=save_vision_adapter(model,\"08_structure_adapter\")\n",
    "adapter_sha = hashlib.sha256((save_dir/\"adapter_model.safetensors\").read_bytes()).hexdigest()\n",
    "anchor=invoice_item(examples_for(\"familiar\",1)[0])\n",
    "handoff={\"features\":feature_manifest(train,32,2),\n",
    "         \"adapter_sha256\":adapter_sha,\"parity_key\":anchor.key,\n",
    "         \"parity_tokens\":generate_vision(model,processor,anchor)[\"tokens\"]}\n",
    "Path(\"08_handoff.json\").write_text(json.dumps(handoff,indent=2),encoding=\"utf-8\")\n",
    "print(\"Adapter bytes SHA256:\",adapter_sha)\n",
    "print(\"Adapted:\",summarise(adapted[\"invoices\"]))\n",
    "assert (save_dir/\"adapter_config.json\").is_file()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e360e53e",
   "metadata": {},
   "source": [
    "## Which gains survive a layout change?\n",
    "\n",
    "Compare named slices and audit changed records. Chart accuracy and amount error answer different questions. Unparseable charts remain part of the exact-score denominator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c740b17",
   "metadata": {},
   "outputs": [],
   "source": [
    "def exact_rows(result, split):\n",
    "    return [row for row in result[\"invoices\"] if row[\"split\"] == split]\n",
    "\n",
    "paired={split: paired_family_exact(exact_rows(baseline,split),exact_rows(adapted,split),\n",
    "                                  lambda row: row[\"metrics\"][\"exact\"])\n",
    "        for split in locked}\n",
    "print(\"Exact invoice changes in percentage points:\",paired)\n",
    "print(\"Charts, base and adapted:\",\n",
    "      [sum(r[\"metrics\"][\"exact\"] for r in result[\"charts\"])/len(result[\"charts\"]) for result in (baseline,adapted)])\n",
    "chart_exact_paired=paired_family_exact(baseline[\"charts\"],adapted[\"charts\"],\n",
    "                                      lambda row: row[\"metrics\"][\"exact\"])\n",
    "write_results(\"08_structure_results.json\",{\"rules\":rules_rows,\"base\":baseline,\"adapted\":adapted,\n",
    "    \"paired_exact\":paired,\"paired_chart_exact\":chart_exact_paired,\"training\":training,\"t4_profile\":t4_profile,\"adapter_sha256\":adapter_sha,\n",
    "    \"locked_ids\":{name:[x.key for x in rows] for name,rows in locked.items()}})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51f4e334",
   "metadata": {},
   "source": [
    "## Run it yourself\n",
    "\n",
    "Increase chart training exposure at a fixed update budget, vary the number of invoice rows, and compare both changes on the same layout hold-out. Keep the separate capstone release set closed.\n",
    "\n",
    "Sources: [Qwen2-VL](https://huggingface.co/docs/transformers/v4.51.3/model_doc/qwen2_vl), [PEFT quantisation](https://huggingface.co/docs/peft/v0.15.0/developer_guides/quantization), [Nemotron document extraction](https://huggingface.co/blog/nvidia/building-on-nemotron-35-parse-open-data-fine-tunin).\n",
    "\n",
    "[Read the result and compare the three systems](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/08-extract-tables-and-charts)."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
