Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

split: add KLD/task metrics and session smoke

Resynth91878cb8557d
diff --git a/doc/split.md b/doc/split.md
index 5187bda..f91e2e6 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -30,6 +30,28 @@ Measured configuration: an RX 9070 (`gfx1201`, 15.92 GiB) over USB4 as `part0` a
118 GiB Strix Halo iGPU (`gfx1151`) as `part1`. The numbers below are measurements from
that pair, not assumptions of the interface.
+### Measured results
+
+GLM-5.3-Flash, MTP on, one long summary prompt per depth, 128 decode tokens (500K uses
+64). These are measured values for the configuration above; they are not targets.
+
+| Context | Arm | Prefill t/s | Decode t/s | Acceptance |
+| --- | --- | --- | --- | --- |
+| 8K | split, N=4 | 448 | 23.58 | 62.3% |
+| 8K | single device | 330 | 24.42 | 70.8% |
+| 32K | split, N=4 | 495 | 25.15 | 70.8% |
+| 32K | single device | 386 | 24.82 | 73.1% |
+| 128K | split, N=4 | 495 | 25.12 | 70.8% |
+| 128K | single device | 391 | 23.24 | 62.3% |
+| 500K | split, N=5 | 446 | 28.84 | 78.0% |
+
+Prefill is consistently faster on the split because the first 4-5 layers run on the
+`part0` card. Decode is within a few percent either way. At 500K the split fits: the
+load-time peaks are 10.75 GiB on `part0` and 100.2 GiB on `part1`. A single 118 GiB
+device did not have headroom for the same context on this pair, so the split's benefit
+there is capacity, not only speed. Acceptance samples are 50-114 drafted tokens per arm; treat the differences
+as overlapping intervals rather than a trend.
+
## Quick start
The GLM server and the split harnesses accept the flags below. The environment-only path
@@ -118,9 +140,25 @@ defect.
the passkey prompt is too short for an acceptance comparison. `--vision-image` encodes
one image through the split vision tower; the harness sets `EXL3_CONV_GEMM=1` as the
safe gfx12 spatial-merge fallback.
+- `--kld-corpus PATH --kld-slices N --kld-len L --kld-out FILE` teacher-forces corpus
+ slices and `--kld-compare BASE SPLIT` reports KLD both ways, top-1 agreement and PPL.
+ The short battery also reports programmatic task checks. Use these for split-on quality:
+ a mixed-architecture pair is not bitwise.
+- `tools/strix_halo/split_sessions_smoke.py` sends N concurrent requests at a running
+ server and checks that every response succeeds and that the requests overlap.
## Known limitations
+- Split-on is deterministic run-to-run, but it is **not bitwise** equal to a single
+ device on a mixed-architecture pair. Measured on GLM, N=4: 4/6 short greedy prompts
+ identical, task checks 5/6 vs 4/6, PPL 9.374 vs 9.401 and KLD 2.08e-2 with 94.52%
+ top-1 agreement over 1022 positions. The distributions and task accuracy are
+ unchanged; a few near-tie argmax positions flip. Use KLD/task metrics for split-on.
+- At 500K context the split fits the measured pair (`part0` 10.75 GiB, `part1` 100.2 GiB
+ load-time peak). A single 118 GiB device did not have headroom for the same context
+ there; size for capacity, not only speed.
+- Concurrent serving is smoke-tested at 4 sessions with MTP on (4/4 responses overlap,
+ no queue or slot error). A heavier mixed chat/image/tool workload is future work.
- MTP on the split is deterministic at 8K/32K/128K with N=4 in the measured
configuration (two independent runs: 6/6 greedy prompts and identical long-prompt ids).
The earlier N=6 128K battery used short prompts; N=6 long prefill OOMs a 16 GB part0,
diff --git a/tests/test_split_eval_cpu.py b/tests/test_split_eval_cpu.py
new file mode 100644
index 0000000..4a982da
--- /dev/null
+++ b/tests/test_split_eval_cpu.py
@@ -0,0 +1,118 @@
+"""CPU tests for the split_eval quality helpers.
+
+Task scoring and KLD/PPL math must be checked without loading a model: they are the
+numbers Stage 2 uses to judge split quality when token-for-token equality is not
+expected on a mixed-architecture pair.
+"""
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
[email protected](scope = "module")
+def ev():
+ path = ROOT / "tools" / "strix_halo" / "split_eval.py"
+ spec = importlib.util.spec_from_file_location("split_eval", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["split_eval"] = module
+ spec.loader.exec_module(module)
+ yield module
+ sys.modules.pop("split_eval", None)
+
+
[email protected]("index,text,passed", [
+ (0, "The capital of France is Paris.", True),
+ (0, "I am not sure.", False),
+ (1, "def reverse(head):\n nxt = head.next\n return nxt", True),
+ (1, "Use a loop.", False),
+ (2, "Rayleigh scattering makes the sky blue.", True),
+ (3, "53, 59, 61, 67, 71", True),
+ (3, "51, 55, 57", False),
+ (3, "153, 253, 353", False),
+ (4, "The trip takes 2 hours 45 minutes.", True),
+ (4, "2 h 45 min", True),
+ (4, "two hours and forty-five minutes", True),
+ (4, "The trip takes about 3 hours.", False),
+ (4, "The trip takes 3 hours and 45 minutes, arriving at 17:20.", False),
+ (5, "Romeo and Juliet are in Verona.", True),
+])
+def test_score_task(ev, index, text, passed):
+ assert ev.score_task(index, text)["passed"] is passed
+
+
+def test_acceptance_ci95_bounds(ev):
+ ci = ev.acceptance_ci95(50, 50)
+ assert ci is not None
+ assert ci[0] < 50.0 < ci[1]
+ assert ev.acceptance_ci95(0, 0) is None
+
+
+def test_kld_stats_identical_is_zero(ev):
+ lp = torch.log_softmax(torch.randn(8, 16), -1)
+ st = ev.kld_stats(lp, lp)
+ assert st["positions"] == 8
+ assert st["kld_base_to_split"] == pytest.approx(0.0, abs = 1e-6)
+ assert st["kld_split_to_base"] == pytest.approx(0.0, abs = 1e-6)
+ assert st["top1_agreement_pct"] == pytest.approx(100.0)
+
+
+def test_kld_stats_detects_divergence(ev):
+ a = torch.log_softmax(torch.randn(8, 16), -1)
+ b = torch.log_softmax(torch.randn(8, 16), -1)
+ st = ev.kld_stats(a, b)
+ assert st["kld_base_to_split"] > 0.0
+ assert st["kld_split_to_base"] > 0.0
+ assert 0.0 <= st["top1_agreement_pct"] < 100.0
+
+
[email protected](scope = "module")
+def sessions_smoke():
+ pytest.importorskip("aiohttp")
+ path = ROOT / "tools" / "strix_halo" / "split_sessions_smoke.py"
+ spec = importlib.util.spec_from_file_location("split_sessions_smoke", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["split_sessions_smoke"] = module
+ spec.loader.exec_module(module)
+ yield module
+ sys.modules.pop("split_sessions_smoke", None)
+
+
+def test_parse_metrics(sessions_smoke):
+ body = (
+ "# HELP llamacpp:tokens_predicted_total Total tokens generated\n"
+ "# TYPE llamacpp:tokens_predicted_total counter\n"
+ "llamacpp:tokens_predicted_total 456\n"
+ "llamacpp:prompt_seconds_total 2.794384\n"
+ "llamacpp:tokens_predicted_seconds_total 65.976150\n"
+ "llamacpp:kv_cache_usage_ratio 0\n"
+ "not a sample line\n"
+ )
+ m = sessions_smoke.parse_metrics(body)
+ assert m["llamacpp:tokens_predicted_total"] == 456.0
+ assert m["llamacpp:prompt_seconds_total"] == pytest.approx(2.794384)
+ assert m["llamacpp:tokens_predicted_seconds_total"] == pytest.approx(65.976150)
+ assert m["llamacpp:kv_cache_usage_ratio"] == 0.0
+
+
+def test_kld_compare_roundtrip(ev, tmp_path, capsys):
+ a = torch.log_softmax(torch.randn(6, 12), -1).half()
+ b = torch.log_softmax(torch.randn(6, 12), -1).half()
+ common = dict(model = "m", corpus = "c", slices = 1, len = 6, scored = [5], nll = [2.0])
+ torch.save({**common, "mode": "baseline", "ids": [[1, 2, 3, 4, 5, 6]],
+ "logprobs": [a]}, tmp_path / "a.kld")
+ torch.save({**common, "mode": "split", "ids": [[1, 2, 3, 4, 5, 6]],
+ "logprobs": [b]}, tmp_path / "b.kld")
+ ev.kld_compare(str(tmp_path / "a.kld"), str(tmp_path / "b.kld"))
+ out = capsys.readouterr().out
+ assert "KLD mean" in out
+ assert "top1 agreement" in out
+ assert "PPL" in out
diff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.py
index 25e7e1f..aaf7772 100644
--- a/tools/strix_halo/split_eval.py
+++ b/tools/strix_halo/split_eval.py
@@ -17,6 +17,12 @@ Usage (from the repo root, after `source tools/strix_halo/env.sh`):
python tools/strix_halo/split_eval.py -m <pack> --baseline --no-graphs --out /tmp/base.json
python tools/strix_halo/split_eval.py --compare /tmp/base.json /tmp/split.json
python tools/strix_halo/split_eval.py -m <pack> --needle-depth 120000 --out /tmp/needle.json
+ python tools/strix_halo/split_eval.py -m <pack> --kld-corpus /path/corpus.txt --kld-out /tmp/A.kld
+ python tools/strix_halo/split_eval.py --kld-compare /tmp/A.kld /tmp/B.kld
+
+The short battery also scores programmatic task checks, and the split/one-device
+comparison reports them. --kld-out teacher-forces corpus slices through
+Model.forward; --kld-compare reports KLD in both directions, top-1 agreement and PPL.
The split run forces the graph paths off before exllamav3 is imported (Phase 4 owns
correctness; per-segment capture is Phase 6).
@@ -26,6 +32,7 @@ from __future__ import annotations
import argparse
import json
import os
+import re
import sys
import time
@@ -109,6 +116,14 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--bench-acceptance", action="store_true",
help="run all long-form summary instructions at --bench-depth and report the "
"aggregate draft acceptance with a 95%% interval")
+ p.add_argument("--kld-corpus", default=os.environ.get("KYOJIN_KLD_CORPUS"),
+ help="plain-text corpus for --kld-out (or set KYOJIN_KLD_CORPUS)")
+ p.add_argument("--kld-slices", type=int, default=2, help="corpus slices for --kld-out")
+ p.add_argument("--kld-len", type=int, default=512, help="tokens per KLD slice")
+ p.add_argument("--kld-out", default=None,
+ help="teacher-force the corpus and save log-probs/PPL for --kld-compare")
+ p.add_argument("--kld-compare", nargs=2, metavar=("BASE", "SPLIT"),
+ help="compare two --kld-out files: KLD both directions, top-1 agreement, PPL")
p.add_argument("--out", default=None, help="write the full JSON here")
p.add_argument("--compare", nargs=2, metavar=("BASE", "SPLIT"),
help="compare two saved runs: prompt ids and decode numbers")
@@ -118,6 +133,10 @@ def parse_args() -> argparse.Namespace:
p.error("--bench-acceptance needs --bench-depth N (the prompt depth to measure)")
if args.vision_image and args.no_vision:
p.error("--vision-image needs the vision tower; remove --no-vision")
+ if args.kld_out and not args.kld_corpus:
+ p.error("--kld-out needs --kld-corpus (a plain-text file) or KYOJIN_KLD_CORPUS")
+ if args.kld_out and (args.kld_slices < 1 or args.kld_len < 2):
+ p.error("--kld-slices must be >= 1 and --kld-len >= 2")
args.part0_layers_defaulted = args.part0_layers is None
if args.part0_layers is None:
# Harness tuning for memory, not a split property: a small part0 card cannot
@@ -237,6 +256,107 @@ def acceptance_ci95(accepted: int, rejected: int) -> list[float] | None:
return [round(max(0.0, center - half) * 100.0, 2), round(min(1.0, center + half) * 100.0, 2)]
+def score_task(index: int, text: str) -> dict:
+ """Coarse programmatic check for the short battery: task accuracy, not just id equality.
+
+ Greedy ids already show determinism; this adds a signal that a run is still *correct*
+ when a mixed-architecture pair legitimately diverges token-for-token.
+ """
+ t = (text or "").lower()
+ expected, passed = "", False
+ if index == 0: # capital of France
+ expected, passed = "paris", "paris" in t
+ elif index == 1: # reverse a linked list
+ expected, passed = "def + next", "def " in t and "next" in t
+ elif index == 2: # why the sky is blue
+ expected, passed = "scatter/rayleigh", any(w in t for w in ("scatter", "rayleigh", "wavelength"))
+ elif index == 3: # five primes between 50 and 100
+ expected = ">=3 primes 50-100"
+ primes = re.findall(r"\b(?:53|59|61|67|71|73|79|83|89|97)\b", t)
+ passed = len(set(primes)) >= 3
+ elif index == 4: # 14:35 -> 17:20 is 2 h 45 min
+ expected = "2 h 45 min"
+ passed = bool(re.search(
+ r"\b2\s*(?:h|hrs?|hours?)\s*(?:and\s*)?45\b|\b2:45\b|two hours (?:and )?forty[- ]five", t))
+ elif index == 5: # Romeo and Juliet
+ expected, passed = "verona/love", "verona" in t or ("love" in t and ("famil" in t or "feud" in t))
+ return {"task": index, "expected": expected, "passed": bool(passed)}
+
+
+def kld_stats(lp_a, lp_b) -> dict:
+ """Compare two (positions, vocab) log-probability matrices.
+
+ Returns mean KLD in both directions, top-1 agreement and the positions compared. The
+ first argument is the reference (baseline) arm.
+ """
+ import torch
+ n = min(int(lp_a.shape[0]), int(lp_b.shape[0]))
+ if n <= 0:
+ return {"positions": 0}
+ a = lp_a[:n].float()
+ b = lp_b[:n].float()
+ return {
+ "positions": n,
+ "kld_base_to_split": float((a.exp() * (a - b)).sum(-1).mean()),
+ "kld_split_to_base": float((b.exp() * (b - a)).sum(-1).mean()),
+ "top1_agreement_pct": float((a.argmax(-1) == b.argmax(-1)).float().mean() * 100.0),
+ }
+
+
+def corpus_ids(path: str, tokenizer, need: int):
+ """At least ``need`` ids from a plain-text corpus (repeats the text if it is short)."""
+ text = open(path, encoding="utf8", errors="replace").read()
+ ids = tokenizer.encode(text, encode_special_tokens = False).flatten()
+ if ids.numel() < need:
+ reps = need // max(1, ids.numel()) + 1
+ ids = ids.repeat(reps)
+ return ids
+
+
+def run_kld(model, ids):
+ """One cacheless teacher-forced forward; returns per-position log-probs and mean NLL."""
+ import torch
+ logits = model.forward(ids.unsqueeze(0), {"attn_mode": "flash_attn_nc"})
+ lp = torch.log_softmax(logits[0].float(), -1)
+ n = min(lp.shape[0] - 1, ids.numel() - 1)
+ tgt = ids[1:1 + n].to(lp.device)
+ nll = float(-lp[:n].gather(1, tgt[:, None]).sum())
+ return lp[:n].half().cpu(), nll, n
+
+
+def kld_compare(base_path: str, split_path: str) -> None:
+ """Report KLD/PPL from two --kld-out files (baseline first)."""
+ import torch
+ base = torch.load(base_path, map_location = "cpu", weights_only = True)
+ split = torch.load(split_path, map_location = "cpu", weights_only = True)
+ if base.get("ids") != split.get("ids"):
+ raise SystemExit("KLD files do not use the same corpus slices")
+ scored = kld_pos = 0
+ kld_ab = kld_ba = agree = 0.0
+ nll_a = nll_b = 0.0
+ for i, (la, lb) in enumerate(zip(base["logprobs"], split["logprobs"])):
+ st = kld_stats(la, lb)
+ n = st["positions"]
+ if n == 0:
+ continue
+ kld_ab += st["kld_base_to_split"] * n
+ kld_ba += st["kld_split_to_base"] * n
+ agree += st["top1_agreement_pct"] * n
+ kld_pos += n
+ nll_a += base["nll"][i]
+ nll_b += split["nll"][i]
+ scored += base["scored"][i]
+ print(f"[kld] slice {i}: KLD {st['kld_base_to_split']:.3e} / {st['kld_split_to_base']:.3e} "
+ f"(base|split, split|base), top1 {st['top1_agreement_pct']:.2f}%", flush = True)
+ if kld_pos == 0 or scored == 0:
+ raise SystemExit("KLD files have no scored positions")
+ import math
+ print(f"[kld] KLD mean {kld_ab / kld_pos:.3e} (base|split) / {kld_ba / kld_pos:.3e} (split|base); "
+ f"top1 agreement {agree / kld_pos:.2f}%; "
+ f"PPL base {math.exp(nll_a / scored):.4f}, split {math.exp(nll_b / scored):.4f} "
+ f"({kld_pos} positions)", flush = True)
+
+
def main() -> None:
args = parse_args()
if args.part0_layers_defaulted and not args.baseline:
@@ -246,6 +366,9 @@ def main() -> None:
if args.compare:
compare(args.compare[0], args.compare[1])
return
+ if args.kld_compare:
+ kld_compare(args.kld_compare[0], args.kld_compare[1])
+ return
configure_env(args)
@@ -387,16 +510,22 @@ def main() -> None:
f"first {times[0]:.2f} s, second {times[1]:.2f} s, "
f"embeddings {tuple(emb.embeddings.shape)} on {emb.embeddings.device}", flush = True)
- for prompt in PROMPTS:
+ for i, prompt in enumerate(PROMPTS):
ids = ids_of(prompt, tokenizer)
r = run_job(gen, Job, ids, args.tokens)
r["prompt"] = prompt
r["prompt_tokens"] = int(ids.numel())
+ r["task_check"] = score_task(i, r["text"])
result["prompts"].append(r)
print(f"[eval] {prompt[:44]!r}: {r['tokens']} tokens"
+ (f", ttft {r['ttft_s']:.2f} s" if r["ttft_s"] else "")
+ (f", decode {r['tokens'] / r['decode_s']:.2f} t/s"
- if r["decode_s"] and r["tokens"] > 1 else ""), flush = True)
+ if r["decode_s"] and r["tokens"] > 1 else "")
+ + (f", task {'PASS' if r['task_check']['passed'] else 'FAIL'}"
+ if r["task_check"]["expected"] else ""), flush = True)
+ checks = [p["task_check"] for p in result["prompts"]]
+ result["tasks"] = {"passed": sum(t["passed"] for t in checks), "total": len(checks)}
+ print(f"[eval] tasks {result['tasks']['passed']}/{result['tasks']['total']} passed", flush = True)
if not args.no_perf:
for i, prompt in enumerate(PERF_PROMPTS):
@@ -494,6 +623,39 @@ def main() -> None:
f"prefill {ids.numel() / r['ttft_s']:.2f} t/s, decode {tps:.2f} t/s, "
f"accept {acc}/{rej}", flush = True)
+ if args.kld_out:
+ import math
+ need = args.kld_slices * args.kld_len + 4096
+ all_ids = corpus_ids(args.kld_corpus, tokenizer, need)
+ scored = kld_pos = 0
+ nll_sum = 0.0
+ entries = []
+ start = min(4096, max(0, all_ids.numel() - args.kld_slices * (args.kld_len + 37)))
+ for s in range(args.kld_slices):
+ off = start + s * (args.kld_len + 37)
+ ids = all_ids[off:off + args.kld_len].clone()
+ lp, nll, n = run_kld(model, ids)
+ entries.append({"ids": ids.tolist(), "logprobs": lp, "nll": nll, "scored": n})
+ nll_sum += nll
+ scored += n
+ print(f"[kld] slice {s}: {n} positions, NLL mean {nll / max(1, n):.4f}, "
+ f"PPL {math.exp(nll / max(1, n)):.4f}", flush = True)
+ payload = {
+ "model": args.model, "mode": result["mode"],
+ "corpus": args.kld_corpus, "slices": args.kld_slices, "len": args.kld_len,
+ "ids": [e["ids"] for e in entries], "nll": [e["nll"] for e in entries],
+ "scored": [e["scored"] for e in entries],
+ "logprobs": [e["logprobs"] for e in entries],
+ }
+ torch.save(payload, args.kld_out)
+ result["kld"] = {
+ "corpus": args.kld_corpus, "slices": args.kld_slices, "len": args.kld_len,
+ "out": args.kld_out, "scored": scored,
+ "ppl": math.exp(nll_sum / scored) if scored else None,
+ }
+ print(f"[kld] wrote {args.kld_out}: PPL {result['kld']['ppl']:.4f} "
+ f"({scored} positions)", flush = True)
+
for d in devs:
result["devices"][str(d)].update({
"allocated_gib": round(torch.cuda.memory_allocated(d) / 2**30, 2),
@@ -531,6 +693,10 @@ def compare(base_path: str, split_path: str) -> None:
print(f"[compare] first divergence at {d}: "
f"{a[d:d + 8]} vs {b[d:d + 8]}")
print(f"[compare] {same}/{n} greedy prompts identical")
+ for label, run in (("base", base), ("split", split)):
+ if "tasks" in run:
+ t = run["tasks"]
+ print(f"[compare] tasks {label}: {t['passed']}/{t['total']} passed")
if base.get("perf") and split.get("perf"):
for i, (a, b) in enumerate(zip(base["perf"], split["perf"])):
if a.get("decode_tps") and b.get("decode_tps"):
diff --git a/tools/strix_halo/split_sessions_smoke.py b/tools/strix_halo/split_sessions_smoke.py
new file mode 100644
index 0000000..a03ca8f
--- /dev/null
+++ b/tools/strix_halo/split_sessions_smoke.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""Concurrent-session smoke for a served model (split or single device).
+
+Starts no server: point it at an already-running OpenAI-compatible endpoint. The
+point of the Stage 2 check is that the split still serves several requests through
+one Generator: the requests must overlap, all return 200, and the server's metrics
+must count every completion. Overlap is checked from the accumulated prompt/predict
+seconds in `/metrics`; the wall time alone cannot distinguish concurrency from a
+queue, because a queued request's wall includes its wait.
+
+ python tools/glm/serve.py --sessions 4 --num-draft 2 --part0-layers 4 ...
+ python tools/strix_halo/split_sessions_smoke.py --port 8299 --sessions 4 \
+ --max-tokens 128 --out /tmp/sessions.json
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import time
+import urllib.request
+
+import aiohttp
+
+PROMPTS = [
+ "Name three primary colours and explain where each appears in a rainbow.",
+ "Write a Python function that returns the nth Fibonacci number, with a docstring.",
+ "A bus leaves at 09:10 and arrives at 11:55. How long is the trip? Show the work.",
+ "Summarize the water cycle in four short sentences.",
+ "List the first five prime numbers and say why 1 is not prime.",
+ "Explain the difference between RAM and a hard disk in three sentences.",
+ "Write a haiku about winter, then explain the imagery in one sentence.",
+ "What is the capital of Japan, and what is one well-known landmark there?",
+]
+
+
+def metrics(port: int) -> str:
+ try:
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/metrics", timeout = 5) as r:
+ return r.read().decode("utf8", "replace")
+ except Exception as exc: # noqa: BLE001
+ return f"metrics unavailable: {type(exc).__name__}: {exc}"
+
+
+def parse_metrics(text: str) -> dict[str, float]:
+ """Numeric sample values from a Prometheus text body (comments ignored)."""
+ out = {}
+ for line in (text or "").splitlines():
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ name, _, value = line.rpartition(" ")
+ if not name or not value:
+ continue
+ try:
+ out[name] = float(value)
+ except ValueError:
+ continue
+ return out
+
+
+# The server accumulates one projection/prefill time per request. If two or more
+# requests ran at once those sums overlap and exceed the wall clock; a queue gives a
+# ratio near 1.0, so 1.3 is a safe floor for "these requests overlapped".
+MIN_OVERLAP_RATIO = 1.3
+
+
+async def one(session, url, model, prompt, max_tokens, index, timeout_s):
+ body = {
+ "model": model,
+ "messages": [{"role": "user", "content": prompt}],
+ "max_tokens": max_tokens,
+ "temperature": 0.0,
+ "stream": False,
+ }
+ t0 = time.perf_counter()
+ try:
+ async with session.post(url, json = body,
+ timeout = aiohttp.ClientTimeout(total = timeout_s)) as r:
+ j = await r.json()
+ dt = time.perf_counter() - t0
+ if r.status != 200:
+ return {"index": index, "status": r.status, "wall_s": dt,
+ "error": str(j)[:400]}
+ u = j.get("usage", {})
+ msg = (j.get("choices") or [{}])[0].get("message", {})
+ return {
+ "index": index,
+ "status": r.status,
+ "wall_s": round(dt, 3),
+ "prompt_tokens": u.get("prompt_tokens"),
+ "completion_tokens": u.get("completion_tokens"),
+ "cached_tokens": u.get("prompt_tokens_details", {}).get("cached_tokens")
+ if isinstance(u.get("prompt_tokens_details"), dict) else None,
+ "text": ((msg.get("content") or "") + (msg.get("reasoning_content") or ""))[:160],
+ "finish_reason": (j.get("choices") or [{}])[0].get("finish_reason"),
+ }
+ except Exception as exc: # noqa: BLE001
+ return {"index": index, "status": None, "wall_s": round(time.perf_counter() - t0, 3),
+ "error": f"{type(exc).__name__}: {exc}"}
+
+
+async def run(args):
+ url = f"http://127.0.0.1:{args.port}/v1/chat/completions"
+ prompts = (PROMPTS * ((args.sessions + len(PROMPTS) - 1) // len(PROMPTS)))[:args.sessions]
+ before = metrics(args.port)
+ async with aiohttp.ClientSession() as session:
+ t0 = time.perf_counter()
+ results = await asyncio.gather(*[
+ one(session, url, args.model, p, args.max_tokens, i, args.timeout)
+ for i, p in enumerate(prompts)
+ ])
+ wall = time.perf_counter() - t0
+ after = metrics(args.port)
+ before_m = parse_metrics(before)
+ after_m = parse_metrics(after)
+ ok = sum(1 for r in results if r.get("status") == 200)
+ completion_total = sum(int(r.get("completion_tokens") or 0) for r in results)
+
+ def delta(key):
+ return max(0.0, after_m.get(key, 0.0) - before_m.get(key, 0.0))
+
+ prompt_tokens = delta("llamacpp:prompt_tokens_total")
+ predicted_tokens = delta("llamacpp:tokens_predicted_total")
+ prompt_s = delta("llamacpp:prompt_seconds_total")
+ predict_s = delta("llamacpp:tokens_predicted_seconds_total")
+ server_work_s = prompt_s + predict_s
+ overlap_ratio = server_work_s / wall if wall > 0 else 0.0
+ result = {
+ "port": args.port,
+ "sessions": args.sessions,
+ "max_tokens": args.max_tokens,
+ "wall_s": round(wall, 3),
+ "ok": ok,
+ "total": len(results),
+ "results": results,
+ "metrics_before": before,
+ "metrics_after": after,
+ "metrics": {
+ "prompt_tokens": prompt_tokens,
+ "predicted_tokens": predicted_tokens,
+ "prompt_seconds": round(prompt_s, 3),
+ "predicted_seconds": round(predict_s, 3),
+ "server_work_s": round(server_work_s, 3),
+ "overlap_ratio": round(overlap_ratio, 2),
+ "completion_tokens_reported": completion_total,
+ },
+ }
+ print(f"[sessions] {ok}/{len(results)} requests returned 200 in {wall:.2f} s "
+ f"(sum of request walls {sum(r.get('wall_s') or 0 for r in results):.2f} s)", flush = True)
+ print(f"[sessions] server work {server_work_s:.2f} s vs wall {wall:.2f} s "
+ f"(overlap {overlap_ratio:.2f}x); metrics counted {predicted_tokens:.0f} predicted "
+ f"tokens, responses reported {completion_total}", flush = True)
+ for r in results:
+ print(f"[sessions] {r['index']}: status {r.get('status')} "
+ f"wall {r.get('wall_s')} s tokens {r.get('completion_tokens')} "
+ f"finish {r.get('finish_reason')}"
+ + (f" error {r['error']}" if r.get("error") else ""), flush = True)
+ if args.out:
+ with open(args.out, "w", encoding = "utf8") as f:
+ json.dump(result, f, indent = 1)
+ print(f"[sessions] wrote {args.out}", flush = True)
+ if ok != len(results):
+ raise SystemExit(f"session smoke failed: {ok}/{len(results)} requests returned 200")
+ if not after_m:
+ raise SystemExit("session smoke failed: /metrics was unavailable or empty")
+ if predicted_tokens < completion_total:
+ raise SystemExit(f"session smoke failed: metrics counted {predicted_tokens:.0f} predicted "
+ f"tokens but responses reported {completion_total}")
+ if args.sessions > 1 and overlap_ratio < MIN_OVERLAP_RATIO:
+ raise SystemExit(f"session smoke failed: requests did not overlap "
+ f"(server work {server_work_s:.2f} s vs wall {wall:.2f} s, "
+ f"ratio {overlap_ratio:.2f} < {MIN_OVERLAP_RATIO})")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--port", type = int, default = 8299)
+ ap.add_argument("--model", default = "glm-5.3-exl3")
+ ap.add_argument("--sessions", type = int, default = 4)
+ ap.add_argument("--max-tokens", type = int, default = 128)
+ ap.add_argument("--timeout", type = float, default = 1200.0)
+ ap.add_argument("--out", default = None)
+ args = ap.parse_args()
+ asyncio.run(run(args))
+
+
+if __name__ == "__main__":
+ main()