""" batching_gpu.py: Part 7's static vs continuous batching, on a GPU. Same factory (GPT-2-small shape: 12 floors, width 768, 12 heads, random weights), same 32 chat requests, same 8 seats, rewritten in PyTorch so it runs on CUDA (FP16). All 32 requests are waiting at time 0. Every number is a real, timed run. """ import time import numpy as np import torch D, LAYERS, HEADS, D_FF, VOCAB = 768, 12, 12, 3072, 256 HD = D // HEADS SEATS = 8 dev = "cuda" if torch.cuda.is_available() else "cpu" dt = torch.float16 if dev == "cuda" else torch.float32 def sync(): if dev == "cuda": torch.cuda.synchronize() def norm(x): # x: (T, D) return torch.nn.functional.layer_norm(x, (D,)) class Engine: def __init__(self, seed=0): g = torch.Generator().manual_seed(seed) w = lambda *s: (torch.randn(*s, generator=g) * 0.02).to(dev, dt) self.emb = w(VOCAB, D) self.layers = [dict(qkv=w(D, 3 * D), out=w(D, D), up=w(D, D_FF), down=w(D_FF, D)) for _ in range(LAYERS)] def new_user(self, max_len): return dict(K=torch.zeros(LAYERS, HEADS, max_len, HD, device=dev, dtype=dt), V=torch.zeros(LAYERS, HEADS, max_len, HD, device=dev, dtype=dt), n=0) @torch.no_grad() def trip(self, x, segments): """x: (T, D) for T tokens; segments: [(user, n_tokens), ...]""" for i, p in enumerate(self.layers): q, k, v = (norm(x) @ p["qkv"]).split(D, dim=1) # shared tables outs, col = [], 0 for u, t in segments: # per-user notebook s, e = u["n"], u["n"] + t hq = q[col:col + t].view(t, HEADS, HD).transpose(0, 1) u["K"][i, :, s:e] = k[col:col + t].view(t, HEADS, HD).transpose(0, 1) u["V"][i, :, s:e] = v[col:col + t].view(t, HEADS, HD).transpose(0, 1) o = torch.nn.functional.scaled_dot_product_attention( hq, u["K"][i, :, :e], u["V"][i, :, :e], is_causal=(t > 1 and s == 0)) outs.append(o.transpose(0, 1).reshape(t, D)) col += t x = x + torch.cat(outs) @ p["out"] x = x + torch.nn.functional.gelu(norm(x) @ p["up"], approximate="tanh") @ p["down"] for u, t in segments: u["n"] += t return x def prefill(self, user, ids): return self.trip(self.emb[ids], [(user, len(ids))]) def decode_step(self, users, tok=7): return self.trip(self.emb[tok].expand(len(users), D).contiguous(), [(u, 1) for u in users]) def request_stream(n=32, seed=3, prompt=32, lo=8, hi=480): 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)] def run(mode, reqs, eng, rng): queue = [dict(r) for r in reqs] active, steps, seat_steps, useful = [], 0, 0, 0 first, done = {}, {} sync(); t0 = time.perf_counter() while queue or active: if mode == "continuous" or not active: while queue and len(active) < SEATS: r = queue.pop(0) r["u"] = eng.new_user(r["prompt"] + r["out"] + 1) eng.prefill(r["u"], torch.as_tensor(rng.integers(0, VOCAB, r["prompt"]), device=dev)) r["made"] = 0 active.append(r) eng.decode_step([r["u"] for r in active]) sync(); now = time.perf_counter() - t0 steps += 1 seat_steps += SEATS for r in active: if r["made"] < r["out"]: r["made"] += 1 useful += 1 first.setdefault(r["id"], now) if r["made"] == r["out"]: done[r["id"]] = now if mode == "continuous": active = [r for r in active if r["made"] < r["out"]] elif all(r["made"] >= r["out"] for r in active): active = [] wall = time.perf_counter() - t0 fin = np.array([done[r["id"]] for r in reqs]) wait = np.array([first[r["id"]] for r in reqs]) return dict(wall=wall, steps=steps, busy=useful / seat_steps, tps=useful / wall, fin_avg=fin.mean(), fin_p90=np.percentile(fin, 90), first_avg=wait.mean(), first_p90=np.percentile(wait, 90), done=done) if __name__ == "__main__": name = torch.cuda.get_device_name(0) if dev == "cuda" else "CPU" print(f"device: {name}, {str(dt).replace('torch.', '')}, torch {torch.__version__}") reqs = request_stream() outs = np.array([r["out"] for r in reqs]) print(f"32 requests, prompt 32 tokens each; answer lengths: " f"min {outs.min()}, median {int(np.median(outs))}, mean {outs.mean():.0f}, max {outs.max()}") print(f"total answer tokens to produce: {outs.sum():,}\n") eng = Engine() for _ in range(20): # warm-up eng.decode_step([eng.new_user(4) for _ in range(SEATS)]) sync() res = {m: run(m, reqs, eng, np.random.default_rng(7)) for m in ["static", "continuous"]} s, c = res["static"], res["continuous"] rows = [("decode steps", "steps", "{:,.0f}"), ("seats doing real work", "busy", "{:.0%}"), ("wall time (s)", "wall", "{:.2f}"), ("answer tokens/s", "tps", "{:,.0f}"), ("avg wait for first word (ms)", "first_avg", "ms"), ("p90 wait for first word (ms)", "first_p90", "ms"), ("avg time to finish (s)", "fin_avg", "{:.2f}"), ("p90 time to finish (s)", "fin_p90", "{:.2f}")] print(f"{'':30}{'static':>12}{'continuous':>12}") for label, k, f in rows: fmt = (lambda v: f"{v*1e3:,.0f}") if f == "ms" else f.format print(f"{label:30}{fmt(s[k]):>12}{fmt(c[k]):>12}") print(f"\nspeed-up in answer tokens/s: {c['tps']/s['tps']:.2f}x") short = [r["id"] for r in reqs if r["out"] <= np.median(outs)] print(f"shorter half of requests, avg time to finish: static {np.mean([s['done'][i] for i in short]):.2f} s, " f"continuous {np.mean([c['done'][i] for i in short]):.2f} s")