okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221launch: say once when the draft layer cannot be downloaded offline3dcdb99a7

main
10.3 KiB177 linesraw
1"""Drive each entry point for one (machine class, model set) and return what the engine would be started with, normalized.
2
3A record has the same shape for every entry point:
4
5  entry            which one
6  command          what the person (or the app) asked for, in words
7  fetches          what the drafter fetch was asked to download: file name, variant, backend (nothing is downloaded)
8  setup_args       what the entry point hands to setup.py (Terminal launch only)
9  config_file      the run config the entry point leaves on disk (normalized)
10  engine           {exe, argv, env_set, notes}: what serve/server.py would start: engine_args(cfg, exe) and the variables child_env(cfg) adds
11  not_driven       (setup only) present instead of the above for a class whose setup is another script (Intel Arc, Mac), with the reason
12"""
13
14from __future__ import annotations
15
16import contextlib
17import io
18import json
19import os
20import subprocess
21import sys
22from pathlib import Path
23from unittest import mock
24
25from .matrix import ModelSet
26from .normalize import normalize
27from .world import ROOT, World, context_for
28
29HERE = Path(__file__).resolve().parent
30
31
32def run_cli(argv: list[str]) -> tuple[int, str, str]:
33    from strata_cli.cli import main
34    out, err = io.StringIO(), io.StringIO()
35    saved = dict(os.environ)            # main() sets variables on its own process for the programs it starts (GGML_NO_BACKTRACE, strata_control/childenv.py): that is
36    try:                                # the command's doing, not the machine's, so it must not become the baseline the engine's environment is compared with
37        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
38            try:
39                code = main(argv)
40            except SystemExit as e:
41                code = int(e.code or 0) if not isinstance(e.code, str) else 1
42    finally:
43        os.environ.clear()
44        os.environ.update(saved)
45    return code, out.getvalue(), err.getvalue()
46
47def engine_start(world: World, cfg: dict) -> dict:
48    """What serve/server.py hands to the engine for this run config: the arguments (engine_args) and the variables child_env adds to the environment."""
49    from serve import server
50    baseline = dict(os.environ)
51    notes = io.StringIO()
52    with contextlib.redirect_stdout(notes):
53        argv = server.engine_args(dict(cfg), cfg["exe"])
54        env = server.child_env(dict(cfg))
55    env_set = {k: v for k, v in sorted(env.items()) if baseline.get(k) != v}
56    return {"exe": cfg["exe"], "argv": [str(a) for a in argv], "env_set": env_set,
57            "notes": [l for l in notes.getvalue().splitlines() if l.strip()]}
58
59
60def setup_fetches_layer(world: World, args: list[str]) -> None:
61    """setup.py's step 6 on a computer without the draft layer: fetched unless setup is told "--mtp off" or "--drafter dflash2" (setup.py ~10327)."""
62    word = args[args.index("--mtp") + 1] if "--mtp" in args else None
63    drafter = args[args.index("--drafter") + 1] if "--drafter" in args else None
64    if word == "off" or drafter == "dflash2" or (world.mtp / "experts.bin").exists():
65        return
66    world.mtp.mkdir(parents=True, exist_ok=True)
67    (world.mtp / "experts.bin").write_bytes(b"e")
68    (world.mtp / "draft_vocab.bin").write_bytes(b"v")
69    (world.data / "mtp" / "mtp-q2_0.gguf").write_bytes(b"m")
70    world.fetches.append({"call": "setup_mtp_layer"})
71
72
73def drive_launch(world: World, extra: tuple[str, ...] = (), setup_runs: bool | str = False, fresh: bool = False) -> dict:
74    """`strata launch --model <set> --yes --no-tui` through the real command, with the engine start, the model download and the tuning replaced.
75    `extra`: more words for the command (`--drafting off`), for the tests that launch several times in one world.  `setup_runs`: setup runs at this launch
76    (as it does at every launch whose --model-path or data folder the installed copy does not match, runner.installed_serves_request) and leaves the
77    draft-layer word in the installed config as strata_control/setup_config.py writes it: the stand-in config afresh, "--mtp off" -> "mtp": false (and no --mtp
78    in the args), "--mtp on" -> true, no word -> the earlier value kept (setup.carry_over).
79    "when_needed": only when ensure_model would not reuse the installed copy (the record then says "setup_ran").
80    `fresh`: a computer without the draft layer (World.fresh): setup's step 6 is simulated too (setup_fetches_layer), and the record has the plan's parts
81    (`plan_parts`, Runner.model_state() before setup) and its drafting line (`plan_drafting`)."""
82    from strata_cli.launch import catalog as C, runner as R
83    seen: dict = {}
84    cat = C.Catalog(root=world.install, hardware=world.hardware_report())
85
86    def ensure_model(self):
87        if fresh:
88            seen["plan_parts"] = [p.kind for p in self.model_state().parts]
89            seen["plan_drafting"] = self.drafting_plan_line()
90        seen["setup_args"] = args = self.setup_args()
91        runs = setup_runs
92        if runs == "when_needed":                            # ensure_model's own test for reusing the installed copy
93            path, desc = self.installed_state()
94            runs = not (path is not None and desc is not None and R.desc_matches(desc, self.s) and not R.files_present(R.read_config(path))
95                        and not self.layer_back(path) and self.installed_serves_request(path))
96        seen["setup_ran"] = bool(runs)
97        if runs:                                             # setup writes the config afresh and carries an earlier "mtp" over unless --mtp is given
98            from strata_control import draft_layer
99            if fresh:
100                setup_fetches_layer(world, args)
101                self.note_setup_lines(getattr(world, "setup_said", []))     # what setup printed (a test sets it: mtp_fetch's offline line)
102            old = json.loads(world.config_path.read_text(encoding="utf-8")) if world.config_path.exists() else {}
103            cfg = world.base_config()
104            word = args[args.index("--mtp") + 1] if "--mtp" in args else None
105            if word is not None:
106                cfg["mtp"] = word != "off"
107            elif "mtp" in old:
108                cfg["mtp"] = old["mtp"]
109            draft_layer.apply(cfg)
110            world.config_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
111        return world.config_path
112
113    with mock.patch.object(C, "Catalog", lambda *a, **k: cat), \
114            mock.patch.object(R.Runner, "ensure_engine", lambda self: None), \
115            mock.patch.object(R.Runner, "ensure_model", ensure_model), \
116            mock.patch.object(R.Runner, "tune", lambda self: None), \
117            mock.patch.object(R.Runner, "start", lambda self: seen.setdefault("started", True) and None), \
118            mock.patch.object(R.Runner, "open_access", lambda self: None), \
119            mock.patch.object(R.Runner, "check_serving", lambda self: None):
120        command = ["launch", "--model", world.mset.model, "--yes", "--no-tui", "--context", str(context_for(world.machine, world.mset)), *extra]
121        orig_run = R.Runner.run
122
123        def run(self, **kw):
124            seen["runner"] = self
125            return orig_run(self, **kw)
126
127        with mock.patch.object(R.Runner, "run", run):
128            code, out, err = run_cli(command)
129    runner = seen.get("runner")
130    if code != 0 or runner is None or runner.config_path is None:
131        return {"entry": "launch", "command": "strata " + " ".join(command), "failed": {"exit": code, "stderr": err[-400:], "stdout": out[-400:]}}
132    cfg = json.loads(Path(runner.config_path).read_text(encoding="utf-8"))
133    return {"entry": "launch", "command": "strata " + " ".join(command), "fetches": list(world.fetches),
134            "setup_args": seen.get("setup_args"), "config_file": cfg, "engine": engine_start(world, cfg),
135            **({"setup_ran": seen.get("setup_ran")} if setup_runs else {}),
136            **({"plan_parts": seen.get("plan_parts"), "plan_drafting": seen.get("plan_drafting"), "notices": list(runner.notices)} if fresh else {})}
137
138
139def drive_app(world: World, which: str) -> dict:
140    """The app's Load, in a Node process: the host's own createNativeControl with a fake Control for everything but the Drafting calls, which go through the
141    real strata_control (python -m tests.snapshot.control_shim) on the same simulated machine.  Returns the run config the host wrote and the Python side's
142    engine start for it."""
143    node = os.environ.get("STRATA_SNAPSHOT_NODE") or "node"
144    world_file = world.root / "world.json"
145    world_file.write_text(json.dumps({"machine": world.machine.key, "set": world.mset.key, "root": str(world.root)}), encoding="utf-8")
146    env = {**os.environ, "STRATA_SNAPSHOT_PYTHON": sys.executable, "STRATA_SNAPSHOT_REPO": str(ROOT)}
147    proc = subprocess.run([node, str(HERE / "app_driver.mjs"), str(world_file), which], cwd=str(ROOT), env=env, capture_output=True, text=True, timeout=240)
148    last = [l for l in proc.stdout.splitlines() if l.startswith("SNAPSHOT-RESULT ")]
149    if proc.returncode != 0 or not last:
150        return {"entry": "app_" + which, "failed": {"exit": proc.returncode, "stderr": proc.stderr[-1500:], "stdout": proc.stdout[-800:]}}
151    got = json.loads(last[-1][len("SNAPSHOT-RESULT "):])
152    cfg = got.get("config_file")
153    out = {"entry": "app_" + which, "command": got.get("command"), "fetches": got.get("fetches"), "control_calls": got.get("control_calls"), "config_file": cfg}
154    if cfg:
155        with world.patched():
156            out["engine"] = engine_start(world, cfg)
157    return out
158
159
160def drive(machine_key: str, set_key: str, entry: str, root: Path | None = None) -> dict:
161    """One record, normalized.  A fresh scratch world every time."""
162    from .matrix import machine as get_machine, model_set as get_set
163    world = World(get_machine(machine_key), get_set(set_key), root).build()
164    try:
165        if entry == "setup":
166            from .setup_driver import drive_setup
167            rec = drive_setup(world)
168        elif entry == "launch":
169            with world.patched():
170                rec = drive_launch(world)
171        elif entry in ("app_plain", "app_models"):
172            rec = drive_app(world, entry[4:])
173        else:
174            raise ValueError(entry)
175        return normalize(rec, world)
176    finally:
177        world.close()