{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 6.3 · Quantization and Speculative Decoding\n", "\n", "**Goal:** quantize one weight matrix by hand and measure the error; load the serving model in 16, 8 and\n", "4 bits and measure weight memory, decode speed and perplexity on a fixed text; write speculative\n", "decoding by hand with a small draft model and measure its acceptance rate and speed-up; then break\n", "each of the three ideas once.\n", "\n", "**Runs on:** an NVIDIA GPU with at least 12 GB for everything (the book's numbers come from an RTX 3060\n", "12 GB); a free 16 GB Kaggle or Colab T4 runs it too, without the 7 B cell (set `LAB_7B=0`) and with CUDA-graph\n", "speeds that differ. Without a GPU the cells that need one are skipped and the by-hand sections run on the\n", "CPU with the 0.5 B sibling of the model, a short text and float32. Install: `uv run --with torch\n", "--with transformers --with bitsandbytes --with accelerate --with pandas --with pyarrow --with matplotlib\n", "jupyter lab` (the first run downloads about 3 GB of weights, plus 1 GB for the draft model and 15 GB for the\n", "optional 7 B model; no login needed).\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-6-3-quant-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import gc\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import random\n", "import statistics\n", "import subprocess\n", "import time\n", "import warnings\n", "\n", "import torch\n", "import torch.nn.functional as F\n", "import transformers\n", "from huggingface_hub import hf_hub_download\n", "from safetensors import safe_open\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "warnings.filterwarnings(\"ignore\")\n", "transformers.logging.set_verbosity_error()\n", "torch.set_grad_enabled(False) # an inference lab\n", "\n", "try:\n", " import bitsandbytes as bnb\n", " from transformers import BitsAndBytesConfig\n", " HAVE_BNB = torch.cuda.is_available()\n", "except Exception as e: # not installed, or no CUDA build for this machine\n", " bnb, HAVE_BNB = None, False\n", " print(\"bitsandbytes not available:\", type(e).__name__)\n", "\n", "ON_GPU = torch.cuda.is_available() and os.environ.get(\"LAB_DEVICE\", \"cuda\") == \"cuda\"\n", "DEVICE = \"cuda\" if ON_GPU else \"cpu\"\n", "FAST = os.environ.get(\"LAB_FAST\", \"0\") == \"1\" # tiny settings: a quick check that every cell runs\n", "RUN_7B = ON_GPU and os.environ.get(\"LAB_7B\", \"1\") == \"1\" and not FAST\n", "TINY = (not ON_GPU) or FAST # short text, few windows\n", "\n", "# The serving model of Vols 6-7 and its 0.5 B sibling (data/models.json), pinned to exact revisions.\n", "SERVING = (\"Qwen/Qwen2.5-1.5B-Instruct\", \"989aa7980e4cf806f80c7fef2b1adb7bc71aa306\")\n", "DRAFT = (\"Qwen/Qwen2.5-0.5B-Instruct\", \"7ae557604adf67be50417f59c2c2f167def9a775\")\n", "BIG = (\"Qwen/Qwen2.5-7B-Instruct\", \"a09a35458c702b33eeacc393d103063234e8bc28\") # Apache-2.0, 7.6 B parameters\n", "MODEL_ID, REVISION = SERVING if ON_GPU else DRAFT # without a GPU the 0.5 B model is the subject\n", "DTYPE = torch.float16 if ON_GPU else torch.float32\n", "BW = 336.2e9 # bytes/s: the RTX 3060's measured bandwidth (Ch 4.1); the ceiling arithmetic of this lab uses it\n", "print(\"PyTorch\", torch.__version__, \"| transformers\", transformers.__version__, \"| device:\", DEVICE,\n", " \"| tiny\" if TINY else \"\", \"| bitsandbytes\", getattr(bnb, \"__version__\", \"none\"))\n", "print(\"model:\", MODEL_ID, \"@\", REVISION[:10], \"| dtype:\", str(DTYPE).replace(\"torch.\", \"\"))\n", "\n", "\n", "def sync():\n", " if ON_GPU:\n", " torch.cuda.synchronize()\n", "\n", "\n", "def free():\n", " gc.collect()\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", "\n", "\n", "def out_dir():\n", " forced = os.environ.get(\"LAB_OUT_DIR\")\n", " if forced:\n", " d = pathlib.Path(forced)\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-6-3-quant\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def save_csv(name, rows):\n", " path = out_dir() / name\n", " with path.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=list(rows[0].keys()), lineterminator=\"\\n\")\n", " w.writeheader()\n", " w.writerows(rows)\n", " print(\"saved\", path)\n", "\n", "\n", "MACHINE = torch.cuda.get_device_name(0) if ON_GPU else f\"{platform.system()} {platform.machine()} (cpu)\"" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write your answers down before you run anything below; the cells that follow print the real numbers.\n", "\n", "1. **Bytes.** The serving model has 1,543,714,304 parameters; 233,373,696 of them are the embedding matrix,\n", " which the output layer shares. If every *other* weight is stored in 8 bits, then in 4 bits (plus one\n", " 16-bit scale for each 64 weights), how many bytes is the model? Assume the embedding matrix stays in\n", " 16 bits (library defaults leave it alone).\n", "2. **Ceiling.** At the RTX 3060's 336.2 GB/s, what is the decode ceiling in tokens per second for the 4-bit\n", " model? And will the Python loop of Lab 6.1 (about 50 tokens/s in 16 bits) reach it?\n", "3. **One outlier.** In a weight matrix where one weight is 50 times larger than the typical one, which is\n", " worse in 4 bits: one scale for the whole matrix, or one scale for each group of 128 weights? By how much?\n", "4. **Perplexity.** Going from 16 to 8 to 4 bits, perplexity on a fixed text rises by about: under 1 %,\n", " about 5 %, about 30 %, or more? (Your answer for each step.)\n", "5. **Draft and verify.** A draft model proposes `k = 4` tokens; each is accepted with probability 0.7 (if the\n", " ones before it were). How many tokens does one round produce on average? If the draft step costs 0.3 of\n", " a target step, and verifying 5 tokens costs one target step, what is the speed-up?\n", "6. **Distribution.** In greedy decoding, will speculative decoding write exactly the same tokens as the\n", " target model alone? Why, or why not?" ], "id": "lab-6-3-quant-02" }, { "cell_type": "code", "metadata": {}, "source": [ "PREDICT = {\n", " \"bytes_8bit\": None, \"bytes_4bit\": None, \"ceiling_4bit_tokens_per_s\": None,\n", " \"per_tensor_vs_group_with_outlier\": None, \"ppl_rise_8bit\": None, \"ppl_rise_4bit\": None,\n", " \"tokens_per_round\": None, \"speedup\": None, \"greedy_identical\": None,\n", "}\n", "print(PREDICT)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build: quantize by hand\n", "\n", "**The idea.** A weight is a 16-bit float. We want 8 or 4 bits. Pick a *scale* `s` and store the integer\n", "`q = round(w / s)`; to use the weight, multiply back: `w ≈ q · s`. With a symmetric scheme, `s = max|w| / q_max`\n", "(`q_max = 127` for int8, `7` for int4), so the biggest weight lands exactly on the top integer.\n", "An asymmetric scheme also stores a *zero point* `z`, `q = round(w / s) + z`, and uses the whole range\n", "`[min, max]`; it helps for values that are not centred on 0 (activations after a ReLU, say).\n", "\n", "**How many scales.** One scale for the whole matrix (*per-tensor*) is simplest. One per row (*per-channel*)\n", "or one per `g` consecutive weights (*per-group*, `g` = 128, 64, 32, ...) costs extra storage (one 16-bit\n", "scale per group: 16/128 = 0.125 bits per weight at `g = 128`) but follows the values more closely." ], "id": "lab-6-3-quant-04" }, { "cell_type": "code", "metadata": {}, "source": [ "def quantize(w, bits=8, group=None, sym=True):\n", " \"\"\"Fake-quantize `w` (2-D): round to integers with scales, return (dequantized, q, scale, zero).\n", " group=None: one scale per tensor; group=\"row\": per row; group=g: one per g consecutive weights in a row.\"\"\"\n", " rows, cols = w.shape\n", " g = rows * cols if group is None else (cols if group == \"row\" else group)\n", " if group is None:\n", " blocks = w.reshape(1, -1)\n", " else:\n", " assert cols % g == 0, (cols, g)\n", " blocks = w.reshape(-1, g)\n", " if sym:\n", " qmax = 2 ** (bits - 1) - 1\n", " scale = blocks.abs().amax(dim=1, keepdim=True).clamp_min(1e-12) / qmax\n", " zero = torch.zeros_like(scale)\n", " q = torch.clamp(torch.round(blocks / scale), -qmax, qmax)\n", " else:\n", " lo, hi = blocks.amin(dim=1, keepdim=True), blocks.amax(dim=1, keepdim=True)\n", " scale = (hi - lo).clamp_min(1e-12) / (2**bits - 1)\n", " zero = torch.round(-lo / scale)\n", " q = torch.clamp(torch.round(blocks / scale) + zero, 0, 2**bits - 1)\n", " deq = ((q - zero) * scale).reshape(rows, cols)\n", " return deq, q.to(torch.int32), scale, zero\n", "\n", "\n", "# A worked example on 8 numbers, the last one an outlier. Two groups of 4.\n", "WORKED = torch.tensor([[0.12, -0.31, 0.05, 0.27, -0.08, 0.19, -0.22, 1.60]])\n", "print(\"weights \", [round(v, 3) for v in WORKED[0].tolist()])\n", "for label, bits, group, sym in ((\"int8 per-tensor\", 8, None, True), (\"int4 per-tensor\", 4, None, True),\n", " (\"int4 groups of 4\", 4, 4, True), (\"int4 per-tensor asym\", 4, None, False)):\n", " deq, q, scale, zero = quantize(WORKED, bits, group, sym)\n", " err = (deq - WORKED).abs()\n", " print(f\"{label:22s} scale {[round(s, 4) for s in scale.flatten().tolist()]} zero {[int(z) for z in zero.flatten().tolist()]}\")\n", " print(f\"{'':22s} q {q.flatten().tolist()}\")\n", " print(f\"{'':22s} back {[round(v, 3) for v in deq[0].tolist()]} max error {err.max().item():.3f} \"\n", " f\"mean error {err.mean().item():.3f}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### A real weight matrix\n", "\n", "We read single tensors straight from the model's `safetensors` file, so the full model is never loaded.\n", "First a scan of every linear layer: how large is the biggest weight compared with the typical one\n", "(`max |w| / std`)? That ratio decides how much a single scale wastes." ], "id": "lab-6-3-quant-06" }, { "cell_type": "code", "metadata": {}, "source": [ "WEIGHT_FILE = hf_hub_download(MODEL_ID, \"model.safetensors\", revision=REVISION)\n", "\n", "\n", "def linear_names(f):\n", " return [n for n in f.keys() if n.endswith(\"_proj.weight\")]\n", "\n", "\n", "rows_scan = []\n", "with safe_open(WEIGHT_FILE, framework=\"pt\") as f:\n", " names = linear_names(f)\n", " for n in names[: (24 if FAST else None)]:\n", " w = f.get_tensor(n).float()\n", " rows_scan.append({\"name\": n, \"rows\": w.shape[0], \"cols\": w.shape[1], \"std\": round(w.std().item(), 5),\n", " \"max_abs\": round(w.abs().max().item(), 4),\n", " \"max_over_std\": round((w.abs().max() / w.std()).item(), 1)})\n", "save_csv(\"weight-scan.csv\", rows_scan)\n", "ratios = sorted(r[\"max_over_std\"] for r in rows_scan)\n", "print(f\"{len(rows_scan)} linear weight matrices | max/std: min {ratios[0]}, median {ratios[len(ratios) // 2]}, max {ratios[-1]}\")\n", "worst = max(rows_scan, key=lambda r: r[\"max_over_std\"])\n", "typical = sorted(rows_scan, key=lambda r: r[\"max_over_std\"])[len(rows_scan) // 2]\n", "print(\"typical :\", typical)\n", "print(\"largest :\", worst)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-07" }, { "cell_type": "code", "metadata": {}, "source": [ "def read_weight(name):\n", " with safe_open(WEIGHT_FILE, framework=\"pt\") as f:\n", " return f.get_tensor(name).float()\n", "\n", "\n", "SCHEMES = [(8, None), (8, \"row\"), (8, 128), (8, 32), (4, None), (4, \"row\"), (4, 128), (4, 64), (4, 32), (4, 16)]\n", "g = torch.Generator().manual_seed(0)\n", "quant_rows = []\n", "for label, rec in ((\"typical\", typical), (\"largest max/std\", worst)):\n", " W = read_weight(rec[\"name\"])\n", " X = torch.randn(W.shape[1], 64, generator=g) # 64 random input vectors\n", " Y = W @ X\n", " print(f\"\\n{label}: {rec['name']} shape {tuple(W.shape)} max/std {rec['max_over_std']}\")\n", " print(f\"{'scheme':16s} {'weight error':>13s} {'output error':>13s} {'bits/weight':>12s}\")\n", " for bits, group in SCHEMES:\n", " deq, q, scale, zero = quantize(W, bits, group)\n", " w_err = ((deq - W).norm() / W.norm()).item()\n", " y_err = ((deq @ X - Y).norm() / Y.norm()).item()\n", " gsize = W.numel() if group is None else (W.shape[1] if group == \"row\" else group)\n", " bpw = bits + 16 / gsize # one 16-bit scale per group\n", " name = f\"int{bits} \" + (\"per-tensor\" if group is None else \"per-row\" if group == \"row\" else f\"group {group}\")\n", " print(f\"{name:16s} {100 * w_err:12.2f}% {100 * y_err:12.2f}% {bpw:12.3f}\")\n", " quant_rows.append({\"matrix\": label, \"name\": rec[\"name\"], \"bits\": bits,\n", " \"group\": \"tensor\" if group is None else group, \"weight_error_pct\": round(100 * w_err, 3),\n", " \"output_error_pct\": round(100 * y_err, 3), \"bits_per_weight\": round(bpw, 4),\n", " \"max_over_std\": rec[\"max_over_std\"]})\n", "save_csv(\"quant-error.csv\", quant_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: how does the error change with the group size, and at what price? Why is the *largest max/std*\n", "matrix hurt more by one scale for the whole tensor? How many of the 255 int8 levels (or 15 int4 levels) does\n", "a typical weight of that matrix actually use under per-tensor scaling? (Compute it: count the distinct\n", "values of `q` that carry 99 % of the weights.)" ], "id": "lab-6-3-quant-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Which scheme hurts the model? Quantize every linear layer, measure perplexity\n", "\n", "Fake quantization: round every linear weight to the grid and put the *dequantized* number back, so the\n", "model keeps running in 16 bits. It saves no memory and no time. What it shows is the *quality* of the\n", "scheme alone. Perplexity is `exp(mean negative log-probability of the true next token)` on a fixed text:\n", "lower is better, and `1` would mean the model is never surprised.\n", "\n", "The fixed text is the test split of WikiText-2 (raw), the usual benchmark for this. The model has very\n", "likely seen Wikipedia text in training, so the absolute number says nothing about new text; the\n", "*differences* between schemes on the same text are the point." ], "id": "lab-6-3-quant-10" }, { "cell_type": "code", "metadata": {}, "source": [ "WIN = 1024 if not TINY else 256\n", "N_WIN = 64 if not TINY else 4\n", "FALLBACK_TEXT = False\n", "try:\n", " import pandas as pd\n", " WT_FILE = hf_hub_download(\"Salesforce/wikitext\", \"wikitext-2-raw-v1/test-00000-of-00001.parquet\", repo_type=\"dataset\")\n", " TEXT = \"\\n\\n\".join(pd.read_parquet(WT_FILE)[\"text\"].tolist())\n", " TEXT_NAME = \"WikiText-2 raw, test split (Salesforce/wikitext, snapshot \" + WT_FILE.split(\"snapshots/\")[1][:10] + \")\"\n", "except Exception as e:\n", " FALLBACK_TEXT = True\n", " TEXT = (\"Once upon a time, in a small village by the sea, there lived a fisherman named Tomas. Every morning \"\n", " \"before the sun came up he pushed his old blue boat into the water and rowed out past the rocks. \") * 200\n", " TEXT_NAME = \"FALLBACK: a short story repeated (WikiText-2 could not be loaded: \" + type(e).__name__ + \")\"\n", "\n", "tok = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)\n", "TEXT_IDS = tok(TEXT, return_tensors=\"pt\").input_ids[0]\n", "USED = TEXT_IDS[: WIN * N_WIN]\n", "print(\"text:\", TEXT_NAME)\n", "print(f\"{len(TEXT):,} characters = {len(TEXT.encode()):,} bytes = {len(TEXT_IDS):,} tokens; \"\n", " f\"used: {N_WIN} windows of {WIN} tokens = {len(USED):,} tokens\")\n", "\n", "\n", "@torch.no_grad()\n", "def perplexity(mdl, ids=None, window=WIN, n_win=N_WIN, tokenizer=None, device=None):\n", " \"\"\"Mean cross-entropy of the true next token over non-overlapping windows. Returns a dict with\n", " ppl, mean NLL (nats), tokens scored, and (if a tokenizer is given) the bytes of the scored tokens.\"\"\"\n", " ids = USED if ids is None else ids\n", " device = device or next(mdl.parameters()).device\n", " nll, n, nbytes = 0.0, 0, 0\n", " for w in range(n_win):\n", " x = ids[w * window:(w + 1) * window][None].to(device)\n", " if x.shape[1] < window:\n", " break\n", " logits = mdl(input_ids=x).logits[0, :-1].float()\n", " nll += F.cross_entropy(logits, x[0, 1:], reduction=\"sum\").item()\n", " n += x.shape[1] - 1\n", " if tokenizer is not None:\n", " nbytes += len(tokenizer.decode(x[0, 1:].tolist()).encode())\n", " return {\"ppl\": math.exp(nll / n), \"nll\": nll / n, \"tokens\": n, \"bytes\": nbytes, \"nll_sum\": nll}\n", "\n", "\n", "def apply_scheme(mdl, bits, group, sym=True):\n", " \"\"\"Replace every linear weight by its fake-quantized version, read fresh from the file each time (so\n", " nothing accumulates). bits=None restores the original weights.\"\"\"\n", " params = dict(mdl.named_parameters())\n", " with safe_open(WEIGHT_FILE, framework=\"pt\") as f:\n", " for n in linear_names(f):\n", " w = f.get_tensor(n).float().to(params[n].device)\n", " if bits is not None:\n", " w, *_ = quantize(w, bits, group, sym)\n", " params[n].copy_(w.to(params[n].dtype))\n", "\n", "\n", "def load_plain():\n", " return AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=DTYPE).to(DEVICE).eval()\n", "\n", "\n", "model = load_plain()\n", "SIM = [(\"16-bit (original)\", None, None), (\"int8 per-tensor\", 8, None), (\"int8 group 128\", 8, 128),\n", " (\"int4 per-tensor\", 4, None), (\"int4 per-row\", 4, \"row\"), (\"int4 group 128\", 4, 128), (\"int4 group 32\", 4, 32)]\n", "if TINY:\n", " SIM = [s for s in SIM if s[0] in (\"16-bit (original)\", \"int8 group 128\", \"int4 per-tensor\", \"int4 group 128\")]\n", "sim_rows, base_ppl = [], None\n", "for label, bits, group in SIM:\n", " apply_scheme(model, bits, group)\n", " r = perplexity(model)\n", " base_ppl = base_ppl or r[\"ppl\"]\n", " gsize = None if bits is None else (1536 if group == \"row\" else group)\n", " sim_rows.append({\"scheme\": label, \"bits\": 16 if bits is None else bits,\n", " \"group\": \"\" if group is None else group, \"ppl\": round(r[\"ppl\"], 4),\n", " \"ppl_vs_16bit_pct\": round(100 * (r[\"ppl\"] / base_ppl - 1), 2), \"tokens\": r[\"tokens\"]})\n", " print(f\"{label:20s} perplexity {r['ppl']:10.3f} ({100 * (r['ppl'] / base_ppl - 1):+8.2f} % vs 16-bit)\")\n", "apply_scheme(model, None, None)\n", "save_csv(\"scheme-perplexity.csv\", sim_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build: the real thing, 16 vs 8 vs 4 bits\n", "\n", "`bitsandbytes` is a library that quantizes a model *as it loads*:\n", "\n", "- **8-bit** is LLM.int8() (Dettmers et al.): the weights are stored as int8 with one scale per row; at run\n", " time the few input features with huge activations (the outliers, section 5) are multiplied in 16 bits, the\n", " rest in int8.\n", "- **4-bit** is NF4 (the \"normal float\" of QLoRA): 16 levels placed where normally distributed weights are\n", " dense, with one scale per block of 64 weights. Weights are stored two per byte and dequantized to\n", " 16 bits inside the matrix-vector kernel.\n", "\n", "Both leave the embedding matrix (and so the tied output layer) in 16 bits. The loader is a one-line\n", "change: `quantization_config=BitsAndBytesConfig(...)`. We measure with the same hand loop as Lab 6.1: a\n", "prefill of 32 tokens, then one token per step with a growing cache, greedy." ], "id": "lab-6-3-quant-12" }, { "cell_type": "code", "metadata": {}, "source": [ "STORY = (\n", " \"Once upon a time, in a small village by the sea, there lived a fisherman named Tomas. \"\n", " \"Every morning before the sun came up he pushed his old blue boat into the water and rowed out past \"\n", " \"the rocks. The sea was quiet that day, and the gulls followed him all the way to the edge of the bay. \"\n", ")\n", "STORY_IDS = tok(STORY, return_tensors=\"pt\").input_ids[0][:32]\n", "print(\"decode prompt:\", len(STORY_IDS), \"tokens\")\n", "AR = torch.arange(4096, device=DEVICE)\n", "\n", "\n", "def core_of(m):\n", " return getattr(m, \"model\", None) or m.transformer # Qwen: .model; GPT-2: .transformer\n", "\n", "\n", "class EagerRunner:\n", " \"\"\"The hand loop of Lab 6.1: a growing cache, one Python call per forward pass. `feed(tokens, start)` runs\n", " the tokens at positions start.. and returns the greedy next token at each position, [1, n].\"\"\"\n", "\n", " def __init__(self, mdl):\n", " self.m, self.core, self.cache = mdl, core_of(mdl), None\n", "\n", " def prefill(self, ids):\n", " P = ids.shape[1]\n", " out = self.core(input_ids=ids, position_ids=AR[:P][None], use_cache=True)\n", " self.cache = out.past_key_values\n", " return self.m.lm_head(out.last_hidden_state[:, -1]).argmax(-1)\n", "\n", " def feed(self, tok_, start):\n", " n = tok_.shape[1]\n", " o = self.core(input_ids=tok_, position_ids=AR[start:start + n][None], past_key_values=self.cache, use_cache=True)\n", " return self.m.lm_head(o.last_hidden_state).argmax(-1)\n", "\n", " def truncate(self, n):\n", " cur = self.cache.get_seq_length()\n", " if n < cur:\n", " self.cache.crop(n - cur) # forget everything after the first n positions (transformers 5 counts negatively)\n", "\n", "\n", "class GraphRunner:\n", " \"\"\"The same, replayed from CUDA graphs over a pre-allocated cache: one graph per width (tokens per call).\n", " The cache never moves. A static cache writes new keys at `cumulative_length` and then advances it, so inside\n", " the graph we first set that counter from a one-number tensor, `start_s`, which each call fills in. That is\n", " also how \"forgetting\" the rejected draft tokens works: the next call simply writes over them.\"\"\"\n", "\n", " def __init__(self, mdl, max_len):\n", " from transformers import StaticCache\n", " self.m, self.core, self.max_len = mdl, core_of(mdl), max_len\n", " self.cache = StaticCache(config=mdl.config, max_cache_len=max_len)\n", " self.start_s = torch.zeros((), dtype=torch.long, device=DEVICE)\n", " self.graphs = {}\n", "\n", " def prefill(self, ids):\n", " P = ids.shape[1]\n", " for layer in self.cache.layers: # a new request starts writing at position 0 again\n", " layer.cumulative_length.fill_(0)\n", " out = self.core(input_ids=ids, position_ids=AR[:P][None], cache_position=AR[:P],\n", " past_key_values=self.cache, use_cache=True)\n", " return self.m.lm_head(out.last_hidden_state[:, -1]).argmax(-1)\n", "\n", " def _capture(self, n, start):\n", " tok_s = torch.zeros(1, n, dtype=torch.long, device=DEVICE)\n", "\n", " def step():\n", " for layer in self.cache.layers:\n", " layer.cumulative_length.copy_(self.start_s)\n", " pos = self.start_s + AR[:n]\n", " o = self.core(input_ids=tok_s, position_ids=pos[None], cache_position=pos,\n", " past_key_values=self.cache, use_cache=True)\n", " return self.m.lm_head(o.last_hidden_state).argmax(-1)\n", "\n", " self.start_s.fill_(start)\n", " side = torch.cuda.Stream()\n", " side.wait_stream(torch.cuda.current_stream())\n", " with torch.cuda.stream(side): # warm-up off the graph: allocations, kernel selection\n", " for _ in range(3):\n", " step()\n", " torch.cuda.current_stream().wait_stream(side)\n", " graph = torch.cuda.CUDAGraph()\n", " with torch.cuda.graph(graph):\n", " out_s = step()\n", " self.graphs[n] = (graph, tok_s, out_s)\n", "\n", " def feed(self, tok_, start):\n", " n = tok_.shape[1]\n", " if n not in self.graphs:\n", " self._capture(n, start) # writes scratch values at positions start..start+n-1, overwritten right below\n", " graph, tok_s, out_s = self.graphs[n]\n", " tok_s.copy_(tok_)\n", " self.start_s.fill_(start)\n", " graph.replay()\n", " return out_s\n", "\n", " def truncate(self, n):\n", " pass # nothing to do: the next call writes from its own `start`\n", "\n", "\n", "def make_runner(mdl, kind, max_len=4096):\n", " return GraphRunner(mdl, max_len) if kind == \"graph\" else EagerRunner(mdl)\n", "\n", "\n", "@torch.no_grad()\n", "def plain_generate(runner, prompt, n_new):\n", " \"\"\"Greedy decoding, one token per call. Returns (tokens, mean ms per token, first two steps left out).\"\"\"\n", " P = prompt.shape[1]\n", " cur = runner.prefill(prompt)\n", " out = [cur.item()]\n", " cur = cur[:, None]\n", " times = []\n", " for i in range(1, n_new):\n", " t0 = time.perf_counter()\n", " o = runner.feed(cur, P + i - 1)\n", " out.append(o.item()) # reading the token waits for the GPU\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " cur = o\n", " return out, statistics.mean(times[2:]) if len(times) > 3 else statistics.mean(times) # first steps: warm-up, graph capture" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-13" }, { "cell_type": "code", "metadata": {}, "source": [ "def measure_decode(mdl, kind, n_new=96, repeats=3):\n", " \"\"\"Median ms per token of the hand loop (kind='eager') or the graph replay (kind='graph').\"\"\"\n", " prompt = STORY_IDS[None].to(DEVICE)\n", " best, toks = [], None\n", " for r in range(repeats + 1): # the first repeat is a warm-up\n", " runner = make_runner(mdl, kind, max_len=len(STORY_IDS) + n_new + 8)\n", " toks, ms = plain_generate(runner, prompt, n_new)\n", " if r > 0:\n", " best.append(ms)\n", " del runner\n", " return statistics.median(best), toks\n", "\n", "\n", "TASKS = [ # a quick sanity check, not a benchmark: 14 questions with a checkable answer\n", " (\"What is the capital of Japan? Answer with one word.\", \"tokyo\"),\n", " (\"What is 12 times 12? Answer with just the number.\", \"144\"),\n", " (\"Which planet is known as the Red Planet? One word.\", \"mars\"),\n", " (\"What is the chemical symbol for gold? Answer with just the symbol.\", \"au\"),\n", " (\"How many days are in a leap year? Just the number.\", \"366\"),\n", " (\"Who wrote the play Romeo and Juliet? Give only the name.\", \"shakespeare\"),\n", " (\"What is the opposite of 'cold'? One word.\", \"hot\"),\n", " (\"What is the square root of 81? Just the number.\", \"9\"),\n", " (\"What is the largest ocean on Earth? One or two words.\", \"pacific\"),\n", " (\"What is 15 plus 27? Just the number.\", \"42\"),\n", " (\"What is 347 plus 589? Just the number.\", \"936\"),\n", " (\"What is 23 times 19? Just the number.\", \"437\"),\n", " (\"What is the capital of Australia? One word.\", \"canberra\"),\n", " (\"What is the 10th prime number? Just the number.\", \"29\"),\n", "]\n", "\n", "\n", "def chat_ids(tokenizer, user, device=None):\n", " text = tokenizer.apply_chat_template([{\"role\": \"user\", \"content\": user}], tokenize=False, add_generation_prompt=True)\n", " return tokenizer(text, return_tensors=\"pt\").input_ids.to(device or DEVICE)\n", "\n", "\n", "def task_score(mdl, tokenizer):\n", " ok = 0\n", " for q, a in TASKS:\n", " runner = EagerRunner(mdl)\n", " toks, _ = plain_generate(runner, chat_ids(tokenizer, q), 12)\n", " ok += a in tokenizer.decode(toks).lower()\n", " return ok\n", "\n", "\n", "def load_format(kind, spec=SERVING, compute=torch.float16):\n", " mid, rev = spec\n", " if kind == \"fp16\":\n", " return AutoModelForCausalLM.from_pretrained(mid, revision=rev, dtype=DTYPE,\n", " **({\"device_map\": {\"\": 0}} if ON_GPU else {})).eval()\n", " if kind == \"int8\":\n", " q = BitsAndBytesConfig(load_in_8bit=True)\n", " elif kind == \"nf4\":\n", " q = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type=\"nf4\", bnb_4bit_compute_dtype=compute)\n", " return AutoModelForCausalLM.from_pretrained(mid, revision=rev, dtype=compute, quantization_config=q,\n", " device_map={\"\": 0}).eval()\n", "\n", "\n", "def bytes_read_per_token(mdl, alloc):\n", " \"\"\"Every weight is read once per token, except the input embedding when it is not tied to the output layer\n", " (a lookup of one row).\"\"\"\n", " emb = mdl.get_input_embeddings().weight\n", " return alloc - (0 if mdl.config.tie_word_embeddings else emb.numel() * emb.element_size())\n", "\n", "\n", "formats, fp16_tokens = [], None\n", "if ON_GPU and HAVE_BNB:\n", " model = None\n", " free()\n", " plan = [(\"16-bit float\", \"fp16\", SERVING), (\"8-bit (LLM.int8)\", \"int8\", SERVING), (\"4-bit (NF4)\", \"nf4\", SERVING)]\n", " for label, kind, spec in plan:\n", " base = torch.cuda.memory_allocated()\n", " mdl = load_format(kind, spec)\n", " sync()\n", " alloc = torch.cuda.memory_allocated() - base\n", " row = {\"format\": label, \"model\": spec[0], \"weight_bytes\": alloc, \"footprint_bytes\": mdl.get_memory_footprint()}\n", " torch.cuda.reset_peak_memory_stats()\n", " r = perplexity(mdl)\n", " row.update(ppl=round(r[\"ppl\"], 4), peak_bytes_eval=torch.cuda.max_memory_allocated() - base, ppl_tokens=r[\"tokens\"])\n", " row[\"eager_ms\"], toks = measure_decode(mdl, \"eager\")\n", " if kind == \"fp16\":\n", " fp16_tokens = toks\n", " row[\"same_prefix_as_16bit\"] = next((i for i, (a, b) in enumerate(zip(toks, fp16_tokens)) if a != b), len(toks))\n", " try:\n", " row[\"graph_ms\"], gtoks = measure_decode(mdl, \"graph\")\n", " row[\"graph_same_as_eager\"] = gtoks == toks\n", " except Exception as e: # an 8-bit layer decides on the fly which columns are outliers: not capturable\n", " row[\"graph_ms\"], row[\"graph_same_as_eager\"] = \"\", \"\"\n", " print(f\" [{label}] graph decode skipped: {type(e).__name__}: {str(e)[:100]}\")\n", " row[\"tasks_correct\"] = task_score(mdl, tok)\n", " row[\"bytes_read_per_token\"] = bytes_read_per_token(mdl, alloc)\n", " row[\"ceiling_ms\"] = round(row[\"bytes_read_per_token\"] / BW * 1e3, 3)\n", " formats.append(row)\n", " print(f\"{label:18s} weights {alloc / 1e9:6.3f} GB | ppl {row['ppl']:8.3f} | eager {row['eager_ms']:6.2f} ms \"\n", " f\"| graph {row['graph_ms'] if row['graph_ms'] == '' else round(row['graph_ms'], 2)} ms \"\n", " f\"| ceiling {row['ceiling_ms']:.2f} ms | tasks {row['tasks_correct']}/{len(TASKS)} \"\n", " f\"| same tokens as 16-bit for {row['same_prefix_as_16bit']}/96\")\n", " del mdl\n", " free()\n", " print(f\" allocated after freeing: {torch.cuda.memory_allocated() / 1e6:.1f} MB\")\n", "else:\n", " print(\"no GPU or no bitsandbytes: the real 8-bit and 4-bit loads are skipped (section 2's simulation ran)\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The bigger model: what 4 bits buy\n", "\n", "Fewer bytes per weight is also a way to run a model that does not fit. `Qwen/Qwen2.5-7B-Instruct`\n", "(Apache-2.0) has 7,615,616,512 parameters: 15.2 GB in 16 bits, more than the card has. We try it in 16\n", "bits first (this is expected to fail), then in 4 bits. This cell downloads 15 GB the first time." ], "id": "lab-6-3-quant-15" }, { "cell_type": "code", "metadata": {}, "source": [ "big_rows = []\n", "if RUN_7B and HAVE_BNB:\n", " free()\n", " base = torch.cuda.memory_allocated()\n", " try:\n", " t = load_format(\"fp16\", BIG)\n", " res16 = \"loaded\"\n", " del t\n", " except Exception as e:\n", " res16 = type(e).__name__\n", " print(\"7 B in 16 bits:\", type(e).__name__, \"-\", str(e).split(\"\\n\")[0][:160])\n", " free()\n", " print(\"allocated after the failed load:\", torch.cuda.memory_allocated() / 1e6, \"MB\")\n", " mdl = load_format(\"nf4\", BIG)\n", " sync()\n", " alloc = torch.cuda.memory_allocated() - base\n", " big_tok = AutoTokenizer.from_pretrained(BIG[0], revision=BIG[1])\n", " same_tok = big_tok(\"Once upon a time, 12345 héllo\").input_ids == tok(\"Once upon a time, 12345 héllo\").input_ids\n", " torch.cuda.reset_peak_memory_stats()\n", " r = perplexity(mdl)\n", " compute = \"float16\"\n", " if math.isnan(r[\"ppl\"]): # float16 overflows in some 7 B activations: compute in bfloat16 instead\n", " del mdl\n", " free()\n", " mdl = load_format(\"nf4\", BIG, compute=torch.bfloat16)\n", " torch.cuda.reset_peak_memory_stats()\n", " r = perplexity(mdl)\n", " compute = \"bfloat16\"\n", " row = {\"format\": \"7B 4-bit (NF4)\", \"model\": BIG[0], \"weight_bytes\": alloc, \"footprint_bytes\": mdl.get_memory_footprint(),\n", " \"ppl\": round(r[\"ppl\"], 4), \"peak_bytes_eval\": torch.cuda.max_memory_allocated() - base, \"ppl_tokens\": r[\"tokens\"],\n", " \"fp16_load_result\": res16, \"compute_dtype\": compute, \"same_tokenizer_as_1p5b\": same_tok}\n", " row[\"eager_ms\"], toks = measure_decode(mdl, \"eager\")\n", " row[\"same_prefix_as_16bit\"] = \"\"\n", " try:\n", " row[\"graph_ms\"], _ = measure_decode(mdl, \"graph\")\n", " except Exception as e:\n", " row[\"graph_ms\"] = \"\"\n", " print(\" graph decode skipped:\", type(e).__name__, str(e)[:100])\n", " row[\"tasks_correct\"] = task_score(mdl, big_tok)\n", " row[\"bytes_read_per_token\"] = bytes_read_per_token(mdl, alloc)\n", " row[\"ceiling_ms\"] = round(row[\"bytes_read_per_token\"] / BW * 1e3, 3)\n", " big_rows.append(row)\n", " print({k: v for k, v in row.items()})\n", " del mdl\n", " free()\n", "formats += big_rows\n", "if formats:\n", " cols = []\n", " for r_ in formats:\n", " for k in r_:\n", " if k not in cols:\n", " cols.append(k)\n", " save_csv(\"formats.csv\", [{k: r_.get(k, \"\") for k in cols} for r_ in formats])" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: how many bytes did each format save, and is it the 2x and 4x the bit counts suggest (what is left in\n", "16 bits)? Which format is closest to its bandwidth ceiling, and which is far from it? Why is the 8-bit model\n", "*slower* than the 16-bit one? Is the 7 B model in 4 bits better than the 1.5 B in 16 bits on perplexity, and what\n", "does it cost in bytes?" ], "id": "lab-6-3-quant-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Why a quantized matrix is not automatically faster: one matrix-vector product\n", "\n", "Decode multiplies one vector by each weight matrix: bytes in, one multiply-add per weight. A 4-bit matrix holds a\n", "quarter of the bytes, but only a kernel that *unpacks the 4-bit numbers while reading them* gets the speed. We\n", "time one `[8960, 1536]` matrix (a feed-forward layer of this model, 27.5 MB in 16 bits) three ways: 16-bit; our own\n", "4-bit (packed two per byte, scale per 128) unpacked to 16 bits in PyTorch and then multiplied; and the\n", "library's fused 4-bit kernel." ], "id": "lab-6-3-quant-18" }, { "cell_type": "code", "metadata": {}, "source": [ "micro = []\n", "if ON_GPU and HAVE_BNB:\n", " W16 = read_weight(\"model.layers.10.mlp.up_proj.weight\").to(\"cuda\", torch.float16)\n", " x16 = torch.randn(1, W16.shape[1], generator=torch.Generator().manual_seed(0)).to(\"cuda\", torch.float16)\n", "\n", " def bench_ms(fn, loops=50, repeats=7):\n", " fn()\n", " sync()\n", " res = []\n", " for _ in range(repeats):\n", " e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)\n", " e0.record()\n", " for _ in range(loops):\n", " fn()\n", " e1.record()\n", " sync()\n", " res.append(e0.elapsed_time(e1) / loops)\n", " return statistics.median(res)\n", "\n", " # our 4-bit: symmetric, groups of 128 along each row, two values per byte\n", " deq, q, scale, zero = quantize(W16.float(), 4, 128)\n", " qi = (q.reshape(W16.shape).to(torch.int16) + 8).to(torch.uint8) # 1..15\n", " packed = (qi[:, 0::2] | (qi[:, 1::2] << 4)).contiguous() # [rows, cols/2] bytes\n", " scales = scale.reshape(W16.shape[0], -1).to(torch.float16) # [rows, cols/128]\n", "\n", " def unpack(packed, scales):\n", " lo, hi = (packed & 0xF).to(torch.float16) - 8, (packed >> 4).to(torch.float16) - 8\n", " w = torch.stack([lo, hi], dim=-1).reshape(packed.shape[0], -1)\n", " return (w.reshape(w.shape[0], -1, 128) * scales[:, :, None]).reshape(w.shape[0], -1)\n", "\n", " print(\"own unpack vs the fake-quantized matrix: largest difference\",\n", " f\"{(unpack(packed, scales).float() - deq).abs().max().item():.2e}\")\n", " err_own = ((F.linear(x16, unpack(packed, scales)).float() - F.linear(x16, W16).float()).norm()\n", " / F.linear(x16, W16).float().norm()).item()\n", " qW, state = bnb.functional.quantize_4bit(W16, blocksize=64, quant_type=\"nf4\")\n", " y_ref = F.linear(x16, W16)\n", " y_bnb = bnb.matmul_4bit(x16, qW.t(), state)\n", " err_bnb = ((y_bnb.float() - y_ref.float()).norm() / y_ref.float().norm()).item()\n", " stored16 = W16.numel() * 2\n", " stored_own = packed.numel() + scales.numel() * 2\n", " stored_bnb = qW.numel() + state.absmax.numel() * 4\n", " for label, fn, nbytes, err in (\n", " (\"16-bit F.linear\", lambda: F.linear(x16, W16), stored16, 0.0),\n", " (\"own 4-bit: unpack to 16-bit, then F.linear\", lambda: F.linear(x16, unpack(packed, scales)), stored_own, err_own),\n", " (\"bitsandbytes NF4 fused kernel\", lambda: bnb.matmul_4bit(x16, qW.t(), state), stored_bnb, err_bnb),\n", " ):\n", " ms = bench_ms(fn)\n", " micro.append({\"method\": label, \"stored_bytes\": nbytes, \"ms\": round(ms, 4), \"effective_GBps\": round(nbytes / (ms / 1e3) / 1e9, 1),\n", " \"output_error_pct\": round(100 * err, 3)})\n", " print(f\"{label:44s} stored {nbytes / 1e6:6.2f} MB | {ms * 1e3:7.1f} us | {nbytes / (ms / 1e3) / 1e9:6.1f} GB/s of stored bytes \"\n", " f\"| output error {100 * err:.2f} %\")\n", " save_csv(\"dequant-microbench.csv\", micro)\n", " del W16, x16, packed, scales, qW, state\n", " free()\n", "else:\n", " print(\"needs a GPU and bitsandbytes: skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Why activations are harder than weights\n", "\n", "So far only *weights* were rounded; the numbers flowing between layers (activations) stayed in 16 bits. That is\n", "**weight-only** quantization, the kind that pays off in decode (bytes of weights dominate). **Weight and\n", "activation** quantization (W8A8) also does the multiplication in int8, which pays off in prefill (compute-bound),\n", "but activations have a problem weights do not: a few *channels* are huge, for every token. We record, for every\n", "linear layer, the largest absolute value per input channel over 512 tokens of text." ], "id": "lab-6-3-quant-20" }, { "cell_type": "code", "metadata": {}, "source": [ "if model is None:\n", " model = load_plain()\n", "n_tok = 512 if not TINY else 128\n", "x_ids = TEXT_IDS[:n_tok][None].to(DEVICE)\n", "chan_max, captured = {}, {}\n", "\n", "\n", "def make_hook(name):\n", " def hook(mod, args):\n", " x = args[0].detach()\n", " chan_max[name] = x.abs().amax(dim=tuple(range(x.ndim - 1))).float().cpu()\n", " if name in WANT:\n", " captured[name] = x[0].float().cpu()\n", " return hook\n", "\n", "\n", "WANT = set()\n", "hooks = [m.register_forward_pre_hook(make_hook(n)) for n, m in model.named_modules() if isinstance(m, torch.nn.Linear) and n.endswith(\"_proj\")]\n", "model(input_ids=x_ids)\n", "for h in hooks:\n", " h.remove()\n", "act_rows = []\n", "for n, cm in chan_max.items():\n", " med = cm.median().item()\n", " act_rows.append({\"layer\": n, \"channels\": cm.numel(), \"max_channel_absmax\": round(cm.max().item(), 2),\n", " \"median_channel_absmax\": round(med, 4), \"max_over_median\": round(cm.max().item() / med, 1),\n", " \"worst_channel\": int(cm.argmax())})\n", "save_csv(\"activation-outliers.csv\", act_rows)\n", "act_rows.sort(key=lambda r: -r[\"max_over_median\"])\n", "print(f\"{len(act_rows)} linear layers; largest channel / median channel of the same layer (512 tokens):\")\n", "for r in act_rows[:5]:\n", " print(\" \", r)\n", "print(\" median layer:\", act_rows[len(act_rows) // 2])" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The layers with the largest ratio are where W8A8 hurts. We take the worst one, read its weight, and compare\n", "four ways to compute `y = x Wᵀ` with int8 numbers against the 16-bit answer: (a) weights int8 per row, activations\n", "kept in 16 bits (weight-only); (b) activations int8 with *one scale per tensor*; (c) activations int8 with one scale\n", "per token; (d) LLM.int8()'s decomposition: the input channels whose largest value is above a threshold of 6 are\n", "multiplied in 16 bits, everything else in int8." ], "id": "lab-6-3-quant-22" }, { "cell_type": "code", "metadata": {}, "source": [ "worst_layer = act_rows[0][\"layer\"]\n", "WANT.add(worst_layer)\n", "hooks = [m.register_forward_pre_hook(make_hook(n)) for n, m in model.named_modules() if n == worst_layer]\n", "model(input_ids=x_ids)\n", "for h in hooks:\n", " h.remove()\n", "Xa = captured[worst_layer] # [tokens, in_features] float32\n", "Wl = read_weight(worst_layer + \".weight\") # [out, in]\n", "Yref = Xa @ Wl.T\n", "\n", "\n", "def int8_rows(w): # per-row symmetric int8, dequantized\n", " return quantize(w, 8, \"row\")[0]\n", "\n", "\n", "def int8_act(x, per=\"tensor\"):\n", " if per == \"tensor\":\n", " s = x.abs().max() / 127\n", " return torch.round(x / s).clamp(-127, 127) * s\n", " s = x.abs().amax(dim=1, keepdim=True) / 127\n", " return torch.round(x / s).clamp(-127, 127) * s\n", "\n", "\n", "Wq = int8_rows(Wl)\n", "outlier = Xa.abs().amax(dim=0) > 6.0\n", "y_decomp = int8_act(Xa[:, ~outlier]) @ Wq[:, ~outlier].T + Xa[:, outlier] @ Wl[:, outlier].T\n", "rel = lambda y: 100 * ((y - Yref).norm() / Yref.norm()).item()\n", "w8a8 = [\n", " {\"method\": \"weights int8 per row, activations 16-bit\", \"output_error_pct\": round(rel(Xa @ Wq.T), 3)},\n", " {\"method\": \"weights int8 per row, activations int8 per tensor\", \"output_error_pct\": round(rel(int8_act(Xa) @ Wq.T), 3)},\n", " {\"method\": \"weights int8 per row, activations int8 per token\", \"output_error_pct\": round(rel(int8_act(Xa, 'token') @ Wq.T), 3)},\n", " {\"method\": f\"LLM.int8 split: {int(outlier.sum())} outlier channels in 16-bit, rest int8\", \"output_error_pct\": round(rel(y_decomp), 3)},\n", "]\n", "print(f\"layer {worst_layer}: {Xa.shape[0]} tokens x {Xa.shape[1]} channels; largest |x| {Xa.abs().max():.1f}, \"\n", " f\"median channel max {Xa.abs().amax(dim=0).median():.3f}\")\n", "for r in w8a8:\n", " print(f\"{r['method']:70s} output error {r['output_error_pct']:8.3f} %\")\n", "for r in w8a8:\n", " r[\"layer\"] = worst_layer\n", "save_csv(\"w8a8-error.csv\", w8a8)\n", "del Xa, Wl, Wq, captured\n", "if ON_GPU:\n", " model = None\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: which channel is the outlier, and is it the same for every token? Why does *one scale per token*\n", "not fix it? What does the split of (d) cost in bytes and in speed?" ], "id": "lab-6-3-quant-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Build: speculative decoding\n", "\n", "**The idea.** Decode reads all the weights to produce *one* token, but Ch 4.1 and Ch 6.1 showed that a pass over\n", "`k + 1` tokens costs almost the same as a pass over one (the weights are read once either way). So let a cheap\n", "*draft* model write `k` tokens, then let the big *target* model score all of them in **one** pass and keep the\n", "longest prefix it agrees with, plus one token of its own:\n", "\n", "```text\n", "draft: d1 d2 d3 d4 (k = 4 cheap steps, one token each)\n", "target: [last, d1, d2, d3, d4] in one pass -> its own choice at each of the 5 positions\n", "accept: d1, d2 match; d3 does not -> emit d1, d2 and the target's token at that position\n", "```\n", "\n", "Every round emits at least one token (the target's own), at most `k + 1`. In **greedy** decoding the emitted\n", "tokens are exactly the ones the target alone would have written. With sampling, an accept/reject rule keeps\n", "the *distribution* exact (the next cell checks it). The speed-up depends on the **acceptance rate** `α` (the\n", "chance a drafted token is accepted) and on the cost ratio `c` of one draft step to one target step:\n", "\n", "```text\n", "tokens per round E = (1 - α^(k+1)) / (1 - α) (if each token is accepted with chance α, independently)\n", "time per round k · t_draft + t_verify (t_verify ≈ t_target)\n", "speed-up S = E · t_target / (k · t_draft + t_verify) ≈ E / (c · k + 1)\n", "```" ], "id": "lab-6-3-quant-25" }, { "cell_type": "code", "metadata": {}, "source": [ "def expected_tokens(alpha, k):\n", " return (k + 1) if alpha >= 1 else (1 - alpha ** (k + 1)) / (1 - alpha)\n", "\n", "\n", "def predicted_speedup(alpha, k, t_draft, t_target, t_verify=None):\n", " t_verify = t_target if t_verify is None else t_verify\n", " return expected_tokens(alpha, k) * t_target / (k * t_draft + t_verify)\n", "\n", "\n", "print(\"worked example (your Predict 5): alpha 0.7, k 4 ->\", round(expected_tokens(0.7, 4), 3), \"tokens per round; c = 0.3 ->\",\n", " round(predicted_speedup(0.7, 4, 0.3, 1.0), 3), \"x\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The output distribution is unchanged: the sampling rule, checked\n", "\n", "With sampling, the draft draws a token `x ~ q`. The target has its own distribution `p`. Accept `x` with\n", "probability `min(1, p(x) / q(x))`; if rejected, draw from the *residual* `max(0, p - q)` (renormalised). The\n", "claim: the result is distributed exactly as `p`, whatever `q` is. Five tokens, 2 million draws:" ], "id": "lab-6-3-quant-27" }, { "cell_type": "code", "metadata": {}, "source": [ "p = torch.tensor([0.50, 0.20, 0.15, 0.10, 0.05])\n", "q = torch.tensor([0.20, 0.40, 0.10, 0.25, 0.05])\n", "gen = torch.Generator().manual_seed(0)\n", "N = 2_000_000\n", "x = torch.multinomial(q, N, replacement=True, generator=gen)\n", "accept = torch.rand(N, generator=gen) < torch.minimum(torch.ones(5), p / q)[x]\n", "resid = torch.clamp(p - q, min=0)\n", "resid = resid / resid.sum()\n", "y = torch.where(accept, x, torch.multinomial(resid, N, replacement=True, generator=gen))\n", "emp = torch.bincount(y, minlength=5).float() / N\n", "emp_q = torch.bincount(x, minlength=5).float() / N\n", "alpha_theory = torch.minimum(p, q).sum().item()\n", "exact_rows = [{\"token\": i, \"p_target\": p[i].item(), \"q_draft\": q[i].item(), \"empirical_after_rule\": round(emp[i].item(), 5),\n", " \"empirical_draft_alone\": round(emp_q[i].item(), 5)} for i in range(5)]\n", "save_csv(\"spec-sampling-exact.csv\", exact_rows)\n", "print(f\"{'token':>5} {'p (target)':>11} {'q (draft)':>10} {'after the rule':>15} {'draft alone':>12}\")\n", "for r in exact_rows:\n", " print(f\"{r['token']:5d} {r['p_target']:11.3f} {r['q_draft']:10.3f} {r['empirical_after_rule']:15.4f} {r['empirical_draft_alone']:12.4f}\")\n", "print(f\"largest |empirical - p|: {(emp - p).abs().max().item():.5f} (draft alone: {(emp_q - p).abs().max().item():.5f})\")\n", "print(f\"acceptance chance sum(min(p, q)) = {alpha_theory:.3f}; measured {accept.float().mean().item():.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Greedy speculative decoding by hand\n", "\n", "State between rounds: both models' caches hold every committed token except the last one (`last`), which is the\n", "next input. One round:\n", "\n", "1. the draft runs `k` single-token steps from `last`, each taking the previous draft token as input;\n", "2. the target runs one pass over `[last, d1 .. dk]` and returns its greedy choice at each of the `k + 1` positions;\n", "3. `m` = how many drafted tokens equal the target's choices, in order; emit `d1 .. dm` and the target's token `p_m`;\n", "4. both caches forget everything after the committed prefix (the rejected drafts).\n", "\n", "We run the loop twice. `eager` is the Python loop of Lab 6.1. `graph` replays CUDA graphs, because (Lab 6.1) the\n", "eager loop's time is set by Python issuing about 1,200 kernels, not by the GPU, and then a draft step costs as much\n", "as a target step." ], "id": "lab-6-3-quant-29" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def spec_generate(tgt, drf, prompt, n_new, k, drf_prompt=None):\n", " \"\"\"Greedy speculative decoding. tgt, drf: runners. Returns (tokens, ms per token after the first, stats).\"\"\"\n", " P = prompt.shape[1]\n", " first = tgt.prefill(prompt)\n", " drf.prefill(prompt if drf_prompt is None else drf_prompt)\n", " out = [first.item()]\n", " last, n = out[0], P + 1 # n = committed length; the caches hold n - 1 positions\n", " drafted = torch.zeros(1, k, dtype=torch.long, device=DEVICE)\n", " ver = torch.zeros(1, k + 1, dtype=torch.long, device=DEVICE)\n", " reach = [0] * (k + 1) # rounds that accepted at least i drafted tokens\n", " rounds = 0\n", " sync()\n", " t0 = time.perf_counter()\n", " while len(out) < n_new:\n", " cur = torch.tensor([[last]], device=DEVICE)\n", " ver[:, 0:1].copy_(cur)\n", " for i in range(k):\n", " o = drf.feed(cur, n - 1 + i)\n", " drafted[:, i:i + 1].copy_(o)\n", " cur = o\n", " ver[:, 1:].copy_(drafted)\n", " p_l = tgt.feed(ver, n - 1)[0].tolist() # one read-back per round\n", " d_l = drafted[0].tolist()\n", " m = 0\n", " while m < k and d_l[m] == p_l[m]:\n", " m += 1\n", " new = d_l[:m] + [p_l[m]]\n", " out += new\n", " last = new[-1]\n", " for i in range(m + 1):\n", " reach[i] += 1\n", " rounds += 1\n", " tgt.truncate(n + m) # keep committed[: n + m]\n", " if m == k: # the draft never read d_k: feed it so the draft cache is complete\n", " drf.feed(drafted[:, k - 1:k], n + k - 1)\n", " else:\n", " drf.truncate(n + m)\n", " n += m + 1\n", " sync()\n", " ms = (time.perf_counter() - t0) * 1e3\n", " emitted = len(out) - 1\n", " accepted = emitted - rounds # every round emits its accepted drafts plus one token of the target's own\n", " attempts = accepted + (rounds - reach[k]) # each accepted draft was a successful try; each round that stopped early, one failed try\n", " stats = {\"rounds\": rounds, \"emitted\": emitted, \"tokens_per_round\": emitted / rounds,\n", " \"accept_rate\": accepted / attempts, # alpha: chance a drafted token is accepted, given the ones before it were\n", " \"accepted_share\": accepted / (rounds * k), # drafted tokens that were accepted, over all drafted tokens\n", " \"reach\": reach}\n", " return out[:n_new], ms / emitted, stats" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-30" }, { "cell_type": "code", "metadata": {}, "source": [ "PROMPTS = [ # varied work; each answer is long enough that no run ends early\n", " \"Explain in about 150 words why the sky is blue.\",\n", " \"Write a Python function that returns the n-th Fibonacci number, with a docstring and two examples.\",\n", " \"List twelve fruits, one per line, with a short description of each.\",\n", " \"Tell me a story of about 150 words about a fisherman who finds a glowing pearl.\",\n", " \"Translate into French, then explain each word choice: 'The library opens at nine and closes at five.'\",\n", " \"What is 17 times 23? Show every step of the long multiplication in detail.\",\n", "]\n", "N_NEW = 128 if not FAST else 48\n", "KS = [1, 2, 3, 4, 6, 8] if not FAST else [2, 4]\n", "if FAST:\n", " PROMPTS = PROMPTS[:2]\n", "\n", "spec_rows, reach_rows = [], []\n", "draft_model = tgt_model = None\n", "verify_rows = []\n", "if ON_GPU:\n", " tgt_model = load_plain()\n", " draft_model = AutoModelForCausalLM.from_pretrained(DRAFT[0], revision=DRAFT[1], dtype=DTYPE).to(DEVICE).eval()\n", " print(\"target\", sum(p_.numel() for p_ in tgt_model.parameters()), \"parameters; draft\",\n", " sum(p_.numel() for p_ in draft_model.parameters()), \"parameters; same vocabulary:\",\n", " tgt_model.config.vocab_size == draft_model.config.vocab_size)\n", " pids = [chat_ids(tok, p_) for p_ in PROMPTS]\n", "\n", " # (a) what one forward pass costs against the number of tokens in it (graph replay, context about 200)\n", " def verify_cost(mdl, label):\n", " gr = GraphRunner(mdl, 512)\n", " gr.prefill(TEXT_IDS[:200][None].to(DEVICE))\n", " for n_tok_ in ([1, 2, 3, 5, 9, 17, 33, 65, 129] if not FAST else [1, 5, 9]):\n", " tk = TEXT_IDS[200:200 + n_tok_][None].to(DEVICE)\n", " gr.feed(tk, 200)\n", " sync()\n", " ts = []\n", " for _ in range(30):\n", " t0 = time.perf_counter()\n", " gr.feed(tk, 200)\n", " sync()\n", " ts.append((time.perf_counter() - t0) * 1e3)\n", " verify_rows.append({\"model\": label, \"tokens_in_pass\": n_tok_, \"ms\": round(statistics.median(ts), 3)})\n", " print(f\"{label:22s} one pass over {n_tok_:4d} tokens: {verify_rows[-1]['ms']:7.3f} ms\")\n", " del gr\n", " free()\n", "\n", " verify_cost(tgt_model, \"1.5B 16-bit\")\n", " if HAVE_BNB:\n", " q4 = load_format(\"nf4\")\n", " verify_cost(q4, \"1.5B 4-bit (NF4)\")\n", " del q4\n", " free()\n", " save_csv(\"verify-cost.csv\", verify_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-31" }, { "cell_type": "code", "metadata": {}, "source": [ "diff_cases = {}\n", "\n", "\n", "def step_cost(mdl, kind):\n", " \"\"\"Median over 3 runs of the mean ms per plain decode step (48 tokens).\"\"\"\n", " return statistics.median(plain_generate(make_runner(mdl, kind, 1024), pids[0], 48)[1] for _ in range(3))\n", "\n", "\n", "def run_grid(tgt, label, kinds, ks, prompt_ids_):\n", " \"\"\"Speculative decoding of every prompt at every k against plain decoding of the same target.\"\"\"\n", " for kind in kinds:\n", " t_t, t_d = step_cost(tgt, kind), step_cost(draft_model, kind)\n", " print(f\"[{label}] {kind:6s}: one target step {t_t:.2f} ms | one draft step {t_d:.2f} ms | c = {t_d / t_t:.2f}\")\n", " t_r, d_r = make_runner(tgt, kind, 1024), make_runner(draft_model, kind, 1024) # graphs are captured once and reused\n", " for k in ks:\n", " spec_generate(t_r, d_r, pids[0], 24, k) # warm-up: captures the graphs of this k\n", " for pi in prompt_ids_:\n", " plain_toks, plain_ms = plain_generate(t_r, pids[pi], N_NEW)\n", " for k in ks:\n", " toks, ms, st = spec_generate(t_r, d_r, pids[pi], N_NEW, k)\n", " t_v = next((v[\"ms\"] for v in verify_rows if v[\"model\"] == label and v[\"tokens_in_pass\"] == k + 1), t_t) if kind == \"graph\" else t_t\n", " row = {\"target\": label, \"mode\": kind, \"prompt\": pi, \"k\": k, \"alpha\": round(st[\"accept_rate\"], 4),\n", " \"accepted_share\": round(st[\"accepted_share\"], 4), \"tokens_per_round\": round(st[\"tokens_per_round\"], 3),\n", " \"predicted_tokens_per_round\": round(expected_tokens(st[\"accept_rate\"], k), 3), \"rounds\": st[\"rounds\"],\n", " \"plain_ms_per_token\": round(plain_ms, 3), \"spec_ms_per_token\": round(ms, 3),\n", " \"speedup\": round(plain_ms / ms, 3),\n", " \"predicted_speedup\": round(predicted_speedup(st[\"accept_rate\"], k, t_d, t_t, t_v), 3),\n", " \"identical_to_plain\": toks == plain_toks,\n", " \"first_difference\": next((i for i, (a_, b_) in enumerate(zip(toks, plain_toks)) if a_ != b_), -1)}\n", " spec_rows.append(row)\n", " if not row[\"identical_to_plain\"]:\n", " diff_cases[(label, kind, pi, k)] = (toks, plain_toks)\n", " reach_rows.extend({\"target\": label, \"mode\": kind, \"prompt\": pi, \"k\": k, \"i\": i, \"rounds_reaching\": v}\n", " for i, v in enumerate(st[\"reach\"]))\n", " print(f\" {kind:6s} prompt {pi} k {k}: alpha {row['alpha']:.2f} | {row['tokens_per_round']:.2f} tok/round \"\n", " f\"(formula {row['predicted_tokens_per_round']:.2f}) | plain {plain_ms:.2f} vs spec {ms:.2f} ms/token = \"\n", " f\"{row['speedup']:.2f}x (formula {row['predicted_speedup']:.2f}x) | identical {row['identical_to_plain']}\")\n", " del t_r, d_r\n", " free()\n", "\n", "\n", "if ON_GPU:\n", " run_grid(tgt_model, \"1.5B 16-bit\", (\"eager\", \"graph\"), KS, range(len(pids)))\n", " if HAVE_BNB and not FAST:\n", " q4 = load_format(\"nf4\")\n", " run_grid(q4, \"1.5B 4-bit (NF4)\", (\"graph\",), [2, 4], range(len(pids)))\n", " del q4\n", " free()\n", " save_csv(\"spec-decode.csv\", spec_rows)\n", " save_csv(\"acceptance-by-position.csv\", reach_rows)\n", "else:\n", " print(\"needs a GPU (and a draft model smaller than the target): skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: for which prompts is the acceptance rate high, and why would it be? Does a larger `k` always help? In\n", "which mode does speculative decoding win, and why is the eager mode different? Compare the *predicted* tokens per\n", "round and speed-up (formula with your measured `α` and `c`) with the measured ones: which of the two predictions is\n", "closer, and what does the formula leave out? With a 4-bit target, what does the table of one-pass costs (above) say\n", "about the verify pass?" ], "id": "lab-6-3-quant-33" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Is the output really the same?\n", "\n", "In exact arithmetic, greedy speculative decoding writes the target's tokens. On a GPU in 16 bits, a pass over\n", "`k + 1` tokens and a pass over one token use different kernels and add numbers in a different order, so the two\n", "can disagree when the target's top two scores are almost equal. For every run that did not match, we look at the\n", "token where it first differed and ask the 16-bit target for its two scores there." ], "id": "lab-6-3-quant-34" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " diff_rows = []\n", " print(f\"{sum(1 for r in spec_rows if not r['identical_to_plain'])} of {len(spec_rows)} runs differ from plain decoding\")\n", " for (label, kind, pi, k), (toks, plain_toks) in diff_cases.items():\n", " if label != \"1.5B 16-bit\":\n", " continue\n", " j = next(i for i, (a_, b_) in enumerate(zip(toks, plain_toks)) if a_ != b_)\n", " ctx = torch.cat([pids[pi][0], torch.tensor(plain_toks[:j], dtype=torch.long, device=DEVICE)])[None]\n", " logits = tgt_model(input_ids=ctx).logits[0, -1].float()\n", " top2 = logits.topk(2).values\n", " diff_rows.append({\"mode\": kind, \"prompt\": pi, \"k\": k, \"first_difference\": j, \"plain_token\": plain_toks[j],\n", " \"spec_token\": toks[j], \"logit_plain_token\": round(logits[plain_toks[j]].item(), 3),\n", " \"logit_spec_token\": round(logits[toks[j]].item(), 3), \"top1_minus_top2\": round((top2[0] - top2[1]).item(), 3)})\n", " print(diff_rows[-1])\n", " if diff_rows:\n", " save_csv(\"spec-differences.csv\", diff_rows)\n", " print()\n", " print(f\"{'target':17s} {'mode':6s} {'k':>2s} {'alpha':>6s} | tokens per round: {'formula':>7s} {'measured':>8s} | speed-up: {'formula':>7s} {'measured':>8s}\")\n", " for label in dict.fromkeys(r[\"target\"] for r in spec_rows):\n", " for kind in dict.fromkeys(r[\"mode\"] for r in spec_rows if r[\"target\"] == label):\n", " for k in sorted({r[\"k\"] for r in spec_rows if r[\"target\"] == label and r[\"mode\"] == kind}):\n", " rs = [r for r in spec_rows if r[\"target\"] == label and r[\"mode\"] == kind and r[\"k\"] == k]\n", " m = lambda key: statistics.mean(r[key] for r in rs)\n", " print(f\"{label:17s} {kind:6s} {k:2d} {m('alpha'):6.3f} | {'':17s}{m('predicted_tokens_per_round'):7.2f} {m('tokens_per_round'):8.2f} \"\n", " f\"| {'':9s}{m('predicted_speedup'):7.2f}x {m('speedup'):7.2f}x\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The library path\n", "\n", "`transformers` has this built in: pass `assistant_model=` to `generate()`. It uses the same growing-cache eager\n", "loop as our `eager` mode, so it is the fair comparison for it." ], "id": "lab-6-3-quant-36" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " lib_rows = []\n", " pid = pids[0]\n", " kw = dict(max_new_tokens=N_NEW, min_new_tokens=N_NEW, do_sample=False, pad_token_id=tok.eos_token_id)\n", " draft_model.generation_config.num_assistant_tokens = 4\n", " draft_model.generation_config.num_assistant_tokens_schedule = \"constant\"\n", " for rep in range(2):\n", " sync()\n", " t0 = time.perf_counter()\n", " a = tgt_model.generate(input_ids=pid, **kw)\n", " sync()\n", " t_plain = time.perf_counter() - t0\n", " t0 = time.perf_counter()\n", " b = tgt_model.generate(input_ids=pid, assistant_model=draft_model, **kw)\n", " sync()\n", " t_spec = time.perf_counter() - t0\n", " same = torch.equal(a, b)\n", " lib_rows.append({\"path\": \"transformers generate(assistant_model=...), k=4, prompt 0, greedy\",\n", " \"plain_s\": round(t_plain, 3), \"assisted_s\": round(t_spec, 3), \"speedup\": round(t_plain / t_spec, 3),\n", " \"identical_tokens\": same, \"new_tokens\": N_NEW})\n", " print(lib_rows[-1])\n", " save_csv(\"spec-library.csv\", lib_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-37" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| Group size in section 2 | 256, 16, 8 | Where does the extra storage for scales start to cost more than the error it removes? |\n", "| Bits | int3, int2 (change `quantize` bits) | At which bit width does the perplexity of section 2's simulation leave the \"usable\" range? |\n", "| Symmetric vs asymmetric | `sym=False` in `apply_scheme` | Which weights gain from a zero point, and why do few of them? |\n", "| Text for perplexity | a different text; window 256 vs 2048 | Which numbers stay comparable between formats and which do not? |\n", "| Number of draft tokens `k` | 1 to 16 | Where does the measured speed-up peak, and does the formula predict where? |\n", "| Prompt type | code, a list, free story, arithmetic | Which text gets the highest acceptance, and what does that say about when a draft model is a good idea? |\n", "| Draft quantized | load the draft in NF4 | Does a 4-bit draft keep its acceptance rate? What does it cost in speed? |\n", "| Sampling | write the accept/reject rule into `spec_generate` | Does the acceptance rate rise or fall against greedy, and is the first token still the target's? |" ], "id": "lab-6-3-quant-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three pre-broken cells. For each: read the symptom, write down what you think is wrong and how you would prove\n", "it, then fix it. The questions are under each cell; the answers are in the Instructor Companion." ], "id": "lab-6-3-quant-39" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · One scale for the whole tensor\n", "\n", "A teammate quantizes a feed-forward weight matrix of the model to 4 bits with a single scale for the whole matrix\n", "(nothing else is changed) and reports: \"the layer's output is nearly all zeros\"." ], "id": "lab-6-3-quant-40" }, { "cell_type": "code", "metadata": {}, "source": [ "Wb = read_weight(typical[\"name\"])\n", "Wb[17, 5] = 40 * Wb.std() # one weight, 40 standard deviations out (the real largest max/std is in section 2)\n", "Xb = torch.randn(Wb.shape[1], 64, generator=torch.Generator().manual_seed(1))\n", "deq_b, q_b, scale_b, _ = quantize(Wb, 4)\n", "print(\"matrix\", tuple(Wb.shape), \"| largest |w| / std =\", round((Wb.abs().max() / Wb.std()).item(), 1))\n", "print(\"output error:\", f\"{100 * ((deq_b @ Xb - Wb @ Xb).norm() / (Wb @ Xb).norm()).item():.1f} %\")\n", "print(\"share of weights stored as the integer 0:\", f\"{100 * (q_b == 0).float().mean().item():.2f} %\")\n", "print(\"scale:\", f\"{scale_b.item():.5f}\", \"| std of the weights:\", f\"{Wb.std().item():.5f}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-41" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: what is the step size of the 4-bit grid compared with the typical weight, and what does rounding do to\n", "every weight smaller than half a step? Why is one weight enough to do this? Which quantity of the scan in section 2\n", "warns you before you quantize? Fix it without changing the number of bits, and say what it costs." ], "id": "lab-6-3-quant-42" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · Perplexities that cannot be compared\n", "\n", "Two reports land on your desk. (1) \"GPT-2 (124 M) has perplexity X and Qwen2.5-0.5B has perplexity Y on WikiText-2,\n", "so Qwen is Z times better.\" (2) \"Model B has perplexity 23.7, model A has 16.2: B is 46 % worse.\" Run the cell that\n", "reproduces the numbers, and read the columns of the table before you believe either report." ], "id": "lab-6-3-quant-43" }, { "cell_type": "code", "metadata": {}, "source": [ "def sub_model(spec, dtype=None):\n", " return AutoModelForCausalLM.from_pretrained(spec[0], revision=spec[1] if len(spec) > 1 else None,\n", " dtype=dtype or DTYPE).to(DEVICE).eval()\n", "\n", "\n", "cmp_rows = []\n", "free()\n", "q05 = model if not ON_GPU else sub_model(DRAFT)\n", "tok05 = AutoTokenizer.from_pretrained(DRAFT[0], revision=DRAFT[1])\n", "gpt2_tok = AutoTokenizer.from_pretrained(\"openai-community/gpt2\")\n", "gpt2 = sub_model((\"openai-community/gpt2\", None), dtype=torch.float32 if not ON_GPU else DTYPE)\n", "g_ids = gpt2_tok(TEXT, return_tensors=\"pt\").input_ids[0]\n", "for name, mdl, tk, ids in ((\"GPT-2 124M\", gpt2, gpt2_tok, g_ids), (\"Qwen2.5-0.5B\", q05, tok05, TEXT_IDS)):\n", " r = perplexity(mdl, ids, window=WIN, n_win=N_WIN, tokenizer=tk)\n", " cmp_rows.append({\"comparison\": \"different models, same text\", \"model\": name, \"window\": WIN, \"tokens\": r[\"tokens\"],\n", " \"bytes\": r[\"bytes\"], \"ppl\": round(r[\"ppl\"], 3), \"bits_per_byte\": round(r[\"nll_sum\"] / r[\"bytes\"] / math.log(2), 4)})\n", "for w_ in ((256, 1024) if not TINY else (64, 256)): # the same model at two window sizes\n", " r = perplexity(q05, TEXT_IDS, window=w_, n_win=max(1, (WIN * N_WIN) // w_), tokenizer=tok05)\n", " cmp_rows.append({\"comparison\": \"same model, different window\", \"model\": \"Qwen2.5-0.5B\", \"window\": w_, \"tokens\": r[\"tokens\"],\n", " \"bytes\": r[\"bytes\"], \"ppl\": round(r[\"ppl\"], 3), \"bits_per_byte\": round(r[\"nll_sum\"] / r[\"bytes\"] / math.log(2), 4)})\n", "print(f\"the whole text: {len(TEXT_IDS):,} Qwen tokens, {len(g_ids):,} GPT-2 tokens, {len(TEXT.encode()):,} bytes\")\n", "print(f\"{'comparison':32s} {'model':14s} {'window':>6s} {'tokens':>8s} {'bytes':>8s} {'ppl':>9s} {'bits/byte':>10s}\")\n", "for r in cmp_rows:\n", " print(f\"{r['comparison']:32s} {r['model']:14s} {r['window']:6d} {r['tokens']:8d} {r['bytes']:8d} {r['ppl']:9.3f} {r['bits_per_byte']:10.4f}\")\n", "save_csv(\"ppl-comparability.csv\", cmp_rows)\n", "del gpt2\n", "if ON_GPU:\n", " del q05\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-44" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: perplexity is `exp` of the loss *per token*. What is a token for GPT-2, and what is one for Qwen, and\n", "how many of each does the same text have (the notebook printed the counts in section 2)? So what exactly does a\n", "ratio of the two perplexities compare? What would you report instead (the table has a column that does not depend\n", "on the tokenizer), and what must you hold fixed when you compare a 16-bit and a 4-bit model of the *same*\n", "family? Which of the two reports (1) and (2) can you trust, and under what conditions?" ], "id": "lab-6-3-quant-45" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · A draft that does not speak the target's language\n", "\n", "A teammate wants a faster 1.5 B model and has a 124 M GPT-2 lying around, which is certainly cheap. They plug it\n", "in as the draft. First the crash they saw (run on the CPU, where an error is an error and not a corrupted GPU),\n", "then the \"fix\" they shipped." ], "id": "lab-6-3-quant-46" }, { "cell_type": "code", "metadata": {}, "source": [ "gpt2_cpu = AutoModelForCausalLM.from_pretrained(\"openai-community/gpt2\", dtype=torch.float32).eval()\n", "qwen_ids = chat_ids(tok, PROMPTS[0], \"cpu\")\n", "print(\"largest token id the target's tokenizer produced for the prompt:\", int(qwen_ids.max()),\n", " \"| GPT-2 vocabulary size:\", gpt2_cpu.config.vocab_size)\n", "try:\n", " gpt2_cpu(input_ids=qwen_ids)\n", "except Exception as e:\n", " print(\"crash:\", type(e).__name__, \"-\", str(e)[:100])\n", "del gpt2_cpu\n", "free()\n", "\n", "\n", "class ClampedRunner:\n", " \"\"\"The 'fix': squeeze every id into the draft's vocabulary so that nothing is out of range.\"\"\"\n", "\n", " def __init__(self, inner, vocab):\n", " self.inner, self.vocab = inner, vocab\n", "\n", " def prefill(self, ids):\n", " return self.inner.prefill(ids.clamp(max=self.vocab - 1))\n", "\n", " def feed(self, tok_, start):\n", " return self.inner.feed(tok_.clamp(max=self.vocab - 1), start)\n", "\n", " def truncate(self, n):\n", " self.inner.truncate(n)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-47" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " bad = sub_model((\"openai-community/gpt2\", None))\n", " rows7c = []\n", " t_r = make_runner(tgt_model, \"eager\", 1024)\n", " d_r = ClampedRunner(make_runner(bad, \"eager\", 1024), bad.config.vocab_size)\n", " toks, ms, st = spec_generate(t_r, d_r, pids[0], 64, 4)\n", " _, plain_ms = plain_generate(make_runner(tgt_model, \"eager\", 1024), pids[0], 64)\n", " rows7c.append({\"draft\": \"GPT-2 124M, ids clamped to its vocabulary\", \"k\": 4, \"alpha\": round(st[\"accept_rate\"], 4),\n", " \"tokens_per_round\": round(st[\"tokens_per_round\"], 3), \"plain_ms_per_token\": round(plain_ms, 3),\n", " \"spec_ms_per_token\": round(ms, 3), \"speedup\": round(plain_ms / ms, 3)})\n", " print(rows7c[-1])\n", " print(\"the same words, two tokenizers:\", gpt2_tok.tokenize(\"Explain why\")[:6], \"vs\", tok.tokenize(\"Explain why\")[:6])\n", " try:\n", " tgt_model.generate(input_ids=pids[0], assistant_model=bad, max_new_tokens=8, do_sample=False)\n", " print(\"library: generate(assistant_model=GPT-2) ran without an error\")\n", " except Exception as e:\n", " print(\"library:\", type(e).__name__, \"-\", str(e).split(chr(10))[0][:200])\n", " save_csv(\"spec-failure.csv\", rows7c)\n", " del bad\n", " free()\n", "else:\n", " print(\"needs a GPU: skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-48" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: why did the first call crash, and why does the second not? What is the acceptance rate, and what does it\n", "tell you about how the target judges the draft's tokens? Without any crash, how would you notice this in\n", "production (which two numbers)? What property must a draft and a target share, and what does the library line above\n", "say about it?" ], "id": "lab-6-3-quant-49" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Where the time went (profiler)\n", "\n", "This section runs last on purpose: after the profiler has run once, every later call in the process is slower\n", "(Lab 6.1). We profile one decode step of each format: how many kernels it launches, how long the GPU is busy, and how\n", "long Python needs to issue them." ], "id": "lab-6-3-quant-50" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def profile_step(mdl, ctx=32):\n", " from torch.profiler import ProfilerActivity, profile\n", " runner = EagerRunner(mdl)\n", " prompt = TEXT_IDS[:ctx][None].to(DEVICE)\n", " cur = runner.prefill(prompt)[:, None]\n", " pos = [ctx]\n", "\n", " def step():\n", " o = runner.feed(cur, pos[0])\n", " pos[0] += 1\n", " return o\n", "\n", " step(); step(); sync()\n", " t0 = time.perf_counter()\n", " step()\n", " issue_ms = (time.perf_counter() - t0) * 1e3\n", " sync()\n", " with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:\n", " step()\n", " sync()\n", " total, n, by = 0.0, 0, {}\n", " for e in prof.events():\n", " if e.device_type == torch.autograd.DeviceType.CUDA:\n", " us = e.device_time if hasattr(e, \"device_time\") else e.cuda_time\n", " total += us\n", " n += 1\n", " d = by.setdefault(e.name, [0.0, 0])\n", " d[0] += us\n", " d[1] += 1\n", " top = sorted(((k_, v[0] / 1e3, v[1]) for k_, v in by.items()), key=lambda x: -x[1])[:3]\n", " return n, total / 1e3, issue_ms, top\n", "\n", "\n", "prof_rows = []\n", "if ON_GPU and HAVE_BNB:\n", " del tgt_model, draft_model\n", " free()\n", " for label, kind in ((\"16-bit float\", \"fp16\"), (\"8-bit (LLM.int8)\", \"int8\"), (\"4-bit (NF4)\", \"nf4\")):\n", " mdl = load_format(kind)\n", " profile_step(mdl) # warm-up\n", " n, busy, issue, top = profile_step(mdl)\n", " prof_rows.append({\"format\": label, \"kernels\": n, \"gpu_busy_ms\": round(busy, 3), \"python_issue_ms\": round(issue, 3),\n", " \"top_kernel\": top[0][0][:60], \"top_kernel_ms\": round(top[0][1], 3), \"top_kernel_launches\": top[0][2]})\n", " print(f\"{label:18s} {n:5d} kernels | GPU busy {busy:6.2f} ms | Python issue {issue:6.2f} ms | top: {top[0][0][:50]} {top[0][1]:.2f} ms x{top[0][2]}\")\n", " del mdl\n", " free()\n", " save_csv(\"decode-profile.csv\", prof_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-51" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Versions tested" ], "id": "lab-6-3-quant-52" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"Python\", platform.python_version(), \"|\", platform.platform())\n", "print(\"PyTorch\", torch.__version__, \"| CUDA runtime\", torch.version.cuda, \"| transformers\", transformers.__version__,\n", " \"| bitsandbytes\", getattr(bnb, \"__version__\", \"none\"))\n", "print(\"models:\", SERVING[0], SERVING[1], \"|\", DRAFT[0], DRAFT[1], \"|\", BIG[0], BIG[1])\n", "print(\"text:\", TEXT_NAME, \"| scored tokens per format:\", len(USED) - N_WIN, f\"({N_WIN} windows of {WIN})\")\n", "if ON_GPU:\n", " print(\"GPU:\", torch.cuda.get_device_name(0), \"| compute capability\", torch.cuda.get_device_capability(0))\n", " try:\n", " drv = subprocess.run([\"nvidia-smi\", \"--query-gpu=driver_version\", \"--format=csv,noheader\"],\n", " capture_output=True, text=True).stdout.strip()\n", " print(\"NVIDIA driver\", drv)\n", " except Exception:\n", " pass" ], "execution_count": null, "outputs": [], "id": "lab-6-3-quant-53" } ] }