Merge branch 'claude/cp-latency' into claude/port-gpu-bringup

This commit is contained in:
Pavlo Ratushnyi
2026-10-24 02:00:07 +02:00
28 changed files with 3403 additions and 56 deletions
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Runs inside run-e2e.sh (as E2E_RUN_CMD, so inside a holder job, with the engine loaded and the current strata-next on :8081):
# starts the BASELINE strata-next (commit dbf487b logic) on :8082 against the same engine and replays one synthesized Codex session
# (scripts/cp/synth_session.py) alternately through the two, then joins the client's timings with the servers' stage logs.
# Test tooling only; no credential is printed (keys are read from files).
set -uo pipefail
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
BINS=${CP_BINS:-$HOME/work/leleka-cp/bin}
OUT=${E2E_OUT_DIR:?run through run-e2e.sh}
STATE=$HOME/work/leleka-e2e/state
SESSION=${CP_SESSION:-$HOME/work/leleka-cp/data/s945.json}
TOK=$STATE/tokenizer-assets/tokenizer
SIZE=${CP_SIZE:-100000}
TURNS=${CP_TURNS:-20}
MAXOUT=${CP_MAX_OUT:-64}
sed 's/127.0.0.1:8081/127.0.0.1:8082/' "$STATE/strata.json" >"$STATE/strata-base.json"
[ "$(grep -c 8082 "$STATE/strata-base.json")" = 1 ] || { echo "could not derive the baseline config"; exit 3; }
STRATA_STAGE_TRACE=log "$BINS/strata-next-base" serve --config "$STATE/strata-base.json" >"$OUT/strata-base.log" 2>&1 &
PID_BASE=$!
if ! "$BINS/strata-next-base" wait-ready --url http://127.0.0.1:8082 --model qwen-iq3 --key-file "$STATE/api-key" --timeout-s 180 >"$OUT/wait-ready-base.log" 2>&1; then
echo "baseline strata-next never became ready"; tail -20 "$OUT/wait-ready-base.log" "$OUT/strata-base.log"; kill -INT $PID_BASE 2>/dev/null; exit 6
fi
echo "both servers ready: $(date -u +%T)"
sha256sum "$BINS"/strata-next-base "$BINS"/strata-next-new "$BINS"/leleka-inference "$BINS"/cp_replay | cut -c1-16,65-
"$BINS/cp_replay" "$TOK" "$SESSION" --live http://127.0.0.1:8081,http://127.0.0.1:8082 --names new,base --key-file "$STATE/api-key" \
--size "$SIZE" --turns "$TURNS" --max-output-tokens "$MAXOUT" >"$OUT/live.txt" 2>"$OUT/live.err"
RC=$?
cat "$OUT/live.err" | tail -5
kill -INT $PID_BASE 2>/dev/null
for _ in $(seq 1 20); do kill -0 $PID_BASE 2>/dev/null || break; sleep 1; done
kill -KILL $PID_BASE 2>/dev/null
python3 -I "$HERE/live_report.py" "$OUT/live.txt" new="$OUT/strata-next.log" base="$OUT/strata-base.log" | tee "$OUT/live-report.txt"
echo "cp_replay exit status $RC"
exit $RC
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Offline: join the client's per-turn timings of `cp_replay --live` with the servers' logs (experiments only).
live_report.py LIVE.txt ARM=SERVER_LOG [ARM=SERVER_LOG ...]
LIVE.txt holds `LIVE {json}` lines (one per request, with the client's unix-ms send/done times). Each SERVER_LOG is the stderr of a
`strata-next serve` run with STRATA_STAGE_TRACE=log: `stage NAME MS t_unix_ms=END`, `generation start: t_unix_ms=T ...` and
`generation done: ... prompt_ms=P ...` lines. A turn is joined with the lines of its arm's log that fall inside [send, done].
Per turn the client's time to the first token splits into
pre = send -> `generation start` (everything the control plane does before it hands the prompt to the engine)
engine= `generation start` -> first text delta as the worker saw it (`prompt_ms`: engine start call, prefill, first round)
post = the rest (first delta at the worker -> first token event at the client)
"""
import json
import re
import statistics
import sys
PRE_STAGES = ["http_body_json", "request_decode", "request_validate", "render", "tokenize", "enqueue", "worker_prompt_text", "engine_start"]
def load_log(path):
stages, starts, dones = [], [], []
for line in open(path, errors="replace"):
m = re.match(r"stage (\S+) ([\d.]+) t_unix_ms=(\d+)", line)
if m:
stages.append((int(m.group(3)), m.group(1), float(m.group(2))))
continue
m = re.match(r"generation start: t_unix_ms=(\d+)", line)
if m:
starts.append(int(m.group(1)))
continue
m = re.match(r"generation done: t_unix_ms=(\d+).*prompt_tokens=(\d+) reused=(\d+).*prompt_ms=([\d.]+) decode_ms=([\d.]+)", line)
if m:
dones.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), float(m.group(4))))
return stages, starts, dones
def pct(values, q):
v = sorted(values)
return v[round(q * (len(v) - 1))] if v else float("nan")
def main():
live = [json.loads(l[5:]) for l in open(sys.argv[1]) if l.startswith("LIVE ")]
logs = {}
for spec in sys.argv[2:]:
arm, path = spec.split("=", 1)
logs[arm] = load_log(path)
rows = []
for turn in live:
stages, starts, dones = logs[turn["arm"]]
lo, hi = turn["sent_unix_ms"] - 5, turn["done_unix_ms"] + 50
window = [(n, ms) for t, n, ms in stages if lo <= t <= hi]
start = next((t for t in starts if lo <= t <= hi), None)
done = next((d for d in dones if lo <= d[0] <= hi), None)
stage_sum = {name: sum(ms for n, ms in window if n == name) for name in PRE_STAGES}
pre = (start - turn["sent_unix_ms"]) if start else float("nan")
engine = done[3] if done else float("nan")
post = turn["ttft_ms"] - pre - engine
rows.append({**turn, "pre": pre, "engine": engine, "post": post, "stages": stage_sum,
"reused": done[2] if done else 0, "prompt_tokens": done[1] if done else 0})
print("turn arm round prompt reused ttft_ms created pre_ms engine_ms post_ms total_ms terminal")
for r in rows:
print(f"{r['turn']:>4} {r['arm']:<5} {r['round']:>5} {r['prompt_tokens']:>7} {r['reused']:>7} {r['ttft_ms']:>8.1f} {r['created_ms']:>8.1f} {r['pre']:>7.1f} {r['engine']:>10.1f} {r['post']:>8.1f} {r['total_ms']:>9.1f} {r['terminal']}")
print("\nper arm, turns after the first of each arm (median / p95), ms:")
for arm in logs:
mine = [r for r in rows if r["arm"] == arm][1:]
if not mine:
continue
def cell(key):
values = [r[key] for r in mine]
return f"{statistics.median(values):8.1f} / {pct(values, 0.95):8.1f}"
print(f" {arm:<6} n={len(mine):<3} ttft {cell('ttft_ms')} created {cell('created_ms')} pre {cell('pre')} engine {cell('engine')} post {cell('post')}")
names = ", ".join(f"{k}={statistics.median(r['stages'][k] for r in mine):.2f}" for k in PRE_STAGES)
print(f" median pre-engine stages: {names}")
main()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# Interleaved A/B of the host-side request path on the instant engine (docs/cp-latency.md), repeats alternating base and new so a shared
# machine hurts both arms alike. Builds only; the model, the GPU and Python are not involved except for the summary table.
#
# run-ab.sh BASE_TREE NEW_TREE TOKENIZER_DIR SESSION.json OUT_DIR [REPS] [cp_replay args...]
#
# BASE_TREE / NEW_TREE: source trees (e.g. `git archive dbf487b` and a checkout of the new head), each already carrying
# control-plane/examples/cp_replay.rs and desktop-core/examples/cp_replay_grpc.rs (the baseline needs `encode_reference` and
# `decodes_to` shims on its Tokenizer for --verify only, not for timing). CARGO_TARGET_DIR_BASE / _NEW choose the target dirs.
# Writes OUT_DIR/{base,new}-{proc,grpc}-N.{json,txt}; `python3 scripts/cp/summarize.py OUT_DIR` prints the tables.
set -euo pipefail
BASE=$1 NEW=$2 TOK=$3 SESSION=$4 OUT=$5; REPS=${6:-3}; shift 6 2>/dev/null || shift $#
mkdir -p "$OUT"
build() { # tree target
( cd "$1" && CARGO_TARGET_DIR="$2" cargo build --locked --release -p strata-control --example cp_replay \
&& CARGO_TARGET_DIR="$2" cargo build --locked --release -p strata-desktop-core --example cp_replay_grpc ) >&2
}
TB=${CARGO_TARGET_DIR_BASE:-$BASE/target-ab}
TN=${CARGO_TARGET_DIR_NEW:-$NEW/target-ab}
build "$BASE" "$TB"
build "$NEW" "$TN"
for r in $(seq 1 "$REPS"); do
for cfg in base new; do
T=$TN; [ $cfg = base ] && T=$TB
for mode in proc grpc; do
EX=cp_replay; [ $mode = grpc ] && EX=cp_replay_grpc
"$T/release/examples/$EX" "$TOK" "$SESSION" --label "$cfg-$mode-$r" --out "$OUT/$cfg-$mode-$r.json" "$@" \
>"$OUT/$cfg-$mode-$r.txt" 2>/dev/null
echo "done $cfg-$mode-$r"
done
done
done
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Offline: summarize cp_replay result files (experiments only).
summarize.py DIR -- reads DIR/{base,new}-{proc,grpc}-N.json and prints, per mode and history size, the warm-turn p50 and p95
per metric and per stage (min over repeats of each repeat's percentile: the machine is shared).
"""
import glob, json, os, re, statistics, sys
def pct(values, q):
v = sorted(values)
return v[round(q * (len(v) - 1))] if v else float("nan")
def load(directory):
runs = {}
for path in sorted(glob.glob(os.path.join(directory, "*.json"))):
m = re.match(r"(base|new)-(proc|grpc)-(\d+)\.json", os.path.basename(path))
if not m:
continue
doc = json.load(open(path))
runs.setdefault((m.group(2), m.group(1)), []).append(doc)
return runs
def per_size(docs, metric, stage=None):
"""size -> list over repeats of (cold, p50, p95)"""
out = {}
for doc in docs:
for res in doc["results"]:
rows = res["rows"]
def val(r):
if stage is None:
return r[metric]
return r["stages"].get(stage, {}).get("ms", 0.0)
warm = [val(r) for r in rows[1:]]
out.setdefault(res["size"], []).append((val(rows[0]), pct(warm, 0.5), pct(warm, 0.95)))
return out
def best(entries, k):
return min(e[k] for e in entries)
def main():
runs = load(sys.argv[1])
metrics = ["pre_engine_ms", "first_event_ms", "tail_ms"]
stages = ["http_body_json", "request_decode", "request_validate", "render", "tokenize", "worker_prompt_text", "engine_start", "post_decode", "post_assemble", "post_store", "delta_retokenize"]
for mode in ("proc", "grpc"):
if (mode, "base") not in runs:
continue
print(f"\n### {'in-process instant engine' if mode == 'proc' else 'instant engine behind the real gRPC runtime server'}")
sizes = sorted(per_size(runs[(mode, "new")], "pre_engine_ms"))
for label, names, stage in (("metric", metrics, False), ("stage", stages, True)):
print(f"\n| {label} (ms, warm turns) | " + " | ".join(f"{s//1000}k base p50 / p95 | {s//1000}k new p50 / p95" for s in sizes) + " |")
print("|---|" + "---|---|" * len(sizes))
for name in names:
cells = []
for s in sizes:
for cfg in ("base", "new"):
e = per_size(runs[(mode, cfg)], name if not stage else None, name if stage else None).get(s)
cells.append(f"{best(e,1):.2f} / {best(e,2):.2f}" if e else "-")
print(f"| {name} | " + " | ".join(cells) + " |")
print("\ncold first request (ms, min over repeats):")
for cfg in ("base", "new"):
e = per_size(runs[(mode, cfg)], "pre_engine_ms")
print(f" {cfg:5s} pre_engine cold: " + ", ".join(f"{s//1000}k={best(e[s],0):.1f}" for s in sorted(e)))
main()
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""Offline tooling (experiments only; production stays Python-free): synthesize Codex-shaped Responses API request material
from a captured session (the engine-side capture holds the rendered prompt token ids, not the HTTP bodies).
synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ_INDEX OUT.json [--extend CAPTURE2 LAST2]
The last request's prompt is decoded with the pinned vocabulary and the chat template is inverted: system block (tools, merged
instructions), user messages, assistant turns (`<think>` reasoning, text, `<tool_call>` markup) and `<tool_response>` user turns become
Responses `instructions`, `tools`, and `input` items (message / reasoning / function_call / function_call_output) exactly as Codex
replays them. OUT.json holds the invariant part of a request and the item list with its round boundaries, plus the captured prompt
ids of the last request so a harness can check that rendering + tokenizing the synthesized body reproduces the capture exactly.
With --extend the items of a second capture (call ids and text tagged so no two items are byte-identical) are appended, to reach
history sizes beyond the capture.
"""
import json
import re
import sys
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from tok_py import Vocab # noqa: E402
CALL_RE = re.compile(r"<tool_call>\n<function=([^>]+)>\n(.*?)</function>\n</tool_call>", re.S)
PARAM_RE = re.compile(r"<parameter=([^>]+)>\n(.*?)\n</parameter>\n", re.S)
RESP_RE = re.compile(r"<tool_response>\n(.*?)\n</tool_response>", re.S)
def split_segments(text):
segs = []
pos = 0
marker = "<|im_start|>"
idx = [m.start() for m in re.finditer(re.escape(marker), text)]
for a, b in zip(idx, idx[1:] + [len(text)]):
seg = text[a + len(marker):b]
segs.append(seg)
return segs
def parse_system(seg):
# seg = "system\n...<|im_end|>\n"
body = seg[len("system\n"):]
assert body.endswith("<|im_end|>\n"), body[-40:]
body = body[: -len("<|im_end|>\n")]
tools_start = body.index("<tools>\n") + len("<tools>\n")
tools_end = body.index("\n</tools>")
tools = [json.loads(l) for l in body[tools_start:tools_end].split("\n")]
rest = body[tools_end + len("\n</tools>"):]
marker = "</IMPORTANT>"
k = rest.index(marker) + len(marker)
tail = rest[k:]
assert tail.startswith("\n\n"), repr(tail[:30])
instructions = tail[2:]
flat = []
for t in tools:
f = t["function"]
o = {"type": "function", "name": f["name"]}
if "description" in f:
o["description"] = f["description"]
if "strict" in f:
o["strict"] = f["strict"]
if "parameters" in f:
o["parameters"] = f["parameters"]
flat.append(o)
return instructions, flat
def message(role, text):
kind = "output_text" if role == "assistant" else "input_text"
return {"type": "message", "role": role, "content": [{"type": kind, "text": text}]}
def arg_value(raw, schema):
prop = (schema or {}).get("properties", {})
kind = None
return raw, prop
def parse_assistant(seg, tools, serial):
body = seg[len("assistant\n"):]
assert body.endswith("<|im_end|>\n"), repr(body[-30:])
body = body[: -len("<|im_end|>\n")]
assert body.startswith("<think>\n")
close = body.index("\n</think>\n\n")
reasoning = body[len("<think>\n"):close]
content = body[close + len("\n</think>\n\n"):]
items = []
if reasoning:
items.append({"type": "reasoning", "summary": [], "content": [{"type": "reasoning_text", "text": reasoning}]})
first = content.find("<tool_call>\n")
text = content if first < 0 else content[:first]
text = text.strip()
if text:
items.append(message("assistant", text))
calls = []
for m in CALL_RE.finditer(content):
name, params = m.group(1), m.group(2)
schema = next((t.get("parameters") for t in tools if t["name"] == name), None) or {}
props = schema.get("properties", {})
args = {}
for p in PARAM_RE.finditer(params):
pname, raw = p.group(1), p.group(2)
ptype = props.get(pname, {}).get("type")
if ptype == "string" or ptype is None:
args[pname] = raw
else:
try:
args[pname] = json.loads(raw)
except ValueError:
args[pname] = raw
serial[0] += 1
call_id = f"call_{serial[0]:06d}"
calls.append(call_id)
items.append({"type": "function_call", "name": name, "call_id": call_id,
"arguments": json.dumps(args, ensure_ascii=False, separators=(",", ":"))})
return items, calls
def parse_user(seg, pending_calls):
body = seg[len("user\n"):]
assert body.endswith("<|im_end|>\n")
body = body[: -len("<|im_end|>\n")]
if body.startswith("<tool_response>\n") and pending_calls:
outs = [m.group(1) for m in RESP_RE.finditer(body)]
assert len(outs) == len(pending_calls), (len(outs), len(pending_calls))
return [{"type": "function_call_output", "call_id": c, "output": o} for c, o in zip(pending_calls, outs)], True
return [message("user", body)], False
def build(vocab, capture, last, serial):
req = json.load(open(f"{capture}/req-{last:06d}.json"))
ids = req["prompt_ids"]
text = vocab.decode(ids)
segs = split_segments(text)
instructions, tools = parse_system(segs[0])
items, rounds = [], []
pending = []
# the final segment is the generation prompt "assistant\n<think>\n"
assert segs[-1] == "assistant\n<think>\n", repr(segs[-1])
for seg in segs[1:-1]:
if seg.startswith("assistant\n"):
new, calls = parse_assistant(seg, tools, serial)
items += new
pending = calls
else:
new, was_output = parse_user(seg, pending)
items += new
pending = []
# a request can be made after a user message or after tool outputs
rounds.append(len(items))
return instructions, tools, items, rounds, ids
def retag(items, rounds, tag):
out = []
for it in items:
it = json.loads(json.dumps(it))
if it["type"] == "message":
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
elif it["type"] == "function_call_output":
it["output"] = f"[{tag}] " + it["output"]
elif it["type"] == "reasoning":
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
elif it["type"] == "function_call":
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
out.append(it)
# call ids in outputs
for it in out:
if it["type"] == "function_call_output":
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
return out
def main():
argv = sys.argv[1:]
tok_dir, capture, last, out = argv[0], argv[1], int(argv[2]), argv[3]
extend = None
if "--extend" in argv:
k = argv.index("--extend")
extend = (argv[k + 1], int(argv[k + 2]))
vocab = Vocab(tok_dir)
serial = [0]
instructions, tools, items, rounds, ids = build(vocab, capture, last, serial)
doc = {"instructions": instructions, "tools": tools, "items": items, "rounds": rounds,
"capture_prompt_ids": ids, "capture_items": len(items)}
if extend:
i2, t2, items2, rounds2, _ = build(vocab, extend[0], extend[1], serial)
# skip the leading environment/task user messages of the second session: keep from its first assistant turn
first_assistant = next(n for n, it in enumerate(items2) if it["type"] in ("reasoning", "function_call") or (it["type"] == "message" and it["role"] == "assistant"))
base = len(items)
tail = retag(items2[first_assistant:], rounds2, "x")
doc["items"] = items + tail
doc["rounds"] = rounds + [base + (r - first_assistant) for r in rounds2 if r > first_assistant]
json.dump(doc, open(out, "w", encoding="utf-8"), ensure_ascii=False)
print(f"items={len(doc['items'])} rounds={len(doc['rounds'])} tools={len(tools)} instructions_bytes={len(instructions)} capture_tokens={len(ids)}")
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
"""Offline helper (experiments only): decode captured prompt ids to text with the pinned vocab.json (byte-level BPE alphabet)."""
import json, os
def _byte_alphabet():
bs = list(range(0x21, 0x7f)) + list(range(0xa1, 0xad)) + list(range(0xae, 0x100))
cs = bs[:]
n = 0
for b in range(256):
if b not in bs:
bs.append(b); cs.append(256 + n); n += 1
return {chr(c): b for b, c in zip(bs, cs)}
class Vocab:
def __init__(self, directory):
vocab = json.load(open(os.path.join(directory, "vocab.json"), encoding="utf-8"))
self.tokens = [None] * len(vocab)
for t, i in vocab.items():
self.tokens[i] = t
self.rev = _byte_alphabet()
def decode_bytes(self, ids):
out = bytearray()
for i in ids:
for ch in self.tokens[i]:
out.append(self.rev[ch])
return bytes(out)
def decode(self, ids):
return self.decode_bytes(ids).decode("utf-8")
+26
View File
@@ -0,0 +1,26 @@
set -uo pipefail
# claude/cp-latency: the host side of one Codex session on the real engine. One model load; two API servers in front of the same engine
# (the current strata-next on :8081 and the baseline dbf487b logic on :8082); one synthesized Codex session (capture 945, history ~100k tokens,
# 20 consecutive requests, max_output_tokens 64) sent alternately through the two, so the engine sees the same prompt sequence either way.
# Prints the per-request table and per-arm medians of: client TTFT, pre-engine time (send -> generation start), engine time, post time.
# Needs (outside Git, copied by the operator): $CP/bin/{leleka-inference,strata-next-new,strata-next-base,cp_replay}, $CP/data/s945.json,
# the e2e bins for leleka-daemon / leleka-cli, and the scripts of this branch under $CP/scripts/cp.
CP=$HOME/work/leleka-cp
E2E=$HOME/work/leleka-e2e/bin-sm120
mkdir -p $CP/bin-e2e $CP/runs
ln -sf $CP/bin/leleka-inference $CP/bin-e2e/leleka-inference
ln -sf $CP/bin/strata-next-new $CP/bin-e2e/strata-next
ln -sf $E2E/leleka-daemon $CP/bin-e2e/leleka-daemon
ln -sf $E2E/leleka-cli $CP/bin-e2e/leleka-cli
export E2E_BIN=$CP/bin-e2e
export E2E_OUT=$CP/runs/9f1-cp-live-ab
export CP_BINS=$CP/bin CP_SESSION=$CP/data/s945.json CP_SIZE=${CP_SIZE:-100000} CP_TURNS=${CP_TURNS:-20}
export STRATA_STAGE_TRACE=log
export LELEKA_BRINGUP_TRACE=1
export E2E_SAMPLE_S=10
export E2E_RUN_CMD="bash $CP/scripts/cp/live-ab.sh"
rm -rf $E2E_OUT
date -u +%FT%TZ
bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh
echo "run-e2e rc=$?"
date -u +%FT%TZ