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++
setup: bench-data recommendations (tips only), calibrate tries more pool-worker counts
Niko12213772ded7c669
diff --git a/setup.py b/setup.pyindex 8bc23ed9b..e496869b7 100644--- a/setup.py+++ b/setup.py@@ -462,6 +462,58 @@ def recommend_pool_workers(args: list) -> list:return [*args, "--pool-workers", str(n)]+def linux_sockets(sys_root: str = "/sys"):+ """(sockets, physical cores per socket) from the kernel's topology files, or None when they do not say."""+ cores = {}+ for cpu in (Path(sys_root) / "devices" / "system" / "cpu").glob("cpu[0-9]*"):+ pkg, core = cpu / "topology" / "physical_package_id", cpu / "topology" / "core_id"+ try:+ cores.setdefault(pkg.read_text(encoding="utf-8").strip(), set()).add(core.read_text(encoding="utf-8").strip())+ except OSError:+ return None+ return (len(cores), min(len(c) for c in cores.values())) if cores else None+++def cpu_sockets():+ """(sockets, physical cores per socket); None when unknown. Windows: the packages and cores that+ GetLogicalProcessorInformationEx lists (RelationProcessorPackage 3, RelationProcessorCore 0)."""+ try:+ if not WIN:+ return linux_sockets()+ k32 = ctypes.windll.kernel32+ counts = {}+ for rel in (0, 3):+ n = ctypes.c_ulong(0)+ k32.GetLogicalProcessorInformationEx(rel, None, ctypes.byref(n))+ if not n.value:+ return None+ buf = ctypes.create_string_buffer(n.value)+ if not k32.GetLogicalProcessorInformationEx(rel, buf, ctypes.byref(n)):+ return None+ raw, at, c = buf.raw[:n.value], 0, 0+ while at + 8 <= len(raw):+ size = struct.unpack_from("<II", raw, at)[1]+ if size <= 0:+ break+ c += 1+ at += size+ counts[rel] = c+ return (counts[3], counts[0] // counts[3]) if counts[3] else None+ except Exception:+ return None+++def two_socket_note(sockets) -> list[str]:+ """Bench #674 #707 (2-socket Xeons: 17-18 workers beat 35 by ~20%): a tip to keep the expert pool on one socket's+ cores, one fewer for the host loop. Nothing is written to the config."""+ if not sockets or sockets[0] < 2 or sockets[1] < 3:+ return []+ n = sockets[1] - 1+ return [f"tip: this PC has {sockets[0]} CPU sockets of {sockets[1]} cores. Expert workers on the other socket have "+ f"been measured slower than fewer, local ones (35 vs 17-18 on 2-socket Xeons): try --pool-workers {n} in "+ "the config's args (START-HERE --calibrate measures it on this PC)"]++def cpu_info():"""(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI),the same test the engine makes (cpu_avx512_ok), not just AVX-512F."""@@ -3537,6 +3589,51 @@ def parallel_note(asked: int | None, vram_gbs, arena_gb: float, ctx: int, kv: streturn lines+PREFILL_BIG_RAM_GB = 96 # bench #433 #440 #834 #669: --prefill auto:32768 +21-35% at 96 GB, ~3x slower at 32 GB+PREFILL_RISK_RAM_GB = 64 # below this an explicit auto:32768 is warned about+HEADROOM_RAM_GB = 48 # bench #834: STRATA_RESIDENT_HEADROOM_GIB=6 on a PC with this much RAM or less+AGENT_CACHE_FREE_GB = 24 # bench #882 #440: RAM left beside the model for the conversation cache+AGENT_CACHE_MIB = 8192+SMALL_VISION_VRAM_GB = 12.5 # bench #469: the GPU image encoder shrinks the prompt chunks on cards up to 12 GB+++def arg_after(args, flag):+ """The value after `flag` in an argument list, or None."""+ return args[args.index(flag) + 1] if flag in args[:-1] else None+++def bench_tips(args, env, ram: float, model_ram_gb: float, vram_gb: float, vision: str, win: bool) -> list[str]:+ """Recommendations from the community bench data (plan 0.1.40 item 14). Text only: nothing here changes a+ default, the config or the engine's arguments (recommend, never force). `ram` is this PC's RAM, `model_ram_gb`+ what the chosen model keeps in it."""+ tips = []+ cache = arg_after(args, "--expert-cache")+ if win and cache is not None and cache != "auto":+ tips.append(f"warning: --expert-cache {cache} is a fixed size. On Windows, a size that leaves almost no VRAM free "+ "has run up to 7x slower (#780 #781); a smaller number, or auto, leaves the driver room")+ prefill = arg_after(args, "--prefill")+ if prefill == "auto:32768" and ram < PREFILL_RISK_RAM_GB:+ tips.append(f"warning: --prefill auto:32768 on {ram:.0f} GB of RAM: it ran ~3x slower than --prefill auto with "+ "32 GB (#834 #669); it paid off (+21-35%) with 96 GB")+ elif prefill == "auto" and ram >= PREFILL_BIG_RAM_GB:+ tips.append(f"tip: with {ram:.0f} GB of RAM, --prefill auto:32768 in the config's args read prompts 21-35% "+ "faster in community benchmarks (#433 #440 #834); not set, nothing changes")+ resident = any(a in args for a in ("--resident-experts", "--resident-budget-gib"))+ if resident and ram <= HEADROOM_RAM_GB and "STRATA_RESIDENT_HEADROOM_GIB" not in (env or {}):+ tips.append(f"tip: on a PC with {ram:.0f} GB of RAM, \"env\": {{\"STRATA_RESIDENT_HEADROOM_GIB\": \"6\"}} in the "+ "config kept decode speed in a community benchmark and left the system 2 GiB more (#834); the "+ "default is 4")+ if "--conversation-cache-mib" not in args and ram - model_ram_gb >= AGENT_CACHE_FREE_GB:+ tips.append(f"tip: for several agents or clients at once, --conversation-cache-mib {AGENT_CACHE_MIB} in the "+ "config's args keeps each one's conversation; without it they were measured re-reading ~90% of "+ "their prompts (#882 #440; docs/DETAILS.md, Multiple conversations)")+ if vision == "gpu" and 0 < vram_gb <= SMALL_VISION_VRAM_GB:+ tips.append("tip: the image encoder on the GPU makes a prompt's chunks smaller on a card this size (243 vs 750 "+ "tok/s measured, #469); run setup again with --vision cpu to read prompts ~3x faster, at about "+ "2-3 s per picture")+ return tips++DISPLAY_RESERVE_MIB = 1500 # #779: the tip for an NVIDIA card that also drives a displayDESKTOP_RESERVE_MIB = 3072 # #560 #516: what kept a KDE/Wayland desktop alive beside a full expert cache@@ -4599,6 +4696,10 @@ def main() -> int:ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else ""))else: # #642: measured counts (a calibration) win over the rulecfg["args"] = recommend_pool_workers(cfg["args"])+ for line in two_socket_note(cpu_sockets()): # bench tips: text only, the config is not touched+ say(" " + line)+ for line in bench_tips(cfg["args"], cfg.get("env"), ram, MODELS[model]["ram_gb"], gpu.get("vram_gb", 0.0), vision, WIN):+ say(" " + line)write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None)script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)# offered only when someone answers: --yes installs and adopted earlier installs are not held up by itdiff --git a/tools/calibrate.py b/tools/calibrate.pyindex 779005623..48d79c1ee 100644--- a/tools/calibrate.py+++ b/tools/calibrate.py@@ -60,15 +60,32 @@ def with_arg(args: list[str], flag: str, value: str | None) -> list[str]:return out-def worker_candidates(default: int) -> list[int]:- """The engine's own count, and fewer: two thirds and a half (at least 2), without repeats."""+def worker_candidates(default: int, extra=()) -> list[int]:+ """The engine's own count, and fewer: two thirds, a half and a quarter (at least 2), plus `extra` (the P-cores+ minus one on a hybrid CPU, one socket's cores minus one on a 2-socket PC), without repeats. Bench #780 #815+ #707 #674: 4 beat 15 by 28.7% on 8P + 16E; 17-18 beat 35 by ~20% on 2-socket Xeons."""c = [default]- for w in (round(default * 2 / 3), round(default / 2)):- if w >= 2 and w not in c:+ for w in (round(default * 2 / 3), round(default / 2), round(default / 4), *extra):+ if 2 <= w < default and w not in c:c.append(w)return c+def host_worker_extras() -> list[int]:+ """P-cores - 1 (hybrid CPU) and one socket's cores - 1 (several sockets) of this PC: more counts to try."""+ try:+ import setup+ out = []+ cores, sockets = setup.cpu_cores(), setup.cpu_sockets()+ if cores:+ out.append(cores[0] - 1)+ if sockets and sockets[0] >= 2:+ out.append(sockets[1] - 1)+ return out+ except Exception:+ return []++def pick(measured: dict, default_key, min_gain: float = MIN_GAIN):"""The key with the best median tok/s, or `default_key` unless the best beats it by more than min_gain."""med = {k: statistics.median(v) for k, v in measured.items() if v}@@ -119,7 +136,7 @@ def run(cfg: dict, say=print, start_engine=None) -> dict:tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"),json.loads((tpath / "token_type.json").read_text()))ids_list = [chat_ids(tok, p) for p in PROMPTS]- return measure(engine_args(cfg), ids_list, start_engine, say)+ return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras())def engine_args(cfg: dict) -> list[str]:@@ -145,7 +162,7 @@ def engine_error(log: str | None, since: int = 0) -> str | None:return next((x for x in reversed(lines) if x.startswith(("strata", "ERR"))), lines[-1] if lines else None)-def measure(base_args: list[str], ids_list, start_engine, say=print) -> dict:+def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=()) -> dict:t0 = time.time()report: dict = {}say(" Loading the model for the measurements ...")@@ -190,10 +207,10 @@ def measure(base_args: list[str], ids_list, start_engine, say=print) -> dict:settings["--spec-min-p"] = f"{chosen[1]:.2f}"base_rate = statistics.median(confirm[chosen]) if confirm.get(chosen) else None# 4. fewer CPU workers (a restart each), with the chosen settings- if d_workers and len(worker_candidates(d_workers)) > 1:+ if d_workers and len(worker_candidates(d_workers, extra_workers)) > 1:tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}")by_workers = {}- for w in worker_candidates(d_workers):+ for w in worker_candidates(d_workers, extra_workers):say(f" Measuring with {w} CPU workers (restarts the engine) ...")e = start_engine(with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)))try:diff --git a/tools/test_calibrate.py b/tools/test_calibrate.pyindex a03286c5a..61adf0ca4 100644--- a/tools/test_calibrate.py+++ b/tools/test_calibrate.py@@ -113,7 +113,7 @@ class Calibrate(unittest.TestCase):(tok / "token_type.json").write_text(json.dumps([1, 1]))seen = []saved = CAL.measure- CAL.measure = lambda args, ids_list, start_engine, say=print: seen.append(args) or {}+ CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(): seen.append(args) or {}fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()})try:with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}):@@ -140,8 +140,11 @@ class Calibrate(unittest.TestCase):self.assertIsNone(CAL.engine_error(str(Path(d) / "missing.log")))def test_worker_candidates(self):- self.assertEqual(CAL.worker_candidates(6), [6, 4, 3])- self.assertEqual(CAL.worker_candidates(23), [23, 15, 12])+ self.assertEqual(CAL.worker_candidates(6), [6, 4, 3, 2])+ self.assertEqual(CAL.worker_candidates(23), [23, 15, 12, 6]) # a quarter: 4 beat 15 on 8P + 16E+ self.assertEqual(CAL.worker_candidates(23, (7,)), [23, 15, 12, 6, 7]) # P-cores - 1+ self.assertEqual(CAL.worker_candidates(35, (17,)), [35, 23, 18, 9, 17]) # 2 sockets: one socket's cores - 1+ self.assertEqual(CAL.worker_candidates(6, (6, 1, 9)), [6, 4, 3, 2]) # none above the default, none below 2self.assertEqual(CAL.worker_candidates(3), [3, 2])self.assertEqual(CAL.worker_candidates(1), [1])diff --git a/tools/test_setup_bench_tips.py b/tools/test_setup_bench_tips.pynew file mode 100644index 000000000..141f377b9--- /dev/null+++ b/tools/test_setup_bench_tips.py@@ -0,0 +1,99 @@+"""Setup's recommendations from the community bench data (0.1.40): text only, never a changed default.++ python -m unittest tools.test_setup_bench_tips+"""+from __future__ import annotations++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 setup # noqa: E402+from test_setup_hybrid import fake_sys # noqa: E402++BASE = ["--expert-cache", "auto", "--prefill", "auto", "--max-context", "65536"]+++def tips(args=BASE, env=None, ram=32.0, model=20.0, vram=12.0, vision="none", win=False):+ return setup.bench_tips(list(args), env, ram, model, vram, vision, win)+++class BenchTips(unittest.TestCase):+ def test_nothing_to_say_on_a_plain_pc(self):+ self.assertEqual(tips(), [])++ def test_explicit_cache_warns_on_windows_only(self):+ a = ["--expert-cache", "2400", "--prefill", "auto"]+ self.assertTrue(any("--expert-cache 2400" in t and "7x" in t for t in tips(a, win=True)))+ self.assertEqual(tips(a, win=False), [])+ self.assertEqual(tips(BASE, win=True), []) # auto: nothing to warn about++ def test_prefill_auto_32768_follows_the_ram(self):+ self.assertTrue(any("auto:32768" in t and t.startswith("tip") for t in tips(ram=128)))+ self.assertEqual([t for t in tips(ram=64) if "auto:32768" in t], [])+ big = ["--prefill", "auto:32768"]+ self.assertTrue(any(t.startswith("warning") and "auto:32768" in t for t in tips(big, ram=32)))+ self.assertEqual([t for t in tips(big, ram=96) if "auto:32768" in t], [])++ def test_resident_headroom_on_small_ram(self):+ res = [*BASE, "--resident-experts"]+ self.assertTrue(any("STRATA_RESIDENT_HEADROOM_GIB" in t for t in tips(res, ram=32)))+ self.assertTrue(any("STRATA_RESIDENT_HEADROOM_GIB" in t for t in tips([*BASE, "--resident-budget-gib", "40"], ram=48)))+ self.assertEqual([t for t in tips(res, ram=64) if "HEADROOM" in t], [])+ self.assertEqual([t for t in tips(res, {"STRATA_RESIDENT_HEADROOM_GIB": "8"}, ram=32) if "HEADROOM" in t], [])+ self.assertEqual([t for t in tips(BASE, ram=32) if "HEADROOM" in t], []) # not a resident config++ def test_conversation_cache_for_agents(self):+ self.assertTrue(any("--conversation-cache-mib 8192" in t for t in tips(ram=64, model=40)))+ self.assertEqual([t for t in tips(ram=64, model=41) if "conversation" in t], []) # < 24 GB left+ self.assertEqual([t for t in tips([*BASE, "--conversation-cache-mib", "4096"], ram=128) if "conversation" in t], [])++ def test_vision_cpu_on_small_cards(self):+ self.assertTrue(any("--vision cpu" in t for t in tips(vision="gpu", vram=12)))+ self.assertEqual([t for t in tips(vision="gpu", vram=24) if "vision" in t], [])+ self.assertEqual([t for t in tips(vision="cpu", vram=12) if "vision" in t], [])++ def test_tips_never_touch_the_arguments(self):+ a = ["--expert-cache", "2400", "--prefill", "auto", "--resident-experts"]+ before = list(a)+ env = {}+ tips(a, env, ram=128, vision="gpu", win=True)+ self.assertEqual(a, before)+ self.assertEqual(env, {})+++class Sockets(unittest.TestCase):+ def fake(self, d, sockets, cores):+ n = 0+ for s in range(sockets):+ for c in range(cores):+ t = Path(d) / "devices" / "system" / "cpu" / f"cpu{n}" / "topology"+ t.mkdir(parents=True)+ (t / "physical_package_id").write_text(str(s))+ (t / "core_id").write_text(str(c))+ n += 1++ def test_linux_sockets(self):+ with tempfile.TemporaryDirectory() as d:+ self.fake(d, 2, 18)+ self.assertEqual(setup.linux_sockets(d), (2, 18))+ with tempfile.TemporaryDirectory() as d:+ self.fake(d, 1, 8)+ self.assertEqual(setup.linux_sockets(d), (1, 8))+ with tempfile.TemporaryDirectory() as d:+ self.assertIsNone(setup.linux_sockets(d))++ def test_two_socket_tip(self):+ t = setup.two_socket_note((2, 18))+ self.assertEqual(len(t), 1)+ self.assertIn("--pool-workers 17", t[0])+ self.assertEqual(setup.two_socket_note((1, 18)), [])+ self.assertEqual(setup.two_socket_note(None), [])+++if __name__ == "__main__":+ unittest.main()