diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 2c0af96c..85beb7b0 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -36,7 +36,8 @@ With a layer split, the engine options go into the config's `args`: | Option | What it does | | --- | --- | | `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | -| `--batch-groups G` | with a layer split: the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | +| `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | +| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by @@ -128,7 +129,7 @@ counter-based draw (Philox(seed, position)). - A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk boundary, and not for pictures. - Admissions are one at a time: two new long prompts are read one after the other. -- `--batch-groups` needs every stage on its own GPU; a pipelined slot is not kept as a conversation cache. +- `--batch-groups` needs every stage on its own GPU. A pipelined slot is a conversation cache again (0.1.41): a request left alone in its slot goes back to the solo path with its drafts, as on one GPU. - The slot sessions take VRAM (above) and, with KV streaming, pinned RAM. ## Measured diff --git a/serve/server.py b/serve/server.py index f93826fe..553f440c 100644 --- a/serve/server.py +++ b/serve/server.py @@ -707,7 +707,10 @@ class StrataEngine: if asked and self.batch != asked: print(f"[strata] parallel requests: {asked} asked, the engine runs {self.batch or 'one at a time'} " "(its log says why)", flush=True) - groups = int(args[args.index("--batch-groups") + 1]) if "--batch-groups" in args else 1 + _bg = args[args.index("--batch-groups") + 1] if "--batch-groups" in args else "default" + # no `--batch-groups` (the default on a layer split) or `auto`: the engine picks the groups and says so + # (INFO batch_groups=G); a number is the group count asked for (1 = off) + groups = int(self.info.get("batch_groups") or 1) if _bg in ("auto", "default") else int(_bg) groups = groups if self.batch and groups > 0 and self.batch % groups == 0 else 1 gs = self.batch // groups if self.batch else 0 # slots in the order that spreads requests over the pipeline's groups first: 0, gs, 2gs, .., 1, gs+1, .. @@ -5211,6 +5214,10 @@ class Server(ThreadingHTTPServer): # On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on # either one (a forgotten second start of run-.bat). Without it the second start fails loudly instead. allow_reuse_address = os.name != "nt" + # socketserver listens with a backlog of 5: a burst of 30-40 clients at once got "connection reset by peer" on the + # first ones (measured on 4 x R9700, also with one request at a time); the requests wait in the server, not the kernel + # (STRATA_HTTP_BACKLOG overrides it) + request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256)) def handle_error(self, request, client_address): if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace diff --git a/serve/test_parallel.py b/serve/test_parallel.py index bd834bea..2485e801 100644 --- a/serve/test_parallel.py +++ b/serve/test_parallel.py @@ -25,7 +25,8 @@ FAKE_BATCH = r'''import queue, sys, threading, time args = sys.argv[1:] slots = int(args[args.index("--batch") + 1]) if "--batch" in args else 0 fit = int(args[args.index("--fit") + 1]) if "--fit" in args else slots -fail = "--fail-window" in args # #997: the first window over two slots fails +fail = "--fail-window" in args +groups = int(args[args.index("--says-groups") + 1]) if "--says-groups" in args else 0 # INFO batch_groups=G (--batch-groups auto) # #997: the first window over two slots fails STEP = 0.02 CH = 32 lines, stop = queue.Queue(), threading.Event() @@ -39,7 +40,7 @@ def reader(): lines.put(None) threading.Thread(target=reader, daemon=True).start() print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") + - (" slot_cache=1" if "--slotcache" in args else ""), flush=True) + (" slot_cache=1" if "--slotcache" in args else "") + (f" batch_groups={groups}" if groups > 1 else ""), flush=True) print("READY 4096 stop", flush=True) LONG = list(b"LONGREPLY") def continued(ids): # (the whole reply, how much of it the prompt already ends with: a request continued) @@ -245,7 +246,7 @@ class PickSlot(unittest.TestCase): class ParallelService(unittest.TestCase): """The real StrataEngine and Service over HTTP, the fake engine behind them.""" - def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False): + def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False, says_groups=0, more=()): import serve.server as server self.tmp = tempfile.TemporaryDirectory() script = Path(self.tmp.name) / "fake_strata.py" @@ -256,6 +257,8 @@ class ParallelService(unittest.TestCase): extra += ["--slotcache"] if slot_cache else [] extra += ["--fail-window"] if fail else [] extra += ["--reuse"] if reuse else [] + extra += ["--says-groups", str(says_groups)] if says_groups else [] + extra += list(more) with mock.patch.object(server.subprocess, "Popen", lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)): self.engine = StrataEngine("strata", extra) @@ -296,6 +299,45 @@ class ParallelService(unittest.TestCase): self.assertEqual(self.engine.batch, 2) self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2) + def test_batch_groups_auto_follows_the_engine(self): + """--batch-groups auto: the engine picks the groups and says so (INFO batch_groups=G); the server spreads the + requests over those groups, and a plain number is read as before.""" + self.start(8, says_groups=4, more=["--batch-groups", "auto"]) + e = self.engine + self.assertEqual((e.batch, e.slot_groups), (8, 4)) + self.assertEqual(e.slot_group, [0, 0, 1, 1, 2, 2, 3, 3]) + self.assertEqual(e.slot_order[:4], [0, 2, 4, 6]) + self.tearDown(); self.httpd = self.engine = self.tmp = None + self.start(8, more=["--batch-groups", "auto"]) # an engine that reports none: one group + self.assertEqual(self.engine.slot_groups, 1) + self.tearDown(); self.httpd = self.engine = self.tmp = None + self.start(8, more=["--batch-groups", "2"]) + self.assertEqual(self.engine.slot_groups, 2) + self.tearDown(); self.httpd = self.engine = self.tmp = None + self.start(8, says_groups=4) # 0.1.41: no flag on a layer split = the engine's choice + self.assertEqual(self.engine.slot_groups, 4) + self.tearDown(); self.httpd = self.engine = self.tmp = None + self.start(8, says_groups=4, more=["--batch-groups", "1"]) # the opt-out + self.assertEqual(self.engine.slot_groups, 1) + + def test_a_burst_of_connections_is_not_reset(self): + """30-40 clients at once got "connection reset by peer" with the listen backlog of 5 (4 x R9700 burst): the + server listens with a deep backlog (STRATA_HTTP_BACKLOG, 256), so 60 simultaneous requests all get answers.""" + import serve.server as server + self.assertGreaterEqual(server.Server.request_queue_size, 64) + self.start(2) + errs, ok = [], [] + def one(i): + try: + self.chat(f"burst {i}", max_tokens=8) + ok.append(i) + except Exception as e: # noqa: BLE001 + errs.append(repr(e)) + th = [threading.Thread(target=one, args=(i,)) for i in range(60)] + for t in th: t.start() + for t in th: t.join() + self.assertEqual((len(ok), errs[:2]), (60, [])) + def test_stop_strings_in_a_batch_slot(self): """#454: a stop string cuts the answer in --batch mode too, and the slot is freed for the next request.""" self.start(2) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 8c14a550..433d3957 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -536,6 +536,8 @@ struct Options { /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. int batch_groups = 1; + bool batch_groups_set = false; ///< --batch-groups was given (a number or auto): no default then + bool batch_groups_auto = false; ///< --batch-groups auto (#417 stage 1): one group per stage of a layer split, if it divides --batch bool batch_mtp = false; ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot std::string spec_oracle; int spec_corrupt = 0; @@ -1784,7 +1786,12 @@ int main(int argc, char** argv) { else if (a == "--batch") o.batch = std::atoi(next("--batch")); else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch else if (a == "--trim-stage-weights") o.trim_stage_weights = true; - else if (a == "--batch-groups") o.batch_groups = std::atoi(next("--batch-groups")); + else if (a == "--batch-groups") { + const char* bgv = next("--batch-groups"); + o.batch_groups_set = true; + if (std::strcmp(bgv, "auto") == 0) o.batch_groups_auto = true; + else o.batch_groups = std::atoi(bgv); + } else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle"); else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt")); @@ -3884,6 +3891,21 @@ int main(int argc, char** argv) { o.batch = cap; } } + // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: + // 90 tok/s in one group, 136 in 2, 166 in 4). The most groups, at most one per stage, that divide the slots. + auto resolve_groups_auto = [&] { + // default (0.1.41): a layer split with --batch pipelines one group per stage; --batch-groups 1 opts out + if (!o.batch_groups_set && !stages.empty() && o.batch > 1) o.batch_groups_auto = true; + if (!o.batch_groups_auto) return; + int best = 1; + for (int d = 2; d <= (int) stages.size() + 1 && d <= o.batch; ++d) + if (o.batch % d == 0) best = d; + if (stages.empty()) best = 1; + o.batch_groups = best; + std::fprintf(stderr, "strata generate: --batch-groups auto: %d group%s of %d slot%s\n", best, best == 1 ? "" : "s", + o.batch / best, o.batch / best == 1 ? "" : "s"); + }; + if (o.batch > 0) resolve_groups_auto(); if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { std::fprintf(stderr, "strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " "one group\n", o.batch_groups, o.batch); @@ -3931,6 +3953,7 @@ int main(int argc, char** argv) { o.batch = 0; } else { o.batch = fit; + resolve_groups_auto(); // (the slots that fit may not be the ones asked for) if (o.batch_groups > 1 && o.batch % o.batch_groups != 0) o.batch_groups = 1; // the sessions' VRAM is the expert cache's: say what it costs (docs/BATCHING.md has the measured trade) std::fprintf(stderr, "strata generate: --batch %d: the slot sessions take %.2f GiB of VRAM on CUDA0 that the " @@ -8536,7 +8559,10 @@ int main(int argc, char** argv) { const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); std::printf("BDONE %d %lld %s %.1f\n", gi * GS + t, (long long) sl.produced, fin, ms); sl.active = false; - sl.cached = false; // the pipeline's pad rows: a pipelined slot is not reused as a cache + // a pipelined slot is a cache again (#857: a request left alone in its slot goes back to the solo path with its + // drafts): its state is final once its last window has left the last stage. A later group window whose pad + // row writes this slot clears the flag (below, where the group starts), so a stale state is never reused + sl.cached = o.prompt_cache > 0 && !sl.img; } else { sl.x = y; sl.p += 1; diff --git a/tools/serve_load.py b/tools/serve_load.py new file mode 100644 index 00000000..aa4be73d --- /dev/null +++ b/tools/serve_load.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Small load generator for the OpenAI-compatible server: C clients at once, each a different prompt. + + python3 tools/serve_load.py http://127.0.0.1:8080 --clients 1,2,4,8 --rounds 3 --max-tokens 256 + +For every client count it sends C streamed chat requests at the same moment (each prompt starts with its own nonce, so +the prompt cache cannot help), and reports per round and as medians: total tokens/s (all generated tokens over the +wall time of the burst), per-request tokens/s, time to first token (p50 / p95 over all requests of that count), and +the request latency (p50 / p95). With --save DIR it writes every answer, so a later run can be compared byte for +byte with `--compare DIR` (greedy answers of a request must not depend on who else ran). + +Standard library only. The prompts are fixed texts, so two runs of the tool send the same requests. +""" +import argparse, json, os, statistics, sys, threading, time, urllib.request + +TOPICS = [ + "the history of lighthouses and how their lenses worked", + "how a mechanical watch keeps time", + "why bridges are built as arches and as suspension spans", + "the water cycle and what a drought does to a river valley", + "how bread rises, from yeast to crust", + "the design of a medieval castle and why walls were stepped", + "how a transistor switches, explained for a curious teenager", + "the life of a honey bee colony through one year", +] + + +def prompt_for(i: int, words: int, nonce: str = "") -> str: + topic = TOPICS[i % len(TOPICS)] + return (f"[request {i}{nonce}] Write a clear, well organised essay of about {words} words on {topic}. " + f"Use plain prose, no lists.") + + +def one(url, key, model, i, words, max_tokens, res, extra, think, nonce=""): + body = {"model": model, "stream": True, "max_tokens": max_tokens, "temperature": 0, + "messages": [{"role": "user", "content": prompt_for(i, words, nonce)}]} + if not think: + body["reasoning_effort"] = "none" + body["chat_template_kwargs"] = {"enable_thinking": False} + body.update(extra) + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", + **({"Authorization": "Bearer " + key} if key else {})}) + t0 = time.perf_counter() + first, n, text = None, 0, [] + err = None + try: + with urllib.request.urlopen(req, timeout=900) as r: + for raw in r: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data:"): + continue + d = line[5:].strip() + if d == "[DONE]": + break + try: + j = json.loads(d) + except ValueError: + continue + for ch in j.get("choices", []): + dl = ch.get("delta", {}) + piece = (dl.get("content") or "") + (dl.get("reasoning_content") or "") + if piece: + if first is None: + first = time.perf_counter() - t0 + n += 1 # one SSE chunk = one token (the server flushes per token) + text.append(piece) + if j.get("usage"): + n = j["usage"].get("completion_tokens", n) + except Exception as e: # noqa: BLE001 + err = repr(e) + res[i] = {"first": first, "tokens": n, "total": time.perf_counter() - t0, "text": "".join(text), "err": err} + + +def pct(v, p): + v = sorted(v) + if not v: + return float("nan") + k = (len(v) - 1) * p + lo, hi = int(k), min(int(k) + 1, len(v) - 1) + return v[lo] + (v[hi] - v[lo]) * (k - lo) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("url") + ap.add_argument("--clients", default="1,2,4,8") + ap.add_argument("--rounds", type=int, default=3) + ap.add_argument("--max-tokens", type=int, default=256) + ap.add_argument("--words", type=int, default=800, help="the essay length asked for (longer = longer prompt? no: the answer)") + ap.add_argument("--model", default="strata") + ap.add_argument("--key", default=os.environ.get("STRATA_KEY", "")) + ap.add_argument("--nonce", default=str(int(time.time())), help="prefix of the per-request nonce (every round reads fresh prompts); '' = identical prompts every round; fix it to compare two runs") + ap.add_argument("--think", action="store_true") + ap.add_argument("--stagger", type=float, default=0.0, help="seconds between the starts of the clients of a burst") + ap.add_argument("--save", help="write every answer (clients/round/request) here") + ap.add_argument("--compare", help="compare every answer with the files a --save run wrote") + ap.add_argument("--json", help="write the table as JSON") + a = ap.parse_args() + extra = {} + out = [] + bad = 0 + for c in [int(x) for x in a.clients.split(",")]: + rows = [] + for rd in range(a.rounds): + res = {} + th = [] + t0 = time.perf_counter() + for i in range(c): + t = threading.Thread(target=one, args=(a.url, a.key, a.model, i, a.words, a.max_tokens, res, extra, a.think, f" {a.nonce}-{c}-{rd}" if a.nonce else "")) + t.start() + th.append(t) + if a.stagger: + time.sleep(a.stagger) + for t in th: + t.join() + wall = time.perf_counter() - t0 + toks = sum(r["tokens"] for r in res.values()) + errs = [r["err"] for r in res.values() if r["err"]] + firsts = [r["first"] for r in res.values() if r["first"] is not None] + tot = [r["total"] for r in res.values()] + per = [r["tokens"] / max(r["total"] - (r["first"] or 0), 1e-6) for r in res.values()] + rows.append({"wall": wall, "toks": toks, "tps": toks / wall, "first": firsts, "lat": tot, "per": per, "err": errs}) + if a.save: + d = os.path.join(a.save, f"c{c}", f"r{rd}") + os.makedirs(d, exist_ok=True) + for i, r in res.items(): + open(os.path.join(d, f"{i}.txt"), "w", encoding="utf-8").write(r["text"]) + if a.compare: + for i, r in res.items(): + p = os.path.join(a.compare, f"c{c}", f"r{rd}", f"{i}.txt") + if os.path.exists(p): + ref = open(p, encoding="utf-8").read() + if ref != r["text"]: + n = next((k for k, (x, y) in enumerate(zip(ref, r["text"])) if x != y), min(len(ref), len(r["text"]))) + print(f" DIFF c={c} round={rd} req={i}: first difference at char {n}") + bad += 1 + print(f"c={c} round={rd}: {toks} tokens in {wall:.1f}s = {toks / wall:.1f} tok/s total" + + (f" ERRORS {errs[:2]}" if errs else ""), flush=True) + allf = [x for r in rows for x in r["first"]] + alll = [x for r in rows for x in r["lat"]] + allp = [x for r in rows for x in r["per"]] + s = {"clients": c, "total_tps": statistics.median(r["tps"] for r in rows), + "per_req_tps": statistics.median(allp) if allp else float("nan"), + "first_p50": pct(allf, .5), "first_p95": pct(allf, .95), + "lat_p50": pct(alll, .5), "lat_p95": pct(alll, .95), "errors": sum(len(r["err"]) for r in rows)} + out.append(s) + print("\nclients total tok/s per-req tok/s first p50/p95 (s) latency p50/p95 (s) errors") + for s in out: + print(f"{s['clients']:>7} {s['total_tps']:>11.1f} {s['per_req_tps']:>13.1f} " + f"{s['first_p50']:>7.2f}/{s['first_p95']:<7.2f} {s['lat_p50']:>8.2f}/{s['lat_p95']:<8.2f} {s['errors']}") + if a.json: + json.dump(out, open(a.json, "w"), indent=1) + if a.compare: + print("compare:", "ALL IDENTICAL" if not bad else f"{bad} DIFFERENT") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main())