docs/BATCHING.md: reading beside the decoding slots, and what it measured
The opt-in's section: how the read and the windows share the GPUs, the doorbell thread, the give-way at a chunk, where
the mode is off. Measured against main (a0116b27) on 2x RTX 5090 in one window (main, this, this, main): the stops,
the streams' rate during the reads with the same answers every run, the joining prompts' TTFT, a question during a
read, the same randomised load on both, the doorbell thread's first wait as an A/B; 16 GB cards on each side; a weaker
host as well in #1906's shape; the default path's check; text equality.
tools/piped_read_join_bench.py, the client that measured it, is #2050's, unchanged (the same file as there).
This commit is contained in:
1 parent
34b726e090
commit
6c5c382b94
2 files changed
+322
No files matched your search
@@ -141,6 +141,102 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske
|
||||
- Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`).
|
||||
- A client that disconnects stops its slot (`BSTOP`); the others go on.
|
||||
|
||||
## Reading a prompt beside pipelined groups (experimental, opt-in)
|
||||
|
||||
With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is
|
||||
read, however long it is (#1906). One GPU does not have this problem: there the slots decode between the prompt's
|
||||
chunks for `STRATA_BATCH_DECODE_SHARE` x the chunk's time.
|
||||
|
||||
`STRATA_PIPED_CONCURRENT=1` reads a prompt on a thread of its own while the slot groups keep decoding through the
|
||||
pipeline, instead of stopping them: the prompt's chunks and the slots' windows run on the same GPUs at once, on their
|
||||
own streams (the windows' at the device's highest priority on CUDA; `STRATA_PIPED_CONCURRENT_PRIO=0` keeps the default),
|
||||
so the slots never wait for the read and the read is one run with no drain inside it.
|
||||
|
||||
- The prompt's K/V goes to the main sessions and the slots' to their own, so they do not touch each other's state. The
|
||||
n-gram (PLE) table both of them read is locked. The adaptive VRAM tier stands still during the read: its round lands
|
||||
before the read and none starts while it runs.
|
||||
- The VRAM expert slots the prompt path borrows are lent before the read and refilled after it, with nothing in flight;
|
||||
in between the slots' windows compute those experts on the CPU.
|
||||
- The slots' doorbells are served on a thread of their own during the read, which makes no CUDA call. A CUDA call can
|
||||
wait for the driver's lock while its holder waits for the GPU - a free, or the module the first kernel of a new shape
|
||||
loads - and a window on that GPU waits for its doorbell (issue #31's pattern: two such hangs were found and read from
|
||||
the engine's stall dumps while this was built). The MTP drafter's prompt buffers and the prompt path's pinned upload
|
||||
slots are sized before the read, so its thread allocates and frees nothing. Between windows the doorbell thread waits
|
||||
for the next launch, which wakes it (a timed sleep is a whole timer tick on Windows, up to 15.6 ms). A window that
|
||||
will not finish is still found (its graph ended with a layer still to ring, or no layer rang for 20 s), and the stall
|
||||
watchdog stays on for the whole read.
|
||||
- A waiting shorter request takes over at the read's next chunk (`BYIELD`), also when no slot decodes: the run ends
|
||||
there, the pipeline is drained and the part read waits in a slot, as off the pipeline. A read nobody waits for is not cut.
|
||||
- Off, said once, where the read's thread would allocate or free (`STRATA_PREFILL_HELP=1`, `STRATA_SPLIT_MTP_BATCH=1`),
|
||||
where serving a doorbell makes a CUDA call (`--pcie-mode dma`, `STRATA_FS_SLOTS`, the helper caches
|
||||
`--expert-cache-device1..3`), and with an expert source that hands out buffers it recycles (the GGUF in place, an
|
||||
unbuffered source, `STRATA_IO_PREFETCH`): the experts come from the RAM arena or the mapped file. A prompt with
|
||||
pictures is read the usual way.
|
||||
|
||||
One log line per read (`strata batch: read N tokens on a thread of its own in X ms (concurrent, to Q of T); the slots
|
||||
decoded R rows meanwhile (S rows/s; stage k: W windows, H ms host each)`). Built for CUDA and HIP (HIP keeps the default
|
||||
stream priority, and is not run on a GPU here); SYCL does not have it.
|
||||
|
||||
Measured on 2x RTX 5090 (Swift 1.5 IQ3_S, split 25, `--batch 6 --batch-groups 2`, resident experts, k8v4, 262K,
|
||||
`--kv-resident 32768`, the engine-default decode share): main (`a0116b27`) against this mode, a fresh engine per arm in
|
||||
the order main, this mode, this mode, main (`tools/piped_read_join_bench.py`; the fixed-prompt rows send the same four
|
||||
stream prompts every run, so the streams' answers and work are the same):
|
||||
|
||||
| | main | `STRATA_PIPED_CONCURRENT=1` |
|
||||
| --- | ---: | ---: |
|
||||
| 64K + 32K cold prompts beside four streams: longest stop of a stream | 11.9 s | 0.77-0.84 s |
|
||||
| ... the streams' tokens meanwhile | 289-291 | 1,411-1,679 |
|
||||
| ... the prompts' TTFT | 6.8 / 5.8-5.9 s | 8.1-8.2 / 8.2-8.3 s |
|
||||
| the same with fixed stream prompts: the streams' rate while the prompts are read | 2-3 tok/s | 85-92 tok/s |
|
||||
| ... the streams finish at | 26.1-27.1 s | 24.6-25.3 s |
|
||||
| ... GPU utilization while the prompts are read | 75-86% | 85-91% |
|
||||
| a one-line question 1 s into a cold 45K read, nothing decoding: its TTFT | 5.7-5.9 s | 1.9 s |
|
||||
| ... and the 45K prompt's own TTFT | 6.2-6.4 s | 7.4-7.5 s |
|
||||
|
||||
The joining prompts pay for the GPU time the streams now get. Over a whole run with the same work, the streams
|
||||
finished 5-8% sooner (6.4% on average); with prompts that change from run to run (the bench's), the run's token rate
|
||||
varies more than that between runs. Between windows the doorbell thread first slept 50 us, which is a whole timer
|
||||
tick on Windows: the same build with `STRATA_TEST_BELL_SLEEP_US=50` gave the streams 64-67 tok/s during the reads
|
||||
instead of 85-92.
|
||||
|
||||
The same randomised load (`soak`: three streams, cold joins of 4-64K, short questions, follow-ups of earlier joins,
|
||||
clients leaving mid-read and mid-answer; 5 minutes, the same seed) on main and in this mode: 167 and 180 requests
|
||||
answered; the longest gap inside a stream 9.8 and 1.0 s (90th percentile 8.5 and 0.7 s); the joins' TTFT median 3.8
|
||||
and 4.6 s. A request that comes during a read still waits for it, unless its prompt is under half as long (`BYIELD`).
|
||||
|
||||
A 16 GB card on each side (`--vram-reserve-mib 16600 --kv-resident 16384`, the same flags otherwise):
|
||||
|
||||
| | main | this mode |
|
||||
| --- | ---: | ---: |
|
||||
| fixed stream prompts, 64K + 32K joining: the streams' rate while the prompts are read | 0.9 tok/s | 52.9 tok/s |
|
||||
| ... the streams finish at | 70.6 s | 63.8 s |
|
||||
| ... the prompts' TTFT | 9.5 / 10.1 s | 15.8 / 21.1 s |
|
||||
| a one-line question 1 s into a cold 45K read: its TTFT | 7.3 s | 3.8 s |
|
||||
| the 45K prompt read alone | 7.33 s | 7.25 s |
|
||||
|
||||
A weaker host as well (16 GB cards, the experts from the mapped file, AVX2 expert kernels, 6 pool workers), in #1906's
|
||||
shape (`--batch 2 --batch-groups 2`): one stream decoding while another's cold prompt is read:
|
||||
|
||||
| cold prompt | main: the stream's longest stop / tok/s meanwhile / the prompt's TTFT | this mode |
|
||||
| --- | ---: | ---: |
|
||||
| 64K | 11.1 s / 2.4 / 10.9 s | 0.41 s / 25.7 / 11.7 s |
|
||||
| 127K | 20.3 s / 1.5 / 19.9 s | 0.64 s / 32.7 / 20.7 s |
|
||||
|
||||
So the cost is the joining prompt's: +4-7% beside one stream, +20-45% beside four on these cards, and +67-109% beside
|
||||
four on 16 GB cards, where the streams' windows take a larger share of the GPU.
|
||||
|
||||
**Checked:** with the variable unset this build gives main's tokens (six greedy answers' SHA-256 equal in two engine
|
||||
starts each, `--prompt-cache 0 --adapt-swaps 0 --pcie-frac 0`) at main's speed. In this mode, 25 minutes of the
|
||||
randomised load above (also on `--batch 2`): about 760 requests, 340 concurrent reads and 88 give-ways, with no hang, no
|
||||
error and no stall report.
|
||||
|
||||
**Text equality** (`batch_interleave_test.py --long 40000` with its exact settings, `--batch 4 --batch-groups 2`, no
|
||||
conversation cache): this test is not reproducible run to run on this PC even for main (A differed from its solo tokens
|
||||
at token 142 in one run of two). In this mode every request equaled its solo tokens in two runs of three - D giving way
|
||||
at its first chunk (`YIELDED 2 2048`), E admitted meanwhile, D going on and A going back to the solo path included,
|
||||
which main does not do on this path (D never gives way there); the third run had B off at token 74, a near tie that
|
||||
flips on main as well. Greedy only; other GPU pairs, three or more stages and sampled decoding not measured.
|
||||
|
||||
## The VRAM expert tier keeps adapting in batch windows
|
||||
|
||||
Batch windows count which experts they route to, and every `--adapt-every` windows (default 4) the engine swaps the
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Decoding streams while long cold prompts join: how smooth the streams stay, and what the joining prompt pays.
|
||||
|
||||
Runs against a running `serve/server.py` (OpenAI API). N streams decode long greedy answers (thinking off); after a
|
||||
delay one or two long cold prompts join. Every streamed token's arrival is timed on the client. Reported per scenario:
|
||||
|
||||
joiner_ttft_s the joining prompt's time to first token
|
||||
worst_max_gap_s the longest time any decoding stream received no token during the join window
|
||||
mean_stalled_s per stream, the sum of gaps above 0.5 s during the window (mean over the streams)
|
||||
stream_tokens_during_join tokens the decoding streams received from the first joiner's arrival to the last
|
||||
joiner's first token + 1 s
|
||||
aggregate_tok_s the streams' tokens / the run's wall time (throughput of the whole run)
|
||||
|
||||
Two scenarios without decoding streams (#1504's test): `followup` reads a cold 45K prompt alone and sends a short
|
||||
prompt 1 s later (followup_ttft_s: how long the short one waits behind the read; long_ttft_s: what the read pays);
|
||||
`read_alone` is the same read without the follow-up (what the read costs by itself).
|
||||
|
||||
The prompts are synthetic: the joiners are text from this repository's own files (src, include, serve, tools, docs), so
|
||||
they route to most experts the way real code and tool output do; a joiner never repeats an earlier prompt (the
|
||||
conversation cache would turn it into a warm read). `--determinism` instead sends fixed greedy prompts and prints the
|
||||
SHA-256 of each answer (to compare two builds' output tokens).
|
||||
|
||||
python tools/piped_read_join_bench.py --port 8080 --out join.json
|
||||
python tools/piped_read_join_bench.py --port 8080 --scenarios two_joiners,followup --repeat 3
|
||||
python tools/piped_read_join_bench.py --port 8080 --determinism
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CODING = ["Write a Python function that parses an INI file into nested dicts, with tests. Explain each step.",
|
||||
"Implement a thread-safe LRU cache in C++ with a short explanation of the design and its complexity.",
|
||||
"Explain, with code, how to stream a large CSV file in Go and aggregate per-key statistics.",
|
||||
"Write a TypeScript debounce and throttle pair with tests and explain where each one fits."]
|
||||
DETERMINISM = ["Count from 1 to 40, comma separated.", "List the planets of the solar system in order, one per line.",
|
||||
"Write the first 12 Fibonacci numbers.", "Explain in three sentences what a hash map is.",
|
||||
'Translate "good morning, how are you" into French, German and Spanish.',
|
||||
"Write a haiku about compilers."]
|
||||
# name -> the joins (delay s, size in K tokens) beside decoding streams, or (size, follow-up delay s) with none decoding
|
||||
SCENARIOS = {"cold32k": [(6, 32)], "cold64k": [(6, 64)], "two_joiners": [(6, 64), (12, 32)],
|
||||
"followup": (45, 1.0), "read_alone": (45, 0)}
|
||||
_FILES = []
|
||||
|
||||
|
||||
def corpus(chars, offset):
|
||||
"""About `chars` characters of this repository's own files, from the `offset`-th file on (at most 60,000 each)."""
|
||||
if not _FILES:
|
||||
for sub, pat in (("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py"),
|
||||
("docs", "*.md")):
|
||||
_FILES.extend(sorted((ROOT / sub).rglob(pat)))
|
||||
parts, n, i = [], 0, offset
|
||||
while n < chars:
|
||||
p = _FILES[i % len(_FILES)]
|
||||
i += 1
|
||||
text = p.read_text(encoding="utf-8", errors="replace")[:60000]
|
||||
parts.append("=== %s ===\n%s\n" % (p.relative_to(ROOT).as_posix(), text))
|
||||
n += len(parts[-1])
|
||||
return "".join(parts)[:chars]
|
||||
|
||||
|
||||
def request(content, max_tokens, model):
|
||||
"""One streamed greedy chat request with thinking off."""
|
||||
return json.dumps({"model": model, "messages": [{"role": "user", "content": content}], "temperature": 0,
|
||||
"max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True},
|
||||
"chat_template_kwargs": {"enable_thinking": False}}).encode()
|
||||
|
||||
|
||||
def stream(port, raw, timeout=1800):
|
||||
"""-> (token arrival times, text, usage, the time the request was sent)"""
|
||||
c = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout)
|
||||
ts, text, usage = [], [], None
|
||||
t0 = time.monotonic()
|
||||
c.request("POST", "/v1/chat/completions", raw, {"Content-Type": "application/json", "Connection": "close"})
|
||||
r = c.getresponse()
|
||||
if r.status != 200:
|
||||
raise RuntimeError("HTTP %d" % r.status)
|
||||
while True:
|
||||
line = r.readline(1 << 20)
|
||||
if not line:
|
||||
break
|
||||
if not line.startswith(b"data:"):
|
||||
continue
|
||||
data = line[5:].strip()
|
||||
if data == b"[DONE]":
|
||||
break
|
||||
item = json.loads(data)
|
||||
if item.get("usage"):
|
||||
usage = item["usage"]
|
||||
for ch in item.get("choices") or []:
|
||||
d = (ch.get("delta") or {}).get("content")
|
||||
if d:
|
||||
ts.append(time.monotonic())
|
||||
text.append(d)
|
||||
c.close()
|
||||
return ts, "".join(text), usage or {}, t0
|
||||
|
||||
|
||||
def pct(v, p):
|
||||
v = sorted(v)
|
||||
return v[min(len(v) - 1, max(0, int(round(p / 100 * (len(v) - 1)))))] if v else 0
|
||||
|
||||
|
||||
def smooth(ts, lo, hi):
|
||||
"""One stream's arrivals in [lo, hi]: tokens, the longest and p99 gap, and the time in gaps above 0.5 s."""
|
||||
inside = [t for t in ts if lo <= t <= hi]
|
||||
gaps = [b - a for a, b in zip(ts, ts[1:]) if b >= lo and a <= hi]
|
||||
return {"tokens": len(inside), "max_gap_s": round(max(gaps or [0]), 3), "p99_gap_s": round(pct(gaps, 99), 3),
|
||||
"stalled_s": round(sum(g for g in gaps if g > 0.5), 3)}
|
||||
|
||||
|
||||
def scenario(port, model, name, n, joins, max_tokens, tag):
|
||||
"""`n` streams decode; each join (delay s, size in K tokens) then sends a cold prompt of this repository's text."""
|
||||
events, joined = {}, {}
|
||||
|
||||
def decode(i):
|
||||
content = "Stream %s-%s-%d. %s" % (tag, name, i, CODING[i % len(CODING)])
|
||||
events[i] = stream(port, request(content, max_tokens, model))[0]
|
||||
|
||||
def join(k, delay, size):
|
||||
time.sleep(delay)
|
||||
text = corpus(int(size * 1024 * 3.3), 7 * size + k + 131 * len(name))
|
||||
content = "Join %s-%s-%d.\n%s\nName the file that defines the class above in one line." % (tag, name, k, text)
|
||||
ts, _, usage, t0 = stream(port, request(content, 64, model))
|
||||
joined[k] = {"sent": t0, "first": ts[0] if ts else None, "usage": usage}
|
||||
|
||||
t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=decode, args=(i,)) for i in range(n)]
|
||||
threads += [threading.Thread(target=join, args=(k, d, size)) for k, (d, size) in enumerate(joins)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
lo = min(v["sent"] for v in joined.values())
|
||||
hi = max(v["first"] for v in joined.values()) + 1.0
|
||||
per = [smooth(ts, lo, hi) for _, ts in sorted(events.items())]
|
||||
ends = [ts[-1] for ts in events.values() if ts]
|
||||
joins_in_order = [v for _, v in sorted(joined.items())]
|
||||
return {"joiner_ttft_s": [round(v["first"] - v["sent"], 3) for v in joins_in_order],
|
||||
"joiner_prompt_tokens": [v["usage"].get("prompt_tokens") for v in joins_in_order],
|
||||
"joiner_cached_tokens": [(v["usage"].get("prompt_tokens_details") or {}).get("cached_tokens")
|
||||
for v in joins_in_order],
|
||||
"worst_max_gap_s": max(p["max_gap_s"] for p in per),
|
||||
"mean_stalled_s": round(statistics.mean(p["stalled_s"] for p in per), 3),
|
||||
"stream_tokens_during_join": sum(p["tokens"] for p in per),
|
||||
"aggregate_tok_s": round(sum(len(t) for t in events.values()) / (max(ends) - t0), 1),
|
||||
"streams": per}
|
||||
|
||||
|
||||
def alone(port, model, name, size, follow, tag):
|
||||
"""A cold prompt of `size` K tokens with nothing decoding; with `follow`, a short prompt `follow` s after it."""
|
||||
got = {}
|
||||
|
||||
def long_read():
|
||||
text = corpus(int(size * 1024 * 3.3), 11 * size + 131 * len(name))
|
||||
content = "Read %s-%s.\n%s\nName the file that defines the class above in one line." % (tag, name, text)
|
||||
ts, _, usage, t0 = stream(port, request(content, 64, model))
|
||||
got["long"] = (t0, ts[0] if ts else None, usage)
|
||||
|
||||
def short():
|
||||
time.sleep(follow)
|
||||
content = "Follow-up %s-%s: what is 17 x 23? Reply with the number only." % (tag, name)
|
||||
ts, _, usage, t0 = stream(port, request(content, 16, model))
|
||||
got["short"] = (t0, ts[0] if ts else None, usage)
|
||||
|
||||
threads = [threading.Thread(target=long_read)] + ([threading.Thread(target=short)] if follow else [])
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
out = {"long_ttft_s": round(got["long"][1] - got["long"][0], 3),
|
||||
"long_prompt_tokens": got["long"][2].get("prompt_tokens")}
|
||||
if follow:
|
||||
out["followup_ttft_s"] = round(got["short"][1] - got["short"][0], 3)
|
||||
out["followup_prompt_tokens"] = got["short"][2].get("prompt_tokens")
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8080)
|
||||
ap.add_argument("--model", default=None, help="default: the server's own model id")
|
||||
ap.add_argument("--streams", type=int, default=4)
|
||||
ap.add_argument("--max-tokens", type=int, default=2048)
|
||||
ap.add_argument("--scenarios", default="cold32k,cold64k,two_joiners",
|
||||
help="comma-separated: " + ", ".join(SCENARIOS))
|
||||
ap.add_argument("--repeat", type=int, default=1, help="runs of each scenario (each with its own cold prompts)")
|
||||
ap.add_argument("--out")
|
||||
ap.add_argument("--determinism", action="store_true")
|
||||
a = ap.parse_args()
|
||||
tag = time.strftime("%H%M%S")
|
||||
if a.model is None:
|
||||
c = http.client.HTTPConnection("127.0.0.1", a.port, timeout=30)
|
||||
c.request("GET", "/v1/models")
|
||||
a.model = json.loads(c.getresponse().read())["data"][0]["id"]
|
||||
c.close()
|
||||
if a.determinism:
|
||||
rows = []
|
||||
for p in DETERMINISM:
|
||||
_, text, usage, _ = stream(a.port, request(p, 128, a.model))
|
||||
rows.append({"prompt_sha256": hashlib.sha256(p.encode()).hexdigest()[:12],
|
||||
"answer_sha256": hashlib.sha256(text.encode()).hexdigest(),
|
||||
"tokens": usage.get("completion_tokens")})
|
||||
print(json.dumps(rows, indent=1))
|
||||
return
|
||||
out = {}
|
||||
for rep in range(a.repeat):
|
||||
for name in a.scenarios.split(","):
|
||||
spec, run_tag = SCENARIOS[name], "%s.%d" % (tag, rep)
|
||||
key = name if a.repeat == 1 else "%s#%d" % (name, rep + 1)
|
||||
if isinstance(spec, tuple):
|
||||
out[key] = alone(a.port, a.model, name, spec[0], spec[1], run_tag)
|
||||
else:
|
||||
out[key] = scenario(a.port, a.model, name, a.streams, spec, a.max_tokens, run_tag)
|
||||
print(json.dumps({"scenario": key, **{k: v for k, v in out[key].items() if k != "streams"}}), flush=True)
|
||||
time.sleep(3)
|
||||
if a.out:
|
||||
Path(a.out).write_text(json.dumps(out, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user