""" engine.py: the Word Factory used in Part 7 (same as Part 3's two_phases.py). GPT-2-small shape (12 floors, width 768, 12 heads), random weights, NumPy, CPU. One trip through the floors can carry tokens for several users at once: the big tables are shared, each user's attention reads only their own notebook. """ import numpy as np D, LAYERS, HEADS, D_FF, VOCAB = 768, 12, 12, 3072, 256 HD = D // HEADS KV_BYTES_PER_TOKEN = 2 * LAYERS * D * 4 # K and V, 12 floors, float32 = 72 KB def norm(x): # x: (D, T) return (x - x.mean(0)) / np.sqrt(x.var(0) + 1e-5) def gelu(x): return 0.5 * x * (1 + np.tanh(0.7978845608 * (x + 0.044715 * x * x * x))) class Engine: def __init__(self, seed=0): rng = np.random.default_rng(seed) w = lambda *s: (rng.standard_normal(s) * 0.02).astype(np.float32) self.emb = w(VOCAB, D) self.layers = [dict(qkv=w(3 * D, D), out=w(D, D), up=w(D_FF, D), down=w(D, D_FF)) for _ in range(LAYERS)] def new_user(self, max_len): """A notebook reserved up front for max_len tokens (Part 3 style).""" return dict(K=np.zeros((LAYERS, HEADS, max_len, HD), np.float32), V=np.zeros((LAYERS, HEADS, max_len, HD), np.float32), n=0) def trip(self, x, segments): """x: (D, T) for T tokens; segments: [(user, n_tokens), ...]""" 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 qi = q[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) u["K"][i, :, s:e] = k[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) u["V"][i, :, s:e] = v[:, col:col + t].reshape(HEADS, HD, t).transpose(0, 2, 1) Kc, Vc = u["K"][i, :, :e], u["V"][i, :, :e] 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 prefill(self, user, ids): return self.trip(self.emb[ids].T.copy(), [(user, len(ids))]) def decode_step(self, users, tok=7): x = np.repeat(self.emb[tok][:, None], len(users), 1) return self.trip(x, [(u, 1) for u in users]) def request_stream(n=32, seed=3, prompt=32, lo=8, hi=480): """n chat requests. Prompt length fixed; answer lengths long-tailed like real chats: most short, a few long (lognormal, clipped to lo..hi tokens).""" rng = np.random.default_rng(seed) outs = np.clip(rng.lognormal(mean=4.3, sigma=0.9, size=n), lo, hi).astype(int) return [dict(id=i, prompt=prompt, out=int(o)) for i, o in enumerate(outs)]