R1/R3: tools/research_run.py, docs/RESEARCH_RUNS.md (measured numbers), DETAILS.md strata_prefix section

This commit is contained in:
Niko1221 committed 2026-10-07 00:01:12 +02:00
1 parent 13d14a4944
commit feccbfe32f
4 files changed
+307

No files matched your search

+14
View File
@@ -797,6 +797,20 @@ follows the reused prefix (or the root) is read in one run, and its session is n
It still starts from a checkpoint it matches, and still saves the system-prompt root when that reaches
`--prompt-cache-root`. Without the field (or with `true`) nothing changes.
**One long document, many questions: a pinned shared prefix (opt-in, 0.1.40.2, [RESEARCH_RUNS.md](RESEARCH_RUNS.md)).**
A request can say where the document ends: `"strata_prefix": {"messages": 1}` (the first message is the document),
`{"message": 0, "chars": 210000}` (the first 210,000 characters of message 0, for a client that sends the document and
the question in one message) or `{"tokens": 12345}`. The engine reads the prompt in two parts there, keeps the checkpoint
at the boundary pinned (retention never evicts it, a parked conversation holding it stays parked, `SAVE` keeps it) and,
when a later question resumes from it, does not park the question it leaves. So the next question starts at the end of
the document, and 20 questions cost one read of it. Without the field the server's checkpoints are where they were: the
last turn's start, the system prompt's end and every `--prompt-cache-every` tokens, so a question that follows a long
document in the same chat re-reads up to 16K tokens of it (55 s at 262K on a Tesla P100). The field is checked against the
prompt's own ids (the prefix is always the longest common start), a prefix that cannot be marked is said in the server's
window and ignored, and a malformed field is a 400. One pinned prefix at a time per engine (a new one replaces it);
it needs `--prompt-cache 3` or more. `tools/research_run.py` runs a document and a question list against a server with and
without it. The engine's own key is `pin=N` on the `GEN` line.
**Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192
--conversation-cache-slots 4` to the engine arguments to park up to four conversations
in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when
+60
View File
@@ -0,0 +1,60 @@
# One long document, many questions (0.1.40.2, opt-in)
Read a long document once, then ask many different questions without reading it again. All numbers: Tesla P100 16 GB,
IQ2_XS, `--kv int8 --kv-resident 32768`, MTP on, greedy, the 0.1.40 engine unless a row says "pin".
## What the engine already did (0.1.40)
The conversation cache keeps small checkpoints (the GDN and indexer state, about 118 MiB each); the K/V of the document
stays in the session, so a question that starts from a checkpoint reads only what lies past it.
| 262K document (258,655 tokens) | time to first token |
|---|---|
| first question (cold read) | 904 s (286 tok/s) |
| questions 2-20, engine with a turn boundary at the document's end | 0.53 s median (0.44-0.72) |
| the same through the server's chat API (no turn boundary at the document's end) | 55.5 s each (15 measured): the engine re-reads up to `--prompt-cache-every` (16,384) tokens from the last periodic checkpoint |
| `parallel` 2 through the server | the first two questions 918 s and 979 s; the next pair read the document again from token 0 |
Checkpoint RAM: +804 MiB resident after the first read (6 checkpoints); each later question adds at most 10 MiB. The
K/V of 262K takes 3.06 GiB of pinned RAM, once per session (`--batch` slots each take their own).
Identity (greedy, 64 tokens): questions 1 and 12 on a fresh engine give the same tokens as in the 20-question run.
Caveat: IQ models are not byte-reproducible at temperature 0 between runs unless `STRATA_IQ_MT_MIN=1` (DETAILS.md);
some answers differ between two runs of the same prompt for that reason, with or without the field below.
## `strata_prefix` (and the engine's `pin=N`)
`"strata_prefix": {"messages": 1}`, `{"message": 0, "chars": N}` or `{"tokens": N}` marks the start of the prompt as the
shared document. The checkpoint at its end is pinned: never evicted, kept in the parked-conversation budget, kept by
`SAVE`, and a question that resumes from it does not park the branch it leaves.
| 64K document (P100) | no field | with the field |
|---|---|---|
| engine, raw prompts, questions 2-5 | 48.6 s | 0.35-0.53 s |
| a 100K-token branch between two questions, then a question | 149 s | 0.55 s |
| another 20K prompt between (`--conversation-cache-mib 8192`) | 49 s | 0.97 s (restored), then 0.44 s |
| server, 18K-token document, split messages / one message | 8.8 s | 0.6-0.8 s |
| server `parallel` 2, six questions | 730 s (every pair re-reads) | 220 s (questions 3-6: 2.5-3.8 s) |
Copy-on-write K/V pages across `--batch` slots are NOT built: each slot keeps its own K/V (3.06 GiB at 262K, about 12 GiB
at 1M), and admitting a branch copies the prefix K/V (3 s at 262K). The pinned prefix removes the re-read, not the copy.
`tools/research_run.py` runs a document and a question list against a server with and without the field.
## R3: expert slots against K/V blocks (P100, IQ2_XS)
64K document, 5 questions. Prefill, then median first token of a short question, then decode:
| expert slots (GiB) | prefill | first token | decode |
|---|---|---|---|
| 2,083 (2.81) | 230 s | 0.69 s | 27.5 tok/s |
| 3,500 | 200.7 s | 0.61 s | 30.9 |
| 5,000 | 200.7 s | 0.55 s | 34.2 |
| 7,000 | 200.7 s | 0.51 s | 36.7 |
Marginal value of VRAM: decode 0.31-0.41 s per GiB per 200-token answer between 2,000 and 5,000 slots, 0.15 above;
prefill gains only below the prompt loan's floor. K/V cells in VRAM (`--kv-resident`): 4096 / 16384 / 32768 / 65536 give
34.05 / 34.06 / 34.21 / 34.92 tok/s at 64K; at 262K (5,000 slots) 8192 / 32768 / 131072 give 29.54 / 29.46 / 29.49 tok/s
(block hit rate 92.6 / 94.5 / 95.7 %). So the K/V block cache is worth nothing per GiB, experts only help decode, and the
read is already served by the loan. A split planner would gain almost nothing, so none was built. The one real lever in
the read is the chunk: `--prefill 16384` with 7,000 slots reads 64K in 186.4 s against 200.7 s (-7%), and 4096 takes 228 s;
it needs the larger loan and changes the chunking, hence the rounding, so it is not a placement-only change.
+144
View File
@@ -0,0 +1,144 @@
"""A scripted research run against a running Strata server: one long document, then many different questions.
Reads the document once, then asks each question and reports, per question, the time to the first streamed token and
the whole request, and the run's total. Greedy (temperature 0), so two runs of the same file give the same answers and
a change in how the server keeps the document (the shared prefix below) can be compared answer by answer.
python tools/research_run.py --url http://127.0.0.1:8080 --doc paper.txt --questions questions.txt
python tools/research_run.py --doc paper.txt --questions q.txt --prefix off --json base.json
python tools/research_run.py --doc paper.txt --questions q.txt --prefix on --json fork.json
python tools/research_run.py --compare base.json fork.json
--layout split (the default): the document is the first message, the question the second.
--layout joined: one message, "document + question" (a client that cannot split them).
--prefix on: the request carries "strata_prefix" naming the document as the shared prefix (docs/DETAILS.md): the
server reads it once and every question starts from it. off: the field is left out.
--parallel N: N questions at a time (the server needs "parallel": N for them to run together).
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
import threading
import time
import urllib.request
from pathlib import Path
def request_body(doc: str, question: str, layout: str, prefix: bool, max_tokens: int, model: str | None) -> dict:
if layout == "joined":
body = {"messages": [{"role": "user", "content": doc + "\n\nQuestion: " + question + "\nAnswer:"}]}
if prefix:
body["strata_prefix"] = {"message": 0, "chars": len(doc) + 2}
else:
body = {"messages": [{"role": "user", "content": doc}, {"role": "user", "content": question}]}
if prefix:
body["strata_prefix"] = {"messages": 1}
body.update(temperature=0, max_tokens=max_tokens, stream=True)
if model:
body["model"] = model
return body
def ask(url: str, body: dict, headers: dict, timeout: float) -> dict:
t0 = time.time()
req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers=headers)
first, parts = None, []
with urllib.request.urlopen(req, timeout=timeout) as r:
for raw in r:
line = raw.decode("utf-8", "replace").strip()
if not line.startswith("data:") or line.endswith("[DONE]"):
continue
event = json.loads(line[5:])
for choice in event.get("choices", []):
delta = choice.get("delta", {})
piece = (delta.get("reasoning_content") or "") + (delta.get("content") or "")
if piece and first is None:
first = time.time() - t0
parts.append(piece)
return {"ttft_s": round(first or 0.0, 3), "wall_s": round(time.time() - t0, 2), "text": "".join(parts)}
def run(args) -> dict:
doc = Path(args.doc).read_text(encoding="utf-8", errors="replace")
if args.limit_chars:
doc = doc[:args.limit_chars]
questions = [x.strip() for x in Path(args.questions).read_text(encoding="utf-8").splitlines() if x.strip()]
questions = questions[:args.n] if args.n else questions
headers = {"Content-Type": "application/json"}
if args.api_key:
headers["Authorization"] = "Bearer " + args.api_key
rows: list[dict | None] = [None] * len(questions)
started = time.time()
for k in range(0, len(questions), max(1, args.parallel)):
group = list(range(k, min(k + max(1, args.parallel), len(questions))))
def one(i):
try:
rows[i] = {"q": i, **ask(args.url, request_body(doc, questions[i], args.layout, args.prefix == "on",
args.max_tokens, args.model), headers, args.timeout)}
except Exception as e: # noqa: BLE001 - a failed question is reported, the run goes on
rows[i] = {"q": i, "error": repr(e)}
threads = [threading.Thread(target=one, args=(i,)) for i in group]
[t.start() for t in threads]
[t.join() for t in threads]
for i in group:
r = rows[i]
print(f"q{i:02d} first token {r.get('ttft_s', '-')} s total {r.get('wall_s', '-')} s "
f"{r.get('error') or repr(r['text'][:60])}", flush=True)
out = {"url": args.url, "layout": args.layout, "prefix": args.prefix, "doc_chars": len(doc), "questions": rows,
"total_s": round(time.time() - started, 1)}
later = [r["ttft_s"] for r in rows[1:] if r and "ttft_s" in r]
if later:
out["first_token_median_after_first_s"] = round(statistics.median(later), 3)
print(f"total {out['total_s']} s" + (f", median first token after the first question {out['first_token_median_after_first_s']} s"
if later else ""), flush=True)
return out
def compare(a_path: str, b_path: str) -> int:
a, b = (json.loads(Path(p).read_text(encoding="utf-8")) for p in (a_path, b_path))
same = diff = 0
for x, y in zip(a["questions"], b["questions"]):
if "text" in x and "text" in y:
if x["text"] == y["text"]:
same += 1
else:
diff += 1
print(f"q{x['q']:02d}: the answers differ")
print(f"{same} answers identical, {diff} differ; total {a['total_s']} s -> {b['total_s']} s; median first token "
f"{a.get('first_token_median_after_first_s')} s -> {b.get('first_token_median_after_first_s')} s")
return 1 if diff else 0
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--url", default="http://127.0.0.1:8080")
ap.add_argument("--api-key", default="")
ap.add_argument("--model", default=None)
ap.add_argument("--doc")
ap.add_argument("--questions", help="a text file, one question per line")
ap.add_argument("--n", type=int, default=0, help="only the first N questions")
ap.add_argument("--layout", choices=("split", "joined"), default="split")
ap.add_argument("--prefix", choices=("on", "off"), default="on")
ap.add_argument("--parallel", type=int, default=1)
ap.add_argument("--max-tokens", type=int, default=128)
ap.add_argument("--limit-chars", type=int, default=0, help="use only the first N characters of the document")
ap.add_argument("--timeout", type=float, default=7200.0)
ap.add_argument("--json", help="write the per-question results here")
ap.add_argument("--compare", nargs=2, metavar=("A.json", "B.json"), help="compare two saved runs' answers and times")
args = ap.parse_args(argv)
if args.compare:
return compare(*args.compare)
if not args.doc or not args.questions:
ap.error("--doc and --questions are needed")
out = run(args)
if args.json:
Path(args.json).write_text(json.dumps(out, indent=1), encoding="utf-8")
return 1 if any("error" in r for r in out["questions"]) else 0
if __name__ == "__main__":
sys.exit(main())
+89
View File
@@ -0,0 +1,89 @@
"""Offline test of tools/research_run.py against the server's mock engine (no GPU, no pack)."""
import contextlib
import io
import json
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tools"))
import research_run # noqa: E402
from serve.frontend import ChatTemplate # noqa: E402
from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402
class Recorder(MockEngine):
def __init__(self, *a, **k):
super().__init__(*a, **k)
self.samplings = []
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
self.samplings.append(dict(sampling))
yield from super().generate(ids, max_new, sampling, cancel, embeddings)
class ResearchRun(unittest.TestCase):
@classmethod
def setUpClass(cls):
tok = ByteTokenizer()
cls.engine = Recorder(tok, "an answer", max_context=8192)
cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
cls.httpd = serve(cls.svc, port=0)
cls.url = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
cls.dir = tempfile.TemporaryDirectory()
d = Path(cls.dir.name)
(d / "doc.txt").write_text("The document. " * 40, encoding="utf-8")
(d / "q.txt").write_text("What is it?\nWho wrote it?\n\nWhen?\n", encoding="utf-8")
@classmethod
def tearDownClass(cls):
cls.httpd.shutdown()
cls.httpd.server_close()
cls.dir.cleanup()
def go(self, *extra):
d = Path(self.dir.name)
out = d / "out.json"
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = research_run.main(["--url", self.url, "--doc", str(d / "doc.txt"), "--questions", str(d / "q.txt"),
"--json", str(out), *extra])
return code, json.loads(out.read_text(encoding="utf-8")), buf.getvalue()
def test_split_run_names_the_prefix_and_reports_every_question(self):
self.engine.samplings.clear()
code, out, text = self.go("--prefix", "on")
self.assertEqual(code, 0, text)
self.assertEqual([q["q"] for q in out["questions"]], [0, 1, 2]) # the blank line is skipped
self.assertTrue(all(q["text"] for q in out["questions"]))
self.assertEqual(len(self.engine.samplings), 3)
for s in self.engine.samplings:
self.assertEqual(s["strata_prefix"]["tokens"] > 0, True) # resolved by the server
self.assertIn("median first token", text)
def test_prefix_off_and_the_joined_layout(self):
self.engine.samplings.clear()
self.go("--prefix", "off")
self.assertTrue(all("strata_prefix" not in s for s in self.engine.samplings))
self.engine.samplings.clear()
code, out, _ = self.go("--prefix", "on", "--layout", "joined", "--parallel", "2")
self.assertEqual(code, 0)
self.assertTrue(all(s["strata_prefix"]["tokens"] > 0 for s in self.engine.samplings))
def test_compare(self):
d = Path(self.dir.name)
self.go("--prefix", "off")
(d / "a.json").write_text((d / "out.json").read_text(encoding="utf-8"), encoding="utf-8")
self.go("--prefix", "on")
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
code = research_run.main(["--compare", str(d / "a.json"), str(d / "out.json")])
self.assertEqual(code, 0, buf.getvalue())
self.assertIn("3 answers identical, 0 differ", buf.getvalue())
if __name__ == "__main__":
unittest.main()