Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
tools: batch_test.py takes up to 32 prompts (folds in havok2-htwo's batch_test16.py and batch_test32.py)
Niko1221db568409fc92
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 69b7cdf86..1693cfc08 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -1821,7 +1821,7 @@ the pairs in which the switched arm won). They are here so you can try them on y180-2,619 tokens - on the 4-GPU split with `--prefill 2048` (chunks of 1,024 tokens and more: the streamed walk),the same with 9 GB less expert cache per GPU (20-31% of the expert reads streamed, so groups mix in-place, copied andmid-group flushed experts), and on one GPU with `--expert-cache-per-layer`; the 150 greedy tokens of each of- `tools/batch_test16.py`'s 16 prompts (solo and batch) were identical too, and to those of a build without the+ `tools/batch_test.py --n 16` prompts (solo and batch) were identical too, and to those of a build without theoption. The uniform cache (no profile) holds no resident expert when a native pack's prompt is read (serve needs theprofile, and a one-shot run fills the cache only while it decodes), so `expert_cache_slot_guard_test` covers it.diff --git a/tools/batch_test.py b/tools/batch_test.pyindex 5dd61f548..78060b3dc 100644--- a/tools/batch_test.py+++ b/tools/batch_test.py@@ -20,7 +20,17 @@ QUESTIONS = ["Explain how a transformer's attention works, step by step.","Donne une recette de tarte aux pommes, etape par etape.","Describe the life cycle of a star like the Sun.",+ "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.",+ "Write a Rust function that parses a CSV line with quoted fields, then explain it.",+ "What were the main consequences of the invention of the printing press?",+ "Explique le theoreme de Pythagore avec trois demonstrations differentes.",+ "Describe how the immune system responds to a viral infection.",+ "Explain the difference between processes and threads in an operating system.",+ "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.",+ "How does public-key cryptography work? Give an example with RSA.",]+# more than 16 slots: the same questions again, asked to answer in German+QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS]def tokenizer(path):diff --git a/tools/batch_test16.py b/tools/batch_test16.pydeleted file mode 100644index 77686d5ce..000000000--- a/tools/batch_test16.py+++ /dev/null@@ -1,181 +0,0 @@-#!/usr/bin/env python3-"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch-windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate.-- python3 tools/batch_test.py --exe engine/strata --config strata-<model>.json --batch 4 --n 4 \- --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000"-"""-import argparse, json, os, subprocess, sys, tempfile, threading, time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-import strata_tokenizer as ST # noqa: E402--QUESTIONS = [- "Explique en detail le fonctionnement d'un B-tree.",- "Write a Python function that merges overlapping intervals, then explain it.",- "Compare TCP and QUIC: handshake, congestion control, multiplexing.",- "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.",- "What are the main causes of the French Revolution?",- "Explain how a transformer's attention works, step by step.",- "Donne une recette de tarte aux pommes, etape par etape.",- "Describe the life cycle of a star like the Sun.",- "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.",- "Write a Rust function that parses a CSV line with quoted fields, then explain it.",- "What were the main consequences of the invention of the printing press?",- "Explique le theoreme de Pythagore avec trois demonstrations differentes.",- "Describe how the immune system responds to a viral infection.",- "Explain the difference between processes and threads in an operating system.",- "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.",- "How does public-key cryptography work? Give an example with RSA.",-]---def tokenizer(path):- t = Path(path)- vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))- tokens = [None] * len(vocab)- for s, i in vocab.items():- tokens[i] = s- merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n")- types = json.loads((t / "token_type.json").read_text())- return ST.Tokenizer(tokens, merges, types)---class Engine:- def __init__(self, exe, cfg, batch, extra_env, extra_args):- args = list(cfg["args"])- if len(cfg.get("gpu") or []) > 1:- args += ["--layer-split", str(cfg.get("layer_split") or "auto")]- if batch:- args += ["--batch", str(batch)]- args += extra_args- env = dict(os.environ, **extra_env)- env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")])- if os.name == "nt":- env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")])- self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log")- self.log = open(self.log_path, "w")- self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE,- stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env)- for line in self.p.stdout:- if line.startswith("READY"):- return- raise SystemExit(f"the engine ended before READY - see {self.log_path}")-- def send(self, line):- self.p.stdin.write(line + "\n")- self.p.stdin.flush()-- def lines(self):- for line in self.p.stdout:- yield line.rstrip("\n")---def main():- ap = argparse.ArgumentParser()- ap.add_argument("--exe", required=True)- ap.add_argument("--config", required=True)- ap.add_argument("--batch", type=int, default=4)- ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)")- ap.add_argument("--max-new", type=int, default=64)- ap.add_argument("--skip-solo", action="store_true")- ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"')- ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"')- ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds")- ap.add_argument("--long-tokens", type=int, default=0,- help="the LAST prompt is read from about this many tokens of filler text first: its chunks run "- "beside the earlier slots' windows (the prompt path lends experts then)")- ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)")- a = ap.parse_args()- cfg = json.loads(Path(a.config).read_text())- tok = tokenizer(cfg["tokenizer"])- prompts = []- for q in QUESTIONS[: a.n]:- text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"- if a.long_tokens and q is QUESTIONS[a.n - 1]:- para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open "- "risks, and asked the staff to report back next quarter. ")- per = max(1, len(tok.encode(para % 100)))- filler = "".join(para % i for i in range(a.long_tokens // per + 1))- text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"- prompts.append(tok.encode(text, parse_special=True))- env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})}- if a.mt_min:- env["STRATA_IQ_MT_MIN"] = a.mt_min- eng = Engine(a.exe, cfg, a.batch, env, a.extra.split())- out = eng.lines()-- solo = []- if not a.skip_solo:- for i, ids in enumerate(prompts):- eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x))- got, t0 = [], time.time()- for line in out:- if line.startswith("T "):- got.append(int(line.split()[1]))- elif line.startswith("DONE") or line.startswith("ERR"):- print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True)- break- solo.append(got)-- # batch: admit every prompt, then the slots decode together- got = {i: [] for i in range(len(prompts))}- done = {}- t_admit = time.time()- first_bt = None- for i, ids in enumerate(prompts):- eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x))- for line in out:- if line.startswith("T "):- got[i].append(int(line.split()[1]))- elif line.startswith("BT "):- _, s, y = line.split()- got[int(s)].append(int(y))- first_bt = first_bt or time.time()- elif line.startswith("BDONE "):- done[int(line.split()[1])] = line- elif line.startswith("ERR"):- print("batch:", line)- return 1- elif line.startswith("BADM "):- if line.split()[2] == "0":- done[i] = line- break- t_admitted = time.time()- for line in out:- if line.startswith("BT "):- _, s, y = line.split()- got[int(s)].append(int(y))- first_bt = first_bt or time.time()- elif line.startswith("BDONE "):- done[int(line.split()[1])] = line- if len(done) == len(prompts):- break- elif line.startswith("ERR"):- print("batch:", line)- return 1- t_end = time.time()- total = sum(len(v) for v in got.values())- print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; "- f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, "- f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token",- flush=True)- ok = True- for i in range(len(prompts)):- b = got[i]- if solo:- same = b == solo[i]- ok &= same- first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None)- print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}")- print(" ", ascii(tok.decode(b)[:160]))- if a.dump:- Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8")- eng.send("QUIT")- eng.p.wait(timeout=180) # the next run needs the GPUs back- return 0 if ok else 2---if __name__ == "__main__":- sys.exit(main())diff --git a/tools/batch_test32.py b/tools/batch_test32.pydeleted file mode 100644index fd60e26bd..000000000--- a/tools/batch_test32.py+++ /dev/null@@ -1,183 +0,0 @@-#!/usr/bin/env python3-"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch-windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate.-- python3 tools/batch_test.py --exe engine/strata --config strata-<model>.json --batch 4 --n 4 \- --extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000"-"""-import argparse, json, os, subprocess, sys, tempfile, threading, time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-import strata_tokenizer as ST # noqa: E402--QUESTIONS = [- "Explique en detail le fonctionnement d'un B-tree.",- "Write a Python function that merges overlapping intervals, then explain it.",- "Compare TCP and QUIC: handshake, congestion control, multiplexing.",- "Raconte l'histoire du calcul de pi, d'Archimede a nos jours.",- "What are the main causes of the French Revolution?",- "Explain how a transformer's attention works, step by step.",- "Donne une recette de tarte aux pommes, etape par etape.",- "Describe the life cycle of a star like the Sun.",- "Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert.",- "Write a Rust function that parses a CSV line with quoted fields, then explain it.",- "What were the main consequences of the invention of the printing press?",- "Explique le theoreme de Pythagore avec trois demonstrations differentes.",- "Describe how the immune system responds to a viral infection.",- "Explain the difference between processes and threads in an operating system.",- "Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen.",- "How does public-key cryptography work? Give an example with RSA.",-]--QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS]---def tokenizer(path):- t = Path(path)- vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))- tokens = [None] * len(vocab)- for s, i in vocab.items():- tokens[i] = s- merges = (t / "merges.txt").read_text(encoding="utf-8").split("\n")- types = json.loads((t / "token_type.json").read_text())- return ST.Tokenizer(tokens, merges, types)---class Engine:- def __init__(self, exe, cfg, batch, extra_env, extra_args):- args = list(cfg["args"])- if len(cfg.get("gpu") or []) > 1:- args += ["--layer-split", str(cfg.get("layer_split") or "auto")]- if batch:- args += ["--batch", str(batch)]- args += extra_args- env = dict(os.environ, **extra_env)- env["LD_LIBRARY_PATH"] = ":".join(cfg.get("lib_dirs", []) + [env.get("LD_LIBRARY_PATH", "")])- if os.name == "nt":- env["PATH"] = os.pathsep.join(cfg.get("lib_dirs", []) + [env.get("PATH", "")])- self.log_path = os.environ.get("BATCH_TEST_LOG") or os.path.join(tempfile.gettempdir(), "batch_test_engine.log")- self.log = open(self.log_path, "w")- self.p = subprocess.Popen([exe, "--serve", *args], cwd=cfg.get("cwd"), stdin=subprocess.PIPE,- stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=env)- for line in self.p.stdout:- if line.startswith("READY"):- return- raise SystemExit(f"the engine ended before READY - see {self.log_path}")-- def send(self, line):- self.p.stdin.write(line + "\n")- self.p.stdin.flush()-- def lines(self):- for line in self.p.stdout:- yield line.rstrip("\n")---def main():- ap = argparse.ArgumentParser()- ap.add_argument("--exe", required=True)- ap.add_argument("--config", required=True)- ap.add_argument("--batch", type=int, default=4)- ap.add_argument("--n", type=int, default=4, help="prompts (<= --batch)")- ap.add_argument("--max-new", type=int, default=64)- ap.add_argument("--skip-solo", action="store_true")- ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"')- ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"')- ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds")- ap.add_argument("--long-tokens", type=int, default=0,- help="the LAST prompt is read from about this many tokens of filler text first: its chunks run "- "beside the earlier slots' windows (the prompt path lends experts then)")- ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)")- a = ap.parse_args()- cfg = json.loads(Path(a.config).read_text())- tok = tokenizer(cfg["tokenizer"])- prompts = []- for q in QUESTIONS[: a.n]:- text = f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"- if a.long_tokens and q is QUESTIONS[a.n - 1]:- para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open "- "risks, and asked the staff to report back next quarter. ")- per = max(1, len(tok.encode(para % 100)))- filler = "".join(para % i for i in range(a.long_tokens // per + 1))- text = f"<|im_start|>user\n{filler}\n\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"- prompts.append(tok.encode(text, parse_special=True))- env = {"STRATA_DECODE_TIMING": "1", **({"STRATA_VERIFY_PROFILE": "1"} if os.environ.get("PROF") else {})}- if a.mt_min:- env["STRATA_IQ_MT_MIN"] = a.mt_min- eng = Engine(a.exe, cfg, a.batch, env, a.extra.split())- out = eng.lines()-- solo = []- if not a.skip_solo:- for i, ids in enumerate(prompts):- eng.send(" ".join(x for x in ("GEN", str(a.max_new), a.keys, ",".join(map(str, ids))) if x))- got, t0 = [], time.time()- for line in out:- if line.startswith("T "):- got.append(int(line.split()[1]))- elif line.startswith("DONE") or line.startswith("ERR"):- print(f"solo {i}: {len(got)} tokens in {time.time() - t0:.1f}s {line[:60]}", flush=True)- break- solo.append(got)-- # batch: admit every prompt, then the slots decode together- got = {i: [] for i in range(len(prompts))}- done = {}- t_admit = time.time()- first_bt = None- for i, ids in enumerate(prompts):- eng.send(" ".join(x for x in ("BGEN", str(i), str(a.max_new), a.keys, ",".join(map(str, ids))) if x))- for line in out:- if line.startswith("T "):- got[i].append(int(line.split()[1]))- elif line.startswith("BT "):- _, s, y = line.split()- got[int(s)].append(int(y))- first_bt = first_bt or time.time()- elif line.startswith("BDONE "):- done[int(line.split()[1])] = line- elif line.startswith("ERR"):- print("batch:", line)- return 1- elif line.startswith("BADM "):- if line.split()[2] == "0":- done[i] = line- break- t_admitted = time.time()- for line in out:- if line.startswith("BT "):- _, s, y = line.split()- got[int(s)].append(int(y))- first_bt = first_bt or time.time()- elif line.startswith("BDONE "):- done[int(line.split()[1])] = line- if len(done) == len(prompts):- break- elif line.startswith("ERR"):- print("batch:", line)- return 1- t_end = time.time()- total = sum(len(v) for v in got.values())- print(f"batch: {len(prompts)} slots, {total} tokens; admissions {t_admitted - t_admit:.1f}s; "- f"then {t_end - t_admitted:.1f}s -> aggregate {total / max(t_end - t_admit, 1e-9):.1f} tok/s overall, "- f"{sum(len(v) for v in got.values()) / max(t_end - (first_bt or t_admit), 1e-9):.1f} tok/s from the first batch token",- flush=True)- ok = True- for i in range(len(prompts)):- b = got[i]- if solo:- same = b == solo[i]- ok &= same- first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None)- print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}")- print(" ", ascii(tok.decode(b)[:160]))- if a.dump:- Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8")- eng.send("QUIT")- eng.p.wait(timeout=180) # the next run needs the GPUs back- return 0 if ok else 2---if __name__ == "__main__":- sys.exit(main())