okami.mom/strata

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

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
11.8 KiB226 linesraw
1"""The owner's rule for setup (#403 #406 #364 #384): setup RECOMMENDS, it never forces - and the recommended answers
2stay exactly what they were.  setup.main() with --yes (and with Enter for every question) on a few PCs writes the same
3run config, byte for byte, as 0.1.32 plus the fixes on top of it did (tools/test_setup_golden.json, written by that
4setup).  Every outside effect is mocked: no GPU, no downloads, nothing written outside a temp folder.
5
6    python -m unittest tools.test_setup_golden
7    python tools/test_setup_golden.py --write      (only to record a new baseline on purpose)
8"""
9from __future__ import annotations
10
11import contextlib
12import io
13import json
14import re
15import sys
16import tempfile
17import types
18import unittest
19from pathlib import Path
20from unittest import mock
21
22ROOT = Path(__file__).resolve().parents[1]
23sys.path.insert(0, str(ROOT))
24import setup  # noqa: E402
25
26GOLDEN = Path(__file__).with_name("test_setup_golden.json")
27
28
29def card(i, name, vram, arch):
30    return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": "580.97"}
31
32
33# the PCs: total RAM as ram_gb() reads it (a little under the label), the cards as nvidia-smi lists them
34PROFILES = {
35    "64GB-1x32GB": (63.7, [card(0, "NVIDIA GeForce RTX 5090", 31.8, "120")]),                  # #406
36    "32GB-2x24GB": (31.9, [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)]),  # #364
37    "47GB-2x16GB": (47.0, [card(i, "NVIDIA GeForce RTX 5060 Ti", 15.9, "120") for i in range(2)]),   # #384
38    "96GB-1x16GB": (95.8, [card(0, "NVIDIA GeForce RTX 5080", 15.9, "120")]),
39    "128GB-1x24GB": (127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89")]),
40}
41# (family, model): None = the recommended size
42MODELS = [("qwen", None), ("qwen", "Q2_0"), ("qwen", "IQ3_XXS"), ("qwen", "IQ3_S"), ("unsloth", "UD-Q4_K_XL")]
43
44
45class FakeGGUF:
46    """gguf_reader.GGUFFile: shard 2 holds the PLE table."""
47    def __init__(self, path):
48        names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"]
49        self.tensors = [types.SimpleNamespace(name=n) for n in names]
50
51
52def normalize(v, t: Path):
53    """The config with the temp folder and the platform's names taken out (it compares on Windows and Linux)."""
54    if isinstance(v, dict):
55        return {k: normalize(x, t) for k, x in v.items()}
56    if isinstance(v, list):
57        return [normalize(x, t) for x in v]
58    if isinstance(v, str):
59        v = v.replace(str(t), "<T>").replace("\\", "/")
60        # the platform's own names of the programs (strata.exe or strata, strata-vision.exe or strata-vision, ...) so the baseline compares on Windows and Linux (#3325)
61        for name, label in ((setup.HVEXE, "<HVEXE>"), (setup.VEXE, "<VEXE>"), (setup.EXE, "<EXE>")):
62            v = re.sub(rf"(?<![w.-]){re.escape(name)}(?![w.-])", label, v)   # #973: only the whole name, not "strata-x.log" on Linux
63        return v
64    return v
65
66
67def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()):
68    """setup.main() on a mocked PC -> (exit code, printed text, the written config or None, the questions asked).
69    answers: None = --yes (a question fails the run), "" = Enter for every question, a list of answers in order, or
70    {words of a question: its answer} (Enter for the others).
71    extra: more patches (mock.patch objects).  configs: (name, dict) run configs already in the Strata folder."""
72    with tempfile.TemporaryDirectory() as tmp:
73        t = Path(tmp)
74        (t / "data" / "mtp" / "rt").mkdir(parents=True)
75        (t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"")
76        eng = t / "engine"
77        eng.mkdir()
78        (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.32", "source": "local", "cuda_dirs": ["<cuda>"]}))
79        for name, c in configs:
80            (t / name).write_text(json.dumps(c))
81        asked = []
82
83        def fake_input(prompt=""):
84            asked.append(prompt)
85            if answers is None:
86                raise AssertionError(f"asked {prompt!r} with --yes")
87            if isinstance(answers, list):
88                return answers.pop(0) if answers else ""
89            if isinstance(answers, dict):                  # {words of the question: answer}, else Enter
90                return next((v for k, v in answers.items() if k in prompt), "")
91            return answers
92
93        def fake_download(url, dst, what=None):
94            dst.parent.mkdir(parents=True, exist_ok=True)
95            dst.write_bytes(b"")
96            setup.mark(dst)
97
98        patches = [
99            mock.patch.object(setup, "ROOT", t),
100            mock.patch.object(setup, "GPU_PICK", None),
101            mock.patch.object(setup, "data_folder", lambda d, *a, **k: (t / "data", [])),
102            mock.patch.object(setup, "load_settings", lambda: {}),
103            mock.patch.object(setup, "save_settings", lambda s: None),
104            mock.patch.object(setup, "gpus", lambda: found),
105            mock.patch.object(setup, "card_speeds", lambda: {}),
106            mock.patch.object(setup, "amd_gpus", lambda: []),
107            mock.patch.object(setup, "ram_gb", lambda: ram),
108            mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)),
109            mock.patch.object(setup, "cpu_cores", lambda: None),   # #642: not a hybrid CPU
110            mock.patch.object(setup, "vision_threads", lambda logical=None: 6),   # the baseline PC has 12 logical CPUs; the runner's own count must not change the golden config
111            mock.patch.object(setup, "page_file_gb", lambda: 16.0),
112            mock.patch.object(setup, "is_wsl", lambda: False),
113            mock.patch.object(setup, "rotational_disk", lambda p: None),   # #605: the test PC's own disk
114            mock.patch.object(setup, "ple_ram_platform_ok", lambda: False),   # 147-verify: the golden configs as on Windows
115            mock.patch.object(setup, "free_gb", lambda p: 900.0),
116            mock.patch.object(setup, "pip_install", lambda *a, **k: None),
117            mock.patch.object(setup, "get_llama_cpp", lambda: t / "llama.cpp"),
118            mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng),
119            mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None),
120            mock.patch.object(setup, "download", fake_download),
121            mock.patch.object(setup, "check_shards", lambda shards: None),
122            mock.patch.object(setup, "verify_sha256", lambda *a, **k: None),
123            mock.patch.object(setup, "run", lambda *a, **k: None),
124            mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False),
125            mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None),
126            mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: t / f"run-{tag}.bat"),
127            mock.patch.object(setup, "saved_calibration", lambda cfg: None),
128            mock.patch.object(setup, "calibrate_config", mock.Mock(side_effect=AssertionError("calibrated"))),
129            mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}),
130            mock.patch.object(sys, "argv", ["setup.py", "--models-dir", str(t / "models"), *argv]
131                              + (["--yes"] if answers is None else [])),
132            mock.patch("builtins.input", fake_input),
133            *extra,
134        ]
135        out = io.StringIO()
136        code = None
137        with contextlib.ExitStack() as st:
138            for p in patches:
139                st.enter_context(p)
140            with contextlib.redirect_stdout(out):
141                try:
142                    code = setup.main()
143                except SystemExit as e:
144                    code = e.code
145        # the config this run wrote: a new file or one whose bytes changed, not just the newest time (a fast run on a coarse clock, GitHub's
146        # Windows runner, wrote strata-iq3_s.json in the same tick as the strata-iq3_xxs.json put here before it, and the name order won)
147        before = {name: json.dumps(c) for name, c in configs}
148        changed = [p for p in t.glob("strata-*.json") if before.get(p.name) != p.read_text(encoding="utf-8")]
149        written = sorted(changed or t.glob("strata-*.json"), key=lambda p: p.stat().st_mtime_ns)
150        cfg = None
151        if written and code == 0:
152            cfg = normalize(json.loads(written[-1].read_text(encoding="utf-8")), t)
153            # "args_written" (strata_control/user_args.py): the arguments as setup wrote them, so a later hand edit can be told; the golden configs keep their own keys
154            assert cfg.pop("args_written", cfg.get("args")) == cfg.get("args"), "args_written is not the written args"
155        return code, out.getvalue(), cfg, asked
156
157
158def argv_for(family, model):
159    return ["--family", family, "--no-start"] + (["--model", model] if model else [])
160
161
162def record() -> dict:
163    """Every profile x model with --yes: the exit code and the config (the baseline this test compares against)."""
164    res = {}
165    for prof, (ram, found) in PROFILES.items():
166        for family, model in MODELS:
167            code, out, cfg, _ = install(ram, found, argv_for(family, model))
168            res[f"{prof} {family} {model or 'recommended'}"] = {"code": code, "config": cfg}
169    return res
170
171
172class Golden(unittest.TestCase):
173    """--yes and Enter: the same config as the baseline wherever the baseline wrote one."""
174
175    @classmethod
176    def setUpClass(cls):
177        cls.golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
178
179    def cases(self):
180        for prof, (ram, found) in PROFILES.items():
181            for family, model in MODELS:
182                key = f"{prof} {family} {model or 'recommended'}"
183                if self.golden[key]["code"] == 0:
184                    yield key, ram, found, family, model
185
186    def test_the_baseline_covers_every_kind_of_pc(self):
187        written = [k for k, v in self.golden.items() if v["code"] == 0]
188        self.assertGreaterEqual(len(written), 20)
189        lowram_multi = self.golden["32GB-2x24GB qwen IQ3_XXS"]["config"]   # #364 -> #642: low-RAM, two cards -> both
190        self.assertIn("--resident-experts" if "--resident-experts" in lowram_multi["args"] else "--mmap-experts",
191                      lowram_multi["args"])
192        self.assertEqual(lowram_multi.get("gpu"), [0, 1])                   # 0.1.40 (#642): resident on both cards; roles: Main 1 goes last, as before
193
194    def test_yes(self):
195        for key, ram, found, family, model in self.cases():
196            with self.subTest(key):
197                code, out, cfg, asked = install(ram, found, argv_for(family, model))
198                self.assertEqual(code, 0, out[-3000:])
199                self.assertEqual(cfg, self.golden[key]["config"], out[-3000:])
200                self.assertEqual(asked, [])
201
202    def test_enter_for_every_question(self):
203        for key, ram, found, family, model in self.cases():
204            if "UD-Q4_K_XL" in key and ram < 48:               # --yes consents to the risk; Enter declines it (the
205                continue                                       # "Install it anyway? [n]" question), by design
206            with self.subTest(key):
207                code, out, cfg, asked = install(ram, found, argv_for(family, model), answers="")
208                self.assertEqual(code, 0, out[-3000:])
209                self.assertEqual(cfg, self.golden[key]["config"], out[-3000:])
210
211    def test_the_refusals_with_yes_alone_stay(self):
212        """A size the baseline refused with --yes and no explicit --model still stops (--yes alone is no consent)."""
213        for prof, (ram, found) in PROFILES.items():
214            for family, model in MODELS:
215                key = f"{prof} {family} {model or 'recommended'}"
216                if self.golden[key]["code"] != 0 and model is None:
217                    with self.subTest(key):
218                        self.assertNotEqual(install(ram, found, argv_for(family, model))[0], 0)
219
220
221if __name__ == "__main__":
222    if "--write" in sys.argv:
223        GOLDEN.write_text(json.dumps(record(), indent=1, sort_keys=True) + "\n", encoding="utf-8")
224        print(f"wrote {GOLDEN}")
225    else:
226        unittest.main()