{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "lab-02-00",
   "metadata": {},
   "source": [
    "# 02 · Profile a transformer\n",
    "\n",
    "Which parts of a request consume time and memory?\n",
    "\n",
    "Measure prefill and decoding separately. Change prompt length and language one factor at a time. Compare predicted KV-cache growth with allocated GPU memory while holding batch and generation limits fixed.\n",
    "\n",
    "**Measures** — Token counts by language, prefill time, decode rate, peak allocation and predicted KV bytes.\n",
    "\n",
    "**Evidence** — Reproducible profiler trace and a memory budget for one request.\n",
    "\n",
    "**Runtime** — T4. The course bench uses invented facilities, equipment and records."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-01",
   "metadata": {},
   "source": [
    "## Reproduce the environment\n",
    "\n",
    "Install the pinned dependencies and check the hardware receipt before interpreting timings. Runs record their device and software package versions in `evidence/runtime.json`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "lab-02-02",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:42.734468Z",
     "iopub.status.busy": "2026-11-27T06:17:42.734129Z",
     "iopub.status.idle": "2026-11-27T06:17:42.759402Z",
     "shell.execute_reply": "2026-11-27T06:17:42.758610Z"
    }
   },
   "outputs": [],
   "source": [
    "PINS = {'transformers': '4.51.3', 'accelerate': '1.6.0', 'sentence-transformers': '4.1.0', 'bitsandbytes': '0.49.0', 'pypdf': '5.6.1', 'pymupdf': '1.26.1', 'reportlab': '4.4.2', 'rank-bm25': '0.2.2', 'soundfile': '0.13.1'}\n",
    "\n",
    "import importlib.metadata\n",
    "import os\n",
    "import subprocess\n",
    "import sys\n",
    "\n",
    "if os.environ.get(\"COURSE_SMOKE\") != \"1\":\n",
    "    missing = []\n",
    "    for name, version in PINS.items():\n",
    "        try:\n",
    "            matched = importlib.metadata.version(name) == version\n",
    "        except importlib.metadata.PackageNotFoundError:\n",
    "            matched = False\n",
    "        if not matched:\n",
    "            missing.append(f\"{name}=={version}\")\n",
    "    if missing:\n",
    "        try:\n",
    "            import uv\n",
    "        except ImportError:\n",
    "            subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"uv==0.7.13\"], check=True)\n",
    "        subprocess.run([sys.executable, \"-m\", \"uv\", \"pip\", \"install\", \"--quiet\", \"--python\", sys.executable, *missing], check=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-03",
   "metadata": {},
   "source": [
    "## Establish the shared contract\n",
    "\n",
    "Freeze equipment families before deriving ticket variants. Verify an outcome against the decision, exact value and explicit evidence IDs. Keep the release split closed until the capstone. Read-only tools take tenant and role from trusted request metadata."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "lab-02-04",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:42.764256Z",
     "iopub.status.busy": "2026-11-27T06:17:42.763951Z",
     "iopub.status.idle": "2026-11-27T06:17:42.792430Z",
     "shell.execute_reply": "2026-11-27T06:17:42.791589Z"
    }
   },
   "outputs": [],
   "source": [
    "MODEL_IDS = {'text': ('Qwen/Qwen2.5-1.5B-Instruct', '989aa7980e4cf806f80c7fef2b1adb7bc71aa306'), 'vision': ('Qwen/Qwen2-VL-2B-Instruct', '1860c46f12b7449d0f5b426a7474ab715342bc65'), 'speech': ('openai/whisper-base', 'e37978b90ca9030d5170a5c07aadb050351a65bb'), 'embedding': ('sentence-transformers/all-MiniLM-L6-v2', '1110a243fdf4706b3f48f1d95db1a4f5529b4d41'), 'reranker': ('cross-encoder/ms-marco-MiniLM-L6-v2', '233902d25c440f23af6f7d6e94d2946bac0bee0a')}\n",
    "SPLIT_MANIFEST = {'train': {'sha256': '610cd78bdcc4f92095a511c4c92812eace3bcd25f290604d4641f8338438bc4b', 'n': 180, 'families': 18}, 'dev': {'sha256': '51dbc208b6b20a620237dd76ce0a2db4f10aa75f4f8fc404121e301b8d79a0cf', 'n': 120, 'families': 12}, 'holdout': {'sha256': 'd8c88e29283fe660e86b9bf3b3c67fb810f3cfa75c27e2e7043bccfb42766452', 'n': 300, 'families': 30}}\n",
    "LAB_NUMBER = 2\n",
    "\n",
    "import hashlib\n",
    "import json\n",
    "import os\n",
    "import random\n",
    "import re\n",
    "import sqlite3\n",
    "from functools import lru_cache\n",
    "from pathlib import Path\n",
    "\n",
    "SLICES = (\"manual\", \"numeric\", \"multi_source\", \"ambiguity\", \"boundary\", \"follow_up\")\n",
    "SPLITS = {\"train\": (100, 3), \"dev\": (200, 2), \"holdout\": (300, 5)}\n",
    "TENANTS = (\"north-yard\", \"south-yard\")\n",
    "\n",
    "\n",
    "@lru_cache\n",
    "def _assets(split):\n",
    "    first, count = SPLITS[split]\n",
    "    rows = []\n",
    "    for slice_index, category in enumerate(SLICES):\n",
    "        for offset in range(count):\n",
    "            index = first + slice_index * 10 + offset\n",
    "            prefix = (\"P\", \"F\", \"V\")[index % 3]\n",
    "            result = {\n",
    "                \"family\": f\"F{index}\", \"slice\": category, \"tenant\": TENANTS[index % 2],\n",
    "                \"asset\": f\"{prefix}-{index}\", \"linked\": f\"S-{index + 400}\",\n",
    "                \"team\": (\"mechanical\", \"controls\", \"electrical\")[index % 3],\n",
    "                \"limit\": 67 + (index * 19) % 36,\n",
    "                \"inspection\": f\"2025-{index % 12 + 1:02d}-{index % 27 + 1:02d}\",\n",
    "                \"fault\": (\"seal wear\", \"sensor drift\", \"filter blockage\", \"bearing vibration\")[index % 4],\n",
    "                \"version\": \"r3\",\n",
    "            }\n",
    "            for source in (\"manual\", \"inventory\", \"graph\"):\n",
    "                result[f\"{source}_id\"] = f\"{source}-{result['asset']}-r3\"\n",
    "            rows.append(result)\n",
    "    return tuple(rows)\n",
    "\n",
    "\n",
    "def assets(split=\"dev\"):\n",
    "    return [dict(row) for row in _assets(split)]\n",
    "\n",
    "\n",
    "def manual_text(asset_record):\n",
    "    return (\n",
    "        f\"Equipment manual for {asset_record['asset']} (revision {asset_record['version']}). \"\n",
    "        f\"Maximum operating temperature: {asset_record['limit']} C. \"\n",
    "        f\"Known fault: {asset_record['fault']}. The supporting system is {asset_record['linked']}. \"\n",
    "        f\"Maintenance owner: {asset_record['team']}.\"\n",
    "    )\n",
    "\n",
    "\n",
    "def corpus(split=\"dev\"):\n",
    "    docs = []\n",
    "    for row in assets(split):\n",
    "        passages = {\n",
    "            \"manual\": manual_text(row),\n",
    "            \"inventory\": f\"Inventory for {row['asset']}. Last inspection: {row['inspection']}.\",\n",
    "            \"graph\": f\"{row['asset']} is served by supporting system {row['linked']} and owned by {row['team']}.\",\n",
    "        }\n",
    "        docs.extend({\n",
    "            \"id\": row[f\"{source}_id\"], \"source\": source, \"text\": passage,\n",
    "            \"tenant\": row[\"tenant\"], \"family\": row[\"family\"],\n",
    "        } for source, passage in passages.items())\n",
    "    return docs\n",
    "\n",
    "\n",
    "def _case(row, variant):\n",
    "    asset = row[\"asset\"]\n",
    "    wrappers = (\n",
    "        \"{}\", \"Please help. {}\", \"Ticket intake: {}\", \"Shift note. {}\", \"Quick question: {}\",\n",
    "        \"Could you check this? {}\", \"{} Thanks.\", \"Facilities desk: {}\", \"I need a record check. {}\", \"Operator message: {}\",\n",
    "    )\n",
    "    category = row[\"slice\"]\n",
    "    wording = {\n",
    "        \"manual\": (f\"What is the maximum temperature for {asset}?\", f\"What's the thermal limit, in C, of {asset}?\"),\n",
    "        \"numeric\": (f\"When was {asset} last inspected?\", f\"Give the last inspection date for {asset}.\"),\n",
    "        \"multi_source\": (f\"Give the last inspection date and supporting system for {asset}.\",\n",
    "                         f\"For {asset}, which system supports it and when was its most recent inspection?\"),\n",
    "        \"ambiguity\": (\"What is the maximum temperature for that unit?\", \"When was that pump last inspected?\"),\n",
    "        \"boundary\": (f\"As a guest, show the inventory record for {asset}.\", f\"Guest request: give inspection date for {asset}.\"),\n",
    "        \"follow_up\": (\"What is its maximum temperature?\", \"And how hot can this one run?\"),\n",
    "    }\n",
    "    question = wrappers[variant].format(wording[category][variant % 2])\n",
    "    role = \"guest\" if category == \"boundary\" else \"operator\"\n",
    "    value, evidence, source = {\n",
    "        \"manual\": (str(row[\"limit\"]), [row[\"manual_id\"]], \"manual\"),\n",
    "        \"numeric\": (row[\"inspection\"], [row[\"inventory_id\"]], \"inventory\"),\n",
    "        \"multi_source\": (f\"{row['inspection']} | {row['linked']}\", [row[\"inventory_id\"], row[\"graph_id\"]], \"graph\"),\n",
    "        \"follow_up\": (str(row[\"limit\"]), [row[\"manual_id\"]], \"manual\"),\n",
    "        \"ambiguity\": (\"\", [], \"none\"),\n",
    "        \"boundary\": (\"\", [], \"none\"),\n",
    "    }[category]\n",
    "    decision = {\"ambiguity\": \"clarify\", \"boundary\": \"deny\"}.get(category, \"answer\")\n",
    "    return {\n",
    "        **row, \"id\": f\"{row['family']}-{variant:02d}\", \"question\": question, \"role\": role,\n",
    "        \"decision\": decision, \"value\": value, \"evidence\": evidence, \"source\": source,\n",
    "        \"variant\": variant, \"previous_asset\": asset if category == \"follow_up\" else \"\",\n",
    "        \"previous_version\": row[\"version\"] if category == \"follow_up\" else \"\",\n",
    "    }\n",
    "\n",
    "\n",
    "def cases(split=\"dev\"):\n",
    "    return [_case(row, variant) for row in assets(split) for variant in range(10)]\n",
    "\n",
    "\n",
    "def digest(rows):\n",
    "    serial = json.dumps(rows, ensure_ascii=False, sort_keys=True, separators=(\",\", \":\")).encode()\n",
    "    return hashlib.sha256(serial).hexdigest()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-05",
   "metadata": {},
   "source": [
    "### Preserve source authority\n",
    "\n",
    "Generate original documents and an inventory view. Parameterize the database query, set it read-only, and select only evidence that belongs to the trusted tenant."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "lab-02-06",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:42.798889Z",
     "iopub.status.busy": "2026-11-27T06:17:42.798587Z",
     "iopub.status.idle": "2026-11-27T06:17:42.810848Z",
     "shell.execute_reply": "2026-11-27T06:17:42.809929Z"
    }
   },
   "outputs": [],
   "source": [
    "@lru_cache\n",
    "def _inventory(split):\n",
    "    db = sqlite3.connect(\":memory:\")\n",
    "    db.row_factory = sqlite3.Row\n",
    "    db.execute(\"CREATE TABLE inventory(asset TEXT PRIMARY KEY, tenant TEXT, inspection TEXT, version TEXT)\")\n",
    "    db.executemany(\n",
    "        \"INSERT INTO inventory VALUES(:asset, :tenant, :inspection, :version)\", assets(split)\n",
    "    )\n",
    "    db.execute(\"CREATE VIEW operator_inventory AS SELECT asset, tenant, inspection, version FROM inventory\")\n",
    "    db.execute(\"PRAGMA query_only = ON\")\n",
    "    return db\n",
    "\n",
    "\n",
    "def read_inventory(asset, tenant, role=\"operator\", split=\"dev\"):\n",
    "    if role != \"operator\":\n",
    "        return None\n",
    "    row = _inventory(split).execute(\n",
    "        \"SELECT * FROM operator_inventory WHERE asset = ? AND tenant = ?\", (asset, tenant)\n",
    "    ).fetchone()\n",
    "    return dict(row) if row is not None else None\n",
    "\n",
    "\n",
    "def safe_context(case, split=\"dev\"):\n",
    "    if case[\"role\"] != \"operator\" or case.get(\"tenant\") not in TENANTS:\n",
    "        return \"\"\n",
    "    if case[\"slice\"] == \"ambiguity\":\n",
    "        return \"\"\n",
    "    asset_id = case.get(\"previous_asset\") if case[\"slice\"] == \"follow_up\" else case[\"asset\"]\n",
    "    source_ids = {\n",
    "        d[f\"{source}_id\"]\n",
    "        for d in assets(split) if d[\"asset\"] == asset_id and d[\"tenant\"] == case[\"tenant\"]\n",
    "        for source in (\"manual\", \"inventory\", \"graph\")\n",
    "    }\n",
    "    return \"\\n\".join(f\"[{doc['id']}] {doc['text']}\" for doc in corpus(split) if doc[\"id\"] in source_ids)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-07",
   "metadata": {},
   "source": [
    "### Score the outcome\n",
    "\n",
    "A correct decision still needs the right value and complete evidence. Use a paired bootstrap over equipment families when comparing two systems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "lab-02-08",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:42.815470Z",
     "iopub.status.busy": "2026-11-27T06:17:42.815136Z",
     "iopub.status.idle": "2026-11-27T06:17:42.831556Z",
     "shell.execute_reply": "2026-11-27T06:17:42.830775Z"
    }
   },
   "outputs": [],
   "source": [
    "def score_answer(case, answer):\n",
    "    if not isinstance(answer, dict) or not isinstance(answer.get(\"evidence\"), list):\n",
    "        return 0\n",
    "    evidence = answer[\"evidence\"]\n",
    "    return int(\n",
    "        answer.get(\"decision\") == case[\"decision\"]\n",
    "        and isinstance(answer.get(\"value\"), str)\n",
    "        and answer[\"value\"].strip() == case[\"value\"]\n",
    "        and all(isinstance(item, str) for item in evidence)\n",
    "        and sorted(evidence) == sorted(case[\"evidence\"])\n",
    "    )\n",
    "\n",
    "\n",
    "def paired_interval(cases, candidate, incumbent, draws=1500):\n",
    "    if len(cases) != len(candidate) or len(cases) != len(incumbent) or not cases:\n",
    "        raise ValueError(\"Expected equal-length nonempty case and score arrays.\")\n",
    "    groups = {}\n",
    "    for case, new, old in zip(cases, candidate, incumbent):\n",
    "        groups.setdefault(case[\"family\"], []).append(int(new) - int(old))\n",
    "    summaries = [(sum(values), len(values)) for values in groups.values()]\n",
    "    rng = random.Random(401)\n",
    "    estimates = []\n",
    "    for _ in range(draws):\n",
    "        sampled = rng.choices(summaries, k=len(summaries))\n",
    "        estimates.append(sum(total for total, _ in sampled) / sum(n for _, n in sampled))\n",
    "    estimates.sort()\n",
    "    return {\n",
    "        \"delta\": sum(total for total, _ in summaries) / len(cases),\n",
    "        \"low\": estimates[int(draws * .025)],\n",
    "        \"high\": estimates[int(draws * .975) - 1],\n",
    "        \"n\": len(cases), \"families\": len(summaries),\n",
    "    }\n",
    "\n",
    "\n",
    "def decode_answer(text):\n",
    "    try:\n",
    "        answer = json.loads(text.strip())\n",
    "    except (AttributeError, ValueError):\n",
    "        return {}\n",
    "    return answer if isinstance(answer, dict) else {}\n",
    "\n",
    "\n",
    "def answer_prompt(case, context):\n",
    "    previous = case.get(\"previous_asset\") or \"none\"\n",
    "    return (\n",
    "        \"You are a facilities helpdesk. Use only the supplied records. Decide answer, clarify, or deny. \"\n",
    "        \"Deny requests from a guest. Clarify when the equipment is unspecified and no previous equipment is listed. \"\n",
    "        \"Output exactly one JSON object with keys decision, value and evidence. For deny or clarify use an empty \"\n",
    "        \"value and evidence array. Use the exact record text for dates or identifiers and an integer-as-string \"\n",
    "        \"for temperatures. When asked for both inspection and supporting system, return DATE | SYSTEM. \"\n",
    "        \"For an answer include only supporting record IDs in evidence.\\n\"\n",
    "        f\"Role: {case['role']}\\nPrevious equipment: {previous}\\nRequest: {case['question']}\\n\"\n",
    "        f\"Records:\\n{context or '(none)'}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-09",
   "metadata": {},
   "source": [
    "### Record the runtime and evidence\n",
    "\n",
    "The model checkpoints are fixed. Local smoke mode uses offline fixtures to exercise the notebook code path. It cannot produce GPU measurements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "lab-02-10",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:42.835943Z",
     "iopub.status.busy": "2026-11-27T06:17:42.835580Z",
     "iopub.status.idle": "2026-11-27T06:17:52.911015Z",
     "shell.execute_reply": "2026-11-27T06:17:52.910284Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Evidence saved to evidence/runtime.json\n",
      "{\n",
      "  \"device\": \"Tesla T4\",\n",
      "  \"python\": \"3.13.16\",\n",
      "  \"platform\": \"Linux\",\n",
      "  \"packages\": {\n",
      "    \"torch\": \"2.14.1+cu130\",\n",
      "    \"transformers\": \"4.51.3\",\n",
      "    \"accelerate\": \"1.6.0\",\n",
      "    \"numpy\": \"2.4.6\",\n",
      "    \"scikit-learn\": \"1.6.1\",\n",
      "    \"matplotlib\": \"3.10.0\",\n",
      "    \"bitsandbytes\": \"0.49.0\",\n",
      "    \"sentence-transformers\": \"4.1.0\"\n",
      "  },\n",
      "  \"smoke\": false,\n",
      "  \"cuda\": \"13.0\",\n",
      "  \"memory_bytes\": 15637086208,\n",
      "  \"capability\": [\n",
      "    7,\n",
      "    5\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "def _convert(value):\n",
    "    if hasattr(value, \"tolist\"):\n",
    "        return value.tolist()\n",
    "    if hasattr(value, \"item\"):\n",
    "        return value.item()\n",
    "    if isinstance(value, Path):\n",
    "        return str(value)\n",
    "    raise TypeError(type(value).__name__)\n",
    "\n",
    "\n",
    "def save(name, value):\n",
    "    output = Path(\"evidence\")\n",
    "    output.mkdir(exist_ok=True)\n",
    "    path = output / f\"{name}.json\"\n",
    "    path.write_text(json.dumps(value, indent=2, ensure_ascii=False, default=_convert, allow_nan=False) + \"\\n\")\n",
    "    print(f\"Evidence saved to {path}\")\n",
    "    return path\n",
    "\n",
    "\n",
    "def chart(title, labels, values, unit):\n",
    "    import matplotlib.pyplot as plt\n",
    "    import numpy as np\n",
    "    from matplotlib.ticker import PercentFormatter\n",
    "\n",
    "    values = np.asarray(values, dtype=float)\n",
    "    positions = np.arange(len(labels))\n",
    "    palette = (\"#3d6b5b\", \"#298876\", \"#7b97a2\", \"#9c6951\")\n",
    "    paper, ink, line = \"#f5f7f2\", \"#20382f\", \"#d3ded6\"\n",
    "    readable = [label.replace(\"_\", \" \") for label in labels]\n",
    "    fig, axes = plt.subplots(figsize=(8.1, max(2.55, .48 * len(labels) + 1.7)), layout=\"constrained\")\n",
    "    fig.patch.set_facecolor(paper)\n",
    "    axes.set_facecolor(paper)\n",
    "    bars = axes.barh(positions, values, height=.55, color=[palette[i % len(palette)] for i in positions])\n",
    "    axes.set_yticks(positions, labels=readable)\n",
    "    axes.invert_yaxis()\n",
    "    fraction = unit.casefold() == \"fraction\"\n",
    "    if fraction:\n",
    "        axes.xaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))\n",
    "    axes.set_xlabel(\"Share of cases\" if fraction else unit, color=ink, loc=\"left\", labelpad=8)\n",
    "    axes.set_title(title, loc=\"left\", color=ink, weight=\"semibold\", pad=15, fontsize=16)\n",
    "    axes.set_axisbelow(True)\n",
    "    axes.grid(axis=\"x\", color=line, linewidth=.75)\n",
    "    axes.spines[[\"top\", \"right\", \"left\", \"bottom\"]].set_visible(False)\n",
    "    axes.tick_params(axis=\"both\", length=0, colors=ink, pad=5)\n",
    "    finite = values[np.isfinite(values)]\n",
    "    if len(finite):\n",
    "        left, right = min(0.0, finite.min()), max(0.0, finite.max())\n",
    "        span = right - left or 1.0\n",
    "        axes.set_xlim(left - (.15 * span if left < 0 else 0), right + .18 * span)\n",
    "        for bar, value in zip(bars, values):\n",
    "            if not np.isfinite(value):\n",
    "                continue\n",
    "            center = bar.get_y() + bar.get_height() / 2\n",
    "            if value == 0:\n",
    "                axes.scatter([0], [center], s=14, color=ink, clip_on=False, zorder=3)\n",
    "            formatted = f\"{value:.1%}\" if fraction else f\"{value:,.3g}\"\n",
    "            axes.annotate(formatted, (value, center), xytext=(6 if value >= 0 else -6, 0), textcoords=\"offset points\",\n",
    "                          ha=\"left\" if value >= 0 else \"right\", va=\"center\", color=ink, fontsize=10)\n",
    "    target = Path(\"evidence\") / (re.sub(r\"[^a-z0-9]+\", \"-\", title.lower()).strip(\"-\") + \".svg\")\n",
    "    target.parent.mkdir(exist_ok=True)\n",
    "    fig.savefig(target)\n",
    "    plt.show()\n",
    "    plt.close(fig)\n",
    "\n",
    "import importlib.metadata\n",
    "import platform\n",
    "import sys\n",
    "import time\n",
    "\n",
    "COURSE_SMOKE = os.environ.get(\"COURSE_SMOKE\") == \"1\"\n",
    "HAS_MODEL_RUNTIME = not COURSE_SMOKE and LAB_NUMBER != 10\n",
    "if HAS_MODEL_RUNTIME:\n",
    "    import torch\n",
    "    from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
    "\n",
    "\n",
    "def device_name():\n",
    "    if COURSE_SMOKE:\n",
    "        return \"CPU smoke\"\n",
    "    if not HAS_MODEL_RUNTIME:\n",
    "        return \"CPU\"\n",
    "    return torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"CPU\"\n",
    "\n",
    "\n",
    "def sync():\n",
    "    if HAS_MODEL_RUNTIME and torch.cuda.is_available():\n",
    "        torch.cuda.synchronize()\n",
    "\n",
    "\n",
    "def load_text(quant=False):\n",
    "    if not HAS_MODEL_RUNTIME:\n",
    "        raise RuntimeError(\"Use a fixture explicitly inside the CPU smoke lane.\")\n",
    "    repo, revision = MODEL_IDS[\"text\"]\n",
    "    tokenizer = AutoTokenizer.from_pretrained(repo, revision=revision, padding_side=\"left\")\n",
    "    options = {\"revision\": revision, \"attn_implementation\": \"sdpa\"}\n",
    "    if torch.cuda.is_available():\n",
    "        options.update(torch_dtype=torch.float16, device_map={\"\": 0})\n",
    "    else:\n",
    "        options.update(torch_dtype=torch.float32)\n",
    "    if quant:\n",
    "        if not torch.cuda.is_available():\n",
    "            raise RuntimeError(\"NF4 comparison requires CUDA.\")\n",
    "        options[\"quantization_config\"] = BitsAndBytesConfig(\n",
    "            load_in_4bit=True, bnb_4bit_quant_type=\"nf4\", bnb_4bit_compute_dtype=torch.float16,\n",
    "        )\n",
    "    return tokenizer, AutoModelForCausalLM.from_pretrained(repo, **options).eval()\n",
    "\n",
    "\n",
    "def generate(tokenizer, model, prompts, max_new_tokens=48, temperature=0.0, **kwargs):\n",
    "    rendered = [\n",
    "        tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": p}], tokenize=False, add_generation_prompt=True)\n",
    "        for p in prompts\n",
    "    ]\n",
    "    tokens = tokenizer(rendered, return_tensors=\"pt\", padding=True, add_special_tokens=False).to(model.device)\n",
    "    sampling = {\"do_sample\": True, \"temperature\": temperature} if temperature > 0 else {\"do_sample\": False}\n",
    "    with torch.inference_mode():\n",
    "        output = model.generate(\n",
    "            **tokens, max_new_tokens=max_new_tokens, pad_token_id=tokenizer.pad_token_id,\n",
    "            **sampling, **kwargs,\n",
    "        )\n",
    "    return tokenizer.batch_decode(output[:, tokens.input_ids.shape[1]:], skip_special_tokens=True)\n",
    "\n",
    "\n",
    "def write_receipt():\n",
    "    versions = {}\n",
    "    for package in (\"torch\", \"transformers\", \"accelerate\", \"numpy\", \"scikit-learn\", \"matplotlib\", \"bitsandbytes\", \"sentence-transformers\"):\n",
    "        try:\n",
    "            versions[package] = importlib.metadata.version(package)\n",
    "        except importlib.metadata.PackageNotFoundError:\n",
    "            pass\n",
    "    receipt = {\n",
    "        \"device\": device_name(), \"python\": sys.version.split()[0], \"platform\": platform.system(),\n",
    "        \"packages\": versions, \"smoke\": COURSE_SMOKE,\n",
    "    }\n",
    "    if HAS_MODEL_RUNTIME and torch.cuda.is_available():\n",
    "        props = torch.cuda.get_device_properties(0)\n",
    "        receipt.update(cuda=torch.version.cuda, memory_bytes=props.total_memory, capability=list(torch.cuda.get_device_capability(0)))\n",
    "    save(\"runtime\", receipt)\n",
    "    print(json.dumps(receipt, indent=2))\n",
    "    return receipt\n",
    "\n",
    "if 'get_ipython' in globals() and get_ipython() is not None:\n",
    "    from matplotlib_inline.backend_inline import set_matplotlib_formats\n",
    "    set_matplotlib_formats('svg')\n",
    "hardware = write_receipt()\n",
    "if True and os.environ.get('COURSE_T4') == '1':\n",
    "    assert 'T4' in hardware['device'], f\"Expected T4, got {hardware['device']}\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-11",
   "metadata": {},
   "source": [
    "# Lab 02 · Profile a transformer\n",
    "\n",
    "The operator following up on F-250 asks, “What is its maximum temperature?”\n",
    "The desk already knows which revision applies. What changes if the same\n",
    "authorised dossier is copied into the prompt repeatedly? Predict which\n",
    "part of the wait will grow before looking at the measurements.\n",
    "\n",
    "[Read the lesson](https://docs.recohut.com/courses/advanced-ai-systems-engineering/1-measure-the-model/02-profile-a-transformer).\n",
    "The measured lane uses the pinned Qwen checkpoint on a T4. The offline check\n",
    "covers the memory formula, request selection and grading using fixtures."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "lab-02-12",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:52.915545Z",
     "iopub.status.busy": "2026-11-27T06:17:52.914792Z",
     "iopub.status.idle": "2026-11-27T06:17:52.927642Z",
     "shell.execute_reply": "2026-11-27T06:17:52.926831Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length sweep: (128, 512, 1024) input tokens, batch size 1, 9 output tokens\n",
      "Quality sample: 24 tickets from 12 development families\n"
     ]
    }
   ],
   "source": [
    "from statistics import median\n",
    "from time import perf_counter\n",
    "\n",
    "PROMPT_LENGTHS = (128, 512, 1024)\n",
    "GENERATED_TOKENS = 9\n",
    "REPEATS = 7\n",
    "DOSSIER_COPIES = 8\n",
    "QUALITY_TOKEN_BUDGET = 48\n",
    "QUALITY_BATCH = 6\n",
    "started_lab = perf_counter()\n",
    "development_rows = cases(\"dev\")\n",
    "quality_cases = [case for case in development_rows if case[\"variant\"] in (0, 1)]\n",
    "focus_case = next(case for case in quality_cases if case[\"id\"] == \"F250-00\")\n",
    "LANGUAGE_TEXT = {\n",
    "    \"English\": focus_case[\"question\"],\n",
    "    \"Spanish\": \"¿Cuál es su temperatura máxima?\",\n",
    "    \"Hindi\": \"इसका अधिकतम तापमान क्या है?\",\n",
    "}\n",
    "assert len(quality_cases) == 24\n",
    "assert {row[\"slice\"] for row in quality_cases} == set(SLICES)\n",
    "assert digest(development_rows) == SPLIT_MANIFEST[\"dev\"][\"sha256\"]\n",
    "print(\"Length sweep:\", PROMPT_LENGTHS, \"input tokens, batch size 1,\", GENERATED_TOKENS, \"output tokens\")\n",
    "print(\"Quality sample:\", len(quality_cases), \"tickets from\",\n",
    "      len({row[\"family\"] for row in quality_cases}), \"development families\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-13",
   "metadata": {},
   "source": [
    "## Derive the persistent cache budget\n",
    "\n",
    "Grouped-query attention may use fewer KV heads than query heads. Count\n",
    "keys and values, layers, batch rows, KV heads, head dimension, token\n",
    "positions and bytes per element. For a prompt of length P and G emitted\n",
    "tokens, the final cache has P + G − 1 positions. Prefill predicts the first\n",
    "output. Each subsequent forward adds the previous output to the cache.\n",
    "\n",
    "Peak allocated GPU memory also reflects temporary activations, attention\n",
    "buffers, logits, and implementation overhead. It answers a different\n",
    "capacity question from the persistent KV byte count."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "lab-02-14",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:17:52.931098Z",
     "iopub.status.busy": "2026-11-27T06:17:52.930753Z",
     "iopub.status.idle": "2026-11-27T06:18:12.465737Z",
     "shell.execute_reply": "2026-11-27T06:18:12.464777Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.13/dist-packages/huggingface_hub/utils/_auth.py:104: UserWarning: \n",
      "Error while fetching `HF_TOKEN` secret value from your vault: 'Requesting secret HF_TOKEN timed out. Secrets can only be fetched when running from the Colab UI.'.\n",
      "You are not authenticated with the Hugging Face Hub in this notebook.\n",
      "If the error persists, please let us know by opening an issue on GitHub (https://github.com/huggingface/huggingface_hub/issues/new).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Sliding Window Attention is enabled but not implemented for `sdpa`; unexpected results may be encountered.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Measured device and derived cache configuration: Tesla T4 {'layers': 28, 'kv_heads': 2, 'head_dim': 128, 'element_bytes': 2}\n",
      "Model and tokeniser load, ms: 19521.108113000024\n"
     ]
    }
   ],
   "source": [
    "def kv_bytes(positions, layers, kv_heads, head_dim, element_bytes, batch_size=1):\n",
    "    return 2 * layers * batch_size * positions * kv_heads * head_dim * element_bytes\n",
    "\n",
    "\n",
    "assert kv_bytes(5, layers=2, kv_heads=2, head_dim=4, element_bytes=2) == 320\n",
    "assert kv_bytes(6, layers=2, kv_heads=2, head_dim=4, element_bytes=2) - 320 == 64\n",
    "\n",
    "measurements = []\n",
    "language_rows = []\n",
    "profile_summary = []\n",
    "load_ms = None\n",
    "\n",
    "if COURSE_SMOKE:\n",
    "    # This declared shape only exercises the cache arithmetic.\n",
    "    cache_shape = {\"layers\": 8, \"kv_heads\": 2, \"head_dim\": 64, \"element_bytes\": 2}\n",
    "    for length in PROMPT_LENGTHS:\n",
    "        profile_summary.append({\n",
    "            \"input_tokens\": length,\n",
    "            \"predicted_final_kv_bytes\": kv_bytes(length + GENERATED_TOKENS - 1, **cache_shape),\n",
    "            \"evidence\": \"illustrative_shape_only\",\n",
    "        })\n",
    "    print(\"Offline fixtures do not produce GPU timings or tokeniser counts.\")\n",
    "else:\n",
    "    import torch\n",
    "\n",
    "    started = perf_counter()\n",
    "    tokenizer, text_model = load_text()\n",
    "    sync()\n",
    "    load_ms = (perf_counter() - started) * 1000\n",
    "    if text_model.device.type != \"cuda\":\n",
    "        raise RuntimeError(\"The measured profile requires a CUDA model and allocator.\")\n",
    "    config = text_model.config\n",
    "    cache_shape = {\n",
    "        \"layers\": config.num_hidden_layers,\n",
    "        \"kv_heads\": config.num_key_value_heads,\n",
    "        \"head_dim\": getattr(config, \"head_dim\", None) or config.hidden_size // config.num_attention_heads,\n",
    "        \"element_bytes\": next(text_model.parameters()).element_size(),\n",
    "    }\n",
    "    print(\"Measured device and derived cache configuration:\", device_name(), cache_shape)\n",
    "    print(\"Model and tokeniser load, ms:\", load_ms)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-15",
   "metadata": {},
   "source": [
    "## Hold the answer fixed while changing the input\n",
    "\n",
    "Add duplicate copies of records already approved for the request. Guest\n",
    "tickets and requests with no identified equipment still receive no records.\n",
    "The same decision, value and evidence IDs are required in both arms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "lab-02-16",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:18:12.470967Z",
     "iopub.status.busy": "2026-11-27T06:18:12.470101Z",
     "iopub.status.idle": "2026-11-27T06:18:12.479928Z",
     "shell.execute_reply": "2026-11-27T06:18:12.479298Z"
    }
   },
   "outputs": [],
   "source": [
    "CONDITIONS = (\"single_dossier\", \"repeated_dossier\")\n",
    "\n",
    "\n",
    "def records_for(case, condition):\n",
    "    records = safe_context(case)\n",
    "    if condition == \"repeated_dossier\" and records:\n",
    "        return \"\\n\\n\".join([records] * DOSSIER_COPIES)\n",
    "    return records\n",
    "\n",
    "\n",
    "def chat_ids(prompt):\n",
    "    return tokenizer.apply_chat_template(\n",
    "        [{\"role\": \"user\", \"content\": prompt}], tokenize=True, add_generation_prompt=True,\n",
    "    )\n",
    "\n",
    "\n",
    "assert records_for(focus_case, CONDITIONS[1]).count(safe_context(focus_case)) == DOSSIER_COPIES\n",
    "for row in quality_cases:\n",
    "    if row[\"decision\"] != \"answer\":\n",
    "        assert all(not records_for(row, condition) for condition in CONDITIONS)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-17",
   "metadata": {},
   "source": [
    "## Separate prefill and decode\n",
    "\n",
    "A forward pass over the complete input creates the cache. Subsequent passes\n",
    "process one token at a time with that cache and the growing attention mask.\n",
    "The output projection consumes just the last position because that is the\n",
    "position needed to choose the next token. CUDA synchronisation brackets\n",
    "each timing window. The first profile follows model setup and each condition\n",
    "has later repeated measurements. Decode deliberately continues for a fixed\n",
    "token budget, even when the model would usually stop.\n",
    "\n",
    "The length sweep repeats the tokenised F-250 prompt to each exact length.\n",
    "Compare this control with the complete F-250 prompts without truncation.\n",
    "The translated question has the same meaning in each row; it tests how the\n",
    "tokeniser represents the question by itself, without chat framing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "lab-02-18",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:18:12.485546Z",
     "iopub.status.busy": "2026-11-27T06:18:12.484081Z",
     "iopub.status.idle": "2026-11-27T06:18:12.503675Z",
     "shell.execute_reply": "2026-11-27T06:18:12.502874Z"
    }
   },
   "outputs": [],
   "source": [
    "def fixed_length_ids(length):\n",
    "    body = chat_ids(answer_prompt(focus_case, records_for(focus_case, CONDITIONS[0])))\n",
    "    return (body * ((length + len(body) - 1) // len(body)))[:length]\n",
    "\n",
    "\n",
    "def profile_tokens(token_ids):\n",
    "    input_ids = torch.tensor([token_ids], dtype=torch.long, device=text_model.device)\n",
    "    attention_mask = torch.ones(\n",
    "        (1, len(token_ids) + GENERATED_TOKENS - 1), dtype=torch.long, device=text_model.device,\n",
    "    )\n",
    "    sync()\n",
    "    torch.cuda.reset_peak_memory_stats(text_model.device)\n",
    "    allocation_before = torch.cuda.memory_allocated(text_model.device)\n",
    "    with torch.inference_mode():\n",
    "        started = perf_counter()\n",
    "        output = text_model.model(\n",
    "            input_ids=input_ids, attention_mask=attention_mask[:, :len(token_ids)], use_cache=True,\n",
    "        )\n",
    "        cache = output.past_key_values\n",
    "        hidden = output.last_hidden_state[:, -1:]\n",
    "        next_id = text_model.lm_head(hidden).argmax(dim=-1)\n",
    "        del output, hidden\n",
    "        sync()\n",
    "        prefill_ms = (perf_counter() - started) * 1000\n",
    "        prefill_allocated = torch.cuda.memory_allocated(text_model.device)\n",
    "\n",
    "        started = perf_counter()\n",
    "        for step in range(1, GENERATED_TOKENS):\n",
    "            output = text_model.model(\n",
    "                input_ids=next_id, attention_mask=attention_mask[:, :len(token_ids) + step],\n",
    "                past_key_values=cache, use_cache=True,\n",
    "            )\n",
    "            cache = output.past_key_values\n",
    "            next_id = text_model.lm_head(output.last_hidden_state[:, -1:]).argmax(dim=-1)\n",
    "            del output\n",
    "        sync()\n",
    "        decode_ms = (perf_counter() - started) * 1000\n",
    "        final_allocated = torch.cuda.memory_allocated(text_model.device)\n",
    "        peak_allocated = torch.cuda.max_memory_allocated(text_model.device)\n",
    "\n",
    "    final_positions = int(cache.get_seq_length())\n",
    "    tensor_kv = sum(tensor.numel() * tensor.element_size()\n",
    "                    for layer in cache.to_legacy_cache() for tensor in layer)\n",
    "    predicted = kv_bytes(final_positions, **cache_shape)\n",
    "    assert final_positions == len(token_ids) + GENERATED_TOKENS - 1\n",
    "    assert tensor_kv == predicted, (tensor_kv, predicted, cache_shape)\n",
    "    return {\n",
    "        \"input_tokens\": len(token_ids),\n",
    "        \"generated_tokens\": GENERATED_TOKENS,\n",
    "        \"cache_positions\": final_positions,\n",
    "        \"prefill_ms\": prefill_ms,\n",
    "        \"decode_ms\": decode_ms,\n",
    "        \"decode_ms_per_token\": decode_ms / (GENERATED_TOKENS - 1),\n",
    "        \"decode_tokens_per_second\": (GENERATED_TOKENS - 1) / (decode_ms / 1000),\n",
    "        \"baseline_allocated_bytes\": allocation_before,\n",
    "        \"prefill_extra_allocated_bytes\": prefill_allocated - allocation_before,\n",
    "        \"final_extra_allocated_bytes\": final_allocated - allocation_before,\n",
    "        \"peak_extra_allocated_bytes\": peak_allocated - allocation_before,\n",
    "        \"predicted_final_kv_bytes\": predicted,\n",
    "        \"measured_kv_tensor_bytes\": tensor_kv,\n",
    "    }\n",
    "\n",
    "def warm_summary(rows):\n",
    "    first = rows[0]\n",
    "    summary = {name: first[name] for name in (\n",
    "        \"experiment\", \"condition\", \"input_tokens\", \"generated_tokens\", \"cache_positions\",\n",
    "        \"predicted_final_kv_bytes\", \"measured_kv_tensor_bytes\",\n",
    "    )}\n",
    "    summary[\"repeats\"] = len(rows)\n",
    "    for name in (\n",
    "        \"prefill_ms\", \"decode_ms\", \"decode_ms_per_token\", \"decode_tokens_per_second\",\n",
    "        \"baseline_allocated_bytes\", \"prefill_extra_allocated_bytes\",\n",
    "        \"final_extra_allocated_bytes\", \"peak_extra_allocated_bytes\",\n",
    "    ):\n",
    "        observations = [row[name] for row in rows]\n",
    "        summary[f\"median_{name}\"] = median(observations)\n",
    "        summary[f\"min_{name}\"] = min(observations)\n",
    "        summary[f\"max_{name}\"] = max(observations)\n",
    "    return summary"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-19",
   "metadata": {},
   "source": [
    "## Profile the waiting time\n",
    "\n",
    "Measure the first short-dossier profile separately from warmed profiles.\n",
    "Reverse the order on alternating rounds and keep the individual times.\n",
    "The ranges describe the observed repetitions in one session."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "lab-02-20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:18:12.508083Z",
     "iopub.status.busy": "2026-11-27T06:18:12.507697Z",
     "iopub.status.idle": "2026-11-27T06:18:54.355152Z",
     "shell.execute_reply": "2026-11-27T06:18:54.354036Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First request profile: {'experiment': 'f250', 'condition': 'single_dossier', 'phase': 'first_profile', 'repeat': 0, 'input_tokens': 279, 'generated_tokens': 9, 'cache_positions': 287, 'prefill_ms': 3675.9109150000313, 'decode_ms': 996.1697720000302, 'decode_ms_per_token': 124.52122150000378, 'decode_tokens_per_second': 8.030759640435825, 'baseline_allocated_bytes': 3087434240, 'prefill_extra_allocated_bytes': 16519680, 'final_extra_allocated_bytes': 16749056, 'peak_extra_allocated_bytes': 35092480, 'predicted_final_kv_bytes': 8228864, 'measured_kv_tensor_bytes': 8228864}\n"
     ]
    }
   ],
   "source": [
    "first_profile = None\n",
    "if not COURSE_SMOKE:\n",
    "    length_inputs = [(f\"{length} tokens\", fixed_length_ids(length)) for length in PROMPT_LENGTHS]\n",
    "    focus_inputs = [\n",
    "        (condition, chat_ids(answer_prompt(focus_case, records_for(focus_case, condition))))\n",
    "        for condition in CONDITIONS\n",
    "    ]\n",
    "    language_inputs = []\n",
    "    for language, request in LANGUAGE_TEXT.items():\n",
    "        token_ids = tokenizer.encode(request, add_special_tokens=False)\n",
    "        language_inputs.append((language, token_ids))\n",
    "        language_rows.append({\n",
    "            \"language\": language, \"prompt\": request,\n",
    "            \"characters\": len(request), \"tokens\": len(token_ids),\n",
    "        })\n",
    "\n",
    "    first_name, first_tokens = focus_inputs[0]\n",
    "    first_profile = {\n",
    "        \"experiment\": \"f250\", \"condition\": first_name, \"phase\": \"first_profile\", \"repeat\": 0,\n",
    "        **profile_tokens(first_tokens),\n",
    "    }\n",
    "    measurements.append(first_profile)\n",
    "    print(\"First request profile:\", first_profile)\n",
    "\n",
    "    warm_inputs = [\n",
    "        (experiment, *row)\n",
    "        for experiment, inputs in ((\"length\", length_inputs), (\"f250\", focus_inputs),\n",
    "                                   (\"translated_request\", language_inputs))\n",
    "        for row in inputs\n",
    "    ]\n",
    "    for repeat in range(1, REPEATS + 1):\n",
    "        # Reverse order on alternating repeats to expose measurement-order effects.\n",
    "        ordering = warm_inputs if repeat % 2 else list(reversed(warm_inputs))\n",
    "        for experiment, label, token_ids in ordering:\n",
    "            measurements.append({\n",
    "                \"experiment\": experiment, \"condition\": label, \"phase\": \"warm\", \"repeat\": repeat,\n",
    "                **profile_tokens(token_ids),\n",
    "            })\n",
    "\n",
    "    for experiment, condition, _ in warm_inputs:\n",
    "        rows = [row for row in measurements if row[\"experiment\"] == experiment\n",
    "                and row[\"condition\"] == condition and row[\"phase\"] == \"warm\"]\n",
    "        assert len(rows) == REPEATS\n",
    "        profile_summary.append(warm_summary(rows))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-21",
   "metadata": {},
   "source": [
    "## Check strict answers separately\n",
    "\n",
    "Profile timings use a fixed, short decode. For the quality comparison,\n",
    "use greedy generation with a separate token cap so the desk can emit its\n",
    "complete JSON. Grade the same tickets under both dossier conditions.\n",
    "Keep every ticket in the denominator, including invalid JSON."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "lab-02-22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:18:54.360518Z",
     "iopub.status.busy": "2026-11-27T06:18:54.360123Z",
     "iopub.status.idle": "2026-11-27T06:19:28.016359Z",
     "shell.execute_reply": "2026-11-27T06:19:28.015392Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.13/dist-packages/transformers/generation/configuration_utils.py:631: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.7` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.\n",
      "  warnings.warn(\n",
      "/usr/local/lib/python3.13/dist-packages/transformers/generation/configuration_utils.py:636: UserWarning: `do_sample` is set to `False`. However, `top_p` is set to `0.8` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_p`.\n",
      "  warnings.warn(\n",
      "/usr/local/lib/python3.13/dist-packages/transformers/generation/configuration_utils.py:653: UserWarning: `do_sample` is set to `False`. However, `top_k` is set to `20` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_k`.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "def grade_output(case, condition, raw, input_tokens):\n",
    "    expected = {key: case[key] for key in (\"decision\", \"value\", \"evidence\")}\n",
    "    output = decode_answer(raw)\n",
    "    passed = score_answer(case, output)\n",
    "    if passed:\n",
    "        reason = \"pass\"\n",
    "    elif not output:\n",
    "        reason = \"unparseable_or_empty_object\"\n",
    "    elif output.get(\"decision\") != expected[\"decision\"]:\n",
    "        reason = \"wrong_decision\"\n",
    "    elif not isinstance(output.get(\"value\"), str) or output[\"value\"].strip() != expected[\"value\"]:\n",
    "        reason = \"wrong_value\"\n",
    "    else:\n",
    "        reason = \"wrong_evidence\"\n",
    "    return {\n",
    "        \"id\": case[\"id\"], \"family\": case[\"family\"], \"slice\": case[\"slice\"],\n",
    "        \"question\": case[\"question\"], \"previous_asset\": case[\"previous_asset\"],\n",
    "        \"role\": case[\"role\"], \"expected\": expected, \"condition\": condition,\n",
    "        \"input_tokens\": input_tokens, \"raw\": raw, \"parsed\": output,\n",
    "        \"strict_pass\": passed, \"reason\": reason,\n",
    "    }\n",
    "\n",
    "\n",
    "def summarise_quality(rows):\n",
    "    scores = {\n",
    "        condition: [row[\"strict_pass\"] for row in rows if row[\"condition\"] == condition]\n",
    "        for condition in CONDITIONS\n",
    "    }\n",
    "    original, repeated = (scores[condition] for condition in CONDITIONS)\n",
    "    return {\n",
    "        \"all\": {condition: {\"passed\": sum(values), \"n\": len(values)}\n",
    "                for condition, values in scores.items()},\n",
    "        \"slices\": [\n",
    "            {\"slice\": name, \"condition\": condition, \"n\": len(selected),\n",
    "             \"passed\": sum(row[\"strict_pass\"] for row in selected)}\n",
    "            for name in SLICES for condition in CONDITIONS\n",
    "            if (selected := [row for row in rows if row[\"slice\"] == name and row[\"condition\"] == condition])\n",
    "        ],\n",
    "        \"paired\": paired_interval(quality_cases, repeated, original),\n",
    "    }\n",
    "\n",
    "\n",
    "quality_rows = []\n",
    "if COURSE_SMOKE:\n",
    "    assert grade_output(focus_case, CONDITIONS[0], \"not JSON\", None)[\"reason\"] == \"unparseable_or_empty_object\"\n",
    "    for condition in CONDITIONS:\n",
    "        for case in quality_cases:\n",
    "            fake = {key: case[key] for key in (\"decision\", \"value\", \"evidence\")}\n",
    "            if condition == CONDITIONS[1] and case[\"id\"] == focus_case[\"id\"]:\n",
    "                fake[\"value\"] = \"wrong\"\n",
    "            quality_rows.append(grade_output(case, condition, json.dumps(fake), None))\n",
    "    fixture_quality = summarise_quality(quality_rows)\n",
    "    assert fixture_quality[\"paired\"][\"delta\"] == -1 / len(quality_cases)\n",
    "    assert next(row for row in quality_rows if row[\"reason\"] == \"wrong_value\")[\"id\"] == focus_case[\"id\"]\n",
    "    print(\"Offline checks passed for paired grading, malformed JSON and wrong values.\")\n",
    "    quality_rows.clear()\n",
    "else:\n",
    "    for condition in CONDITIONS:\n",
    "        prompts = [answer_prompt(case, records_for(case, condition)) for case in quality_cases]\n",
    "        for offset in range(0, len(prompts), QUALITY_BATCH):\n",
    "            batch = prompts[offset:offset + QUALITY_BATCH]\n",
    "            replies = generate(tokenizer, text_model, batch, max_new_tokens=QUALITY_TOKEN_BUDGET)\n",
    "            selected = quality_cases[offset:offset + QUALITY_BATCH]\n",
    "            for case, prompt, raw in zip(selected, batch, replies, strict=True):\n",
    "                quality_rows.append(grade_output(case, condition, raw, len(chat_ids(prompt))))\n",
    "    assert all([row[\"id\"] for row in quality_rows if row[\"condition\"] == condition]\n",
    "               == [case[\"id\"] for case in quality_cases] for condition in CONDITIONS)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-23",
   "metadata": {},
   "source": [
    "## Read the evidence\n",
    "\n",
    "Inspect the F-250 profiles, the two complete replies and the input IDs\n",
    "before interpreting aggregate accuracy. A repeated record adds tokens\n",
    "without adding any independent facts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "lab-02-24",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-27T06:19:28.021839Z",
     "iopub.status.busy": "2026-11-27T06:19:28.021485Z",
     "iopub.status.idle": "2026-11-27T06:19:28.421240Z",
     "shell.execute_reply": "2026-11-27T06:19:28.420291Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Profile summary:\n",
      "{'experiment': 'length', 'condition': '128 tokens', 'input_tokens': 128, 'generated_tokens': 9, 'cache_positions': 136, 'predicted_final_kv_bytes': 3899392, 'measured_kv_tensor_bytes': 3899392, 'repeats': 7, 'median_prefill_ms': 59.47935099999313, 'min_prefill_ms': 57.477638000023035, 'max_prefill_ms': 501.6096670000252, 'median_decode_ms': 474.3297480000024, 'min_decode_ms': 463.2748599999559, 'max_decode_ms': 629.1289730000358, 'median_decode_ms_per_token': 59.2912185000003, 'min_decode_ms_per_token': 57.909357499994485, 'max_decode_ms_per_token': 78.64112162500447, 'median_decode_tokens_per_second': 16.865904012412816, 'min_decode_tokens_per_second': 12.715993609150702, 'max_decode_tokens_per_second': 17.26836634304042, 'median_baseline_allocated_bytes': 3095951360, 'min_baseline_allocated_bytes': 3095951360, 'max_baseline_allocated_bytes': 3095951360, 'median_prefill_extra_allocated_bytes': 3670528, 'min_prefill_extra_allocated_bytes': 3670528, 'max_prefill_extra_allocated_bytes': 3670528, 'median_final_extra_allocated_bytes': 3899904, 'min_final_extra_allocated_bytes': 3899904, 'max_final_extra_allocated_bytes': 3899904, 'median_peak_extra_allocated_bytes': 12649472, 'min_peak_extra_allocated_bytes': 12649472, 'max_peak_extra_allocated_bytes': 12649472}\n",
      "{'experiment': 'length', 'condition': '512 tokens', 'input_tokens': 512, 'generated_tokens': 9, 'cache_positions': 520, 'predicted_final_kv_bytes': 14909440, 'measured_kv_tensor_bytes': 14909440, 'repeats': 7, 'median_prefill_ms': 138.8662150000073, 'min_prefill_ms': 127.7788419999979, 'max_prefill_ms': 183.73428400002467, 'median_decode_ms': 482.3870580000289, 'min_decode_ms': 427.44668599999613, 'max_decode_ms': 520.8030239999744, 'median_decode_ms_per_token': 60.29838225000361, 'min_decode_ms_per_token': 53.43083574999952, 'max_decode_ms_per_token': 65.1003779999968, 'median_decode_tokens_per_second': 16.584192853697, 'min_decode_tokens_per_second': 15.36089391063212, 'max_decode_tokens_per_second': 18.715784358660514, 'median_baseline_allocated_bytes': 3095957504, 'min_baseline_allocated_bytes': 3095957504, 'max_baseline_allocated_bytes': 3095957504, 'median_prefill_extra_allocated_bytes': 14680576, 'min_prefill_extra_allocated_bytes': 14680576, 'max_prefill_extra_allocated_bytes': 14680576, 'median_final_extra_allocated_bytes': 14909952, 'min_final_extra_allocated_bytes': 14909952, 'max_final_extra_allocated_bytes': 14909952, 'median_peak_extra_allocated_bytes': 50728960, 'min_peak_extra_allocated_bytes': 50728960, 'max_peak_extra_allocated_bytes': 50728960}\n",
      "{'experiment': 'length', 'condition': '1024 tokens', 'input_tokens': 1024, 'generated_tokens': 9, 'cache_positions': 1032, 'predicted_final_kv_bytes': 29589504, 'measured_kv_tensor_bytes': 29589504, 'repeats': 7, 'median_prefill_ms': 280.9143339999878, 'min_prefill_ms': 245.40379300003679, 'max_prefill_ms': 295.8350229999951, 'median_decode_ms': 459.5873940000388, 'min_decode_ms': 455.3732150000087, 'max_decode_ms': 645.5043670000009, 'median_decode_ms_per_token': 57.44842425000485, 'min_decode_ms_per_token': 56.92165187500109, 'max_decode_ms_per_token': 80.68804587500011, 'median_decode_tokens_per_second': 17.406917823336393, 'min_decode_tokens_per_second': 12.393409570844915, 'max_decode_tokens_per_second': 17.568007376103242, 'median_baseline_allocated_bytes': 3095965696, 'min_baseline_allocated_bytes': 3095965696, 'max_baseline_allocated_bytes': 3095965696, 'median_prefill_extra_allocated_bytes': 29360640, 'min_prefill_extra_allocated_bytes': 29360640, 'max_prefill_extra_allocated_bytes': 29360640, 'median_final_extra_allocated_bytes': 29590016, 'min_final_extra_allocated_bytes': 29590016, 'max_final_extra_allocated_bytes': 29590016, 'median_peak_extra_allocated_bytes': 100671488, 'min_peak_extra_allocated_bytes': 100671488, 'max_peak_extra_allocated_bytes': 100671488}\n",
      "{'experiment': 'f250', 'condition': 'single_dossier', 'input_tokens': 279, 'generated_tokens': 9, 'cache_positions': 287, 'predicted_final_kv_bytes': 8228864, 'measured_kv_tensor_bytes': 8228864, 'repeats': 7, 'median_prefill_ms': 105.898676000038, 'min_prefill_ms': 86.9066810000163, 'max_prefill_ms': 136.57026200002065, 'median_decode_ms': 460.5659229999901, 'min_decode_ms': 371.6574039999614, 'max_decode_ms': 685.7799750000027, 'median_decode_ms_per_token': 57.57074037499876, 'min_decode_ms_per_token': 46.457175499995174, 'max_decode_ms_per_token': 85.72249687500033, 'median_decode_tokens_per_second': 17.369934683596146, 'min_decode_tokens_per_second': 11.665549143513514, 'max_decode_tokens_per_second': 21.525200127590708, 'median_baseline_allocated_bytes': 3095953920, 'min_baseline_allocated_bytes': 3095953920, 'max_baseline_allocated_bytes': 3095953920, 'median_prefill_extra_allocated_bytes': 8000000, 'min_prefill_extra_allocated_bytes': 8000000, 'max_prefill_extra_allocated_bytes': 8000000, 'median_final_extra_allocated_bytes': 8229376, 'min_final_extra_allocated_bytes': 8229376, 'max_final_extra_allocated_bytes': 8229376, 'median_peak_extra_allocated_bytes': 26572800, 'min_peak_extra_allocated_bytes': 26572800, 'max_peak_extra_allocated_bytes': 26572800}\n",
      "{'experiment': 'f250', 'condition': 'repeated_dossier', 'input_tokens': 1105, 'generated_tokens': 9, 'cache_positions': 1113, 'predicted_final_kv_bytes': 31911936, 'measured_kv_tensor_bytes': 31911936, 'repeats': 7, 'median_prefill_ms': 326.07755900005486, 'min_prefill_ms': 290.34402500002443, 'max_prefill_ms': 378.30475499998784, 'median_decode_ms': 484.0855159999933, 'min_decode_ms': 467.27563899997904, 'max_decode_ms': 632.4240700000132, 'median_decode_ms_per_token': 60.51068949999916, 'min_decode_ms_per_token': 58.40945487499738, 'max_decode_ms_per_token': 79.05300875000165, 'median_decode_tokens_per_second': 16.5260057068101, 'min_decode_tokens_per_second': 12.649739912650436, 'max_decode_tokens_per_second': 17.120515884630482, 'median_baseline_allocated_bytes': 3095967232, 'min_baseline_allocated_bytes': 3095967232, 'max_baseline_allocated_bytes': 3095967232, 'median_prefill_extra_allocated_bytes': 31683072, 'min_prefill_extra_allocated_bytes': 31683072, 'max_prefill_extra_allocated_bytes': 31683072, 'median_final_extra_allocated_bytes': 31912448, 'min_final_extra_allocated_bytes': 31912448, 'max_final_extra_allocated_bytes': 31912448, 'median_peak_extra_allocated_bytes': 107391488, 'min_peak_extra_allocated_bytes': 107391488, 'max_peak_extra_allocated_bytes': 107391488}\n",
      "{'experiment': 'translated_request', 'condition': 'English', 'input_tokens': 6, 'generated_tokens': 9, 'cache_positions': 14, 'predicted_final_kv_bytes': 401408, 'measured_kv_tensor_bytes': 401408, 'repeats': 7, 'median_prefill_ms': 68.54464000002736, 'min_prefill_ms': 52.63523100001066, 'max_prefill_ms': 211.33066599998074, 'median_decode_ms': 538.7886780000031, 'min_decode_ms': 375.4392769999981, 'max_decode_ms': 642.9063260000021, 'median_decode_ms_per_token': 67.34858475000038, 'min_decode_ms_per_token': 46.929909624999766, 'max_decode_ms_per_token': 80.36329075000026, 'median_decode_tokens_per_second': 14.848121957009562, 'min_decode_tokens_per_second': 12.443492428786545, 'max_decode_tokens_per_second': 21.308372592034477, 'median_baseline_allocated_bytes': 3095949824, 'min_baseline_allocated_bytes': 3095949824, 'max_baseline_allocated_bytes': 3095949824, 'median_prefill_extra_allocated_bytes': 172544, 'min_prefill_extra_allocated_bytes': 172544, 'max_prefill_extra_allocated_bytes': 172544, 'median_final_extra_allocated_bytes': 401920, 'min_final_extra_allocated_bytes': 401920, 'max_final_extra_allocated_bytes': 401920, 'median_peak_extra_allocated_bytes': 710656, 'min_peak_extra_allocated_bytes': 710656, 'max_peak_extra_allocated_bytes': 710656}\n",
      "{'experiment': 'translated_request', 'condition': 'Spanish', 'input_tokens': 8, 'generated_tokens': 9, 'cache_positions': 16, 'predicted_final_kv_bytes': 458752, 'measured_kv_tensor_bytes': 458752, 'repeats': 7, 'median_prefill_ms': 58.82332200002338, 'min_prefill_ms': 57.387383000047976, 'max_prefill_ms': 109.4739370000184, 'median_decode_ms': 483.9076479999562, 'min_decode_ms': 456.0182839999811, 'max_decode_ms': 707.5201929999935, 'median_decode_ms_per_token': 60.48845599999453, 'min_decode_ms_per_token': 57.00228549999764, 'max_decode_ms_per_token': 88.44002412499918, 'median_decode_tokens_per_second': 16.53208010467469, 'min_decode_tokens_per_second': 11.307097774946579, 'max_decode_tokens_per_second': 17.543156230113638, 'median_baseline_allocated_bytes': 3095949824, 'min_baseline_allocated_bytes': 3095949824, 'max_baseline_allocated_bytes': 3095949824, 'median_prefill_extra_allocated_bytes': 229888, 'min_prefill_extra_allocated_bytes': 229888, 'max_prefill_extra_allocated_bytes': 229888, 'median_final_extra_allocated_bytes': 459264, 'min_final_extra_allocated_bytes': 459264, 'max_final_extra_allocated_bytes': 459264, 'median_peak_extra_allocated_bytes': 768000, 'min_peak_extra_allocated_bytes': 768000, 'max_peak_extra_allocated_bytes': 768000}\n",
      "{'experiment': 'translated_request', 'condition': 'Hindi', 'input_tokens': 26, 'generated_tokens': 9, 'cache_positions': 34, 'predicted_final_kv_bytes': 974848, 'measured_kv_tensor_bytes': 974848, 'repeats': 7, 'median_prefill_ms': 59.38708600001519, 'min_prefill_ms': 57.763311000030626, 'max_prefill_ms': 235.67512400001078, 'median_decode_ms': 480.005675999962, 'min_decode_ms': 462.56871600002114, 'max_decode_ms': 719.8407669999938, 'median_decode_ms_per_token': 60.00070949999525, 'min_decode_ms_per_token': 57.82108950000264, 'max_decode_ms_per_token': 89.98009587499922, 'median_decode_tokens_per_second': 16.666469585665133, 'min_decode_tokens_per_second': 11.113568954062961, 'max_decode_tokens_per_second': 17.29472773078678, 'median_baseline_allocated_bytes': 3095949824, 'min_baseline_allocated_bytes': 3095949824, 'max_baseline_allocated_bytes': 3095949824, 'median_prefill_extra_allocated_bytes': 745984, 'min_prefill_extra_allocated_bytes': 745984, 'max_prefill_extra_allocated_bytes': 745984, 'median_final_extra_allocated_bytes': 975360, 'min_final_extra_allocated_bytes': 975360, 'max_final_extra_allocated_bytes': 975360, 'median_peak_extra_allocated_bytes': 2476544, 'min_peak_extra_allocated_bytes': 2476544, 'max_peak_extra_allocated_bytes': 2476544}\n",
      "Translated request token counts: [{'language': 'English', 'prompt': 'What is its maximum temperature?', 'characters': 32, 'tokens': 6}, {'language': 'Spanish', 'prompt': '¿Cuál es su temperatura máxima?', 'characters': 31, 'tokens': 8}, {'language': 'Hindi', 'prompt': 'इसका अधिकतम तापमान क्या है?', 'characters': 27, 'tokens': 26}]\n",
      "Strict quality: {'all': {'single_dossier': {'passed': 0, 'n': 24}, 'repeated_dossier': {'passed': 0, 'n': 24}}, 'slices': [{'slice': 'manual', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'manual', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}, {'slice': 'numeric', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'numeric', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}, {'slice': 'multi_source', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'multi_source', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}, {'slice': 'ambiguity', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'ambiguity', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}, {'slice': 'boundary', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'boundary', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}, {'slice': 'follow_up', 'condition': 'single_dossier', 'n': 4, 'passed': 0}, {'slice': 'follow_up', 'condition': 'repeated_dossier', 'n': 4, 'passed': 0}], 'paired': {'delta': 0.0, 'low': 0.0, 'high': 0.0, 'n': 24, 'families': 12}}\n",
      "F-250 response: {'id': 'F250-00', 'family': 'F250', 'slice': 'follow_up', 'question': 'What is its maximum temperature?', 'previous_asset': 'F-250', 'role': 'operator', 'expected': {'decision': 'answer', 'value': '101', 'evidence': ['manual-F-250-r3']}, 'condition': 'single_dossier', 'input_tokens': 279, 'raw': '```json\\n{\\n  \"decision\": \"The maximum temperature of F-250 is 101°C.\",\\n  \"value\": null,\\n  \"evidence\": [\\n    \"inventory-F-250-r3\",\\n', 'parsed': {}, 'strict_pass': 0, 'reason': 'unparseable_or_empty_object'}\n",
      "First strict failure: {'id': 'F200-00', 'family': 'F200', 'slice': 'manual', 'question': 'What is the maximum temperature for V-200?', 'previous_asset': '', 'role': 'operator', 'expected': {'decision': 'answer', 'value': '87', 'evidence': ['manual-V-200-r3']}, 'condition': 'single_dossier', 'input_tokens': 279, 'raw': '```json\\n{\\n  \"decision\": \"The maximum temperature for V-200 is 87°C.\",\\n  \"value\": null,\\n  \"evidence\": [\\n    \"manual-V-200-r3\",\\n   ', 'parsed': {}, 'strict_pass': 0, 'reason': 'unparseable_or_empty_object'}\n",
      "F-250 response: {'id': 'F250-00', 'family': 'F250', 'slice': 'follow_up', 'question': 'What is its maximum temperature?', 'previous_asset': 'F-250', 'role': 'operator', 'expected': {'decision': 'answer', 'value': '101', 'evidence': ['manual-F-250-r3']}, 'condition': 'repeated_dossier', 'input_tokens': 1105, 'raw': '```json\\n{\\n  \"decision\": \"The maximum temperature of the F-250 equipment is 101°C.\",\\n  \"value\": null,\\n  \"evidence\": [\\n    \"manual-F-250-r', 'parsed': {}, 'strict_pass': 0, 'reason': 'unparseable_or_empty_object'}\n",
      "First strict failure: {'id': 'F200-00', 'family': 'F200', 'slice': 'manual', 'question': 'What is the maximum temperature for V-200?', 'previous_asset': '', 'role': 'operator', 'expected': {'decision': 'answer', 'value': '87', 'evidence': ['manual-V-200-r3']}, 'condition': 'repeated_dossier', 'input_tokens': 1091, 'raw': '```json\\n{\\n  \"decision\": \"The maximum temperature for V-200 is 87°C.\",\\n  \"value\": null,\\n  \"evidence\": [\\n    \"manual-V-200-r3\",\\n   ', 'parsed': {}, 'strict_pass': 0, 'reason': 'unparseable_or_empty_object'}\n",
      "Measurement wall time, seconds: 95.11141714700005\n",
      "Evidence saved to evidence/summary.json\n",
      "Evidence saved to evidence/records.json\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"591.59952pt\" height=\"234.47952pt\" viewBox=\"0 0 591.59952 234.47952\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2026-11-27T06:19:28.368009</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.10.0, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 234.47952 \n",
       "L 591.59952 234.47952 \n",
       "L 591.59952 -0 \n",
       "L 0 -0 \n",
       "z\n",
       "\" style=\"fill: #f5f7f2\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 73.995312 194.92327 \n",
       "L 584.39952 194.92327 \n",
       "L 584.39952 34.3575 \n",
       "L 73.995312 34.3575 \n",
       "z\n",
       "\" style=\"fill: #f5f7f2\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 73.995312 194.92327 \n",
       "L 73.995312 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\"/>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 0 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(70.814062 207.521707) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 150.984253 194.92327 \n",
       "L 150.984253 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\"/>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 50 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(144.621753 207.521707) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 227.973193 194.92327 \n",
       "L 227.973193 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\"/>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 100 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(218.429443 207.521707) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 304.962134 194.92327 \n",
       "L 304.962134 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\"/>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 150 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(295.418384 207.521707) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 381.951074 194.92327 \n",
       "L 381.951074 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\"/>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 200 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(372.407324 207.521707) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 458.940015 194.92327 \n",
       "L 458.940015 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\"/>\n",
       "     <g id=\"text_6\">\n",
       "      <!-- 250 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(449.396265 207.521707) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_7\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <path d=\"M 535.928955 194.92327 \n",
       "L 535.928955 34.3575 \n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: none; stroke: #d3ded6; stroke-width: 0.75; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_14\"/>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 300 -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(526.385205 207.521707) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-33\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(127.246094 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_8\">\n",
       "     <!-- Milliseconds -->\n",
       "     <g style=\"fill: #20382f\" transform=\"translate(73.995312 225.199833) scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-4d\" d=\"M 628 4666 \n",
       "L 1569 4666 \n",
       "L 2759 1491 \n",
       "L 3956 4666 \n",
       "L 4897 4666 \n",
       "L 4897 0 \n",
       "L 4281 0 \n",
       "L 4281 4097 \n",
       "L 3078 897 \n",
       "L 2444 897 \n",
       "L 1241 4097 \n",
       "L 1241 0 \n",
       "L 628 0 \n",
       "L 628 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \n",
       "L 1178 3500 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 3500 \n",
       "z\n",
       "M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 4134 \n",
       "L 603 4134 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \n",
       "L 2834 2853 \n",
       "Q 2591 2978 2328 3040 \n",
       "Q 2066 3103 1784 3103 \n",
       "Q 1356 3103 1142 2972 \n",
       "Q 928 2841 928 2578 \n",
       "Q 928 2378 1081 2264 \n",
       "Q 1234 2150 1697 2047 \n",
       "L 1894 2003 \n",
       "Q 2506 1872 2764 1633 \n",
       "Q 3022 1394 3022 966 \n",
       "Q 3022 478 2636 193 \n",
       "Q 2250 -91 1575 -91 \n",
       "Q 1294 -91 989 -36 \n",
       "Q 684 19 347 128 \n",
       "L 347 722 \n",
       "Q 666 556 975 473 \n",
       "Q 1284 391 1588 391 \n",
       "Q 1994 391 2212 530 \n",
       "Q 2431 669 2431 922 \n",
       "Q 2431 1156 2273 1281 \n",
       "Q 2116 1406 1581 1522 \n",
       "L 1381 1569 \n",
       "Q 847 1681 609 1914 \n",
       "Q 372 2147 372 2553 \n",
       "Q 372 3047 722 3315 \n",
       "Q 1072 3584 1716 3584 \n",
       "Q 2034 3584 2315 3537 \n",
       "Q 2597 3491 2834 3397 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-64\" d=\"M 2906 2969 \n",
       "L 2906 4863 \n",
       "L 3481 4863 \n",
       "L 3481 0 \n",
       "L 2906 0 \n",
       "L 2906 525 \n",
       "Q 2725 213 2448 61 \n",
       "Q 2172 -91 1784 -91 \n",
       "Q 1150 -91 751 415 \n",
       "Q 353 922 353 1747 \n",
       "Q 353 2572 751 3078 \n",
       "Q 1150 3584 1784 3584 \n",
       "Q 2172 3584 2448 3432 \n",
       "Q 2725 3281 2906 2969 \n",
       "z\n",
       "M 947 1747 \n",
       "Q 947 1113 1208 752 \n",
       "Q 1469 391 1925 391 \n",
       "Q 2381 391 2643 752 \n",
       "Q 2906 1113 2906 1747 \n",
       "Q 2906 2381 2643 2742 \n",
       "Q 2381 3103 1925 3103 \n",
       "Q 1469 3103 1208 2742 \n",
       "Q 947 2381 947 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-4d\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(86.279297 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(114.0625 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(141.845703 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(169.628906 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(197.412109 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(249.511719 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(311.035156 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(366.015625 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(427.197266 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(490.576172 0)\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(554.052734 0)\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_15\"/>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 128 tokens -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(13.5625 61.196905) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \n",
       "Q 1584 2216 1326 1975 \n",
       "Q 1069 1734 1069 1313 \n",
       "Q 1069 891 1326 650 \n",
       "Q 1584 409 2034 409 \n",
       "Q 2484 409 2743 651 \n",
       "Q 3003 894 3003 1313 \n",
       "Q 3003 1734 2745 1975 \n",
       "Q 2488 2216 2034 2216 \n",
       "z\n",
       "M 1403 2484 \n",
       "Q 997 2584 770 2862 \n",
       "Q 544 3141 544 3541 \n",
       "Q 544 4100 942 4425 \n",
       "Q 1341 4750 2034 4750 \n",
       "Q 2731 4750 3128 4425 \n",
       "Q 3525 4100 3525 3541 \n",
       "Q 3525 3141 3298 2862 \n",
       "Q 3072 2584 2669 2484 \n",
       "Q 3125 2378 3379 2068 \n",
       "Q 3634 1759 3634 1313 \n",
       "Q 3634 634 3220 271 \n",
       "Q 2806 -91 2034 -91 \n",
       "Q 1263 -91 848 271 \n",
       "Q 434 634 434 1313 \n",
       "Q 434 1759 690 2068 \n",
       "Q 947 2378 1403 2484 \n",
       "z\n",
       "M 1172 3481 \n",
       "Q 1172 3119 1398 2916 \n",
       "Q 1625 2713 2034 2713 \n",
       "Q 2441 2713 2670 2916 \n",
       "Q 2900 3119 2900 3481 \n",
       "Q 2900 3844 2670 4047 \n",
       "Q 2441 4250 2034 4250 \n",
       "Q 1625 4250 1398 4047 \n",
       "Q 1172 3844 1172 3481 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \n",
       "L 1172 3500 \n",
       "L 2356 3500 \n",
       "L 2356 3053 \n",
       "L 1172 3053 \n",
       "L 1172 1153 \n",
       "Q 1172 725 1289 603 \n",
       "Q 1406 481 1766 481 \n",
       "L 2356 481 \n",
       "L 2356 0 \n",
       "L 1766 0 \n",
       "Q 1100 0 847 248 \n",
       "Q 594 497 594 1153 \n",
       "L 594 3053 \n",
       "L 172 3053 \n",
       "L 172 3500 \n",
       "L 594 3500 \n",
       "L 594 4494 \n",
       "L 1172 4494 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 1991 \n",
       "L 2875 3500 \n",
       "L 3609 3500 \n",
       "L 1753 1863 \n",
       "L 3688 0 \n",
       "L 2938 0 \n",
       "L 1159 1709 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(127.246094 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(190.869141 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(222.65625 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(261.865234 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(323.046875 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(377.332031 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(438.855469 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(502.234375 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_16\"/>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 512 tokens -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(13.5625 118.439604) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(127.246094 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(190.869141 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(222.65625 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(261.865234 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(323.046875 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(377.332031 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(438.855469 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(502.234375 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_17\"/>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 1024 tokens -->\n",
       "      <g style=\"fill: #20382f\" transform=\"translate(7.2 175.682303) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \n",
       "L 825 1625 \n",
       "L 2419 1625 \n",
       "L 2419 4116 \n",
       "z\n",
       "M 2253 4666 \n",
       "L 3047 4666 \n",
       "L 3047 1625 \n",
       "L 3713 1625 \n",
       "L 3713 1100 \n",
       "L 3047 1100 \n",
       "L 3047 0 \n",
       "L 2419 0 \n",
       "L 2419 1100 \n",
       "L 313 1100 \n",
       "L 313 1709 \n",
       "L 2253 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(63.623047 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(127.246094 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(190.869141 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(254.492188 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(286.279297 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(325.488281 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6b\" transform=\"translate(386.669922 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(440.955078 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(502.478516 0)\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(565.857422 0)\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 73.995312 41.655944 \n",
       "L 165.580357 41.655944 \n",
       "L 165.580357 73.139428 \n",
       "L 73.995312 73.139428 \n",
       "z\n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: #3d6b5b\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 73.995312 98.898643 \n",
       "L 287.818568 98.898643 \n",
       "L 287.818568 130.382127 \n",
       "L 73.995312 130.382127 \n",
       "z\n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: #298876\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 73.995312 156.141342 \n",
       "L 506.541251 156.141342 \n",
       "L 506.541251 187.624826 \n",
       "L 73.995312 187.624826 \n",
       "z\n",
       "\" clip-path=\"url(#p8be93d0e39)\" style=\"fill: #7b97a2\"/>\n",
       "   </g>\n",
       "   <g id=\"text_12\">\n",
       "    <!-- 59.5 -->\n",
       "    <g style=\"fill: #20382f\" transform=\"translate(171.580357 60.157061) scale(0.1 -0.1)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-39\" d=\"M 703 97 \n",
       "L 703 672 \n",
       "Q 941 559 1184 500 \n",
       "Q 1428 441 1663 441 \n",
       "Q 2288 441 2617 861 \n",
       "Q 2947 1281 2994 2138 \n",
       "Q 2813 1869 2534 1725 \n",
       "Q 2256 1581 1919 1581 \n",
       "Q 1219 1581 811 2004 \n",
       "Q 403 2428 403 3163 \n",
       "Q 403 3881 828 4315 \n",
       "Q 1253 4750 1959 4750 \n",
       "Q 2769 4750 3195 4129 \n",
       "Q 3622 3509 3622 2328 \n",
       "Q 3622 1225 3098 567 \n",
       "Q 2575 -91 1691 -91 \n",
       "Q 1453 -91 1209 -44 \n",
       "Q 966 3 703 97 \n",
       "z\n",
       "M 1959 2075 \n",
       "Q 2384 2075 2632 2365 \n",
       "Q 2881 2656 2881 3163 \n",
       "Q 2881 3666 2632 3958 \n",
       "Q 2384 4250 1959 4250 \n",
       "Q 1534 4250 1286 3958 \n",
       "Q 1038 3666 1038 3163 \n",
       "Q 1038 2656 1286 2365 \n",
       "Q 1534 2075 1959 2075 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-39\" transform=\"translate(63.623047 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(127.246094 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(159.033203 0)\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_13\">\n",
       "    <!-- 139 -->\n",
       "    <g style=\"fill: #20382f\" transform=\"translate(293.818568 117.39976) scale(0.1 -0.1)\">\n",
       "     <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-33\" transform=\"translate(63.623047 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-39\" transform=\"translate(127.246094 0)\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_14\">\n",
       "    <!-- 281 -->\n",
       "    <g style=\"fill: #20382f\" transform=\"translate(512.541251 174.642459) scale(0.1 -0.1)\">\n",
       "     <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-38\" transform=\"translate(63.623047 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-31\" transform=\"translate(127.246094 0)\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"text_15\">\n",
       "    <!-- Warm prefill by input length -->\n",
       "    <g style=\"fill: #20382f\" transform=\"translate(73.995312 19.3575) scale(0.16 -0.16)\">\n",
       "     <defs>\n",
       "      <path id=\"DejaVuSans-Bold-57\" d=\"M 191 4666 \n",
       "L 1344 4666 \n",
       "L 2150 1275 \n",
       "L 2950 4666 \n",
       "L 4109 4666 \n",
       "L 4909 1275 \n",
       "L 5716 4666 \n",
       "L 6859 4666 \n",
       "L 5759 0 \n",
       "L 4372 0 \n",
       "L 3525 3547 \n",
       "L 2688 0 \n",
       "L 1300 0 \n",
       "L 191 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-61\" d=\"M 2106 1575 \n",
       "Q 1756 1575 1579 1456 \n",
       "Q 1403 1338 1403 1106 \n",
       "Q 1403 894 1545 773 \n",
       "Q 1688 653 1941 653 \n",
       "Q 2256 653 2472 879 \n",
       "Q 2688 1106 2688 1447 \n",
       "L 2688 1575 \n",
       "L 2106 1575 \n",
       "z\n",
       "M 3816 1997 \n",
       "L 3816 0 \n",
       "L 2688 0 \n",
       "L 2688 519 \n",
       "Q 2463 200 2181 54 \n",
       "Q 1900 -91 1497 -91 \n",
       "Q 953 -91 614 226 \n",
       "Q 275 544 275 1050 \n",
       "Q 275 1666 698 1953 \n",
       "Q 1122 2241 2028 2241 \n",
       "L 2688 2241 \n",
       "L 2688 2328 \n",
       "Q 2688 2594 2478 2717 \n",
       "Q 2269 2841 1825 2841 \n",
       "Q 1466 2841 1156 2769 \n",
       "Q 847 2697 581 2553 \n",
       "L 581 3406 \n",
       "Q 941 3494 1303 3539 \n",
       "Q 1666 3584 2028 3584 \n",
       "Q 2975 3584 3395 3211 \n",
       "Q 3816 2838 3816 1997 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-72\" d=\"M 3138 2547 \n",
       "Q 2991 2616 2845 2648 \n",
       "Q 2700 2681 2553 2681 \n",
       "Q 2122 2681 1889 2404 \n",
       "Q 1656 2128 1656 1613 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 3500 \n",
       "L 1656 3500 \n",
       "L 1656 2925 \n",
       "Q 1872 3269 2151 3426 \n",
       "Q 2431 3584 2822 3584 \n",
       "Q 2878 3584 2943 3579 \n",
       "Q 3009 3575 3134 3559 \n",
       "L 3138 2547 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-6d\" d=\"M 3781 2919 \n",
       "Q 3994 3244 4286 3414 \n",
       "Q 4578 3584 4928 3584 \n",
       "Q 5531 3584 5847 3212 \n",
       "Q 6163 2841 6163 2131 \n",
       "L 6163 0 \n",
       "L 5038 0 \n",
       "L 5038 1825 \n",
       "Q 5041 1866 5042 1909 \n",
       "Q 5044 1953 5044 2034 \n",
       "Q 5044 2406 4934 2573 \n",
       "Q 4825 2741 4581 2741 \n",
       "Q 4263 2741 4089 2478 \n",
       "Q 3916 2216 3909 1719 \n",
       "L 3909 0 \n",
       "L 2784 0 \n",
       "L 2784 1825 \n",
       "Q 2784 2406 2684 2573 \n",
       "Q 2584 2741 2328 2741 \n",
       "Q 2006 2741 1831 2477 \n",
       "Q 1656 2213 1656 1722 \n",
       "L 1656 0 \n",
       "L 531 0 \n",
       "L 531 3500 \n",
       "L 1656 3500 \n",
       "L 1656 2988 \n",
       "Q 1863 3284 2130 3434 \n",
       "Q 2397 3584 2719 3584 \n",
       "Q 3081 3584 3359 3409 \n",
       "Q 3638 3234 3781 2919 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-20\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-70\" d=\"M 1656 506 \n",
       "L 1656 -1331 \n",
       "L 538 -1331 \n",
       "L 538 3500 \n",
       "L 1656 3500 \n",
       "L 1656 2988 \n",
       "Q 1888 3294 2169 3439 \n",
       "Q 2450 3584 2816 3584 \n",
       "Q 3463 3584 3878 3070 \n",
       "Q 4294 2556 4294 1747 \n",
       "Q 4294 938 3878 423 \n",
       "Q 3463 -91 2816 -91 \n",
       "Q 2450 -91 2169 54 \n",
       "Q 1888 200 1656 506 \n",
       "z\n",
       "M 2400 2772 \n",
       "Q 2041 2772 1848 2508 \n",
       "Q 1656 2244 1656 1747 \n",
       "Q 1656 1250 1848 986 \n",
       "Q 2041 722 2400 722 \n",
       "Q 2759 722 2948 984 \n",
       "Q 3138 1247 3138 1747 \n",
       "Q 3138 2247 2948 2509 \n",
       "Q 2759 2772 2400 2772 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-65\" d=\"M 4031 1759 \n",
       "L 4031 1441 \n",
       "L 1416 1441 \n",
       "Q 1456 1047 1700 850 \n",
       "Q 1944 653 2381 653 \n",
       "Q 2734 653 3104 758 \n",
       "Q 3475 863 3866 1075 \n",
       "L 3866 213 \n",
       "Q 3469 63 3072 -14 \n",
       "Q 2675 -91 2278 -91 \n",
       "Q 1328 -91 801 392 \n",
       "Q 275 875 275 1747 \n",
       "Q 275 2603 792 3093 \n",
       "Q 1309 3584 2216 3584 \n",
       "Q 3041 3584 3536 3087 \n",
       "Q 4031 2591 4031 1759 \n",
       "z\n",
       "M 2881 2131 \n",
       "Q 2881 2450 2695 2645 \n",
       "Q 2509 2841 2209 2841 \n",
       "Q 1884 2841 1681 2658 \n",
       "Q 1478 2475 1428 2131 \n",
       "L 2881 2131 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-66\" d=\"M 2841 4863 \n",
       "L 2841 4128 \n",
       "L 2222 4128 \n",
       "Q 1984 4128 1890 4042 \n",
       "Q 1797 3956 1797 3744 \n",
       "L 1797 3500 \n",
       "L 2753 3500 \n",
       "L 2753 2700 \n",
       "L 1797 2700 \n",
       "L 1797 0 \n",
       "L 678 0 \n",
       "L 678 2700 \n",
       "L 122 2700 \n",
       "L 122 3500 \n",
       "L 678 3500 \n",
       "L 678 3744 \n",
       "Q 678 4316 997 4589 \n",
       "Q 1316 4863 1984 4863 \n",
       "L 2841 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-69\" d=\"M 538 3500 \n",
       "L 1656 3500 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 3500 \n",
       "z\n",
       "M 538 4863 \n",
       "L 1656 4863 \n",
       "L 1656 3950 \n",
       "L 538 3950 \n",
       "L 538 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-6c\" d=\"M 538 4863 \n",
       "L 1656 4863 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-62\" d=\"M 2400 722 \n",
       "Q 2759 722 2948 984 \n",
       "Q 3138 1247 3138 1747 \n",
       "Q 3138 2247 2948 2509 \n",
       "Q 2759 2772 2400 2772 \n",
       "Q 2041 2772 1848 2508 \n",
       "Q 1656 2244 1656 1747 \n",
       "Q 1656 1250 1848 986 \n",
       "Q 2041 722 2400 722 \n",
       "z\n",
       "M 1656 2988 \n",
       "Q 1888 3294 2169 3439 \n",
       "Q 2450 3584 2816 3584 \n",
       "Q 3463 3584 3878 3070 \n",
       "Q 4294 2556 4294 1747 \n",
       "Q 4294 938 3878 423 \n",
       "Q 3463 -91 2816 -91 \n",
       "Q 2450 -91 2169 54 \n",
       "Q 1888 200 1656 506 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 4863 \n",
       "L 1656 4863 \n",
       "L 1656 2988 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-79\" d=\"M 78 3500 \n",
       "L 1197 3500 \n",
       "L 2138 1125 \n",
       "L 2938 3500 \n",
       "L 4056 3500 \n",
       "L 2584 -331 \n",
       "Q 2363 -916 2067 -1148 \n",
       "Q 1772 -1381 1288 -1381 \n",
       "L 641 -1381 \n",
       "L 641 -647 \n",
       "L 991 -647 \n",
       "Q 1275 -647 1404 -556 \n",
       "Q 1534 -466 1606 -231 \n",
       "L 1638 -134 \n",
       "L 78 3500 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-6e\" d=\"M 4056 2131 \n",
       "L 4056 0 \n",
       "L 2931 0 \n",
       "L 2931 347 \n",
       "L 2931 1631 \n",
       "Q 2931 2084 2911 2256 \n",
       "Q 2891 2428 2841 2509 \n",
       "Q 2775 2619 2662 2680 \n",
       "Q 2550 2741 2406 2741 \n",
       "Q 2056 2741 1856 2470 \n",
       "Q 1656 2200 1656 1722 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 3500 \n",
       "L 1656 3500 \n",
       "L 1656 2988 \n",
       "Q 1909 3294 2193 3439 \n",
       "Q 2478 3584 2822 3584 \n",
       "Q 3428 3584 3742 3212 \n",
       "Q 4056 2841 4056 2131 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-75\" d=\"M 500 1363 \n",
       "L 500 3500 \n",
       "L 1625 3500 \n",
       "L 1625 3150 \n",
       "Q 1625 2866 1622 2436 \n",
       "Q 1619 2006 1619 1863 \n",
       "Q 1619 1441 1641 1255 \n",
       "Q 1663 1069 1716 984 \n",
       "Q 1784 875 1895 815 \n",
       "Q 2006 756 2150 756 \n",
       "Q 2500 756 2700 1025 \n",
       "Q 2900 1294 2900 1772 \n",
       "L 2900 3500 \n",
       "L 4019 3500 \n",
       "L 4019 0 \n",
       "L 2900 0 \n",
       "L 2900 506 \n",
       "Q 2647 200 2364 54 \n",
       "Q 2081 -91 1741 -91 \n",
       "Q 1134 -91 817 281 \n",
       "Q 500 653 500 1363 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-74\" d=\"M 1759 4494 \n",
       "L 1759 3500 \n",
       "L 2913 3500 \n",
       "L 2913 2700 \n",
       "L 1759 2700 \n",
       "L 1759 1216 \n",
       "Q 1759 972 1856 886 \n",
       "Q 1953 800 2241 800 \n",
       "L 2816 800 \n",
       "L 2816 0 \n",
       "L 1856 0 \n",
       "Q 1194 0 917 276 \n",
       "Q 641 553 641 1216 \n",
       "L 641 2700 \n",
       "L 84 2700 \n",
       "L 84 3500 \n",
       "L 641 3500 \n",
       "L 641 4494 \n",
       "L 1759 4494 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-67\" d=\"M 2919 594 \n",
       "Q 2688 288 2409 144 \n",
       "Q 2131 0 1766 0 \n",
       "Q 1125 0 706 504 \n",
       "Q 288 1009 288 1791 \n",
       "Q 288 2575 706 3076 \n",
       "Q 1125 3578 1766 3578 \n",
       "Q 2131 3578 2409 3434 \n",
       "Q 2688 3291 2919 2981 \n",
       "L 2919 3500 \n",
       "L 4044 3500 \n",
       "L 4044 353 \n",
       "Q 4044 -491 3511 -936 \n",
       "Q 2978 -1381 1966 -1381 \n",
       "Q 1638 -1381 1331 -1331 \n",
       "Q 1025 -1281 716 -1178 \n",
       "L 716 -306 \n",
       "Q 1009 -475 1290 -558 \n",
       "Q 1572 -641 1856 -641 \n",
       "Q 2406 -641 2662 -400 \n",
       "Q 2919 -159 2919 353 \n",
       "L 2919 594 \n",
       "z\n",
       "M 2181 2772 \n",
       "Q 1834 2772 1640 2515 \n",
       "Q 1447 2259 1447 1791 \n",
       "Q 1447 1309 1634 1061 \n",
       "Q 1822 813 2181 813 \n",
       "Q 2531 813 2725 1069 \n",
       "Q 2919 1325 2919 1791 \n",
       "Q 2919 2259 2725 2515 \n",
       "Q 2531 2772 2181 2772 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      <path id=\"DejaVuSans-Bold-68\" d=\"M 4056 2131 \n",
       "L 4056 0 \n",
       "L 2931 0 \n",
       "L 2931 347 \n",
       "L 2931 1625 \n",
       "Q 2931 2084 2911 2256 \n",
       "Q 2891 2428 2841 2509 \n",
       "Q 2775 2619 2662 2680 \n",
       "Q 2550 2741 2406 2741 \n",
       "Q 2056 2741 1856 2470 \n",
       "Q 1656 2200 1656 1722 \n",
       "L 1656 0 \n",
       "L 538 0 \n",
       "L 538 4863 \n",
       "L 1656 4863 \n",
       "L 1656 2988 \n",
       "Q 1909 3294 2193 3439 \n",
       "Q 2478 3584 2822 3584 \n",
       "Q 3428 3584 3742 3212 \n",
       "Q 4056 2841 4056 2131 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "     </defs>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-57\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-61\" transform=\"translate(106.677734 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-72\" transform=\"translate(174.158203 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6d\" transform=\"translate(223.474609 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-20\" transform=\"translate(327.673828 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-70\" transform=\"translate(362.488281 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-72\" transform=\"translate(434.070312 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-65\" transform=\"translate(483.386719 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-66\" transform=\"translate(551.208984 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-69\" transform=\"translate(594.714844 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6c\" transform=\"translate(628.992188 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6c\" transform=\"translate(663.269531 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-20\" transform=\"translate(697.546875 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-62\" transform=\"translate(732.361328 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-79\" transform=\"translate(803.943359 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-20\" transform=\"translate(869.128906 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-69\" transform=\"translate(903.943359 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6e\" transform=\"translate(938.220703 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-70\" transform=\"translate(1009.412109 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-75\" transform=\"translate(1080.994141 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-74\" transform=\"translate(1152.185547 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-20\" transform=\"translate(1199.988281 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6c\" transform=\"translate(1234.802734 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-65\" transform=\"translate(1269.080078 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-6e\" transform=\"translate(1336.902344 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-67\" transform=\"translate(1408.09375 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-74\" transform=\"translate(1479.675781 0)\"/>\n",
       "     <use xlink:href=\"#DejaVuSans-Bold-68\" transform=\"translate(1527.478516 0)\"/>\n",
       "    </g>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p8be93d0e39\">\n",
       "   <rect x=\"73.995312\" y=\"34.3575\" width=\"510.404207\" height=\"160.56577\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 810x314 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "measurement_seconds = None if COURSE_SMOKE else perf_counter() - started_lab\n",
    "quality = summarise_quality(quality_rows) if quality_rows else None\n",
    "\n",
    "print(\"Profile summary:\")\n",
    "for row in profile_summary:\n",
    "    print(row)\n",
    "print(\"Translated request token counts:\", language_rows)\n",
    "if quality is not None:\n",
    "    print(\"Strict quality:\", quality)\n",
    "    for condition in CONDITIONS:\n",
    "        rows = [row for row in quality_rows if row[\"condition\"] == condition]\n",
    "        print(\"F-250 response:\", next(row for row in rows if row[\"id\"] == focus_case[\"id\"]))\n",
    "        failure = next((row for row in rows if not row[\"strict_pass\"]), None)\n",
    "        print(\"First strict failure:\", failure)\n",
    "    print(\"Measurement wall time, seconds:\", measurement_seconds)\n",
    "save(\"summary\", {\n",
    "    \"mode\": \"formula_smoke\" if COURSE_SMOKE else \"cuda_profile\",\n",
    "    \"cache_shape\": cache_shape,\n",
    "    \"token_budget\": GENERATED_TOKENS,\n",
    "    \"model_load_ms\": load_ms,\n",
    "    \"measurement_wall_seconds\": measurement_seconds,\n",
    "    \"first_profile\": first_profile,\n",
    "    \"profiler\": profile_summary,\n",
    "    \"translated_requests\": language_rows,\n",
    "    \"quality\": quality,\n",
    "    \"settings\": {\n",
    "        \"model\": MODEL_IDS[\"text\"],\n",
    "        \"profile_repeats\": REPEATS,\n",
    "        \"f250_case_id\": focus_case[\"id\"],\n",
    "        \"dossier_copies\": DOSSIER_COPIES,\n",
    "        \"quality_batch\": QUALITY_BATCH,\n",
    "        \"quality_token_budget\": QUALITY_TOKEN_BUDGET,\n",
    "        \"quality_split\": SPLIT_MANIFEST[\"dev\"],\n",
    "    },\n",
    "})\n",
    "save(\"records\", {\n",
    "    \"profiles\": measurements,\n",
    "    \"quality\": quality_rows,\n",
    "    \"f250_prompts\": {\n",
    "        condition: answer_prompt(focus_case, records_for(focus_case, condition))\n",
    "        for condition in CONDITIONS\n",
    "    },\n",
    "})\n",
    "\n",
    "if COURSE_SMOKE:\n",
    "    chart(\"Illustrative final KV allocation\",\n",
    "          [str(row[\"input_tokens\"]) for row in profile_summary],\n",
    "          [row[\"predicted_final_kv_bytes\"] / 1024 for row in profile_summary], \"KiB\")\n",
    "else:\n",
    "    sweep = [row for row in profile_summary if row[\"experiment\"] == \"length\"]\n",
    "    chart(\"Warm prefill by input length\", [row[\"condition\"] for row in sweep],\n",
    "          [row[\"median_prefill_ms\"] for row in sweep], \"Milliseconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-25",
   "metadata": {},
   "source": [
    "Compare the shortest and longest warmed input. Cache bytes must grow\n",
    "linearly with token positions for this cache configuration. Prefill and\n",
    "aggregate allocator peaks also depend on kernels and temporary allocations.\n",
    "Compare the translation rows as one matched example. A broader\n",
    "language claim needs many translations and lengths. For a controlled\n",
    "serving estimate, keep the model and output-token target fixed and add\n",
    "concurrency in Lab 11.\n",
    "\n",
    "[Return to the lesson](https://docs.recohut.com/courses/advanced-ai-systems-engineering/1-measure-the-model/02-profile-a-transformer).\n",
    "\n",
    "[FlashAttention](https://arxiv.org/abs/2205.14135)\n",
    "· [Hugging Face KV cache strategies](https://huggingface.co/docs/transformers/v4.51.3/en/kv_cache)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "lab-02-26",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Inspect the per-case records in `evidence/` before drawing a conclusion from an aggregate. Use the printed sample size, split and hardware when comparing it with another run.\n",
    "\n",
    "- [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/abs/2205.14135)"
   ]
  }
 ],
 "metadata": {
  "course": {
   "lab": 2,
   "slug": "02-profile-a-transformer"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
