""" paged_kv.py: the notebook (KV cache) split into pages, PagedAttention style. 1. Same answer? Run the same chats with a reserved notebook and with pages, compare every number the factory produces. 2. Memory: serve the same 32 chats with a fixed amount of notebook room, reserving each chat's maximum up front vs handing out 16-token pages as they fill. (A count of tokens and pages; no math needed.) 3. What pages cost: time to read one chat's notebook, contiguous vs pages. Same factory as engine.py: GPT-2-small shape, random weights, NumPy, CPU. """ import time import numpy as np from engine import Engine, request_stream, norm, gelu, D, LAYERS, HEADS, HD, VOCAB, KV_BYTES_PER_TOKEN PAGE = 16 # tokens per page class PagedEngine(Engine): """Same tables as Engine; notebooks live in one shared pool of pages.""" def __init__(self, n_pages, seed=0): super().__init__(seed) self.K = np.zeros((LAYERS, HEADS, n_pages, PAGE, HD), np.float32) self.V = np.zeros_like(self.K) self.free = list(range(n_pages)) def new_user(self, max_len=None): # max_len ignored: nothing reserved return dict(pages=[], n=0) def trip(self, x, segments): for u, t in segments: # grab pages for the new tokens while len(u["pages"]) * PAGE < u["n"] + t: u["pages"].append(self.free.pop()) for i, p in enumerate(self.layers): q, k, v = np.split(p["qkv"] @ norm(x), 3) outs, col = [], 0 for u, t in segments: s, e = u["n"], u["n"] + t kk = k[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) vv = v[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) for j in range(t): # write each token into its page slot pg, slot = u["pages"][(s + j) // PAGE], (s + j) % PAGE self.K[i, :, pg, slot], self.V[i, :, pg, slot] = kk[:, j], vv[:, j] pages = u["pages"][:(e + PAGE - 1) // PAGE] Kc = self.K[i][:, pages].reshape(HEADS, -1, HD)[:, :e] # gather the pages Vc = self.V[i][:, pages].reshape(HEADS, -1, HD)[:, :e] qi = q[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) att = qi @ Kc.transpose(0, 2, 1) / HD ** 0.5 if t > 1: att = np.where(np.triu(np.ones((t, e), bool), k=s + 1), -1e9, att) att = np.exp(att - att.max(-1, keepdims=True)) att /= att.sum(-1, keepdims=True) outs.append((att @ Vc).transpose(0, 2, 1).reshape(D, t)) col += t x = x + p["out"] @ np.concatenate(outs, 1) x = x + p["down"] @ gelu(p["up"] @ norm(x)) for u, t in segments: u["n"] += t return x def release(self, u): self.free += u["pages"] u["pages"] = [] def same_answer(): rng = np.random.default_rng(5) a, b = Engine(), PagedEngine(n_pages=64) lens = [40, 7, 23] # three chats, odd prompt lengths ua = [a.new_user(80) for _ in lens] ub = [b.new_user() for _ in lens] worst = 0.0 for l, x, y in zip(lens, ua, ub): ids = rng.integers(0, VOCAB, l) worst = max(worst, np.abs(a.prefill(x, ids) - b.prefill(y, ids)).max()) for _ in range(30): # 30 decode steps, all three together worst = max(worst, np.abs(a.decode_step(ua) - b.decode_step(ub)).max()) used = sum(len(u["pages"]) for u in ub) return worst, used, sum(u["n"] for u in ub) def serve(reqs, room_tokens, mode, max_len=1024): """Count-only simulation of continuous batching under a fixed notebook budget. reserve: each chat holds max_len tokens of room from start to finish. paged: each chat holds ceil(tokens so far / 16) pages; if the pool runs dry, the newest chat is sent back to the queue and redone later (preemption).""" queue = [dict(r, made=0) for r in reqs] active, steps, conc, real, held, preempt = [], 0, [], [], [], 0 pages_total = room_tokens // PAGE need = lambda r: -(-(r["prompt"] + r["made"] + 1) // PAGE) # pages after this step while queue or active: if mode == "reserve": while queue and (len(active) + 1) * max_len <= room_tokens: active.append(queue.pop(0)) else: while queue and sum(need(r) for r in active) + need(queue[0]) <= pages_total: active.append(queue.pop(0)) while sum(need(r) for r in active) > pages_total: # out of pages victim = active.pop() victim["made"] = 0 queue.insert(0, victim) preempt += 1 steps += 1 conc.append(len(active)) real.append(sum(r["prompt"] + r["made"] + 1 for r in active)) held.append(len(active) * max_len if mode == "reserve" else sum(need(r) for r in active) * PAGE) for r in active: r["made"] += 1 active = [r for r in active if r["made"] < r["out"]] return dict(steps=steps, avg=np.mean(conc), peak=max(conc), used=sum(real) / sum(held), preempt=preempt) def read_cost(n=512, reps=200): rng = np.random.default_rng(0) Kc = rng.standard_normal((HEADS, n, HD)).astype(np.float32) # one floor, contiguous pool = rng.standard_normal((HEADS, 4096, PAGE, HD)).astype(np.float32) pages = list(rng.permutation(4096)[: n // PAGE]) # scattered pages q = rng.standard_normal((HEADS, 1, HD)).astype(np.float32) def contiguous(): return q @ Kc.transpose(0, 2, 1) def paged(): return q @ pool[:, pages].reshape(HEADS, -1, HD).transpose(0, 2, 1) out = [] for f in (contiguous, paged): f() ts = [] for _ in range(reps): t = time.perf_counter(); f(); ts.append(time.perf_counter() - t) out.append(sorted(ts)[reps // 2] * 1e6) return out if __name__ == "__main__": worst, used, toks = same_answer() print("1) Same answer with pages?") print(f" 3 chats, prompts of 40, 7 and 23 tokens, then 30 words each") print(f" biggest difference in any number: {worst:.1e}") print(f" pages in use: {used} x {PAGE} = {used*PAGE} token slots for {toks} tokens\n") reqs = request_stream() room = 4096 print(f"2) The same 32 chats, notebook room for {room:,} tokens " f"({room*KV_BYTES_PER_TOKEN/1e6:.0f} MB at {KV_BYTES_PER_TOKEN//1024} KB/token), longest chat allowed 1,024") r, p = serve(reqs, room, "reserve"), serve(reqs, room, "paged") print(f"{'':36}{'reserve 1,024':>14}{'16-token pages':>16}") for name, k, f in [("chats in the batch, average", "avg", "{:.1f}"), ("chats in the batch, peak", "peak", "{:d}"), ("room holding real tokens", "used", "{:.0%}"), ("decode steps to serve all 32", "steps", "{:,d}"), ("chats sent back (preempted)", "preempt", "{:d}")]: print(f"{name:36}{f.format(r[k]):>14}{f.format(p[k]):>16}") print(f" -> {p['avg']/r['avg']:.1f}x more chats per step, {r['steps']/p['steps']:.1f}x fewer steps\n") c, pg = read_cost() print("3) What pages cost: read one floor of a 512-token notebook (12 heads)") print(f" contiguous: {c:.0f} us 32 scattered pages: {pg:.0f} us ({pg/c:.1f}x)")