diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 7af3a3e8..7f32e991 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -145,7 +145,11 @@ says so and starts the engine you had. kept, only their names. Another browser or a private window starts empty; clearing the site's data deletes them. - **How the model starts:** `strata-.json` in the Strata folder (context, GPUs, host, API key, ...), written by setup; next to it `run-.bat` / `.sh`, the log `strata-.log` and, when you use "Use for other - apps too", `strata-.shared-settings.json`. + apps too", `strata-.shared-settings.json`. Running setup again for the same model (another context, say) + rewrites the keys setup writes (`exe`, `args`, `port`, `gpu`, `host`, `api_key`, `vision`, ...) and keeps the + ones you added (`sampling`, `mcp_servers`, `mcp`, `cors_origins`, ...); the earlier file is kept as + `strata-.json.bak` (0.1.39). Engine options you added to `"args"` by hand are not carried over: setup names + them, and you add them again. - **The model files** (`models/`, `packs/`, `mtp/`, 70-120 GB): in **`Strata-data` next to the Strata folder**, or wherever `--data-dir` put them. - **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on diff --git a/setup.py b/setup.py index bc5cdd30..3093c8eb 100644 --- a/setup.py +++ b/setup.py @@ -2369,6 +2369,86 @@ def write_config(path: Path, cfg: dict): os.replace(tmp, path) +# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a +# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again +SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", + "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision"}) +SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_RESIDENT_PIN"}) # the "env" entries setup writes +SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) + + +def carry_over(old: dict, cfg: dict) -> list[str]: + """#629: setup run again for an installed model keeps what the user added to its run config: every key setup does + not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write + plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; + the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses + those): `args_dropped` names them.""" + kept = [] + for k, v in old.items(): + if k not in SETUP_KEYS and k not in cfg: + cfg[k] = v + kept.append(k) + env = {k: v for k, v in (old.get("env") or {}).items() if k not in SETUP_ENV and k not in (cfg.get("env") or {})} \ + if isinstance(old.get("env"), dict) else {} + if env: + cfg["env"] = {**(cfg.get("env") or {}), **env} + kept += [f"env {k}" for k in env] + ov, nv = old.get("vision"), cfg.get("vision") + if isinstance(ov, dict) and isinstance(nv, dict): + for k, v in ov.items(): + if k not in SETUP_VISION and k not in nv: + nv[k] = v + kept.append(f"vision {k}") + mm = ov.get("mmproj") # a file of the user's own: not the one setup downloads + if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): + nv["mmproj"] = mm + kept.append("vision mmproj") + return kept + + +def args_dropped(old: dict, cfg: dict) -> list[str]: + """#629: the engine options of the earlier run config that the new one has no more (by flag name): options added + by hand, which a setup run does not carry over - the start of the line that names them.""" + def flags(c): + a = c.get("args") if isinstance(c.get("args"), list) else [] + return [str(x) for x in a if str(x).startswith("--")] + new = set(flags(cfg)) + return list(dict.fromkeys(f for f in flags(old) if f not in new)) + + +def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: + """#629: setup's run config, written over an earlier one for the same model without losing what the user added + to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as + strata-.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when + this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" + old_path = cfg_path if cfg_path.is_file() else source + old = None + if old_path is not None and old_path.is_file(): + try: + old = json.loads(old_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + pass + if not isinstance(old, dict): + old = None + kept = carry_over(old, cfg) if old is not None else [] + bak = None + if cfg_path.is_file() and old != cfg: + bak = cfg_path.with_name(cfg_path.name + ".bak") + try: + shutil.copyfile(cfg_path, bak) + except OSError as e: + warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})") + bak = None + write_config(cfg_path, cfg) + if kept: + ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept)) + if bak is not None: + dropped = args_dropped(old, cfg) if old is not None else [] + say(f" the earlier run config is kept as {bak.name}" + ( + f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}" + if dropped else "")) + + def readable_config(path: Path) -> bool: """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" text = None @@ -3010,6 +3090,7 @@ def main() -> int: if a.update: # #475: UPDATE.bat / update.sh - never starts the model return update_install(have, a) explicit = a.setup or a.model or a.family or a.check or a.no_start + adopted = None # #629: the earlier install this copy is set up like if not have and not explicit: # a new copy of Strata (an update unzipped elsewhere): set it prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here if prev is not None: @@ -3018,6 +3099,7 @@ def main() -> int: say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " "copy the same way - the model files are reused, nothing big is downloaded.") a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] + adopted = prev a.kv = a.kv or ch["kv"] a.vision = a.vision or ch["vision"] a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] @@ -3664,7 +3746,7 @@ def main() -> int: import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) - write_config(cfg_path, cfg) + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) script = write_run_script(tag, cfg_path, port) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it if cal is None and not hip and not a.no_start and not a.yes and ask( diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py new file mode 100644 index 00000000..ada27efb --- /dev/null +++ b/tools/test_setup_config.py @@ -0,0 +1,135 @@ +"""Tests for what setup keeps in a model's run config when it runs again (#629), the browser choice (#609) and the +image-token flag (#625). Every outside effect is mocked (tools/test_setup_golden.py's install()). + + python -m unittest tools.test_setup_config +""" +from __future__ import annotations + +import contextlib +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 + + +def quiet(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return fn(*args, **kw), out.getvalue() + + +USER = {"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, + "mcp_servers": {"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}}, + "mcp": {"timeout_s": 60, "max_result_chars": 16000, "max_rounds": 8}, + "cors_origins": ["http://localhost:3000"], "reasoning_effort": "low"} + + +class CarryOver(unittest.TestCase): + """#629: setup run again (a different --context) keeps the keys it does not write and keeps the old file as .bak.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_user_keys_survive_a_rerun(self): + code, out, first, _ = self.run_setup("--context", "65536") + self.assertEqual(code, 0, out) + old = {**first, **USER, "args": first["args"] + ["--hand-option", "7"]} + code, out, cfg, _ = self.run_setup("--context", "131072", configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + for k, v in USER.items(): + self.assertEqual(cfg[k], v, k) + a = cfg["args"] + self.assertEqual(a[a.index("--max-context") + 1], "131072") # the new choice is used + self.assertNotIn("--hand-option", a) # setup chooses the engine options... + self.assertIn("kept from your earlier strata-q2_0.json: sampling, mcp_servers, mcp, cors_origins, " + "reasoning_effort", out) + self.assertIn("kept as strata-q2_0.json.bak", out) + self.assertIn("--hand-option", out) # ...and says which ones it did not keep + + def test_a_first_install_is_unchanged(self): + code, out, cfg, _ = self.run_setup() + self.assertEqual(code, 0, out) + self.assertNotIn("kept from", out) + self.assertNotIn(".bak", out) + self.assertFalse(set(cfg) - setup.SETUP_KEYS) # setup writes only its own keys + + def test_setup_keys_are_rewritten(self): + code, out, first, _ = self.run_setup() + old = {**first, "model_name": "renamed", "port": 9999, "draft_vocab": "en", "host": "0.0.0.0"} + code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["model_name"], first["model_name"]) + self.assertEqual(cfg["port"], first["port"]) + self.assertNotIn("host", cfg) # as before: --host is given to setup + self.assertEqual(cfg["draft_vocab"], "en") # kept by its own rule (saved_draft_vocab) + self.assertNotIn("kept from", out) + + def test_write_setup_config(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + mm = Path(d) / "mmproj-Q8_0.gguf" + mm.write_bytes(b"") + old = {"exe": "e", "args": ["--kv", "int8", "--threads", "8"], "sampling": {"temperature": 0.7}, + "env": {"STRATA_RESIDENT_PIN": "0", "MY_VAR": "1"}, + "vision": {"exe": "v", "mmproj": str(mm), "gpu": False, "max_tokens": 300, "min_tokens": 64}} + p.write_text(json.dumps(old), encoding="utf-8") + new = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, "max_tokens": 300}} + _, out = quiet(setup.write_setup_config, p, new) + got = json.loads(p.read_text(encoding="utf-8")) + self.assertEqual(got["sampling"], {"temperature": 0.7}) + self.assertEqual(got["env"], {"MY_VAR": "1"}) # setup's own env entry is setup's to write + self.assertEqual(got["vision"]["mmproj"], str(mm)) # a Q8_0 mmproj of the user's own (#625) + self.assertEqual(got["vision"]["min_tokens"], 64) + self.assertEqual(got["exe"], "e2") + self.assertEqual(json.loads((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8")), old) + self.assertIn("--threads", out) + # the same again: nothing changes, so no new copy is made + (Path(d) / "strata-x.json.bak").unlink() + again = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, + "max_tokens": 300}} + quiet(setup.write_setup_config, p, again) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), got) + + def test_an_unreadable_earlier_config_is_replaced_with_a_copy(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + p.write_text("{cut off", encoding="utf-8") + quiet(setup.write_setup_config, p, {"exe": "e", "args": []}) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": []}) + self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off") + + def test_a_missing_mmproj_is_not_carried(self): + old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}} + new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}} + self.assertEqual(setup.carry_over(old, new), []) + self.assertEqual(new["vision"]["mmproj"], "/data/mmproj-BF16.gguf") + + def test_a_copy_set_up_like_the_last_one_keeps_them_too(self): + with tempfile.TemporaryDirectory() as d: + src = Path(d) / "other" / "strata-x.json" + src.parent.mkdir() + src.write_text(json.dumps({"exe": "old", "mcp_servers": {"a": {"command": "x"}}}), encoding="utf-8") + p = Path(d) / "strata-x.json" + quiet(setup.write_setup_config, p, {"exe": "new"}, src) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), + {"exe": "new", "mcp_servers": {"a": {"command": "x"}}}) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) # nothing here was replaced + + +if __name__ == "__main__": + unittest.main()