From f23eda8c952fbf332fd482480837697d62b289f3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:48:42 +0200 Subject: [PATCH 01/18] auto-tuner: single-knob candidates from the measured spec, interleaved rounds with noise and drift guards, memory guards, saved presets (one store for CLI and app), re-check, strata tune auto / strata presets --- serve/server.py | 21 + strata_cli/cli.py | 9 +- strata_cli/tune_commands.py | 401 +++++++++++++++++ strata_control/autotune.py | 796 +++++++++++++++++++++++++++++++++ strata_control/presets.py | 517 +++++++++++++++++++++ strata_control/tune_knobs.py | 473 ++++++++++++++++++++ strata_control/tune_machine.py | 313 +++++++++++++ strata_control/tune_session.py | 478 ++++++++++++++++++++ tests/tuning/stub_session.py | 90 ++++ tests/tuning/test_autotune.py | 332 ++++++++++++++ tests/tuning/test_presets.py | 175 ++++++++ 11 files changed, 3604 insertions(+), 1 deletion(-) create mode 100644 strata_cli/tune_commands.py create mode 100644 strata_control/autotune.py create mode 100644 strata_control/presets.py create mode 100644 strata_control/tune_knobs.py create mode 100644 strata_control/tune_machine.py create mode 100644 strata_control/tune_session.py create mode 100644 tests/tuning/stub_session.py create mode 100644 tests/tuning/test_autotune.py create mode 100644 tests/tuning/test_presets.py diff --git a/serve/server.py b/serve/server.py index 606b7026..c819fda4 100644 --- a/serve/server.py +++ b/serve/server.py @@ -7182,6 +7182,10 @@ def sampling_defaults_from_config(cfg: dict) -> dict: if not number or value != int(value) or value <= 0: raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer") out[key] = int(value) + elif key == "strata_tune": # a saved tuning's per-request settings (strata_control/presets.py) + if not isinstance(value, dict): + raise SystemExit(f"[strata] config sampling.strata_tune={value!r}: expected an object") + out[key] = {k: v for k, v in value.items() if k in ("pcie_frac", "spec_min_p", "aux_cpus")} elif key == "experimental_speed_projection": if not isinstance(value, bool): raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or " @@ -7409,6 +7413,23 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in ap.error("--shutdown-timeout must be in 0..300 seconds") config_bytes = Path(a.config).read_bytes() if a.config else b"" cfg = json.loads(config_bytes.decode("utf-8-sig")) if a.config else {} # Notepad adds a BOM + if a.config and a.engine == "strata" and not os.environ.get("STRATA_NO_PRESET"): + # the saved tuning for this model and these choices (strata_control/presets.py): applied with no measurement. A tune's + # own worker sets STRATA_NO_PRESET so that it measures the configuration it was given. Never fails the start. + try: + from strata_control import presets as _presets + cfg, _applied = _presets.overlay(cfg) + if _applied.get("applied"): + print(f"[strata] saved tuning '{_applied['preset']['name']}' applied: " + f"{' '.join(f'{k} {v}' for k, v in {**(_applied.get('args') or {}), **(_applied.get('env') or {})}.items())}" + f"{'; ' + _applied['notice'] if _applied.get('notice') and 'identical' not in _applied['notice'] else ''}", flush=True) + if _applied.get("state") == "soft": + print("[strata] this PC or engine changed since it was saved (" + "; ".join(_applied["reasons"]) + + "): a short re-check is available (strata presets recheck)", flush=True) + elif _applied.get("why_not"): + print(f"[strata] saved tuning '{_applied['preset']['name']}' {_applied['why_not']}; re-tune with strata tune auto", flush=True) + except Exception as _e: # noqa: BLE001 + print(f"[strata] saved tuning could not be read ({type(_e).__name__}); starting with the configuration as it is", flush=True) attestation_key = os.environ.pop("STRATA_OWNER_ATTEST_KEY", None) launch_attestation = None if a.owner_fd is not None: diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 001ae125..784590f2 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -24,7 +24,7 @@ BACKENDS = ("metal", "cuda", "hip", "sycl", "cpu") from strata_control.doctor import inspect as inspect_components from strata_control.profiles import ProfileError from strata_cli.client import ClientError, Endpoint -from strata_cli import monitor_commands +from strata_cli import monitor_commands, tune_commands class _VersionAction(argparse.Action): @@ -440,6 +440,8 @@ def parser() -> argparse.ArgumentParser: tune_list.add_argument("--state-dir", default=None) tune_list.add_argument("--output", choices=("human", "json"), default="human") + tune_commands.add_tune_auto(tune_sp) + tune_commands.add_presets(sp) monitor_commands.add_status(sp) monitor_commands.add_monitor(sp) monitor_commands.add_logs(sp) @@ -1351,6 +1353,9 @@ def _tune(a: argparse.Namespace) -> int: from strata_control.paths import state_base return state_base() / "tuning" + if a.tune_command == "auto": + return tune_commands.auto(a) + if a.tune_command == "list": root = state_root() jobs = [] @@ -1795,6 +1800,8 @@ def _run(a: argparse.Namespace) -> int: return _bench(a) if a.command == "timeskip": return _timeskip(a) + if a.command == "presets": + return tune_commands.presets_command(a) if a.command == "tune": return _tune(a) if a.command == "runtime": diff --git a/strata_cli/tune_commands.py b/strata_cli/tune_commands.py new file mode 100644 index 00000000..d0a4bf0c --- /dev/null +++ b/strata_cli/tune_commands.py @@ -0,0 +1,401 @@ +"""`strata tune auto` (the real tuner) and `strata presets` (the saved results), for the Terminal and, through JSON output +and a status file, for the desktop app. The same code and the same store serve both.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import tempfile +import threading +import time +from pathlib import Path +from typing import Any + + +# --------------------------------------------------------------------------- parsers + +def add_tune_auto(tune_sp: argparse._SubParsersAction) -> None: + p = tune_sp.add_parser( + "auto", help="find the fastest settings for this PC and save them as a preset (quick: about 20 minutes)", + description="Measures your configuration, tries single-knob changes in interleaved rounds against it, keeps only gains " + "above the noise, and saves the result as a named preset that is applied at every start. " + "Nothing changes if the current settings are already the fastest.") + p.add_argument("target", help="a saved profile name or a run configuration (JSON) to tune") + p.add_argument("--mode", choices=("quick", "thorough"), default="quick", + help="quick: about 20 minutes. thorough: up to 2 hours, 5-pair confirmation (default quick)") + p.add_argument("--goal", default="speed", help="speed (full performance), room (leave memory free), or room:MiB " + "(leave that much graphics memory free)") + p.add_argument("--leave-ram", type=int, default=0, metavar="PERCENT", help="leave this share of system memory free (0-50)") + p.add_argument("--use", choices=("chat", "coding"), default="chat", help="coding judges long-prompt speed as well") + p.add_argument("--allow-small-differences", action="store_true", + help="also try settings that can change answers slightly (expert cache split, speculative window)") + p.add_argument("--allow-not-repeatable", action="store_true", help="also try settings whose answers are not repeatable") + p.add_argument("--name", default=None, help="the preset's name (default: model, context and your wish)") + p.add_argument("--time", dest="minutes", type=float, default=None, help="time to spend, in minutes") + p.add_argument("--no-save", action="store_true", help="measure and report, but do not save a preset") + p.add_argument("--gpu-lock", default=os.environ.get("STRATA_TUNE_GPU_LOCK"), + help="a lock file held around every engine run (shared boxes)") + p.add_argument("--no-quiet-check", action="store_true", help="do not wait for other engines or a busy CPU") + p.add_argument("--serve-dir", default=None, help="the folder that holds serve/ (default: this installation)") + p.add_argument("--work-dir", default=None, help="where the run's configs and logs go (default: a temp folder)") + p.add_argument("--status-file", default=None, help="progress as JSON, rewritten at every step (for the desktop app)") + p.add_argument("--boot-timeout", type=float, default=900.0) + p.add_argument("--output", choices=("human", "json"), default="human") + + +def add_presets(sp: argparse._SubParsersAction) -> None: + pr = sp.add_parser("presets", help="saved tuning presets: list, apply, rename, delete, undo, re-check") + psp = pr.add_subparsers(dest="presets_command", required=True) + + def common(x: argparse.ArgumentParser) -> argparse.ArgumentParser: + x.add_argument("--output", choices=("human", "json"), default="human") + return x + + l = common(psp.add_parser("list", help="every saved preset (or those for one model/configuration)")) + l.add_argument("--model", default=None, help="only presets whose model or quant contains this text") + s = common(psp.add_parser("status", help="which preset a configuration would start with, and whether it is still valid")) + s.add_argument("target", help="a saved profile name or a run configuration (JSON)") + sh = common(psp.add_parser("show", help="one preset in full")) + sh.add_argument("preset") + ap = common(psp.add_parser("apply", help="make a preset the active one for its choices (the previous one is kept for undo)")) + ap.add_argument("preset") + rn = common(psp.add_parser("rename", help="give a preset another name")) + rn.add_argument("preset") + rn.add_argument("name") + de = common(psp.add_parser("delete", help="delete a preset")) + de.add_argument("preset") + un = common(psp.add_parser("undo", help="go back to the preset that was active before (or the standard settings)")) + un.add_argument("preset", help="a preset, or a configuration target with --config") + un.add_argument("--config", default=None, help="a profile name or run configuration whose slot to undo") + ex = common(psp.add_parser("export", help="write a preset to a file (or print it)")) + ex.add_argument("preset") + ex.add_argument("--file", default=None) + im = common(psp.add_parser("import", help="read a preset from a file")) + im.add_argument("file") + rc = common(psp.add_parser("recheck", help="a short check (about 2 minutes) that a preset is still as fast")) + rc.add_argument("preset") + rc.add_argument("target", help="the profile name or run configuration the preset belongs to") + rc.add_argument("--gpu-lock", default=os.environ.get("STRATA_TUNE_GPU_LOCK")) + rc.add_argument("--serve-dir", default=None) + rc.add_argument("--work-dir", default=None) + rc.add_argument("--status-file", default=None) + rc.add_argument("--boot-timeout", type=float, default=900.0) + rc.add_argument("--no-quiet-check", action="store_true") + + +# --------------------------------------------------------------------------- helpers + +def _print(payload: dict[str, Any], machine: bool, human: str) -> int: + if machine: + print(json.dumps({"schema_version": 1, "ok": True, **payload}, ensure_ascii=False, default=str)) + else: + print(human) + return 0 + + +def _fail(message: str, code: int, machine: bool) -> int: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}})) + else: + print(f"strata: {message}", file=sys.stderr) + return code + + +def _load_target(target: str) -> tuple[Path, dict[str, Any]]: + from strata_control import profiles + path, _profile, _rev = profiles.resolve(target) + return path, profiles.read_run_config(path) + + +def _engine_exe(cfg: dict[str, Any]) -> str: + from strata_control import engine_component + ref = cfg.get("exe") + if engine_component.is_reference(ref): + return engine_component.expand(ref, cfg, full=False) + p = Path(ref) + return str(p if p.is_absolute() else Path(cfg.get("cwd") or ".") / p) + + +def _serve_dir(a: argparse.Namespace) -> Path: + if getattr(a, "serve_dir", None): + return Path(a.serve_dir) + return Path(__file__).resolve().parent.parent + + +def _lock_factory(a: argparse.Namespace, log): + if not getattr(a, "gpu_lock", None): + return None + from strata_control.tune_session import FileLock + return lambda: FileLock(a.gpu_lock, log=log) + + +def _parse_goal(text: str) -> tuple[str, int]: + if text in ("speed", "full"): + return "speed", 0 + if text == "room": + return "room", 0 + if text.startswith("room:"): + return "room", max(0, int(text[5:])) + raise ValueError("goal is speed, room or room:MiB") + + +def _write_status(path: str | None, payload: dict[str, Any]) -> None: + if not path: + return + try: + tmp = path + ".tmp" + Path(tmp).write_text(json.dumps(payload, ensure_ascii=False, default=str), encoding="utf-8") + os.replace(tmp, path) + except OSError: + pass + + +def minutes_text(seconds: float | None) -> str: + if seconds is None: + return "" + m = max(1, int(round(seconds / 60.0))) + return f"about {m} min left" + + +def _hw_hash(identity: dict[str, Any]) -> str: + from strata_control import tune_machine + return tune_machine.stable_hash((identity.get("hardware") or {}).get("hard")) + + +# --------------------------------------------------------------------------- tune auto + +def auto(a: argparse.Namespace) -> int: + from strata_control import autotune, engine_component, presets, tune_knobs, tune_machine, tuning + from strata_control.tune_session import WorkerSession + + machine = a.output == "json" + try: + goal, reserve = _parse_goal(a.goal) + cfg_path, cfg = _load_target(a.target) + except Exception as e: # noqa: BLE001 + return _fail(str(e), getattr(e, "exit_code", 2), machine) + if not 0 <= a.leave_ram <= 50: + return _fail("--leave-ram is a percentage from 0 to 50", 2, machine) + if a.leave_ram and goal == "speed": + goal = "room" + exe = _engine_exe(cfg) + if not Path(exe).exists(): + return _fail(f"no engine was found at {exe}", 5, machine) + identity = presets.current_identity(cfg, exe=exe) + backend = (identity.get("engine") or {}).get("backend") or engine_component.detect_backend()[0] or "cpu" + flags = tuning.engine_flag_inventory(Path(exe)) + opts = autotune.Options(mode=a.mode, goal=goal, reserve_mib=reserve, ram_wish_pct=a.leave_ram, use=a.use, + allow_placement=a.allow_small_differences, allow_nonrepeatable=a.allow_not_repeatable, + budget_s=(a.minutes * 60.0 if a.minutes else None), check_busy=not a.no_quiet_check) + ctx = autotune.context_from_config(cfg, engine_backend=backend, opts=opts, engine_flags=flags) + hw = _hw_hash(identity) + digest = (identity.get("model") or {}).get("sha256_shard1") + bad = presets.bad_signatures(hw_hash=hw, model_digest=digest, engine_sha=(identity.get("engine") or {}).get("sha256")) + + cancel = threading.Event() + state: dict[str, Any] = {"stage": "start", "message": "Starting", "state": "running"} + + def say(line: str) -> None: + if not machine: + print(line, file=sys.stderr, flush=True) + + def progress(p: dict[str, Any]) -> None: + state.update(p) + state["minutes_left"] = None if p.get("eta_s") is None else max(1, int(round(p["eta_s"] / 60.0))) + state["text"] = (f"Finding the fastest settings for your PC… {minutes_text(p.get('eta_s'))}" + if p.get("eta_s") is not None else "Finding the fastest settings for your PC…") + _write_status(a.status_file, state) + say(f"[{p.get('elapsed_s', 0) // 60:>3d}m] {p['message']}" + (f" ({minutes_text(p['eta_s'])})" if p.get("eta_s") else "")) + + workdir = Path(a.work_dir) if a.work_dir else Path(tempfile.mkdtemp(prefix="strata-tune-")) + session = WorkerSession(base_config=cfg, python=sys.executable, serve_dir=_serve_dir(a), workdir=workdir, + boot_timeout_s=a.boot_timeout, lock=_lock_factory(a, say), log=say) + base_args = [str(x) for x in cfg.get("args") or []] + # the wish becomes part of the base: leave-room asks the engine for the reserve if the configuration has none yet + if goal == "room" and reserve and "--vram-reserve-mib" not in base_args and ctx.family == "flash-next" \ + and backend in ("cuda", "hip") and (flags is None or "--vram-reserve-mib" in flags): + base_args += ["--vram-reserve-mib", str(reserve)] + ctx.base_args = list(base_args) + tuner = autotune.Tuner(session, base_args, dict(cfg.get("env") or {}), ctx, opts, progress=progress, cancel=cancel, + history_bad=bad, quiet=None) + say(f"Tuning {presets.choices_from_config(cfg).get('model')} ({a.mode}); engine {exe}") + try: + result = tuner.run() + except KeyboardInterrupt: + cancel.set() + result = tuner.result + result.outcome, result.message = "cancelled", "Stopped. Your settings were not changed." + out = result.to_dict() + choices = presets.choices_from_config(cfg, use=a.use) + choices["goal"], choices["reserve_mib"] = goal, reserve + if a.leave_ram: + choices["leave_ram_pct"] = a.leave_ram + saved = None + try: + presets.record_trials(result.trials, hw_hash=hw, model_digest=digest, + engine_sha=(identity.get("engine") or {}).get("sha256")) + except OSError: + pass + if result.outcome in ("improved", "default_confirmed") and not a.no_save: + try: + saved = presets.create(out, choices=choices, identity=identity, name=a.name, mode=a.mode) + except presets.PresetError as e: + result.notes.append(str(e)) + out["preset"] = ({"id": saved["id"], "name": saved["name"]} if saved else None) + state.update({"state": "done", "result": out, "stage": "done"}) + _write_status(a.status_file, state) + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "result": out}, ensure_ascii=False, default=str)) + else: + print(_human_result(out, saved)) + return {"improved": 0, "default_confirmed": 0, "cancelled": 130}.get(result.outcome, 6) + + +def _human_result(r: dict[str, Any], saved: dict[str, Any] | None) -> str: + lines = [""] + if r["outcome"] == "improved": + lines.append(f"Done in {r['seconds'] / 60:.0f} min: +{r['gain_pct']:.0f}% faster answers" + + (f", saved as '{saved['name']}'." if saved else ".")) + s = r["settings"] + shown = {**{k: v for k, v in s["args"].items()}, **s["env"], **{f"per request {k}": v for k, v in s["per_request"].items()}} + lines.append(" Changed: " + ", ".join(f"{k} {v}" for k, v in shown.items())) + lines.append(f" Measured: {r['base'].get('decode_tok_s')} -> {r['chosen'].get('decode_tok_s')} tok/s " + f"({r['faster_pairs']} of {r['pairs']} pairs faster)") + from strata_control.tune_knobs import ANSWER_NOTICE + lines.append(" " + ANSWER_NOTICE.get(r["answers"]["class"], "")) + else: + lines.append(r["message"] or r["outcome"]) + if saved: + lines.append(f" Saved as '{saved['name']}' so it is not tuned again on reopen.") + for n in r.get("notes") or []: + lines.append(f" note: {n}") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- presets + +def presets_command(a: argparse.Namespace) -> int: + from strata_control import autotune, presets, tune_knobs + + machine = a.output == "json" + cmd = a.presets_command + try: + if cmd == "list": + items = presets.list_presets(model=a.model) + human = "\n".join(f"{'*' if p['active'] else ' '} {p['id'][:8]} {p['name']} " + f"{(p.get('measured') or {}).get('gain_pct') or 0:+.0f}% {p['answers']['class']}" + for p in items) or "No saved presets yet. Run: strata tune auto " + return _print({"presets": [_summary(p) for p in items]}, machine, human) + if cmd == "status": + return _status(a, machine) + if cmd == "show": + p = presets.find(a.preset) + return _print({"preset": p}, machine, json.dumps(p, indent=2, ensure_ascii=False)) + if cmd == "apply": + p = presets.activate_preset(a.preset) + return _print({"preset": _summary(p), "notice": presets.notice(p)}, machine, + f"'{p['name']}' is now active. It is used the next time the model starts. Undo: strata presets undo {p['id'][:8]}") + if cmd == "rename": + p = presets.rename(a.preset, a.name) + return _print({"preset": _summary(p)}, machine, f"Renamed to '{p['name']}'.") + if cmd == "delete": + p = presets.find(a.preset) + presets.delete(a.preset) + return _print({"deleted": p["id"]}, machine, f"Deleted '{p['name']}'.") + if cmd == "undo": + if a.config: + _path, cfg = _load_target(a.config) + ident = presets.current_identity(cfg) + slot = presets.slot_key(presets.choices_from_config(cfg), (ident.get("model") or {}).get("sha256_shard1")) + else: + slot = a.preset + back = presets.undo(slot) + return _print({"active": _summary(back) if back else None}, machine, + f"Back to '{back['name']}'." if back else "Back to the standard settings.") + if cmd == "export": + data = presets.export_preset(a.preset) + if a.file: + Path(a.file).write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8") + return _print({"file": a.file}, machine, f"Wrote {a.file}") + print(json.dumps(data, indent=2, ensure_ascii=False)) + return 0 + if cmd == "import": + data = json.loads(Path(a.file).read_text(encoding="utf-8-sig")) + p = presets.import_preset(data) + return _print({"preset": _summary(p)}, machine, f"Imported '{p['name']}'. Apply it with: strata presets apply {p['id'][:8]}") + if cmd == "recheck": + return _recheck(a, machine) + except presets.PresetError as e: + return _fail(str(e), 5, machine) + except (OSError, ValueError) as e: + return _fail(str(e), getattr(e, "exit_code", 2), machine) + return _fail("unknown presets command", 2, machine) + + +def _summary(p: dict[str, Any]) -> dict[str, Any]: + from strata_control import presets + m = p.get("measured") or {} + return {"id": p["id"], "name": p["name"], "active": bool(p.get("active")), "created": p.get("created"), + "choices": p.get("choices"), "settings": p.get("settings"), "answers": p.get("answers"), + "notice": presets.notice(p), "gain_pct": m.get("gain_pct"), "decode_tok_s": m.get("decode_tok_s"), + "baseline_decode_tok_s": (p.get("baseline") or {}).get("decode_tok_s"), "tuner": p.get("tuner"), + "recheck": p.get("recheck"), "slot": p.get("slot")} + + +def _status(a: argparse.Namespace, machine: bool) -> int: + from strata_control import presets + _path, cfg = _load_target(a.target) + ident = presets.current_identity(cfg) + choices = presets.choices_from_config(cfg) + slot = presets.slot_key(choices, (ident.get("model") or {}).get("sha256_shard1")) + idx = presets._index().get(slot) or {} + items = [p for p in presets.list_presets() if p.get("slot") == slot] + active = next((p for p in items if p["id"] == idx.get("active")), None) + stale = presets.staleness(active, ident) if active else None + default = presets.default_name(choices) + return _print({"slot": slot, "suggested_name": default, "choices": choices, + "active": _summary(active) if active else None, "state": stale["state"] if stale else None, + "reasons": stale["reasons"] if stale else [], "presets": [_summary(p) for p in items], + "can_undo": bool(idx.get("history")) or bool(active)}, + machine, (f"Active: '{active['name']}' ({stale['state']})" if active else "No saved tuning for these choices yet.")) + + +def _recheck(a: argparse.Namespace, machine: bool) -> int: + from strata_control import autotune, presets, tuning + from strata_control.tune_session import WorkerSession + preset = presets.find(a.preset) + _path, cfg = _load_target(a.target) + exe = _engine_exe(cfg) + ident = presets.current_identity(cfg, exe=exe) + stale = presets.staleness(preset, ident) + if stale["state"] == "hard": + return _fail("this PC changed too much for a re-check (" + "; ".join(stale["reasons"]) + "): tune again with strata tune auto", 5, machine) + engine_changed = int((preset.get("identity", {}).get("engine") or {}).get("tuning_epoch") or 0) != \ + int((ident.get("engine") or {}).get("tuning_epoch") or 0) + opts = autotune.Options(use=(preset.get("choices") or {}).get("use", "chat")) + ctx = autotune.context_from_config(cfg, engine_backend=(ident.get("engine") or {}).get("backend"), opts=opts, + engine_flags=tuning.engine_flag_inventory(Path(exe))) + say = (lambda s: None) if machine else (lambda s: print(s, file=sys.stderr, flush=True)) + workdir = Path(a.work_dir) if a.work_dir else Path(tempfile.mkdtemp(prefix="strata-recheck-")) + session = WorkerSession(base_config=cfg, python=sys.executable, serve_dir=_serve_dir(a), workdir=workdir, + boot_timeout_s=a.boot_timeout, lock=_lock_factory(a, say), log=say) + state: dict[str, Any] = {"state": "running"} + + def progress(p: dict[str, Any]) -> None: + state.update(p) + _write_status(a.status_file, state) + say(p["message"]) + + out = autotune.recheck(session, [str(x) for x in cfg.get("args") or []], preset, ctx=ctx, engine_changed=engine_changed, + progress=progress) + out["identity"] = ident + updated = presets.record_recheck(preset["id"], out) + state.update({"state": "done", "result": {k: v for k, v in out.items() if k != "identity"}}) + _write_status(a.status_file, state) + human = {"keep": "Still as fast as when it was saved. Kept.", + "retune": "Not as fast as before: " + str(out.get("reason")) + "\nYou can tune again with: strata tune auto", + "inconclusive": "Could not tell (the PC was busy). Kept; try again later."}[out["verdict"]] + return _print({"verdict": out["verdict"], "reason": out.get("reason"), "result": {k: v for k, v in out.items() if k != "identity"}, + "preset": _summary(updated)}, machine, human) diff --git a/strata_control/autotune.py b/strata_control/autotune.py new file mode 100644 index 00000000..b98e7660 --- /dev/null +++ b/strata_control/autotune.py @@ -0,0 +1,796 @@ +"""The auto-tuner: find the fastest settings for this PC, for this model, for what the user asked for. + +What it does (TUNING-SPEC.md sections 5-6, measured on five machines): + +1. **Starts from the user's own configuration** (the "base") and changes one knob at a time (`tune_knobs`). It never starts + a candidate at "the first value of every dimension". +2. Measures with the real worker over HTTP, on the engine's own clock (`tune_session`), the same fixed request set every + time. Restart knobs are tried as **interleaved rounds**: every round runs the base and each candidate once, in a + rotating order, so machine drift cannot favour one of them. Per-request knobs need no restart and are tried first, in + one engine. +3. Accepts a candidate only if the **median of its per-round ratios** to the base beats the noise: at least +3%, and twice + the drift and twice the A/A gap measured on the base runs, in every round (quick) or at least 4 of 5 (thorough + confirm), without losing more than 2% elsewhere (prompt speed). A gain the noise can explain is not a gain: the result + is then "your current settings are already the fastest" and nothing changes. +4. Guards before every start: free RAM, free graphics memory, other engines running, the CPU busy with something else. + A candidate that does not fit is skipped, never started. A candidate must not use more memory than the base the user + asked for (so "leave 20% for my work" is respected). The first crash stops the stage. +5. Only knobs whose answers are byte-identical (class exact) are chosen on their own; the others need the user's tick. + +Progress and time left are reported through a callback; a cancel stops at the next run and keeps nothing half-measured. +""" + +from __future__ import annotations + +import math +import statistics +import threading +import time +from dataclasses import dataclass, field +from typing import Any, Callable + +from strata_control import tune_knobs, tune_machine +from strata_control.tune_session import RequestSet, RunResult, Session, StartFailed + +MIN_FREE_RAM_MIB = 3584 # 3.5 GiB left for the system at every start (6.5) +STAGE_GAP_NOISY = 0.04 # an A/A gap above this: the machine is noisy (6.5) + + +class Cancelled(Exception): + """The user stopped the tune; what was measured so far is kept in the result.""" + + +# --------------------------------------------------------------------------- options and result + +@dataclass +class Options: + mode: str = "quick" # quick | thorough + goal: str = "speed" # speed | room + reserve_mib: int = 0 # graphics memory to leave free (goal room) + ram_wish_pct: int = 0 # system memory to leave free, in percent (goal room, e.g. 20) + use: str = "chat" # chat | coding + allow_placement: bool = False + allow_nonrepeatable: bool = False + budget_s: float | None = None # quick 20 min, thorough 2 h + margin: float = 0.03 + rounds: int | None = None # quick 2, thorough 3 (screen); confirm 5 in thorough + confirm_pairs: int | None = None # thorough: 5 + per_request: bool = True + min_free_ram_mib: int = MIN_FREE_RAM_MIB + wait_ram_s: float = 600.0 + busy_pct: float = 25.0 + wait_busy_s: float = 300.0 + check_busy: bool = True + + def resolved(self) -> "Options": + o = Options(**self.__dict__) + thorough = o.mode == "thorough" + o.budget_s = o.budget_s or (7200.0 if thorough else 1200.0) + o.rounds = o.rounds or (3 if thorough else 2) + o.confirm_pairs = o.confirm_pairs if o.confirm_pairs is not None else (5 if thorough else 0) + return o + + +@dataclass +class ArmReport: + id: str + label: str + settings: dict[str, Any] + env: dict[str, Any] + answer: str + status: str = "pending" # pending | tested | dropped | failed | skipped + reason: str = "" + runs: list[dict[str, Any]] = field(default_factory=list) # per round: ratios vs that round's base + ratio_decode: float | None = None + ratio_pp: float | None = None + pairs: int = 0 + faster: int = 0 + won: bool = False + + def to_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + +@dataclass +class TuneResult: + outcome: str = "default_confirmed" # improved | default_confirmed | inconclusive | base_failed | cancelled + message: str = "" + mode: str = "quick" + seconds: float = 0.0 + runs: int = 0 + base: dict[str, Any] = field(default_factory=dict) + chosen: dict[str, Any] = field(default_factory=dict) + gain_pct: float = 0.0 + gain_decode_pct: float = 0.0 + gain_pp_pct: float = 0.0 + settings: dict[str, Any] = field(default_factory=lambda: {"args": {}, "env": {}, "per_request": {}}) + answers: dict[str, Any] = field(default_factory=lambda: {"class": "exact", "fields": []}) + arms: list[dict[str, Any]] = field(default_factory=list) + skipped: list[dict[str, str]] = field(default_factory=list) + noise: dict[str, Any] = field(default_factory=dict) + pairs: int = 0 + faster_pairs: int = 0 + per_request: list[dict[str, Any]] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + classes: list[str] = field(default_factory=list) + facts: dict[str, Any] = field(default_factory=dict) + trials: list[dict[str, Any]] = field(default_factory=list) # every engine run, for the history store + + def to_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + +# --------------------------------------------------------------------------- pure decision rules + +def metric(run: dict[str, Any] | RunResult, use: str) -> float | None: + """The number a configuration is judged on (6.1): decode speed for chat; for coding the geometric mean of decode + speed and long-prompt speed (the 4K prompt when no long one was measured).""" + get = (lambda k: run.get(k)) if isinstance(run, dict) else (lambda k: getattr(run, k, None)) + d = get("decode_tok_s") + if not d: + return None + if use == "coding": + p = get("pp_long_tok_s") or get("pp_tok_s") + if p: + return math.sqrt(d * p) + return float(d) + + +def median_ratio(ratios: list[float]) -> float | None: + return statistics.median(ratios) if ratios else None + + +def accept_threshold(margin: float, aa_gap: float, drift: float) -> float: + """How far above 1.0 a median ratio has to be: the margin, or twice the noise the base runs showed (6.7 rule 3).""" + return 1.0 + max(margin, 2.0 * aa_gap, 2.0 * drift) + + +def is_win(ratios: list[float], pp_ratios: list[float], *, threshold: float, need: int | None = None) -> bool: + """A win: the median ratio beats the threshold, enough rounds were faster, and the prompt speed lost at most 2%.""" + if not ratios: + return False + need = len(ratios) if need is None else need + faster = sum(1 for r in ratios if r > 1.0) + if faster < need or statistics.median(ratios) < threshold: + return False + if pp_ratios and statistics.median(pp_ratios) < 0.98: + return False + return True + + +def rotate(items: list[Any], r: int) -> list[Any]: + k = r % len(items) if items else 0 + return items[k:] + items[:k] + + +# --------------------------------------------------------------------------- the tuner + +class Tuner: + def __init__(self, session: Session, base_args: list[str], base_env: dict[str, str], ctx: tune_knobs.Context, + options: Options, *, progress: Callable[[dict[str, Any]], None] | None = None, + cancel: threading.Event | None = None, history_bad: set[str] | None = None, + clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep, + system: Callable[[], dict[str, Any]] | None = None, total_ram_mib: int | None = None, + total_vram_mib: int | None = None, quiet: Callable[[], str | None] | None = None) -> None: + self.session = session + self.base_args = list(base_args) + self.base_env = dict(base_env) + self.ctx = ctx + self.o = options.resolved() + self.progress = progress or (lambda p: None) + self.cancel = cancel or threading.Event() + self.history_bad = history_bad or set() + self.clock = clock + self.sleep = sleep + self.system = system or session.system + self.result = TuneResult(mode=self.o.mode) + self.started = 0.0 + self.run_times: list[float] = [] + self.planned_runs = 0 + self.done_runs = 0 + self.base_runs: list[RunResult] = [] + self.total_ram = total_ram_mib or (tune_machine.memory().get("total_mib") or 0) + self.total_vram = total_vram_mib + self.quiet = quiet + self.storm = False + + # ---- bookkeeping + def _say(self, stage: str, message: str, **extra: Any) -> None: + elapsed = self.clock() - self.started + avg = statistics.mean(self.run_times) if self.run_times else 150.0 + remaining = max(0, self.planned_runs - self.done_runs) + eta = min(max(0.0, self.o.budget_s - elapsed), remaining * avg) if self.planned_runs else None + self.progress({"stage": stage, "message": message, "elapsed_s": round(elapsed), "runs_done": self.done_runs, + "runs_planned": self.planned_runs, "eta_s": None if eta is None else round(eta), **extra}) + + def _check_cancel(self) -> None: + if self.cancel.is_set(): + raise Cancelled() + + def _over_budget(self, reserve_s: float = 0.0) -> bool: + return (self.clock() - self.started) + reserve_s > self.o.budget_s + + def _avg_run(self) -> float: + return statistics.mean(self.run_times) if self.run_times else 150.0 + + # ---- guards + def _wait_for_quiet(self) -> None: + """Pause while another engine runs or the CPU is busy with something else (6.5, 6.7 rule 5).""" + if not self.o.check_busy: + return + waited = 0.0 + while True: + why = self.quiet() if self.quiet else self._machine_busy() + if not why: + return + if waited >= self.o.wait_busy_s: + self.result.notes.append(f"measured while the machine was busy ({why})") + return + self._say("waiting", f"Waiting for the PC to be quiet ({why})") + self._check_cancel() + self.sleep(10.0) + waited += 10.0 + + def _machine_busy(self) -> str | None: + eng = tune_machine.other_engines() + if eng: + return "another Strata engine is running" + busy = tune_machine.cpu_busy_percent(1.0) + if busy is not None and busy > self.o.busy_pct: + return f"the CPU is {busy:.0f}% busy" + return None + + def _ram_guard(self, delta_mib: int, label: str) -> str | None: + """None when a start fits; otherwise the plain reason it does not.""" + waited = 0.0 + while True: + mem = self.system().get("memory", {}) + avail = mem.get("available_mib") + if avail is None: + return None # unreadable: the engine's own guard decides + need = self.o.min_free_ram_mib + delta_mib + base_rss = self.base_runs[0].rss_peak_mib if self.base_runs else None + if base_rss: + need += base_rss + elif self.total_ram: + need = max(need, self.o.min_free_ram_mib) + if avail >= need: + return None + if waited >= self.o.wait_ram_s: + return (f"not enough free memory to start it safely ({avail / 1024:.1f} GiB free, " + f"{need / 1024:.1f} GiB needed)") + self._say("waiting", f"Waiting for memory to be freed before trying {label}") + self._check_cancel() + self.sleep(10.0) + waited += 10.0 + + # ---- one engine run + def _run(self, args: list[str], env: dict[str, str | None], spec: RequestSet, label: str, + points: Callable[[Any], None] | None = None) -> RunResult: + self._check_cancel() + self._wait_for_quiet() + t0 = self.clock() + try: + with self.session.engine(args, env) as eng: + res = eng.measure(spec) + if points is not None and res.status == "PASS": + points(eng) + except StartFailed as e: + res = RunResult(status=e.status, reason=e.reason) + dt = self.clock() - t0 + self.run_times.append(dt) + self.done_runs += 1 + res.wall_s = round(dt, 1) + self.result.runs += 1 + self.result.trials.append({"label": label, "args": args, "env": env, "status": res.status, "reason": res.reason, + "decode_tok_s": res.decode_tok_s, "pp_tok_s": res.pp_tok_s, + "rss_peak_mib": res.rss_peak_mib, "load_s": res.load_s, "at": time.time()}) + return res + + # ---- the whole job + def run(self) -> TuneResult: + self.started = self.clock() + r = self.result + try: + self._run_stages() + except Cancelled: + r.outcome, r.message = "cancelled", "Stopped. Your settings were not changed." + r.seconds = round(self.clock() - self.started, 1) + return r + + def _spec(self) -> RequestSet: + long_tokens = 0 + if self.o.use == "coding" and self.o.mode == "thorough": + long_tokens = min(28000, int(0.8 * self.ctx.context_tokens)) + return RequestSet(warmups=2 if self.o.mode == "thorough" else 1, decodes=3, decode_tokens=200, + pp_tokens=4096 if self.ctx.context_tokens >= 6000 else 1024, long_tokens=long_tokens) + + def _run_stages(self) -> None: + r, o = self.result, self.o + spec = self._spec() + self.planned_runs = 6 # corrected once the candidates are known + self._say("start", "Checking your PC before the first measurement") + + # ---- stage 1: the base run (the user's configuration, untouched), with the per-request guard in the same engine + why = self._ram_guard(0, "your current settings") + if why: + r.outcome, r.message = "base_failed", "Not tuned: " + why + return + pr_rows: list[dict[str, Any]] = [] + + def per_request_points(eng: Any) -> None: + if o.per_request: + pr_rows.extend(self._per_request_stage(eng)) + + self._say("base", "Measuring your current settings") + base1 = self._run(self.base_args, {}, spec, "base", points=per_request_points) + self.base_runs.append(base1) + if base1.status != "PASS" or not metric(base1, o.use): + r.outcome = "base_failed" + r.message = "Your current settings could not be measured: " + (base1.reason or base1.status) + return + r.base = base1.to_dict() + r.facts = dict(base1.facts) + self.ctx.facts = dict(base1.facts) + if base1.vram_used_mib is not None and self.total_vram is None: + cards = [g for g in self.system().get("gpus", []) if g.get("vram_total_mib")] + self.total_vram = sum(g["vram_total_mib"] for g in cards) if cards else None + r.per_request = pr_rows + r.classes = tune_knobs.machine_classes(self.ctx) + + # ---- stage 2: plan the candidates for this machine; how many depends on the time chosen + planned, skipped = tune_knobs.plan_arms(self.ctx, mode=o.mode, history_bad=self.history_bad) + r.skipped = skipped + per_arm = o.rounds or 2 + if o.mode == "thorough": + n_arms = len(planned) + else: + left = int((o.budget_s - (self.clock() - self.started)) / max(1.0, self._avg_run())) + fixed = (per_arm - 1) + 1 + 2 # extra base rounds, the final base, a combined-confirm margin + n_arms = min(len(planned), max(0, (left - fixed) // per_arm)) + for p in planned[n_arms:]: + skipped.append({"id": p.arm.id, "label": p.arm.label, "reason": "left out to stay inside the time you chose"}) + planned = planned[:n_arms] + arms = [ArmReport(p.arm.id, p.arm.label, dict(p.args), dict(p.env), p.arm.answer) for p in planned] + by_id = {a.id: a for a in arms} + self.planned_runs = self.done_runs + per_arm * (len(planned) + 1) - 1 + 1 + (o.confirm_pairs or 0) * 2 + if not planned: + self._say("plan", "No other setting is worth trying on this PC") + + # ---- stage 3: interleaved rounds. Every round runs the base and each live candidate once, in a rotating order. + round_runs: list[dict[str, RunResult]] = [{} for _ in range(per_arm)] + round_runs[0]["base"] = base1 + alive = list(planned) + stop = False + for rnd in range(per_arm): + if stop or self.storm or (rnd > 0 and not alive): + break + for item in rotate(["base"] + alive, rnd): + self._check_cancel() + if self._over_budget(reserve_s=2 * self._avg_run()): + r.notes.append("the time you chose ran out before every round finished") + stop = True + break + if item == "base": + if rnd == 0: + continue # round 1's base is the run above + if self._ram_guard(0, "your current settings"): + r.notes.append("not enough free memory for another measurement of your current settings; the search stopped") + stop = True + break + self._say("rounds", f"Measuring your current settings again (round {rnd + 1} of {per_arm})") + b = self._run(self.base_args, {}, spec, f"base r{rnd + 1}") + if b.status != "PASS": + r.notes.append("your current settings failed to start a second time; the search stopped") + self.storm = stop = True + break + self.base_runs.append(b) + round_runs[rnd]["base"] = b + continue + p = item + rep = by_id[p.arm.id] + why = self._ram_guard(p.arm.ram_delta_mib, p.arm.label) + if why: + rep.status, rep.reason = "skipped", why + alive = [x for x in alive if x.arm.id != p.arm.id] + continue + self._say("rounds", f"Trying: {p.arm.label} (round {rnd + 1} of {per_arm})", arm=p.arm.id) + res = self._run(tune_knobs.apply_to_argv(self.base_args, p.args), dict(p.env), spec, p.arm.id) + if res.status != "PASS": + rep.status, rep.reason = "failed", f"{res.status}: {res.reason}" + alive = [x for x in alive if x.arm.id != p.arm.id] + if res.status == "OOM": + self.storm = stop = True + r.notes.append("an engine ran out of memory; the search stopped (nothing was retried)") + break + continue + over = self._memory_overrun(res, base1) + if over: + rep.status, rep.reason = "failed", over + alive = [x for x in alive if x.arm.id != p.arm.id] + continue + round_runs[rnd][p.arm.id] = res + # a candidate that lost by more than the margin against its own round's base is dropped from later rounds + for p in list(alive): + b, c = round_runs[rnd].get("base"), round_runs[rnd].get(p.arm.id) + m_b, m_c = (metric(b, o.use) if b else None), (metric(c, o.use) if c else None) + if m_b and m_c and m_c / m_b < 1.0 - o.margin: + by_id[p.arm.id].status = "dropped" + by_id[p.arm.id].reason = f"slower by {100 * (1 - m_c / m_b):.1f}% in round {rnd + 1}" + alive = [x for x in alive if x.arm.id != p.arm.id] + data: dict[str, list[tuple[RunResult, RunResult]]] = { + a.id: [(rr["base"], rr[a.id]) for rr in round_runs if a.id in rr and "base" in rr] for a in arms} + + # ---- noise: the A/A gap between base runs, the drift against a final base run + end_base: RunResult | None = None + ran_any = any(len(v) for v in data.values()) + if not self.storm and not self.cancel.is_set() and ran_any and not self._over_budget() and not self._ram_guard(0, "your current settings"): + self._say("drift", "Measuring your current settings once more to check the PC did not drift") + end_base = self._run(self.base_args, {}, spec, "base end") + if end_base.status == "PASS": + self.base_runs.append(end_base) + mb = [metric(b, o.use) for b in self.base_runs if metric(b, o.use)] + aa = abs(mb[1] / mb[0] - 1.0) if len(mb) >= 2 else 0.0 + drift = abs(mb[-1] / mb[0] - 1.0) if len(mb) >= 3 else (aa if len(mb) == 2 else 0.0) + spread = (max(mb) / min(mb) - 1.0) if len(mb) >= 2 else 0.0 + r.noise = {"aa_gap": round(aa, 4), "drift": round(drift, 4), "spread": round(spread, 4), + "base_runs": [round(x, 2) for x in mb], "noisy": spread > STAGE_GAP_NOISY} + threshold = accept_threshold(o.margin, aa, drift) + + # ---- evaluate the candidates + winners: list[ArmReport] = [] + for p in planned: + rep = by_id[p.arm.id] + rows = data[p.arm.id] + if rep.status in ("failed", "skipped") or not rows: + continue + ratios, pps = [], [] + for b, c in rows: + mc, mbb = metric(c, o.use), metric(b, o.use) + if mc and mbb: + ratios.append(mc / mbb) + if c.pp_tok_s and b.pp_tok_s: + pps.append(c.pp_tok_s / b.pp_tok_s) + rep.pairs = len(ratios) + rep.faster = sum(1 for x in ratios if x > 1.0) + rep.ratio_decode = round(statistics.median(ratios), 4) if ratios else None + rep.ratio_pp = round(statistics.median(pps), 4) if pps else None + rep.runs = [{"ratio": round(x, 4)} for x in ratios] + if rep.status == "dropped": + continue + rep.status = "tested" + if len(ratios) >= per_arm and is_win(ratios, pps, threshold=threshold): + rep.won = True + winners.append(rep) + r.arms = [a.to_dict() for a in arms] + + if r.noise["noisy"] and not winners: + r.notes.append(f"the PC was noisy ({spread * 100:.1f}% between identical runs)") + + # ---- stage 4: stack the winners, then (thorough) confirm against the base with more pairs + chosen_args: dict[str, Any] = {} + chosen_env: dict[str, str | None] = {} + final_pairs: list[tuple[RunResult, RunResult]] = [] + if winners: + winners.sort(key=lambda a: a.ratio_decode or 0.0, reverse=True) + incumbent = [winners[0]] + for extra in winners[1:]: + conflict = set(extra.settings) & {k for w in incumbent for k in w.settings} + if not conflict: + incumbent.append(extra) + for w in incumbent: + chosen_args.update(w.settings) + chosen_env.update(w.env) + need_confirm = len(incumbent) > 1 or (o.confirm_pairs or 0) > 0 + if need_confirm and not self._over_budget(reserve_s=2 * self._avg_run()): + n = o.confirm_pairs or 2 + self._say("confirm", "Confirming the combined result against your current settings") + final_pairs = self._confirm(chosen_args, chosen_env, spec, n) + ratios = [metric(c, o.use) / metric(b, o.use) for b, c in final_pairs if metric(c, o.use) and metric(b, o.use)] + pps = [c.pp_tok_s / b.pp_tok_s for b, c in final_pairs if c.pp_tok_s and b.pp_tok_s] + need = max(2, int(math.ceil(0.8 * len(ratios)))) if len(ratios) >= 5 else len(ratios) + if not (ratios and is_win(ratios, pps, threshold=threshold, need=need)): + # the stack did not hold; fall back to the best single winner, which already won its own pairs + if len(incumbent) > 1: + r.notes.append("the combination did not beat the best single change; keeping the best single change") + best = incumbent[0] + chosen_args, chosen_env = dict(best.settings), dict(best.env) + final_pairs = [(b, c) for b, c in data[best.id]] + else: + winners, chosen_args, chosen_env, final_pairs = [], {}, {}, [] + r.notes.append("the gain did not hold up in the confirmation, so nothing was changed") + else: + pass + else: + best = incumbent[0] + chosen_args, chosen_env = dict(best.settings), dict(best.env) + final_pairs = list(data[best.id]) + if not final_pairs and winners: + final_pairs = list(data[winners[0].id]) + + # ---- per-request winners (found in the base engine): keep only the ones that won every round + per_request_chosen = {row["key"]: row["value"] for row in r.per_request if row.get("won")} + + # ---- result + if end_base is not None and end_base.status == "PASS" and drift > 0.03 and winners: + gain_guess = statistics.median([metric(c, o.use) / metric(b, o.use) for b, c in final_pairs]) - 1.0 if final_pairs else 0.0 + if gain_guess < 2 * drift: + chosen_args, chosen_env, winners, final_pairs = {}, {}, [], [] + per_request_chosen = {} + r.outcome = "inconclusive" + r.message = ("The PC changed speed while measuring (about %.0f%%), more than the gain found, so nothing " + "was changed. Try again when nothing else is running." % (drift * 100)) + if r.outcome != "inconclusive": + if chosen_args or chosen_env or per_request_chosen: + r.outcome = "improved" + elif r.noise["noisy"] and (spread > 2 * STAGE_GAP_NOISY): + r.outcome = "inconclusive" + r.message = "The PC was too noisy to tell settings apart, so nothing was changed. Try again when it is idle." + else: + r.outcome = "default_confirmed" + r.message = "Your current settings are already the fastest we found. Nothing was changed." + r.settings = {"args": chosen_args, "env": chosen_env, "per_request": per_request_chosen} + cls, fields = "exact", [] + for rep in arms: + if rep.won and any(k in chosen_args for k in rep.settings) or (rep.won and any(k in chosen_env for k in rep.env)): + if tune_knobs.ANSWER_ORDER.index(rep.answer) > tune_knobs.ANSWER_ORDER.index(cls): + cls = rep.answer + if rep.answer != "exact": + fields += list(rep.settings) + list(rep.env) + for key in per_request_chosen: + for row in tune_knobs.PER_REQUEST: + if row["key"] == key and tune_knobs.ANSWER_ORDER.index(row["answer"]) > tune_knobs.ANSWER_ORDER.index(cls): + cls = row["answer"] + if row["key"] == key and row["answer"] != "exact": + fields.append(key) + r.answers = {"class": cls, "fields": sorted(set(fields))} + if final_pairs: + ratios = [metric(c, o.use) / metric(b, o.use) for b, c in final_pairs if metric(c, o.use) and metric(b, o.use)] + pps = [c.pp_tok_s / b.pp_tok_s for b, c in final_pairs if c.pp_tok_s and b.pp_tok_s] + r.pairs = len(ratios) + r.faster_pairs = sum(1 for x in ratios if x > 1.0) + r.gain_pct = round(100 * (statistics.median(ratios) - 1.0), 1) if ratios else 0.0 + r.gain_pp_pct = round(100 * (statistics.median(pps) - 1.0), 1) if pps else 0.0 + dec = [c.decode_tok_s / b.decode_tok_s for b, c in final_pairs if c.decode_tok_s and b.decode_tok_s] + r.gain_decode_pct = round(100 * (statistics.median(dec) - 1.0), 1) if dec else 0.0 + c_runs = [c for _, c in final_pairs] + r.chosen = {"decode_tok_s": round(statistics.median([c.decode_tok_s for c in c_runs if c.decode_tok_s]), 2) + if any(c.decode_tok_s for c in c_runs) else None, + "pp_tok_s": round(statistics.median([c.pp_tok_s for c in c_runs if c.pp_tok_s]), 1) + if any(c.pp_tok_s for c in c_runs) else None, + "rss_peak_mib": max([c.rss_peak_mib for c in c_runs if c.rss_peak_mib] or [None]) if any(c.rss_peak_mib for c in c_runs) else None, + "vram_used_mib": max([c.vram_used_mib for c in c_runs if c.vram_used_mib] or [None]) if any(c.vram_used_mib for c in c_runs) else None} + elif r.outcome == "improved" and per_request_chosen: + r.gain_pct = r.gain_decode_pct = round(100 * (statistics.median( + [row["ratio"] for row in r.per_request if row.get("won")]) - 1.0), 1) + r.chosen = dict(r.base) + else: + r.chosen = {k: r.base.get(k) for k in ("decode_tok_s", "pp_tok_s", "rss_peak_mib", "vram_used_mib")} + if r.outcome == "improved": + r.message = "+%.0f%% faster answers" % r.gain_pct if r.gain_pct >= 0.5 else "slightly faster" + self._say("done", r.message or "Done") + + # ---- helpers + def _memory_overrun(self, res: RunResult, base: RunResult) -> str | None: + """A candidate that takes more memory than the base the user asked for is not a candidate (their wish, 20% left + for work, is a promise about memory).""" + if res.rss_peak_mib and base.rss_peak_mib and res.rss_peak_mib > base.rss_peak_mib * 1.05 + 512 and self.o.goal == "room": + return "it needs more memory than your current settings, which would eat into the memory you wanted left free" + if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib: + return "it left the PC with too little free memory" + if self.o.goal == "room" and self.o.ram_wish_pct and self.total_ram and res.min_avail_mib is not None and \ + base.min_avail_mib is not None: + if res.min_avail_mib < base.min_avail_mib - max(512, 0.03 * self.total_ram): + return "it left less memory free than your current settings" + if self.o.goal == "room" and res.vram_used_mib is not None and base.vram_used_mib is not None and \ + res.vram_used_mib > base.vram_used_mib + 256: + return "it uses more graphics memory than your current settings" + if self.o.goal == "room" and self.o.reserve_mib and self.total_vram and res.vram_used_mib is not None and \ + base.vram_used_mib is not None and self.total_vram - base.vram_used_mib >= self.o.reserve_mib - 128 and \ + self.total_vram - res.vram_used_mib < self.o.reserve_mib - 128: + return "it would not leave the graphics memory you wanted free" + return None + + def _confirm(self, args: dict[str, Any], env: dict[str, str | None], spec: RequestSet, pairs: int) -> list[tuple[RunResult, RunResult]]: + """Interleaved pairs of the combined settings against the base (the order alternates).""" + out: list[tuple[RunResult, RunResult]] = [] + cand_args = tune_knobs.apply_to_argv(self.base_args, args) + for i in range(pairs): + self._check_cancel() + if self._over_budget(reserve_s=2 * self._avg_run()): + self.result.notes.append("confirmation stopped early: the time you chose ran out") + break + first = "cand" if i % 2 == 0 else "base" + runs: dict[str, RunResult] = {} + for who in (first, "base" if first == "cand" else "cand"): + self._say("confirm", f"Confirming (pair {i + 1} of {pairs})") + runs[who] = self._run(cand_args if who == "cand" else self.base_args, env if who == "cand" else {}, spec, + f"confirm {who} {i + 1}") + if runs["cand"].status == "PASS" and runs["base"].status == "PASS": + if self.o.use and metric(runs["cand"], self.o.use) and metric(runs["base"], self.o.use): + out.append((runs["base"], runs["cand"])) + self.base_runs.append(runs["base"]) + else: + break + return out + + def _per_request_stage(self, eng: Any) -> list[dict[str, Any]]: + """Per-request settings against the engine's own choice, in this one engine, 3 interleaved rounds (6.3 step 2). + + A value is kept only if it beat the default by the margin in every round. No restart is needed, so these are + tried before any restart (5). One value per key can win.""" + points: list[tuple[str, Any]] = [] + for spec in tune_knobs.PER_REQUEST: + if self.ctx.backend not in spec["backends"]: + continue + if spec["answer"] != "exact" and not tune_knobs.allowed(spec["answer"], self.ctx): + continue + for v in spec["values"]: + points.append((spec["key"], v)) + if not points: + return [] + rounds = 3 + default: dict[int, float] = {} + vals: dict[tuple[str, Any], dict[int, float]] = {pt: {} for pt in points} + self._say("per_request", "Trying settings that need no restart") + for rnd in range(rounds): + for item in rotate([None] + points, rnd): + self._check_cancel() + if item is None: + d = eng.decode_once(None, 200) + if d: + default[rnd] = d + else: + d = eng.decode_once({item[0]: item[1]}, 200) + if d: + vals[item][rnd] = d + rows: list[dict[str, Any]] = [] + for pt in points: + ratios = [vals[pt][i] / default[i] for i in range(rounds) if i in vals[pt] and i in default] + won = len(ratios) == rounds and all(x >= 1.0 + self.o.margin for x in ratios) + rows.append({"key": pt[0], "value": pt[1], "ratios": [round(x, 4) for x in ratios], + "ratio": round(statistics.median(ratios), 4) if ratios else None, "won": won}) + best: dict[str, dict[str, Any]] = {} + for row in rows: + if row["won"] and (row["key"] not in best or row["ratio"] > best[row["key"]]["ratio"]): + best[row["key"]] = row + for row in rows: + row["won"] = best.get(row["key"]) is row + return rows + + +# --------------------------------------------------------------------------- building a tuner from a run configuration + +def split_args(argv: list[str]) -> list[str]: + return [str(a) for a in argv] + + +def detect_family(args: list[str]) -> str: + for i, a in enumerate(args): + if a == "--mtp" and i + 1 < len(args): + return "qwen36" if str(args[i + 1]).isdigit() else "flash-next" + if "--pack" in args or "--native" in args: + return "flash-next" + return "flash-next" + + +def model_gib_of(args: list[str]) -> float: + """Total size of the model files a configuration names, shards included.""" + from pathlib import Path + import re + total = 0 + seen: set[str] = set() + for i, a in enumerate(args): + if a in ("--native", "--model", "--ple-gguf") and i + 1 < len(args): + p = Path(str(args[i + 1])) + if not p.is_file() or str(p) in seen: + continue + m = re.match(r"(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name) + group = sorted(p.parent.glob(f"{m.group(1)}-*-of-{m.group(3)}.gguf")) if m else [p] + for f in group: + if str(f) not in seen: + seen.add(str(f)) + total += f.stat().st_size + return round(total / 1024 ** 3, 1) + + +def context_from_config(cfg: dict[str, Any], *, engine_backend: str | None, opts: Options, + engine_flags: list[str] | None = None, system: dict[str, Any] | None = None, + family: str | None = None) -> tune_knobs.Context: + args = split_args(cfg.get("args") or []) + system = system or {"memory": tune_machine.memory(), "gpus": tune_machine.gpus(), "cpu": tune_machine.cpu()} + gpu_cfg = cfg.get("gpu") + wanted = gpu_cfg if isinstance(gpu_cfg, list) else ([gpu_cfg] if isinstance(gpu_cfg, int) else None) + cards = system.get("gpus") or [] + used = [g for g in cards if not wanted or g.get("index") in wanted] or cards + ctx_tokens = 32768 + for i, a in enumerate(args): + if a == "--max-context" and i + 1 < len(args) and str(args[i + 1]).isdigit(): + ctx_tokens = int(args[i + 1]) + mem = system.get("memory") or {} + cpu = system.get("cpu") or {} + backend = engine_backend or ("cuda" if any(g.get("vendor") == "nvidia" for g in cards) else + "hip" if any(g.get("vendor") == "amd" for g in cards) else "cpu") + arch = None + return tune_knobs.Context( + backend=backend, family=family or detect_family(args), gpu_count=max(1, len(used)), + vram_mib=min((g["vram_total_mib"] for g in used if g.get("vram_total_mib")), default=0), + ram_gib=int((mem.get("total_mib") or 0) // 1024), model_gib=model_gib_of(args), + hybrid_cpu=bool(cpu.get("hybrid")), logical_threads=int(cpu.get("logical") or 0), arch=arch, + context_tokens=ctx_tokens, goal=opts.goal, use=opts.use, allow_placement=opts.allow_placement, + allow_nonrepeatable=opts.allow_nonrepeatable, engine_flags=engine_flags, base_args=args) + + +# --------------------------------------------------------------------------- the short "still good?" re-check (8.3) + +def recheck(session: Session, base_args: list[str], preset: dict[str, Any], *, ctx: tune_knobs.Context, + engine_changed: bool = False, progress: Callable[[dict[str, Any]], None] | None = None, + cancel: threading.Event | None = None, clock: Callable[[], float] = time.monotonic) -> dict[str, Any]: + """Is a saved preset still as fast as when it was made? One restart with the preset's settings and 30-45 s of requests. + + Pass rule (against the stored numbers, not a fresh baseline): decode and the 4K prompt at least 95% of what was stored, + memory within the stored +5%. A failing prompt rate is measured once more with a second start before it counts (the + prompt rate of some cards is bimodal between engine starts). When the engine changed in a way that can move speed + (``tuning_epoch``) a baseline start is added and the preset must be at least as fast as doing nothing. + The result is ``keep``, ``retune`` (suggested, never forced) or ``inconclusive`` (noise or a competing process).""" + progress = progress or (lambda p: None) + cancel = cancel or threading.Event() + t0 = clock() + s = preset.get("settings") or {} + stored = preset.get("measured") or {} + args = tune_knobs.apply_to_argv(base_args, s.get("args") or {}) + env = dict(s.get("env") or {}) + spec = RequestSet(warmups=1, decodes=3, decode_tokens=200, pp_tokens=4096 if ctx.context_tokens >= 6000 else 1024, long_tokens=0) + if ctx.backend == "sycl": + spec.pp_tokens = 0 # the A750's 4K prompt takes a minute: decode only (8.3) + out: dict[str, Any] = {"verdict": "inconclusive", "request_set": RECHECK_SET_NAME, "notes": []} + + def one(a: list[str], e: dict[str, str | None], label: str) -> RunResult: + if cancel.is_set(): + raise Cancelled() + progress({"stage": "recheck", "message": label, "elapsed_s": round(clock() - t0)}) + try: + with session.engine(a, e) as eng: + r = eng.measure(spec) + except StartFailed as ex: + return RunResult(status=ex.status, reason=ex.reason) + return r + + try: + run = one(args, env, "Checking your saved settings") + if run.status != "PASS": + out.update(verdict="retune", reason=f"the saved settings did not start now: {run.status} {run.reason}") + out["seconds"] = round(clock() - t0, 1) + return out + out["measured"] = {"decode_tok_s": run.decode_tok_s, "pp4k_tok_s": run.pp_tok_s, "rss_peak_mib": run.rss_peak_mib, + "vram_peak_mib": run.vram_used_mib} + sd, sp = stored.get("decode_tok_s"), stored.get("pp4k_tok_s") + problems: list[str] = [] + if sd and run.decode_tok_s and run.decode_tok_s < 0.95 * sd: + problems.append(f"answers are {100 * (1 - run.decode_tok_s / sd):.0f}% slower than when it was saved") + if sp and run.pp_tok_s and run.pp_tok_s < 0.95 * sp: + again = one(args, env, "Checking prompt speed once more") + if again.status == "PASS" and again.pp_tok_s and again.pp_tok_s >= 0.95 * sp: + out["notes"].append("prompt speed varied between starts; the second start was fine") + else: + problems.append("long prompts are slower than when it was saved") + for key, got in (("rss_peak_mib", run.rss_peak_mib), ("vram_peak_mib", run.vram_used_mib)): + ref = stored.get(key) + if ref and got and got > 1.05 * ref: + problems.append("it now uses more memory than when it was saved") + break + if engine_changed: + base = one(base_args, {}, "Checking against the standard settings after the engine update") + if base.status == "PASS" and base.decode_tok_s and run.decode_tok_s and run.decode_tok_s < base.decode_tok_s: + problems.append("the standard settings are now faster than the saved ones") + out["baseline"] = {"decode_tok_s": base.decode_tok_s, "pp4k_tok_s": base.pp_tok_s} + out["problems"] = problems + out["verdict"] = "retune" if problems else "keep" + out["reason"] = ("Still as fast as when it was saved." if not problems else "; ".join(problems)) + except Cancelled: + out.update(verdict="inconclusive", reason="Stopped.") + out["seconds"] = round(clock() - t0, 1) + return out + + +RECHECK_SET_NAME = "recheck/1" diff --git a/strata_control/presets.py b/strata_control/presets.py new file mode 100644 index 00000000..f99e5f7b --- /dev/null +++ b/strata_control/presets.py @@ -0,0 +1,517 @@ +"""Saved tuning presets: tune once, keep it. + +One store for the Terminal and the desktop app: a folder of small JSON files (``presets/`` beside the profiles), so tuning in +one place covers the other. A preset holds + +* the settings the tuner found (``settings``: engine arguments, environment, per-request defaults), +* what was measured (speeds and the baseline they were compared to), +* the user's choices it was made for (model, context, KV format, "leave room" or "full performance", chat or coding), and +* the identity it is valid for: the PC (graphics card and driver, memory, processor), the engine build and the model file. + +On every start the **active** preset for the model's choices is applied with no measurement (`overlay`, called by the +server before it starts the engine). When the identity changed the preset says how much: a new graphics card or model file +is a *hard* change (settings may not even start, so they are not applied on their own); a new driver or an engine build +with a new ``tuning_epoch`` is a *soft* change (the preset still applies, and a 2-minute re-check is offered, never forced). + +Several named presets per model; activating one keeps the one it replaced, so **undo** restores it exactly. Nothing here +starts an engine or changes anything but its own folder. +""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +import time +import uuid +from pathlib import Path +from typing import Any + +from strata_control import tune_knobs, tune_machine + +SCHEMA = "strata.preset/1" +RECHECK_SET = "recheck/1" +DEFAULT_LAST_OK_DAYS = 90 + + +class PresetError(ValueError): + """A preset is missing or invalid; the message is for the user.""" + + +# --------------------------------------------------------------------------- the folder + +def preset_dir() -> Path: + explicit = os.environ.get("STRATA_PRESET_DIR") + if explicit: + return Path(explicit).expanduser() + from strata_control import profiles + return profiles.profile_dir().parent / "presets" + + +def _atomic(path: Path, payload: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(fd, "wb") as fh: + fh.write(payload) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def _write_json(path: Path, obj: Any) -> None: + _atomic(path, (json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8")) + + +def _read_json(path: Path, default: Any) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return default + + +def _path(pid: str) -> Path: + if not re.fullmatch(r"[0-9a-f]{32}", pid): + raise PresetError("that is not a preset id") + return preset_dir() / f"{pid}.json" + + +# --------------------------------------------------------------------------- the choices a preset belongs to + +_QUANT = re.compile(r"(UD-Q\d_K_\w+|IQ\d_[A-Z]+|Q\d_K_[A-Z]+|Q\d_K|Q\d_\d|Q\d|BF16|F16)", re.I) + + +def choices_from_config(cfg: dict[str, Any], *, use: str = "chat") -> dict[str, Any]: + """What the user chose, read from a run configuration: model, context, KV format, pictures, and whether they asked to + leave room for other work. The slot a preset is active in is made from these.""" + args = [str(a) for a in cfg.get("args") or []] + + def val(flag: str) -> str | None: + for i, a in enumerate(args): + if a == flag and i + 1 < len(args) and not args[i + 1].startswith("--"): + return args[i + 1] + return None + + ctx = val("--max-context") + native = val("--native") or val("--model") or "" + quant = (_QUANT.search(Path(native).name) or _QUANT.search(str(cfg.get("model_name") or ""))) + profile = cfg.get("ui_resource_profile") + reserve = cfg.get("vram_reserve_mib") + room = profile == "work" + return { + "model": str(cfg.get("model_name") or Path(native).stem or "model"), + "quant": quant.group(1).upper() if quant else None, + "model_file": native, + "context": int(ctx) if ctx and ctx.isdigit() else None, + "kv": val("--kv") or "int8", + "vision": bool(cfg.get("ui_vision_enabled")) or "--vision" in args, + "goal": "room" if room else "speed", + "reserve_mib": int(reserve) if isinstance(reserve, (int, float)) else 0, + "use": use, + "family": "qwen36" if (val("--mtp") or "").isdigit() else "flash-next", + } + + +def default_name(choices: dict[str, Any]) -> str: + ctx = choices.get("context") + ctx_s = f"{ctx // 1024}K" if ctx else "?" + label = choices.get("quant") or choices.get("model") or "Model" + wish = "Work" if choices.get("goal") == "room" else "Full speed" + return f"{label} {ctx_s} – {wish}" + + +def slot_key(choices: dict[str, Any], model_digest: str | None) -> str: + """Presets of the same model file, context, KV format, pictures and wish compete for the active place.""" + return tune_machine.stable_hash({"m": model_digest, "ctx": choices.get("context"), "kv": choices.get("kv"), + "v": bool(choices.get("vision")), "g": choices.get("goal")}) + + +# --------------------------------------------------------------------------- identity and staleness + +def current_identity(cfg: dict[str, Any], *, exe: str | None = None, pcie: str | None = None) -> dict[str, Any]: + """The identity this PC, engine and model file have now.""" + from strata_control import engine_component + args = [str(a) for a in cfg.get("args") or []] + files = [a for a in args if a.lower().endswith(".gguf")] + native = None + for i, a in enumerate(args): + if a == "--native" and i + 1 < len(args): + native = args[i + 1] + first = native or (files[0] if files else None) + engine_path = exe + if engine_path is None: + try: + ref = cfg.get("exe") + engine_path = engine_component.expand(ref, cfg, full=False) if ref else None + except Exception: # noqa: BLE001 + engine_path = cfg.get("exe") + return {"hardware": tune_machine.hardware_identity(pcie=pcie), + "engine": tune_machine.engine_identity(engine_path) if engine_path else {}, + "model": tune_machine.model_identity([first]) if first and Path(first).is_file() else {}} + + +def staleness(preset: dict[str, Any], now: dict[str, Any], *, today: float | None = None) -> dict[str, Any]: + """Compare a preset's identity with the current one: ``state`` is fresh, soft (re-check offered) or hard (settings + are not applied on their own; re-tune offered). ``reasons`` are plain words.""" + old = preset.get("identity") or {} + hard: list[str] = [] + soft: list[str] = [] + oh, nh = (old.get("hardware") or {}).get("hard") or {}, (now.get("hardware") or {}).get("hard") or {} + if oh and nh: + if oh.get("gpus") != nh.get("gpus"): + hard.append("the graphics card changed") + if oh.get("cpu") != nh.get("cpu") or oh.get("logical") != nh.get("logical"): + hard.append("the processor changed") + a, b = oh.get("ram_gib"), nh.get("ram_gib") + if a and b and abs(a - b) / max(a, b) > 0.10: + hard.append("the amount of memory changed") + if oh.get("pcie") and nh.get("pcie") and oh["pcie"] != nh["pcie"]: + hard.append("the PCIe link changed") + om, nm = (old.get("model") or {}), (now.get("model") or {}) + if om.get("sha256_shard1") and nm.get("sha256_shard1") and om["sha256_shard1"] != nm["sha256_shard1"]: + hard.append("the model file changed") + oe, ne = (old.get("engine") or {}), (now.get("engine") or {}) + if oe.get("backend") and ne.get("backend") and oe["backend"] != ne["backend"]: + hard.append("the engine's graphics backend changed") + if oe and ne and int(oe.get("tuning_epoch") or 0) != int(ne.get("tuning_epoch") or 0): + soft.append("the engine was updated in a way that can change speed") + elif oe.get("version") and ne.get("version") and oe["version"] != ne["version"] and \ + oe.get("sha256") and ne.get("sha256") and oe["sha256"] != ne["sha256"] and \ + int(oe.get("tuning_epoch") or 0) != int(ne.get("tuning_epoch") or 0): + soft.append("the engine was updated") + os_, ns = (old.get("hardware") or {}).get("soft") or {}, (now.get("hardware") or {}).get("soft") or {} + if os_.get("driver") and ns.get("driver") and os_["driver"] != ns["driver"]: + soft.append("the graphics driver changed") + last_ok = ((preset.get("recheck") or {}).get("last_ok_epoch")) or preset.get("created_epoch") + if last_ok and (today or time.time()) - last_ok > DEFAULT_LAST_OK_DAYS * 86400: + soft.append("it has not been checked for a while") + if hard: + return {"state": "hard", "reasons": hard + soft} + if soft: + return {"state": "soft", "reasons": soft} + return {"state": "fresh", "reasons": []} + + +# --------------------------------------------------------------------------- the store + +def _index() -> dict[str, Any]: + idx = _read_json(preset_dir() / "active.json", {}) + return idx if isinstance(idx, dict) else {} + + +def _save_index(idx: dict[str, Any]) -> None: + _write_json(preset_dir() / "active.json", idx) + + +def load(pid: str) -> dict[str, Any]: + data = _read_json(_path(pid), None) + if not isinstance(data, dict) or data.get("schema") != SCHEMA: + raise PresetError("that preset does not exist") + return data + + +def find(ref: str) -> dict[str, Any]: + """A preset by id, id prefix or exact name (case-insensitive); an ambiguous name is refused.""" + items = list_presets() + exact = [p for p in items if p["id"] == ref] + if exact: + return exact[0] + by_prefix = [p for p in items if len(ref) >= 4 and p["id"].startswith(ref)] + by_name = [p for p in items if p["name"].lower() == ref.lower()] + found = by_name or by_prefix + if not found: + raise PresetError(f"no preset called '{ref}'") + if len(found) > 1: + raise PresetError(f"'{ref}' matches {len(found)} presets; use the id") + return found[0] + + +def list_presets(*, model: str | None = None) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + d = preset_dir() + if not d.is_dir(): + return out + idx = _index() + active_ids = {v.get("active") for v in idx.values() if isinstance(v, dict)} + for f in sorted(d.glob("*.json")): + if f.name == "active.json": + continue + data = _read_json(f, None) + if not isinstance(data, dict) or data.get("schema") != SCHEMA: + continue + if model and model.lower() not in json.dumps(data.get("choices", {})).lower(): + continue + data["active"] = data.get("id") in active_ids + out.append(data) + out.sort(key=lambda p: p.get("created_epoch", 0), reverse=True) + return out + + +def _name_taken(name: str, exclude: str | None = None) -> bool: + return any(p["name"].lower() == name.lower() and p["id"] != exclude for p in list_presets()) + + +def _unique_name(name: str) -> str: + if not _name_taken(name): + return name + n = 2 + while _name_taken(f"{name} ({n})"): + n += 1 + return f"{name} ({n})" + + +def create(result: dict[str, Any], *, choices: dict[str, Any], identity: dict[str, Any], name: str | None = None, + mode: str = "quick", activate: bool = True, base_args: dict[str, Any] | None = None) -> dict[str, Any]: + """Save a tune result as a named preset (active at once unless ``activate`` is False).""" + settings = result.get("settings") or {"args": {}, "env": {}, "per_request": {}} + problems = tune_knobs.check_setting(settings.get("args") or {}, settings.get("env") or {}, + tune_knobs.Context(context_tokens=choices.get("context") or 32768, + family=choices.get("family") or "flash-next")) + if problems: + raise PresetError("these settings are outside the safe rules and cannot be saved: " + "; ".join(problems)) + base = result.get("base") or {} + chosen = result.get("chosen") or {} + pid = uuid.uuid4().hex + now = time.time() + digest = (identity.get("model") or {}).get("sha256_shard1") + preset = { + "schema": SCHEMA, "id": pid, "name": _unique_name(name or default_name(choices)), + "created": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(now)), "created_epoch": now, + "tuner": {"mode": mode, "version": "1", "seconds": result.get("seconds"), "outcome": result.get("outcome")}, + "choices": choices, "identity": identity, "slot": slot_key(choices, digest), + "settings": {"args": settings.get("args") or {}, "env": settings.get("env") or {}, + "per_request": settings.get("per_request") or {}}, + "answers": result.get("answers") or {"class": "exact", "fields": []}, + "baseline": {"args": base_args or {}, "decode_tok_s": base.get("decode_tok_s"), "pp4k_tok_s": base.get("pp_tok_s"), + "pairs": result.get("pairs"), "noise_aa_decode": (result.get("noise") or {}).get("aa_gap")}, + "measured": {"decode_tok_s": chosen.get("decode_tok_s"), "pp4k_tok_s": chosen.get("pp_tok_s"), + "vram_peak_mib": chosen.get("vram_used_mib"), "rss_peak_mib": chosen.get("rss_peak_mib"), + "pairs": result.get("pairs"), "faster_pairs": result.get("faster_pairs"), + "gain_pct": result.get("gain_pct"), "gain_decode_pct": result.get("gain_decode_pct"), + "gain_pp_pct": result.get("gain_pp_pct")}, + "noise": result.get("noise") or {}, + "evidence": {"arms": result.get("arms"), "per_request": result.get("per_request"), "notes": result.get("notes"), + "classes": result.get("classes")}, + "recheck": {"request_set": RECHECK_SET, "last_ok": None, "last_ok_epoch": None, "last_result": None}, + "previous": None, + } + _write_json(_path(pid), preset) + if activate: + activate_preset(pid) + preset = load(pid) + return preset + + +def activate_preset(ref: str) -> dict[str, Any]: + """Make a preset the active one for its slot; the one it replaces is kept for undo.""" + p = find(ref) + idx = _index() + entry = idx.get(p["slot"]) if isinstance(idx.get(p["slot"]), dict) else {"active": None, "history": []} + if entry.get("active") == p["id"]: + return p + if entry.get("active"): + entry.setdefault("history", []).append(entry["active"]) + entry["history"] = entry["history"][-20:] + p["previous"] = entry.get("active") + entry["active"] = p["id"] + idx[p["slot"]] = entry + _write_json(_path(p["id"]), {k: v for k, v in p.items() if k != "active"}) + _save_index(idx) + p["active"] = True + return p + + +def deactivate_slot(slot: str) -> None: + """Back to the standard setup for this slot (the active preset is kept for undo).""" + idx = _index() + entry = idx.get(slot) + if isinstance(entry, dict) and entry.get("active"): + entry.setdefault("history", []).append(entry["active"]) + entry["active"] = None + _save_index(idx) + + +def undo(slot_or_ref: str) -> dict[str, Any] | None: + """Restore the preset that was active before the current one (None = the standard setup). ``slot_or_ref`` is a slot + key or any preset of the slot.""" + idx = _index() + slot = slot_or_ref if slot_or_ref in idx else None + if slot is None: + slot = find(slot_or_ref)["slot"] + entry = idx.get(slot) + if not isinstance(entry, dict) or not entry.get("history") and entry.get("active") is None: + raise PresetError("there is nothing to undo") + hist = entry.get("history") or [] + if not hist: + entry["active"] = None + _save_index(idx) + return None + prev = hist.pop() + entry["history"] = hist + entry["active"] = prev if _path(prev).exists() else None + _save_index(idx) + return load(entry["active"]) if entry["active"] else None + + +def rename(ref: str, name: str) -> dict[str, Any]: + name = name.strip() + if not name or len(name) > 80 or re.search(r"[\r\n\0]", name): + raise PresetError("choose a name of 1 to 80 characters") + p = find(ref) + if _name_taken(name, p["id"]): + raise PresetError("another preset already has that name") + p["name"] = name + p.pop("active", None) + _write_json(_path(p["id"]), p) + return find(p["id"]) + + +def delete(ref: str) -> None: + p = find(ref) + idx = _index() + for slot, entry in list(idx.items()): + if not isinstance(entry, dict): + continue + entry["history"] = [h for h in entry.get("history", []) if h != p["id"]] + if entry.get("active") == p["id"]: + entry["active"] = entry["history"].pop() if entry["history"] else None + _save_index(idx) + try: + _path(p["id"]).unlink() + except OSError: + pass + + +def export_preset(ref: str) -> dict[str, Any]: + p = find(ref) + p.pop("active", None) + return p + + +def import_preset(data: dict[str, Any]) -> dict[str, Any]: + if not isinstance(data, dict) or data.get("schema") != SCHEMA: + raise PresetError("that file is not a Strata preset") + problems = tune_knobs.check_setting((data.get("settings") or {}).get("args") or {}, (data.get("settings") or {}).get("env") or {}, + tune_knobs.Context(context_tokens=(data.get("choices") or {}).get("context") or 32768)) + if problems: + raise PresetError("the preset has settings outside the safe rules: " + "; ".join(problems)) + data = dict(data) + data["id"] = uuid.uuid4().hex + data["name"] = _unique_name(str(data.get("name") or "Imported preset")) + data["previous"] = None + data.pop("active", None) + _write_json(_path(data["id"]), data) + return find(data["id"]) + + +def record_recheck(ref: str, outcome: dict[str, Any]) -> dict[str, Any]: + p = find(ref) + p.pop("active", None) + rc = dict(p.get("recheck") or {}) + rc["last_result"] = outcome + if outcome.get("verdict") == "keep": + rc["last_ok"] = time.strftime("%Y-%m-%dT%H:%M:%S%z") + rc["last_ok_epoch"] = time.time() + # an identity that was soft-stale is refreshed once the settings were checked on this PC + if outcome.get("identity"): + p["identity"] = outcome["identity"] + better = outcome.get("measured") + if better and p.get("measured", {}).get("decode_tok_s") and better.get("decode_tok_s") and \ + better["decode_tok_s"] > 1.03 * p["measured"]["decode_tok_s"]: + p["measured"].update({k: v for k, v in better.items() if v is not None}) + p["recheck"] = rc + _write_json(_path(p["id"]), p) + return find(p["id"]) + + +# --------------------------------------------------------------------------- applying the active preset at every start + +def notice(preset: dict[str, Any]) -> str: + return tune_knobs.ANSWER_NOTICE.get((preset.get("answers") or {}).get("class", "exact"), "") + + +def overlay(cfg: dict[str, Any], *, now: dict[str, Any] | None = None, use: str = "chat") -> tuple[dict[str, Any], dict[str, Any]]: + """The run configuration with the active preset for its choices put on top, and what was done. + + No measurement happens here. A preset whose identity changed in a *hard* way is not applied (it says why); a *soft* change + applies it and marks it for a re-check. A setting that is outside the safe rules is left out, never applied. Never raises: + a store that cannot be read means "no preset", and the engine starts with the configuration as it is.""" + info: dict[str, Any] = {"applied": False} + try: + if not preset_dir().is_dir(): + return cfg, info + choices = choices_from_config(cfg, use=use) + now = now or current_identity(cfg) + digest = (now.get("model") or {}).get("sha256_shard1") + entry = _index().get(slot_key(choices, digest)) + if not isinstance(entry, dict) or not entry.get("active"): + return cfg, info + preset = load(entry["active"]) + stale = staleness(preset, now) + info.update({"preset": {"id": preset["id"], "name": preset["name"]}, "state": stale["state"], "reasons": stale["reasons"]}) + if stale["state"] == "hard": + info["why_not"] = "not applied: " + "; ".join(stale["reasons"]) + return cfg, info + s = preset.get("settings") or {} + ctx = tune_knobs.Context(context_tokens=choices.get("context") or 32768, family=choices.get("family") or "flash-next") + problems = tune_knobs.check_setting(s.get("args") or {}, s.get("env") or {}, ctx) + if problems: + info["why_not"] = "not applied: " + "; ".join(problems) + return cfg, info + out = json.loads(json.dumps(cfg)) + out["args"] = tune_knobs.apply_to_argv([str(a) for a in out.get("args") or []], s.get("args") or {}) + if s.get("env"): + out["env"] = tune_knobs.apply_to_env(dict(out.get("env") or {}), s["env"]) + if s.get("per_request"): + sampling = dict(out.get("sampling") or {}) + sampling.setdefault("strata_tune", {k: v for k, v in s["per_request"].items() if v is not None}) + out["sampling"] = sampling + info.update({"applied": True, "args": s.get("args"), "env": s.get("env"), "per_request": s.get("per_request"), + "answers": preset.get("answers"), "notice": notice(preset)}) + return out, info + except Exception as e: # noqa: BLE001 - serving must never fail because of the preset store + info["error"] = f"{type(e).__name__}: {e}" + return cfg, info + + +# --------------------------------------------------------------------------- history of every trial + +def history_path() -> Path: + return preset_dir() / "history.jsonl" + + +def record_trials(trials: list[dict[str, Any]], *, hw_hash: str, model_digest: str | None, engine_sha: str | None) -> None: + from strata_control import tune_knobs as k + rows = [] + for t in trials: + args = {} + a = t.get("args") or [] + rows.append({"at": t.get("at"), "hw": hw_hash, "model": model_digest, "engine": engine_sha, "label": t.get("label"), + "sig": " ".join(str(x) for x in a) + "|" + json.dumps(t.get("env") or {}, sort_keys=True), + "status": t.get("status"), "reason": t.get("reason"), "decode_tok_s": t.get("decode_tok_s"), + "pp_tok_s": t.get("pp_tok_s"), "rss_peak_mib": t.get("rss_peak_mib")}) + if not rows: + return + p = history_path() + p.parent.mkdir(parents=True, exist_ok=True) + with open(p, "a", encoding="utf-8") as fh: + for r in rows: + fh.write(json.dumps(r, sort_keys=True) + "\n") + + +def bad_signatures(*, hw_hash: str, model_digest: str | None, engine_sha: str | None) -> set[str]: + """Candidates that did not start on this PC with this engine and model before (UNSUPPORTED or OOM): never retried.""" + bad: set[str] = set() + try: + for line in history_path().read_text(encoding="utf-8").splitlines(): + r = json.loads(line) + if r.get("hw") == hw_hash and r.get("model") == model_digest and r.get("engine") == engine_sha and \ + r.get("status") in ("UNSUPPORTED", "OOM"): + bad.add(r.get("label") or "") + except (OSError, ValueError): + pass + return bad diff --git a/strata_control/tune_knobs.py b/strata_control/tune_knobs.py new file mode 100644 index 00000000..5785f88c --- /dev/null +++ b/strata_control/tune_knobs.py @@ -0,0 +1,473 @@ +"""The tuner's knowledge, as data: which settings it may try, the bounds, the never-pick list, and what each costs. + +Everything here comes from the measured study in ``phaseA-tests/split/TUNING-SPEC.md`` (S5a, draft 1; section numbers +below are that document's). The rules are tables, not code, so a new measurement changes a row, and the same rows check a +candidate before it runs and a preset before it is applied. + +Rule 1 (6.6): a candidate is a **single-knob change of the user's own configuration**. It never starts at "the first +value of every dimension" (that is how the old Terminal sweep put ``--expert-cache 0 --kv fp16 --spec-min-p 0.001`` in +place of the user's settings). Rule 2: a value outside the bounds, or on the never list, is not tried. Rule 3: boolean +flags are present or absent (``--kv-grow 0`` is an unknown argument). + +Answer classes (3.2): ``exact`` (byte-identical to the standard setup), ``placement`` (same math, a different CPU/GPU +split, so near-ties can flip), ``quality`` (changes the numbers on purpose; never automatic), ``nonrepeatable`` (not +bit-exact run to run). Only ``exact`` is picked on its own; the others need the user's tick. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Callable, Sequence + +ANSWER_ORDER = ("exact", "placement", "nonrepeatable", "quality") + +#: What the Tune screen says about a preset's answer class (3.4), in plain words. +ANSWER_NOTICE = { + "exact": "Answers are identical to the standard setup.", + "placement": "Answers may differ slightly from the standard setup.", + "nonrepeatable": "Answers are not repeatable run to run.", + "quality": "Includes a quality setting that changes the numbers.", +} + +#: Flags that take no value (present = on, absent = off). +BOOL_FLAGS = frozenset({"--kv-grow", "--trim-stage-weights", "--no-host-worker", "--no-pool", "--mmap-experts", + "--resident-experts", "--prompt-cache-tail", "--vram-elastic", "--split-skip-if-fits", + "--resident-cpu-experts", "--no-hit-poke", "--expert-cache-per-layer", "--batch-mtp"}) + + +# --------------------------------------------------------------------------- the arms + +@dataclass(frozen=True) +class Arm: + """One candidate: a single knob (or one tied group) changed from the user's configuration.""" + + id: str + label: str # plain words, shown in the progress and the result + answer: str # exact | placement | nonrepeatable | quality + set_args: dict[str, Any] = field(default_factory=dict) # flag -> value | True (present) | None (remove) + env: dict[str, str | None] = field(default_factory=dict) + families: tuple[str, ...] = ("flash-next",) + backends: tuple[str, ...] = ("cuda", "hip") + classes: tuple[str, ...] = () # machine classes (6.2) whose list this arm is on + needs: tuple[str, ...] = () # machine facts that must hold, see `condition_holds` + goals: tuple[str, ...] = ("speed", "coding", "chat", "room") + ram_delta_mib: int = 0 # extra memory the engine is predicted to take over the base run + deep_only: bool = False + #: a dynamic value: name of a computed number ("workers-2" ...), filled from the base run's engine log + dynamic: dict[str, str] = field(default_factory=dict) + + def requires_flags(self) -> list[str]: + return [f for f in self.set_args if self.set_args[f] is not None] + + +ARMS: tuple[Arm, ...] = ( + # --- class A: RAM-bound resident mode (6.2) --------------------------------------------------------------- + Arm("adapt_async", "Learn which experts to keep while you chat, in the background", "nonrepeatable", + {"--adapt-async": 1}, backends=("cuda",), classes=("A",), needs=("resident_ram", "one_gpu")), + Arm("pin_by_need", "Pin memory only when needed", "exact", {}, {"STRATA_PIN_BY_NEED": "1"}, + backends=("cuda",), classes=("A",), needs=("one_gpu",)), + Arm("host_core_last", "Run the control thread on the last CPU core", "exact", {"--host-core": "last"}, + classes=("A", "F")), + # --- class B: large graphics memory (experts mostly resident) --------------------------------------------- + Arm("adapt_tier_fast", "Re-balance the expert cache faster", "placement", + {"--adapt-every": 1, "--adapt-swaps": 80, "--adapt-decay": 0.97}, classes=("B",)), + Arm("spec3", "Shorter speculative window (3 tokens)", "placement", {"--spec": 3}, classes=("A", "B")), + Arm("prefill_32k", "Larger prompt chunks (faster very long prompts)", "exact", {"--prefill": "auto:32768"}, + classes=("B",), goals=("coding",), ram_delta_mib=4096, needs=("vram_ge_24g",)), + # --- class C: mid graphics memory, PCIe-bound ------------------------------------------------------------- + Arm("adapt_decay_09", "Forget old expert use a little faster", "placement", {"--adapt-decay": 0.9}, + classes=("C", "G"), backends=("cuda", "hip", "sycl")), + Arm("trim_stage", "Trim stage weights on two cards", "exact", {"--trim-stage-weights": True}, + backends=("cuda",), classes=("C",), needs=("two_gpus",)), + Arm("workers_minus2", "Two fewer CPU helper threads", "exact", {}, classes=("C",), + dynamic={"--pool-workers": "workers-2"}), + # --- class F: hybrid CPU (performance + efficiency cores) ------------------------------------------------- + Arm("workers_minus1", "One fewer CPU helper thread", "exact", {}, classes=("F",), + dynamic={"--pool-workers": "workers-1"}, needs=("hybrid_cpu",)), + # --- class G: Intel Arc (SYCL) ---------------------------------------------------------------------------- + Arm("pcie_start_02", "Start with a smaller PCIe share", "placement", {"--pcie-frac": 0.2}, + backends=("sycl",), classes=("G",)), + # --- Qwen3.6 hybrid (class D) ----------------------------------------------------------------------------- + Arm("q36_workers_explicit", "Fix the CPU helper thread count", "exact", {}, families=("qwen36",), + backends=("cuda", "hip"), classes=("D",), dynamic={"--pool-workers": "workers"}, needs=("hybrid_experts",)), + Arm("q36_mtp1", "Shorter draft window (1)", "placement", {"--mtp": 1}, families=("qwen36",), + backends=("cuda", "hip"), classes=("D",), needs=("hybrid_experts",)), + Arm("q36_prefill_4096", "Larger prompt chunks (twice the prompt speed, a little slower answers)", "exact", + {"--prefill": 4096}, families=("qwen36",), backends=("cuda", "hip"), classes=("D",), goals=("coding",), + needs=("hybrid_experts",)), + Arm("q36_hybrid_rows_256", "Larger hybrid row blocks", "exact", {"--hybrid-rows": 256}, families=("qwen36",), + backends=("cuda", "hip"), classes=("D",), needs=("hybrid_experts",), deep_only=True), + # --- thorough only: effects measured as flat, tried last -------------------------------------------------- + Arm("kv_grow", "Allocate the conversation memory as it grows", "exact", {"--kv-grow": True}, + classes=("B", "C"), backends=("cuda", "hip", "sycl"), deep_only=True), +) + +#: The per-request settings (3.1, 4.1). They need no restart, so every one is tried before any restart (5). +#: `values` are tried against the engine's own choice (absent); a win needs >= 3% in every round. +PER_REQUEST: tuple[dict[str, Any], ...] = ( + {"key": "pcie_frac", "values": (0.2, 0.35, 0.0), "backends": ("cuda", "hip", "sycl"), + "label": "PCIe share", "answer": "placement"}, + {"key": "spec_min_p", "values": (0.7, 0.5), "backends": ("cuda", "hip", "sycl", "metal"), + "label": "speculative confidence floor", "answer": "exact"}, + {"key": "aux_cpus", "values": (1, 0), "backends": ("cuda", "hip"), "label": "spare CPU cores for helper threads", + "answer": "exact"}, +) + +# --------------------------------------------------------------------------- bounds and the never list + +#: Safe bounds (6.6, column 3). A value outside them is not tried and is refused in a preset. +BOUNDS: dict[str, dict[str, Any]] = { + "--spec": {"choices": (3, 4)}, + "--spec-min-p": {"min": 0.3, "max": 0.7}, + "--mtp": {"choices": (1, 2, 3), "numeric_only": True}, # Qwen3.6; Flash-Next's --mtp is a path + "--pcie-frac": {"min": 0.0, "max": 0.55}, + "--adapt-every": {"min": 1, "max": 4}, + "--adapt-swaps": {"min": 80, "max": 160}, + "--adapt-decay": {"min": 0.7, "max": 0.97}, + "--hybrid-rows": {"min": 64, "max": 256}, + "--host-core": {"choices": ("first", "last")}, + "--prefill": {"choices": ("auto", "auto:16384", "auto:32768", 2048, 4096)}, +} + +#: The never-pick list (4.5), as rows: ``flag`` (or ``env``), a condition on the machine, the value test and the reason +#: in plain words. ``when`` names facts from `condition_holds`; empty = always. +NEVER: tuple[dict[str, Any], ...] = ( + {"env": "STRATA_SH_STREAM", "when": ("gfx12",), "reason": "it halves decode speed on this graphics card"}, + {"env": "STRATA_RDNA2_SGEMM", "value": "all", "when": ("gfx12",), "reason": "it makes long prompts five times slower"}, + {"env": "STRATA_SELECT_SIMT", "reason": "its gain is below the 3% margin"}, + {"env": "STRATA_HIP_WMMA", "reason": "it changes the numbers (a quality setting)"}, + {"flag": "--pool-affinity", "when": ("hybrid_cpu",), "values": ("auto", "p-cores"), + "reason": "it made answers 47% slower on a CPU with performance and efficiency cores"}, + {"flag": "--pool-workers", "test": "above_engine_default", "reason": "more helper threads than the engine chose made it 36% slower"}, + {"flag": "--ple-io", "values": ("ram", "mmap"), "when": ("ram_bound",), + "reason": "it needs the table in memory, which this PC does not have to spare (-61% speed)"}, + {"flag": "--adapt-every", "test": "at_least", "limit": 100000, "reason": "turning the expert re-balancing off cost 3% to 44%"}, + {"flag": "--kv-resident", "test": "below_context", "reason": "it made answers 27% to 34% slower and changes them"}, + {"flag": "--pcie-frac", "test": "at_least", "limit": 0.75, "when": ("pcie_bound",), + "reason": "a high PCIe share made answers 14% to 37% slower"}, + {"flag": "--prefill", "test": "fixed_below_auto", "reason": "smaller prompt chunks made long prompts 11% to 75% slower"}, + {"flag": "--expert-vram", "test": "without_prefill", "families": ("qwen36",), + "reason": "without a matching prompt chunk it made prompts 44% slower"}, + {"flag": "--spec", "test": "at_least", "limit": 6, "reason": "wider speculative windows were 4% to 16% slower"}, + {"flag": "--spec", "test": "at_most", "limit": 2, "families": ("flash-next",), "reason": "a 2-token window was 4% to 11% slower"}, + {"flag": "--lookup-chain", "reason": "it was 3% to 8.5% slower"}, + {"flag": "--vram-reserve-mib", "when": ("vram_le_8g",), "reason": "this card cannot start with a reserve"}, + {"flag": "--expert-cache", "test": "zero_or_small", "reason": "turning the GPU expert cache off or very small costs speed"}, + {"flag": "--mtp", "test": "mtp_extreme", "families": ("qwen36",), "reason": "that draft window was 10% to 28% slower"}, +) + +#: Which flags change answers by themselves, for the notice on a preset (3.4). +ANSWER_OF_FLAG: dict[str, str] = { + "--expert-cache": "placement", "--vram-reserve-mib": "placement", "--adapt-every": "placement", + "--adapt-swaps": "placement", "--adapt-decay": "placement", "--adapt-min-gain": "placement", + "--pcie-frac": "placement", "--spec": "placement", "--mtp": "placement", "--lookup-chain": "placement", + "--kv-resident": "placement", "--kv": "quality", "--adapt-async": "nonrepeatable", +} + + +# --------------------------------------------------------------------------- the context rules run in + +@dataclass +class Context: + """The machine and the choices a candidate plan is made for.""" + + backend: str = "cuda" # cuda | hip | sycl | metal | cpu + family: str = "flash-next" # flash-next | qwen36 + gpu_count: int = 1 + vram_mib: int = 0 # the card the model runs on (smallest if several) + ram_gib: int = 0 + model_gib: float = 0.0 + hybrid_cpu: bool = False + logical_threads: int = 0 + arch: str | None = None # e.g. gfx1201 + context_tokens: int = 32768 + goal: str = "speed" # speed | room + use: str = "chat" # chat | coding + allow_placement: bool = False + allow_nonrepeatable: bool = False + facts: dict[str, Any] = field(default_factory=dict) # parsed from the base run's engine log + engine_flags: Sequence[str] | None = None + base_args: list[str] = field(default_factory=list) + + +def condition_holds(name: str, ctx: Context) -> bool: + f = ctx.facts + return { + "resident_ram": bool(f.get("resident_ram")), + "one_gpu": ctx.gpu_count <= 1, + "two_gpus": ctx.gpu_count == 2, + "hybrid_cpu": ctx.hybrid_cpu, + "hybrid_experts": bool(f.get("hybrid_experts")), + "vram_ge_24g": ctx.vram_mib >= 24000, + "vram_le_8g": 0 < ctx.vram_mib <= 8400, + "gfx12": bool(ctx.arch and ctx.arch.startswith("gfx12")), + "pcie_bound": 0 < ctx.vram_mib < 24000, + "ram_bound": bool(ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 30), + }.get(name, False) + + +def machine_classes(ctx: Context) -> list[str]: + """The classes of 6.2 this machine belongs to, in the order their candidate lists are walked.""" + classes: list[str] = [] + if ctx.family == "qwen36": + classes.append("D" if ctx.facts.get("hybrid_experts") else "E") + return classes + if ctx.backend == "sycl": + return ["G"] + if ctx.facts.get("resident_ram") or (ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 12): + classes.append("A") + classes.append("B" if ctx.vram_mib >= 24000 else "C") + if ctx.hybrid_cpu: + classes.append("F") + return classes + + +# --------------------------------------------------------------------------- rule checks + +def _as_number(value: Any) -> float | None: + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _prefill_below_auto(value: Any) -> bool: + n = _as_number(value) + return n is not None and not str(value).startswith("auto") + + +def check_setting(args: dict[str, Any], env: dict[str, str | None], ctx: Context) -> list[str]: + """Reasons (plain words) a setting must not be applied; an empty list means it is inside the rules. + + ``args`` maps flag -> value (True for a present boolean flag); ``env`` maps name -> value.""" + problems: list[str] = [] + ctx_tokens = ctx.context_tokens + default_workers = ctx.facts.get("workers") + for rule in NEVER: + fams = rule.get("families") + if fams and ctx.family not in fams: + continue + if any(not condition_holds(w, ctx) for w in rule.get("when", ())): + continue + if "env" in rule: + if rule["env"] in env and env[rule["env"]] not in (None, "", "0") and \ + ("value" not in rule or env[rule["env"]] == rule["value"]): + problems.append(f"{rule['env']}: {rule['reason']}") + continue + flag = rule["flag"] + if flag not in args or args[flag] is None: + continue + value = args[flag] + test = rule.get("test") + hit = False + if "values" in rule: + hit = str(value) in rule["values"] + elif test is None: + hit = True + elif test == "above_engine_default": + n = _as_number(value) + hit = n is not None and default_workers is not None and n > float(default_workers) + elif test == "at_least": + n = _as_number(value) + hit = n is not None and n >= rule["limit"] + elif test == "at_most": + n = _as_number(value) + hit = n is not None and n <= rule["limit"] and flag == "--spec" + elif test == "below_context": + n = _as_number(value) + hit = n is not None and n < ctx_tokens + elif test == "fixed_below_auto": + hit = _prefill_below_auto(value) and ctx.family == "flash-next" + if ctx.family == "qwen36": + n = _as_number(value) + hit = n is not None and n <= 512 + elif test == "without_prefill": + hit = "--prefill" not in args and "--prefill" not in _flags_of(ctx.base_args) + elif test == "zero_or_small": + n = _as_number(value) + hit = n is not None and str(value) != "auto" and n < 0.5 * float(ctx.facts.get("auto_slots") or 0 or 1) + elif test == "mtp_extreme": + n = _as_number(value) + hit = n is not None and (n == 0 or n >= 4) + if hit: + problems.append(f"{flag} {value}: {rule['reason']}") + for flag, value in args.items(): + bound = BOUNDS.get(flag) + if not bound or value is None or value is True: + continue + if bound.get("numeric_only") and _as_number(value) is None: + continue + if "choices" in bound and value not in bound["choices"] and str(value) not in [str(c) for c in bound["choices"]]: + problems.append(f"{flag} {value}: outside the safe values {list(bound['choices'])}") + n = _as_number(value) + if n is not None and "min" in bound and n < bound["min"]: + problems.append(f"{flag} {value}: below the safe minimum {bound['min']}") + if n is not None and "max" in bound and n > bound["max"]: + problems.append(f"{flag} {value}: above the safe maximum {bound['max']}") + return problems + + +def _flags_of(argv: Sequence[str]) -> set[str]: + return {a for a in argv if isinstance(a, str) and a.startswith("--")} + + +def answer_class(args: dict[str, Any], env: dict[str, str | None] | None = None, + base_args: dict[str, Any] | None = None) -> tuple[str, list[str]]: + """The worst answer class among the settings that differ from the base, and which flags cause it.""" + worst, fields = "exact", [] + base_args = base_args or {} + for flag, value in args.items(): + if base_args.get(flag) == value: + continue + cls = ANSWER_OF_FLAG.get(flag) + if cls: + fields.append(flag) + if ANSWER_ORDER.index(cls) > ANSWER_ORDER.index(worst): + worst = cls + return worst, fields + + +def allowed(answer: str, ctx: Context) -> bool: + """May an arm of this answer class be picked on its own? Exact always; the rest need the user's tick; quality never.""" + return answer == "exact" or (answer == "placement" and ctx.allow_placement) or \ + (answer == "nonrepeatable" and ctx.allow_nonrepeatable) + + +# --------------------------------------------------------------------------- planning + +def dynamic_value(spec: str, ctx: Context) -> Any: + f = ctx.facts + workers = f.get("workers") + if spec == "workers": + return int(workers) if workers else None + if spec.startswith("workers-") and workers: + value = int(workers) - int(spec[len("workers-"):]) + floor = max(2, int(workers) // 4 + 1) # never below N/4 (6.6) + return value if value >= floor else None + return None + + +@dataclass +class PlannedArm: + arm: Arm + args: dict[str, Any] + env: dict[str, str | None] + + +def plan_arms(ctx: Context, *, mode: str = "quick", history_bad: set[str] | None = None) -> tuple[list[PlannedArm], list[dict[str, str]]]: + """The candidates for this machine in the order they are tried, and the ones left out with the reason. + + Order: the machine's classes in order (6.2), each class's arms in the table order. Quick keeps the first ones the + time budget allows; thorough keeps all of them, flat knobs last.""" + classes = machine_classes(ctx) + base_flags = _flags_of(ctx.base_args) + chosen: list[PlannedArm] = [] + skipped: list[dict[str, str]] = [] + seen: set[str] = set() + for cls in classes: + for arm in ARMS: + if cls not in arm.classes or arm.id in seen: + continue + seen.add(arm.id) + + def skip(reason: str) -> None: + skipped.append({"id": arm.id, "label": arm.label, "reason": reason}) + + if ctx.family not in arm.families: + continue + if ctx.backend not in arm.backends: + skip(f"not a {ctx.backend} setting") + continue + if arm.deep_only and mode != "thorough": + skip("only tried in the thorough tune (it was measured as flat)") + continue + if ctx.goal not in arm.goals and ctx.use not in arm.goals: + skip("does not serve what you asked for") + continue + if not allowed(arm.answer, ctx): + skip({"placement": "it can change answers slightly; tick 'allow small answer differences' to try it", + "nonrepeatable": "answers would not repeat run to run; tick 'allow settings that are not repeatable' to try it", + "quality": "it is a quality setting, never chosen automatically"}.get(arm.answer, "not allowed")) + continue + miss = [n for n in arm.needs if not condition_holds(n, ctx)] + if miss: + skip("this PC does not match: " + ", ".join(miss).replace("_", " ")) + continue + args = dict(arm.set_args) + bad = False + for flag, spec in arm.dynamic.items(): + v = dynamic_value(spec, ctx) + if v is None: + skip("the engine's current value could not be read") + bad = True + break + args[flag] = v + if bad: + continue + if ctx.engine_flags is not None: + unknown = [f for f in args if f not in ctx.engine_flags] + if unknown: + skip("this engine does not accept " + ", ".join(unknown)) + continue + problems = check_setting(args, dict(arm.env), ctx) + if problems: + skip("; ".join(problems)) + continue + if all(_current(ctx.base_args, f) == _norm(v) for f, v in args.items()) and not arm.env: + skip("already the current setting") + continue + sig = signature(args, arm.env) + if history_bad and (sig in history_bad or arm.id in history_bad): + skip("did not start on this PC before") + continue + chosen.append(PlannedArm(arm, args, dict(arm.env))) + return chosen, skipped + + +def _norm(value: Any) -> str | None: + return None if value is None else ("" if value is True else str(value)) + + +def _current(argv: Sequence[str], flag: str) -> str | None: + """The value a flag has in an argv list: '' for a bare flag, None when absent.""" + for i, a in enumerate(argv): + if a == flag: + if flag in BOOL_FLAGS or i + 1 >= len(argv) or str(argv[i + 1]).startswith("--"): + return "" + return str(argv[i + 1]) + return None + + +def signature(args: dict[str, Any], env: dict[str, str | None] | None = None) -> str: + parts = [f"{k}={_norm(v)}" for k, v in sorted(args.items())] + [f"{k}={v}" for k, v in sorted((env or {}).items())] + return "|".join(parts) + + +def apply_to_argv(argv: Sequence[str], args: dict[str, Any]) -> list[str]: + """The user's argv with the candidate's settings put on top (Rule 3: a boolean is present or absent).""" + out = list(argv) + for flag, value in args.items(): + i = 0 + while i < len(out): + if out[i] == flag: + n = 1 if (flag in BOOL_FLAGS or i + 1 >= len(out) or str(out[i + 1]).startswith("--")) else 2 + del out[i:i + n] + else: + i += 1 + if value is None or value is False: + continue + if value is True or flag in BOOL_FLAGS: + out.append(flag) + else: + out.extend([flag, str(value)]) + return out + + +def apply_to_env(env: dict[str, str], changes: dict[str, str | None]) -> dict[str, str]: + out = dict(env) + for k, v in changes.items(): + if v is None: + out.pop(k, None) + else: + out[k] = str(v) + return out diff --git a/strata_control/tune_machine.py b/strata_control/tune_machine.py new file mode 100644 index 00000000..7410f444 --- /dev/null +++ b/strata_control/tune_machine.py @@ -0,0 +1,313 @@ +"""What the tuner needs to know about this PC, read without ever raising. + +Every probe here is optional: a missing tool or an unreadable file gives ``None`` (or an empty list), never an +exception, because the tuner must still run on a machine whose sensors it cannot read, only with fewer guards. +A guard that cannot read its input says so in the report ("the free graphics memory could not be read"); it does not +pretend the memory was free. + +Stdlib only, like the rest of Strata Control. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import re +import shutil +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +MIB = 1024 * 1024 + + +# --------------------------------------------------------------------------- memory + +def memory() -> dict[str, int | None]: + """System RAM in MiB: ``total`` and ``available`` (what a new process could use without swapping).""" + try: + if os.name == "nt": + import ctypes + + class _Status(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + + status = _Status() + status.dwLength = ctypes.sizeof(_Status) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)): + return {"total_mib": int(status.ullTotalPhys // MIB), "available_mib": int(status.ullAvailPhys // MIB)} + elif sys.platform == "darwin": + total = int(subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, + timeout=5).stdout.strip()) // MIB + vm = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=5).stdout + page = int(re.search(r"page size of (\d+)", vm).group(1)) if re.search(r"page size of (\d+)", vm) else 16384 + pages = 0 + for key in ("Pages free", "Pages inactive", "Pages speculative"): + m = re.search(rf"{key}:\s+(\d+)", vm) + pages += int(m.group(1)) if m else 0 + return {"total_mib": total, "available_mib": pages * page // MIB} + else: + info: dict[str, int] = {} + for line in Path("/proc/meminfo").read_text().splitlines(): + key, _, rest = line.partition(":") + info[key] = int(rest.split()[0]) + return {"total_mib": info["MemTotal"] // 1024, "available_mib": info["MemAvailable"] // 1024} + except Exception: # noqa: BLE001 - a probe must not raise + pass + return {"total_mib": None, "available_mib": None} + + +# --------------------------------------------------------------------------- graphics cards + +def _run(argv: list[str], timeout: float = 10.0) -> str | None: + try: + return subprocess.run(argv, capture_output=True, text=True, timeout=timeout).stdout + except Exception: # noqa: BLE001 + return None + + +def gpus() -> list[dict[str, Any]]: + """Graphics cards with their memory: ``name``, ``vram_total_mib``, ``vram_used_mib`` (None when unreadable), + ``driver``, ``vendor``. NVIDIA through nvidia-smi, AMD through the kernel's sysfs files; Intel and Apple report + their name only where it is known, and leave the memory unreadable.""" + out: list[dict[str, Any]] = [] + smi = shutil.which("nvidia-smi") + if smi: + text = _run([smi, "--query-gpu=index,name,memory.total,memory.used,driver_version", + "--format=csv,noheader,nounits"]) + for line in (text or "").splitlines(): + parts = [p.strip() for p in line.split(",")] + if len(parts) >= 5: + try: + out.append({"vendor": "nvidia", "index": int(parts[0]), "name": parts[1], + "vram_total_mib": int(float(parts[2])), "vram_used_mib": int(float(parts[3])), + "driver": parts[4]}) + except ValueError: + continue + if not out and sys.platform.startswith("linux"): + base = Path("/sys/class/drm") + if base.is_dir(): + index = 0 + for card in sorted(base.glob("card[0-9]*")): + dev = card / "device" + try: + vendor = (dev / "vendor").read_text().strip() + total = int((dev / "mem_info_vram_total").read_text()) // MIB + used = int((dev / "mem_info_vram_used").read_text()) // MIB + except (OSError, ValueError): + continue + if vendor != "0x1002": + continue + name = None + try: + name = (dev / "product_name").read_text().strip() + except OSError: + pass + out.append({"vendor": "amd", "index": index, "name": name or f"AMD GPU {index}", + "vram_total_mib": total, "vram_used_mib": used, "driver": None}) + index += 1 + return out + + +def gpu_used_mib(indexes: list[int] | None = None) -> int | None: + """Graphics memory in use now, summed over the cards the model runs on (all when ``indexes`` is None).""" + cards = gpus() + if not cards: + return None + vals = [c["vram_used_mib"] for c in cards if c.get("vram_used_mib") is not None + and (not indexes or c["index"] in indexes)] + return sum(vals) if vals else None + + +# --------------------------------------------------------------------------- processor + +def cpu() -> dict[str, Any]: + """``model``, ``logical`` and ``physical`` thread counts, and ``hybrid`` (performance plus efficiency cores).""" + logical = os.cpu_count() or 1 + model = platform.processor() or platform.machine() + physical: int | None = None + hybrid = False + try: + if sys.platform.startswith("linux"): + text = Path("/proc/cpuinfo").read_text() + m = re.search(r"model name\s*:\s*(.+)", text) + if m: + model = m.group(1).strip() + cores = set() + for block in text.split("\n\n"): + pid = re.search(r"physical id\s*:\s*(\d+)", block) + cid = re.search(r"core id\s*:\s*(\d+)", block) + if pid and cid: + cores.add((pid.group(1), cid.group(1))) + physical = len(cores) or None + hybrid = Path("/sys/devices/cpu_core").exists() and Path("/sys/devices/cpu_atom").exists() + elif os.name == "nt": + try: + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as k: + model = str(winreg.QueryValueEx(k, "ProcessorNameString")[0]).strip() or model + except OSError: + pass + physical, hybrid = _windows_cores() + elif sys.platform == "darwin": + model = (_run(["sysctl", "-n", "machdep.cpu.brand_string"]) or model).strip() + phys = _run(["sysctl", "-n", "hw.physicalcpu"]) + physical = int(phys) if phys and phys.strip().isdigit() else None + hybrid = False + except Exception: # noqa: BLE001 + pass + return {"model": model, "logical": logical, "physical": physical, "hybrid": hybrid} + + +def _windows_cores() -> tuple[int | None, bool]: + """(physical cores, hybrid) from GetLogicalProcessorInformationEx: hybrid when the cores have more than one + efficiency class (performance and efficiency cores).""" + try: + import ctypes + from ctypes import wintypes + + k = ctypes.windll.kernel32 + k.GetLogicalProcessorInformationEx.argtypes = [wintypes.DWORD, ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)] + size = wintypes.DWORD(0) + k.GetLogicalProcessorInformationEx(0, None, ctypes.byref(size)) # 0 = RelationProcessorCore + buf = ctypes.create_string_buffer(size.value) + if not k.GetLogicalProcessorInformationEx(0, buf, ctypes.byref(size)): + return None, False + raw = bytes(buf.raw[:size.value]) + classes, cores, offset = set(), 0, 0 + while offset + 10 <= len(raw): + rel_size = int.from_bytes(raw[offset + 4:offset + 8], "little") + if rel_size <= 0: + break + classes.add(raw[offset + 9]) # PROCESSOR_RELATIONSHIP.EfficiencyClass + cores += 1 + offset += rel_size + return (cores or None), len(classes) > 1 + except Exception: # noqa: BLE001 + return None, False + + +_last_cpu: tuple[float, int, int] | None = None + + +def cpu_busy_percent(sample_s: float = 1.0) -> float | None: + """How busy the whole CPU was over the last ``sample_s`` seconds (0-100), or None when unreadable.""" + def read() -> tuple[int, int] | None: + try: + if sys.platform.startswith("linux"): + f = Path("/proc/stat").read_text().splitlines()[0].split()[1:] + v = [int(x) for x in f] + idle = v[3] + (v[4] if len(v) > 4 else 0) + return sum(v), idle + if os.name == "nt": + import ctypes + from ctypes import wintypes + idle, kern, user = wintypes.FILETIME(), wintypes.FILETIME(), wintypes.FILETIME() + if not ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)): + return None + q = lambda t: (t.dwHighDateTime << 32) | t.dwLowDateTime # noqa: E731 + return q(kern) + q(user), q(idle) + except Exception: # noqa: BLE001 + return None + return None + + a = read() + if a is None: + return None + time.sleep(sample_s) + b = read() + if b is None or b[0] == a[0]: + return None + return round(100.0 * (1.0 - (b[1] - a[1]) / (b[0] - a[0])), 1) + + +def other_engines(own_pids: set[int] | None = None) -> list[str]: + """Command lines of Strata engines that this tune did not start (a second engine changes every number).""" + own = own_pids or set() + found: list[str] = [] + try: + if os.name == "nt": + text = _run(["powershell", "-NoProfile", "-Command", + "Get-CimInstance Win32_Process -Filter \"Name='strata.exe'\" | " + "Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"], timeout=20) + if text and text.strip(): + data = json.loads(text) + for row in data if isinstance(data, list) else [data]: + if int(row.get("ProcessId", 0)) not in own and "--serve" in (row.get("CommandLine") or ""): + found.append((row.get("CommandLine") or "")[:160]) + else: + text = _run(["ps", "-eo", "pid=,args="]) or "" + for line in text.splitlines(): + pid_s, _, args = line.strip().partition(" ") + if pid_s.isdigit() and int(pid_s) not in own and re.search(r"(^|/)strata(\s|$)", args.split(" --serve")[0]) \ + and " --serve" in args: + found.append(args[:160]) + except Exception: # noqa: BLE001 + pass + return found + + +# --------------------------------------------------------------------------- the key a preset is valid for + +def _round_down(value: int | None, step: int) -> int | None: + return None if value is None else value - value % step + + +def hardware_identity(*, pcie: str | None = None) -> dict[str, Any]: + """Hardware in two parts. ``hard``: a change means the stored settings may not even start (graphics card, + memory sizes, processor). ``soft``: a change deserves a short re-check (graphics driver).""" + cards = gpus() + mem = memory() + c = cpu() + return { + "hard": { + "gpus": [{"name": g["name"], "vram_mib": g["vram_total_mib"]} for g in cards], + "cpu": c["model"], "logical": c["logical"], "physical": c["physical"], "hybrid": c["hybrid"], + "ram_gib": _round_down((mem["total_mib"] or 0) // 1024 or None, 2), + "pcie": pcie, "os": platform.system(), + }, + "soft": {"driver": sorted({g["driver"] for g in cards if g.get("driver")}), "os_release": platform.release()}, + } + + +def engine_identity(exe: str | os.PathLike[str]) -> dict[str, Any]: + """The engine build: version, backend, build id and executable SHA-256 from its manifest, plus the manifest's + ``tuning_epoch`` (bumped when a kernel or default change can move a tuning result).""" + folder = Path(exe).resolve().parent + manifest: dict[str, Any] = {} + try: + manifest = json.loads((folder / "engine-component.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + pass + sha = None + for entry in manifest.get("files") or []: + if entry.get("path") == manifest.get("entrypoint", Path(exe).name): + sha = entry.get("sha256") + return {"version": manifest.get("version"), "backend": manifest.get("backend"), + "build_id": manifest.get("build_id"), "sha256": sha, + "tuning_epoch": int(manifest.get("tuning_epoch") or 0), "path": str(exe)} + + +def model_identity(files: list[str | os.PathLike[str]]) -> dict[str, Any]: + """The model file(s): size and a digest of the head, middle and tail of the first shard (the whole file would + mean reading tens of gigabytes before every tune).""" + from strata_control import tune_history + out: list[dict[str, Any]] = [] + for f in files[:2]: + ident = tune_history.file_identity(Path(f)) + out.append({"name": Path(f).name, "bytes": ident.get("bytes"), "digest": ident.get("digest"), + "method": ident.get("method")}) + first = out[0] if out else {} + return {"files": out, "sha256_shard1": first.get("digest"), "bytes": first.get("bytes")} + + +def stable_hash(obj: Any) -> str: + return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str).encode()).hexdigest()[:16] diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py new file mode 100644 index 00000000..6c1759ac --- /dev/null +++ b/strata_control/tune_session.py @@ -0,0 +1,478 @@ +"""Running one engine configuration and measuring it, for the tuner. + +A *session* is what the tuner needs from the outside world: start an engine with these arguments and environment, run the +fixed request set, report numbers, stop. The real session (`WorkerSession`) starts Strata's own worker (``serve.server``) +on a **copy** of the user's run configuration and talks to it over HTTP, so the engine, the queueing and the prompt +handling are exactly the ones the user gets. The numbers come from the engine's own clock (the ``timings`` block of the +reply), not from this process's stopwatch. The stub session in the tests implements the same two methods. + +Never invents a number: an engine that does not start, answers nothing or answers too little raises `StartFailed` or +returns a result whose ``status`` says why, and the tuner records that as the candidate's result. +""" + +from __future__ import annotations + +import contextlib +import json +import os +import random +import re +import secrets +import socket +import statistics +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Iterator, Protocol + +from strata_control import tune_machine + +# --------------------------------------------------------------------------- the contract + + +class StartFailed(RuntimeError): + """The engine did not come up. ``status``: FAIL_BOOT | OOM | UNSUPPORTED | TIMEOUT.""" + + def __init__(self, status: str, reason: str) -> None: + super().__init__(reason) + self.status = status + self.reason = reason + + +@dataclass +class RequestSet: + """The fixed work every run does, so two configurations are compared on the same requests.""" + + warmups: int = 1 + decodes: int = 3 + decode_tokens: int = 200 + pp_tokens: int = 4096 + long_tokens: int = 0 # 0 = no long prompt + + +@dataclass +class RunResult: + status: str = "PASS" # PASS | FAIL_BOOT | OOM | UNSUPPORTED | TIMEOUT | NO_TOKENS + reason: str = "" + load_s: float | None = None + decode_tok_s: float | None = None # median of the measured decodes + decode_runs: list[float] = field(default_factory=list) + pp_tok_s: float | None = None # the warm prompt (the second one; the first is cold) + pp_cold_tok_s: float | None = None + ttft_s: float | None = None + pp_long_tok_s: float | None = None + rss_peak_mib: float | None = None + vram_used_mib: float | None = None # this run's total graphics memory in use (all cards, absolute) + vram_added_mib: float | None = None # ... minus what was in use before the engine started + min_avail_mib: float | None = None # lowest free system RAM seen while the engine ran + facts: dict[str, Any] = field(default_factory=dict) + wall_s: float = 0.0 + + def to_dict(self) -> dict[str, Any]: + return dict(self.__dict__) + + +class Engine(Protocol): + facts: dict[str, Any] + + def measure(self, spec: RequestSet) -> RunResult: ... + + def decode_once(self, tune: dict[str, Any] | None = None, tokens: int = 200) -> float | None: ... + + +class Session(Protocol): + def engine(self, args: list[str], env: dict[str, str | None]) -> contextlib.AbstractContextManager[Engine]: ... + + def system(self) -> dict[str, Any]: ... + + +# --------------------------------------------------------------------------- the engine log + +_FACTS = [ + ("slots", re.compile(r"expert cache (\d+) slots"), int), + ("workers", re.compile(r"(\d+) (?:expert-)?pool workers"), int), + ("cpu_threads", re.compile(r"(\d+) CPU threads"), int), + ("pcie_gbs", re.compile(r"PCIe probe: ([\d.]+) GB/s"), float), + ("pcie_frac", re.compile(r"-> pcie_frac ([\d.]+)"), float), + ("chunk", re.compile(r"prompt chunk auto: (\d+) tokens"), int), + ("avail_gib", re.compile(r"available ([\d.]+) GiB \(MemAvailable"), float), + ("loaded_gib", re.compile(r"loaded ([\d.]+) GiB at"), float), +] + + +def parse_facts(text: str) -> dict[str, Any]: + """What the engine's own log says about the setup it chose (the last value of each fact wins).""" + facts: dict[str, Any] = {} + for key, rx, cast in _FACTS: + found = rx.findall(text) + if found: + try: + facts[key] = cast(found[-1]) + except ValueError: + pass + if "workers" not in facts and "cpu_threads" in facts: + facts["workers"] = facts["cpu_threads"] + low = text.lower() + facts["resident_ram"] = bool(re.search(r"resident[- ](?:ram|experts)|low-ram mode|resident ram", low)) + facts["hybrid_experts"] = "hybrid experts" in low or "hybrid:" in low + facts["unknown_argument"] = bool(re.search(r"unknown argument|unrecognized (?:argument|option)", low)) + return facts + + +def failure_kind(text: str, returncode: int | None) -> tuple[str, str]: + """Classify an engine that ended before it was ready: (status, one plain line).""" + low = text.lower() + lines = [ln.strip() for ln in text.splitlines() if re.search( + r"unknown argument|unrecognized|invalid value|out of memory|memory guard|cannot|failed|error|refus|killed", ln, re.I)] + reason = " | ".join(lines[:3])[:300] + if re.search(r"unknown argument|unrecognized (argument|option)", low): + return "UNSUPPORTED", reason or "the engine does not accept one of the settings" + if re.search(r"out of memory|memory guard|cannot allocate|std::bad_alloc|oom", low) or returncode in (-9, 137, 3221226505): + return "OOM", reason or "the engine ran out of memory" + return "FAIL_BOOT", reason or f"the engine stopped while starting (exit {returncode})" + + +# --------------------------------------------------------------------------- prompts + +_SENTENCES = ( + "The harbour town woke slowly, with fishing boats knocking against the wooden piers.", + "A small team measured how long each step of the process took and wrote the numbers in a notebook.", + "Rain fell on the old railway station while a clerk sorted letters by hand.", + "The recipe asked for two cups of flour, a pinch of salt and patience.", + "In the library, a quiet reader turned pages while the clock in the hall struck three.", + "Engineers compared the two bridges and noted how each handled wind and weight.", + "The orchard produced more apples than the village could eat, so the surplus went to the city market.", + "She packed a map, a flask of tea and a spare pair of boots for the long walk north.", + "Each morning the baker lit the oven before dawn and left the shop door unlocked for the milkman.", + "A careful gardener keeps a record of when each seed is planted and when it first sprouts.", + "The museum's new wing displayed instruments that once guided ships across open water.", + "Traffic slowed near the tunnel entrance, and the radio suggested taking the coast road instead.", + "Two neighbours argued kindly over whose tomato plants had grown taller that summer.", + "The orchestra tuned together, a single note spreading through the hall until the conductor raised a hand.", + "He wrote down every question he had about the machine before opening its case.", + "A river of lanterns floated past the bridge as the festival reached its final evening.", +) + + +def make_prompt(tokens: int, salt: str, chars_per_token: float = 4.4) -> str: + """A prompt of about ``tokens`` tokens that no earlier run has seen: its first line is the salt, so a cached prefix is + never reused, and the rest is shuffled prose.""" + rng = random.Random(salt) + target = int(tokens * chars_per_token) + parts = [f"Reference {salt}."] + size = len(parts[0]) + while size < target: + s = rng.choice(_SENTENCES) + parts.append(s) + size += len(s) + 1 + parts.append("Now answer in one short sentence: what is the main subject of the text above?") + return " ".join(parts) + + +DECODE_PROMPTS = ( + "Write a long, detailed story about a lighthouse keeper who finds a message in a bottle. Keep going without stopping.", + "Explain step by step how a bicycle works, covering the frame, wheels, gears, chain and brakes in depth.", +) + + +# --------------------------------------------------------------------------- a flock for the box locks + +class FileLock: + """An exclusive advisory lock on a file, held around each engine run (the lent boxes' /data/gpu.lock rule).""" + + def __init__(self, path: str | os.PathLike[str], wait_s: float = 5400.0, log: Callable[[str], None] = lambda s: None) -> None: + self.path = str(path) + self.wait_s = wait_s + self.log = log + self._fh = None + + def __enter__(self) -> "FileLock": + Path(self.path).parent.mkdir(parents=True, exist_ok=True) + self._fh = open(self.path, "a+") + deadline = time.time() + self.wait_s + told = False + while True: + try: + if os.name == "nt": + import msvcrt + self._fh.seek(0) + msvcrt.locking(self._fh.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return self + except OSError: + if time.time() > deadline: + self._fh.close() + raise StartFailed("TIMEOUT", f"the lock {self.path} was not free within {int(self.wait_s)} s") + if not told: + self.log(f"waiting for the lock {self.path}") + told = True + time.sleep(2.0) + + def __exit__(self, *exc: object) -> None: + try: + if os.name == "nt": + import msvcrt + self._fh.seek(0) + msvcrt.locking(self._fh.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN) + except OSError: + pass + finally: + if self._fh: + self._fh.close() + + +# --------------------------------------------------------------------------- the real session + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class WorkerEngine: + """One running worker and the requests that measure it.""" + + def __init__(self, session: "WorkerSession", proc: subprocess.Popen, port: int, key: str, log_files: list[Path], + load_s: float, vram_before: int | None, log: Callable[[str], None]) -> None: + self.s = session + self.proc = proc + self.port = port + self.key = key + self.log_files = log_files + self.load_s = load_s + self.vram_before = vram_before + self.log = log + self.model = "strata-local" + self.min_avail: float | None = None + self.facts: dict[str, Any] = parse_facts(self.log_text()) + self.salt_n = 0 + self._model_id() + + # ---- helpers + def log_text(self) -> str: + out = [] + for f in self.log_files: + try: + out.append(f.read_text(encoding="utf-8", errors="replace")) + except OSError: + pass + return "\n".join(out) + + def _model_id(self) -> None: + try: + req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/models", headers=self._h()) + with urllib.request.urlopen(req, timeout=10) as r: + data = json.loads(r.read()) + self.model = ((data.get("data") or [{}])[0]).get("id") or self.model + except Exception: # noqa: BLE001 + pass + + def _h(self) -> dict[str, str]: + return {"content-type": "application/json", "authorization": f"Bearer {self.key}"} + + def _sample_mem(self) -> None: + a = tune_machine.memory().get("available_mib") + if a is not None: + self.min_avail = a if self.min_avail is None else min(self.min_avail, a) + + def chat(self, prompt: str, max_tokens: int, tune: dict[str, Any] | None = None, timeout: float = 1800.0) -> dict[str, Any]: + body: dict[str, Any] = {"model": self.model, "stream": False, "max_tokens": max_tokens, "temperature": 0.0, + "messages": [{"role": "user", "content": prompt}], "strata_checkpoint": False} + if tune: + body["strata_tune"] = tune + req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", + data=json.dumps(body).encode(), headers=self._h(), method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + data = json.loads(r.read()) + except urllib.error.HTTPError as e: + raise StartFailed("NO_TOKENS", f"the worker refused the request ({e.code}): {e.read()[:200]!r}") from None + except (urllib.error.URLError, OSError, ValueError) as e: + code = self.proc.poll() + status, why = failure_kind(self.log_text()[-4000:], code) if code is not None else ("TIMEOUT", str(e)) + raise StartFailed(status, f"the engine did not answer: {why}") from None + self._sample_mem() + return data + + # ---- measurements + def decode_once(self, tune: dict[str, Any] | None = None, tokens: int = 200) -> float | None: + for prompt in DECODE_PROMPTS: + data = self.chat(prompt, tokens, tune) + t = data.get("timings") or {} + n, rate = t.get("predicted_n"), t.get("predicted_per_second") + if n and rate and n >= max(32, tokens // 2): + return float(rate) + return None + + def prompt_once(self, tokens: int) -> dict[str, float | None]: + self.salt_n += 1 + salt = secrets.token_hex(6) + text = make_prompt(tokens, salt, self.s.chars_per_token) + data = self.chat(text, 8) + t = data.get("timings") or {} + usage = data.get("usage") or {} + pt = usage.get("prompt_tokens") + if isinstance(pt, int) and pt > 64 and not self.s.calibrated: + self.s.chars_per_token = max(2.0, min(8.0, self.s.chars_per_token * tokens / pt)) + self.s.calibrated = True + rate = t.get("prompt_per_second") + # a prompt that was partly cached is not a prompt-speed measurement + if t.get("cache_n") and t.get("prompt_n") and t["cache_n"] > 0.1 * (t["prompt_n"] + t["cache_n"]): + rate = None + ms = t.get("prompt_ms") + return {"rate": float(rate) if rate else None, "ttft_s": float(ms) / 1000.0 if ms else None, + "tokens": pt if isinstance(pt, int) else None} + + def measure(self, spec: RequestSet) -> RunResult: + t0 = time.time() + res = RunResult(load_s=self.load_s, facts=dict(self.facts)) + for _ in range(spec.warmups): + self.decode_once(None, 64) + runs: list[float] = [] + for _ in range(spec.decodes): + r = self.decode_once(None, spec.decode_tokens) + if r: + runs.append(r) + res.decode_runs = [round(x, 3) for x in runs] + if not runs: + res.status, res.reason = "NO_TOKENS", "the engine produced no measurable decode" + else: + res.decode_tok_s = round(statistics.median(runs), 3) + if spec.pp_tokens: + cold = self.prompt_once(spec.pp_tokens) + warm = self.prompt_once(spec.pp_tokens) + res.pp_cold_tok_s = cold["rate"] + res.pp_tok_s, res.ttft_s = warm["rate"], warm["ttft_s"] + if spec.long_tokens: + res.pp_long_tok_s = self.prompt_once(spec.long_tokens)["rate"] + res.rss_peak_mib = tune_engine_peak(self.proc.pid) + used = tune_machine.gpu_used_mib() + if used is not None: + res.vram_used_mib = used + if self.vram_before is not None: + res.vram_added_mib = used - self.vram_before + res.min_avail_mib = self.min_avail + res.facts = dict(parse_facts(self.log_text())) + res.wall_s = round(time.time() - t0, 1) + return res + + +def tune_engine_peak(pid: int) -> float | None: + try: + from strata_control.tune_engine import process_tree_peak_mib + return process_tree_peak_mib(pid) + except Exception: # noqa: BLE001 + return None + + +class WorkerSession: + """Starts ``serve.server`` on a copy of the run configuration for each configuration the tuner asks for.""" + + def __init__(self, *, base_config: dict[str, Any], python: str | os.PathLike[str] | None = None, + serve_dir: str | os.PathLike[str], workdir: str | os.PathLike[str] | None = None, + boot_timeout_s: float = 900.0, lock: Callable[[], contextlib.AbstractContextManager] | None = None, + log: Callable[[str], None] = lambda s: None, extra_env: dict[str, str] | None = None) -> None: + self.base = json.loads(json.dumps(base_config)) + self.python = str(python or sys.executable) + self.serve_dir = Path(serve_dir) + self.workdir = Path(workdir) if workdir else Path(tempfile.mkdtemp(prefix="strata-tune-")) + self.workdir.mkdir(parents=True, exist_ok=True) + self.boot_timeout_s = boot_timeout_s + self.lock = lock + self.log = log + self.extra_env = dict(extra_env or {}) + self.chars_per_token = 4.4 + self.calibrated = False + self.runs = 0 + + def system(self) -> dict[str, Any]: + return {"memory": tune_machine.memory(), "gpus": tune_machine.gpus(), "cpu": tune_machine.cpu()} + + @contextlib.contextmanager + def engine(self, args: list[str], env: dict[str, str | None]) -> Iterator[WorkerEngine]: + with contextlib.ExitStack() as stack: + if self.lock is not None: + stack.enter_context(self.lock()) + self.runs += 1 + n = self.runs + cfg = json.loads(json.dumps(self.base)) + cfg["args"] = list(args) + cenv = dict(cfg.get("env") or {}) + for k, v in env.items(): + if v is None: + cenv.pop(k, None) + else: + cenv[k] = str(v) + cfg["env"] = cenv + key = secrets.token_hex(16) + port = _free_port() + engine_log = self.workdir / f"engine-{n}.log" + worker_log = self.workdir / f"worker-{n}.log" + engine_log.write_text("") + cfg.update({"api_key": key, "port": port, "host": "127.0.0.1", "open_browser": False, "log": str(engine_log)}) + cfg_path = self.workdir / f"run-{n}.json" + cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + spawn_env = dict(os.environ) + spawn_env.update(self.extra_env) + for k, v in env.items(): + if v is None: + spawn_env.pop(k, None) + spawn_env["PYTHONUNBUFFERED"] = "1" + spawn_env["STRATA_NO_PRESET"] = "1" # measure the configuration as given, not a saved tuning on top + before = tune_machine.gpu_used_mib() + wl = open(worker_log, "w") + argv = [self.python, "-m", "serve.server", "--engine", "strata", "--config", str(cfg_path), + "--host", "127.0.0.1", "--port", str(port)] + t0 = time.time() + try: + from serve import lifeline + proc = lifeline.popen(argv, "worker", cwd=str(self.serve_dir), env=spawn_env, stdout=wl, + stderr=subprocess.STDOUT) + except OSError as e: + wl.close() + raise StartFailed("FAIL_BOOT", f"the worker could not be started: {e}") from None + try: + deadline = t0 + self.boot_timeout_s + ready = False + while time.time() < deadline: + if proc.poll() is not None: + text = (engine_log.read_text(errors="replace") if engine_log.exists() else "") + "\n" + \ + worker_log.read_text(errors="replace") + status, why = failure_kind(text, proc.returncode) + raise StartFailed(status, why) + try: + req = urllib.request.Request(f"http://127.0.0.1:{port}/health", + headers={"authorization": f"Bearer {key}"}) + with urllib.request.urlopen(req, timeout=2) as r: + if r.status == 200: + ready = True + break + except (urllib.error.URLError, OSError): + time.sleep(0.5) + if not ready: + raise StartFailed("TIMEOUT", f"the engine was not ready within {int(self.boot_timeout_s)} s") + eng = WorkerEngine(self, proc, port, key, [engine_log, worker_log], time.time() - t0, before, self.log) + yield eng + finally: + try: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=60) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=30) + finally: + wl.close() + # the engine gives its graphics memory back a moment after it exits + time.sleep(3.0) diff --git a/tests/tuning/stub_session.py b/tests/tuning/stub_session.py new file mode 100644 index 00000000..7d954c7e --- /dev/null +++ b/tests/tuning/stub_session.py @@ -0,0 +1,90 @@ +"""A stand-in for `tune_session.WorkerSession`: speeds are computed from the flags it is given, so the tuner's decisions can be +tested without an engine. The numbers mean nothing about any hardware.""" + +from __future__ import annotations + +import contextlib +import random +from typing import Any, Callable + +from strata_control.tune_session import RequestSet, RunResult, StartFailed + + +class StubEngine: + def __init__(self, session: "StubSession", args: list[str], env: dict[str, Any]) -> None: + self.s = session + self.args = args + self.env = env + self.facts = dict(session.facts) + + def _rate(self, tune: dict[str, Any] | None = None) -> float: + base = self.s.model(self.args, self.env, tune) + return base * (1.0 + self.s.rng.gauss(0.0, self.s.noise)) + + def decode_once(self, tune: dict[str, Any] | None = None, tokens: int = 200) -> float | None: + self.s.decodes += 1 + return self._rate(tune) + + def measure(self, spec: RequestSet) -> RunResult: + d = [self._rate() for _ in range(spec.decodes)] + import statistics + pp = self.s.pp(self.args, self.env) * (1.0 + self.s.rng.gauss(0.0, self.s.noise / 3)) + r = RunResult(load_s=20.0, decode_tok_s=statistics.median(d), decode_runs=d, pp_tok_s=pp, pp_cold_tok_s=pp * 0.8, + ttft_s=4096 / pp, rss_peak_mib=self.s.rss(self.args, self.env), vram_used_mib=self.s.vram(self.args), + vram_added_mib=self.s.vram(self.args) - 400, min_avail_mib=self.s.avail - self.s.rss(self.args, self.env), + facts=dict(self.facts), wall_s=self.s.run_s) + return r + + +class StubSession: + def __init__(self, *, model: Callable[..., float], pp: Callable[..., float] | None = None, noise: float = 0.005, + seed: int = 1, facts: dict[str, Any] | None = None, fail: Callable[[list[str], dict], StartFailed | None] | None = None, + rss: Callable[..., float] | None = None, vram: Callable[..., float] | None = None, avail: float = 40000, + run_s: float = 90.0, clock: Any = None) -> None: + self.clock = clock + self.model = model + self.pp = pp or (lambda a, e: 1500.0) + self.noise = noise + self.rng = random.Random(seed) + self.facts = facts or {"workers": 6, "slots": 3000, "resident_ram": False} + self.fail = fail + self.rss = rss or (lambda a, e: 12000.0) + self.vram = vram or (lambda a: 10000.0) + self.avail = avail + self.run_s = run_s + self.runs: list[tuple[list[str], dict]] = [] + self.decodes = 0 + self.mem = {"total_mib": 64000, "available_mib": avail} + + def system(self) -> dict[str, Any]: + return {"memory": dict(self.mem), "gpus": [{"vendor": "nvidia", "index": 0, "name": "Stub GPU", "vram_total_mib": 12000, + "vram_used_mib": 400, "driver": "1"}], "cpu": {"model": "stub", "logical": 12, "hybrid": False}} + + @contextlib.contextmanager + def engine(self, args: list[str], env: dict[str, Any]): + self.runs.append((list(args), dict(env))) + if self.clock is not None: + self.clock.t += self.run_s + if self.fail: + err = self.fail(args, env) + if err: + raise err + yield StubEngine(self, list(args), dict(env)) + + +def flag(args: list[str], name: str) -> str | None: + for i, a in enumerate(args): + if a == name: + return args[i + 1] if i + 1 < len(args) and not str(args[i + 1]).startswith("--") else "" + return None + + +class FakeClock: + def __init__(self) -> None: + self.t = 0.0 + + def __call__(self) -> float: + return self.t + + def sleep(self, s: float) -> None: + self.t += s diff --git a/tests/tuning/test_autotune.py b/tests/tuning/test_autotune.py new file mode 100644 index 00000000..1e95d304 --- /dev/null +++ b/tests/tuning/test_autotune.py @@ -0,0 +1,332 @@ +"""The auto-tuner's decisions, tested with a stub engine whose speed is computed from the flags it is given.""" + +from __future__ import annotations + +import threading +import unittest + +from strata_control import autotune, tune_knobs +from strata_control.tune_session import StartFailed + +from tests.tuning.stub_session import FakeClock, StubSession, flag + +BASE = ["--pack", "P", "--native", "m.gguf", "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", + "--spec-min-p", "0.5", "--mtp", "D", "--max-context", "131072", "--kv", "int8", "--kv-resident", "32768", + "--vram-reserve-mib", "1536"] + + +def make_ctx(**kw): + ctx = tune_knobs.Context(backend="cuda", family="flash-next", gpu_count=1, vram_mib=12000, ram_gib=64, model_gib=60.0, + context_tokens=131072, base_args=list(BASE), logical_threads=12, **kw) + ctx.facts = {"workers": 6, "slots": 3000} + return ctx + + +def speed_with(gains: dict[str, float], base=60.0): + """tok/s as a function of the flags: each (flag, value) in `gains` multiplies the speed.""" + def model(args, env, tune=None): + v = base + for (f, val), g in gains.items(): + if f.startswith("STRATA_"): + if env.get(f) == val: + v *= g + elif flag(args, f) == val: + v *= g + if tune: + for k, g in (gains.get(("tune", None)) or {}).items() if False else []: + pass + return v + return model + + +def run_tuner(model, *, opts=None, ctx=None, clock=None, session_kw=None, cancel=None, progress=None, **kw): + clock = clock or FakeClock() + session = StubSession(model=model, clock=clock, **(session_kw or {})) + t = autotune.Tuner(session, BASE, {}, ctx or make_ctx(), opts or autotune.Options(), clock=clock, sleep=clock.sleep, + system=session.system, total_ram_mib=64000, total_vram_mib=12000, quiet=lambda: None, + cancel=cancel, progress=progress, **kw) + return t, session, t.run() + + +class RulesTest(unittest.TestCase): + def test_never_list(self): + ctx = make_ctx(arch="gfx1201") + bad = [({"--expert-cache": 0}, {}), ({"--kv-resident": 20480}, {}), ({"--pcie-frac": 0.75}, {}), + ({"--spec": 6}, {}), ({"--spec": 2}, {}), ({"--lookup-chain": 4}, {}), ({"--adapt-every": 100000}, {}), + ({"--prefill": 512}, {}), ({"--ple-io": "ram"}, {}), ({}, {"STRATA_SH_STREAM": "1"}), + ({}, {"STRATA_RDNA2_SGEMM": "all"}), ({}, {"STRATA_HIP_WMMA": "1"}), ({"--pool-workers": 8}, {})] + for args, env in bad: + self.assertTrue(tune_knobs.check_setting(args, env, ctx), (args, env)) + ok = [({"--spec": 3}, {}), ({"--host-core": "last"}, {}), ({"--pool-workers": 4}, {}), ({"--prefill": "auto:32768"}, {}), + ({"--adapt-every": 1, "--adapt-swaps": 80, "--adapt-decay": 0.97}, {}), ({"--pcie-frac": 0.2}, {})] + for args, env in ok: + self.assertEqual(tune_knobs.check_setting(args, env, ctx), [], (args, env)) + + def test_hybrid_cpu_affinity_never(self): + ctx = make_ctx() + ctx.hybrid_cpu = True + self.assertTrue(tune_knobs.check_setting({"--pool-affinity": "auto"}, {}, ctx)) + ctx.hybrid_cpu = False + self.assertEqual(tune_knobs.check_setting({"--pool-affinity": "auto"}, {}, ctx), []) + + def test_boolean_flags_are_present_or_absent(self): + self.assertEqual(tune_knobs.apply_to_argv(["--a", "1"], {"--kv-grow": True}), ["--a", "1", "--kv-grow"]) + self.assertEqual(tune_knobs.apply_to_argv(["--kv-grow", "--a", "1"], {"--kv-grow": None}), ["--a", "1"]) + self.assertNotIn("0", tune_knobs.apply_to_argv(["--kv-grow"], {"--kv-grow": False})) + + def test_candidates_are_single_knob_changes_of_the_users_config(self): + ctx = make_ctx(allow_placement=True) + arms, skipped = tune_knobs.plan_arms(ctx, mode="thorough") + self.assertTrue(arms) + for p in arms: + argv = tune_knobs.apply_to_argv(BASE, p.args) + # everything the user had that the arm does not name is untouched (Rule 1) + for f in ("--expert-cache", "--kv", "--spec-min-p", "--vram-reserve-mib", "--max-context"): + if f not in p.args: + self.assertEqual(flag(argv, f), flag(BASE, f), (p.arm.id, f)) + self.assertEqual(tune_knobs.check_setting(p.args, p.env, ctx), []) + + def test_answer_changing_arms_need_the_users_tick(self): + ctx = make_ctx() + ids = {p.arm.id for p in tune_knobs.plan_arms(ctx, mode="thorough")[0]} + self.assertNotIn("spec3", ids) + self.assertNotIn("adapt_async", ids) + ctx2 = make_ctx(allow_placement=True) + self.assertIn("spec3", {p.arm.id for p in tune_knobs.plan_arms(ctx2, mode="thorough")[0]}) + ctx3 = make_ctx(allow_nonrepeatable=True) + ctx3.facts = {"workers": 6, "resident_ram": True} + self.assertIn("adapt_async", {p.arm.id for p in tune_knobs.plan_arms(ctx3, mode="thorough")[0]}) + + def test_engine_without_a_flag_drops_the_arm_with_a_reason(self): + ctx = make_ctx() + ctx.engine_flags = ["--spec"] + arms, skipped = tune_knobs.plan_arms(ctx, mode="thorough") + self.assertFalse(any(p.arm.id == "host_core_last" for p in arms)) + self.assertTrue(any("does not accept" in s["reason"] for s in skipped)) + + def test_qwen36_and_sycl_lists(self): + q = make_ctx() + q.family = "qwen36" + q.facts = {"workers": 6, "hybrid_experts": True} + ids = [p.arm.id for p in tune_knobs.plan_arms(q, mode="thorough")[0]] + self.assertIn("q36_workers_explicit", ids) + self.assertNotIn("host_core_last", ids) + s = make_ctx(allow_placement=True) + s.backend = "sycl" + ids = [p.arm.id for p in tune_knobs.plan_arms(s, mode="thorough")[0]] + self.assertEqual(set(ids) - {"adapt_decay_09", "pcie_start_02"}, set()) + + def test_workers_arm_never_goes_below_a_quarter(self): + c = make_ctx() + c.facts = {"workers": 4} + self.assertEqual(tune_knobs.dynamic_value("workers-2", c), 2) + c.facts = {"workers": 2} + self.assertIsNone(tune_knobs.dynamic_value("workers-2", c)) + + +class TunerTest(unittest.TestCase): + def test_finds_a_real_gain_and_changes_one_knob(self): + model = speed_with({("--host-core", "last"): 1.08}) + t, s, r = run_tuner(model, ctx=make_ctx()) + self.assertEqual(r.outcome, "improved", r.notes) + self.assertEqual(r.settings["args"], {"--host-core": "last"}) + self.assertAlmostEqual(r.gain_pct, 8.0, delta=2.0) + self.assertEqual(r.answers["class"], "exact") + for args, env in s.runs: # every run kept the user's own flags + self.assertEqual(flag(args, "--expert-cache"), "auto") + self.assertEqual(flag(args, "--kv"), "int8") + self.assertLessEqual(r.seconds, 1200 + 90 * 2) + + def test_no_gain_keeps_the_default(self): + t, s, r = run_tuner(lambda a, e, tune=None: 60.0, session_kw={"noise": 0.02}) + self.assertEqual(r.outcome, "default_confirmed") + self.assertEqual(r.settings, {"args": {}, "env": {}, "per_request": {}}) + self.assertIn("already the fastest", r.message) + + def test_a_gain_below_the_margin_is_not_taken(self): + model = speed_with({("--host-core", "last"): 1.02}) + t, s, r = run_tuner(model, session_kw={"noise": 0.001}) + self.assertEqual(r.settings["args"], {}) + + def test_losing_candidates_are_dropped_after_one_loss(self): + model = speed_with({("--host-core", "last"): 0.85}) + t, s, r = run_tuner(model, session_kw={"noise": 0.001}) + arm = [a for a in r.arms if a["id"] == "host_core_last"][0] + self.assertEqual(arm["status"], "dropped") + self.assertEqual(sum(1 for args, _ in s.runs if flag(args, "--host-core") == "last"), 1) + + def test_machine_drift_is_not_mistaken_for_a_gain(self): + clock = FakeClock() + counter = {"n": 0} + + def model(args, env, tune=None): # the machine slows 1.2% per engine start + return 60.0 * (1.0 - 0.012 * len(session.runs)) * (1.03 if flag(args, "--host-core") == "last" else 1.0) + session = StubSession(model=model, clock=clock, noise=0.0005) + t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(), clock=clock, sleep=clock.sleep, system=session.system, + total_ram_mib=64000, quiet=lambda: None) + r = t.run() + self.assertEqual(r.settings["args"], {}, r.notes) + + def test_candidate_that_does_not_fit_is_never_started(self): + model = speed_with({("--host-core", "last"): 1.10}) + clock = FakeClock() + session = StubSession(model=model, clock=clock, avail=9000, rss=lambda a, e: 12000.0) + calls = {"n": 0} + real = session.system + + def system(): + out = real() + out["memory"]["available_mib"] = 40000 if not session.runs else 9000 # after the base run only 9 GB is free + return out + t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(wait_ram_s=30), clock=clock, sleep=clock.sleep, + system=system, total_ram_mib=64000, quiet=lambda: None) + r = t.run() + self.assertEqual(len(session.runs), 1, "only the base was started") + self.assertEqual(r.outcome, "default_confirmed") + self.assertTrue(any(a["status"] == "skipped" and "memory" in a["reason"] for a in r.arms)) + + def test_first_oom_stops_the_search(self): + def fail(args, env): + return StartFailed("OOM", "out of memory") if flag(args, "--host-core") == "last" else None + t, s, r = run_tuner(speed_with({}), session_kw={"fail": fail}) + self.assertTrue(any("ran out of memory" in n for n in r.notes)) + self.assertEqual(sum(1 for a, _ in s.runs if flag(a, "--host-core") == "last"), 1) + self.assertEqual(r.settings["args"], {}) + + def test_unsupported_candidate_fails_alone(self): + def fail(args, env): + return StartFailed("UNSUPPORTED", "unknown argument: --host-core") if flag(args, "--host-core") else None + ctx = make_ctx() + ctx.facts = {"workers": 6} + t, s, r = run_tuner(speed_with({("--pool-workers", "4"): 1.1}), ctx=ctx, session_kw={"fail": fail}) + failed = [a for a in r.arms if a["status"] == "failed"] + self.assertTrue(failed and "UNSUPPORTED" in failed[0]["reason"]) + self.assertEqual(r.settings["args"], {"--pool-workers": 4}) + + def test_room_goal_refuses_a_faster_candidate_that_takes_more_memory(self): + model = speed_with({("--host-core", "last"): 1.1}) + rss = lambda a, e: 20000.0 if flag(a, "--host-core") == "last" else 12000.0 + t, s, r = run_tuner(model, opts=autotune.Options(goal="room", ram_wish_pct=20, reserve_mib=1536), session_kw={"rss": rss}) + self.assertEqual(r.settings["args"], {}) + self.assertTrue(any("more memory" in a["reason"] for a in r.arms)) + t, s, r = run_tuner(model, opts=autotune.Options(goal="speed"), session_kw={"rss": rss}) + self.assertEqual(r.settings["args"], {"--host-core": "last"}) + + def test_cancel_changes_nothing(self): + cancel = threading.Event() + model = speed_with({("--host-core", "last"): 1.1}) + n = {"i": 0} + + def progress(p): + if p["stage"] == "rounds": + cancel.set() + t, s, r = run_tuner(model, cancel=cancel, progress=progress) + self.assertEqual(r.outcome, "cancelled") + self.assertEqual(r.settings["args"], {}) + + def test_the_time_chosen_bounds_the_number_of_restarts(self): + model = speed_with({}) + t, s, r = run_tuner(model, session_kw={"run_s": 300.0}, opts=autotune.Options(budget_s=1200)) + self.assertLessEqual(len(s.runs), 1200 / 300 + 1) + t, s, r = run_tuner(model, session_kw={"run_s": 60.0}, opts=autotune.Options(budget_s=1200)) + self.assertGreater(len(s.runs), 4) + + def test_progress_reports_stage_and_time_left(self): + seen = [] + t, s, r = run_tuner(speed_with({}), progress=seen.append) + self.assertTrue(any(p["stage"] == "base" for p in seen)) + etas = [p["eta_s"] for p in seen if p.get("eta_s") is not None] + self.assertTrue(etas) + self.assertLessEqual(etas[-1], etas[0]) + self.assertEqual(seen[-1]["stage"], "done") + + def test_per_request_value_needs_every_round(self): + wins = {"n": 0} + + def model(args, env, tune=None): + if tune and tune.get("spec_min_p") == 0.7: + return 60.0 * 1.06 + return 60.0 + t, s, r = run_tuner(model, session_kw={"noise": 0.002}) + self.assertEqual(r.settings["per_request"].get("spec_min_p"), 0.7) + self.assertEqual(r.outcome, "improved") + + calls = {"n": 0} + + def noisy(args, env, tune=None): + if tune and tune.get("spec_min_p") == 0.7: + calls["n"] += 1 + return 60.0 * (1.06 if calls["n"] % 3 else 0.99) # one round in three it does not win + return 60.0 + t, s2, r = run_tuner(noisy, session_kw={"noise": 0.0}) + self.assertNotIn("spec_min_p", r.settings["per_request"]) + + def test_thorough_confirms_with_five_pairs(self): + model = speed_with({("--host-core", "last"): 1.06}) + t, s, r = run_tuner(model, opts=autotune.Options(mode="thorough", budget_s=7200), session_kw={"noise": 0.003}) + self.assertEqual(r.outcome, "improved") + self.assertEqual(r.pairs, 5) + self.assertGreaterEqual(r.faster_pairs, 4) + + def test_prompt_regression_blocks_a_decode_win(self): + model = speed_with({("--host-core", "last"): 1.08}) + pp = lambda a, e: 1500.0 * (0.8 if flag(a, "--host-core") == "last" else 1.0) + t, s, r = run_tuner(model, session_kw={"pp": pp, "noise": 0.001}) + self.assertEqual(r.settings["args"], {}) + + def test_base_that_cannot_start_is_reported(self): + t, s, r = run_tuner(speed_with({}), session_kw={"fail": lambda a, e: StartFailed("FAIL_BOOT", "x")}) + self.assertEqual(r.outcome, "base_failed") + self.assertEqual(len(s.runs), 1) + + def test_coding_metric_uses_prompt_speed(self): + m = autotune.metric({"decode_tok_s": 100.0, "pp_tok_s": 400.0}, "coding") + self.assertAlmostEqual(m, 200.0) + self.assertEqual(autotune.metric({"decode_tok_s": 100.0, "pp_tok_s": 400.0}, "chat"), 100.0) + + +class DecisionRulesTest(unittest.TestCase): + def test_threshold_follows_the_noise(self): + self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.0, 0.0), 1.03) + self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.025, 0.0), 1.05) + self.assertAlmostEqual(autotune.accept_threshold(0.03, 0.0, 0.04), 1.08) + + def test_is_win(self): + self.assertTrue(autotune.is_win([1.05, 1.06], [1.0], threshold=1.03)) + self.assertFalse(autotune.is_win([1.05, 0.99], [1.0], threshold=1.03)) + self.assertFalse(autotune.is_win([1.04, 1.04], [0.9], threshold=1.03)) + self.assertTrue(autotune.is_win([1.05, 1.06, 1.04, 1.05, 0.99], [1.0], threshold=1.03, need=4)) + + +class RecheckTest(unittest.TestCase): + def _preset(self): + return {"settings": {"args": {"--host-core": "last"}, "env": {}, "per_request": {}}, + "measured": {"decode_tok_s": 60.0, "pp4k_tok_s": 1500.0, "rss_peak_mib": 12000.0, "vram_peak_mib": 10000.0}} + + def test_keep_when_as_fast(self): + s = StubSession(model=lambda a, e, tune=None: 59.0, noise=0.0) + out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx()) + self.assertEqual(out["verdict"], "keep") + self.assertEqual(len(s.runs), 1) + self.assertEqual(flag(s.runs[0][0], "--host-core"), "last") + + def test_retune_suggested_when_slower(self): + s = StubSession(model=lambda a, e, tune=None: 50.0, noise=0.0) + out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx()) + self.assertEqual(out["verdict"], "retune") + self.assertIn("slower", out["reason"]) + + def test_engine_update_adds_a_baseline_start(self): + s = StubSession(model=lambda a, e, tune=None: 60.0 if flag(a, "--host-core") else 62.0, noise=0.0) + out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx(), engine_changed=True) + self.assertEqual(len(s.runs), 2) + self.assertEqual(out["verdict"], "retune") + + def test_a_start_that_fails_suggests_retune(self): + s = StubSession(model=lambda a, e, tune=None: 60.0, fail=lambda a, e: StartFailed("UNSUPPORTED", "unknown argument")) + out = autotune.recheck(s, BASE, self._preset(), ctx=make_ctx()) + self.assertEqual(out["verdict"], "retune") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/tuning/test_presets.py b/tests/tuning/test_presets.py new file mode 100644 index 00000000..ab46de51 --- /dev/null +++ b/tests/tuning/test_presets.py @@ -0,0 +1,175 @@ +"""The preset store: save, name, apply on load, stale detection, undo.""" + +from __future__ import annotations + +import copy +import json +import os +import tempfile +import time +import unittest +from pathlib import Path + +from strata_control import presets + +CFG = {"exe": "strata", "model_name": "swift-iq2_xs", "ui_resource_profile": "work", "vram_reserve_mib": 1536, + "args": ["--pack", "P", "--native", "Swift-IQ3_S-00001-of-00002.gguf", "--expert-cache", "auto", "--prefill", "auto", + "--spec", "4", "--max-context", "131072", "--kv", "int8"]} + + +def identity(driver="610.47", sha="aaa", epoch=0, gpu="RTX 5070", ram=64): + return {"hardware": {"hard": {"gpus": [{"name": gpu, "vram_mib": 12227}], "cpu": "cpu", "logical": 12, "physical": 6, + "hybrid": False, "ram_gib": ram, "pcie": None, "os": "Windows"}, + "soft": {"driver": [driver], "os_release": "11"}}, + "engine": {"version": "0.1.45", "backend": "cuda", "sha256": "e1", "tuning_epoch": epoch}, + "model": {"sha256_shard1": sha, "bytes": 1}} + + +RESULT = {"outcome": "improved", "seconds": 1100, "settings": {"args": {"--host-core": "last"}, "env": {}, "per_request": {}}, + "answers": {"class": "exact", "fields": []}, "base": {"decode_tok_s": 60.0, "pp_tok_s": 1500.0}, + "chosen": {"decode_tok_s": 65.0, "pp_tok_s": 1500.0, "rss_peak_mib": 12000, "vram_used_mib": 9000}, + "gain_pct": 8.3, "pairs": 2, "faster_pairs": 2, "noise": {"aa_gap": 0.004}} + + +class StoreTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + os.environ["STRATA_PRESET_DIR"] = str(Path(self.tmp.name) / "presets") + self.addCleanup(lambda: os.environ.pop("STRATA_PRESET_DIR", None)) + self.addCleanup(self.tmp.cleanup) + self.choices = presets.choices_from_config(CFG) + + def make(self, name=None, ident=None, result=None, choices=None): + return presets.create(result or RESULT, choices=choices or self.choices, identity=ident or identity(), name=name) + + def test_default_name_is_plain_words(self): + self.assertEqual(self.choices["quant"], "IQ3_S") + self.assertEqual(presets.default_name(self.choices), "IQ3_S 128K – Work") + full = dict(self.choices, goal="speed") + self.assertEqual(presets.default_name(full), "IQ3_S 128K – Full speed") + + def test_create_list_rename_delete(self): + p = self.make() + self.assertTrue(p["name"].startswith("IQ3_S 128K")) + self.assertEqual(len(presets.list_presets()), 1) + self.assertTrue(presets.list_presets()[0]["active"]) + q = presets.rename(p["id"], "My fast one") + self.assertEqual(q["name"], "My fast one") + with self.assertRaises(presets.PresetError): + presets.rename(p["id"], "") + p2 = self.make(name="My fast one") # a duplicate name gets a number, never overwrites + self.assertEqual(p2["name"], "My fast one (2)") + presets.delete("My fast one (2)") + self.assertEqual([x["name"] for x in presets.list_presets()], ["My fast one"]) + + def test_activation_keeps_the_previous_one_and_undo_restores_it(self): + a = self.make(name="A") + b = self.make(name="B") + self.assertEqual(presets.find("B")["id"], b["id"]) + slot = a["slot"] + self.assertEqual(presets._index()[slot]["active"], b["id"]) + self.assertEqual(presets.load(b["id"])["previous"], a["id"]) + restored = presets.undo(slot) + self.assertEqual(restored["id"], a["id"]) + self.assertEqual(presets._index()[slot]["active"], a["id"]) + self.assertIsNone(presets.undo(slot)) # undo once more: back to the standard setup + self.assertIsNone(presets._index()[slot]["active"]) + with self.assertRaises(presets.PresetError): + presets.undo(slot) + + def test_unsafe_settings_are_refused(self): + bad = copy.deepcopy(RESULT) + bad["settings"]["args"] = {"--expert-cache": 0} + with self.assertRaises(presets.PresetError): + self.make(result=bad) + + def test_overlay_applies_the_active_preset_without_measuring(self): + self.make() + out, info = presets.overlay(CFG, now=identity()) + self.assertTrue(info["applied"]) + self.assertEqual(info["state"], "fresh") + self.assertEqual(out["args"][-2:], ["--host-core", "last"]) + self.assertEqual(out["args"][:len(CFG["args"])], CFG["args"]) # the user's own flags are untouched + self.assertNotIn("--host-core", CFG["args"]) # the input is not modified + self.assertIn("identical", info["notice"]) + + def test_overlay_other_choices_get_no_preset(self): + self.make() + other = copy.deepcopy(CFG) + other["args"][other["args"].index("--max-context") + 1] = "32768" + out, info = presets.overlay(other, now=identity()) + self.assertFalse(info["applied"]) + self.assertEqual(out, other) + full = copy.deepcopy(CFG) + full["ui_resource_profile"] = "performance" + self.assertFalse(presets.overlay(full, now=identity())[1]["applied"]) + + def test_hard_change_does_not_apply_and_says_why(self): + self.make() + for kw, word in ((dict(gpu="RTX 4090"), "graphics card"), (dict(sha="zzz"), "model file")): + out, info = presets.overlay(CFG, now=identity(**kw)) + if "model file" in word: + self.assertFalse(info["applied"]) if info.get("state") else None + self.assertFalse(info["applied"], kw) + + def test_soft_change_applies_and_asks_for_a_recheck(self): + self.make() + out, info = presets.overlay(CFG, now=identity(driver="620.1")) + self.assertTrue(info["applied"]) + self.assertEqual(info["state"], "soft") + self.assertTrue(any("driver" in r for r in info["reasons"])) + out, info = presets.overlay(CFG, now=identity(epoch=1)) + self.assertEqual(info["state"], "soft") + + def test_staleness_rules(self): + p = self.make() + self.assertEqual(presets.staleness(p, identity())["state"], "fresh") + self.assertEqual(presets.staleness(p, identity(ram=32))["state"], "hard") + self.assertEqual(presets.staleness(p, identity(ram=62))["state"], "fresh") # within 10% + old = dict(p, created_epoch=time.time() - 100 * 86400) + self.assertEqual(presets.staleness(old, identity())["state"], "soft") + + def test_per_request_defaults_reach_the_sampling_block(self): + res = copy.deepcopy(RESULT) + res["settings"]["per_request"] = {"spec_min_p": 0.7} + self.make(result=res) + out, info = presets.overlay(CFG, now=identity()) + self.assertEqual(out["sampling"]["strata_tune"], {"spec_min_p": 0.7}) + + def test_a_broken_store_never_breaks_a_start(self): + self.make() + for f in Path(os.environ["STRATA_PRESET_DIR"]).glob("*.json"): + f.write_text("{not json") + out, info = presets.overlay(CFG, now=identity()) + self.assertEqual(out, CFG) + self.assertFalse(info["applied"]) + + def test_export_import_roundtrip(self): + p = self.make(name="Shared") + data = presets.export_preset(p["id"]) + presets.delete(p["id"]) + q = presets.import_preset(data) + self.assertEqual(q["settings"], p["settings"]) + self.assertNotEqual(q["id"], p["id"]) + data["settings"]["args"] = {"--spec": 6} + with self.assertRaises(presets.PresetError): + presets.import_preset(data) + + def test_recheck_keep_refreshes_the_identity(self): + p = self.make() + out = presets.record_recheck(p["id"], {"verdict": "keep", "identity": identity(driver="620.1"), + "measured": {"decode_tok_s": 70.0}}) + self.assertEqual(presets.staleness(out, identity(driver="620.1"))["state"], "fresh") + self.assertEqual(out["measured"]["decode_tok_s"], 70.0) # better by more than 3%: stored + self.assertIsNotNone(out["recheck"]["last_ok"]) + + def test_trial_history_blocks_a_candidate_that_did_not_start(self): + presets.record_trials([{"label": "host_core_last", "args": ["--x"], "env": {}, "status": "OOM", "at": 1}], + hw_hash="h", model_digest="m", engine_sha="e") + self.assertEqual(presets.bad_signatures(hw_hash="h", model_digest="m", engine_sha="e"), {"host_core_last"}) + self.assertEqual(presets.bad_signatures(hw_hash="h2", model_digest="m", engine_sha="e"), set()) + self.assertEqual(presets.bad_signatures(hw_hash="h", model_digest="m", engine_sha="e2"), set()) + + +if __name__ == "__main__": + unittest.main() From bb3334914942ac0d7273a768b82fecc2d2855970 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:49:59 +0200 Subject: [PATCH 02/18] tuner: memory and quiet checks run inside the box lock right before each start --- strata_control/autotune.py | 35 +++++++++++++++++++++++++--------- strata_control/tune_session.py | 6 ++++-- tests/tuning/stub_session.py | 4 +++- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index b98e7660..f250d63b 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -240,7 +240,7 @@ class Tuner: return f"the CPU is {busy:.0f}% busy" return None - def _ram_guard(self, delta_mib: int, label: str) -> str | None: + def _ram_guard(self, delta_mib: int, label: str, wait_s: float | None = None) -> str | None: """None when a start fits; otherwise the plain reason it does not.""" waited = 0.0 while True: @@ -256,7 +256,7 @@ class Tuner: need = max(need, self.o.min_free_ram_mib) if avail >= need: return None - if waited >= self.o.wait_ram_s: + if waited >= (self.o.wait_ram_s if wait_s is None else wait_s): return (f"not enough free memory to start it safely ({avail / 1024:.1f} GiB free, " f"{need / 1024:.1f} GiB needed)") self._say("waiting", f"Waiting for memory to be freed before trying {label}") @@ -266,22 +266,30 @@ class Tuner: # ---- one engine run def _run(self, args: list[str], env: dict[str, str | None], spec: RequestSet, label: str, - points: Callable[[Any], None] | None = None) -> RunResult: + points: Callable[[Any], None] | None = None, delta_mib: int = 0) -> RunResult: self._check_cancel() - self._wait_for_quiet() t0 = self.clock() + + def pre_start() -> None: + # checked again once the box lock is ours: another stream's engine may have come and gone while we waited + self._wait_for_quiet() + why = self._ram_guard(delta_mib, label, wait_s=60.0) + if why: + raise StartFailed("SKIPPED", why) + try: - with self.session.engine(args, env) as eng: + with self.session.engine(args, env, pre_start=pre_start) as eng: res = eng.measure(spec) if points is not None and res.status == "PASS": points(eng) except StartFailed as e: res = RunResult(status=e.status, reason=e.reason) dt = self.clock() - t0 - self.run_times.append(dt) - self.done_runs += 1 + if res.status != "SKIPPED": + self.run_times.append(dt) + self.done_runs += 1 + self.result.runs += 1 res.wall_s = round(dt, 1) - self.result.runs += 1 self.result.trials.append({"label": label, "args": args, "env": env, "status": res.status, "reason": res.reason, "decode_tok_s": res.decode_tok_s, "pp_tok_s": res.pp_tok_s, "rss_peak_mib": res.rss_peak_mib, "load_s": res.load_s, "at": time.time()}) @@ -380,6 +388,10 @@ class Tuner: break self._say("rounds", f"Measuring your current settings again (round {rnd + 1} of {per_arm})") b = self._run(self.base_args, {}, spec, f"base r{rnd + 1}") + if b.status == "SKIPPED": + r.notes.append("not enough free memory for another measurement of your current settings; the search stopped") + self.storm = stop = True + break if b.status != "PASS": r.notes.append("your current settings failed to start a second time; the search stopped") self.storm = stop = True @@ -395,7 +407,12 @@ class Tuner: alive = [x for x in alive if x.arm.id != p.arm.id] continue self._say("rounds", f"Trying: {p.arm.label} (round {rnd + 1} of {per_arm})", arm=p.arm.id) - res = self._run(tune_knobs.apply_to_argv(self.base_args, p.args), dict(p.env), spec, p.arm.id) + res = self._run(tune_knobs.apply_to_argv(self.base_args, p.args), dict(p.env), spec, p.arm.id, + delta_mib=p.arm.ram_delta_mib) + if res.status == "SKIPPED": + rep.status, rep.reason = "skipped", res.reason + alive = [x for x in alive if x.arm.id != p.arm.id] + continue if res.status != "PASS": rep.status, rep.reason = "failed", f"{res.status}: {res.reason}" alive = [x for x in alive if x.arm.id != p.arm.id] diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index 6c1759ac..fb73651d 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -86,7 +86,7 @@ class Engine(Protocol): class Session(Protocol): - def engine(self, args: list[str], env: dict[str, str | None]) -> contextlib.AbstractContextManager[Engine]: ... + def engine(self, args: list[str], env: dict[str, str | None], pre_start: Callable[[], None] | None = None) -> contextlib.AbstractContextManager[Engine]: ... def system(self) -> dict[str, Any]: ... @@ -399,10 +399,12 @@ class WorkerSession: return {"memory": tune_machine.memory(), "gpus": tune_machine.gpus(), "cpu": tune_machine.cpu()} @contextlib.contextmanager - def engine(self, args: list[str], env: dict[str, str | None]) -> Iterator[WorkerEngine]: + def engine(self, args: list[str], env: dict[str, str | None], pre_start: Callable[[], None] | None = None) -> Iterator[WorkerEngine]: with contextlib.ExitStack() as stack: if self.lock is not None: stack.enter_context(self.lock()) + if pre_start is not None: + pre_start() # the memory and quiet checks run once the lock is ours, right before the start self.runs += 1 n = self.runs cfg = json.loads(json.dumps(self.base)) diff --git a/tests/tuning/stub_session.py b/tests/tuning/stub_session.py index 7d954c7e..bcfac4a5 100644 --- a/tests/tuning/stub_session.py +++ b/tests/tuning/stub_session.py @@ -61,7 +61,9 @@ class StubSession: "vram_used_mib": 400, "driver": "1"}], "cpu": {"model": "stub", "logical": 12, "hybrid": False}} @contextlib.contextmanager - def engine(self, args: list[str], env: dict[str, Any]): + def engine(self, args: list[str], env: dict[str, Any], pre_start=None): + if pre_start is not None: + pre_start() self.runs.append((list(args), dict(env))) if self.clock is not None: self.clock.t += self.run_s From 33120935a3d501a7e11b4d8e837d42a4882c1d09 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:52:06 +0200 Subject: [PATCH 03/18] tuner: a queued kernel flock for the box lock, so other streams' waiters are served in order --- strata_control/tune_session.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index fb73651d..bef618bf 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -23,6 +23,7 @@ import statistics import subprocess import sys import tempfile +import threading import time import urllib.error import urllib.request @@ -194,6 +195,37 @@ class FileLock: def __enter__(self) -> "FileLock": Path(self.path).parent.mkdir(parents=True, exist_ok=True) self._fh = open(self.path, "a+") + if os.name != "nt" and threading.current_thread() is threading.main_thread(): + return self._blocking() + return self._polling() + + def _blocking(self) -> "FileLock": + """A blocking flock(2), queued in the kernel like `flock -x` (so the other streams' waiters are served in order and + a polling tuner is not starved). The wait limit is a timer, not a loop.""" + import fcntl + import signal + + def on_alarm(signum, frame): # noqa: ANN001 + raise TimeoutError + + try: + fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return self + except OSError: + self.log(f"waiting for the lock {self.path}") + old = signal.signal(signal.SIGALRM, on_alarm) + signal.setitimer(signal.ITIMER_REAL, self.wait_s) + try: + fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX) + return self + except TimeoutError: + self._fh.close() + raise StartFailed("TIMEOUT", f"the lock {self.path} was not free within {int(self.wait_s)} s") from None + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, old) + + def _polling(self) -> "FileLock": deadline = time.time() + self.wait_s told = False while True: From e6b3af5889072a9a5e0af3fcbb64f278c46c5b4f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:53:30 +0200 Subject: [PATCH 04/18] tuner: waiting for the box lock does not count against the time budget; session tests --- strata_control/autotune.py | 20 ++++-- tests/tuning/test_session.py | 115 +++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 4 deletions(-) create mode 100644 tests/tuning/test_session.py diff --git a/strata_control/autotune.py b/strata_control/autotune.py index f250d63b..20a712fb 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -97,6 +97,7 @@ class TuneResult: message: str = "" mode: str = "quick" seconds: float = 0.0 + waited_s: float = 0.0 # of those seconds, spent waiting (box lock, busy PC, memory) runs: int = 0 base: dict[str, Any] = field(default_factory=dict) chosen: dict[str, Any] = field(default_factory=dict) @@ -193,10 +194,14 @@ class Tuner: self.total_vram = total_vram_mib self.quiet = quiet self.storm = False + self.waited_s = 0.0 # time spent waiting for the box lock, the PC to be quiet or memory: not the user's budget # ---- bookkeeping + def _elapsed(self) -> float: + return self.clock() - self.started - self.waited_s + def _say(self, stage: str, message: str, **extra: Any) -> None: - elapsed = self.clock() - self.started + elapsed = self._elapsed() avg = statistics.mean(self.run_times) if self.run_times else 150.0 remaining = max(0, self.planned_runs - self.done_runs) eta = min(max(0.0, self.o.budget_s - elapsed), remaining * avg) if self.planned_runs else None @@ -208,7 +213,7 @@ class Tuner: raise Cancelled() def _over_budget(self, reserve_s: float = 0.0) -> bool: - return (self.clock() - self.started) + reserve_s > self.o.budget_s + return self._elapsed() + reserve_s > self.o.budget_s def _avg_run(self) -> float: return statistics.mean(self.run_times) if self.run_times else 150.0 @@ -270,12 +275,18 @@ class Tuner: self._check_cancel() t0 = self.clock() + entered: list[float] = [] + def pre_start() -> None: # checked again once the box lock is ours: another stream's engine may have come and gone while we waited + lock_got = self.clock() + self.waited_s += lock_got - t0 self._wait_for_quiet() why = self._ram_guard(delta_mib, label, wait_s=60.0) + self.waited_s += self.clock() - lock_got if why: raise StartFailed("SKIPPED", why) + entered.append(self.clock()) try: with self.session.engine(args, env, pre_start=pre_start) as eng: @@ -284,7 +295,7 @@ class Tuner: points(eng) except StartFailed as e: res = RunResult(status=e.status, reason=e.reason) - dt = self.clock() - t0 + dt = self.clock() - (entered[0] if entered else t0) # the run itself, not the waiting before it if res.status != "SKIPPED": self.run_times.append(dt) self.done_runs += 1 @@ -304,6 +315,7 @@ class Tuner: except Cancelled: r.outcome, r.message = "cancelled", "Stopped. Your settings were not changed." r.seconds = round(self.clock() - self.started, 1) + r.waited_s = round(self.waited_s, 1) return r def _spec(self) -> RequestSet: @@ -353,7 +365,7 @@ class Tuner: if o.mode == "thorough": n_arms = len(planned) else: - left = int((o.budget_s - (self.clock() - self.started)) / max(1.0, self._avg_run())) + left = int((o.budget_s - self._elapsed()) / max(1.0, self._avg_run())) fixed = (per_arm - 1) + 1 + 2 # extra base rounds, the final base, a combined-confirm margin n_arms = min(len(planned), max(0, (left - fixed) // per_arm)) for p in planned[n_arms:]: diff --git a/tests/tuning/test_session.py b/tests/tuning/test_session.py new file mode 100644 index 00000000..9d6a526e --- /dev/null +++ b/tests/tuning/test_session.py @@ -0,0 +1,115 @@ +"""The real session's request side, against a tiny HTTP server that answers like the worker does (a `timings` block on the +engine's own clock).""" + +from __future__ import annotations + +import json +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +from strata_control import tune_session +from strata_control.tune_session import RequestSet, WorkerEngine, WorkerSession, parse_facts, failure_kind, make_prompt + + +class Handler(BaseHTTPRequestHandler): + seen: list[dict] = [] + + def log_message(self, *a): # noqa: ANN002 + pass + + def do_GET(self): # noqa: N802 + body = json.dumps({"data": [{"id": "stub-model"}]}).encode() + self.send_response(200) + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): # noqa: N802 + req = json.loads(self.rfile.read(int(self.headers["content-length"]))) + Handler.seen.append({"auth": self.headers.get("authorization"), **req}) + n = req["max_tokens"] + prompt_tokens = len(req["messages"][0]["content"]) // 4 + tune = req.get("strata_tune") or {} + rate = 80.0 * (1.1 if tune.get("spec_min_p") == 0.7 else 1.0) + body = json.dumps({"choices": [{"message": {"content": "x"}}], "usage": {"prompt_tokens": prompt_tokens, "completion_tokens": n}, + "timings": {"cache_n": 0, "prompt_n": prompt_tokens, "prompt_ms": prompt_tokens / 2.0, + "prompt_per_second": 2000.0, "predicted_n": n, "predicted_ms": n / rate * 1000, + "predicted_per_second": rate}}).encode() + self.send_response(200) + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class FakeProc: + pid = 0 + + def poll(self): + return None + + +class SessionTest(unittest.TestCase): + def setUp(self): + Handler.seen = [] + self.srv = HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=self.srv.serve_forever, daemon=True).start() + self.addCleanup(self.srv.shutdown) + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + s = WorkerSession(base_config={"args": []}, serve_dir=".", workdir=self.tmp.name) + log = Path(self.tmp.name) / "e.log" + log.write_text("strata generate: expert cache 3160 slots, 4.26 GiB of VRAM\nstrata generate: 5 pool workers on logical processors 2,4\n") + self.eng = WorkerEngine(s, FakeProc(), self.srv.server_address[1], "k", [log], 12.0, None, lambda x: None) + + def test_measure_reads_the_engines_own_clock(self): + r = self.eng.measure(RequestSet(warmups=1, decodes=3, decode_tokens=200, pp_tokens=4096)) + self.assertEqual(r.status, "PASS") + self.assertAlmostEqual(r.decode_tok_s, 80.0, places=1) + self.assertEqual(r.pp_tok_s, 2000.0) + self.assertEqual(r.facts["slots"], 3160) + self.assertEqual(r.facts["workers"], 5) + self.assertTrue(all(h["auth"] == "Bearer k" for h in Handler.seen)) + self.assertTrue(all(h["model"] == "stub-model" for h in Handler.seen)) + + def test_prompts_are_unique_and_unchecked_by_cache(self): + self.eng.prompt_once(4096) + self.eng.prompt_once(4096) + a, b = [h["messages"][0]["content"] for h in Handler.seen[-2:]] + self.assertNotEqual(a[:40], b[:40]) + self.assertTrue(all(h.get("strata_checkpoint") is False for h in Handler.seen)) + + def test_per_request_settings_are_sent_and_change_the_rate(self): + base = self.eng.decode_once(None, 200) + fast = self.eng.decode_once({"spec_min_p": 0.7}, 200) + self.assertAlmostEqual(fast / base, 1.1, places=3) + self.assertEqual(Handler.seen[-1]["strata_tune"], {"spec_min_p": 0.7}) + + def test_prompt_length_calibrates_once(self): + s = self.eng.s + before = s.chars_per_token + self.eng.prompt_once(4096) + self.assertTrue(s.calibrated) + self.assertNotEqual(s.chars_per_token, 0) + text = make_prompt(1000, "abc", s.chars_per_token) + self.assertIn("Reference abc.", text) + + +class ParsingTest(unittest.TestCase): + def test_failure_kinds(self): + self.assertEqual(failure_kind("error: unknown argument: --adapt-min-gain\nusage...", 2)[0], "UNSUPPORTED") + self.assertEqual(failure_kind("native dense upload ... out of memory", 1)[0], "OOM") + self.assertEqual(failure_kind("", -9)[0], "OOM") + self.assertEqual(failure_kind("something else broke", 1)[0], "FAIL_BOOT") + + def test_facts(self): + f = parse_facts("strata generate: 6 CPU threads\nhybrid experts: 37% on the GPU\n") + self.assertEqual(f["workers"], 6) + self.assertTrue(f["hybrid_experts"]) + self.assertTrue(parse_facts("resident RAM mode on")["resident_ram"]) + + +if __name__ == "__main__": + unittest.main() From c0616f06be2cb36c79975313de5705ad8b250fa7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:54:20 +0200 Subject: [PATCH 05/18] tuner: AMD architecture from the kernel for the never list --- strata_control/autotune.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index 20a712fb..bcee5982 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -29,7 +29,7 @@ import time from dataclasses import dataclass, field from typing import Any, Callable -from strata_control import tune_knobs, tune_machine +from strata_control import engine_component, tune_knobs, tune_machine from strata_control.tune_session import RequestSet, RunResult, Session, StartFailed MIN_FREE_RAM_MIB = 3584 # 3.5 GiB left for the system at every start (6.5) @@ -741,6 +741,12 @@ def context_from_config(cfg: dict[str, Any], *, engine_backend: str | None, opts backend = engine_backend or ("cuda" if any(g.get("vendor") == "nvidia" for g in cards) else "hip" if any(g.get("vendor") == "amd" for g in cards) else "cpu") arch = None + if backend == "hip": + try: + archs = engine_component.hip_archs_present() + arch = archs[0] if archs else None + except Exception: # noqa: BLE001 + arch = None return tune_knobs.Context( backend=backend, family=family or detect_family(args), gpu_count=max(1, len(used)), vram_mib=min((g["vram_total_mib"] for g in used if g.get("vram_total_mib")), default=0), From 35cfd187cf765b04cf8da3891ff2c6a38e591bc6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 00:58:17 +0200 Subject: [PATCH 06/18] host: autotune and recheck operations, saved-tuning routes (Strata Control's tuner and presets, run on the config a load would use) --- apps/host/server/index.mjs | 6 + apps/host/server/native-autotune.mjs | 134 +++++++ apps/host/server/native-control.mjs | 386 +++++++++++---------- apps/host/tests/helpers/native-fixture.mjs | 5 +- apps/host/tests/native-autotune.test.mjs | 137 ++++++++ 5 files changed, 485 insertions(+), 183 deletions(-) create mode 100644 apps/host/server/native-autotune.mjs create mode 100644 apps/host/tests/native-autotune.test.mjs diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index ebd1313e..0b74342c 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -773,6 +773,12 @@ async function api(req, res, path, method, url) { if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport()); + /* The auto-tuner's saved tunings (Strata Control's presets, shared with the Terminal). Starting a tune or a re-check is POST /api/native/operations with kind autotune / recheck. */ + if(path==='/api/native/tune/status'&&method==='GET')return json(res,200,await native.tuneStatus({model:url.searchParams.get('model'),resourceProfile:url.searchParams.get('resourceProfile')||undefined,vision:url.searchParams.get('vision')||undefined})); + if(path==='/api/native/tune/presets'&&method==='GET')return json(res,200,await native.tunePresets.list()); + if(path==='/api/native/tune/undo'&&method==='POST'){const body=await readBody(req);return json(res,200,await native.tunePresets.undoFor({model:body.model,resourceProfile:body.resourceProfile,vision:body.vision}));} + const tunePreset=/^\/api\/native\/tune\/presets\/([0-9a-f]{8,32})\/(apply|rename|delete|undo)$/.exec(path); + if(tunePreset&&method==='POST')return json(res,200,await native.tunePresets.action(tunePreset[2],tunePreset[1],await readBody(req))); const nativeOperation=/^\/api\/native\/operations\/([a-z0-9-]+)\/cancel$/.exec(path); if(nativeOperation&&method==='POST')return json(res,200,await native.cancel(nativeOperation[1])); const nativeInstance=/^\/api\/native\/instances\/([a-z0-9-]+)\/(unload|default)$/.exec(path); diff --git a/apps/host/server/native-autotune.mjs b/apps/host/server/native-autotune.mjs new file mode 100644 index 00000000..f6228536 --- /dev/null +++ b/apps/host/server/native-autotune.mjs @@ -0,0 +1,134 @@ +/** + * The app's side of the auto-tuner. The tuner itself is Strata Control's (`strata tune auto`, `strata presets`): the same code and the + * same preset store the Terminal uses, so tuning in one place covers the other. This module only runs those commands, follows the + * status file the tuner rewrites at every step, and turns the answer into the sentence the app shows. It measures nothing itself. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; + +const MODES = new Set(['quick', 'thorough']); +const USES = new Set(['chat', 'coding']); + +/** The one sentence a finished tune is reported with (plain words; the numbers are the tuner's own). */ +export function resultSentence(result) { + if (!result) return 'The tune did not finish.'; + const name = result.preset?.name; + if (result.outcome === 'improved') { + const gain = Math.max(0, Math.round(result.gain_pct ?? 0)); + return `+${gain}% faster answers${name ? `, saved as '${name}'` : ''}`; + } + if (result.outcome === 'default_confirmed') return `Your current settings are already the fastest we found${name ? `. Saved as '${name}' so it is not tuned again` : ''}`; + return result.message || 'Nothing was changed.'; +} + +export function createAutoTune({ launcher, workDir, spawnProcess = spawn, pollMs = 1500 }) { + mkdirSync(workDir, { recursive: true }); + + /** Run one CLI command and read its JSON. Rejects only when the command cannot start or times out. */ + function run(args, { timeoutMs = 60_000 } = {}) { + const l = launcher(); + return new Promise((resolve, reject) => { + const child = spawnProcess(l.command, [...(l.prefix ?? []), ...args], { cwd: l.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: l.env }); + let out = '', err = '', done = false; + const finish = (fn, v) => { if (done) return; done = true; clearTimeout(alarm); fn(v); }; + const alarm = setTimeout(() => { try { child.kill(); } catch { /* gone */ } finish(reject, new Error('Strata did not answer in time.')); }, timeoutMs); + child.stdout?.on('data', c => { out += c; }); + child.stderr?.on('data', c => { err += c; if (err.length > 100_000) err = err.slice(-50_000); }); + child.on('error', e => finish(reject, new Error(`Strata could not start: ${e.message}`))); + child.on('close', code => { + let json = null; + const text = out.trim(); + if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON */ } } + finish(resolve, { code, json, text, stderr: err.trim() }); + }); + }); + } + const need = (r, what) => { + if (r.json?.ok === false) throw new Error(r.json.error?.message ?? what); + if (r.code !== 0 && !r.json) throw new Error(r.stderr.split(/\r?\n/).filter(Boolean).pop() || what); + return r.json ?? {}; + }; + + return { + run, + /** Which saved tuning these choices start with, and whether it is still valid (reads only). */ + async status(configPath) { return need(await run(['presets', 'status', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'The saved tuning could not be read.'); }, + async list() { return need(await run(['presets', 'list', '--output', 'json'], { timeoutMs: 30_000 }), 'The saved tunings could not be read.'); }, + async action(kind, id, extra = {}) { + if (!/^[0-9a-f]{8,32}$/.test(String(id ?? '')) && kind !== 'undo') throw new Error('Choose a saved tuning.'); + const args = { + apply: ['presets', 'apply', id], delete: ['presets', 'delete', id], undo: ['presets', 'undo', id], + rename: ['presets', 'rename', id, String(extra.name ?? '').slice(0, 80)], + }[kind]; + if (!args) throw new Error('Choose a supported action.'); + return need(await run([...args, '--output', 'json'], { timeoutMs: 30_000 }), 'That did not work.'); + }, + /** Undo by configuration: back to the tuning that was active before (or the standard settings). */ + async undoFor(configPath) { return need(await run(['presets', 'undo', 'x', '--config', configPath, '--output', 'json'], { timeoutMs: 45_000 }), 'There is nothing to undo.'); }, + + /** + * The long jobs: `tune auto` and `presets recheck`. `job` is a native-control job: `job.process` lets Stop end it, + * `job.progress` carries what the status file says (stage, minutes left, runs done) and `job.summary` the sentence. + */ + async start(job, kind, opts, { onProgress = () => {} } = {}) { + const l = launcher(); + const tag = job.id.slice(0, 8); + const statusFile = join(workDir, `tune-${tag}.status.json`); + const work = join(workDir, `tune-${tag}`); + rmSync(statusFile, { force: true }); + let args; + if (kind === 'recheck') { + if (!opts.presetId) throw new Error('Choose a saved tuning to check.'); + args = ['presets', 'recheck', opts.presetId, opts.configPath, '--output', 'json', '--status-file', statusFile, '--work-dir', work]; + } else { + const mode = MODES.has(opts.mode) ? opts.mode : 'quick'; + const use = USES.has(opts.use) ? opts.use : 'chat'; + args = ['tune', 'auto', opts.configPath, '--mode', mode, '--use', use, '--output', 'json', '--status-file', statusFile, '--work-dir', work]; + args.push('--goal', opts.goal === 'room' ? 'room' : 'speed'); + if (opts.leaveRam) args.push('--leave-ram', String(Math.max(0, Math.min(50, Math.round(opts.leaveRam))))); + if (opts.allowSmallDifferences) args.push('--allow-small-differences'); + if (opts.name) args.push('--name', String(opts.name).slice(0, 80)); + } + const child = spawnProcess(l.command, [...(l.prefix ?? []), ...args], { cwd: l.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: l.env }); + job.process = child; + let out = '', err = ''; + child.stdout?.on('data', c => { out += c; }); + child.stderr?.on('data', c => { err += c; if (err.length > 100_000) err = err.slice(-50_000); }); + const poll = () => { + try { + const p = JSON.parse(readFileSync(statusFile, 'utf8')); + if (p && p.state !== 'done') { job.progress = { stage: p.stage, text: p.text ?? null, minutesLeft: p.minutes_left ?? null, runsDone: p.runs_done ?? 0, runsPlanned: p.runs_planned ?? 0, elapsedS: p.elapsed_s ?? 0, step: p.message ?? '' }; onProgress(job.progress); } + } catch { /* not written yet */ } + }; + const timer = setInterval(poll, pollMs); + try { + const code = await new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); }); + clearInterval(timer); + let json = null; + const text = out.trim(); + if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON */ } } + if (job.state && job.state !== 'running') return null; // stopped by the user + if (!json) throw new Error(err.split(/\r?\n/).filter(Boolean).pop() || `The tune stopped (exit ${code}).`); + if (json.ok === false) throw new Error(json.error?.message ?? 'The tune failed.'); + const result = json.result ?? json; + if (kind === 'recheck') return { summary: json.verdict === 'keep' ? 'Still as fast as when it was saved.' : (json.reason ?? 'Checked.'), ...json }; + return { summary: resultSentence(result), ...result }; + } finally { + clearInterval(timer); + job.process = null; + rmSync(statusFile, { force: true }); + try { rmSync(work, { recursive: true, force: true }); } catch { /* keep logs if busy */ } + } + }, + }; +} + +export function writeTuneConfig(directory, model, cfg) { + const dir = join(directory, 'native-tune'); + mkdirSync(dir, { recursive: true }); + const path = join(dir, `${model}.json`); + const { api_key, port, ...rest } = cfg; // the key and port belong to a running instance, not to the choices + writeFileSync(path, JSON.stringify(rest, null, 2), { mode: 0o600 }); + return path; +} diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 0b7c7c5a..d62e281e 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -1,181 +1,205 @@ -/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */ -import { spawn } from 'node:child_process'; -import { randomBytes, randomUUID, createHash } from 'node:crypto'; -import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; -import { join, resolve, dirname, basename } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { createServer } from 'node:net'; -import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; -import { resourceSettings } from './native-resources.mjs'; -import { resolvePython, venvPython } from './python-resolver.mjs'; -import os from 'node:os'; -import { runtimeVision } from './native-vision.mjs'; - -const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); -const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); -const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state)); -function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}} - -export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ - mkdirSync(directory,{recursive:true}); - const settingsPath=join(directory,'native-host.json'); - let preferences=readJson(settingsPath,{repo:defaultRepo}); - let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null; - let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null}; - const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[]; - const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})}); - /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine - comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed, - updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */ - const packaged=!!control; - const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; - let defaultId=null,timer=null,closing=false,polling=false; - const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; - const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} - function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} - function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} - function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} - function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} - function python(){return resolvePython({repo:preferences.repo});} - function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} - function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();} - async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;} - async function startClient(){ - const folder=repo(); - buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); - client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}}); - child.stderr.on('data',chunk=>append('control',chunk.toString())); - client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}}); - client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}}); - await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}}); - child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n'); - definitions=(await send('tools/list',{})).tools??[]; - } - async function controlTool(name){ - if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'}; - if(name==='strata_status'){ - const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]); - const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); - const cores=os.cpus().length; - return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), - installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, - installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models}, - hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null}; - } - if(name==='strata_install')throw new Error(NO_INSTALL); - throw new Error(`Strata Control has no ${name}.`); - } - async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} - async function refresh(force=false){ - if(closing)return state(); - if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); - refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; - } - function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} - function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} - function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};} - function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};} - function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} - function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} - async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} - function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};} - - function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} - async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} - function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];} - async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}} - function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);} - async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});} - async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();} - async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); - if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); - if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); - const vision=runtimeVision(config,args.vision); - const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; - const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null; - const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; - if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} - if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})}; - for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.'); - const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex'); - const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement)); - if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id}; - const wasDefault=matching?.id===defaultId; - const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`; - cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])]; - const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port); - const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`); - const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.'); - if(job.state!=='running')return; - await beforeLoad();if(job.state!=='running')return; - if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id); - if(job.state!=='running')return; - writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600}); - const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null}; - let proc=null,started=null; - if(packaged){ - /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */ - const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot; - instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit(); - started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})); - started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);}); - try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;} - } else { - proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); - instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; - for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); - proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); - } - const deadline=Date.now()+300000;while(Date.now()setTimeout(resolve,1200)); - } - if(job.state!=='running'){await unload(id);return;} - if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error); - } - async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');} - async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} - function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();} - async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;} - function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;} - async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv; - if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];} - else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];} - else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];} - else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];} - else throw new Error('Unsupported native operation.'); - return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});}); - } - function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});} - function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);} - async function tune(job,args){ - await refresh(true);if(job.state!=='running')return; - const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile); - if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.'); - if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.'); - if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); - for(const id of [...instances.keys()])await unload(id); - if(job.state!=='running')return; - const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); - if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);} - if(job.state!=='running')return; - const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile); - const next={...current.config,...values,ui_resource_profile:args.profile}; - writeModelConfig(current.path,next); - job.summary='Applying your resource preference and loading the model…';emit(); - const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision}); - if(job.state!=='running'||!loaded?.instanceId)return; - job.summary='Checking your model’s speed…';emit(); - const measured=await benchmark(job,{instanceId:loaded.instanceId}); - return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile}; - } - function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} - async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} - async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} - // Remove nonserializable process references from public jobs. - const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; - return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; -} +/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */ +import { spawn } from 'node:child_process'; +import { randomBytes, randomUUID, createHash } from 'node:crypto'; +import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; +import { join, resolve, dirname, basename } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createServer } from 'node:net'; +import { NATIVE_FIELDS, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; +import { resourceSettings } from './native-resources.mjs'; +import { resolvePython, venvPython } from './python-resolver.mjs'; +import os from 'node:os'; +import { runtimeVision } from './native-vision.mjs'; +import { createAutoTune, writeTuneConfig } from './native-autotune.mjs'; +import { controlEnvironment } from './control-runtime.mjs'; + +const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'); +const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); +const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state)); +function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}} + +export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ + mkdirSync(directory,{recursive:true}); + const settingsPath=join(directory,'native-host.json'); + let preferences=readJson(settingsPath,{repo:defaultRepo}); + let child=null,seq=0,buffer='',pending=new Map(),definitions=[],refreshing=null,lastRead=0,connecting=null; + let snapshot={available:false,repo:preferences.repo,summary:'Connect a local Strata installation.',catalog:null,installed:null,hardware:null,error:null}; + const instances=new Map(),processes=new Map(),jobs=new Map(),logs=[]; + const savedJobs=readJson(join(directory,'native-jobs.json'),[]);for(const j of (Array.isArray(savedJobs)?savedJobs:[]).slice(-12))jobs.set(j.id,{...j,...(j.state==='running'?{state:'error',error:'The host restarted before completion. Check diagnostics, then retry; completed files are kept.',summary:'Interrupted operation'}:{})}); + /* Packaged mode: the app ships Strata Control (control-runtime.mjs). Models are run configs in an install folder, the engine + comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed, + updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */ + const packaged=!!control; + /* The auto-tuner and the saved tunings are Strata Control's (`strata tune auto`, `strata presets`): the app runs them and follows their status file. */ + const autotuner=createAutoTune({spawnProcess,workDir:join(directory,'native-tune'),launcher:()=>{if(packaged)return {command:control.control.python,prefix:[control.control.cli],cwd:control.control.dir,env:controlEnvironment(control.control)};const py=python();return {command:py.command,prefix:[...py.args,join(repo(),'strata.py')],cwd:repo(),env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}};}}); + const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; + let defaultId=null,timer=null,closing=false,polling=false; + const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; + const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; + function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}} + function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} + function python(){return resolvePython({repo:preferences.repo});} + function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} + function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();} + async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;} + async function startClient(){ + const folder=repo(); + buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}}); + client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}}); + child.stderr.on('data',chunk=>append('control',chunk.toString())); + client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}}); + client.on('exit',()=>{if(child===client){child=null;for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Strata control stopped. Python 3.10 or newer is required.'));}pending.clear();}}); + await send('initialize',{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'Strata UI',version:'0.1.0'}}); + child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n'); + definitions=(await send('tools/list',{})).tools??[]; + } + async function controlTool(name){ + if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'}; + if(name==='strata_status'){ + const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]); + const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null})); + const cores=os.cpus().length; + return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'), + installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir}, + installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models}, + hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null}; + } + if(name==='strata_install')throw new Error(NO_INSTALL); + throw new Error(`Strata Control has no ${name}.`); + } + async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;} + async function refresh(force=false){ + if(closing)return state(); + if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state(); + refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing; + } + function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} + function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();} + function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};} + function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};} + function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} + function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} + async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));} + function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};} + + function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} + async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} + function externalRunning(){return Array.isArray(snapshot.external)?snapshot.external.filter(s=>![...instances.values()].some(i=>i.port===s.port)):[];} + async function install(job,args){if(job.state!=='running')return;if(externalRunning().length)throw new Error('Stop the native server running outside this UI before preparing files.');if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel requests before preparing model files.');for(const id of [...instances.keys()])await unload(id);if(job.state!=='running')return;let result=await tool('strata_install',installArgs(args,true));job.summary=result.summary;job.result=result;emit();for(;;){if(job.state!=='running')return;await new Promise(resolve=>setTimeout(resolve,1500));result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(result.install&&!result.install.running){if(result.install.exit_code!==0)throw new Error(result.install.error??result.summary);await refresh(true);if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision});}return result;}}} + function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);} + async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});} + async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();} + /* The configuration a load starts the engine with (before its port and key): the saved model config, the user's choices and the resource profile. The tuner measures exactly this, so a saved tuning belongs to the same choices a load makes. */ + function buildConfig(args,config){ + const vision=runtimeVision(config,args.vision); + const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; + const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null; + const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; + if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} + if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})}; + for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.'); + return {cfg,resources,visionPreferences}; + } + async function loadEngine(job,args){ + await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); + if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); + if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); + const {cfg,resources,visionPreferences}=buildConfig(args,config); + const fingerprint=createHash('sha256').update(JSON.stringify({...cfg,api_key:undefined,port:undefined})).digest('hex'); + const placement=Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu];const matching=[...instances.values()].find(i=>i.model===args.model&&JSON.stringify(i.gpus)===JSON.stringify(placement)); + if(matching?.status==='ready'&&matching.fingerprint===fingerprint&&(args.multiple||instances.size===1))return {summary:`${matching.label} is already ready.`,instanceId:matching.id}; + const wasDefault=matching?.id===defaultId; + const id=matching?.id??randomUUID();let apiModelId=matching?.apiModelId??args.model,suffix=1;while(!matching&&[...instances.values()].some(i=>i.apiModelId===apiModelId))apiModelId=`${args.model}--${++suffix}`; + cfg.aliases=[...new Set([...(Array.isArray(cfg.aliases)?cfg.aliases:typeof cfg.aliases==='string'?cfg.aliases.split(',').map(s=>s.trim()).filter(Boolean):[]),apiModelId])]; + const key=randomBytes(32).toString('hex');cfg.api_key=key;cfg.port=await freePort(args.port); + const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const configPath=join(work,`${id}.json`); + const py=packaged?null:venvPython(repo());if(!packaged&&!existsSync(py))throw new Error('The Strata Python environment is missing. Use Download / repair first.'); + if(job.state!=='running')return; + await beforeLoad();if(job.state!=='running')return; + if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id); + if(job.state!=='running')return; + writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600}); + const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null}; + let proc=null,started=null; + if(packaged){ + /* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */ + const used=new Set([...instances.values()].map(i=>i.profile));let slot=1;while(used.has('app-'+slot))slot++;instance.profile='app-'+slot; + instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit(); + started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300})); + started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);}); + try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;} + } else { + proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); + instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; + for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); + proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); + } + const deadline=Date.now()+300000;while(Date.now()setTimeout(resolve,1200)); + } + if(job.state!=='running'){await unload(id);return;} + if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error); + } + async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');} + async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}} + function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();} + async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;} + function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;} + async function program(job,args){if(packaged)throw new Error(NO_INSTALL);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv; + if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];} + else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];} + else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];} + else if(job.kind==='update-strata'){const status=await execute('git',['status','--porcelain'],folder);if(status.trim())throw new Error('This Strata checkout has local edits. Save or commit them before updating.');const remote=await execute('git',['remote','get-url','origin'],folder);if(!/^https:\/\/github\.com\/Niko1221\/Strata(?:\.git)?\s*$/.test(remote))throw new Error('The native installation must use the official Strata repository to update here.');await execute('git',['pull','--ff-only'],folder);argv=[join(folder,'setup.py'),'--update'];} + else throw new Error('Unsupported native operation.'); + return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});}); + } + function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});} + function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);} + async function tune(job,args){ + await refresh(true);if(job.state!=='running')return; + const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile); + if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.'); + if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.'); + if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); + for(const id of [...instances.keys()])await unload(id); + if(job.state!=='running')return; + const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile}); + if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);} + if(job.state!=='running')return; + const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile); + const next={...current.config,...values,ui_resource_profile:args.profile}; + writeModelConfig(current.path,next); + job.summary='Applying your resource preference and loading the model…';emit(); + const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision}); + if(job.state!=='running'||!loaded?.instanceId)return; + job.summary='Checking your model’s speed…';emit(); + const measured=await benchmark(job,{instanceId:loaded.instanceId}); + return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile}; + } + /* What the tuner measures is what a load would start: the saved model config with the user's choices and the resource profile. */ + function tuneConfig(args){const {config,entry}=record(args.model);if(!entry.ready)throw new Error('Prepare the model before tuning it.');const {cfg}=buildConfig({model:args.model,vision:args.vision,resourceProfile:args.resourceProfile,gpus:args.gpus},config);return {path:writeTuneConfig(directory,args.model,cfg),entry};} + async function tuneStatus(args){await refresh();const {path}=tuneConfig(args);return autotuner.status(path);} + async function autotune(job,args){ + await refresh(true);if(job.state!=='running')return; + if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');} + const {path}=tuneConfig(args); + if(externalRunning().length)throw new Error('Stop the native server running outside this UI before tuning.'); + if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); + for(const id of [...instances.keys()])await unload(id); + if(job.state!=='running')return; + job.summary='Finding the fastest settings for your PC\u2026';emit(); + const room=args.resourceProfile==='work'; + return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); + } + function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):program(job,args),{guided:args.guided===true,model:args.model});} + async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install')await tool('strata_install',{cancel:true});else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} + async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} + // Remove nonserializable process references from public jobs. + const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,...job})=>job);return value;}; + return {state:publicState,tuneStatus,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; +} diff --git a/apps/host/tests/helpers/native-fixture.mjs b/apps/host/tests/helpers/native-fixture.mjs index 55e3cd25..a7926bdb 100644 --- a/apps/host/tests/helpers/native-fixture.mjs +++ b/apps/host/tests/helpers/native-fixture.mjs @@ -4,7 +4,7 @@ import {join} from 'node:path'; import {tmpdir} from 'node:os'; import {NATIVE_FIELDS} from '../../server/native-settings.mjs'; import {createNativeControl} from '../../server/native-control.mjs'; -export function nativeFixture({modelsDirectory}={}){ +export function nativeFixture({modelsDirectory,tuneHandler}={}){ const root=mkdtempSync(join(tmpdir(),'strata-native-test-')),repo=join(root,'repo'),directory=join(root,'data'); const venvBin=process.platform==='win32'?'.venv/Scripts':'.venv/bin',venvPython=process.platform==='win32'?'.venv/Scripts/python.exe':'.venv/bin/python'; for(const path of ['tools','serve',venvBin,'engine/.previous'])mkdirSync(join(repo,path),{recursive:true}); @@ -15,7 +15,8 @@ export function nativeFixture({modelsDirectory}={}){ for(const model of installed.models)writeFileSync(join(repo,model.config),JSON.stringify({model:model.model,gpu:0,args:['--max-context','32768'],env:{PATH:'/native/bin',STRATA_TOKEN:'private'},vision:{gpu:0},aliases:['chat'],unknown_native_key:{preserve:true}})); const calls=[],children=[],requests=[],rpcCalls=[];let programWait=false,hardware={ram_gb:128,gpus:[{index:0,name:'NVIDIA RTX 4090',vram_gb:24},{index:1,name:'NVIDIA RTX 3090',vram_gb:24}]},external=[]; const spawnProcess=(command,args,options)=>{ - calls.push({command,args,options});const child=new EventEmitter();child.stdout=new EventEmitter();child.stderr=new EventEmitter();child.exitCode=null;child.kill=()=>{child.exitCode=0;queueMicrotask(()=>child.emit('exit',0));return true;};children.push(child); + calls.push({command,args,options});const child=new EventEmitter();child.stdout=new EventEmitter();child.stderr=new EventEmitter();child.exitCode=null;child.kill=()=>{child.exitCode=0;queueMicrotask(()=>child.emit('exit',0));return true;}; + if(tuneHandler&&args.some(a=>String(a).endsWith('strata.py'))){child.kill=()=>{child.exitCode=0;queueMicrotask(()=>{child.emit('exit',0);child.emit('close',null);});return true;};queueMicrotask(()=>tuneHandler(child,args,options));return child;}children.push(child); if(args[0]?.endsWith('strata_mcp.py'))child.stdin={write(line){const message=JSON.parse(line);if(!message.id)return;if(message.method==='tools/call')rpcCalls.push(message.params);let result; if(message.method==='initialize')result={protocolVersion:'2024-11-05'}; else if(message.method==='tools/list')result={tools:['strata_models','strata_status','strata_install'].map(name=>({name}))}; diff --git a/apps/host/tests/native-autotune.test.mjs b/apps/host/tests/native-autotune.test.mjs new file mode 100644 index 00000000..606d30a4 --- /dev/null +++ b/apps/host/tests/native-autotune.test.mjs @@ -0,0 +1,137 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { nativeFixture, finishJob } from './helpers/native-fixture.mjs'; +import { resultSentence } from '../server/native-autotune.mjs'; + +const arg = (args, name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; }; + +/** A pretend `strata` command: records what it was asked, writes status-file steps, then prints its JSON. */ +function handler(log, { result, hold = false, delayMs = 60 } = {}) { + return (child, args) => { + log.push(args.slice(args.findIndex(a => String(a).endsWith('strata.py')) + 1)); + const cmd = log.at(-1); + const out = json => { child.stdout.emit('data', Buffer.from(JSON.stringify(json))); child.exitCode = 0; child.emit('exit', 0); child.emit('close', 0); }; + if (cmd[0] === 'presets' && cmd[1] === 'status') return out({ ok: true, active: null, suggested_name: 'IQ2_XS 32K – Full speed', presets: [], state: null, reasons: [] }); + if (cmd[0] === 'presets' && cmd[1] === 'list') return out({ ok: true, presets: [{ id: 'a'.repeat(32), name: 'x' }] }); + if (cmd[0] === 'presets') return out({ ok: true, done: cmd[1] }); + if (cmd[0] === 'tune') { + const status = arg(cmd, '--status-file'); + writeFileSync(status, JSON.stringify({ state: 'running', stage: 'rounds', text: 'Finding the fastest settings for your PC… about 9 min left', minutes_left: 9, runs_done: 3, runs_planned: 9, elapsed_s: 400, message: 'Trying: host core' })); + if (hold) return; // stays running until killed + setTimeout(() => out({ ok: true, result }), delayMs); + } + }; +} + +const improved = { outcome: 'improved', gain_pct: 11.6, seconds: 900, preset: { id: 'b'.repeat(32), name: 'IQ2_XS 32K – Full speed' }, answers: { class: 'exact', fields: [] }, settings: { args: { '--host-core': 'last' }, env: {}, per_request: {} } }; + +test('the result sentence is plain words with the gain and the saved name', () => { + assert.equal(resultSentence(improved), "+12% faster answers, saved as 'IQ2_XS 32K – Full speed'"); + assert.match(resultSentence({ outcome: 'default_confirmed', preset: { name: 'X' } }), /already the fastest/); + assert.equal(resultSentence({ outcome: 'inconclusive', message: 'The PC was too noisy.' }), 'The PC was too noisy.'); +}); + +test('a tune is started on the config a load would use, unloads nothing it did not have, follows progress and reports the saved name', async () => { + const log = []; + const f = nativeFixture({ tuneHandler: handler(log, { result: improved, delayMs: 2500 }) }); + try { + await f.control.refresh(true); + const job = f.control.operation('autotune', { model: 'iq2_xs', mode: 'quick', use: 'chat', resourceProfile: 'work' }); + let seen = null; + for (let n = 0; n < 200 && !seen; n++) { await new Promise(r => setTimeout(r, 30)); const j = f.control.state().jobs.find(x => x.id === job.id); if (j.progress) seen = j.progress; } + assert.ok(seen, 'progress from the status file reaches the job'); + assert.equal(seen.minutesLeft, 9); + const done = await finishJob(f.control, job.id); + assert.equal(done.state, 'done', done.error); + assert.equal(done.result.summary, "+12% faster answers, saved as 'IQ2_XS 32K – Full speed'"); + const cmd = log.find(c => c[0] === 'tune'); + assert.equal(cmd[1], 'auto'); + assert.equal(arg(cmd, '--mode'), 'quick'); + assert.equal(arg(cmd, '--goal'), 'room'); // "Leave 20% for my work" + assert.equal(arg(cmd, '--leave-ram'), '20'); + assert.ok(!cmd.includes('--allow-small-differences')); + const cfg = JSON.parse(readFileSync(cmd[2], 'utf8')); // the config the tuner measures is the one a load would start + assert.equal(cfg.ui_resource_profile, 'work'); + assert.ok(Array.isArray(cfg.args) && cfg.args.includes('--max-context')); + assert.equal(cfg.api_key, undefined); + assert.ok(!existsSync(arg(cmd, '--status-file')), 'the status file is removed afterwards'); + } finally { await f.cleanup(); } +}); + +test('full performance asks for speed with no memory left over, and the tick for small differences is only passed when ticked', async () => { + const log = []; + const f = nativeFixture({ tuneHandler: handler(log, { result: improved }) }); + try { + await f.control.refresh(true); + const done = await finishJob(f.control, f.control.operation('autotune', { model: 'iq3_s', mode: 'thorough', resourceProfile: 'performance', allowSmallDifferences: true }).id); + assert.equal(done.state, 'done', done.error); + const cmd = log.find(c => c[0] === 'tune'); + assert.equal(arg(cmd, '--goal'), 'speed'); + assert.equal(cmd.includes('--leave-ram'), false); + assert.equal(arg(cmd, '--mode'), 'thorough'); + assert.ok(cmd.includes('--allow-small-differences')); + } finally { await f.cleanup(); } +}); + +test('Stop ends the tune and keeps your settings; only one operation at a time', async () => { + const log = []; + const f = nativeFixture({ tuneHandler: handler(log, { hold: true }) }); + try { + await f.control.refresh(true); + const job = f.control.operation('autotune', { model: 'iq2_xs' }); + await new Promise(r => setTimeout(r, 80)); + assert.throws(() => f.control.operation('autotune', { model: 'iq3_s' }), /current engine operation/); + await f.control.cancel(job.id); + const j = f.control.state().jobs.find(x => x.id === job.id); + assert.equal(j.state, 'cancelled'); + assert.equal(j.result, null); + } finally { await f.cleanup(); } +}); + +test('a tune is refused while a model is generating, and loaded models are unloaded first', async () => { + const log = []; + const f = nativeFixture({ tuneHandler: handler(log, { result: improved }) }); + try { + await f.control.refresh(true); + const loaded = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id); + assert.equal(loaded.state, 'done', loaded.error); + f.requests.push({ instanceId: loaded.result.instanceId, state: 'generating' }); + const refused = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id); + assert.equal(refused.state, 'error'); + assert.match(refused.error, /Finish requests/); + f.requests.length = 0; + const done = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id); + assert.equal(done.state, 'done', done.error); + assert.equal(f.control.state().instances.length, 0, 'the model was unloaded so the tuner has the graphics card'); + } finally { await f.cleanup(); } +}); + +test('saved tunings: status for the choices, list, and actions go to Strata Control by id', async () => { + const log = []; + const f = nativeFixture({ tuneHandler: handler(log, {}) }); + try { + await f.control.refresh(true); + const st = await f.control.tuneStatus({ model: 'iq2_xs', resourceProfile: 'performance' }); + assert.equal(st.suggested_name, 'IQ2_XS 32K – Full speed'); + const listed = await f.control.tunePresets.list(); + assert.equal(listed.presets.length, 1); + await f.control.tunePresets.action('rename', 'a'.repeat(32), { name: 'My fast one' }); + assert.deepEqual(log.at(-1).slice(0, 4), ['presets', 'rename', 'a'.repeat(32), 'My fast one']); + await assert.rejects(f.control.tunePresets.action('apply', '../x'), /Choose a saved tuning/); + await assert.rejects(f.control.tunePresets.action('format', 'a'.repeat(32)), /supported action/); + } finally { await f.cleanup(); } +}); + +test('a model that is not prepared cannot be tuned', async () => { + const f = nativeFixture({ tuneHandler: handler([], {}) }); + try { + await f.control.refresh(true); + f.installed.models[0].ready = false; + await f.control.refresh(true); + const job = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id); + assert.equal(job.state, 'error'); + assert.match(job.error, /Prepare the model/); + } finally { await f.cleanup(); } +}); From bd773bbd77a9b4ad21df35c5187ab4b1b49de882 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:02:17 +0200 Subject: [PATCH 07/18] app: Tune model dialog (real tuner, saved tunings, undo) reusing the Auto-tune look; its strings in separate catalogs --- apps/host/scripts/make-tune-locales.py | 171 ++++++++++++++++++++++ apps/host/src/components/NativeModels.tsx | 8 +- apps/host/src/components/NativeTune.tsx | 108 ++++++++++++++ apps/host/src/lib/i18n.ts | 27 +++- apps/host/src/lib/native-tune.ts | 64 ++++++++ apps/host/src/lib/native.ts | 2 +- apps/host/src/locales/tune-de.json | 40 +++++ apps/host/src/locales/tune-en.json | 40 +++++ apps/host/src/locales/tune-es.json | 40 +++++ apps/host/src/locales/tune-ja.json | 40 +++++ apps/host/src/locales/tune-ko.json | 40 +++++ apps/host/src/locales/tune-pt.json | 40 +++++ apps/host/src/locales/tune-ru.json | 40 +++++ apps/host/src/locales/tune-zh.json | 40 +++++ apps/host/tests/tune-locales.test.mjs | 35 +++++ 15 files changed, 723 insertions(+), 12 deletions(-) create mode 100644 apps/host/scripts/make-tune-locales.py create mode 100644 apps/host/src/components/NativeTune.tsx create mode 100644 apps/host/src/lib/native-tune.ts create mode 100644 apps/host/src/locales/tune-de.json create mode 100644 apps/host/src/locales/tune-en.json create mode 100644 apps/host/src/locales/tune-es.json create mode 100644 apps/host/src/locales/tune-ja.json create mode 100644 apps/host/src/locales/tune-ko.json create mode 100644 apps/host/src/locales/tune-pt.json create mode 100644 apps/host/src/locales/tune-ru.json create mode 100644 apps/host/src/locales/tune-zh.json create mode 100644 apps/host/tests/tune-locales.test.mjs diff --git a/apps/host/scripts/make-tune-locales.py b/apps/host/scripts/make-tune-locales.py new file mode 100644 index 00000000..f7a186f0 --- /dev/null +++ b/apps/host/scripts/make-tune-locales.py @@ -0,0 +1,171 @@ +"""Writes src/locales/tune-.json: the interface strings of the Tune model dialog (auto-tuner), kept apart from the main +catalogs so that other work on the interface text does not collide with them. i18n.ts merges them. Run: python scripts/make-tune-locales.py""" +import json +from pathlib import Path + +KEYS = [ + "Tune this model", + "Finding the fastest settings for your PC…", + "about {0} min left", + "This takes about 20 minutes.", + "Stopped. Your settings were not changed.", + "The tune did not finish. Your settings were not changed.", + "Still as fast as when it was saved.", + "It is slower than before. You can tune again.", + "Could not tell right now. Your tuning was kept.", + "+{0}% faster answers, saved as '{1}'", + "Your current settings are already the fastest we found.", + "Nothing was changed.", + "Saved as '{0}', so it is not tuned again when you reopen the app.", + "Speed: {0} → {1} tok/s", + "Answers are identical to the standard setup.", + "Answers may differ slightly from the standard setup.", + "Answers are not repeatable run to run.", + "Includes a quality setting that changes the numbers.", + "Saved tuning in use: {0}", + "+{0}% faster answers", + "This PC changed since it was tuned, so these settings are not used until you tune again.", + "This PC or the engine changed since it was tuned. A short check takes about 2 minutes.", + "No saved tuning for these choices yet.", + "Strata tries different settings on this PC and keeps the ones that make answers faster. Your model is unloaded while this runs, and the computer will be busy.", + "Finish the current operation first.", + "How long to spend", + "Quick (about 20 minutes)", + "Thorough (up to 2 hours)", + "What you mostly do", + "Coding with long prompts", + "Allow settings that can change answers slightly", + "Saved tunings", + "In use", + "Use", + "Check again (about 2 minutes)", + "Tune again", + "Start tuning", + "Tuning your model", +] + +T = { + "zh": [ + "调优此模型", "正在为你的电脑寻找最快的设置…", "还剩约 {0} 分钟", + "这大约需要 20 分钟。", "已停止。你的设置没有改变。", "调优未完成。你的设置没有改变。", + "仍然和保存时一样快。", "比以前慢了。你可以再次调优。", "目前无法判断。已保留你的调优结果。", + "回答快了 {0}%,已保存为“{1}”", "你当前的设置已经是我们找到的最快设置。", "没有做任何改动。", + "已保存为“{0}”,重新打开应用时不会再次调优。", "速度:{0} → {1} tok/s", + "回答与标准设置完全相同。", "回答可能与标准设置略有不同。", "每次运行的回答不一定相同。", + "包含会改变数值的质量设置。", "正在使用的已保存调优:{0}", "回答快了 {0}%", + "自调优以来这台电脑发生了变化,因此在你再次调优之前不会使用这些设置。", + "自调优以来这台电脑或引擎发生了变化。快速检查大约需要 2 分钟。", + "这些选择还没有已保存的调优。", + "Strata 会在这台电脑上尝试不同的设置,并保留能让回答更快的设置。运行期间模型会被卸载,电脑会比较忙。", + "请先完成当前操作。", "花多长时间", "快速(约 20 分钟)", "彻底(最多 2 小时)", "你主要做什么", + "长提示的编程", "允许可能略微改变回答的设置", "已保存的调优", "使用中", "使用", + "再次检查(约 2 分钟)", "再次调优", "开始调优", "正在调优你的模型", + ], + "ja": [ + "このモデルをチューニング", "あなたの PC で最も速い設定を探しています…", "残り約 {0} 分", + "約 20 分かかります。", "停止しました。設定は変更されていません。", "チューニングが完了しませんでした。設定は変更されていません。", + "保存したときと同じ速さを保っています。", "以前より遅くなっています。もう一度チューニングできます。", "今は判断できませんでした。チューニング結果はそのまま保持しています。", + "回答が {0}% 速くなりました。「{1}」として保存しました", "現在の設定が、見つかった中で最も速い設定です。", "何も変更されませんでした。", + "「{0}」として保存しました。アプリを開き直しても再チューニングはしません。", "速度:{0} → {1} tok/s", + "回答は標準設定と完全に同じです。", "回答が標準設定とわずかに異なることがあります。", "回答は実行ごとに同じになるとは限りません。", + "数値を変える品質設定が含まれています。", "使用中の保存済みチューニング:{0}", "回答が {0}% 速くなりました", + "チューニング後にこの PC が変わったため、もう一度チューニングするまでこの設定は使われません。", + "チューニング後にこの PC またはエンジンが変わりました。簡易チェックは約 2 分です。", + "この選択に対する保存済みチューニングはまだありません。", + "Strata はこの PC でさまざまな設定を試し、回答が速くなるものを残します。実行中はモデルがアンロードされ、コンピューターは負荷が高くなります。", + "先に現在の操作を終えてください。", "かける時間", "クイック(約 20 分)", "じっくり(最大 2 時間)", "主な用途", + "長いプロンプトでのコーディング", "回答がわずかに変わる可能性のある設定も許可する", "保存済みチューニング", "使用中", "使用する", + "もう一度チェック(約 2 分)", "もう一度チューニング", "チューニングを開始", "モデルをチューニング中", + ], + "de": [ + "Dieses Modell abstimmen", "Die schnellsten Einstellungen für deinen PC werden gesucht…", "noch etwa {0} Min.", + "Das dauert etwa 20 Minuten.", "Gestoppt. Deine Einstellungen wurden nicht geändert.", "Die Abstimmung wurde nicht abgeschlossen. Deine Einstellungen wurden nicht geändert.", + "Noch genauso schnell wie beim Speichern.", "Langsamer als vorher. Du kannst erneut abstimmen.", "Im Moment nicht feststellbar. Deine Abstimmung wurde beibehalten.", + "+{0} % schnellere Antworten, gespeichert als „{1}“", "Deine aktuellen Einstellungen sind bereits die schnellsten, die wir gefunden haben.", "Es wurde nichts geändert.", + "Gespeichert als „{0}“, deshalb wird beim nächsten Öffnen der App nicht erneut abgestimmt.", "Tempo: {0} → {1} tok/s", + "Die Antworten sind mit der Standardeinstellung identisch.", "Die Antworten können leicht von der Standardeinstellung abweichen.", "Die Antworten sind von Lauf zu Lauf nicht wiederholbar.", + "Enthält eine Qualitätseinstellung, die die Zahlen verändert.", "Gespeicherte Abstimmung in Gebrauch: {0}", "+{0} % schnellere Antworten", + "Dieser PC hat sich seit der Abstimmung verändert, daher werden diese Einstellungen erst nach einer neuen Abstimmung verwendet.", + "Dieser PC oder die Engine hat sich seit der Abstimmung verändert. Eine kurze Prüfung dauert etwa 2 Minuten.", + "Für diese Auswahl gibt es noch keine gespeicherte Abstimmung.", + "Strata probiert auf diesem PC verschiedene Einstellungen aus und behält die, die Antworten schneller machen. Dein Modell wird dabei entladen, und der Computer ist ausgelastet.", + "Beende zuerst den aktuellen Vorgang.", "Wie lange soll es dauern?", "Schnell (etwa 20 Minuten)", "Gründlich (bis zu 2 Stunden)", "Was du hauptsächlich machst", + "Programmieren mit langen Prompts", "Einstellungen erlauben, die Antworten leicht verändern können", "Gespeicherte Abstimmungen", "In Gebrauch", "Verwenden", + "Erneut prüfen (etwa 2 Minuten)", "Erneut abstimmen", "Abstimmung starten", "Dein Modell wird abgestimmt", + ], + "es": [ + "Ajustar este modelo", "Buscando los ajustes más rápidos para tu PC…", "faltan unos {0} min", + "Esto tarda unos 20 minutos.", "Detenido. Tus ajustes no se han cambiado.", "El ajuste no terminó. Tus ajustes no se han cambiado.", + "Sigue tan rápido como cuando se guardó.", "Es más lento que antes. Puedes volver a ajustar.", "Ahora no se puede saber. Se ha conservado tu ajuste.", + "Respuestas un {0} % más rápidas, guardado como «{1}»", "Tus ajustes actuales ya son los más rápidos que hemos encontrado.", "No se ha cambiado nada.", + "Guardado como «{0}», así que no se vuelve a ajustar al reabrir la aplicación.", "Velocidad: {0} → {1} tok/s", + "Las respuestas son idénticas a las del ajuste estándar.", "Las respuestas pueden diferir ligeramente del ajuste estándar.", "Las respuestas no se repiten de una ejecución a otra.", + "Incluye un ajuste de calidad que cambia los números.", "Ajuste guardado en uso: {0}", "Respuestas un {0} % más rápidas", + "Este PC ha cambiado desde el ajuste, así que estos ajustes no se usan hasta que vuelvas a ajustar.", + "Este PC o el motor han cambiado desde el ajuste. Una comprobación breve tarda unos 2 minutos.", + "Todavía no hay un ajuste guardado para estas opciones.", + "Strata prueba distintos ajustes en este PC y conserva los que hacen las respuestas más rápidas. Tu modelo se descarga mientras tanto y el ordenador estará ocupado.", + "Termina primero la operación actual.", "Cuánto tiempo dedicar", "Rápido (unos 20 minutos)", "A fondo (hasta 2 horas)", "Qué haces sobre todo", + "Programar con prompts largos", "Permitir ajustes que pueden cambiar ligeramente las respuestas", "Ajustes guardados", "En uso", "Usar", + "Comprobar de nuevo (unos 2 minutos)", "Ajustar de nuevo", "Empezar a ajustar", "Ajustando tu modelo", + ], + "ru": [ + "Настроить эту модель", "Ищем самые быстрые настройки для вашего ПК…", "осталось примерно {0} мин.", + "Это займёт около 20 минут.", "Остановлено. Ваши настройки не изменились.", "Настройка не завершилась. Ваши настройки не изменились.", + "Всё так же быстро, как при сохранении.", "Сейчас медленнее, чем раньше. Можно настроить заново.", "Сейчас не удалось определить. Ваша настройка сохранена.", + "Ответы быстрее на {0}%, сохранено как «{1}»", "Ваши текущие настройки уже самые быстрые из найденных.", "Ничего не изменено.", + "Сохранено как «{0}», поэтому при повторном открытии приложения настройка не будет повторяться.", "Скорость: {0} → {1} tok/s", + "Ответы такие же, как при стандартных настройках.", "Ответы могут немного отличаться от стандартных настроек.", "Ответы не повторяются от запуска к запуску.", + "Включает настройку качества, которая меняет числа.", "Используется сохранённая настройка: {0}", "Ответы быстрее на {0}%", + "С момента настройки этот ПК изменился, поэтому эти настройки не используются, пока вы не настроите заново.", + "С момента настройки этот ПК или движок изменились. Короткая проверка займёт около 2 минут.", + "Для этих параметров пока нет сохранённой настройки.", + "Strata пробует на этом ПК разные настройки и оставляет те, что ускоряют ответы. Пока это идёт, модель выгружена, а компьютер занят.", + "Сначала завершите текущую операцию.", "Сколько времени потратить", "Быстро (около 20 минут)", "Тщательно (до 2 часов)", "Чем вы в основном занимаетесь", + "Программирование с длинными промптами", "Разрешить настройки, которые могут немного изменить ответы", "Сохранённые настройки", "Используется", "Использовать", + "Проверить снова (около 2 минут)", "Настроить снова", "Начать настройку", "Настройка вашей модели", + ], + "pt": [ + "Ajustar este modelo", "Procurando as configurações mais rápidas para o seu PC…", "faltam cerca de {0} min", + "Isso leva cerca de 20 minutos.", "Interrompido. Suas configurações não foram alteradas.", "O ajuste não terminou. Suas configurações não foram alteradas.", + "Continua tão rápido quanto quando foi salvo.", "Está mais lento do que antes. Você pode ajustar de novo.", "Não foi possível saber agora. Seu ajuste foi mantido.", + "Respostas {0} % mais rápidas, salvo como “{1}”", "Suas configurações atuais já são as mais rápidas que encontramos.", "Nada foi alterado.", + "Salvo como “{0}”, então não é ajustado de novo quando você reabre o app.", "Velocidade: {0} → {1} tok/s", + "As respostas são idênticas às da configuração padrão.", "As respostas podem diferir um pouco da configuração padrão.", "As respostas não se repetem de uma execução para outra.", + "Inclui uma configuração de qualidade que muda os números.", "Ajuste salvo em uso: {0}", "Respostas {0} % mais rápidas", + "Este PC mudou desde o ajuste, então estas configurações não são usadas até você ajustar de novo.", + "Este PC ou o motor mudou desde o ajuste. Uma verificação rápida leva cerca de 2 minutos.", + "Ainda não há ajuste salvo para estas escolhas.", + "O Strata testa configurações diferentes neste PC e mantém as que deixam as respostas mais rápidas. Seu modelo é descarregado enquanto isso e o computador fica ocupado.", + "Termine primeiro a operação atual.", "Quanto tempo dedicar", "Rápido (cerca de 20 minutos)", "Completo (até 2 horas)", "O que você mais faz", + "Programação com prompts longos", "Permitir configurações que podem mudar um pouco as respostas", "Ajustes salvos", "Em uso", "Usar", + "Verificar de novo (cerca de 2 minutos)", "Ajustar de novo", "Iniciar ajuste", "Ajustando o seu modelo", + ], + "ko": [ + "이 모델 최적화", "내 PC에서 가장 빠른 설정을 찾는 중…", "약 {0}분 남음", + "약 20분 걸립니다.", "중지되었습니다. 설정이 변경되지 않았습니다.", "최적화가 완료되지 않았습니다. 설정이 변경되지 않았습니다.", + "저장할 때와 같은 속도를 유지하고 있습니다.", "이전보다 느려졌습니다. 다시 최적화할 수 있습니다.", "지금은 판단할 수 없습니다. 최적화 결과는 유지되었습니다.", + "답변이 {0}% 빨라졌습니다. ‘{1}’(으)로 저장됨", "현재 설정이 찾은 것 중 이미 가장 빠른 설정입니다.", "아무것도 변경되지 않았습니다.", + "‘{0}’(으)로 저장되었으므로 앱을 다시 열어도 다시 최적화하지 않습니다.", "속도: {0} → {1} tok/s", + "답변은 표준 설정과 동일합니다.", "답변이 표준 설정과 조금 다를 수 있습니다.", "답변이 실행마다 동일하지 않습니다.", + "숫자를 바꾸는 품질 설정이 포함되어 있습니다.", "사용 중인 저장된 최적화: {0}", "답변이 {0}% 빨라졌습니다", + "최적화 이후 이 PC가 변경되어 다시 최적화할 때까지 이 설정은 사용되지 않습니다.", + "최적화 이후 이 PC 또는 엔진이 변경되었습니다. 간단 점검은 약 2분 걸립니다.", + "이 선택에 대해 저장된 최적화가 아직 없습니다.", + "Strata는 이 PC에서 여러 설정을 시험하고 답변을 더 빠르게 하는 설정만 남깁니다. 실행하는 동안 모델이 언로드되고 컴퓨터가 바쁝니다.", + "먼저 현재 작업을 끝내세요.", "얼마나 오래 할까요", "빠름 (약 20분)", "꼼꼼히 (최대 2시간)", "주로 하는 일", + "긴 프롬프트로 코딩", "답변을 조금 바꿀 수 있는 설정 허용", "저장된 최적화", "사용 중", "사용", + "다시 점검 (약 2분)", "다시 최적화", "최적화 시작", "모델을 최적화하는 중", + ], +} + +out = Path(__file__).resolve().parent.parent / "src" / "locales" +ids = [f"tune{i + 1:02d}" for i in range(len(KEYS))] +for lang, values in T.items(): + assert len(values) == len(KEYS), (lang, len(values), len(KEYS)) + for k, v in zip(KEYS, values): + import re + assert sorted(re.findall(r"\{\d+\}", k)) == sorted(re.findall(r"\{\d+\}", v)), (lang, k, v) + (out / f"tune-{lang}.json").write_text(json.dumps(dict(zip(ids, values)), ensure_ascii=False, indent=1) + "\n", encoding="utf-8") +(out / "tune-en.json").write_text(json.dumps(dict(zip(ids, KEYS)), ensure_ascii=False, indent=1) + "\n", encoding="utf-8") +print("wrote", len(KEYS), "strings x", len(T) + 1, "languages") diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index fdc6a953..80d244cb 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -10,6 +10,7 @@ import { RunImageModel } from './RunImageModel'; import { useStore } from '../lib/store'; import { NativePresets } from './NativePresets'; import { NativeBenchmark } from './NativeOperations'; +import { NativeTune } from './NativeTune'; import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: { onOtherModels: () => void; @@ -22,7 +23,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false); const [expert, setExpert] = useState(manual), [multiple, setMultiple] = useState(false), [gpus, setGpus] = useState([]), [kv, setKv] = useState('int8'), [lowRam, setLowRam] = useState('auto'), [split, setSplit] = useState('auto'), [deviceChoice, setDeviceChoice] = useState('auto'); const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work'); - const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [benchmark, setBenchmark] = useState(false), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); const presetPending = useRef(false); const families = nativeCatalogModels(native?.catalog?.families ?? []); const expertSection = useRef(null); @@ -91,13 +92,14 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(active ? : null)} {tr(job?.state === 'error' ? void load()}/> : null)} {tr(error ? : null)} -
{tr(onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
+
{tr(onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> setTuneOpen(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
!pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr("Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}

{tr(plan?.plan?.disk_short ? : null)}

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
setManage(false)} actions={ setManage(false)}>{tr("Done")}}>

{tr(selectedFamily?.title)}

{tr(selectedFamily?.sizes.map(v => ))}
{tr("Version")}{tr("Download")}{tr("Status")}
{tr(catalogVersionLabel(v))}{tr(v.model)} · {tr(v.about)}{tr(v.download_gb.toFixed(1))}{tr(" GB")}{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')} { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}

{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}

setBenchmark(false)}/> + {selectedSize ? setTuneOpen(false)} model={selectedSize.id} resourceProfile={resourceProfile} vision={selectedSize.images ? vision : 'no'}/> : null} ; } export function NativeProgress({ job }: { @@ -110,4 +112,4 @@ catch (e) { } finally { setStopping(false); -} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ? void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')} : null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ? void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')} : null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } diff --git a/apps/host/src/components/NativeTune.tsx b/apps/host/src/components/NativeTune.tsx new file mode 100644 index 00000000..94fb95ee --- /dev/null +++ b/apps/host/src/components/NativeTune.tsx @@ -0,0 +1,108 @@ +import { tr } from '../lib/i18n'; +import { useCallback, useEffect, useState } from 'react'; +import { Btn, Dialog, Icon, Select } from './ui'; +import { nativeAction, useNative, type NativeJob } from '../lib/native'; +import { ANSWER_NOTICE, tunePresetAction, tuneStatus, tuneUndo, type TuneProgress, type TunePreset, type TuneResult, type TuneStatus } from '../lib/native-tune'; + +type Phase = 'idle' | 'running' | 'result'; + +/** + * Tune model: find the fastest settings for this PC and keep them. The tuner is Strata Control's (the same one the Terminal runs, + * with the same saved tunings); this dialog only starts it, shows its progress and result in plain words, and lists, switches, + * renames, deletes and undoes the saved tunings. It reuses the Auto-tune dialog's look. + */ +export function NativeTune({ open, onClose, model, resourceProfile, vision }: { + open: boolean; + onClose: () => void; + model: string; + resourceProfile: 'work' | 'performance'; + vision: string; +}) { + const native = useNative(); + const [status, setStatus] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false); + const [mode, setMode] = useState<'quick' | 'thorough'>('quick'), [use, setUse] = useState<'chat' | 'coding'>('chat'), [allowSmall, setAllowSmall] = useState(false); + const [jobId, setJobId] = useState(''), [renaming, setRenaming] = useState(null), [name, setName] = useState(''); + const running = native?.jobs.find(j => (j.kind === 'autotune' || j.kind === 'recheck') && j.state === 'running'); + const job: NativeJob | undefined = native?.jobs.find(j => j.id === jobId) ?? running; + const phase: Phase = job?.state === 'running' ? 'running' : job && job.id === jobId ? 'result' : 'idle'; + const other = native?.jobs.find(j => j.state === 'running' && j.kind !== 'autotune' && j.kind !== 'recheck'); + + const reload = useCallback(async () => { + try { setStatus(await tuneStatus(model, resourceProfile, vision)); setError(''); } + catch (e) { setStatus(null); setError(e instanceof Error ? e.message : String(e)); } + }, [model, resourceProfile, vision]); + useEffect(() => { if (open && phase !== 'running') void reload(); }, [open, phase, reload, job?.state]); + useEffect(() => { if (open && running && !jobId) setJobId(running.id); }, [open, running?.id]); + + async function start(kind: 'autotune' | 'recheck') { + setBusy(true); setError(''); + try { + const started = await nativeAction('operations', { kind, args: { model, resourceProfile, vision, mode, use, allowSmallDifferences: allowSmall, presetId: status?.active?.id } }); + setJobId(started.id); + } catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { setBusy(false); } + } + async function act(fn: () => Promise) { + setBusy(true); setError(''); + try { await fn(); await reload(); } + catch (e) { setError(e instanceof Error ? e.message : String(e)); } + finally { setBusy(false); } + } + function close() { if (phase !== 'running') setJobId(''); onClose(); } + + const progress = job?.progress as TuneProgress | undefined; + const result = job?.state === 'done' ? (job.result as TuneResult | null) : null; + const stopped = job?.state === 'cancelled'; + const ratio = progress && progress.runsPlanned ? Math.min(0.96, progress.runsDone / progress.runsPlanned) : 0; + const left = progress?.minutesLeft ?? null; + const active = status?.active ?? null; + + const orbit = (complete: boolean) =>
; + const notice = (cls?: string) => cls ?

{tr(ANSWER_NOTICE[cls] ?? '')}

: null; + + let body; + let actions; + if (phase === 'running') { + body =
{orbit(false)}

{tr("Finding the fastest settings for your PC…")}

+

{left != null ? tr("about {0} min left", [left]) : tr("This takes about 20 minutes.")}

+ {progress?.step ?

{progress.step}

: null} +
{[0, 1, 2, 3].map(i => = i / 4 && ratio > 0}/>)}
; + actions = <> void act(() => nativeAction(`operations/${job!.id}/cancel`))} disabled={busy}>{tr("Stop")}; + } else if (phase === 'result') { + const improved = result?.outcome === 'improved' || result?.verdict === 'keep'; + const text = stopped ? tr("Stopped. Your settings were not changed.") : job?.state === 'error' ? tr("The tune did not finish. Your settings were not changed.") : result?.verdict ? (result.verdict === 'keep' ? tr("Still as fast as when it was saved.") : result.verdict === 'retune' ? tr("It is slower than before. You can tune again.") : tr("Could not tell right now. Your tuning was kept.")) : result?.outcome === 'improved' ? tr("+{0}% faster answers, saved as '{1}'", [Math.max(0, Math.round(result.gain_pct ?? 0)), result.preset?.name ?? '']) : result?.outcome === 'default_confirmed' ? tr("Your current settings are already the fastest we found.") : (result?.message ?? tr("Nothing was changed.")); + body =
{orbit(improved || result?.outcome === 'default_confirmed')}

{text}

+ {result?.outcome === 'default_confirmed' && result.preset ?

{tr("Saved as '{0}', so it is not tuned again when you reopen the app.", [result.preset.name])}

: null} + {result?.outcome === 'improved' ? <>

{tr("Speed: {0} → {1} tok/s", [Math.round((result.base?.decode_tok_s ?? 0) * 10) / 10, Math.round((result.chosen?.decode_tok_s ?? 0) * 10) / 10])}

{notice(result.answers?.class)} : null} + {job?.state === 'error' ?

{job.error}

: null}
; + actions = <>{status?.can_undo && result?.outcome === 'improved' ? void act(async () => { await tuneUndo(model, resourceProfile, vision); setJobId(''); })}>{tr("Undo")} : null}{tr("Close")}; + } else { + const stale = active && status?.state && status.state !== 'fresh'; + body =
+ {error ?

{error}

: null} + {active ?

{tr("Saved tuning in use: {0}", [active.name])}

+ {active.gain_pct ?

{tr("+{0}% faster answers", [Math.round(active.gain_pct)])}

: null} + {notice(active.answers?.class)} + {stale ?

{status?.state === 'hard' ? tr("This PC changed since it was tuned, so these settings are not used until you tune again.") : tr("This PC or the engine changed since it was tuned. A short check takes about 2 minutes.")}

: null}
+ :

{tr("No saved tuning for these choices yet.")}

} +

{tr("Strata tries different settings on this PC and keeps the ones that make answers faster. Your model is unloaded while this runs, and the computer will be busy.")}

+ {other ?

{tr("Finish the current operation first.")}

: null} + + + {status && status.presets.length ?

{tr("Saved tunings")}

+ {status.presets.map(p =>
+ {p.name}{p.active ? {'·'} {tr("In use")} : null} + {!p.active ? void act(() => tunePresetAction(p.id, 'apply'))}>{tr("Use")} : null} + { setRenaming(p); setName(p.name); }}>{tr("Rename")} + void act(() => tunePresetAction(p.id, 'delete'))}>{tr("Delete")}
)} +
: null} + {renaming ?
setName(e.target.value)}/> void act(async () => { await tunePresetAction(renaming.id, 'rename', { name: name.trim() }); setRenaming(null); })}>{tr("Save")} setRenaming(null)}>{tr("Cancel")}
: null} +
; + actions = <>{tr("Close")} + {status?.can_undo ? void act(async () => { await tuneUndo(model, resourceProfile, vision); })}>{tr("Undo")} : null} + {active && status?.state === 'soft' ? void start('recheck')}>{tr("Check again (about 2 minutes)")} : null} + void start('autotune')}>{tr(active ? "Tune again" : "Start tuning")}; + } + return {body}; +} diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index ffbe6add..53c9196f 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -1,14 +1,25 @@ -import english from '../locales/en.json'; -import zh from '../locales/zh.json'; -import ja from '../locales/ja.json'; -import de from '../locales/de.json'; -import es from '../locales/es.json'; -import ru from '../locales/ru.json'; -import pt from '../locales/pt.json'; -import ko from '../locales/ko.json'; +import baseEnglish from '../locales/en.json'; +import tune_en from '../locales/tune-en.json'; +import tune_zh from '../locales/tune-zh.json'; +import tune_ja from '../locales/tune-ja.json'; +import tune_de from '../locales/tune-de.json'; +import tune_es from '../locales/tune-es.json'; +import tune_ru from '../locales/tune-ru.json'; +import tune_pt from '../locales/tune-pt.json'; +import tune_ko from '../locales/tune-ko.json'; +import base_zh from '../locales/zh.json'; +import base_ja from '../locales/ja.json'; +import base_de from '../locales/de.json'; +import base_es from '../locales/es.json'; +import base_ru from '../locales/ru.json'; +import base_pt from '../locales/pt.json'; +import base_ko from '../locales/ko.json'; export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; export type Language=typeof LANGUAGES[number]['value']; +/* The Tune model dialog's strings live in tune-.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ +const english:Record={...baseEnglish,...tune_en}; +const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh},{...base_ja,...tune_ja},{...base_de,...tune_de},{...base_es,...tune_es},{...base_ru,...tune_ru},{...base_pt,...tune_pt},{...base_ko,...tune_ko}] as Record[]; const catalogs:Record>={en:english,zh,ja,de,es,ru,pt,ko}; const entities:Record={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/native-tune.ts b/apps/host/src/lib/native-tune.ts new file mode 100644 index 00000000..fc4e2b89 --- /dev/null +++ b/apps/host/src/lib/native-tune.ts @@ -0,0 +1,64 @@ +import { api } from './client'; + +/** A saved tuning, as Strata Control reports it (the same store the Terminal uses). */ +export interface TunePreset { + id: string; + name: string; + active: boolean; + created?: string; + answers?: { class: 'exact' | 'placement' | 'nonrepeatable' | 'quality'; fields: string[] }; + settings?: { args: Record; env: Record; per_request: Record }; + gain_pct?: number | null; + decode_tok_s?: number | null; + baseline_decode_tok_s?: number | null; + recheck?: { last_ok?: string | null; last_result?: { verdict?: string; reason?: string } | null } | null; + slot?: string; +} + +export interface TuneStatus { + ok: boolean; + slot: string; + suggested_name: string; + active: TunePreset | null; + /** fresh, soft (a short check is offered) or hard (the settings are not applied; tune again). */ + state: 'fresh' | 'soft' | 'hard' | null; + reasons: string[]; + presets: TunePreset[]; + can_undo: boolean; +} + +export interface TuneProgress { stage: string; text: string | null; minutesLeft: number | null; runsDone: number; runsPlanned: number; elapsedS: number; step: string } + +export interface TuneResult { + summary: string; + outcome?: 'improved' | 'default_confirmed' | 'inconclusive' | 'base_failed' | 'cancelled'; + message?: string; + gain_pct?: number; + seconds?: number; + pairs?: number; + faster_pairs?: number; + base?: { decode_tok_s?: number | null }; + chosen?: { decode_tok_s?: number | null }; + answers?: { class: TunePreset['answers'] extends infer A ? (A extends { class: infer C } ? C : never) : never; fields: string[] }; + preset?: { id: string; name: string } | null; + notes?: string[]; + verdict?: 'keep' | 'retune' | 'inconclusive'; + reason?: string; +} + +const q = (o: Record) => Object.entries(o).filter(([, v]) => v).map(([k, v]) => `${k}=${encodeURIComponent(v as string)}`).join('&'); + +export const tuneStatus = (model: string, resourceProfile: string, vision: string) => + api.get(`/api/native/tune/status?${q({ model, resourceProfile, vision })}`); +export const tunePresetAction = (id: string, action: 'apply' | 'rename' | 'delete' | 'undo', body: Record = {}) => + api.post(`/api/native/tune/presets/${id}/${action}`, body); +export const tuneUndo = (model: string, resourceProfile: string, vision: string) => + api.post('/api/native/tune/undo', { model, resourceProfile, vision }); + +/** The four answer classes, in the words the app uses (the Terminal prints the same sentences). */ +export const ANSWER_NOTICE: Record = { + exact: 'Answers are identical to the standard setup.', + placement: 'Answers may differ slightly from the standard setup.', + nonrepeatable: 'Answers are not repeatable run to run.', + quality: 'Includes a quality setting that changes the numbers.', +}; diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index b4fb4df8..6029e611 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -4,7 +4,7 @@ import type { Hardware, RuntimeModels } from './types'; export interface NativeSize {id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean} -export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;result:Record|null} +export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;result:Record|null;progress?:Record|null} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}} let state:NativeState|null=null,timer:ReturnType|null=null,reading:Promise|null=null; diff --git a/apps/host/src/locales/tune-de.json b/apps/host/src/locales/tune-de.json new file mode 100644 index 00000000..9d3ded55 --- /dev/null +++ b/apps/host/src/locales/tune-de.json @@ -0,0 +1,40 @@ +{ + "tune01": "Dieses Modell abstimmen", + "tune02": "Die schnellsten Einstellungen für deinen PC werden gesucht…", + "tune03": "noch etwa {0} Min.", + "tune04": "Das dauert etwa 20 Minuten.", + "tune05": "Gestoppt. Deine Einstellungen wurden nicht geändert.", + "tune06": "Die Abstimmung wurde nicht abgeschlossen. Deine Einstellungen wurden nicht geändert.", + "tune07": "Noch genauso schnell wie beim Speichern.", + "tune08": "Langsamer als vorher. Du kannst erneut abstimmen.", + "tune09": "Im Moment nicht feststellbar. Deine Abstimmung wurde beibehalten.", + "tune10": "+{0} % schnellere Antworten, gespeichert als „{1}“", + "tune11": "Deine aktuellen Einstellungen sind bereits die schnellsten, die wir gefunden haben.", + "tune12": "Es wurde nichts geändert.", + "tune13": "Gespeichert als „{0}“, deshalb wird beim nächsten Öffnen der App nicht erneut abgestimmt.", + "tune14": "Tempo: {0} → {1} tok/s", + "tune15": "Die Antworten sind mit der Standardeinstellung identisch.", + "tune16": "Die Antworten können leicht von der Standardeinstellung abweichen.", + "tune17": "Die Antworten sind von Lauf zu Lauf nicht wiederholbar.", + "tune18": "Enthält eine Qualitätseinstellung, die die Zahlen verändert.", + "tune19": "Gespeicherte Abstimmung in Gebrauch: {0}", + "tune20": "+{0} % schnellere Antworten", + "tune21": "Dieser PC hat sich seit der Abstimmung verändert, daher werden diese Einstellungen erst nach einer neuen Abstimmung verwendet.", + "tune22": "Dieser PC oder die Engine hat sich seit der Abstimmung verändert. Eine kurze Prüfung dauert etwa 2 Minuten.", + "tune23": "Für diese Auswahl gibt es noch keine gespeicherte Abstimmung.", + "tune24": "Strata probiert auf diesem PC verschiedene Einstellungen aus und behält die, die Antworten schneller machen. Dein Modell wird dabei entladen, und der Computer ist ausgelastet.", + "tune25": "Beende zuerst den aktuellen Vorgang.", + "tune26": "Wie lange soll es dauern?", + "tune27": "Schnell (etwa 20 Minuten)", + "tune28": "Gründlich (bis zu 2 Stunden)", + "tune29": "Was du hauptsächlich machst", + "tune30": "Programmieren mit langen Prompts", + "tune31": "Einstellungen erlauben, die Antworten leicht verändern können", + "tune32": "Gespeicherte Abstimmungen", + "tune33": "In Gebrauch", + "tune34": "Verwenden", + "tune35": "Erneut prüfen (etwa 2 Minuten)", + "tune36": "Erneut abstimmen", + "tune37": "Abstimmung starten", + "tune38": "Dein Modell wird abgestimmt" +} diff --git a/apps/host/src/locales/tune-en.json b/apps/host/src/locales/tune-en.json new file mode 100644 index 00000000..5761db29 --- /dev/null +++ b/apps/host/src/locales/tune-en.json @@ -0,0 +1,40 @@ +{ + "tune01": "Tune this model", + "tune02": "Finding the fastest settings for your PC…", + "tune03": "about {0} min left", + "tune04": "This takes about 20 minutes.", + "tune05": "Stopped. Your settings were not changed.", + "tune06": "The tune did not finish. Your settings were not changed.", + "tune07": "Still as fast as when it was saved.", + "tune08": "It is slower than before. You can tune again.", + "tune09": "Could not tell right now. Your tuning was kept.", + "tune10": "+{0}% faster answers, saved as '{1}'", + "tune11": "Your current settings are already the fastest we found.", + "tune12": "Nothing was changed.", + "tune13": "Saved as '{0}', so it is not tuned again when you reopen the app.", + "tune14": "Speed: {0} → {1} tok/s", + "tune15": "Answers are identical to the standard setup.", + "tune16": "Answers may differ slightly from the standard setup.", + "tune17": "Answers are not repeatable run to run.", + "tune18": "Includes a quality setting that changes the numbers.", + "tune19": "Saved tuning in use: {0}", + "tune20": "+{0}% faster answers", + "tune21": "This PC changed since it was tuned, so these settings are not used until you tune again.", + "tune22": "This PC or the engine changed since it was tuned. A short check takes about 2 minutes.", + "tune23": "No saved tuning for these choices yet.", + "tune24": "Strata tries different settings on this PC and keeps the ones that make answers faster. Your model is unloaded while this runs, and the computer will be busy.", + "tune25": "Finish the current operation first.", + "tune26": "How long to spend", + "tune27": "Quick (about 20 minutes)", + "tune28": "Thorough (up to 2 hours)", + "tune29": "What you mostly do", + "tune30": "Coding with long prompts", + "tune31": "Allow settings that can change answers slightly", + "tune32": "Saved tunings", + "tune33": "In use", + "tune34": "Use", + "tune35": "Check again (about 2 minutes)", + "tune36": "Tune again", + "tune37": "Start tuning", + "tune38": "Tuning your model" +} diff --git a/apps/host/src/locales/tune-es.json b/apps/host/src/locales/tune-es.json new file mode 100644 index 00000000..2466e931 --- /dev/null +++ b/apps/host/src/locales/tune-es.json @@ -0,0 +1,40 @@ +{ + "tune01": "Ajustar este modelo", + "tune02": "Buscando los ajustes más rápidos para tu PC…", + "tune03": "faltan unos {0} min", + "tune04": "Esto tarda unos 20 minutos.", + "tune05": "Detenido. Tus ajustes no se han cambiado.", + "tune06": "El ajuste no terminó. Tus ajustes no se han cambiado.", + "tune07": "Sigue tan rápido como cuando se guardó.", + "tune08": "Es más lento que antes. Puedes volver a ajustar.", + "tune09": "Ahora no se puede saber. Se ha conservado tu ajuste.", + "tune10": "Respuestas un {0} % más rápidas, guardado como «{1}»", + "tune11": "Tus ajustes actuales ya son los más rápidos que hemos encontrado.", + "tune12": "No se ha cambiado nada.", + "tune13": "Guardado como «{0}», así que no se vuelve a ajustar al reabrir la aplicación.", + "tune14": "Velocidad: {0} → {1} tok/s", + "tune15": "Las respuestas son idénticas a las del ajuste estándar.", + "tune16": "Las respuestas pueden diferir ligeramente del ajuste estándar.", + "tune17": "Las respuestas no se repiten de una ejecución a otra.", + "tune18": "Incluye un ajuste de calidad que cambia los números.", + "tune19": "Ajuste guardado en uso: {0}", + "tune20": "Respuestas un {0} % más rápidas", + "tune21": "Este PC ha cambiado desde el ajuste, así que estos ajustes no se usan hasta que vuelvas a ajustar.", + "tune22": "Este PC o el motor han cambiado desde el ajuste. Una comprobación breve tarda unos 2 minutos.", + "tune23": "Todavía no hay un ajuste guardado para estas opciones.", + "tune24": "Strata prueba distintos ajustes en este PC y conserva los que hacen las respuestas más rápidas. Tu modelo se descarga mientras tanto y el ordenador estará ocupado.", + "tune25": "Termina primero la operación actual.", + "tune26": "Cuánto tiempo dedicar", + "tune27": "Rápido (unos 20 minutos)", + "tune28": "A fondo (hasta 2 horas)", + "tune29": "Qué haces sobre todo", + "tune30": "Programar con prompts largos", + "tune31": "Permitir ajustes que pueden cambiar ligeramente las respuestas", + "tune32": "Ajustes guardados", + "tune33": "En uso", + "tune34": "Usar", + "tune35": "Comprobar de nuevo (unos 2 minutos)", + "tune36": "Ajustar de nuevo", + "tune37": "Empezar a ajustar", + "tune38": "Ajustando tu modelo" +} diff --git a/apps/host/src/locales/tune-ja.json b/apps/host/src/locales/tune-ja.json new file mode 100644 index 00000000..186a7850 --- /dev/null +++ b/apps/host/src/locales/tune-ja.json @@ -0,0 +1,40 @@ +{ + "tune01": "このモデルをチューニング", + "tune02": "あなたの PC で最も速い設定を探しています…", + "tune03": "残り約 {0} 分", + "tune04": "約 20 分かかります。", + "tune05": "停止しました。設定は変更されていません。", + "tune06": "チューニングが完了しませんでした。設定は変更されていません。", + "tune07": "保存したときと同じ速さを保っています。", + "tune08": "以前より遅くなっています。もう一度チューニングできます。", + "tune09": "今は判断できませんでした。チューニング結果はそのまま保持しています。", + "tune10": "回答が {0}% 速くなりました。「{1}」として保存しました", + "tune11": "現在の設定が、見つかった中で最も速い設定です。", + "tune12": "何も変更されませんでした。", + "tune13": "「{0}」として保存しました。アプリを開き直しても再チューニングはしません。", + "tune14": "速度:{0} → {1} tok/s", + "tune15": "回答は標準設定と完全に同じです。", + "tune16": "回答が標準設定とわずかに異なることがあります。", + "tune17": "回答は実行ごとに同じになるとは限りません。", + "tune18": "数値を変える品質設定が含まれています。", + "tune19": "使用中の保存済みチューニング:{0}", + "tune20": "回答が {0}% 速くなりました", + "tune21": "チューニング後にこの PC が変わったため、もう一度チューニングするまでこの設定は使われません。", + "tune22": "チューニング後にこの PC またはエンジンが変わりました。簡易チェックは約 2 分です。", + "tune23": "この選択に対する保存済みチューニングはまだありません。", + "tune24": "Strata はこの PC でさまざまな設定を試し、回答が速くなるものを残します。実行中はモデルがアンロードされ、コンピューターは負荷が高くなります。", + "tune25": "先に現在の操作を終えてください。", + "tune26": "かける時間", + "tune27": "クイック(約 20 分)", + "tune28": "じっくり(最大 2 時間)", + "tune29": "主な用途", + "tune30": "長いプロンプトでのコーディング", + "tune31": "回答がわずかに変わる可能性のある設定も許可する", + "tune32": "保存済みチューニング", + "tune33": "使用中", + "tune34": "使用する", + "tune35": "もう一度チェック(約 2 分)", + "tune36": "もう一度チューニング", + "tune37": "チューニングを開始", + "tune38": "モデルをチューニング中" +} diff --git a/apps/host/src/locales/tune-ko.json b/apps/host/src/locales/tune-ko.json new file mode 100644 index 00000000..0dfccea9 --- /dev/null +++ b/apps/host/src/locales/tune-ko.json @@ -0,0 +1,40 @@ +{ + "tune01": "이 모델 최적화", + "tune02": "내 PC에서 가장 빠른 설정을 찾는 중…", + "tune03": "약 {0}분 남음", + "tune04": "약 20분 걸립니다.", + "tune05": "중지되었습니다. 설정이 변경되지 않았습니다.", + "tune06": "최적화가 완료되지 않았습니다. 설정이 변경되지 않았습니다.", + "tune07": "저장할 때와 같은 속도를 유지하고 있습니다.", + "tune08": "이전보다 느려졌습니다. 다시 최적화할 수 있습니다.", + "tune09": "지금은 판단할 수 없습니다. 최적화 결과는 유지되었습니다.", + "tune10": "답변이 {0}% 빨라졌습니다. ‘{1}’(으)로 저장됨", + "tune11": "현재 설정이 찾은 것 중 이미 가장 빠른 설정입니다.", + "tune12": "아무것도 변경되지 않았습니다.", + "tune13": "‘{0}’(으)로 저장되었으므로 앱을 다시 열어도 다시 최적화하지 않습니다.", + "tune14": "속도: {0} → {1} tok/s", + "tune15": "답변은 표준 설정과 동일합니다.", + "tune16": "답변이 표준 설정과 조금 다를 수 있습니다.", + "tune17": "답변이 실행마다 동일하지 않습니다.", + "tune18": "숫자를 바꾸는 품질 설정이 포함되어 있습니다.", + "tune19": "사용 중인 저장된 최적화: {0}", + "tune20": "답변이 {0}% 빨라졌습니다", + "tune21": "최적화 이후 이 PC가 변경되어 다시 최적화할 때까지 이 설정은 사용되지 않습니다.", + "tune22": "최적화 이후 이 PC 또는 엔진이 변경되었습니다. 간단 점검은 약 2분 걸립니다.", + "tune23": "이 선택에 대해 저장된 최적화가 아직 없습니다.", + "tune24": "Strata는 이 PC에서 여러 설정을 시험하고 답변을 더 빠르게 하는 설정만 남깁니다. 실행하는 동안 모델이 언로드되고 컴퓨터가 바쁝니다.", + "tune25": "먼저 현재 작업을 끝내세요.", + "tune26": "얼마나 오래 할까요", + "tune27": "빠름 (약 20분)", + "tune28": "꼼꼼히 (최대 2시간)", + "tune29": "주로 하는 일", + "tune30": "긴 프롬프트로 코딩", + "tune31": "답변을 조금 바꿀 수 있는 설정 허용", + "tune32": "저장된 최적화", + "tune33": "사용 중", + "tune34": "사용", + "tune35": "다시 점검 (약 2분)", + "tune36": "다시 최적화", + "tune37": "최적화 시작", + "tune38": "모델을 최적화하는 중" +} diff --git a/apps/host/src/locales/tune-pt.json b/apps/host/src/locales/tune-pt.json new file mode 100644 index 00000000..a5a5ded5 --- /dev/null +++ b/apps/host/src/locales/tune-pt.json @@ -0,0 +1,40 @@ +{ + "tune01": "Ajustar este modelo", + "tune02": "Procurando as configurações mais rápidas para o seu PC…", + "tune03": "faltam cerca de {0} min", + "tune04": "Isso leva cerca de 20 minutos.", + "tune05": "Interrompido. Suas configurações não foram alteradas.", + "tune06": "O ajuste não terminou. Suas configurações não foram alteradas.", + "tune07": "Continua tão rápido quanto quando foi salvo.", + "tune08": "Está mais lento do que antes. Você pode ajustar de novo.", + "tune09": "Não foi possível saber agora. Seu ajuste foi mantido.", + "tune10": "Respostas {0} % mais rápidas, salvo como “{1}”", + "tune11": "Suas configurações atuais já são as mais rápidas que encontramos.", + "tune12": "Nada foi alterado.", + "tune13": "Salvo como “{0}”, então não é ajustado de novo quando você reabre o app.", + "tune14": "Velocidade: {0} → {1} tok/s", + "tune15": "As respostas são idênticas às da configuração padrão.", + "tune16": "As respostas podem diferir um pouco da configuração padrão.", + "tune17": "As respostas não se repetem de uma execução para outra.", + "tune18": "Inclui uma configuração de qualidade que muda os números.", + "tune19": "Ajuste salvo em uso: {0}", + "tune20": "Respostas {0} % mais rápidas", + "tune21": "Este PC mudou desde o ajuste, então estas configurações não são usadas até você ajustar de novo.", + "tune22": "Este PC ou o motor mudou desde o ajuste. Uma verificação rápida leva cerca de 2 minutos.", + "tune23": "Ainda não há ajuste salvo para estas escolhas.", + "tune24": "O Strata testa configurações diferentes neste PC e mantém as que deixam as respostas mais rápidas. Seu modelo é descarregado enquanto isso e o computador fica ocupado.", + "tune25": "Termine primeiro a operação atual.", + "tune26": "Quanto tempo dedicar", + "tune27": "Rápido (cerca de 20 minutos)", + "tune28": "Completo (até 2 horas)", + "tune29": "O que você mais faz", + "tune30": "Programação com prompts longos", + "tune31": "Permitir configurações que podem mudar um pouco as respostas", + "tune32": "Ajustes salvos", + "tune33": "Em uso", + "tune34": "Usar", + "tune35": "Verificar de novo (cerca de 2 minutos)", + "tune36": "Ajustar de novo", + "tune37": "Iniciar ajuste", + "tune38": "Ajustando o seu modelo" +} diff --git a/apps/host/src/locales/tune-ru.json b/apps/host/src/locales/tune-ru.json new file mode 100644 index 00000000..07b12e50 --- /dev/null +++ b/apps/host/src/locales/tune-ru.json @@ -0,0 +1,40 @@ +{ + "tune01": "Настроить эту модель", + "tune02": "Ищем самые быстрые настройки для вашего ПК…", + "tune03": "осталось примерно {0} мин.", + "tune04": "Это займёт около 20 минут.", + "tune05": "Остановлено. Ваши настройки не изменились.", + "tune06": "Настройка не завершилась. Ваши настройки не изменились.", + "tune07": "Всё так же быстро, как при сохранении.", + "tune08": "Сейчас медленнее, чем раньше. Можно настроить заново.", + "tune09": "Сейчас не удалось определить. Ваша настройка сохранена.", + "tune10": "Ответы быстрее на {0}%, сохранено как «{1}»", + "tune11": "Ваши текущие настройки уже самые быстрые из найденных.", + "tune12": "Ничего не изменено.", + "tune13": "Сохранено как «{0}», поэтому при повторном открытии приложения настройка не будет повторяться.", + "tune14": "Скорость: {0} → {1} tok/s", + "tune15": "Ответы такие же, как при стандартных настройках.", + "tune16": "Ответы могут немного отличаться от стандартных настроек.", + "tune17": "Ответы не повторяются от запуска к запуску.", + "tune18": "Включает настройку качества, которая меняет числа.", + "tune19": "Используется сохранённая настройка: {0}", + "tune20": "Ответы быстрее на {0}%", + "tune21": "С момента настройки этот ПК изменился, поэтому эти настройки не используются, пока вы не настроите заново.", + "tune22": "С момента настройки этот ПК или движок изменились. Короткая проверка займёт около 2 минут.", + "tune23": "Для этих параметров пока нет сохранённой настройки.", + "tune24": "Strata пробует на этом ПК разные настройки и оставляет те, что ускоряют ответы. Пока это идёт, модель выгружена, а компьютер занят.", + "tune25": "Сначала завершите текущую операцию.", + "tune26": "Сколько времени потратить", + "tune27": "Быстро (около 20 минут)", + "tune28": "Тщательно (до 2 часов)", + "tune29": "Чем вы в основном занимаетесь", + "tune30": "Программирование с длинными промптами", + "tune31": "Разрешить настройки, которые могут немного изменить ответы", + "tune32": "Сохранённые настройки", + "tune33": "Используется", + "tune34": "Использовать", + "tune35": "Проверить снова (около 2 минут)", + "tune36": "Настроить снова", + "tune37": "Начать настройку", + "tune38": "Настройка вашей модели" +} diff --git a/apps/host/src/locales/tune-zh.json b/apps/host/src/locales/tune-zh.json new file mode 100644 index 00000000..740e69bf --- /dev/null +++ b/apps/host/src/locales/tune-zh.json @@ -0,0 +1,40 @@ +{ + "tune01": "调优此模型", + "tune02": "正在为你的电脑寻找最快的设置…", + "tune03": "还剩约 {0} 分钟", + "tune04": "这大约需要 20 分钟。", + "tune05": "已停止。你的设置没有改变。", + "tune06": "调优未完成。你的设置没有改变。", + "tune07": "仍然和保存时一样快。", + "tune08": "比以前慢了。你可以再次调优。", + "tune09": "目前无法判断。已保留你的调优结果。", + "tune10": "回答快了 {0}%,已保存为“{1}”", + "tune11": "你当前的设置已经是我们找到的最快设置。", + "tune12": "没有做任何改动。", + "tune13": "已保存为“{0}”,重新打开应用时不会再次调优。", + "tune14": "速度:{0} → {1} tok/s", + "tune15": "回答与标准设置完全相同。", + "tune16": "回答可能与标准设置略有不同。", + "tune17": "每次运行的回答不一定相同。", + "tune18": "包含会改变数值的质量设置。", + "tune19": "正在使用的已保存调优:{0}", + "tune20": "回答快了 {0}%", + "tune21": "自调优以来这台电脑发生了变化,因此在你再次调优之前不会使用这些设置。", + "tune22": "自调优以来这台电脑或引擎发生了变化。快速检查大约需要 2 分钟。", + "tune23": "这些选择还没有已保存的调优。", + "tune24": "Strata 会在这台电脑上尝试不同的设置,并保留能让回答更快的设置。运行期间模型会被卸载,电脑会比较忙。", + "tune25": "请先完成当前操作。", + "tune26": "花多长时间", + "tune27": "快速(约 20 分钟)", + "tune28": "彻底(最多 2 小时)", + "tune29": "你主要做什么", + "tune30": "长提示的编程", + "tune31": "允许可能略微改变回答的设置", + "tune32": "已保存的调优", + "tune33": "使用中", + "tune34": "使用", + "tune35": "再次检查(约 2 分钟)", + "tune36": "再次调优", + "tune37": "开始调优", + "tune38": "正在调优你的模型" +} diff --git a/apps/host/tests/tune-locales.test.mjs b/apps/host/tests/tune-locales.test.mjs new file mode 100644 index 00000000..a27bf2d1 --- /dev/null +++ b/apps/host/tests/tune-locales.test.mjs @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; + +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tune-${l}.json`, 'utf8'))]))); +const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); +const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); +const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); +const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('the Tune dialog strings exist in every language with the same slots and no empty text', () => { + for (const l of languages) { + assert.deepEqual(Object.keys(catalogs[l]), Object.keys(catalogs.en), l); + for (const [id, source] of Object.entries(catalogs.en)) { + assert.ok(catalogs[l][id].trim(), `${l}:${id} is empty`); + assert.deepEqual(slots(catalogs[l][id]), slots(source), `${l}:${id}`); + } + } +}); + +test('the Tune strings do not collide with the main catalog ids or texts, and translate through tr()', () => { + const mainTexts = new Set(Object.values(main)); + for (const [id, text] of Object.entries(catalogs.en)) { + assert.ok(!(id in main), id); + assert.ok(!mainTexts.has(text), `already in the main catalog: ${text}`); + } + setTranslationLanguage('de'); + assert.equal(tr('Tune this model'), catalogs.de.tune01); + assert.equal(tr('about {0} min left', [7]), catalogs.de.tune03.replace('{0}', '7')); + assert.equal(tr("+{0}% faster answers, saved as '{1}'", [12, 'IQ3_S 128K']), catalogs.de.tune10.replace('{0}', '12').replace('{1}', 'IQ3_S 128K')); + setTranslationLanguage('en'); + assert.equal(tr('Tune this model'), 'Tune this model'); +}); From aab3810b549e7c8cea2b658ed87f2f0be020bc6f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:03:41 +0200 Subject: [PATCH 08/18] tuner: the GPU cache's 'resident experts' wording is not the low-RAM resident mode --- strata_control/tune_knobs.py | 4 ++-- strata_control/tune_session.py | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/strata_control/tune_knobs.py b/strata_control/tune_knobs.py index 5785f88c..b6a296dd 100644 --- a/strata_control/tune_knobs.py +++ b/strata_control/tune_knobs.py @@ -193,7 +193,7 @@ class Context: def condition_holds(name: str, ctx: Context) -> bool: f = ctx.facts return { - "resident_ram": bool(f.get("resident_ram")), + "resident_ram": bool(f.get("resident_ram")) or "--resident-experts" in ctx.base_args, "one_gpu": ctx.gpu_count <= 1, "two_gpus": ctx.gpu_count == 2, "hybrid_cpu": ctx.hybrid_cpu, @@ -214,7 +214,7 @@ def machine_classes(ctx: Context) -> list[str]: return classes if ctx.backend == "sycl": return ["G"] - if ctx.facts.get("resident_ram") or (ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 12): + if condition_holds("resident_ram", ctx) or (ctx.ram_gib and ctx.model_gib and ctx.ram_gib - ctx.model_gib < 12): classes.append("A") classes.append("B" if ctx.vram_mib >= 24000 else "C") if ctx.hybrid_cpu: diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index bef618bf..54232e4b 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -119,7 +119,8 @@ def parse_facts(text: str) -> dict[str, Any]: if "workers" not in facts and "cpu_threads" in facts: facts["workers"] = facts["cpu_threads"] low = text.lower() - facts["resident_ram"] = bool(re.search(r"resident[- ](?:ram|experts)|low-ram mode|resident ram", low)) + # the engine's low-RAM resident mode (--resident-experts) says so in its log; "resident experts" alone is the GPU cache's own wording + facts["resident_ram"] = bool(re.search(r"resident ram mode|resident complement|resident [\d.]+ gib, pinned|low-ram mode", low)) facts["hybrid_experts"] = "hybrid experts" in low or "hybrid:" in low facts["unknown_argument"] = bool(re.search(r"unknown argument|unrecognized (?:argument|option)", low)) return facts From 5f054d2a2c1277ab2755ff602b83616e597f310b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:04:17 +0200 Subject: [PATCH 09/18] tests: resident-mode detection --- tests/tuning/test_session.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/tuning/test_session.py b/tests/tuning/test_session.py index 9d6a526e..3474b801 100644 --- a/tests/tuning/test_session.py +++ b/tests/tuning/test_session.py @@ -104,6 +104,10 @@ class ParsingTest(unittest.TestCase): self.assertEqual(failure_kind("", -9)[0], "OOM") self.assertEqual(failure_kind("something else broke", 1)[0], "FAIL_BOOT") + def test_gpu_cache_wording_is_not_the_low_ram_mode(self): + self.assertFalse(parse_facts("R4 hit path ON - resident experts are computed on the GPU")["resident_ram"]) + self.assertTrue(parse_facts("WARNING: the whole resident RAM mode does not fit (FileExpertSource: resident complement 34.47 GiB")["resident_ram"]) + def test_facts(self): f = parse_facts("strata generate: 6 CPU threads\nhybrid experts: 37% on the GPU\n") self.assertEqual(f["workers"], 6) From 7d43470f319df1966eb7497c099f17c7db15d8e4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:10:56 +0200 Subject: [PATCH 10/18] app: Tune dialog tidy, short Check again label; headless UI fixture for it --- apps/host/scripts/make-tune-locales.py | 7 +++ apps/host/src/components/NativeTune.tsx | 6 +-- apps/host/src/locales/tune-de.json | 2 +- apps/host/src/locales/tune-en.json | 2 +- apps/host/src/locales/tune-es.json | 2 +- apps/host/src/locales/tune-ja.json | 2 +- apps/host/src/locales/tune-ko.json | 2 +- apps/host/src/locales/tune-pt.json | 2 +- apps/host/src/locales/tune-ru.json | 2 +- apps/host/src/locales/tune-zh.json | 2 +- apps/host/tests/fixtures/tune-ui-host.mjs | 66 +++++++++++++++++++++++ 11 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 apps/host/tests/fixtures/tune-ui-host.mjs diff --git a/apps/host/scripts/make-tune-locales.py b/apps/host/scripts/make-tune-locales.py index f7a186f0..c364a66d 100644 --- a/apps/host/scripts/make-tune-locales.py +++ b/apps/host/scripts/make-tune-locales.py @@ -159,6 +159,13 @@ T = { ], } +# the "Check again" button keeps to one short line; the 2 minutes are said in the sentence above it +import re as _re +_i = KEYS.index("Check again (about 2 minutes)") +KEYS[_i] = "Check again" +for _v in T.values(): + _v[_i] = _re.split(r"\s*[((]", _v[_i])[0].strip() + out = Path(__file__).resolve().parent.parent / "src" / "locales" ids = [f"tune{i + 1:02d}" for i in range(len(KEYS))] for lang, values in T.items(): diff --git a/apps/host/src/components/NativeTune.tsx b/apps/host/src/components/NativeTune.tsx index 94fb95ee..75b366a9 100644 --- a/apps/host/src/components/NativeTune.tsx +++ b/apps/host/src/components/NativeTune.tsx @@ -80,7 +80,7 @@ export function NativeTune({ open, onClose, model, resourceProfile, vision }: { const stale = active && status?.state && status.state !== 'fresh'; body =
{error ?

{error}

: null} - {active ?

{tr("Saved tuning in use: {0}", [active.name])}

+ {active ?

{tr("Saved tuning in use: {0}", [active.name])}

{active.gain_pct ?

{tr("+{0}% faster answers", [Math.round(active.gain_pct)])}

: null} {notice(active.answers?.class)} {stale ?

{status?.state === 'hard' ? tr("This PC changed since it was tuned, so these settings are not used until you tune again.") : tr("This PC or the engine changed since it was tuned. A short check takes about 2 minutes.")}

: null}
@@ -99,9 +99,9 @@ export function NativeTune({ open, onClose, model, resourceProfile, vision }: { : null} {renaming ?
setName(e.target.value)}/> void act(async () => { await tunePresetAction(renaming.id, 'rename', { name: name.trim() }); setRenaming(null); })}>{tr("Save")} setRenaming(null)}>{tr("Cancel")}
: null}
; - actions = <>{tr("Close")} + actions = <> {status?.can_undo ? void act(async () => { await tuneUndo(model, resourceProfile, vision); })}>{tr("Undo")} : null} - {active && status?.state === 'soft' ? void start('recheck')}>{tr("Check again (about 2 minutes)")} : null} + {active && status?.state === 'soft' ? void start('recheck')}>{tr("Check again")} : null} void start('autotune')}>{tr(active ? "Tune again" : "Start tuning")}; } return {body}; diff --git a/apps/host/src/locales/tune-de.json b/apps/host/src/locales/tune-de.json index 9d3ded55..2b95ea11 100644 --- a/apps/host/src/locales/tune-de.json +++ b/apps/host/src/locales/tune-de.json @@ -33,7 +33,7 @@ "tune32": "Gespeicherte Abstimmungen", "tune33": "In Gebrauch", "tune34": "Verwenden", - "tune35": "Erneut prüfen (etwa 2 Minuten)", + "tune35": "Erneut prüfen", "tune36": "Erneut abstimmen", "tune37": "Abstimmung starten", "tune38": "Dein Modell wird abgestimmt" diff --git a/apps/host/src/locales/tune-en.json b/apps/host/src/locales/tune-en.json index 5761db29..969cf56e 100644 --- a/apps/host/src/locales/tune-en.json +++ b/apps/host/src/locales/tune-en.json @@ -33,7 +33,7 @@ "tune32": "Saved tunings", "tune33": "In use", "tune34": "Use", - "tune35": "Check again (about 2 minutes)", + "tune35": "Check again", "tune36": "Tune again", "tune37": "Start tuning", "tune38": "Tuning your model" diff --git a/apps/host/src/locales/tune-es.json b/apps/host/src/locales/tune-es.json index 2466e931..2dd19940 100644 --- a/apps/host/src/locales/tune-es.json +++ b/apps/host/src/locales/tune-es.json @@ -33,7 +33,7 @@ "tune32": "Ajustes guardados", "tune33": "En uso", "tune34": "Usar", - "tune35": "Comprobar de nuevo (unos 2 minutos)", + "tune35": "Comprobar de nuevo", "tune36": "Ajustar de nuevo", "tune37": "Empezar a ajustar", "tune38": "Ajustando tu modelo" diff --git a/apps/host/src/locales/tune-ja.json b/apps/host/src/locales/tune-ja.json index 186a7850..8420fa7b 100644 --- a/apps/host/src/locales/tune-ja.json +++ b/apps/host/src/locales/tune-ja.json @@ -33,7 +33,7 @@ "tune32": "保存済みチューニング", "tune33": "使用中", "tune34": "使用する", - "tune35": "もう一度チェック(約 2 分)", + "tune35": "もう一度チェック", "tune36": "もう一度チューニング", "tune37": "チューニングを開始", "tune38": "モデルをチューニング中" diff --git a/apps/host/src/locales/tune-ko.json b/apps/host/src/locales/tune-ko.json index 0dfccea9..9b352c29 100644 --- a/apps/host/src/locales/tune-ko.json +++ b/apps/host/src/locales/tune-ko.json @@ -33,7 +33,7 @@ "tune32": "저장된 최적화", "tune33": "사용 중", "tune34": "사용", - "tune35": "다시 점검 (약 2분)", + "tune35": "다시 점검", "tune36": "다시 최적화", "tune37": "최적화 시작", "tune38": "모델을 최적화하는 중" diff --git a/apps/host/src/locales/tune-pt.json b/apps/host/src/locales/tune-pt.json index a5a5ded5..22da2023 100644 --- a/apps/host/src/locales/tune-pt.json +++ b/apps/host/src/locales/tune-pt.json @@ -33,7 +33,7 @@ "tune32": "Ajustes salvos", "tune33": "Em uso", "tune34": "Usar", - "tune35": "Verificar de novo (cerca de 2 minutos)", + "tune35": "Verificar de novo", "tune36": "Ajustar de novo", "tune37": "Iniciar ajuste", "tune38": "Ajustando o seu modelo" diff --git a/apps/host/src/locales/tune-ru.json b/apps/host/src/locales/tune-ru.json index 07b12e50..7bf326d6 100644 --- a/apps/host/src/locales/tune-ru.json +++ b/apps/host/src/locales/tune-ru.json @@ -33,7 +33,7 @@ "tune32": "Сохранённые настройки", "tune33": "Используется", "tune34": "Использовать", - "tune35": "Проверить снова (около 2 минут)", + "tune35": "Проверить снова", "tune36": "Настроить снова", "tune37": "Начать настройку", "tune38": "Настройка вашей модели" diff --git a/apps/host/src/locales/tune-zh.json b/apps/host/src/locales/tune-zh.json index 740e69bf..6ac7e66e 100644 --- a/apps/host/src/locales/tune-zh.json +++ b/apps/host/src/locales/tune-zh.json @@ -33,7 +33,7 @@ "tune32": "已保存的调优", "tune33": "使用中", "tune34": "使用", - "tune35": "再次检查(约 2 分钟)", + "tune35": "再次检查", "tune36": "再次调优", "tune37": "开始调优", "tune38": "正在调优你的模型" diff --git a/apps/host/tests/fixtures/tune-ui-host.mjs b/apps/host/tests/fixtures/tune-ui-host.mjs new file mode 100644 index 00000000..8ba9d59a --- /dev/null +++ b/apps/host/tests/fixtures/tune-ui-host.mjs @@ -0,0 +1,66 @@ +/** Disposable UI fixture for the Tune model dialog: the real native control over fake models, and a pretend `strata` command that + * reports progress and a result after a few seconds. No weights, no engine. Needs the demo host on 5161 and a built dist. */ +import http from 'node:http'; +import { readFile, writeFile } from 'node:fs/promises'; +import { writeFileSync } from 'node:fs'; +import { resolve, extname } from 'node:path'; +import { nativeFixture } from '../helpers/native-fixture.mjs'; + +const arg = (a, n) => { const i = a.indexOf(n); return i < 0 ? undefined : a[i + 1]; }; +let saved = []; +const slot = 'fixture-slot'; +function status() { + const active = saved.find(p => p.active) ?? null; + return { ok: true, slot, suggested_name: 'IQ2_XS 32K – Work', active, state: active ? 'soft' : null, reasons: active ? ['the graphics driver changed'] : [], presets: saved, can_undo: saved.length > 0 }; +} +const stages = [[0, 'Measuring your current settings', 9], [2000, 'Trying: Run the control thread on the last CPU core (round 1 of 2)', 7], [4000, 'Trying: Pin memory only when needed (round 2 of 2)', 3]]; +const handler = (child, args) => { + const cmd = args.slice(args.findIndex(a => String(a).endsWith('strata.py')) + 1); + const out = json => { child.stdout.emit('data', Buffer.from(JSON.stringify(json))); child.exitCode = 0; child.emit('exit', 0); child.emit('close', 0); }; + if (cmd[0] === 'presets') { + if (cmd[1] === 'status') return out(status()); + if (cmd[1] === 'list') return out({ ok: true, presets: saved }); + const id = cmd[2]; + if (cmd[1] === 'apply') saved = saved.map(p => ({ ...p, active: p.id === id })); + if (cmd[1] === 'delete') saved = saved.filter(p => p.id !== id); + if (cmd[1] === 'rename') saved = saved.map(p => p.id === id ? { ...p, name: cmd[3] } : p); + if (cmd[1] === 'undo') saved = saved.slice(1); + return out({ ok: true }); + } + if (cmd[0] === 'tune') { + const sf = arg(cmd, '--status-file'); + stages.forEach(([at, step, left], i) => setTimeout(() => { try { writeFileSync(sf, JSON.stringify({ state: 'running', stage: 'rounds', text: `Finding the fastest settings for your PC… about ${left} min left`, minutes_left: left, runs_done: i * 2 + 1, runs_planned: 8, message: step })); } catch { /* gone */ } }, at)); + setTimeout(() => { + const preset = { id: 'c'.repeat(32), name: 'IQ2_XS 32K – Work', active: true, gain_pct: 11.6, answers: { class: 'exact', fields: [] } }; + saved = [preset, ...saved.map(p => ({ ...p, active: false }))]; + out({ ok: true, result: { outcome: 'improved', gain_pct: 11.6, seconds: 1100, preset, answers: { class: 'exact', fields: [] }, base: { decode_tok_s: 54.2 }, chosen: { decode_tok_s: 60.5 }, pairs: 2, faster_pairs: 2 } }); + }, 7000); + } +}; +const fixture = nativeFixture({ tuneHandler: handler }); +const control = fixture.control, root = resolve(import.meta.dirname, '../../dist'), upstream = 'http://127.0.0.1:5161'; +await control.refresh(true); +const server = http.createServer(async (req, res) => { + try { + const url = new URL(req.url, 'http://fixture'), path = url.pathname; + let text = ''; if (req.method !== 'GET') for await (const chunk of req) text += chunk; + const body = text ? JSON.parse(text) : {}; + const json = value => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(value)); }; + if (path === '/__fixture/capture' && req.method === 'POST') { await writeFile(process.env.TUNE_SHOT_DIR + '/' + body.name + '.png', Buffer.from(body.data, 'base64')); return json({ ok: true }); } + if (path === '/api/native' && req.method === 'GET') return json(await control.refresh()); + if (path === '/api/native/operations') return json(control.operation(body.kind, body.args)); + if (path === '/api/native/tune/status') return json(await control.tuneStatus({ model: url.searchParams.get('model'), resourceProfile: url.searchParams.get('resourceProfile') || undefined, vision: url.searchParams.get('vision') || undefined })); + if (path === '/api/native/tune/undo') return json(await control.tunePresets.undoFor(body)); + let m = /^\/api\/native\/tune\/presets\/([0-9a-f]+)\/(apply|rename|delete|undo)$/.exec(path); if (m) return json(await control.tunePresets.action(m[2], m[1], body)); + m = /^\/api\/native\/operations\/([^/]+)\/cancel$/.exec(path); if (m) return json(await control.cancel(m[1])); + if (path === '/api/native/benchmark') return json(control.benchmarkReport()); + if (path === '/api/hardware') { const v = await (await fetch(upstream + path)).json(); return json({ ...v, gpus: [{ index: 0, id: 'gpu-0', vendor: 'nvidia', name: 'NVIDIA RTX 4090', vramGb: 24, backend: 'cuda', unified: false }] }); } + if (path.startsWith('/api/')) { const r = await fetch(upstream + req.url, { method: req.method, headers: text ? { 'content-type': 'application/json' } : {}, body: text || undefined }); res.writeHead(r.status, { 'content-type': r.headers.get('content-type') ?? 'application/json' }); res.end(Buffer.from(await r.arrayBuffer())); return; } + const file = path === '/' ? '/index.html' : path; if (file.includes('..')) throw new Error('Invalid fixture path'); + const content = await readFile(root + file); + res.writeHead(200, { 'content-type': ({ '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.png': 'image/png' })[extname(file)] ?? 'application/octet-stream' }); res.end(content); + } catch (e) { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: e.message })); } +}); +server.listen(Number(process.env.TUNE_UI_PORT ?? 5270), '127.0.0.1', () => console.log('Tune UI fixture ready')); +let stopping = false; async function stop() { if (stopping) return; stopping = true; server.closeAllConnections(); server.close(); await fixture.cleanup(); process.exit(0); } +process.on('SIGTERM', stop); process.on('SIGINT', stop); From ff62ce3fbe330d7688add6a0a7f4fde151e04b59 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:11:15 +0200 Subject: [PATCH 11/18] app: Tune strings without the duplicate Check again --- apps/host/scripts/make-tune-locales.py | 7 +++---- apps/host/src/locales/tune-de.json | 7 +++---- apps/host/src/locales/tune-en.json | 7 +++---- apps/host/src/locales/tune-es.json | 7 +++---- apps/host/src/locales/tune-ja.json | 7 +++---- apps/host/src/locales/tune-ko.json | 7 +++---- apps/host/src/locales/tune-pt.json | 7 +++---- apps/host/src/locales/tune-ru.json | 7 +++---- apps/host/src/locales/tune-zh.json | 7 +++---- 9 files changed, 27 insertions(+), 36 deletions(-) diff --git a/apps/host/scripts/make-tune-locales.py b/apps/host/scripts/make-tune-locales.py index c364a66d..dfd95870 100644 --- a/apps/host/scripts/make-tune-locales.py +++ b/apps/host/scripts/make-tune-locales.py @@ -159,12 +159,11 @@ T = { ], } -# the "Check again" button keeps to one short line; the 2 minutes are said in the sentence above it -import re as _re +# "Check again" already exists in the main catalog: drop it from this one _i = KEYS.index("Check again (about 2 minutes)") -KEYS[_i] = "Check again" +del KEYS[_i] for _v in T.values(): - _v[_i] = _re.split(r"\s*[((]", _v[_i])[0].strip() + del _v[_i] out = Path(__file__).resolve().parent.parent / "src" / "locales" ids = [f"tune{i + 1:02d}" for i in range(len(KEYS))] diff --git a/apps/host/src/locales/tune-de.json b/apps/host/src/locales/tune-de.json index 2b95ea11..92462ccc 100644 --- a/apps/host/src/locales/tune-de.json +++ b/apps/host/src/locales/tune-de.json @@ -33,8 +33,7 @@ "tune32": "Gespeicherte Abstimmungen", "tune33": "In Gebrauch", "tune34": "Verwenden", - "tune35": "Erneut prüfen", - "tune36": "Erneut abstimmen", - "tune37": "Abstimmung starten", - "tune38": "Dein Modell wird abgestimmt" + "tune35": "Erneut abstimmen", + "tune36": "Abstimmung starten", + "tune37": "Dein Modell wird abgestimmt" } diff --git a/apps/host/src/locales/tune-en.json b/apps/host/src/locales/tune-en.json index 969cf56e..30e2b76c 100644 --- a/apps/host/src/locales/tune-en.json +++ b/apps/host/src/locales/tune-en.json @@ -33,8 +33,7 @@ "tune32": "Saved tunings", "tune33": "In use", "tune34": "Use", - "tune35": "Check again", - "tune36": "Tune again", - "tune37": "Start tuning", - "tune38": "Tuning your model" + "tune35": "Tune again", + "tune36": "Start tuning", + "tune37": "Tuning your model" } diff --git a/apps/host/src/locales/tune-es.json b/apps/host/src/locales/tune-es.json index 2dd19940..6c8df85d 100644 --- a/apps/host/src/locales/tune-es.json +++ b/apps/host/src/locales/tune-es.json @@ -33,8 +33,7 @@ "tune32": "Ajustes guardados", "tune33": "En uso", "tune34": "Usar", - "tune35": "Comprobar de nuevo", - "tune36": "Ajustar de nuevo", - "tune37": "Empezar a ajustar", - "tune38": "Ajustando tu modelo" + "tune35": "Ajustar de nuevo", + "tune36": "Empezar a ajustar", + "tune37": "Ajustando tu modelo" } diff --git a/apps/host/src/locales/tune-ja.json b/apps/host/src/locales/tune-ja.json index 8420fa7b..87c74abf 100644 --- a/apps/host/src/locales/tune-ja.json +++ b/apps/host/src/locales/tune-ja.json @@ -33,8 +33,7 @@ "tune32": "保存済みチューニング", "tune33": "使用中", "tune34": "使用する", - "tune35": "もう一度チェック", - "tune36": "もう一度チューニング", - "tune37": "チューニングを開始", - "tune38": "モデルをチューニング中" + "tune35": "もう一度チューニング", + "tune36": "チューニングを開始", + "tune37": "モデルをチューニング中" } diff --git a/apps/host/src/locales/tune-ko.json b/apps/host/src/locales/tune-ko.json index 9b352c29..8faca5ad 100644 --- a/apps/host/src/locales/tune-ko.json +++ b/apps/host/src/locales/tune-ko.json @@ -33,8 +33,7 @@ "tune32": "저장된 최적화", "tune33": "사용 중", "tune34": "사용", - "tune35": "다시 점검", - "tune36": "다시 최적화", - "tune37": "최적화 시작", - "tune38": "모델을 최적화하는 중" + "tune35": "다시 최적화", + "tune36": "최적화 시작", + "tune37": "모델을 최적화하는 중" } diff --git a/apps/host/src/locales/tune-pt.json b/apps/host/src/locales/tune-pt.json index 22da2023..39359010 100644 --- a/apps/host/src/locales/tune-pt.json +++ b/apps/host/src/locales/tune-pt.json @@ -33,8 +33,7 @@ "tune32": "Ajustes salvos", "tune33": "Em uso", "tune34": "Usar", - "tune35": "Verificar de novo", - "tune36": "Ajustar de novo", - "tune37": "Iniciar ajuste", - "tune38": "Ajustando o seu modelo" + "tune35": "Ajustar de novo", + "tune36": "Iniciar ajuste", + "tune37": "Ajustando o seu modelo" } diff --git a/apps/host/src/locales/tune-ru.json b/apps/host/src/locales/tune-ru.json index 7bf326d6..3f5fe545 100644 --- a/apps/host/src/locales/tune-ru.json +++ b/apps/host/src/locales/tune-ru.json @@ -33,8 +33,7 @@ "tune32": "Сохранённые настройки", "tune33": "Используется", "tune34": "Использовать", - "tune35": "Проверить снова", - "tune36": "Настроить снова", - "tune37": "Начать настройку", - "tune38": "Настройка вашей модели" + "tune35": "Настроить снова", + "tune36": "Начать настройку", + "tune37": "Настройка вашей модели" } diff --git a/apps/host/src/locales/tune-zh.json b/apps/host/src/locales/tune-zh.json index 6ac7e66e..458dbbbf 100644 --- a/apps/host/src/locales/tune-zh.json +++ b/apps/host/src/locales/tune-zh.json @@ -33,8 +33,7 @@ "tune32": "已保存的调优", "tune33": "使用中", "tune34": "使用", - "tune35": "再次检查", - "tune36": "再次调优", - "tune37": "开始调优", - "tune38": "正在调优你的模型" + "tune35": "再次调优", + "tune36": "开始调优", + "tune37": "正在调优你的模型" } From 84ca0b6c215fded623d274cc42038e39651733ad Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:11:57 +0200 Subject: [PATCH 12/18] tuner: five decodes per run, early drop only after a 5% loss, noisy default-confirmed says so --- strata_control/autotune.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index bcee5982..eda8c207 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -33,6 +33,7 @@ from strata_control import engine_component, tune_knobs, tune_machine from strata_control.tune_session import RequestSet, RunResult, Session, StartFailed MIN_FREE_RAM_MIB = 3584 # 3.5 GiB left for the system at every start (6.5) +EARLY_DROP = 0.05 # a candidate this much slower than its own round's base is dropped after one round (run-to-run noise is 2-8%) STAGE_GAP_NOISY = 0.04 # an A/A gap above this: the machine is noisy (6.5) @@ -322,7 +323,7 @@ class Tuner: long_tokens = 0 if self.o.use == "coding" and self.o.mode == "thorough": long_tokens = min(28000, int(0.8 * self.ctx.context_tokens)) - return RequestSet(warmups=2 if self.o.mode == "thorough" else 1, decodes=3, decode_tokens=200, + return RequestSet(warmups=2 if self.o.mode == "thorough" else 1, decodes=5, decode_tokens=200, pp_tokens=4096 if self.ctx.context_tokens >= 6000 else 1024, long_tokens=long_tokens) def _run_stages(self) -> None: @@ -443,7 +444,7 @@ class Tuner: for p in list(alive): b, c = round_runs[rnd].get("base"), round_runs[rnd].get(p.arm.id) m_b, m_c = (metric(b, o.use) if b else None), (metric(c, o.use) if c else None) - if m_b and m_c and m_c / m_b < 1.0 - o.margin: + if m_b and m_c and m_c / m_b < 1.0 - max(o.margin, EARLY_DROP): by_id[p.arm.id].status = "dropped" by_id[p.arm.id].reason = f"slower by {100 * (1 - m_c / m_b):.1f}% in round {rnd + 1}" alive = [x for x in alive if x.arm.id != p.arm.id] @@ -558,6 +559,8 @@ class Tuner: else: r.outcome = "default_confirmed" r.message = "Your current settings are already the fastest we found. Nothing was changed." + if r.noise.get("noisy"): + r.message += " (The PC was busy while measuring, so a small gain could be hidden.)" r.settings = {"args": chosen_args, "env": chosen_env, "per_request": per_request_chosen} cls, fields = "exact", [] for rep in arms: From e62e6bf2f564d42296dd4d7f43c4bf9e7ba70c62 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:15:37 +0200 Subject: [PATCH 13/18] tuner: a killed engine (no message) is an out-of-memory --- strata_control/tune_session.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index 54232e4b..843afef5 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -134,7 +134,8 @@ def failure_kind(text: str, returncode: int | None) -> tuple[str, str]: reason = " | ".join(lines[:3])[:300] if re.search(r"unknown argument|unrecognized (argument|option)", low): return "UNSUPPORTED", reason or "the engine does not accept one of the settings" - if re.search(r"out of memory|memory guard|cannot allocate|std::bad_alloc|oom", low) or returncode in (-9, 137, 3221226505): + if re.search(r"out of memory|memory guard|cannot allocate|std::bad_alloc|oom|^killed$| +killed", low) or returncode in (-9, 137, 3221226505): return "OOM", reason or "the engine ran out of memory" return "FAIL_BOOT", reason or f"the engine stopped while starting (exit {returncode})" From 22265c6ac7d1669f17845942e6b148372728a1b9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:16:07 +0200 Subject: [PATCH 14/18] tuner: fix the killed-engine pattern --- strata_control/tune_session.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/strata_control/tune_session.py b/strata_control/tune_session.py index 843afef5..aa1a3dc3 100644 --- a/strata_control/tune_session.py +++ b/strata_control/tune_session.py @@ -134,8 +134,7 @@ def failure_kind(text: str, returncode: int | None) -> tuple[str, str]: reason = " | ".join(lines[:3])[:300] if re.search(r"unknown argument|unrecognized (argument|option)", low): return "UNSUPPORTED", reason or "the engine does not accept one of the settings" - if re.search(r"out of memory|memory guard|cannot allocate|std::bad_alloc|oom|^killed$| -killed", low) or returncode in (-9, 137, 3221226505): + if re.search(r"out of memory|memory guard|cannot allocate|std::bad_alloc|\boom\b|(?:^|\n)killed(?:\r?\n|$)", low) or returncode in (-9, 137, 3221226505): return "OOM", reason or "the engine ran out of memory" return "FAIL_BOOT", reason or f"the engine stopped while starting (exit {returncode})" From 781690f397ca42bd93f463434000f322641480e1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:25:47 +0200 Subject: [PATCH 15/18] tuner: per-request points get a control and a fresh-engine 5-round confirmation (the first real run showed sending any setting reads ~10% faster) --- strata_control/autotune.py | 71 ++++++++++++++++++++++++++++------- tests/tuning/test_autotune.py | 18 +++++++++ 2 files changed, 76 insertions(+), 13 deletions(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index eda8c207..774c22d6 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -113,6 +113,7 @@ class TuneResult: pairs: int = 0 faster_pairs: int = 0 per_request: list[dict[str, Any]] = field(default_factory=list) + per_request_confirm: dict[str, Any] | None = None notes: list[str] = field(default_factory=list) classes: list[str] = field(default_factory=list) facts: dict[str, Any] = field(default_factory=dict) @@ -540,6 +541,16 @@ class Tuner: # ---- per-request winners (found in the base engine): keep only the ones that won every round per_request_chosen = {row["key"]: row["value"] for row in r.per_request if row.get("won")} + if per_request_chosen and not self.storm and not self.cancel.is_set() and not self._over_budget(reserve_s=self._avg_run()): + # a per-request win from one engine's quick points is only a candidate: confirm it in a fresh engine, 5 interleaved rounds + self._say("confirm", "Confirming the settings that need no restart") + r.per_request_confirm = self._confirm_per_request(per_request_chosen, spec, threshold) + if not r.per_request_confirm["ok"]: + r.notes.append("a per-request setting looked faster in the first test but did not hold in the confirmation, so it was not kept") + per_request_chosen = {} + elif per_request_chosen: + r.notes.append("a per-request setting looked faster but could not be confirmed in the time left, so it was not kept") + per_request_chosen = {} # ---- result if end_base is not None and end_base.status == "PASS" and drift > 0.03 and winners: @@ -593,8 +604,9 @@ class Tuner: "rss_peak_mib": max([c.rss_peak_mib for c in c_runs if c.rss_peak_mib] or [None]) if any(c.rss_peak_mib for c in c_runs) else None, "vram_used_mib": max([c.vram_used_mib for c in c_runs if c.vram_used_mib] or [None]) if any(c.vram_used_mib for c in c_runs) else None} elif r.outcome == "improved" and per_request_chosen: - r.gain_pct = r.gain_decode_pct = round(100 * (statistics.median( - [row["ratio"] for row in r.per_request if row.get("won")]) - 1.0), 1) + r.gain_pct = r.gain_decode_pct = round(100 * ((r.per_request_confirm or {}).get("ratio", 1.0) - 1.0), 1) + r.pairs = len((r.per_request_confirm or {}).get("ratios", [])) + r.faster_pairs = sum(1 for x in (r.per_request_confirm or {}).get("ratios", []) if x > 1.0) r.chosen = dict(r.base) else: r.chosen = {k: r.base.get(k) for k in ("decode_tok_s", "pp_tok_s", "rss_peak_mib", "vram_used_mib")} @@ -649,8 +661,10 @@ class Tuner: def _per_request_stage(self, eng: Any) -> list[dict[str, Any]]: """Per-request settings against the engine's own choice, in this one engine, 3 interleaved rounds (6.3 step 2). - A value is kept only if it beat the default by the margin in every round. No restart is needed, so these are - tried before any restart (5). One value per key can win.""" + A **control** point sends a per-request value equal to what the engine already uses (the configuration's own + `--spec-min-p`), so it changes nothing: whatever it "gains" is the bias of sending a setting at all (the first run + after an idle gap, the order). A value must beat the default by the margin AND beat the control by the margin in every + round. A win here is only a candidate: the tuner confirms it afterwards in a fresh engine. One value per key can win.""" points: list[tuple[str, Any]] = [] for spec in tune_knobs.PER_REQUEST: if self.ctx.backend not in spec["backends"]: @@ -661,27 +675,35 @@ class Tuner: points.append((spec["key"], v)) if not points: return [] + own = tune_knobs._current(self.ctx.base_args, "--spec-min-p") + control = ("control", float(own)) if own not in (None, "") and self.ctx.backend != "metal" else None rounds = 3 - default: dict[int, float] = {} - vals: dict[tuple[str, Any], dict[int, float]] = {pt: {} for pt in points} + default: dict[int, list[float]] = {} + vals: dict[tuple[str, Any], dict[int, float]] = {pt: {} for pt in points + ([control] if control else [])} self._say("per_request", "Trying settings that need no restart") for rnd in range(rounds): - for item in rotate([None] + points, rnd): + order = rotate([None] + points + ([control] if control else []) + [None], rnd) + for item in order: self._check_cancel() if item is None: d = eng.decode_once(None, 200) if d: - default[rnd] = d + default.setdefault(rnd, []).append(d) else: - d = eng.decode_once({item[0]: item[1]}, 200) + key = "spec_min_p" if item[0] == "control" else item[0] + d = eng.decode_once({key: item[1]}, 200) if d: vals[item][rnd] = d + ref = {i: statistics.mean(v) for i, v in default.items() if v} + ctl = [vals[control][i] / ref[i] for i in range(rounds) if control and i in vals[control] and i in ref] if control else [] rows: list[dict[str, Any]] = [] for pt in points: - ratios = [vals[pt][i] / default[i] for i in range(rounds) if i in vals[pt] and i in default] - won = len(ratios) == rounds and all(x >= 1.0 + self.o.margin for x in ratios) - rows.append({"key": pt[0], "value": pt[1], "ratios": [round(x, 4) for x in ratios], - "ratio": round(statistics.median(ratios), 4) if ratios else None, "won": won}) + ratios = [vals[pt][i] / ref[i] for i in range(rounds) if i in vals[pt] and i in ref] + adj = [ratios[j] / ctl[j] for j in range(min(len(ratios), len(ctl)))] if ctl else ratios + won = len(ratios) == rounds and len(adj) == rounds and all(x >= 1.0 + self.o.margin for x in adj) \ + and all(x >= 1.0 + self.o.margin for x in ratios) + rows.append({"key": pt[0], "value": pt[1], "ratios": [round(x, 4) for x in ratios], "control_ratios": [round(x, 4) for x in ctl], + "ratio": round(statistics.median(adj), 4) if adj else None, "won": won}) best: dict[str, dict[str, Any]] = {} for row in rows: if row["won"] and (row["key"] not in best or row["ratio"] > best[row["key"]]["ratio"]): @@ -690,6 +712,29 @@ class Tuner: row["won"] = best.get(row["key"]) is row return rows + def _confirm_per_request(self, chosen: dict[str, Any], spec: RequestSet, threshold: float) -> dict[str, Any]: + """5 interleaved rounds in a fresh engine of the chosen per-request settings against the engine's own choice (two decodes + each, the order alternating). Kept only if the median ratio beats the threshold in at least 4 of 5 rounds.""" + ratios: list[float] = [] + + def points(eng: Any) -> None: + for i in range(5): + self._check_cancel() + got: dict[str, list[float]] = {"d": [], "t": []} + for who in (("d", "t") if i % 2 == 0 else ("t", "d")): + for _ in range(2): + v = eng.decode_once(chosen if who == "t" else None, 200) + if v: + got[who].append(v) + if got["d"] and got["t"]: + ratios.append(statistics.mean(got["t"]) / statistics.mean(got["d"])) + + res = self._run(self.base_args, {}, spec, "confirm per-request", points=points) + ok = res.status == "PASS" and len(ratios) == 5 and sum(1 for x in ratios if x > 1.0) >= 4 \ + and statistics.median(ratios) >= threshold + return {"ok": ok, "ratios": [round(x, 4) for x in ratios], "ratio": round(statistics.median(ratios), 4) if ratios else None, + "status": res.status} + # --------------------------------------------------------------------------- building a tuner from a run configuration diff --git a/tests/tuning/test_autotune.py b/tests/tuning/test_autotune.py index 1e95d304..8addab95 100644 --- a/tests/tuning/test_autotune.py +++ b/tests/tuning/test_autotune.py @@ -261,6 +261,24 @@ class TunerTest(unittest.TestCase): t, s2, r = run_tuner(noisy, session_kw={"noise": 0.0}) self.assertNotIn("spec_min_p", r.settings["per_request"]) + def test_sending_any_setting_is_not_a_gain(self): + # the p620 artifact: every request that carried a setting read ~10% faster than the plain default, even a setting equal + # to what the engine already uses. The control point catches it. + def model(args, env, tune=None): + return 60.0 * (1.10 if tune else 1.0) + t, s, r = run_tuner(model, session_kw={"noise": 0.002}) + self.assertEqual(r.settings["per_request"], {}) + self.assertNotEqual(r.outcome, "improved") + + def test_a_real_per_request_gain_is_confirmed_in_a_fresh_engine(self): + def model(args, env, tune=None): + return 60.0 * (1.06 if tune and tune.get("spec_min_p") == 0.7 else 1.0) + t, s, r = run_tuner(model, session_kw={"noise": 0.002}) + self.assertEqual(r.settings["per_request"], {"spec_min_p": 0.7}) + self.assertEqual(r.per_request_confirm["status"], "PASS") + self.assertGreaterEqual(sum(1 for x in r.per_request_confirm["ratios"] if x > 1.0), 4) + self.assertAlmostEqual(r.gain_pct, 6.0, delta=1.5) + def test_thorough_confirms_with_five_pairs(self): model = speed_with({("--host-core", "last"): 1.06}) t, s, r = run_tuner(model, opts=autotune.Options(mode="thorough", budget_s=7200), session_kw={"noise": 0.003}) From fd0d7fd8750416ab5efa4adb900259494af7b111 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 01:36:19 +0200 Subject: [PATCH 16/18] tuner: the quick budget reserves only the extra base rounds and the final base --- strata_control/autotune.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index 774c22d6..1e3087fc 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -368,7 +368,7 @@ class Tuner: n_arms = len(planned) else: left = int((o.budget_s - self._elapsed()) / max(1.0, self._avg_run())) - fixed = (per_arm - 1) + 1 + 2 # extra base rounds, the final base, a combined-confirm margin + fixed = (per_arm - 1) + 1 # extra base rounds, the final base n_arms = min(len(planned), max(0, (left - fixed) // per_arm)) for p in planned[n_arms:]: skipped.append({"id": p.arm.id, "label": p.arm.label, "reason": "left out to stay inside the time you chose"}) From a3dd4b702d35da52e84d5a36563a8fd535743650 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 02:48:30 +0200 Subject: [PATCH 17/18] tuner: a candidate is refused for low free RAM only if it is worse than the base (a RAM-bound base can sit below the floor itself) --- strata_control/autotune.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index 1e3087fc..ca4d5233 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -620,7 +620,7 @@ class Tuner: for work, is a promise about memory).""" if res.rss_peak_mib and base.rss_peak_mib and res.rss_peak_mib > base.rss_peak_mib * 1.05 + 512 and self.o.goal == "room": return "it needs more memory than your current settings, which would eat into the memory you wanted left free" - if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib: + if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib and \n (base.min_avail_mib is None or res.min_avail_mib < base.min_avail_mib - 512): # a RAM-bound base itself may sit below the floor return "it left the PC with too little free memory" if self.o.goal == "room" and self.o.ram_wish_pct and self.total_ram and res.min_avail_mib is not None and \ base.min_avail_mib is not None: From 0b22b8c7363df41ebe9c740a55b07407b8ca68e3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 02:48:56 +0200 Subject: [PATCH 18/18] tuner: fix the RAM-floor rule syntax --- strata_control/autotune.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/strata_control/autotune.py b/strata_control/autotune.py index ca4d5233..c9528074 100644 --- a/strata_control/autotune.py +++ b/strata_control/autotune.py @@ -620,7 +620,8 @@ class Tuner: for work, is a promise about memory).""" if res.rss_peak_mib and base.rss_peak_mib and res.rss_peak_mib > base.rss_peak_mib * 1.05 + 512 and self.o.goal == "room": return "it needs more memory than your current settings, which would eat into the memory you wanted left free" - if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib and \n (base.min_avail_mib is None or res.min_avail_mib < base.min_avail_mib - 512): # a RAM-bound base itself may sit below the floor + if res.min_avail_mib is not None and res.min_avail_mib < self.o.min_free_ram_mib and ( + base.min_avail_mib is None or res.min_avail_mib < base.min_avail_mib - 512): # a RAM-bound base can sit below the floor itself return "it left the PC with too little free memory" if self.o.goal == "room" and self.o.ram_wish_pct and self.total_ram and res.min_avail_mib is not None and \ base.min_avail_mib is not None: