okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
14.0 KiB243 linesraw
1"""A scratch world for one (machine class, model set): files, a stand-in for setup's output, and the patches that make the probes answer as that machine.
2
3Everything lives under one temporary folder that is also HOME, the data folder, the install folder and every per-user folder, so nothing real is read or written.
4No model file is needed (the model files are empty), no engine runs (the engine is a text stub that carries the strings the program's own checks read), nothing is
5downloaded (the drafter fetch is replaced by a recorder that writes a small stand-in file), and nothing touches the network.
6"""
7
8from __future__ import annotations
9
10import contextlib
11import json
12import os
13import sys
14import tempfile
15from pathlib import Path
16from unittest import mock
17
18from .matrix import MACHINES, Machine, ModelSet
19
20ROOT = Path(__file__).resolve().parents[2]
21if str(ROOT) not in sys.path:
22    sys.path.insert(0, str(ROOT))
23
24#: The engine stub: the strings drafting.engine_form / engine_reads_selector_q4 look for in the program file (a current engine carries them).
25ENGINE_STUB = (b"STRATA ENGINE STUB (config snapshot)\n--mtp-draft-vocab FILE (or --mtp DIR\n--draft-fallback\n"
26               b"--spec 2 or more and --mtp DIR (for DIR/draft_vocab.bin)\nselector codebooks: Q4_0 rows\n")
27
28#: Environment variables a developer or CI may have set that would leak into a start; the world starts from a clean list.
29CLEAR = ("STRATA_SETTINGS_FILE", "STRATA_CONNECTION_DIR", "CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "STRATA_API_KEY",
30         "STRATA_ENGINE_BACKEND", "STRATA_DFLASH2_TUNED_URL", "STRATA_UPDATE_FEED", "STRATA_NO_ACQUIRE", "STRATA_COMPONENTS_DIR")
31
32
33def context_for(machine: Machine, model_set: ModelSet) -> int:
34    if machine.key == "nv_12gb_streaming":
35        return 65536
36    if machine.key == "mac_small":
37        return 32768
38    return 131072
39
40
41class World:
42    def __init__(self, machine: Machine, mset: ModelSet, root: Path | None = None):
43        self._tmp = None
44        if root is None:
45            self._tmp = tempfile.TemporaryDirectory(prefix="strata-snap-")
46            root = Path(self._tmp.name)
47        self.machine, self.mset, self.root = machine, mset, Path(root).resolve()
48        r = self.root
49        self.home, self.install, self.data = r / "home", r / "install", r / "data"
50        self.engine_dir = r / "engine"
51        self.models = self.data / "models"
52        self.pack = self.data / "packs" / mset.key
53        self.mtp = self.data / "mtp" / "rt"
54        self.gguf_dir = self.models / mset.model
55        self.exe = self.engine_dir / "strata"
56        self.tag = ({"qwen": "", "unsloth": "unsloth-"}[mset.family] + mset.model).lower()
57        self.config_path = self.install / f"strata-{self.tag}.json"
58        self.env = {
59            "HOME": str(self.home), "USERPROFILE": str(self.home),
60            "APPDATA": str(r / "roaming"), "LOCALAPPDATA": str(r / "local"),
61            "XDG_CONFIG_HOME": str(r / "xdg-config"), "XDG_STATE_HOME": str(r / "state"), "XDG_DATA_HOME": str(r / "xdg-data"),
62            "STRATA_PROFILE_DIR": str(r / "config" / "profiles"), "STRATA_PRESET_DIR": str(r / "config" / "presets"),
63            "STRATA_LAUNCH_PRESET_DIR": str(r / "config" / "launch-presets"),
64            "STRATA_INSTALL_DIR": str(self.install), "STRATA_RUNTIME_DIR": str(r / "runtime"),
65            "TMPDIR": str(r / "tmp"), "TEMP": str(r / "tmp"), "TMP": str(r / "tmp"),
66            "STRATA_SETTINGS_FILE": str(r / "settings.json"),
67        }
68        self.fetches: list[dict] = []          # what the drafter fetch was asked for (see patches)
69
70    # ------------------------------------------------------------------ files
71    def build(self) -> "World":
72        for d in (self.home, self.install, self.data, self.engine_dir, self.models, self.gguf_dir, self.pack / "tokenizer", self.mtp,
73                  self.root / "tmp", self.root / "roaming", self.root / "local", self.root / "xdg-config", self.root / "state", self.root / "runtime"):
74            d.mkdir(parents=True, exist_ok=True)
75        self.exe.write_bytes(ENGINE_STUB)
76        for shard in self.mset.shards:
77            (self.gguf_dir / shard).write_bytes(b"GGUF")
78        (self.pack / "native_experts.txt").write_text("x")
79        (self.mtp / "experts.bin").write_bytes(b"e")
80        (self.mtp / "draft_vocab.bin").write_bytes(b"v")
81        (self.data / "mtp" / "mtp-q2_0.gguf").write_bytes(b"m")
82        (self.root / "settings.json").write_text(json.dumps({"data_dir": str(self.data), "installs": [str(self.install)]}), encoding="utf-8")
83        self.config_path.write_text(json.dumps(self.base_config(), indent=1), encoding="utf-8")
84        (self.root / "world-info.json").write_text(json.dumps(self.info(), indent=1), encoding="utf-8")
85        return self
86
87    def info(self) -> dict:
88        """What the app driver (Node) needs to know about this world; written next to it so the two sides read the same facts."""
89        m = self.machine
90        platform = {"windows": "windows-x86_64", "linux": f"linux-{m.machine}", "macos": "macos-arm64"}[m.os]
91        family = self.mset.family
92        return {"tag": self.tag, "family": family, "title": family, "modelName": self.mset.model_name, "model": self.mset.model, "sizeId": self.tag,
93                "configPath": str(self.config_path), "hardware": self.hardware_report(), "backend": m.backend, "platform": platform, "exe": str(self.exe),
94                "context": context_for(m, self.mset)}
95
96    def close(self) -> None:
97        if self._tmp is not None:
98            self._tmp.cleanup()
99
100    # ------------------------------------------------------------------ the stand-in for setup.py's output
101    def base_config(self) -> dict:
102        """What setup.py writes for this class and set, rebuilt from setup.py's own rules (the qwen block around line 10975-11200).
103        It is a STAND-IN: setup.py itself cannot be driven without a model download, an engine and a GPU probe (see RESULTS-STEP0.md), so the entry points
104        that start from a saved model all start from this same file.  Differences between entry points are therefore never caused by it."""
105        m, s = self.machine, self.mset
106        ctx = context_for(m, s)
107        shard1 = self.gguf_dir / s.shards[0]
108        ple = self.gguf_dir / s.shards[min(1, len(s.shards) - 1)]
109        args = ["--pack", str(self.pack), "--native", str(shard1)]
110        if len(s.shards) <= 2:
111            args += ["--ple-gguf", str(ple)]
112        args += ["--expert-profile", str(ROOT / "data" / "expert-profile.bin"), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4",
113                 "--spec-min-p", "0.5", "--mtp", str(self.mtp), "--max-context", str(ctx)]
114        if ctx > 8192:
115            args += ["--kv", "int8"]
116        if m.key == "dgx_spark":
117            args += ["--mmap-experts"]
118            args[args.index("--prefill") + 1] = "auto:32768"
119            args += ["--mtp-q4", "all", "--mtp-hnorm", "stream"]
120        if ctx >= 65536 and m.key == "nv_12gb_streaming":
121            args += ["--kv-resident", "32768"]
122        if s.family == "unsloth":
123            args += ["--resident-budget-gib", "24" if m.ram_gb < 100 else "48"]
124        cfg = {"exe": str(self.exe), "args": args, "cwd": str(ROOT), "tokenizer": str(self.pack / "tokenizer"),
125               "model_name": s.model_name, "log": str(self.install / f"strata-{self.tag}.log"), "lib_dirs": [], "port": 8080}
126        if m.backend in ("hip", "metal", "sycl"):
127            cfg["backend"] = m.backend
128        if m.cards > 1:
129            cfg["gpu"] = list(range(m.cards))
130        return cfg
131
132    # ------------------------------------------------------------------ what the probes answer
133    def hardware_report(self) -> dict:
134        """The hardware report the Terminal's catalog and the app's host read (the shape tests/terminal/launch_support.py and the host tests use)."""
135        m = self.machine
136        card = {"index": 0, "name": m.card, "vendor": m.vendor, "vram_gb": m.vram_gb, "usable": True}
137        if m.arch_field is not None:
138            card["arch"] = m.arch_field
139        if m.unified:
140            card["unified_gb"] = m.ram_gb
141            card["uma"] = True
142        hw = {"ram_gb": m.ram_gb, "os": {"windows": "Windows 11", "linux": "Linux", "macos": "Darwin"}[m.os], "disk_free_gb": 2000.0,
143              "cpu": {"avx2": m.machine in ("x86_64",) or None, "name": "snapshot cpu", "cores": 16}, "gpus": [card], "engine_vendor": m.vendor if m.vendor != "apple" else None}
144        if m.os == "macos":
145            hw["mac"] = {"chip": m.card, "macos": "27.2", "unified_gb": m.ram_gb}
146        return hw
147
148    def vram_mib(self) -> float | None:
149        """What the telemetry reader would answer for the ONE card (None for a shared-memory chip, as drafting.card_vram_mib does)."""
150        return self.machine.vram_mib or None
151
152    @contextlib.contextmanager
153    def patched(self):
154        """The Python side of the machine class: engine family, cards, card memory, platform, environment.  Nothing else is replaced."""
155        from strata_control import drafting, drafting_fetch, engine_component
156        m = self.machine
157        archs = list(m.archs)
158        vram = self.vram_mib()
159        saved_env = dict(os.environ)
160        fetches = self.fetches
161
162        class Reader:
163            def ok(self_):                                       # noqa: N805
164                return vram is not None
165
166            def read(self_):                                     # noqa: N805
167                return {"mem_total": int(vram * (1 << 20)) if vram else 0}
168
169        def exists(path) -> bool:
170            try:
171                p = Path(path)
172                return p.is_file() and p.stat().st_size > 0
173            except OSError:
174                return False
175
176        def fake_converted_ok(data_dir, *, size=None, sha256=None, name=None):
177            return bool(data_dir) and exists(Path(data_dir) / drafting.FOLDER / (name or drafting.CONVERTED_NAME))
178
179        def put(path: Path) -> Path:
180            path.parent.mkdir(parents=True, exist_ok=True)
181            path.write_bytes(b"snapshot drafter stand-in\n")
182            return path
183
184        def fake_ensure_tuned(data_dir, *, progress=None, cancel=None, url=None, size=None, sha256=None, name=None, feed=None, throttle=False, backend=None, variant=None):
185            pin = drafting.tuned_pack(variant)
186            fetches.append({"call": "ensure_tuned", "file": name or pin.name, "variant": variant or "selq4", "backend": backend, "gb": pin.gb})
187            return put(Path(data_dir) / drafting.FOLDER / (name or pin.name))
188
189        def fake_ensure(data_dir, *, progress=None, cancel=None, base_url=None, files=None):
190            fetches.append({"call": "ensure", "file": drafting.PACK_NAME, "gb": drafting.DOWNLOAD_GB})
191            put(drafting.target_path(data_dir))
192            (Path(data_dir) / drafting.FOLDER / drafting.VOCAB_NAME).write_bytes(b"v")
193            return drafting.target_path(data_dir)
194
195        def fake_convert(data_dir, **kw):
196            fetches.append({"call": "convert_selector"})
197            return put(drafting.converted_path(data_dir))
198
199        with contextlib.ExitStack() as st:
200            st.enter_context(mock.patch.dict(os.environ, self.env))
201            for k in CLEAR:
202                if k not in self.env:
203                    os.environ.pop(k, None)
204            os.environ["PATH"] = str(self.engine_dir)           # nothing on PATH is probed; the engine is named by the config
205            st.enter_context(mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True))
206            st.enter_context(mock.patch.object(drafting, "_HARDWARE", [(m.backend, archs)]))
207            st.enter_context(mock.patch.object(drafting, "converted_ok", fake_converted_ok))
208            st.enter_context(mock.patch.object(drafting, "_here", exists))
209            st.enter_context(mock.patch.object(drafting, "engine_has_selector_q4", lambda: True))
210            st.enter_context(mock.patch.object(drafting, "installed_engine_exe", lambda: self.exe))
211            st.enter_context(mock.patch.object(drafting, "card_vram_mib", lambda cfg, backend, archs=None: None if m.unified else vram))
212            st.enter_context(mock.patch.object(drafting_fetch, "ensure_tuned", fake_ensure_tuned))
213            st.enter_context(mock.patch.object(drafting_fetch, "ensure", fake_ensure))
214            st.enter_context(mock.patch.object(drafting_fetch, "convert_selector", fake_convert))
215            st.enter_context(mock.patch.object(drafting_fetch, "online", lambda *a, **k: True))
216            st.enter_context(mock.patch.object(engine_component, "detect_backend", lambda: (m.backend, "snapshot")))
217            st.enter_context(mock.patch.object(engine_component, "cuda_archs_present", lambda: archs if m.backend == "cuda" else []))
218            st.enter_context(mock.patch.object(engine_component, "hip_archs_present", lambda: archs if m.backend == "hip" else []))
219            with contextlib.suppress(ImportError):
220                from serve import telemetry
221                st.enter_context(mock.patch.object(telemetry, "gpu_reader", lambda *a, **k: Reader()))
222            try:
223                from serve import server
224                st.enter_context(mock.patch.object(server, "_CARD_CLASS", [drafting.card_class(archs)]))
225                st.enter_context(mock.patch.object(server, "gpu_vram_mib", lambda gl, hip=False: {} if m.unified or vram is None else {int((gl or [0])[0]): vram}))
226            except ImportError:                                  # serve needs its packages: a world without them still plans
227                pass
228            if m.os == "macos":
229                st.enter_context(mock.patch.object(sys, "platform", "darwin"))
230            yield self
231        os.environ.clear()
232        os.environ.update(saved_env)
233
234
235def worlds(machine_keys=None, set_keys=None):
236    for m in MACHINES:
237        if machine_keys and m.key not in machine_keys:
238            continue
239        from .matrix import MODEL_SETS
240        for s in MODEL_SETS:
241            if set_keys and s.key not in set_keys:
242                continue
243            yield m, s