""" batching.py: the same 32 chat requests served two ways, on the same factory. STATIC: fill 8 seats, run the batch until its LONGEST answer is done, then refill. Finished users keep their seat (padding). CONTINUOUS: after EVERY step, finished users leave and waiting users join. All 32 requests are waiting at time 0. Every number is a real, timed run. """ import time import numpy as np from engine import Engine, request_stream, VOCAB SEATS = 8 def run(mode, reqs, eng, rng): queue = [dict(r) for r in reqs] active, t0, steps, seat_steps, useful = [], time.perf_counter(), 0, 0, 0 first, done = {}, {} while queue or active: # who gets a seat this step? 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"], rng.integers(0, VOCAB, r["prompt"])) r["made"] = 0 active.append(r) eng.decode_step([r["u"] for r in active]) 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 = [] # whole batch leaves together 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, useful=useful, 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__": 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() eng.decode_step([eng.new_user(4) for _ in range(SEATS)]) # warm-up res = {} for mode in ["static", "continuous"]: res[mode] = run(mode, reqs, eng, np.random.default_rng(7)) s, c = res["static"], res["continuous"] rows = [("decode steps", "steps", "{:,.0f}"), ("seats doing real work", "busy", "{:.0%}"), ("wall time (s)", "wall", "{:.1f}"), ("answer tokens/s", "tps", "{:.1f}"), ("avg wait for first word (s)", "first_avg", "{:.1f}"), ("p90 wait for first word (s)", "first_p90", "{:.1f}"), ("avg time to finish (s)", "fin_avg", "{:.1f}"), ("p90 time to finish (s)", "fin_p90", "{:.1f}")] print(f"{'':30}{'static':>12}{'continuous':>12}") for name, k, f in rows: print(f"{name:30}{f.format(s[k]):>12}{f.format(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]):.1f} s, " f"continuous {np.mean([c['done'][i] for i in short]):.1f} s")