{ "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.2 · Batching, Scheduling and PagedAttention\n", "\n", "**Goal:** measure what batching does to one GPU (decode steps by hand at batch 1 to 64), see why\n", "serving engines batch at the level of single steps (static against continuous batching), build a\n", "paged KV cache by hand (blocks, a page table, sharing), then serve the same model with vLLM and\n", "measure throughput and per-request latency against the number of concurrent users; finally break\n", "the server three ways (memory setting too high, context too long for the cache, one long prompt\n", "stalling short ones) and measure prefix caching.\n", "\n", "**Runs on:** an NVIDIA GPU with at least 12 GB for the numbers in the book (an RTX 3060 12 GB); a\n", "free 16 GB Kaggle or Colab T4 should also run it (the memory settings are fractions of the card)\n", "but this book did not run a T4. The hand-written parts need only `torch` and `transformers`; the\n", "vLLM parts start a local server on `127.0.0.1` from inside the notebook and stop it again.\n", "Install: `uv venv && uv pip install vllm nbconvert ipykernel` (vLLM brings a matching PyTorch; the\n", "first run downloads about 3 GB of weights from Hugging Face, no login needed). Without a GPU only\n", "the paging build (section 5) runs.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-6-2-batching-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import asyncio\n", "import atexit\n", "import collections\n", "import concurrent.futures\n", "import csv\n", "import gc\n", "import importlib.metadata\n", "import json\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import random\n", "import re\n", "import shutil\n", "import signal\n", "import statistics\n", "import subprocess\n", "import sys\n", "import time\n", "import warnings\n", "\n", "import torch\n", "\n", "warnings.filterwarnings(\"ignore\")\n", "torch.set_grad_enabled(False)\n", "\n", "ON_GPU = torch.cuda.is_available()\n", "DEVICE = \"cuda\" if ON_GPU else \"cpu\"\n", "try:\n", " VLLM_VERSION = importlib.metadata.version(\"vllm\")\n", "except importlib.metadata.PackageNotFoundError:\n", " VLLM_VERSION = None\n", "HAVE_VLLM = ON_GPU and VLLM_VERSION is not None\n", "print(\"PyTorch\", torch.__version__, \"| device:\", DEVICE, \"| vLLM:\", VLLM_VERSION)\n", "\n", "# The serving model of Vols 6-7 (data/models.json): Qwen2.5-1.5B-Instruct, Apache-2.0, ungated, at a\n", "# pinned revision so everybody loads the same weights.\n", "MODEL_ID = \"Qwen/Qwen2.5-1.5B-Instruct\"\n", "REVISION = \"989aa7980e4cf806f80c7fef2b1adb7bc71aa306\"\n", "DTYPE = torch.float16\n", "SERVED, PORT = \"qwen\", 8011\n", "BASE = f\"http://127.0.0.1:{PORT}\" # servers in this lab bind to the loopback address only\n", "MACHINE = torch.cuda.get_device_name(0) if ON_GPU else f\"{platform.system()} {platform.machine()} (cpu)\"\n", "WORK = pathlib.Path(os.environ.get(\"LAB_WORK\", \".work/lab-6-2\"))\n", "WORK.mkdir(parents=True, exist_ok=True)\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-2-batching\"\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", "def pct(xs, q):\n", " xs = sorted(xs)\n", " return xs[min(len(xs) - 1, int(round(q * (len(xs) - 1))))]" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write your answers down before you run anything below. Lab 6.1 measured a decode step of this model\n", "on this GPU: 9.18 ms is the time to read the weights once (3,087,428,608 bytes at 336.2 GB/s), and a\n", "CUDA-graph step took 11.68 ms.\n", "\n", "1. **Batching.** A decode step for `B` users reads the weights once, whatever `B` is. Each user adds\n", " `2 x parameters` FLOP of arithmetic and a read of its own cache. At what batch size does the\n", " step stop being limited by the weight read and become limited by the cores? What tokens per\n", " second does that model predict at `B` = 1, 8 and 64?\n", "2. **Latency.** If 64 users are served at once, does each of them wait about 64 times as long per\n", " token as a single user, about the same, or in between?\n", "3. **Static batching.** Eight requests start together and the batch ends when the longest one ends.\n", " Their output lengths are 16, 32, 64, 128, 256 and 512 tokens in some mix. What share of the\n", " batch's slot-steps produce a token somebody wants?\n", "4. **Cache budget.** A server may use 80 % of the 12 GB card. After the weights and some working\n", " memory, how many tokens of KV cache does it hold? (28,672 bytes per token.)\n", "5. **Stall.** An 8,192-token prompt arrives while other users are decoding. Lab 6.1 measured 1.26 s\n", " to prefill that much. If the server does the whole prompt in one step, how long is every other\n", " user's stream frozen?" ], "id": "lab-6-2-batching-02" }, { "cell_type": "code", "metadata": {}, "source": [ "PREDICT = {\n", " \"batch_where_cores_limit\": None,\n", " \"tokens_per_s_B1_B8_B64\": None,\n", " \"per_token_wait_at_64_users_vs_1\": None,\n", " \"static_batch_useful_share\": None,\n", " \"kv_cache_tokens_at_80pct\": None,\n", " \"stall_ms_for_8192_prompt\": None,\n", "}\n", "print(PREDICT)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Load the model, and the two machine numbers\n", "\n", "Same model, same pinned revision, same float16 as Lab 6.1. The ceiling uses the bandwidth Ch 4.1\n", "measured on this card (336.2 GB/s); the speed of the cores is measured here by one large\n", "float16 matrix multiply, the way Lab 6.1 did." ], "id": "lab-6-2-batching-04" }, { "cell_type": "code", "metadata": {}, "source": [ "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "tok = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)\n", "if ON_GPU:\n", " try:\n", " model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=DTYPE).to(DEVICE).eval()\n", " except TypeError: # older transformers\n", " model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, torch_dtype=DTYPE).to(DEVICE).eval()\n", " cfg = model.config\n", " PARAMS = sum(p.numel() for p in model.parameters())\n", " MODEL_BYTES = sum(p.numel() * p.element_size() for p in model.parameters())\n", "else:\n", " from transformers import AutoConfig\n", " cfg = AutoConfig.from_pretrained(MODEL_ID, revision=REVISION)\n", " PARAMS, MODEL_BYTES = 1_543_714_304, 3_087_428_608 # data/models.json, so the arithmetic below still prints\n", "\n", "LAYERS, Q_HEADS, KV_HEADS = cfg.num_hidden_layers, cfg.num_attention_heads, cfg.num_key_value_heads\n", "HEAD_DIM = getattr(cfg, \"head_dim\", None) or cfg.hidden_size // Q_HEADS\n", "KV_PER_TOKEN = 2 * LAYERS * KV_HEADS * HEAD_DIM * 2 # key + value, float16\n", "print(f\"parameters {PARAMS:,} | weights {MODEL_BYTES:,} bytes | KV cache {KV_PER_TOKEN:,} bytes per token\")\n", "\n", "\n", "def bench(fn, loops=5, repeats=7):\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", "BW_REF = 336.2e9 # Ch 4.1: best add on the RTX 3060\n", "if ON_GPU:\n", " A = torch.randn(8192, 8192, device=\"cuda\", dtype=torch.float16)\n", " PEAK16 = 2 * 8192**3 / (bench(lambda: A @ A) / 1e3)\n", " del A\n", " torch.cuda.empty_cache()\n", "else:\n", " PEAK16 = 26.57e12 # Lab 6.1, RTX 3060\n", "print(f\"fp16 matmul speed: {PEAK16 / 1e12:.2f} TFLOP/s | weight read: {MODEL_BYTES / BW_REF * 1e3:.2f} ms \"\n", " f\"at {BW_REF / 1e9:.1f} GB/s\")\n", "\n", "\n", "def roofline_step(B, ctx):\n", " \"\"\"One decode step for B users each holding ctx tokens of cache: (step ms, memory ms, compute ms).\n", " Memory: the weights once plus every user's cache. Compute: 2 FLOP per parameter per user (the output\n", " matrix is multiplied for every token in decode). Attention's own arithmetic is ignored (small).\"\"\"\n", " mem = (MODEL_BYTES + B * ctx * KV_PER_TOKEN) / BW_REF * 1e3\n", " comp = B * 2 * PARAMS / PEAK16 * 1e3\n", " return max(mem, comp), mem, comp\n", "\n", "\n", "ridge_B = (MODEL_BYTES / BW_REF * 1e3) / (2 * PARAMS / PEAK16 * 1e3)\n", "print(f\"the weight read equals the arithmetic at about B = {ridge_B:.0f} users (cache read ignored)\")\n", "print(f\"{'B':>3} {'step ms':>8} {'memory ms':>10} {'compute ms':>11} {'tokens/s':>9} limited by\")\n", "for B in (1, 2, 4, 8, 16, 32, 64, 128):\n", " s, m, c = roofline_step(B, 384)\n", " print(f\"{B:3d} {s:8.2f} {m:10.2f} {c:11.2f} {B / s * 1e3:9.0f} {'memory' if m >= c else 'compute'}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build: batched decode by hand\n", "\n", "The loop of Lab 6.1, with a batch dimension. All `B` prompts have the same length, so there is no\n", "padding and no attention mask: the cache is `[B, kv_heads, tokens, head_dim]` per layer and one\n", "step feeds `B` new tokens, one per user. We measure the time of one decode step as `B` grows." ], "id": "lab-6-2-batching-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", "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).input_ids\n", "print(\"long text:\", len(LONG_IDS), \"tokens\")\n", "\n", "\n", "def make_prompt(i, n):\n", " \"\"\"A list of n token ids, different for every i: two ids that depend on i, then a window of the long\n", " text. Distinct first tokens mean the prefix cache cannot reuse one request's work for another.\"\"\"\n", " lead = [1000 + (i * 7919) % 100000, 1000 + (i * 104729) % 100000]\n", " off = (i * 211 + 13) % (len(LONG_IDS) - n)\n", " return lead + LONG_IDS[off: off + n - 2]\n", "\n", "\n", "def prompt_batch(B, n):\n", " return torch.tensor([make_prompt(i, n) for i in range(B)], device=DEVICE) # [B, n]\n", "\n", "\n", "@torch.no_grad()\n", "def last_token(hidden):\n", " return model.lm_head(hidden[:, -1]).argmax(-1) # [B]\n", "\n", "\n", "@torch.no_grad()\n", "def decode_batch(ids, n_new):\n", " \"\"\"Prefill [B, P] once, then n_new - 1 decode steps of one token per user.\n", " Returns (tokens [B, n_new], ms of each decode step).\"\"\"\n", " B, P = ids.shape\n", " out = model.model(input_ids=ids, position_ids=torch.arange(P, device=DEVICE)[None].expand(B, P), use_cache=True)\n", " cache, nxt = out.past_key_values, last_token(out.last_hidden_state)\n", " toks, times = [nxt], []\n", " for i in range(1, n_new):\n", " sync()\n", " t0 = time.perf_counter()\n", " out = model.model(input_ids=nxt[:, None], position_ids=torch.full((B, 1), P + i - 1, device=DEVICE),\n", " past_key_values=cache, use_cache=True)\n", " nxt = last_token(out.last_hidden_state)\n", " nxt.tolist() # reading the answer back waits for the GPU\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " toks.append(nxt)\n", " return torch.stack(toks, 1), times\n", "\n", "\n", "# Checkpoint: user 0 gets the same tokens whether it runs alone or inside a batch of 8.\n", "if ON_GPU:\n", " alone, _ = decode_batch(prompt_batch(1, 256), 24)\n", " in_batch, _ = decode_batch(prompt_batch(8, 256), 24)\n", " same = int((alone[0] == in_batch[0]).sum())\n", " print(f\"user 0 alone vs in a batch of 8: {same} of 24 tokens identical\")\n", " print(\"continuation:\", repr(tok.decode(in_batch[0].tolist())))" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3a · Step time against batch size\n", "\n", "Each batch size: a 256-token prompt per user, 48 tokens, the median of three runs; we keep the median\n", "decode step. The model above gives the ceiling; the measured step is slower because of the Python\n", "loop (Lab 6.1: 1,198 kernels launched one by one)." ], "id": "lab-6-2-batching-08" }, { "cell_type": "code", "metadata": {}, "source": [ "BATCHES = [1, 2, 4, 8, 16, 32, 64]\n", "CTX0, N_STEPS = 256, 48\n", "hand_rows = []\n", "if ON_GPU:\n", " decode_batch(prompt_batch(2, CTX0), 6) # warm-up\n", " print(f\"{'B':>3} {'step ms':>8} {'tokens/s':>9} {'per user tok/s':>15} {'roofline ms':>12} {'roofline tok/s':>15}\")\n", " for B in BATCHES:\n", " ids = prompt_batch(B, CTX0)\n", " meds = []\n", " for _ in range(3):\n", " _, t = decode_batch(ids, N_STEPS)\n", " meds.append(statistics.median(t[2:]))\n", " ms = statistics.median(meds)\n", " r_ms = roofline_step(B, CTX0 + N_STEPS // 2)[0]\n", " hand_rows.append({\n", " \"machine\": MACHINE, \"batch\": B, \"context_start\": CTX0, \"step_ms\": round(ms, 3),\n", " \"tokens_per_s\": round(B / ms * 1e3, 1), \"per_user_tokens_per_s\": round(1e3 / ms, 1),\n", " \"roofline_step_ms\": round(r_ms, 3), \"roofline_tokens_per_s\": round(B / r_ms * 1e3, 1),\n", " \"kv_cache_bytes\": B * (CTX0 + N_STEPS // 2) * KV_PER_TOKEN,\n", " })\n", " r = hand_rows[-1]\n", " print(f\"{B:3d} {r['step_ms']:8.2f} {r['tokens_per_s']:9.0f} {r['per_user_tokens_per_s']:15.1f} \"\n", " f\"{r['roofline_step_ms']:12.2f} {r['roofline_tokens_per_s']:15.0f}\")\n", " save_csv(\"hand-loop-batch.csv\", hand_rows)\n", " h1 = next(r for r in hand_rows if r[\"batch\"] == 1)\n", " h64 = next(r for r in hand_rows if r[\"batch\"] == 64)\n", " print(f\"batch 64 against batch 1: step x{h64['step_ms'] / h1['step_ms']:.2f}, throughput x{h64['tokens_per_s'] / h1['tokens_per_s']:.1f}\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Static batching wastes slots\n", "\n", "A *static* batch starts together and ends when its longest member ends: a finished request keeps its\n", "slot but produces nothing. We run the loop above on 32 requests (128-token prompts, output lengths\n", "drawn from a seeded mix from 16 to 512 tokens) in 4 static batches of 8, in arrival order. Everything is\n", "measured: the wall time, and the useful tokens (the ones each request asked for) per second." ], "id": "lab-6-2-batching-10" }, { "cell_type": "code", "metadata": {}, "source": [ "rng = random.Random(0)\n", "MIX_LENGTHS = [16, 32, 64, 128, 256, 512]\n", "MIX_WEIGHTS = [30, 25, 20, 15, 7, 3]\n", "N_MIX, MIX_PROMPT, MIX_WIDTH = 32, 128, 8\n", "MIX_OUT = rng.choices(MIX_LENGTHS, MIX_WEIGHTS, k=N_MIX)\n", "print(f\"{N_MIX} requests, output tokens: mean {statistics.mean(MIX_OUT):.1f}, median {statistics.median(MIX_OUT)}, \"\n", " f\"max {max(MIX_OUT)}, total {sum(MIX_OUT):,}\")\n", "print(\"per static batch of\", MIX_WIDTH, \":\", [max(MIX_OUT[i:i + MIX_WIDTH]) for i in range(0, N_MIX, MIX_WIDTH)], \"steps\")\n", "\n", "slot_steps = sum(MIX_WIDTH * max(MIX_OUT[i:i + MIX_WIDTH]) for i in range(0, N_MIX, MIX_WIDTH))\n", "slot_util = sum(MIX_OUT) / slot_steps\n", "print(f\"useful tokens {sum(MIX_OUT):,} of {slot_steps:,} slot-steps = {slot_util * 100:.1f} % of the slots do useful work\")\n", "\n", "static_rows = []\n", "if ON_GPU:\n", " t0 = time.perf_counter()\n", " for i in range(0, N_MIX, MIX_WIDTH):\n", " ids = prompt_batch(MIX_WIDTH, MIX_PROMPT)\n", " decode_batch(ids, max(MIX_OUT[i:i + MIX_WIDTH]))\n", " sync()\n", " wall = time.perf_counter() - t0\n", " static_rows.append({\n", " \"machine\": MACHINE, \"method\": \"hand loop, static batches of 8\", \"requests\": N_MIX,\n", " \"useful_tokens\": sum(MIX_OUT), \"wall_s\": round(wall, 2),\n", " \"useful_tokens_per_s\": round(sum(MIX_OUT) / wall, 1), \"slot_utilisation\": round(slot_util, 3),\n", " })\n", " r = static_rows[-1]\n", " print(f\"hand loop, static batches of 8: {r['wall_s']} s -> {r['useful_tokens_per_s']} useful tokens/s\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Build: a paged KV cache by hand\n", "\n", "Reserving one long contiguous strip of memory per request, sized for its longest possible answer,\n", "wastes most of it and fragments the rest. PagedAttention instead cuts the cache into fixed **blocks**\n", "of `block_size` tokens, keeps a **page table** per request (a list of block numbers), and lets a block\n", "be shared by several requests with a **reference count**. Here is the whole idea in one small class,\n", "for one layer, in float32 so we can check it against ordinary contiguous attention." ], "id": "lab-6-2-batching-12" }, { "cell_type": "code", "metadata": {}, "source": [ "class PagedCache:\n", " def __init__(self, num_blocks, block_size, kv_heads, head_dim):\n", " self.bs = block_size\n", " self.k = torch.zeros(num_blocks, block_size, kv_heads, head_dim)\n", " self.v = torch.zeros_like(self.k)\n", " self.free = list(range(num_blocks))[::-1] # free list\n", " self.ref = [0] * num_blocks # how many page tables point at each block\n", " self.seqs = {} # seq id -> {\"table\": [block ids], \"len\": tokens}\n", "\n", " def used_blocks(self):\n", " return sum(1 for r in self.ref if r > 0)\n", "\n", " def new_seq(self, sid):\n", " self.seqs[sid] = {\"table\": [], \"len\": 0}\n", "\n", " def _alloc(self):\n", " b = self.free.pop() # raises IndexError when the pool is empty: that is \"the cache is full\"\n", " self.ref[b] = 1\n", " return b\n", "\n", " def append(self, sid, k, v):\n", " \"\"\"Store the key and value of one new token ([kv_heads, head_dim] each).\"\"\"\n", " s = self.seqs[sid]\n", " slot = s[\"len\"] % self.bs\n", " if slot == 0: # last block full (or none yet): take a new one\n", " s[\"table\"].append(self._alloc())\n", " b = s[\"table\"][-1]\n", " if self.ref[b] > 1: # copy on write: the block is shared, so copy it before changing it\n", " nb = self._alloc()\n", " self.k[nb], self.v[nb] = self.k[b].clone(), self.v[b].clone()\n", " self.ref[b] -= 1\n", " s[\"table\"][-1], b = nb, nb\n", " self.k[b, slot], self.v[b, slot] = k, v\n", " s[\"len\"] += 1\n", "\n", " def fork(self, sid, new_sid):\n", " \"\"\"A second request that starts with the same tokens: share every block, copy nothing.\"\"\"\n", " s = self.seqs[sid]\n", " for b in s[\"table\"]:\n", " self.ref[b] += 1\n", " self.seqs[new_sid] = {\"table\": list(s[\"table\"]), \"len\": s[\"len\"]}\n", "\n", " def release(self, sid):\n", " for b in self.seqs.pop(sid)[\"table\"]:\n", " self.ref[b] -= 1\n", " if self.ref[b] == 0:\n", " self.free.append(b)\n", "\n", " def gather(self, sid):\n", " \"\"\"The contiguous keys and values of a request, read through its page table.\"\"\"\n", " s = self.seqs[sid]\n", " k = self.k[s[\"table\"]].reshape(-1, *self.k.shape[2:])[: s[\"len\"]]\n", " v = self.v[s[\"table\"]].reshape(-1, *self.v.shape[2:])[: s[\"len\"]]\n", " return k, v\n", "\n", "\n", "def attend(q, k, v):\n", " \"\"\"q [q_heads, d]; k, v [T, kv_heads, d]. Grouped-query attention for one new token.\"\"\"\n", " g = q.shape[0] // k.shape[1]\n", " k, v = k.repeat_interleave(g, 1), v.repeat_interleave(g, 1) # [T, q_heads, d]\n", " w = torch.softmax(torch.einsum(\"hd,thd->ht\", q, k) / math.sqrt(q.shape[1]), dim=-1)\n", " return torch.einsum(\"ht,thd->hd\", w, v)\n", "\n", "\n", "gen = torch.Generator().manual_seed(0)\n", "KVH, QH, D, BS = 2, 4, 8, 16\n", "pc = PagedCache(num_blocks=64, block_size=BS, kv_heads=KVH, head_dim=D)\n", "pc.new_seq(\"A\")\n", "ks, vs = [], []\n", "for t in range(53):\n", " k, v = torch.randn(KVH, D, generator=gen), torch.randn(KVH, D, generator=gen)\n", " ks.append(k)\n", " vs.append(v)\n", " pc.append(\"A\", k, v)\n", "q = torch.randn(QH, D, generator=gen)\n", "ref_out = attend(q, torch.stack(ks), torch.stack(vs)) # contiguous attention\n", "kk, vv = pc.gather(\"A\")\n", "paged_out = attend(q, kk, vv) # attention through the page table\n", "print(\"A: 53 tokens, block size\", BS, \"| page table\", pc.seqs[\"A\"][\"table\"], \"| blocks used\", pc.used_blocks())\n", "print(\"paged attention equals contiguous attention, max difference:\", (paged_out - ref_out).abs().max().item())\n", "\n", "pc.fork(\"A\", \"B\")\n", "print(\"\\nfork A -> B (same 53 tokens): blocks used\", pc.used_blocks(), \"| B's table\", pc.seqs[\"B\"][\"table\"],\n", " \"| refcounts\", [pc.ref[b] for b in pc.seqs[\"B\"][\"table\"]])\n", "snapshot_A = pc.gather(\"A\")[0].clone()\n", "pc.append(\"B\", torch.randn(KVH, D, generator=gen), torch.randn(KVH, D, generator=gen)) # B writes into the shared tail block\n", "print(\"B appends one token: blocks used\", pc.used_blocks(), \"| A's table\", pc.seqs[\"A\"][\"table\"], \"| B's table\",\n", " pc.seqs[\"B\"][\"table\"], \"| refcounts\", [pc.ref[b] for b in pc.seqs[\"B\"][\"table\"]])\n", "print(\"A's keys unchanged by B's write:\", torch.equal(snapshot_A, pc.gather(\"A\")[0]))\n", "print(\"blocks without sharing: 8 (4 for A, 4 for B); with sharing:\", pc.used_blocks())\n", "pc.release(\"B\")\n", "pc.release(\"A\")\n", "print(\"both released: blocks used\", pc.used_blocks(), \"of 64\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5a · How much memory the three layouts waste (arithmetic on the mixed workload)\n", "\n", "This is a model, not a measurement: for the 32 requests of section 4 (128-token prompt plus the\n", "drawn output length), how many token slots of cache does each layout reserve for them, against the\n", "tokens they actually hold at the end? Layout 1 reserves the model's longest context per request\n", "(the simplest scheme); layout 2 reserves `prompt + the longest output the client allows` (512 here);\n", "layouts 3 and 4 are paged, with 16-token blocks and with 64-token blocks (the block size this vLLM build chose\n", "for this model, see 6a), allocated as the sequence grows." ], "id": "lab-6-2-batching-14" }, { "cell_type": "code", "metadata": {}, "source": [ "final_len = [MIX_PROMPT + n for n in MIX_OUT]\n", "needed = sum(final_len)\n", "MAX_CTX, MAX_NEW = 2048, 512\n", "layouts = {\n", " \"reserve 2048 tokens per request\": MAX_CTX * N_MIX,\n", " \"reserve prompt + 512 per request\": (MIX_PROMPT + MAX_NEW) * N_MIX,\n", " \"paged, 16-token blocks\": sum(math.ceil(n / 16) * 16 for n in final_len),\n", " \"paged, 64-token blocks\": sum(math.ceil(n / 64) * 64 for n in final_len),\n", "}\n", "frag_rows = []\n", "print(f\"tokens actually held at the end: {needed:,} ({needed * KV_PER_TOKEN / 2**20:.1f} MiB)\")\n", "for name, slots in layouts.items():\n", " frag_rows.append({\n", " \"layout\": name, \"requests\": N_MIX, \"tokens_held\": needed, \"token_slots_reserved\": slots,\n", " \"reserved_mib\": round(slots * KV_PER_TOKEN / 2**20, 1), \"wasted_pct\": round((1 - needed / slots) * 100, 1),\n", " \"requests_per_8_gib_if_all_held_at_once\": int(8 * 2**30 // (slots / N_MIX * KV_PER_TOKEN)),\n", " })\n", " r = frag_rows[-1]\n", " print(f\"{name:36s} reserved {r['token_slots_reserved']:7,} slots = {r['reserved_mib']:8.1f} MiB, \"\n", " f\"{r['wasted_pct']:5.1f} % wasted | requests that fit in 8 GiB: {r['requests_per_8_gib_if_all_held_at_once']:,}\")\n", "save_csv(\"paging-waste.csv\", frag_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · The real library: serve with vLLM and measure\n", "\n", "vLLM implements everything above: continuous batching, a paged cache, prefix caching and chunked\n", "prefill. We run its OpenAI-compatible server as a child process of the notebook, bound to `127.0.0.1`,\n", "and drive it with a small load generator: a closed loop of `C` simulated users, each sending a request,\n", "reading the streamed tokens, then sending the next. Every request asks for exactly 256 new tokens\n", "(`ignore_eos`) so all runs do the same work. We time, per request, from sending to the first streamed\n", "token (**TTFT**) and the gap between streamed tokens afterwards (**TPOT**)." ], "id": "lab-6-2-batching-16" }, { "cell_type": "code", "metadata": {}, "source": [ "HAVE_HTTPX = False\n", "if HAVE_VLLM:\n", " import httpx\n", " HAVE_HTTPX = True\n", "\n", "VLLM_BIN = str(pathlib.Path(sys.executable).parent / \"vllm\")\n", "PIDFILE = WORK / \"servers.pids\"\n", "RUNNING = []\n", "\n", "\n", "class ServerFailed(Exception):\n", " pass\n", "\n", "\n", "class Server:\n", " def __init__(self, name, proc, log_path, startup_s):\n", " self.name, self.proc, self.log_path, self.startup_s = name, proc, log_path, startup_s\n", "\n", " def log(self):\n", " return pathlib.Path(self.log_path).read_text(errors=\"replace\")\n", "\n", "\n", "def log_tail(path, n=14, pattern=r\"(Error|error|ERROR|Traceback|ValueError|OutOfMemory|memory|KV cache)\"):\n", " lines = pathlib.Path(path).read_text(errors=\"replace\").splitlines()\n", " hits = [l for l in lines if re.search(pattern, l)]\n", " return \"\\n\".join((hits or lines)[-n:])\n", "\n", "\n", "def start_server(name, extra=(), max_model_len=16384, util=0.80, wait_s=900):\n", " \"\"\"Start `vllm serve` on 127.0.0.1 in its own process group and wait for /health.\"\"\"\n", " log_path = WORK / f\"server-{name}.log\"\n", " cmd = [VLLM_BIN, \"serve\", MODEL_ID, \"--revision\", REVISION, \"--host\", \"127.0.0.1\", \"--port\", str(PORT),\n", " \"--dtype\", \"float16\", \"--served-model-name\", SERVED, \"--max-model-len\", str(max_model_len),\n", " \"--gpu-memory-utilization\", str(util), *extra]\n", " print(\"$\", \" \".join(cmd[1:]))\n", " t0 = time.time()\n", " logf = open(log_path, \"w\")\n", " proc = subprocess.Popen(cmd, stdout=logf, stderr=subprocess.STDOUT, start_new_session=True)\n", " with PIDFILE.open(\"a\") as f:\n", " f.write(f\"{proc.pid}\\n\")\n", " srv = Server(name, proc, log_path, None)\n", " RUNNING.append(srv)\n", " while time.time() - t0 < wait_s:\n", " if proc.poll() is not None:\n", " RUNNING.remove(srv)\n", " raise ServerFailed(f\"server '{name}' exited with code {proc.returncode} after {time.time() - t0:.0f} s\")\n", " try:\n", " if httpx.get(f\"{BASE}/health\", timeout=2).status_code == 200:\n", " srv.startup_s = time.time() - t0\n", " print(f\"server '{name}' ready after {srv.startup_s:.0f} s\")\n", " return srv\n", " except Exception:\n", " pass\n", " time.sleep(2)\n", " stop_server(srv)\n", " raise ServerFailed(f\"server '{name}' not ready after {wait_s} s\")\n", "\n", "\n", "def stop_server(srv):\n", " if srv is None:\n", " return\n", " try:\n", " os.killpg(srv.proc.pid, signal.SIGINT)\n", " srv.proc.wait(90)\n", " except Exception:\n", " pass\n", " try:\n", " os.killpg(srv.proc.pid, signal.SIGKILL) # anything the server's own children left behind\n", " except ProcessLookupError:\n", " pass\n", " srv.proc.wait()\n", " if srv in RUNNING:\n", " RUNNING.remove(srv)\n", " time.sleep(4)\n", " print(f\"server '{srv.name}' stopped; GPU memory free {torch.cuda.mem_get_info()[0] / 2**30:.2f} GiB\")\n", "\n", "\n", "atexit.register(lambda: [stop_server(s) for s in list(RUNNING)])\n", "\n", "\n", "def startup_facts(srv):\n", " \"\"\"The numbers the server prints about its own memory plan, as (key, value, line) rows.\"\"\"\n", " out, text = [], srv.log()\n", " pats = {\n", " \"kv_cache_tokens\": r\"GPU KV cache size: ([\\d,]+) tokens\",\n", " \"max_concurrency_line\": r\"(Maximum concurrency for [\\d,]+ tokens per request: [\\d.]+x)\",\n", " \"model_loading\": r\"(Model loading took [\\d.]+ GiB[^\\n]*)\",\n", " \"kv_memory_gib\": r\"Available KV cache memory: ([\\d.]+) GiB\",\n", " \"memory_plan\": r\"(Free memory on device[^\\n]*?KV cache memory in use is [\\d.]+ GiB)\",\n", " \"chunked_prefill\": r\"enable_chunked_prefill=(\\w+)\",\n", " }\n", " for key, pat in pats.items():\n", " m = re.search(pat, text)\n", " if m:\n", " out.append({\"server\": srv.name, \"key\": key, \"value\": (m.group(1) or m.group(0)).strip()})\n", " return out\n", "\n", "\n", "def cache_config(srv):\n", " \"\"\"What the server's /metrics says about its cache: block size, number of blocks, capacity in tokens.\"\"\"\n", " text = httpx.get(f\"{BASE}/metrics\", timeout=5).text\n", " out = []\n", " for key in (\"block_size\", \"num_gpu_blocks\", \"kv_cache_size_tokens\", \"kv_cache_max_concurrency\", \"enable_prefix_caching\"):\n", " m = re.search(rf'{key}=\"([^\"]+)\"', text)\n", " if m:\n", " out.append({\"server\": srv.name, \"key\": key, \"value\": m.group(1)})\n", " return out\n", "\n", "\n", "def free_gib():\n", " return torch.cuda.mem_get_info()[0] / 2**30" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-17" }, { "cell_type": "code", "metadata": {}, "source": [ "async def stream_request(client, prompt, max_tokens, kind=\"\", t_ref=None):\n", " \"\"\"One streamed completion. Returns the request's timings in ms (None when it failed).\"\"\"\n", " body = {\"model\": SERVED, \"prompt\": prompt, \"max_tokens\": max_tokens, \"temperature\": 0, \"ignore_eos\": True,\n", " \"stream\": True}\n", " t_send, stamps, status, err = time.perf_counter(), [], None, \"\"\n", " try:\n", " async with client.stream(\"POST\", f\"{BASE}/v1/completions\", json=body) as r:\n", " status = r.status_code\n", " if status != 200:\n", " err = (await r.aread()).decode(errors=\"replace\")[:400]\n", " else:\n", " async for line in r.aiter_lines():\n", " if line.startswith(\"data:\") and \"[DONE]\" not in line:\n", " stamps.append(time.perf_counter())\n", " except Exception as e: # connection problems are data, not crashes\n", " err = repr(e)\n", " res = {\"kind\": kind, \"status\": status, \"error\": err, \"prompt_tokens\": len(prompt), \"chunks\": len(stamps),\n", " \"sent_at_s\": round(t_send - (t_ref or t_send), 4)}\n", " if stamps:\n", " gaps = [(b - a) * 1e3 for a, b in zip(stamps, stamps[1:])]\n", " res.update(ttft_ms=(stamps[0] - t_send) * 1e3, e2e_ms=(stamps[-1] - t_send) * 1e3,\n", " tpot_ms=(stamps[-1] - stamps[0]) * 1e3 / max(1, len(stamps) - 1),\n", " max_gap_ms=max(gaps) if gaps else 0.0)\n", " return res\n", "\n", "\n", "def run_async(coro):\n", " \"\"\"Run a coroutine to completion from a notebook cell (a thread, so a running event loop is no problem).\"\"\"\n", " with concurrent.futures.ThreadPoolExecutor(1) as ex:\n", " return ex.submit(asyncio.run, coro).result()\n", "\n", "\n", "async def closed_loop(prompts, out_lens, concurrency):\n", " \"\"\"`concurrency` users; each takes the next request as soon as its last one finished.\"\"\"\n", " queue = collections.deque(range(len(prompts)))\n", " results = [None] * len(prompts)\n", " async with httpx.AsyncClient(timeout=None, limits=httpx.Limits(max_connections=concurrency + 8)) as client:\n", " async def user():\n", " while queue:\n", " i = queue.popleft()\n", " results[i] = await stream_request(client, prompts[i], out_lens[i])\n", " t0 = time.perf_counter()\n", " await asyncio.gather(*[user() for _ in range(concurrency)])\n", " wall = time.perf_counter() - t0\n", " return results, wall\n", "\n", "\n", "async def waves(prompts, out_lens, width):\n", " \"\"\"Like a static batch: `width` requests together, and the next ones start only when ALL have finished.\"\"\"\n", " results, t0 = [], time.perf_counter()\n", " async with httpx.AsyncClient(timeout=None, limits=httpx.Limits(max_connections=width + 8)) as client:\n", " for i in range(0, len(prompts), width):\n", " results += await asyncio.gather(*[stream_request(client, prompts[j], out_lens[j])\n", " for j in range(i, min(i + width, len(prompts)))])\n", " return results, time.perf_counter() - t0\n", "\n", "\n", "def metrics_snapshot():\n", " text = httpx.get(f\"{BASE}/metrics\", timeout=5).text\n", " out = {}\n", " for line in text.splitlines():\n", " if line.startswith(\"#\"):\n", " continue\n", " m = re.match(r\"(vllm:[a-z0-9_]+?)(?:\\{[^}]*\\})?\\s+([-\\d.e+]+)$\", line)\n", " if m:\n", " out[m.group(1)] = out.get(m.group(1), 0.0) + float(m.group(2))\n", " return out" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6a · Start the server\n", "\n", "Settings: `--gpu-memory-utilization 0.80` (the server may take 80 % of the card), `--max-model-len 16384`\n", "(the longest prompt plus answer it accepts); everything else is the library's default. The server prints\n", "how it split the memory: read the lines below against your prediction 4." ], "id": "lab-6-2-batching-19" }, { "cell_type": "code", "metadata": {}, "source": [ "srv = None\n", "startup_rows = []\n", "if HAVE_VLLM:\n", " print(f\"GPU memory free before the server starts: {free_gib():.2f} GiB (this notebook's own CUDA context included)\")\n", " del model\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " print(f\"after freeing the notebook's copy of the model: {free_gib():.2f} GiB\")\n", " srv = start_server(\"main\")\n", " startup_rows += startup_facts(srv) + cache_config(srv)\n", " print(\"from /metrics:\", {r[\"key\"]: r[\"value\"] for r in startup_rows if r[\"server\"] == \"main\" and r[\"key\"] in\n", " (\"block_size\", \"num_gpu_blocks\", \"kv_cache_size_tokens\")})\n", " for line in srv.log().splitlines():\n", " if re.search(r\"(Model loading took|Available KV cache memory|GPU KV cache size|Maximum concurrency|\"\n", " r\"Chunked prefill|init engine|Graph capturing finished|attention backend|Using .* backend)\", line):\n", " print(line[-230:])\n", " KV_TOKENS = int(next((r[\"value\"].replace(\",\", \"\") for r in startup_rows if r[\"key\"] == \"kv_cache_tokens\"), 0))\n", " VLLM_BLOCK = int(next((r[\"value\"] for r in startup_rows if r[\"key\"] == \"block_size\"), 16))\n", " print(f\"\\nthe server holds {KV_TOKENS:,} tokens of KV cache = {KV_TOKENS * KV_PER_TOKEN / 2**30:.2f} GiB \"\n", " f\"at {KV_PER_TOKEN:,} bytes per token\")\n", "else:\n", " print(\"no GPU or no vLLM installed: skipping the server sections\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6b · Throughput and latency against the number of concurrent users\n", "\n", "For each `C`: `max(8, 3C)` requests of 256 prompt tokens and 256 new tokens, `C` at a time, twice; we keep\n", "the median of the two runs. Throughput is output tokens divided by the wall time of the whole run\n", "(ramp-up and drain included). The *roofline* column is the model of section 2 with an average\n", "context of 384 tokens; it ignores everything but weights, cache and arithmetic, so it is an upper bound." ], "id": "lab-6-2-batching-21" }, { "cell_type": "code", "metadata": {}, "source": [ "SWEEP, P_LEN, O_LEN = [1, 2, 4, 8, 16, 32, 64], 256, 256\n", "conc_rows, raw_rows = [], []\n", "if srv:\n", " run_async(closed_loop([make_prompt(9000 + i, P_LEN) for i in range(16)], [32] * 16, 8)) # warm-up\n", " print(f\"{'C':>3} {'tok/s':>7} {'TTFT med':>9} {'TTFT p95':>9} {'TPOT med':>9} {'TPOT p95':>9} {'e2e s':>7} \"\n", " f\"{'roofline':>9} {'% of roofline':>14}\")\n", " for C in SWEEP:\n", " n_req, per_rep = max(8, 3 * C), []\n", " for rep in range(2):\n", " prompts = [make_prompt(C * 1000 + rep * 500 + i, P_LEN) for i in range(n_req)]\n", " res, wall = run_async(closed_loop(prompts, [O_LEN] * n_req, C))\n", " ok = [r for r in res if r[\"status\"] == 200 and r[\"chunks\"] > 0]\n", " assert len(ok) == n_req, [r[\"error\"] for r in res if r[\"status\"] != 200][:2]\n", " tokens = sum(r[\"chunks\"] for r in ok)\n", " per_rep.append({\n", " \"wall\": wall, \"tok_s\": tokens / wall, \"ttft\": [r[\"ttft_ms\"] for r in ok],\n", " \"tpot\": [r[\"tpot_ms\"] for r in ok], \"e2e\": [r[\"e2e_ms\"] for r in ok],\n", " \"chunks\": statistics.median(r[\"chunks\"] for r in ok)})\n", " for r in ok:\n", " raw_rows.append({\"concurrency\": C, \"repeat\": rep, \"prompt_tokens\": r[\"prompt_tokens\"],\n", " \"chunks\": r[\"chunks\"], \"ttft_ms\": round(r[\"ttft_ms\"], 2),\n", " \"tpot_ms\": round(r[\"tpot_ms\"], 3), \"e2e_ms\": round(r[\"e2e_ms\"], 1),\n", " \"max_gap_ms\": round(r[\"max_gap_ms\"], 2)})\n", " allttft = [x for p in per_rep for x in p[\"ttft\"]]\n", " alltpot = [x for p in per_rep for x in p[\"tpot\"]]\n", " alle2e = [x for p in per_rep for x in p[\"e2e\"]]\n", " tok_s = statistics.median(p[\"tok_s\"] for p in per_rep)\n", " r_ms = roofline_step(C, P_LEN + O_LEN // 2)[0]\n", " conc_rows.append({\n", " \"machine\": MACHINE, \"engine\": f\"vLLM {VLLM_VERSION}\", \"concurrency\": C, \"requests_per_run\": n_req,\n", " \"prompt_tokens\": P_LEN, \"output_tokens\": O_LEN, \"chunks_per_request\": per_rep[0][\"chunks\"],\n", " \"throughput_tokens_per_s\": round(tok_s, 1),\n", " \"ttft_ms_median\": round(statistics.median(allttft), 1), \"ttft_ms_p95\": round(pct(allttft, 0.95), 1),\n", " \"tpot_ms_median\": round(statistics.median(alltpot), 2), \"tpot_ms_p95\": round(pct(alltpot, 0.95), 2),\n", " \"per_user_tokens_per_s\": round(1e3 / statistics.median(alltpot), 1),\n", " \"e2e_s_median\": round(statistics.median(alle2e) / 1e3, 2),\n", " \"roofline_step_ms\": round(r_ms, 3), \"roofline_tokens_per_s\": round(C / r_ms * 1e3, 1),\n", " })\n", " r = conc_rows[-1]\n", " print(f\"{C:3d} {r['throughput_tokens_per_s']:7.0f} {r['ttft_ms_median']:9.1f} {r['ttft_ms_p95']:9.1f} \"\n", " f\"{r['tpot_ms_median']:9.2f} {r['tpot_ms_p95']:9.2f} {r['e2e_s_median']:7.2f} \"\n", " f\"{r['roofline_tokens_per_s']:9.0f} {r['throughput_tokens_per_s'] / r['roofline_tokens_per_s'] * 100:13.0f}%\")\n", " save_csv(\"concurrency.csv\", conc_rows)\n", " save_csv(\"requests-raw.csv\", raw_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6c · Continuous against waves, and what the cache looked like\n", "\n", "The same 32 mixed-length requests as section 4, 8 at a time. *Continuous*: eight users in a closed\n", "loop, so a slot freed by a short request is refilled at once (what vLLM's scheduler is built for). *Waves*:\n", "the client releases 8 requests, waits until **all** have finished, then releases the next 8, which is\n", "how a static batch behaves. Same engine, same requests, same hardware; only the scheduling differs." ], "id": "lab-6-2-batching-23" }, { "cell_type": "code", "metadata": {}, "source": [ "if srv:\n", " mix_prompts = [make_prompt(5000 + i, MIX_PROMPT) for i in range(N_MIX)]\n", " run_async(closed_loop(mix_prompts[:8], [16] * 8, 8)) # warm-up\n", " for label, fn in ((\"vLLM, continuous (8 in flight)\", lambda: run_async(closed_loop(mix_prompts, MIX_OUT, MIX_WIDTH))),\n", " (\"vLLM, waves of 8 (wait for the slowest)\", lambda: run_async(waves(mix_prompts, MIX_OUT, MIX_WIDTH)))):\n", " res, wall = fn()\n", " ok = [r for r in res if r[\"status\"] == 200]\n", " assert len(ok) == N_MIX and all(r[\"chunks\"] == n for r, n in zip(res, MIX_OUT)), \"token counts differ\"\n", " static_rows.append({\n", " \"machine\": MACHINE, \"method\": label, \"requests\": N_MIX, \"useful_tokens\": sum(MIX_OUT),\n", " \"wall_s\": round(wall, 2), \"useful_tokens_per_s\": round(sum(MIX_OUT) / wall, 1),\n", " \"slot_utilisation\": round(slot_util, 3) if \"waves\" in label else \"\",\n", " })\n", " r = static_rows[-1]\n", " print(f\"{label:42s} {r['wall_s']:7.2f} s -> {r['useful_tokens_per_s']:7.1f} useful tokens/s\")\n", " save_csv(\"static-vs-continuous.csv\", static_rows)\n", " cont = next(r for r in static_rows if \"continuous\" in r[\"method\"])\n", " wav = next(r for r in static_rows if \"waves\" in r[\"method\"])\n", " print(f\"continuous is {cont['useful_tokens_per_s'] / wav['useful_tokens_per_s']:.2f}x the waves' throughput\")" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6d · Prefix caching\n", "\n", "Many requests start with the same text (a system prompt, a document, the earlier turns of a chat).\n", "vLLM hashes every full block of prompt tokens, chained to the blocks before it, and keeps finished\n", "blocks in an LRU pool; a new request whose first blocks hash the same reuses them and prefills only the\n", "rest. One user at a time, 2,048-token prompts that end in a 32-token question, 8 requests each:\n", "**cold**: every request has a different 2,048-token prefix; **warm**: the same prefix every time\n", "(the first request is cold and is reported separately). The counters come from the server's `/metrics`." ], "id": "lab-6-2-batching-25" }, { "cell_type": "code", "metadata": {}, "source": [ "pc_rows = []\n", "if srv:\n", " SHARED, QLEN, NREQ = 2048, 32, 8\n", " def cold_prompt(i):\n", " return make_prompt(7000 + i, SHARED + QLEN)\n", " base_shared = make_prompt(8000, SHARED)\n", " def warm_prompt(i):\n", " return base_shared + [1000 + (i * 331) % 90000] + LONG_IDS[3000 + 40 * i: 3000 + 40 * i + QLEN - 1]\n", " for label, builder in ((\"cold: different prefix every time\", cold_prompt), (\"warm: same 2,048-token prefix\", warm_prompt)):\n", " m0 = metrics_snapshot()\n", " res, _ = run_async(closed_loop([builder(i) for i in range(NREQ)], [16] * NREQ, 1))\n", " m1 = metrics_snapshot()\n", " t = [r[\"ttft_ms\"] for r in res]\n", " q = m1.get(\"vllm:prefix_cache_queries_total\", 0) - m0.get(\"vllm:prefix_cache_queries_total\", 0)\n", " h = m1.get(\"vllm:prefix_cache_hits_total\", 0) - m0.get(\"vllm:prefix_cache_hits_total\", 0)\n", " pc_rows.append({\n", " \"machine\": MACHINE, \"case\": label, \"prompt_tokens\": len(builder(0)), \"requests\": NREQ,\n", " \"first_request_ttft_ms\": round(t[0], 1), \"later_requests_ttft_ms_median\": round(statistics.median(t[1:]), 1),\n", " \"prompt_tokens_queried\": int(q), \"prompt_tokens_served_from_cache\": int(h),\n", " \"cache_hit_pct\": round(100 * h / q, 1) if q else \"\"})\n", " r = pc_rows[-1]\n", " print(f\"{label:36s} TTFT first {r['first_request_ttft_ms']:7.1f} ms | later (median of {NREQ - 1}) \"\n", " f\"{r['later_requests_ttft_ms_median']:7.1f} ms | tokens queried {r['prompt_tokens_queried']:,}, \"\n", " f\"from cache {r['prompt_tokens_served_from_cache']:,} ({r['cache_hit_pct']} %)\")\n", " save_csv(\"prefix-cache.csv\", pc_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6e · Where the limits are, read from the server\n", "\n", "A request longer than `--max-model-len` is refused at once, before it costs anything. Read the answer." ], "id": "lab-6-2-batching-27" }, { "cell_type": "code", "metadata": {}, "source": [ "if srv:\n", " r = httpx.post(f\"{BASE}/v1/completions\", timeout=60,\n", " json={\"model\": SERVED, \"prompt\": make_prompt(1, 20000), \"max_tokens\": 8})\n", " print(\"20,000-token prompt against --max-model-len 16384 ->\", r.status_code)\n", " print(r.json().get(\"error\", r.text) if r.headers.get(\"content-type\", \"\").startswith(\"application/json\") else r.text[:300])\n", " m = metrics_snapshot()\n", " print(\"\\nkv cache usage right now (0 to 1):\", m.get(\"vllm:kv_cache_usage_perc\", m.get(\"vllm:gpu_cache_usage_perc\")))\n", " save_csv(\"server-startup.csv\", startup_rows)\n", " stop_server(srv)\n", " srv = None" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Checkpoint\n", "\n", "Compare with your run. The numbers below are the ones the chapter quotes; yours will differ a little\n", "(one GPU, one machine) but the shape must match." ], "id": "lab-6-2-batching-29" }, { "cell_type": "code", "metadata": {}, "source": [ "if hand_rows and conc_rows:\n", " print(f\"hand loop: step at B=1 {hand_rows[0]['step_ms']:.2f} ms -> B=64 {hand_rows[-1]['step_ms']:.2f} ms; \"\n", " f\"tokens/s {hand_rows[0]['tokens_per_s']:.0f} -> {hand_rows[-1]['tokens_per_s']:.0f}\")\n", " print(f\"vLLM: tokens/s at C=1 {conc_rows[0]['throughput_tokens_per_s']:.0f}, at C=64 {conc_rows[-1]['throughput_tokens_per_s']:.0f}; \"\n", " f\"TPOT {conc_rows[0]['tpot_ms_median']:.1f} ms -> {conc_rows[-1]['tpot_ms_median']:.1f} ms\")\n", " print(f\"KV cache the server reserved: {KV_TOKENS:,} tokens = {KV_TOKENS * KV_PER_TOKEN / 2**30:.2f} GiB\")\n", " print(\"slot utilisation of static batches of 8 on the mixed workload:\", f\"{slot_util * 100:.1f} %\")\n", "print(\"your predictions:\", PREDICT)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| `SWEEP` | add 96 and 128 | Where does throughput stop growing, and what does TPOT do there? Compare with the roofline column. |\n", "| `P_LEN`, `O_LEN` | 1,024 in and 64 out; 32 in and 1,024 out | Which of TTFT and TPOT moves, and why? Which workload gets more out of batching? |\n", "| `--max-num-seqs` | 8 and 256 (add to `start_server(extra=...)`) | With 64 users and a limit of 8, where do the other 56 wait, and which metric shows it? |\n", "| `--gpu-memory-utilization` | 0.5, 0.7, 0.9 | What changes in \"GPU KV cache size\", and does throughput at 16 users change? |\n", "| `--block-size` | 8, 16, 32 | How does block size change the waste of section 5a, and the number of page-table entries? |\n", "| `--no-enable-prefix-caching` | rerun 6d | What happens to the warm case, and to the cold one? |\n", "| `MIX_OUT` | all 256 tokens | Do the waves still lose to continuous batching? Why or why not? |\n", "| block size in `PagedCache` | 1, 4, 64 | How many blocks does the forked request copy on its first write? How many tokens of waste at the end of a sequence? |" ], "id": "lab-6-2-batching-31" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Failure playground\n", "\n", "Three ways to break the server. Each cell starts a server (or a pair), catches the failure, and shows the\n", "last relevant lines. For each: what is the symptom, what does the message say it needs, what is the\n", "arithmetic, and which one setting do you change?" ], "id": "lab-6-2-batching-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9a · \"The server dies while starting\" (or does it?)\n", "\n", "`--gpu-memory-utilization` is a fraction of the card's *total* memory that the server may use. Three\n", "experiments. (i) Ask for 0.99 on an otherwise empty card. (ii) Ask for the ordinary 0.80 while another\n", "program on the same GPU (here: this notebook, holding 3 GiB) has taken memory first. (iii) The same as (ii)\n", "with the extensible KV cache turned off (`--disable-extensible-kv-cache`), which is how earlier vLLM versions\n", "sized the cache. Predict each outcome first: starts, or refuses? What is the KV cache size?" ], "id": "lab-6-2-batching-33" }, { "cell_type": "code", "metadata": {}, "source": [ "fail_rows = []\n", "\n", "\n", "def try_start(case, name, util, extra=(), pattern=r\"(ValueError|Error|memory)\"):\n", " try:\n", " s = start_server(name, util=util, extra=extra, wait_s=400)\n", " info = startup_facts(s)\n", " tokens = next((r[\"value\"] for r in info if r[\"key\"] == \"kv_cache_tokens\"), \"?\")\n", " print(f\" -> started; KV cache {tokens} tokens\")\n", " fail_rows.append({\"case\": case, \"result\": \"started\", \"message\": f\"KV cache {tokens} tokens\"})\n", " stop_server(s)\n", " except ServerFailed as e:\n", " print(\" \", e)\n", " print(log_tail(WORK / f\"server-{name}.log\", 6, pattern))\n", " fail_rows.append({\"case\": case, \"result\": \"failed\",\n", " \"message\": log_tail(WORK / f\"server-{name}.log\", 2, pattern).replace(\"\\n\", \" | \")[-500:]})\n", "\n", "\n", "if HAVE_VLLM:\n", " print(f\"free GPU memory before: {free_gib():.2f} GiB of {torch.cuda.mem_get_info()[1] / 2**30:.2f} GiB\")\n", " try_start(\"0.99, empty card\", \"gpu-util-099\", 0.99)\n", " hog = torch.empty(3 * 2**30, dtype=torch.uint8, device=\"cuda\")\n", " print(f\"\\nanother program now holds 3 GiB; free GPU memory {free_gib():.2f} GiB\")\n", " try_start(\"0.80, 3 GiB already taken\", \"gpu-util-080-shared\", 0.80)\n", " try_start(\"0.80, 3 GiB already taken, extensible KV cache off\", \"gpu-util-080-shared-fixed\", 0.80,\n", " extra=[\"--disable-extensible-kv-cache\"], pattern=r\"(ValueError|Free memory)\")\n", " del hog\n", " torch.cuda.empty_cache()" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: the setting is a fraction of what, and when is it checked against what is *free*? Which\n", "of the three runs refused to start, and what did the message tell you to do? Why did the other two start\n", "anyway, and what did the cache size do? What does the extensible cache not protect against (a program that\n", "allocates after the server has started)? Which value would you choose on a card you share, and what would\n", "you change instead?" ], "id": "lab-6-2-batching-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9b · \"It refuses to start: the context is larger than the cache\"\n", "\n", "We ask for the model's full 32,768-token context but give the KV cache a budget of 300 MiB.\n", "At 28,672 bytes per token, how many tokens is that, and how many does one maximum-length request need?\n", "Work it out *before* you run the cell." ], "id": "lab-6-2-batching-36" }, { "cell_type": "code", "metadata": {}, "source": [ "if HAVE_VLLM:\n", " try:\n", " s = start_server(\"tiny-kv\", extra=[\"--kv-cache-memory-bytes\", str(300 * 2**20)], max_model_len=32768, wait_s=400)\n", " stop_server(s)\n", " res = \"started\"\n", " except ServerFailed as e:\n", " res = \"failed\"\n", " print(e)\n", " print(log_tail(WORK / \"server-tiny-kv.log\", 8, r\"(ValueError|KV cache|max seq len|estimated maximum)\"))\n", " fail_rows.append({\"case\": \"max_model_len 32768 with a 300 MiB KV cache\", \"result\": res,\n", " \"message\": log_tail(WORK / \"server-tiny-kv.log\", 2, r\"(ValueError|KV cache)\").replace(\"\\n\", \" | \")[-500:]})\n", " save_csv(\"failure-startup.csv\", fail_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-37" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: what does the message say the model needs, what does it say is available, and what maximum\n", "length does it suggest? Check its numbers against 28,672 bytes per token. Name two different fixes: one\n", "that keeps the context and one that keeps the memory budget." ], "id": "lab-6-2-batching-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9c · \"One long prompt freezes everybody\"\n", "\n", "Four users are streaming a long answer. Then an 8,192-token prompt arrives, followed by short requests\n", "(128 tokens in, 16 out) every 100 ms. We measure the short requests' TTFT, and the longest gap in\n", "the four streams, with and without the long prompt. The server runs three times with a different\n", "per-step token budget (`--max-num-batched-tokens`): 16,384 (the long prompt fits in one step), the default\n", "(2,048 for this version on this card) and 512." ], "id": "lab-6-2-batching-39" }, { "cell_type": "code", "metadata": {}, "source": [ "async def stall_run(with_long, seed=0, long_len=8192, n_bg=4, bg_out=400, n_short=12, gap_s=0.1):\n", " async with httpx.AsyncClient(timeout=None, limits=httpx.Limits(max_connections=40)) as client:\n", " bg = [asyncio.create_task(stream_request(client, make_prompt(900 + i, 64), bg_out, \"bg\")) for i in range(n_bg)]\n", " await asyncio.sleep(1.0) # all four are decoding\n", " t_ref = time.perf_counter()\n", " tasks = []\n", " if with_long:\n", " tasks.append(asyncio.create_task(stream_request(client, make_prompt(77 + 1000 * seed, long_len), 8, \"long\", t_ref)))\n", " await asyncio.sleep(gap_s)\n", " for k in range(n_short):\n", " tasks.append(asyncio.create_task(stream_request(client, make_prompt(300 + k, 128), 16, \"short\", t_ref)))\n", " await asyncio.sleep(gap_s)\n", " res = await asyncio.gather(*tasks, *bg)\n", " return res\n", "\n", "\n", "stall_rows = []\n", "if HAVE_VLLM:\n", " # the default budget of `vllm serve` for this version on a card under 70 GB is 2048 (vllm/engine/arg_utils.py)\n", " for label, budget, extra in ((\"budget 16384\", 16384, [\"--max-num-batched-tokens\", \"16384\"]),\n", " (\"default budget\", 2048, []),\n", " (\"budget 512\", 512, [\"--max-num-batched-tokens\", \"512\"])):\n", " s = start_server(\"stall-\" + label.replace(\" \", \"-\"), extra=extra)\n", " startup_rows += startup_facts(s)\n", " run_async(closed_loop([make_prompt(9500 + i, 256) for i in range(8)], [16] * 8, 4)) # warm-up\n", " for phase, with_long in ((\"without long prompt\", False), (\"with 8,192-token prompt\", True)):\n", " for rep in range(3): # a different long prompt each time, or the prefix cache would serve the repeat\n", " res = run_async(stall_run(with_long, seed=rep))\n", " short = [r for r in res if r[\"kind\"] == \"short\"]\n", " bg = [r for r in res if r[\"kind\"] == \"bg\"]\n", " lg = [r for r in res if r[\"kind\"] == \"long\"]\n", " stall_rows.append({\n", " \"machine\": MACHINE, \"server\": label, \"max_num_batched_tokens\": budget, \"phase\": phase, \"repeat\": rep,\n", " \"short_ttft_ms_median\": round(statistics.median(r[\"ttft_ms\"] for r in short), 1),\n", " \"short_ttft_ms_max\": round(max(r[\"ttft_ms\"] for r in short), 1),\n", " \"stream_max_gap_ms\": round(max(r[\"max_gap_ms\"] for r in bg), 1),\n", " \"long_ttft_ms\": round(lg[0][\"ttft_ms\"], 1) if lg else \"\"})\n", " r = stall_rows[-1]\n", " print(f\" {phase:26s} run {rep}: short TTFT median {r['short_ttft_ms_median']:8.1f} ms, max \"\n", " f\"{r['short_ttft_ms_max']:8.1f} ms | longest gap in a stream {r['stream_max_gap_ms']:8.1f} ms | \"\n", " f\"long prompt TTFT {r['long_ttft_ms']}\")\n", " stop_server(s)\n", " save_csv(\"long-prompt-stall.csv\", stall_rows)\n", " save_csv(\"server-startup.csv\", startup_rows)" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-40" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: how long was the stall, and does it match your prediction 5? Which setting makes it\n", "shorter, and what does it cost the long prompt itself? Why does a smaller per-step budget help the\n", "short requests but delay the long one? (Hint: what does the scheduler fill the step with first?)" ], "id": "lab-6-2-batching-41" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Versions tested" ], "id": "lab-6-2-batching-42" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"Python\", platform.python_version(), \"|\", platform.platform())\n", "print(\"PyTorch\", torch.__version__, \"| CUDA runtime\", torch.version.cuda)\n", "import transformers # noqa: E402\n", "print(\"transformers\", transformers.__version__, \"| vLLM\", VLLM_VERSION, \"| httpx\", importlib.metadata.version(\"httpx\") if HAVE_HTTPX else None)\n", "print(\"model\", MODEL_ID, \"revision\", REVISION, \"| dtype float16\")\n", "if ON_GPU:\n", " print(\"GPU:\", torch.cuda.get_device_name(0), \"| compute capability\", torch.cuda.get_device_capability(0))\n", " try:\n", " print(\"NVIDIA driver\", subprocess.run([\"nvidia-smi\", \"--query-gpu=driver_version\", \"--format=csv,noheader\"],\n", " capture_output=True, text=True).stdout.strip())\n", " except Exception:\n", " pass\n", "leftover = subprocess.run([\"pgrep\", \"-f\", \"vllm serve\"], capture_output=True, text=True).stdout.split()\n", "print(\"vLLM servers still running from this notebook:\", [p for p in leftover if int(p) in {s.proc.pid for s in RUNNING}])" ], "execution_count": null, "outputs": [], "id": "lab-6-2-batching-43" } ] }