{ "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.1 · Prefill, Decode and the KV Cache\n", "\n", "**Goal:** write the text-generation loop by hand for a real open model, with and without a KV\n", "cache; measure time per token against position, time to first token against prompt length, decode\n", "speed against the memory-bandwidth ceiling, and the cache's size in bytes against the formula; then\n", "break the loop three ways.\n", "\n", "**Runs on:** an NVIDIA GPU with at least 8 GB (free Kaggle or Colab T4; the book's numbers come\n", "from an RTX 3060 12 GB). Without a GPU every cell still runs on the CPU with the 0.5 B sibling of the\n", "model, much smaller sizes and float32, so you can read the code and the printed tables; the\n", "bandwidth story is a GPU story. Install: `uv run --with torch --with transformers --with matplotlib\n", "jupyter lab` (the first run downloads about 3 GB of weights from Hugging Face, no login needed).\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-6-1-kvcache-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import copy\n", "import csv\n", "import gc\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import statistics\n", "import subprocess\n", "import time\n", "import warnings\n", "\n", "import torch\n", "import transformers\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "warnings.filterwarnings(\"ignore\") # transformers 5 renames `past_key_values` (still accepted) and warns on every call\n", "transformers.logging.set_verbosity_error()\n", "\n", "torch.set_grad_enabled(False) # an inference lab: never build autograd graphs (they would keep activations alive)\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", "\n", "# The serving model of Vols 6-7 (data/models.json): Qwen2.5-1.5B-Instruct, Apache-2.0, ungated, pinned\n", "# to an exact revision so everybody loads the same weights. Without a GPU: its 0.5 B sibling.\n", "MODELS = {\n", " \"gpu\": (\"Qwen/Qwen2.5-1.5B-Instruct\", \"989aa7980e4cf806f80c7fef2b1adb7bc71aa306\"),\n", " \"cpu\": (\"Qwen/Qwen2.5-0.5B-Instruct\", \"7ae557604adf67be50417f59c2c2f167def9a775\"),\n", "}\n", "MODEL_ID, REVISION = MODELS[\"gpu\" if ON_GPU else \"cpu\"]\n", "DTYPE = torch.float16 if ON_GPU else torch.float32\n", "SMALL = not ON_GPU # CPU path: smaller sizes so every cell finishes in a minute or two\n", "print(\"PyTorch\", torch.__version__, \"| transformers\", transformers.__version__, \"| device:\", DEVICE)\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 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-1-kvcache\"\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-1-kvcache-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\n", "numbers next to them.\n", "\n", "1. **Ceiling.** The model has `P` parameters, each `b` bytes. Your GPU moves `B` bytes per second.\n", " At most how many tokens per second can one user get, ignoring everything but reading the weights?\n", "2. **Recompute.** Generating 512 tokens from a 32-token prompt *without* a cache re-reads and\n", " re-processes the whole sequence at every step. How many token positions are processed in total,\n", " against how many with a cache?\n", "3. **Cache size.** Per token, the cache stores one key and one value vector for every layer and every\n", " key/value head. How many bytes per token for this model? (Look at its `config.json` first.)\n", "4. **First token.** Will the first token of a 4,096-token prompt take about as long as a later\n", " token, 10 times as long, or 100 times as long?\n", "5. **Growth.** With a cache, will the time per token at position 4,096 be the same as at position 64?\n", "\n", "Keep your numbers in the dict below; the last cell of the Explore section prints them again." ], "id": "lab-6-1-kvcache-02" }, { "cell_type": "code", "metadata": {}, "source": [ "PREDICT = {\n", " \"ceiling_tokens_per_s\": None,\n", " \"positions_no_cache\": None,\n", " \"positions_with_cache\": None,\n", " \"kv_bytes_per_token\": None,\n", " \"first_token_4096_vs_later_token\": None,\n", " \"decode_pos4096_vs_pos64\": None,\n", "}\n", "print(PREDICT)" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Load the model and read its shape\n", "\n", "Everything the cache needs is in the model's configuration: the number of layers, how many\n", "key/value heads each has, and how wide a head is. Hugging Face `transformers` loads the weights; the\n", "loop that generates text is ours." ], "id": "lab-6-1-kvcache-04" }, { "cell_type": "code", "metadata": {}, "source": [ "tok = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)\n", "model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=DTYPE).to(DEVICE).eval()\n", "cfg = model.config\n", "\n", "LAYERS = cfg.num_hidden_layers\n", "Q_HEADS = cfg.num_attention_heads\n", "KV_HEADS = cfg.num_key_value_heads\n", "HEAD_DIM = getattr(cfg, \"head_dim\", None) or cfg.hidden_size // Q_HEADS\n", "D_MODEL = cfg.hidden_size\n", "VOCAB = cfg.vocab_size\n", "ITEM = torch.finfo(DTYPE).bits // 8 # bytes per number\n", "\n", "PARAMS = sum(p.numel() for p in model.parameters()) # tied weights are counted once\n", "MODEL_BYTES = sum(p.numel() * p.element_size() for p in model.parameters())\n", "EMBED_PARAMS = VOCAB * D_MODEL\n", "BODY_PARAMS = PARAMS - EMBED_PARAMS # what a token's forward pass multiplies (tied embeddings)\n", "\n", "print(f\"layers {LAYERS} | query heads {Q_HEADS} | key/value heads {KV_HEADS} | head_dim {HEAD_DIM} \"\n", " f\"| d_model {D_MODEL} | vocab {VOCAB:,}\")\n", "print(f\"tie_word_embeddings {cfg.tie_word_embeddings} | max_position_embeddings {cfg.max_position_embeddings:,}\")\n", "print(f\"parameters {PARAMS:,} ({PARAMS / 1e9:.3f} B) | of which embedding matrix {EMBED_PARAMS:,}\")\n", "print(f\"weights in memory {MODEL_BYTES:,} bytes = {MODEL_BYTES / 1e9:.3f} GB = {MODEL_BYTES / 2**30:.3f} GiB\")\n", "\n", "\n", "def kv_bytes(tokens, batch=1, kv_heads=None, layers=LAYERS, head_dim=HEAD_DIM, item=ITEM):\n", " \"\"\"The formula: 2 (key and value) x layers x kv_heads x head_dim x bytes x tokens x batch.\"\"\"\n", " kv_heads = KV_HEADS if kv_heads is None else kv_heads\n", " return 2 * layers * kv_heads * head_dim * item * tokens * batch\n", "\n", "\n", "per_token = kv_bytes(1)\n", "per_token_mha = kv_bytes(1, kv_heads=Q_HEADS)\n", "print(f\"KV cache per token: {per_token:,} bytes = {per_token / 1024:.2f} KiB \"\n", " f\"(if every query head had its own key/value: {per_token_mha:,} bytes, {per_token_mha / per_token:.0f}x more)\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build: the generation loop by hand\n", "\n", "`model(...)` returns the scores of the next token at every position. For generation we need the\n", "scores at the *last* position only, so we call the stack of layers (`model.model`), take the last\n", "hidden vector, and multiply it by the output matrix (`model.lm_head`) ourselves. Taking the last\n", "position before the output matrix matters: scoring all positions would build a `[tokens, vocab]`\n", "table, 151,936 numbers per token. Failure playground 7c shows what that costs.\n", "\n", "**Loop A, no cache.** Every step feeds the *whole* sequence again and keeps one answer.\n", "**Loop B, with a cache.** One *prefill* step feeds the whole prompt and keeps every layer's keys and\n", "values; every later *decode* step feeds one token and reads the cache.\n", "\n", "Greedy decoding (always the highest score) makes the two loops comparable: they must produce the\n", "same tokens. We ignore the end-of-text token so every run produces exactly `n_new` tokens." ], "id": "lab-6-1-kvcache-06" }, { "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", " \"When he reached his usual spot he stopped rowing, looked down into the dark water, and saw something \"\n", " \"shining at the bottom. It was small and round, and it was glowing like a lantern. \"\n", ")\n", "# A long text to cut prompts of any length from: the story, then a list of facts, repeated.\n", "FACTS = (\n", " \"The library opens at nine and closes at five. The bus to the harbour leaves every twenty minutes. \"\n", " \"Bread is baked in the village every morning, and the market sells apples, pears and fish. \"\n", ")\n", "LONG_TEXT = STORY + (FACTS + STORY) * 400\n", "LONG_IDS = tok(LONG_TEXT, return_tensors=\"pt\").input_ids[0]\n", "print(\"long text:\", len(LONG_IDS), \"tokens; story alone:\", len(tok(STORY).input_ids), \"tokens\")\n", "\n", "\n", "def prompt_ids(n, batch=1):\n", " \"\"\"The first n tokens of the long text, as a [batch, n] tensor on the device.\"\"\"\n", " return LONG_IDS[:n].unsqueeze(0).repeat(batch, 1).to(DEVICE)\n", "\n", "\n", "@torch.no_grad()\n", "def last_token(hidden):\n", " \"\"\"Scores for the next token from the LAST position only, then the greedy choice.\"\"\"\n", " return model.lm_head(hidden[:, -1]).argmax(-1) # [batch]\n", "\n", "\n", "@torch.no_grad()\n", "def generate_no_cache(ids, n_new):\n", " \"\"\"Loop A. Returns (tokens, ms per step). Step i feeds ALL len(ids) + i tokens.\"\"\"\n", " ids, times = ids.clone(), []\n", " for _ in range(n_new):\n", " sync()\n", " t0 = time.perf_counter()\n", " hidden = model.model(input_ids=ids, use_cache=False).last_hidden_state\n", " nxt = last_token(hidden)\n", " nxt_cpu = nxt.tolist() # reading the answer back also waits for the GPU\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " ids = torch.cat([ids, nxt[:, None]], dim=1)\n", " return ids, times\n", "\n", "\n", "@torch.no_grad()\n", "def generate_cache(ids, n_new):\n", " \"\"\"Loop B. Returns (tokens, ms per step, the cache). Step 0 is the prefill, the rest are decode.\"\"\"\n", " P = ids.shape[1]\n", " out_ids, times = ids.clone(), []\n", " sync()\n", " t0 = time.perf_counter()\n", " out = model.model(input_ids=ids, position_ids=torch.arange(P, device=DEVICE)[None], use_cache=True)\n", " cache = out.past_key_values\n", " nxt = last_token(out.last_hidden_state)\n", " nxt.tolist()\n", " times.append((time.perf_counter() - t0) * 1e3) # time to first token (TTFT)\n", " out_ids = torch.cat([out_ids, nxt[:, None]], dim=1)\n", " for i in range(1, n_new):\n", " sync()\n", " t0 = time.perf_counter()\n", " out = model.model(\n", " input_ids=nxt[:, None], # ONE new token\n", " position_ids=torch.full((ids.shape[0], 1), P + i - 1, device=DEVICE), # its position\n", " past_key_values=cache, # everything before it\n", " use_cache=True,\n", " )\n", " nxt = last_token(out.last_hidden_state)\n", " nxt.tolist()\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " out_ids = torch.cat([out_ids, nxt[:, None]], dim=1)\n", " return out_ids, times, cache\n", "\n", "\n", "# Checkpoint 1: both loops write the same text.\n", "story_ids = tok(STORY, return_tensors=\"pt\").input_ids.to(DEVICE)\n", "N_CHECK = 24\n", "a, _ = generate_no_cache(story_ids, N_CHECK)\n", "b, _, _ = generate_cache(story_ids, N_CHECK)\n", "print(\"identical tokens:\", torch.equal(a, b), f\"({N_CHECK} new tokens)\")\n", "print(\"continuation:\", repr(tok.decode(b[0, story_ids.shape[1]:])))" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The work, counted\n", "\n", "Without a cache, step `i` processes `P + i` positions; with one, the prefill processes `P` and every\n", "decode step processes 1. Count them for 512 new tokens after a 32-token prompt:" ], "id": "lab-6-1-kvcache-08" }, { "cell_type": "code", "metadata": {}, "source": [ "P0, N_NEW = 32, (96 if SMALL else 512)\n", "no_cache_positions = sum(P0 + i for i in range(N_NEW))\n", "cache_positions = P0 + (N_NEW - 1)\n", "print(f\"prompt {P0}, {N_NEW} new tokens\")\n", "print(f\"positions processed, no cache : {no_cache_positions:,}\")\n", "print(f\"positions processed, cache : {cache_positions:,} \"\n", " f\"({no_cache_positions / cache_positions:.0f}x fewer)\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Measure\n", "\n", "### 4a · Time per token against position, with and without the cache\n", "\n", "Three repeats per loop; the table keeps the median per position. One CSV row per position." ], "id": "lab-6-1-kvcache-10" }, { "cell_type": "code", "metadata": {}, "source": [ "REPEATS = 2 if SMALL else 3\n", "ids0 = prompt_ids(P0)\n", "generate_cache(ids0, 8) # warm-up: kernels, allocator\n", "generate_no_cache(ids0, 4)\n", "\n", "runs_nc, runs_c = [], []\n", "for r in range(REPEATS):\n", " _, t = generate_no_cache(ids0, N_NEW)\n", " runs_nc.append(t)\n", " _, t, _ = generate_cache(ids0, N_NEW)\n", " runs_c.append(t)\n", "\n", "rows = []\n", "for i in range(N_NEW):\n", " pos = P0 + i # tokens in the context when this token is produced\n", " rows.append({\"machine\": MACHINE, \"mode\": \"no_cache\", \"step\": i, \"context_tokens\": pos,\n", " \"ms\": round(statistics.median(r[i] for r in runs_nc), 3)})\n", " rows.append({\"machine\": MACHINE, \"mode\": \"cache\", \"step\": i, \"context_tokens\": pos,\n", " \"ms\": round(statistics.median(r[i] for r in runs_c), 3)})\n", "save_csv(\"time-per-token.csv\", rows)\n", "\n", "nc = [r[\"ms\"] for r in rows if r[\"mode\"] == \"no_cache\"]\n", "cc = [r[\"ms\"] for r in rows if r[\"mode\"] == \"cache\"]\n", "print(f\"{'step':>5} {'context':>8} {'no cache ms':>12} {'cache ms':>9}\")\n", "for i in (0, 1, 2, 8, 32, 64, 128, 256, N_NEW - 1):\n", " if i < N_NEW:\n", " print(f\"{i:5d} {P0 + i:8d} {nc[i]:12.2f} {cc[i]:9.2f}\")\n", "print(f\"total time for {N_NEW} tokens: no cache {sum(nc) / 1e3:.2f} s | cache {sum(cc) / 1e3:.2f} s \"\n", " f\"| cache is {sum(nc) / sum(cc):.1f}x faster overall\")\n", "print(f\"decode only (steps 1..): median cache step {statistics.median(cc[1:]):.2f} ms \"\n", " f\"= {1e3 / statistics.median(cc[1:]):.1f} tokens/s\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4b · Time to first token against prompt length\n", "\n", "**TTFT** is the time from \"prompt handed in\" to \"first token available\". It is the prefill step plus\n", "one read-back. Prefill does `2 x parameters` FLOP per prompt token, so beyond some length the\n", "cores, not the weight read, set the time. We compute both limits first:\n", "\n", "```text\n", "weight read = model bytes / bandwidth (a floor, independent of length)\n", "prefill compute = FLOP / measured fp16 matmul speed (grows with length)\n", "FLOP ~ 2 x body parameters x L + 4 x layers x q_heads x head_dim x L^2 / 2 (causal attention)\n", "```\n", "\n", "First, the two machine numbers, measured here the way Lab 4.1 measured them." ], "id": "lab-6-1-kvcache-12" }, { "cell_type": "code", "metadata": {}, "source": [ "def bench(fn, loops=20, repeats=7):\n", " \"\"\"Median ms per call: warm up, run `loops` calls between two syncs, repeat, take the median.\"\"\"\n", " fn()\n", " sync()\n", " res = []\n", " for _ in range(repeats):\n", " sync()\n", " t0 = time.perf_counter()\n", " for _ in range(loops):\n", " fn()\n", " sync()\n", " res.append((time.perf_counter() - t0) * 1e3 / loops)\n", " return statistics.median(res)\n", "\n", "\n", "if ON_GPU:\n", " x = torch.empty(2**27, device=\"cuda\", dtype=torch.float32) # 512 MiB\n", " y = torch.empty_like(x)\n", " ms = bench(lambda: torch.add(x, 1.0, out=y), loops=10)\n", " BW = 2 * x.numel() * 4 / (ms / 1e3) # read x, write y\n", " del x, y\n", " A = torch.randn(8192, 8192, device=\"cuda\", dtype=torch.float16)\n", " ms = bench(lambda: A @ A, loops=5)\n", " PEAK16 = 2 * 8192**3 / (ms / 1e3) # FLOP/s\n", " del A\n", " torch.cuda.empty_cache()\n", "else:\n", " BW, PEAK16 = float(\"nan\"), float(\"nan\")\n", "BW_REF = 336.2e9 # Ch 4.1: best add on the RTX 3060\n", "print(f\"bandwidth measured here: {BW / 1e9:.1f} GB/s (Ch 4.1 on the RTX 3060: {BW_REF / 1e9:.1f})\")\n", "print(f\"fp16 matmul measured here: {PEAK16 / 1e12:.2f} TFLOP/s\")\n", "# The ceiling uses the book's 336.2 GB/s on the RTX 3060 (Ch 4.1, a 3 GiB add), your own measurement elsewhere;\n", "# on CPU it shows the RTX 3060 numbers, labelled.\n", "CEIL_BW = BW_REF if (not ON_GPU or \"3060\" in torch.cuda.get_device_name(0)) else BW\n", "print(f\"weight read floor: {MODEL_BYTES / CEIL_BW * 1e3:.2f} ms -> ceiling \"\n", " f\"{CEIL_BW / MODEL_BYTES:.1f} tokens/s at {CEIL_BW / 1e9:.1f} GB/s\")\n", "\n", "\n", "def prefill_flop(L):\n", " return 2 * BODY_PARAMS * L + 4 * LAYERS * Q_HEADS * HEAD_DIM * L * L / 2\n", "\n", "\n", "@torch.no_grad()\n", "def ttft_ms(L, repeats):\n", " ids = prompt_ids(L)\n", " pos = torch.arange(L, device=DEVICE)[None]\n", "\n", " def once():\n", " sync()\n", " t0 = time.perf_counter()\n", " out = model.model(input_ids=ids, position_ids=pos, use_cache=True)\n", " last_token(out.last_hidden_state).tolist()\n", " return (time.perf_counter() - t0) * 1e3\n", "\n", " once()\n", " return statistics.median(once() for _ in range(repeats))\n", "\n", "\n", "LENGTHS = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]\n", "if SMALL:\n", " LENGTHS = [1, 4, 16, 64, 256, 1024]\n", "rows = []\n", "for L in LENGTHS:\n", " ms = ttft_ms(L, repeats=7 if L <= 1024 else 3)\n", " rows.append({\n", " \"machine\": MACHINE, \"prompt_tokens\": L, \"ttft_ms\": round(ms, 3),\n", " \"prefill_tokens_per_s\": round(L / (ms / 1e3), 1),\n", " \"flop\": int(prefill_flop(L)),\n", " \"compute_ms_at_measured_peak\": round(prefill_flop(L) / PEAK16 * 1e3, 3) if ON_GPU else \"\",\n", " \"weight_read_ms\": round(MODEL_BYTES / CEIL_BW * 1e3, 3),\n", " })\n", " r = rows[-1]\n", " print(f\"L = {L:6d} TTFT {r['ttft_ms']:9.2f} ms prefill {r['prefill_tokens_per_s']:9.1f} tok/s \"\n", " f\"compute floor {r['compute_ms_at_measured_peak']} weight-read floor {r['weight_read_ms']}\")\n", "save_csv(\"ttft.csv\", rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4c · Decode speed against the bandwidth ceiling\n", "\n", "Decode reads every weight once per token, plus the whole cache so far:\n", "\n", "```text\n", "ceiling(T) = ( model bytes + KV bytes at T tokens ) / bandwidth (ms per token)\n", "```\n", "\n", "We prefill a context of `T` tokens, then time 32 decode steps and take the median. Two versions of the\n", "same step: **eager**, the loop of section 3, where Python launches every kernel one by one; and a\n", "**CUDA graph**, where the whole step is recorded once and replayed with a single launch. The graph\n", "needs a cache whose tensors never move (`StaticCache`), sized here for `T` + 40 tokens." ], "id": "lab-6-1-kvcache-14" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def decode_ms(T, steps=32, batch=1):\n", " \"\"\"Median wall ms of one eager decode step at context length T (after a prefill of T tokens).\"\"\"\n", " ids = prompt_ids(T, batch)\n", " out = model.model(input_ids=ids, use_cache=True)\n", " cache = out.past_key_values\n", " nxt = last_token(out.last_hidden_state)\n", " del out\n", " times = []\n", " for i in range(steps):\n", " sync()\n", " t0 = time.perf_counter()\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((batch, 1), T + i, device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " nxt = last_token(o.last_hidden_state)\n", " nxt.tolist()\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " del cache, o\n", " return statistics.median(times[2:]) # drop two warm-up steps\n", "\n", "\n", "@torch.no_grad()\n", "def graph_decode(T, steps=32):\n", " \"\"\"Median wall ms of one decode step replayed from a CUDA graph, and the tokens it wrote.\n", " Greedy decoding from the same prompt as `decode_ms`, so the tokens can be compared.\"\"\"\n", " from transformers import StaticCache\n", " ids = prompt_ids(T)\n", " cache = StaticCache(config=cfg, max_cache_len=T + steps + 8)\n", " out = model.model(input_ids=ids, position_ids=torch.arange(T, device=DEVICE)[None],\n", " past_key_values=cache, use_cache=True)\n", " first = last_token(out.last_hidden_state)\n", " tok_s = first[:, None].clone() # static input: the graph always reads these addresses\n", " pos_s = torch.full((1, 1), T, device=DEVICE)\n", "\n", " def step():\n", " o = model.model(input_ids=tok_s, position_ids=pos_s, past_key_values=cache, use_cache=True)\n", " return last_token(o.last_hidden_state)\n", "\n", " side = torch.cuda.Stream()\n", " side.wait_stream(torch.cuda.current_stream())\n", " with torch.cuda.stream(side): # warm-up (allocations, kernel selection) off the graph\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): # record one step\n", " out_s = step()\n", " for layer in cache.layers: # the warm-up steps advanced the cache; rewind to T\n", " layer.cumulative_length.fill_(T)\n", " toks, times = [first.item()], []\n", " for i in range(steps):\n", " pos_s.fill_(T + i)\n", " sync()\n", " t0 = time.perf_counter()\n", " graph.replay()\n", " tok_s.copy_(out_s[:, None])\n", " toks.append(out_s.item())\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " return statistics.median(times[2:]), toks\n", "\n", "\n", "@torch.no_grad()\n", "def eager_tokens(T, steps=32):\n", " out = model.model(input_ids=prompt_ids(T), use_cache=True)\n", " cache, nxt = out.past_key_values, last_token(out.last_hidden_state)\n", " toks = [nxt.item()]\n", " for i in range(steps):\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((1, 1), T + i, device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " nxt = last_token(o.last_hidden_state)\n", " toks.append(nxt.item())\n", " return toks" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-15" }, { "cell_type": "code", "metadata": {}, "source": [ "def cuda_kernels(T, static=False, k_top=6):\n", " \"\"\"Profile one eager decode step at context T with the growing cache (or, with static=True, the\n", " pre-allocated one). Returns (kernel count, GPU busy ms, CPU issue ms, top kernels as (name, ms, launches)).\"\"\"\n", " from torch.profiler import ProfilerActivity, profile\n", " if static:\n", " from transformers import StaticCache\n", " cache = StaticCache(config=cfg, max_cache_len=T + 40)\n", " out = model.model(input_ids=prompt_ids(T), position_ids=torch.arange(T, device=DEVICE)[None],\n", " past_key_values=cache, use_cache=True)\n", " else:\n", " out = model.model(input_ids=prompt_ids(T), use_cache=True)\n", " cache = out.past_key_values\n", " nxt = last_token(out.last_hidden_state)\n", " del out\n", " pos = [T]\n", "\n", " @torch.no_grad()\n", " def step():\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((1, 1), pos[0], device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " pos[0] += 1\n", " return last_token(o.last_hidden_state)\n", "\n", " step(); step(); sync()\n", " t0 = time.perf_counter()\n", " step()\n", " issue_ms = (time.perf_counter() - t0) * 1e3 # Python returns once everything is queued\n", " sync()\n", " with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:\n", " step()\n", " sync()\n", " by_name, total_us, n = {}, 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", " d = by_name.setdefault(e.name, [0.0, 0])\n", " d[0] += us\n", " d[1] += 1\n", " total_us += us\n", " n += 1\n", " top = sorted(((name, v[0] / 1e3, v[1]) for name, v in by_name.items()), key=lambda x: -x[1])[:k_top]\n", " return n, total_us / 1e3, issue_ms, top\n", "\n", "\n", "def free_memory():\n", " gc.collect()\n", " if ON_GPU:\n", " torch.cuda.empty_cache()" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-16" }, { "cell_type": "code", "metadata": {}, "source": [ "CONTEXTS = [16, 128, 512, 1024, 2048, 4096, 8192, 16384]\n", "if SMALL:\n", " CONTEXTS = [16, 128, 512, 1024]\n", "ceil_of = lambda T: (MODEL_BYTES + kv_bytes(T)) / CEIL_BW * 1e3\n", "print(f\"ceiling = ({MODEL_BYTES:,} bytes + cache) / {CEIL_BW / 1e9:.1f} GB/s\")\n", "\n", "# Pass 1: eager wall time. Done first on purpose: after the profiler has run once, every later call\n", "# in the process is slower (the profiler's hooks stay installed), which would inflate these numbers.\n", "decode_ms(16, steps=6) # warm-up\n", "eager = {T: decode_ms(T) for T in CONTEXTS}\n", "for T in CONTEXTS:\n", " print(f\"context {T:6d} | eager {eager[T]:6.2f} ms/token = {1e3 / eager[T]:5.1f} tok/s | \"\n", " f\"ceiling {ceil_of(T):.2f} ms = {1e3 / ceil_of(T):.1f} tok/s | eager is {100 * ceil_of(T) / eager[T]:.1f} % of it\")\n", "\n", "# Pass 2: the same step replayed from a CUDA graph.\n", "graph = {}\n", "if ON_GPU:\n", " for T in CONTEXTS:\n", " try:\n", " g_ms, g_toks = graph_decode(T)\n", " graph[T] = (g_ms, g_toks == eager_tokens(T))\n", " except Exception as e: # an older transformers without the StaticCache layout used here\n", " print(\"graph decode skipped:\", type(e).__name__, str(e)[:120])\n", " free_memory()\n", " if T in graph:\n", " print(f\"context {T:6d} | graph {graph[T][0]:6.2f} ms/token = {1e3 / graph[T][0]:5.1f} tok/s \"\n", " f\"(same tokens as eager: {graph[T][1]}) | {100 * ceil_of(T) / graph[T][0]:.1f} % of the ceiling\")\n", "\n", "# Pass 3: what the GPU was busy with (profiler), per context.\n", "busy, k_rows = {}, []\n", "if ON_GPU:\n", " for T in CONTEXTS:\n", " busy[T] = cuda_kernels(T)\n", " free_memory()\n", " for name, kms, cnt in busy[T][3]:\n", " k_rows.append({\"machine\": MACHINE, \"cache\": \"growing\", \"context_tokens\": T, \"kernel\": name[:150],\n", " \"total_ms\": round(kms, 3), \"launches\": cnt})\n", " print(f\"context {T:6d} | {busy[T][0]} kernels | GPU busy {busy[T][1]:6.2f} ms | Python issue {busy[T][2]:6.2f} ms\")\n", " n_s, busy_s, issue_s, top_s = cuda_kernels(CONTEXTS[-1], static=True)\n", " for name, kms, cnt in top_s:\n", " k_rows.append({\"machine\": MACHINE, \"cache\": \"static\", \"context_tokens\": CONTEXTS[-1], \"kernel\": name[:150],\n", " \"total_ms\": round(kms, 3), \"launches\": cnt})\n", " print(f\"static cache at {CONTEXTS[-1]}: {n_s} kernels | GPU busy {busy_s:.2f} ms\")\n", " free_memory()\n", "\n", "rows = []\n", "for T in CONTEXTS:\n", " g = graph.get(T)\n", " rows.append({\n", " \"machine\": MACHINE, \"context_tokens\": T, \"kv_bytes\": kv_bytes(T),\n", " \"eager_ms\": round(eager[T], 3), \"eager_tokens_per_s\": round(1e3 / eager[T], 2),\n", " \"gpu_busy_ms\": round(busy[T][1], 3) if T in busy else \"\",\n", " \"cpu_issue_ms\": round(busy[T][2], 3) if T in busy else \"\",\n", " \"kernels_per_step\": busy[T][0] if T in busy else \"\",\n", " \"graph_ms\": round(g[0], 3) if g else \"\",\n", " \"graph_tokens_per_s\": round(1e3 / g[0], 2) if g else \"\",\n", " \"graph_tokens_match_eager\": g[1] if g else \"\",\n", " \"ceiling_ms\": round(ceil_of(T), 3), \"ceiling_tokens_per_s\": round(1e3 / ceil_of(T), 2),\n", " \"eager_pct_of_ceiling\": round(100 * ceil_of(T) / eager[T], 1),\n", " \"graph_pct_of_ceiling\": round(100 * ceil_of(T) / g[0], 1) if g else \"\",\n", " })\n", "save_csv(\"decode-vs-context.csv\", rows)\n", "if k_rows:\n", " save_csv(\"decode-kernels.csv\", k_rows)\n", " for cache_kind, T in ((\"growing\", CONTEXTS[0]), (\"growing\", CONTEXTS[-1]), (\"static\", CONTEXTS[-1])):\n", " print(f\"top GPU kernels, {cache_kind} cache, context {T}:\")\n", " for r in [r for r in k_rows if r[\"context_tokens\"] == T and r[\"cache\"] == cache_kind]:\n", " print(f\" {r['total_ms']:7.3f} ms x{r['launches']:<4d} {r['kernel'][:100]}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read the columns against each other. The eager wall time per token barely moves with the context and sits\n", "well above what the GPU was busy for: Python needs longer to *issue* about a thousand kernels than the\n", "GPU needs to run them, so the GPU waits for Python. The graph removes the issue cost, and what is left is\n", "the GPU's own time. Which kernels grow with the context, and what do they do? (The two loops use different\n", "caches, a growing one and a pre-allocated one, and different attention kernels; compare numbers within\n", "a column first.)" ], "id": "lab-6-1-kvcache-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4d · The cache's bytes, measured against the formula\n", "\n", "`torch.cuda.memory_allocated()` counts the bytes of every live tensor. Prefill a prompt, throw away\n", "everything except the cache, and the difference from before is the cache. (On CPU there is no such\n", "counter; the cell then adds up the tensors of the cache directly.)" ], "id": "lab-6-1-kvcache-19" }, { "cell_type": "code", "metadata": {}, "source": [ "def cache_tensors_bytes(cache):\n", " return sum(t.numel() * t.element_size() for layer in cache.layers for t in (layer.keys, layer.values))\n", "\n", "\n", "@torch.no_grad()\n", "def measured_cache_bytes(tokens, batch):\n", " gc.collect()\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", " sync()\n", " before = torch.cuda.memory_allocated()\n", " out = model.model(input_ids=prompt_ids(tokens, batch), use_cache=True)\n", " cache = out.past_key_values\n", " del out\n", " if ON_GPU:\n", " sync()\n", " delta = torch.cuda.memory_allocated() - before\n", " else:\n", " delta = cache_tensors_bytes(cache)\n", " direct = cache_tensors_bytes(cache)\n", " del cache\n", " return delta, direct\n", "\n", "\n", "rows = []\n", "CASES = [(1, 1), (1, 16), (1, 128), (1, 1024), (1, 4096), (4, 1024), (8, 1024), (1, 8192)]\n", "if SMALL:\n", " CASES = [(1, 1), (1, 16), (1, 128), (4, 128), (1, 1024)]\n", "print(f\"{'batch':>5} {'tokens':>7} {'measured B':>14} {'formula B':>14} {'ratio':>7} {'MHA formula B':>15}\")\n", "for batch, T in CASES:\n", " delta, direct = measured_cache_bytes(T, batch)\n", " f = kv_bytes(T, batch)\n", " rows.append({\"machine\": MACHINE, \"batch\": batch, \"tokens\": T, \"measured_bytes\": delta,\n", " \"tensor_bytes\": direct, \"formula_bytes\": f, \"ratio\": round(delta / f, 5),\n", " \"if_every_head_had_kv_bytes\": kv_bytes(T, batch, kv_heads=Q_HEADS)})\n", " print(f\"{batch:5d} {T:7d} {delta:14,} {f:14,} {delta / f:7.4f} {rows[-1]['if_every_head_had_kv_bytes']:15,}\")\n", "save_csv(\"kv-bytes.csv\", rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-20" }, { "cell_type": "code", "metadata": {}, "source": [ "# Growth, one decode step at a time: each step should add exactly one token's worth of bytes.\n", "@torch.no_grad()\n", "def growth_per_step(T=256, steps=6):\n", " out = model.model(input_ids=prompt_ids(T), use_cache=True)\n", " cache, nxt = out.past_key_values, last_token(out.last_hidden_state)\n", " del out\n", " gc.collect()\n", " sync()\n", " prev = torch.cuda.memory_allocated() if ON_GPU else cache_tensors_bytes(cache)\n", " deltas = []\n", " for i in range(steps):\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((1, 1), T + i, device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " nxt = last_token(o.last_hidden_state)\n", " del o\n", " sync()\n", " now = torch.cuda.memory_allocated() if ON_GPU else cache_tensors_bytes(cache)\n", " deltas.append(now - prev)\n", " prev = now\n", " return deltas\n", "\n", "\n", "print(\"bytes added per decode step:\", growth_per_step(), \"| formula for one token:\", per_token)" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Your run should show (numbers differ by GPU; the *shapes* must match):\n", "\n", "- the no-cache and cache loops write **identical** tokens;\n", "- **without a cache the time per token grows with the position**; with a cache it stays nearly flat and\n", " far lower, and the whole 512-token run is many times faster;\n", "- **TTFT grows with the prompt**: nearly flat for short prompts (the weight read), then in proportion\n", " to the length (compute), and a 4,096-token prompt's first token takes many times a later token;\n", "- **decode tokens/s is a fraction of the ceiling** `bandwidth / model bytes`: the eager loop is nowhere\n", " near it and flat in the context, the CUDA-graph step is much closer and grows with the context, and the\n", " kernel and timing counts say where the difference goes (Python issuing ~1,000 kernels per token);\n", "- **measured cache bytes equal the formula** to within allocator rounding, and `2 x layers x kv_heads x\n", " head_dim x bytes` per token for this model is the number from section 2." ], "id": "lab-6-1-kvcache-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| `P0`, `N_NEW` | prompt 32 vs 512, 128 vs 1024 new tokens | At which length does the no-cache step cost twice the cache step? Does the ratio of total times keep growing? |\n", "| `DTYPE` | `torch.float32` (needs the 0.5 B model on a 12 GB card) | What happens to model bytes, the ceiling and the measured tokens/s? Do all three move by the same factor? |\n", "| batch in `decode_ms(T, batch=...)` | 1, 2, 4, 8, 16 | The weights are read once per step whatever the batch. What happens to ms per step and to tokens per second? What grows? (Ch 6.2) |\n", "| `kv_bytes(..., kv_heads=...)` | `KV_HEADS` vs `Q_HEADS` | How many times bigger would the cache be if every query head had its own key/value pair? At which context does that matter on a 12 GB card? |\n", "| `LENGTHS` | add 24,000 and 32,000 | Where does the TTFT curve stop being a straight line, and why? (attention's `L^2` term) |\n", "| the prompt text | one token repeated 512 times vs the story | Does TTFT or decode time depend on *what* the tokens are? Why not? |" ], "id": "lab-6-1-kvcache-23" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"your predictions:\", PREDICT)\n", "cc_ms = statistics.median(cc[1:])\n", "print(\"measured:\")\n", "print(f\" ceiling tokens/s {CEIL_BW / MODEL_BYTES:.1f}\")\n", "print(f\" positions processed, no cache / cache {no_cache_positions:,} / {cache_positions:,}\")\n", "print(f\" KV bytes per token {per_token:,}\")\n", "print(f\" decode step at context {P0} + n {cc_ms:.2f} ms\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Each cell is a decode loop with one bug. It runs, it prints, it does not crash. For each one: write\n", "down what you see, what you suspect, which print statement would test the suspicion, and the fix.\n", "Do not look at the loop of section 3 until you have a hypothesis." ], "id": "lab-6-1-kvcache-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · \"The model keeps saying the same thing\"\n", "\n", "Symptom below. Questions: How many different tokens does the output contain? What does the model\n", "*see* at each step? Print the cache length before and after each step." ], "id": "lab-6-1-kvcache-26" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def decode_a(ids, n_new):\n", " P = ids.shape[1]\n", " out = model.model(input_ids=ids, position_ids=torch.arange(P, device=DEVICE)[None], use_cache=True)\n", " cache = out.past_key_values\n", " nxt = last_token(out.last_hidden_state)\n", " toks = [nxt.item()]\n", " for i in range(1, n_new):\n", " step_cache = copy.deepcopy(cache) # a helper \"to be safe\"\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((1, 1), P + i - 1, device=DEVICE),\n", " past_key_values=step_cache, use_cache=True)\n", " nxt = last_token(o.last_hidden_state)\n", " toks.append(nxt.item())\n", " return toks\n", "\n", "\n", "good, _, _ = generate_cache(story_ids, 40)\n", "good_toks = good[0, story_ids.shape[1]:].tolist()\n", "bad_toks = decode_a(story_ids, 40)\n", "print(\"correct :\", repr(tok.decode(good_toks)))\n", "print(\"buggy :\", repr(tok.decode(bad_toks)))\n", "print(\"distinct tokens: correct\", len(set(good_toks)), \"| buggy\", len(set(bad_toks)))" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · \"Same prompt, same weights, different text\"\n", "\n", "Symptom below. Nothing crashes and the loop is as fast as before. Questions: how long does the\n", "buggy output agree with the correct one? Compare token by token. Which number in the call encodes\n", "\"where am I in the sequence\", and what did the cached keys assume it was?" ], "id": "lab-6-1-kvcache-28" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def decode_b(ids, n_new):\n", " P = ids.shape[1]\n", " out = model.model(input_ids=ids, position_ids=torch.arange(P, device=DEVICE)[None], use_cache=True)\n", " cache = out.past_key_values\n", " nxt = last_token(out.last_hidden_state)\n", " toks = [nxt.item()]\n", " for i in range(1, n_new):\n", " o = model.model(input_ids=nxt[:, None], position_ids=torch.full((1, 1), i - 1, device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " nxt = last_token(o.last_hidden_state)\n", " toks.append(nxt.item())\n", " return toks\n", "\n", "\n", "N_B = 60\n", "good, _, _ = generate_cache(story_ids, N_B)\n", "good_toks = good[0, story_ids.shape[1]:].tolist()\n", "bad_toks = decode_b(story_ids, N_B)\n", "first_diff = next((i for i, (x, y) in enumerate(zip(good_toks, bad_toks)) if x != y), None)\n", "same = sum(x == y for x, y in zip(good_toks, bad_toks))\n", "print(\"correct :\", repr(tok.decode(good_toks)))\n", "print(\"buggy :\", repr(tok.decode(bad_toks)))\n", "print(f\"first difference at new token {first_diff}; tokens equal at the same index: {same} of {N_B}\")\n", "save_csv(\"position-bug.csv\", [{\n", " \"machine\": MACHINE, \"model\": MODEL_ID, \"new_tokens\": N_B, \"first_difference_at\": first_diff,\n", " \"equal_tokens\": same, \"prompt_tokens\": story_ids.shape[1],\n", "}])" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · \"It fits, so why does it crash?\"\n", "\n", "**Work out where it breaks before you run anything.** Free memory after the weights are loaded is\n", "printed below. (1) How many tokens of KV cache fit, per sequence and for a batch of sequences of\n", "4,096 tokens? (2) Prefill scoring *every* position (the lazy `model(ids)`) builds a\n", "`[tokens, vocab]` table of fp16 scores: at what prompt length does that table alone fill the free\n", "memory? Write both predictions down. Then run the cells and compare." ], "id": "lab-6-1-kvcache-30" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " free, total = torch.cuda.mem_get_info()\n", " print(f\"total {total / 2**30:.2f} GiB | free after loading the weights {free / 2**30:.2f} GiB ({free:,} bytes)\")\n", " print(f\"KV cache bytes per token: {per_token:,}\")\n", "else:\n", " print(\"no GPU: the memory arithmetic below needs one; read the cells and answer the questions\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-31" }, { "cell_type": "code", "metadata": {}, "source": [ "def try_alloc_kv(batch, tokens):\n", " \"\"\"Allocate the cache's tensors (empty) for `batch` sequences of `tokens` tokens; True if it fits.\"\"\"\n", " try:\n", " bufs = [torch.empty(batch, KV_HEADS, tokens, HEAD_DIM, device=DEVICE, dtype=DTYPE) for _ in range(2 * LAYERS)]\n", " del bufs\n", " return True\n", " except torch.cuda.OutOfMemoryError:\n", " return False\n", " finally:\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", "\n", "\n", "if ON_GPU:\n", " free, _ = torch.cuda.mem_get_info()\n", " T = 4096\n", " predicted = free / kv_bytes(T)\n", " rows = []\n", " print(f\"predicted maximum batch at {T} tokens (cache only): {predicted:.1f}\")\n", " for frac in (0.90, 0.97, 1.03, 1.10):\n", " b = max(1, int(predicted * frac))\n", " ok = try_alloc_kv(b, T)\n", " rows.append({\"kind\": \"kv_cache_batch\", \"tokens_per_sequence\": T, \"batch\": b, \"tokens_total\": b * T,\n", " \"kv_bytes\": kv_bytes(T, b), \"free_bytes\": free, \"fits\": ok})\n", " print(f\"batch {b:4d} x {T} tokens = {kv_bytes(T, b) / 2**30:6.2f} GiB of cache -> \"\n", " f\"{'fits' if ok else 'OutOfMemoryError'}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-32" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " free, _ = torch.cuda.mem_get_info()\n", " logits_per_token = VOCAB * ITEM\n", " print(f\"scoring every position: {logits_per_token:,} bytes per token -> table fills free memory at \"\n", " f\"~{free / logits_per_token:,.0f} tokens\")\n", " for L in (8192, 16384, 32768):\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " need = L * logits_per_token\n", " try:\n", " with torch.no_grad():\n", " out = model(input_ids=prompt_ids(L), use_cache=False)\n", " res = \"fits\"\n", " del out\n", " except torch.cuda.OutOfMemoryError as e:\n", " res = \"OutOfMemoryError\"\n", " rows.append({\"kind\": \"all_position_logits\", \"tokens_per_sequence\": L, \"batch\": 1, \"tokens_total\": L,\n", " \"kv_bytes\": need, \"free_bytes\": free, \"fits\": res == \"fits\"})\n", " print(f\"prompt {L:6d}: logits table {need / 2**30:6.2f} GiB -> {res}\")\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " save_csv(\"oom.csv\", rows)\n", "else:\n", " print(\"no GPU: skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-6-1-kvcache-33" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: which was closer to your prediction, the cache or the score table? What limits a *single\n", "user's* context on this model: the cache, or something else? Which one limits a server with 64 users?\n", "Fix the second crash by changing one argument of the call (hint: look for `logits_to_keep`)." ], "id": "lab-6-1-kvcache-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Versions tested" ], "id": "lab-6-1-kvcache-35" }, { "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", "print(\"model\", MODEL_ID, \"revision\", REVISION, \"| dtype\", str(DTYPE).replace(\"torch.\", \"\"))\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-1-kvcache-36" } ] }