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++
calibrate: the engine's arguments come from the server's engine_args; a failed tuning says why (#447)
Niko12210e4c3e8727c1
diff --git a/setup.py b/setup.pyindex a8898796b..81e60e342 100644--- a/setup.py+++ b/setup.py@@ -2295,10 +2295,17 @@ def calibrate_config(cfg_path: Path) -> bool:say()say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the")say(" draft depth, the CPU threads). It takes about 5-10 minutes; the PC is busy meanwhile.")+ try:+ since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0+ except OSError:+ since = 0try:res = CAL.run(cfg, say=say)except Exception as e: # never stops an install: the defaults staywarn(f"the tuning did not finish ({e}): the default settings stay")+ why = CAL.engine_error(cfg.get("log"), since) # #447: the engine's own reason, not only "see the log"+ if why:+ say(f" the engine said: {why}")return Falsecfg["args"] = CAL.apply(cfg["args"], res["settings"])write_config(cfg_path, cfg)@@ -2685,7 +2692,10 @@ def main() -> int:for i, c in enumerate(have, 1):say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1]- calibrate_config(pick_cfg)+ if not calibrate_config(pick_cfg): # #447: said again where it is not lost above the start+ say()+ warn("this PC is NOT tuned: the tuning failed (the reason is above); the model "+ + ("keeps" if a.no_start else "starts with") + " the default settings")return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab})if have and not (a.setup or a.model or a.family or a.check or a.no_start):@@ -3263,7 +3273,9 @@ def main() -> int:if cal is None and not hip and not a.no_start and not a.yes and ask("Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy ""meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y":- calibrate_config(cfg_path)+ tuned = calibrate_config(cfg_path)+ else:+ tuned = None # not asked for: nothing to repeat belowok(f"start script: {script.name}")say()@@ -3276,6 +3288,9 @@ def main() -> int:say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")if vision != "none":say(" Images: send them in the chat page, in chat.py (/image <path>) or over the API")+ if tuned is False: # #447: a failed tuning is repeated here, not only above+ say(" Tuning: FAILED (the reason is above): the default settings stay - "+ f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again")if a.no_start:return 0return start(cfg_path, port)diff --git a/tools/calibrate.py b/tools/calibrate.pyindex b237c93bd..779005623 100644--- a/tools/calibrate.py+++ b/tools/calibrate.py@@ -119,10 +119,30 @@ 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]- args = list(cfg["args"])- if isinstance(cfg.get("gpu"), list) and "--layer-split" not in args: # several cards: measured as it runs- args += ["--layer-split", str(cfg.get("layer_split") or "auto")]- return measure(args, ids_list, start_engine, say)+ return measure(engine_args(cfg), ids_list, start_engine, say)+++def engine_args(cfg: dict) -> list[str]:+ """The arguments the server starts this config's engine with (serve.server.engine_args), so the tuning measures+ the engine as it runs. #447: this used to read any "gpu" list as a layer split and add --layer-split auto, which+ broke a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1: the engine+ refuses a split that leaves no card without a stage), missed the "0,2" spelling, and ignored split_skip_if_fits."""+ from serve.server import engine_args as server_args+ return server_args(cfg)+++def engine_error(log: str | None, since: int = 0) -> str | None:+ """#447: the engine's own reason for a failed start - the last line of its log written after byte `since` that is+ its own ("strata ..." or "ERR ..."), else the last line there; None without a log or a new line."""+ if not log:+ return None+ try:+ with open(log, "rb") as f:+ f.seek(since)+ lines = [x.strip() for x in f.read()[-16384:].decode("utf-8", "replace").splitlines() if x.strip()]+ except OSError:+ return 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:diff --git a/tools/test_calibrate.py b/tools/test_calibrate.pyindex c97d348fe..a03286c5a 100644--- a/tools/test_calibrate.py+++ b/tools/test_calibrate.py@@ -11,6 +11,7 @@ import sysimport tempfileimport unittestfrom pathlib import Path+from unittest import mockROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "tools"))@@ -91,6 +92,53 @@ class Calibrate(unittest.TestCase):self.assertIsNone(CAL.arg_value(b, "--pool-workers"))self.assertEqual(b.count("--spec-min-p"), 1)+ def test_engine_args_are_the_servers(self):+ # #447: a "gpu" list is a layer split only with two or more cards; "0,2" is one too; split_skip_if_fits counts+ helper = {"args": BASE + ["--expert-cache-device1", "1800"], "gpu": [0], "env": {"CUDA_VISIBLE_DEVICES": "0,1"}}+ self.assertEqual(CAL.engine_args(helper), helper["args"]) # one stage + a helper card: no split+ self.assertEqual(CAL.engine_args({"args": BASE, "gpu": 1}), BASE)+ self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 2]}), BASE + ["--layer-split", "auto"])+ self.assertEqual(CAL.engine_args({"args": BASE, "gpu": "0,2", "layer_split": "18"}),+ BASE + ["--layer-split", "18"])+ self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 1], "split_skip_if_fits": True}),+ BASE + ["--layer-split", "auto", "--split-skip-if-fits"])+ own = BASE + ["--layer-split", ""] # the config's own value wins+ self.assertEqual(CAL.engine_args({"args": own, "gpu": [0, 1]}), own)++ def test_run_measures_with_the_servers_args(self):+ with tempfile.TemporaryDirectory() as d:+ tok = Path(d)+ (tok / "vocab.json").write_text(json.dumps({"a": 0, "b": 1}))+ (tok / "merges.txt").write_text("")+ (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 {}+ fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()})+ try:+ with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}):+ CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0]}, start_engine=lambda a: None)+ finally:+ CAL.measure = saved+ self.assertEqual(seen, [BASE])++ def test_engine_error(self):+ with tempfile.TemporaryDirectory() as d:+ log = Path(d) / "strata-x.log"+ log.write_text("strata generate: an old error\n", encoding="utf-8")+ since = log.stat().st_size+ with open(log, "a", encoding="utf-8") as f:+ f.write("loading ...\nstrata generate: --expert-cache-remote with a layer split needs a GPU that runs "+ "no stage (2 visible, 2 used by the split)\n\n")+ self.assertEqual(CAL.engine_error(str(log), since), "strata generate: --expert-cache-remote with a layer "+ "split needs a GPU that runs no stage (2 visible, 2 used by the split)")+ with open(log, "a", encoding="utf-8") as f:+ f.write("Segmentation fault\n")+ self.assertIn("--expert-cache-remote", CAL.engine_error(str(log), since)) # the engine's own line first+ self.assertEqual(CAL.engine_error(str(log), log.stat().st_size), None) # nothing new since+ self.assertIsNone(CAL.engine_error(None))+ 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])@@ -152,6 +200,35 @@ class SetupIntegration(unittest.TestCase):self.assertEqual(json.loads(cfg_path.read_text())["args"], BASE)self.assertIsNone(self.S.saved_calibration({"args": BASE, "model_name": "m"}))+ def test_failed_calibration_says_the_engines_reason(self):+ # #447: the engine's last error line is printed, and the --calibrate run repeats the failure before it starts+ import contextlib+ import io+ log = Path(self.tmp.name) / "strata-q2_0.log"+ log.write_text("strata generate: an error of an earlier start\n", encoding="utf-8")+ cfg_path = Path(self.tmp.name) / "strata-q2_0.json"+ cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m", "log": str(log)}))++ def boom(*a, **k):+ with open(log, "a", encoding="utf-8") as f:+ f.write("strata generate: --expert-cache-remote with a layer split needs a GPU that runs no stage\n")+ raise RuntimeError(f"the engine exited before it was ready (see {log})")+ CAL.run = boom+ out = io.StringIO()+ with contextlib.redirect_stdout(out):+ self.assertFalse(self.S.calibrate_config(cfg_path))+ self.assertIn("the engine said: strata generate: --expert-cache-remote with a layer split", out.getvalue())+ self.assertNotIn("an earlier start", out.getvalue())+ out = io.StringIO()+ with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \+ mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \+ mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \+ mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \+ contextlib.redirect_stdout(out):+ self.assertEqual(self.S.main(), 0)+ self.assertIn("this PC is NOT tuned: the tuning failed (the reason is above); the model keeps the default "+ "settings", out.getvalue())+if __name__ == "__main__":unittest.main()