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++
Tune for this PC: setup --calibrate measures the PCIe share, draft floor and CPU workers
Niko1221c1afbdac8af4
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex a1b1d1730..9a9166863 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -199,10 +199,22 @@ START-HERE.bat --gguf-dir D:\models\IQ2_XS use GGUF files you already haveSTART-HERE.bat --data-dir E:\Strata-data keep the model files somewhere elseSTART-HERE.bat --port 8081 another portSTART-HERE.bat --gpu 1 another GPU (numbered as nvidia-smi; setup picks the one with the most VRAM)+START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start```With more than one model installed, it asks which one to start. `run-<model>.bat` starts a model directly.+**Tuning for your PC (`--calibrate`, engine 0.1.19).** Three engine settings depend on the PC more than on the model:+- the share of the experts missing from VRAM that are copied to the GPU instead of computed by the CPU+ (`--pcie-frac`: a fast PCIe link and a slower CPU want more, a laptop's narrower link less);+- how sure the draft layer must be to add another guess to a check (`--spec-min-p`);+- how many CPU threads compute experts (`--pool-workers`: on CPUs with efficiency cores, fewer can be faster).++The defaults were measured on a Ryzen 5 7600 with an RTX 5070. Setup offers to measure them on your PC after an+install; `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) does it any time. It measures the output+speed with each setting and keeps one only when it is more than 3% faster. The result is remembered per PC and model+(in the settings file next to the data folder's record), so updates keep it.+### Chat in the terminal (optional)```diff --git a/serve/server.py b/serve/server.pyindex dbfda5e67..d0e9c1f38 100644--- a/serve/server.py+++ b/serve/server.py@@ -262,6 +262,13 @@ class StrataEngine:seed = sampling.get("seed")if isinstance(seed, int) and seed > 0:keys += f" seed={seed}"+ # setup's calibration (tools/calibrate.py): engine settings for this request only, measured without a restart+ tune = sampling.get("strata_tune")+ if isinstance(tune, dict):+ for k in ("pcie_frac", "spec_min_p"):+ v = tune.get(k)+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0:+ keys += f" {k}={float(v)!r}"return keys + StrataEngine.projection_key(sampling)@staticmethoddiff --git a/serve/test_server.py b/serve/test_server.pyindex 5b2b03b10..7ce5ec9ea 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -251,6 +251,13 @@ class SamplingKeys(unittest.TestCase):for bad in (-1, True, 2.5, "20"):self.assertFalse([k for k in self.keys(temperature=0.7, top_k=bad) if k.startswith("top_k=")], bad)+ def test_tune_keys(self):+ k = self.keys(temperature=0, strata_tune={"pcie_frac": 0.2, "spec_min_p": 0.7})+ self.assertIn("pcie_frac=0.2", k)+ self.assertIn("spec_min_p=0.7", k)+ bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2})+ self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")])+def test_penalty_window(self):self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5))self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096))diff --git a/setup.py b/setup.pyindex e79632ff5..1d84f1b2b 100644--- a/setup.py+++ b/setup.py@@ -943,6 +943,50 @@ def is_wsl() -> bool:return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower()+def hardware_key(cfg: dict) -> str:+ """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting+ (the context's KV cache and the image encoder take VRAM from the expert cache)."""+ g = gpu_info(cfg.get("gpu")) or {}+ a = cfg.get("args", [])+ ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?"+ return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB",+ cfg.get("model_name", "?"), ctx, "images" if "--vision" in a else "text"])+++def calibrate_config(cfg_path: Path) -> bool:+ """Measure the engine's hardware-dependent settings on this PC (tools/calibrate.py), write them into the run+ config and remember them per PC and model in the settings file, so an update or a reinstall keeps them."""+ sys.path.insert(0, str(ROOT / "tools"))+ import calibrate as CAL+ cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))+ 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:+ res = CAL.run(cfg, say=say)+ except Exception as e: # never stops an install: the defaults stay+ warn(f"the tuning did not finish ({e}): the default settings stay")+ return False+ cfg["args"] = CAL.apply(cfg["args"], res["settings"])+ cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")+ st = load_settings()+ st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"),+ "date": time.strftime("%Y-%m-%d")}+ save_settings(st)+ if res["settings"]:+ ok("tuned for this PC: " + ", ".join(f"{k} {v}" for k, v in res["settings"].items())+ + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else ""))+ else:+ ok("tuned for this PC: the default settings are already the fastest here"+ + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else ""))+ return True+++def saved_calibration(cfg: dict) -> dict | None:+ """The settings an earlier calibration found for this PC and model, if any."""+ return (load_settings().get("calibration") or {}).get(hardware_key(cfg))++def upgrade_config(cfg_path: Path, cfg: dict) -> dict:"""Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunkitself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL,@@ -1044,6 +1088,8 @@ def main() -> int:ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL),help="where the ready-made engine is (a URL folder or a local folder)")ap.add_argument("--check", action="store_true", help="only check this PC and exit")+ ap.add_argument("--calibrate", action="store_true",+ help="tune the engine's settings for this PC (about 5-10 minutes), then start the model")ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS)a = ap.parse_args()say("Strata - Qwen3.8-Flash-Next on a normal PC (NVIDIA GPU + system RAM + CPU)")@@ -1073,6 +1119,17 @@ def main() -> int:global GPU_PICKGPU_PICK = a.gpuport = a.port or 8080 # a new install's port (issue #32: --port for an existing one)+ if have and a.calibrate and not (a.setup or a.model or a.family or a.check):+ if not a.build:+ update_installed_engine(a.prebuilt)+ pick_cfg = have[0]+ if len(have) > 1:+ say()+ 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)+ return 0 if a.no_start else start(pick_cfg, a.port, a.gpu)if have and not (a.setup or a.model or a.family or a.check or a.no_start):if not a.build:update_installed_engine(a.prebuilt)@@ -1357,8 +1414,19 @@ def main() -> int:if vision == "cpu":cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)cfg_path = ROOT / f"strata-{tag.lower()}.json"+ cal = saved_calibration(cfg)+ if cal is not None:+ sys.path.insert(0, str(ROOT / "tools"))+ import calibrate as CAL+ cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {})+ ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else ""))cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")script = write_run_script(tag, cfg_path, port)+ # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it+ if cal is None 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)ok(f"start script: {script.name}")say()diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 417309ab2..d11328be8 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -2616,13 +2616,15 @@ int main(int argc, char** argv) {size_t free_b = 0, total_b = 0;cudaMemGetInfo(&free_b, &total_b);std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d "- "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld engine=" STRATA_VERSION "\n",+ "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f "+ "spec_min_p=%.2f engine=" STRATA_VERSION "\n",(long long) o.max_context, o.kv.c_str(),(long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1? ss.qsa_states[0].n_slots * 4 : 0),(long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t,o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(),- (long long) (strata::kernels::cpu::expert_layout().total >> 20));+ (long long) (strata::kernels::cpu::expert_layout().total >> 20), pool.workers(), o.pcie_frac,+ o.spec_min_p);}// issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on// a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the@@ -2692,6 +2694,9 @@ int main(int argc, char** argv) {float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f;int req_penalty_last_n = 0;int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent)+ // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of+ // the missed experts and the draft-probability floor, for this request only+ double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;if (endp != nullptr) { // GENI takes only cvec=; its file path is the first token without an =for (;;) {while (*endp == ' ') ++endp;@@ -2714,6 +2719,8 @@ int main(int argc, char** argv) {else if (key == "penalty_freq") req_penalty_freq = fv;else if (key == "penalty_present") req_penalty_present = fv;else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10);+ else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0);+ else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0);// unknown keys are skipped: the ids start at the first token without '='}}@@ -3002,6 +3009,7 @@ int main(int argc, char** argv) {req_sp.penalty_present = req_penalty_present;req_sp.counter = 0;ver.set_sampling(req_sp);+ drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5)));const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap);ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);bool cancelled = false;@@ -3079,9 +3087,9 @@ int main(int argc, char** argv) {if (cancelled) finish = "cancel";while (!cancelled && produced_n < max_new) {int T = S_mtp;- if (o.spec_min_p > 0.0) {+ if (req_spec_min_p > 0.0) {T = 1;- while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T;+ while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T;}if (first_window) T = 1;// a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it@@ -3148,7 +3156,7 @@ int main(int argc, char** argv) {std::fflush(stdout);++rounds;const bool drafted = eos || produced_n >= max_new ||- mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p);+ mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p);if (adapt_thr.joinable()) adapt_thr.join();if (!adapt_ok) {std::printf("ERR an adaptive refill failed\n");diff --git a/tools/calibrate.py b/tools/calibrate.pynew file mode 100644index 000000000..a7c5455b6--- /dev/null+++ b/tools/calibrate.py@@ -0,0 +1,225 @@+"""Tune the engine's hardware-dependent settings on this PC (setup's --calibrate).++Three settings depend on the machine more than on the model, and the defaults are right for the PC they were+measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5):+ --pcie-frac the share of the experts missing from VRAM that are copied over PCIe and run on the GPU instead of+ on the CPU. A fast PCIe link and a slow CPU want more; a laptop's x8 link or a fast CPU want less.+ --spec-min-p how sure the draft layer must be to extend a verify window by another guess. A slower CPU pays more+ per extra window row (more experts per window), so it wants a higher floor.+ --pool-workers the CPU threads that compute experts. Every physical core is not always best: on hybrid CPUs the+ efficiency cores can make the whole window wait for them.+The first two are measured through one engine (per-request `strata_tune` keys); the worker count needs a restart+per value. Decode speed only: the prompt path streams every expert whatever these settings say.++A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - the+adaptive expert tier and the OS make single measurements noisy by a few percent.++ python tools/calibrate.py strata-q2_0.json # measure and print; setup.py --calibrate also saves it+"""+from __future__ import annotations++import json+import statistics+import sys+import threading+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "tools"))+sys.path.insert(0, str(ROOT))++MIN_GAIN = 0.03 # a setting must beat the default by this much to be kept+PCIE_FRACS = (0.0, 0.2, 0.35, 0.55, 0.75)+SPEC_MIN_PS = (0.3, 0.5, 0.7)+MAX_NEW = 128+PROMPTS = (+ "Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.",+ "Explain in two paragraphs how a refrigerator moves heat from inside to outside.",+ "List twelve European capitals with one sentence about each.",+)+++def chat_ids(tok, text: str) -> list[int]:+ return tok.encode(f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",+ parse_special=True)+++def arg_value(args: list[str], flag: str) -> str | None:+ return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None+++def with_arg(args: list[str], flag: str, value: str | None) -> list[str]:+ """`args` with `flag value` set (replaced if present), or removed when value is None."""+ out = list(args)+ if flag in out:+ i = out.index(flag)+ del out[i:i + 2]+ if value is not None:+ out += [flag, value]+ 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."""+ c = [default]+ for w in (round(default * 2 / 3), round(default / 2)):+ if w >= 2 and w not in c:+ c.append(w)+ return c+++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}+ if not med or default_key not in med:+ return default_key+ best = max(med, key=med.get)+ return best if med[best] > med[default_key] * (1.0 + min_gain) else default_key+++class Session:+ """One running engine: measure decode tok/s for a setting (the median of the prompts' rates)."""++ def __init__(self, engine, ids_list):+ self.engine = engine+ self.ids_list = ids_list++ def rate(self, tune: dict | None = None) -> float:+ rates = []+ for ids in self.ids_list:+ sampling = {"temperature": 0}+ if tune:+ sampling["strata_tune"] = tune+ n = sum(1 for t in self.engine.generate(ids, MAX_NEW, sampling, threading.Event()) if t is not None)+ ms = (self.engine.last or {}).get("decode_ms") or 0.0+ if n > 8 and ms > 0:+ rates.append(n / (ms / 1000.0))+ return statistics.median(rates) if rates else 0.0++ def warm_up(self, rounds: int = 2):+ for _ in range(rounds):+ self.rate()+++def run(cfg: dict, say=print, start_engine=None) -> dict:+ """Measure on the engine `cfg` describes; returns {"settings": {flag: value}, "report": {...}}.+ `start_engine(args)` returns a started engine (serve.server.StrataEngine or a stand-in in tests)."""+ if start_engine is None:+ from serve.server import StrataEngine, child_env++ def start_engine(args):+ return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg))+ import strata_tokenizer as ST+ tpath = Path(cfg["tokenizer"])+ vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8"))+ toks = [None] * len(vocab)+ for t, i in vocab.items():+ toks[i] = t+ 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(cfg["args"], ids_list, start_engine, say)+++def measure(base_args: list[str], ids_list, start_engine, say=print) -> dict:+ t0 = time.time()+ report: dict = {}+ say(" Loading the model for the measurements ...")+ base_args = apply(base_args, {}) # the product defaults: what the measurements must beat+ eng = start_engine(base_args)+ try:+ info = dict(getattr(eng, "info", {}) or {})+ d_pcie = float(info.get("pcie_frac", 0.55))+ d_minp = float(info.get("spec_min_p", 0.5))+ d_workers = int(info.get("pool_workers", 0)) or None+ s = Session(eng, ids_list)+ s.warm_up()+ # 1. the PCIe share, at the default draft floor+ by_pcie = {}+ for f in sorted(set(PCIE_FRACS) | {round(d_pcie, 2)}):+ by_pcie[f] = [s.rate({"pcie_frac": f, "spec_min_p": d_minp})]+ say(f" PCIe share {f:.2f}: {by_pcie[f][0]:.1f} tok/s")+ best_pcie = max(by_pcie, key=lambda k: by_pcie[k][0])+ # 2. the draft floor, at that share+ by_minp = {}+ for p in sorted(set(SPEC_MIN_PS) | {round(d_minp, 2)}):+ by_minp[p] = [s.rate({"pcie_frac": best_pcie, "spec_min_p": p})]+ say(f" draft floor {p:.2f}: {by_minp[p][0]:.1f} tok/s")+ best_minp = max(by_minp, key=lambda k: by_minp[k][0])+ # 3. the winner against the default, interleaved, three times each+ dflt, cand = (round(d_pcie, 2), round(d_minp, 2)), (best_pcie, best_minp)+ confirm = {dflt: [], cand: []}+ if cand != dflt:+ for _ in range(3):+ for k in (dflt, cand):+ confirm[k].append(s.rate({"pcie_frac": k[0], "spec_min_p": k[1]}))+ chosen = pick(confirm, dflt) if cand != dflt else dflt+ report.update(default={"pcie_frac": dflt[0], "spec_min_p": dflt[1], "pool_workers": d_workers},+ pcie_sweep={str(k): v for k, v in by_pcie.items()},+ min_p_sweep={str(k): v for k, v in by_minp.items()},+ confirm={f"{k[0]}/{k[1]}": v for k, v in confirm.items()})+ finally:+ close(eng)+ settings = {}+ if chosen != dflt:+ settings["--pcie-frac"] = f"{chosen[0]:.2f}"+ 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:+ 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):+ 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:+ sw = Session(e, ids_list)+ sw.warm_up(1)+ by_workers[w] = [sw.rate(), sw.rate()]+ say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s")+ finally:+ close(e)+ w_best = pick(by_workers, d_workers)+ report["workers"] = {str(k): v for k, v in by_workers.items()}+ if w_best != d_workers:+ settings["--pool-workers"] = str(w_best)+ base_rate = statistics.median(by_workers[w_best])+ elif by_workers.get(d_workers):+ base_rate = statistics.median(by_workers[d_workers])+ report["seconds"] = round(time.time() - t0)+ report["tok_s"] = round(base_rate, 1) if base_rate else None+ return {"settings": settings, "report": report}+++def close(eng):+ proc = getattr(eng, "proc", None)+ if proc is None:+ return+ try:+ proc.stdin.write("QUIT\n")+ proc.stdin.flush()+ proc.stdin.close()+ proc.wait(60)+ except Exception:+ proc.kill()+++DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None} # None: the engine's own choice+++def apply(args: list[str], settings: dict) -> list[str]:+ """`args` with the calibrated settings; a setting the calibration did not change goes back to the product+ default (setup's --spec-min-p 0.5, the engine's own PCIe share and worker count), so an older calibration's+ values never linger."""+ out = list(args)+ for flag, default in DEFAULTS.items():+ out = with_arg(out, flag, settings.get(flag, default))+ return out+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ sys.exit("usage: calibrate.py <strata-*.json>")+ res = run(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig")))+ print(json.dumps(res, indent=1))diff --git a/tools/test_calibrate.py b/tools/test_calibrate.pynew file mode 100644index 000000000..c97d348fe--- /dev/null+++ b/tools/test_calibrate.py@@ -0,0 +1,157 @@+"""Tests for tools/calibrate.py and setup's use of it, without a GPU: a stand-in engine whose decode speed is a+function of the settings it runs with.++ python -m unittest tools.test_calibrate+"""+from __future__ import annotations++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "tools"))+sys.path.insert(0, str(ROOT))+import calibrate as CAL # noqa: E402+++class FakeEngine:+ """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`."""++ def __init__(self, args, speed, info_workers=6, starts=None):+ self.args = list(args)+ w = CAL.arg_value(args, "--pool-workers")+ self.workers = int(w) if w else info_workers+ self.info = {"pool_workers": info_workers, "pcie_frac": 0.55, "spec_min_p": float(CAL.arg_value(args, "--spec-min-p") or 0)}+ self.speed = speed+ self.last = {}+ self.proc = None+ if starts is not None:+ starts.append(list(args))++ def generate(self, ids, max_new, sampling, cancel):+ tune = sampling.get("strata_tune") or {}+ rate = self.speed(tune.get("pcie_frac", 0.55), tune.get("spec_min_p", self.info["spec_min_p"]), self.workers)+ for _ in range(max_new):+ yield 1+ self.last = {"generated": max_new, "decode_ms": max_new / rate * 1000.0}+++BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8192"]+++class Calibrate(unittest.TestCase):+ def run_with(self, speed, workers=6, base=BASE):+ starts = []+ res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts), say=lambda *_: None)+ return res, starts++ def test_defaults_kept_when_flat(self):+ res, _ = self.run_with(lambda f, p, w: 50.0)+ self.assertEqual(res["settings"], {})++ def test_small_gain_is_noise(self):+ # 2% better at pcie 0.35: below MIN_GAIN, so the default stays+ res, _ = self.run_with(lambda f, p, w: 51.0 if abs(f - 0.35) < 1e-6 else 50.0)+ self.assertEqual(res["settings"], {})++ def test_finds_pcie_and_min_p(self):+ def speed(f, p, w):+ return 50.0 + (10.0 if abs(f - 0.2) < 1e-6 else 0.0) + (5.0 if abs(p - 0.7) < 1e-6 else 0.0)+ res, _ = self.run_with(speed)+ self.assertEqual(res["settings"].get("--pcie-frac"), "0.20")+ self.assertEqual(res["settings"].get("--spec-min-p"), "0.70")+ self.assertNotIn("--pool-workers", res["settings"])++ def test_fewer_workers(self):+ # a hybrid CPU: half the workers is 20% faster+ res, starts = self.run_with(lambda f, p, w: 60.0 if w == 3 else 50.0, workers=6)+ self.assertEqual(res["settings"].get("--pool-workers"), "3")+ self.assertEqual(len(starts), 1 + len(CAL.worker_candidates(6))) # one start per worker count, plus the sweep+ self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") # measured against the product default++ def test_old_calibration_is_the_baseline_reset(self):+ # a config tuned earlier: the measurement starts from the product defaults, not from those values+ base = CAL.apply(BASE, {"--pcie-frac": "0.20", "--pool-workers": "3", "--spec-min-p": "0.70"})+ _, starts = self.run_with(lambda f, p, w: 50.0, base=base)+ self.assertIsNone(CAL.arg_value(starts[0], "--pcie-frac"))+ self.assertIsNone(CAL.arg_value(starts[0], "--pool-workers"))+ self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5")++ def test_apply(self):+ a = CAL.apply(BASE, {"--pcie-frac": "0.35", "--pool-workers": "4"})+ self.assertEqual(CAL.arg_value(a, "--pcie-frac"), "0.35")+ self.assertEqual(CAL.arg_value(a, "--pool-workers"), "4")+ self.assertEqual(CAL.arg_value(a, "--spec-min-p"), "0.5")+ b = CAL.apply(a, {}) # back to the defaults+ self.assertIsNone(CAL.arg_value(b, "--pcie-frac"))+ self.assertIsNone(CAL.arg_value(b, "--pool-workers"))+ self.assertEqual(b.count("--spec-min-p"), 1)++ 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(3), [3, 2])+ self.assertEqual(CAL.worker_candidates(1), [1])++ def test_pick(self):+ self.assertEqual(CAL.pick({"a": [50, 51, 49], "b": [53, 52, 60]}, "a"), "b")+ self.assertEqual(CAL.pick({"a": [50, 51, 49], "b": [51, 51.5, 51]}, "a"), "a")+ self.assertEqual(CAL.pick({}, "a"), "a")+++class SetupIntegration(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.old = {k: os.environ.get(k) for k in ("APPDATA", "XDG_CONFIG_HOME")}+ os.environ["APPDATA"] = self.tmp.name+ os.environ["XDG_CONFIG_HOME"] = self.tmp.name+ import setup as S+ self.S = S+ self.saved = (S.gpu_info, S.cpu_info, S.ram_gb, CAL.run)+ S.gpu_info = lambda pick=None: {"name": "RTX Test", "vram_gb": 12.0, "arch": "120", "count": 1, "index": 0}+ S.cpu_info = lambda: ("Test CPU", True, True)+ S.ram_gb = lambda: 64.0++ def tearDown(self):+ self.S.gpu_info, self.S.cpu_info, self.S.ram_gb, CAL.run = self.saved+ for k, v in self.old.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v+ self.tmp.cleanup()++ def test_calibrate_config_writes_and_remembers(self):+ cfg_path = Path(self.tmp.name) / "strata-q2_0.json"+ cfg = {"exe": "x", "args": list(BASE), "model_name": "qwen3.8-flash-next-q2_0"}+ cfg_path.write_text(json.dumps(cfg))+ CAL.run = lambda c, say=print, start_engine=None: {"settings": {"--pcie-frac": "0.20"}, "report": {"tok_s": 61.2}}+ self.assertTrue(self.S.calibrate_config(cfg_path))+ written = json.loads(cfg_path.read_text())+ self.assertEqual(CAL.arg_value(written["args"], "--pcie-frac"), "0.20")+ saved = self.S.saved_calibration(written)+ self.assertEqual(saved["settings"], {"--pcie-frac": "0.20"})+ # another model on the same PC has no calibration yet+ self.assertIsNone(self.S.saved_calibration({**written, "model_name": "swift-iq2_xs"}))+ # another context size is another key (its KV cache changes the expert cache)+ other = dict(written, args=CAL.with_arg(written["args"], "--max-context", "131072"))+ self.assertIsNone(self.S.saved_calibration(other))++ def test_failed_calibration_keeps_defaults(self):+ cfg_path = Path(self.tmp.name) / "strata-q2_0.json"+ cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m"}))++ def boom(*a, **k):+ raise RuntimeError("the engine exited before it was ready")+ CAL.run = boom+ self.assertFalse(self.S.calibrate_config(cfg_path))+ self.assertEqual(json.loads(cfg_path.read_text())["args"], BASE)+ self.assertIsNone(self.S.saved_calibration({"args": BASE, "model_name": "m"}))+++if __name__ == "__main__":+ unittest.main()