okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
13.1 KiB202 linesraw
1"""Qwen4 day on an Intel Arc card: a model of the signed feed (strata_control/feed_models.py) gets an Arc run config, in the Terminal (strata_cli/launch/adopt.py,
2runner.adopt_prepared_files) and in the app (setup.py --backend sycl in CONTROL mode, tools/strata_mcp.py's install plan).
3
4Found by the Q4-READY rehearsal on the A750 (11-09): `strata launch` of a feed model stopped with "Strata can write the settings itself only for the Qwen3.8-Flash-Next,
5Swift, Coder and Gyro files, not for q4rehearsal-a", for a model on the Strata engine and for one on its own shape's engine alike. What these tests pin:
6  * a feed model is laid out like Unsloth's sets: --native the first file, no --ple-gguf (the engine finds the n-gram table by its tensor name), its one GGUF when it is one file;
7  * no Flash-Next draft layer for it; an entry that says drafter: none writes "mtp": false and "drafting": "off" (as setup_config writes it);
8  * a model of its own shape names its engine component (component:strata-q4-lite) and the model's title for the engine's refusal;
9  * the expert profile comes from setup_config.neutral_profile_if_other_shape (the shipped one, or a neutral one for another shape);
10  * a family that is neither built in nor of the feed is refused with the same words as before, and the built-in families' configs are what they were.
11Offline: nothing runs but Python."""
12
13from __future__ import annotations
14
15import json
16import sys
17import tempfile
18import unittest
19from pathlib import Path
20from unittest import mock
21
22ROOT = Path(__file__).resolve().parents[2]
23sys.path.insert(0, str(ROOT))
24sys.path.insert(0, str(ROOT / "tools"))
25import setup  # noqa: E402
26import strata_mcp as M  # noqa: E402
27from strata_cli.launch import adopt  # noqa: E402
28from strata_control import intel_app, setup_config  # noqa: E402
29
30A750 = {"vendor": "intel", "name": "Intel Arc A750", "vram_gb": 8.0, "usable": True, "index": 0}
31
32
33def feed_family(model_id: str, *, shape: str | None = None, drafter: str = "none") -> dict:
34    """A family as strata_control/feed_models.py._flash_next makes it (the keys the Arc path reads)."""
35    fam = {"title": "Qwen4 Rehearsal", "by": "Qwen", "about": "x", "tag": model_id + "-", "name": model_id, "shards": 2, "vision": False, "feed": True,
36           "drafter": drafter, "pack_args": ["--compat-bf16"], "file": {}, "hf": {}, "sha256": {}, "license": "Apache 2.0"}
37    if shape:
38        fam["shape"] = shape
39    return fam
40
41
42class Tree:
43    """A data folder with a prepared pack, the model files, the Flash-Next draft layer folder and a Control folder with the shipped profile."""
44
45    def __init__(self, root: Path, pack_name: str, files: list[str]):
46        self.root = root
47        self.data = root / "Strata-data"
48        self.pack = self.data / "packs" / pack_name
49        (self.pack / "tokenizer").mkdir(parents=True)
50        (self.pack / "tokenizer" / "vocab.json").write_text("{}")
51        (self.pack / "index.txt").write_text("x")
52        (self.data / "mtp" / "rt").mkdir(parents=True)                     # the Flash-Next draft layer is on this PC: a feed model must still not get it
53        self.models = root / "models"
54        self.models.mkdir()
55        self.files = []
56        for name in files:
57            (self.models / name).write_bytes(b"x")
58            self.files.append(self.models / name)
59        self.src = root / "control"
60        (self.src / "data").mkdir(parents=True)
61        (self.src / "data" / "expert-profile.bin").write_bytes(b"STRP")
62
63    def plan(self, family: str, model: str, fam: dict, notes=None):
64        return adopt.plan(family=family, model=model, model_dir=self.models, data_dir=self.data, src=self.src, context=32768, kv="int8",
65                          model_name=f"{fam.get('name', family)}-{model.lower()}", family_def=fam, log=self.root / "x.log", backend="sycl", notes=notes,
66                          pack_name=self.pack.name)
67
68
69class AdoptFeedModels(unittest.TestCase):
70    def setUp(self):
71        self.tmp = tempfile.TemporaryDirectory()
72        self.addCleanup(self.tmp.cleanup)
73        self.root = Path(self.tmp.name)
74        p = mock.patch("strata_cli.launch.adopt.intel_driver", lambda: "i915")
75        p.start()
76        self.addCleanup(p.stop)
77        self.profiles = []
78
79        def neutral(shipped, first, pack, GGUFFile, say=print):                # what setup_config does, recorded (the real one reads the GGUF's header)
80            self.profiles.append((Path(shipped), Path(first), Path(pack)))
81            say("  This model's shape differs from Flash-Next, so a neutral expert profile is used.")
82            return Path(pack) / "expert-profile-4x256.bin"
83        p = mock.patch.object(setup_config, "neutral_profile_if_other_shape", neutral)
84        p.start()
85        self.addCleanup(p.stop)
86
87    def test_a_feed_model_on_the_strata_engine_is_laid_out_like_unsloths_sets(self):
88        t = Tree(self.root, "iq3_xxs-q4rehearsal-a", ["Q4R-IQ3_XXS-00001-of-00002.gguf", "Q4R-IQ3_XXS-00002-of-00002.gguf"])
89        notes = []
90        cfg, problems = t.plan("q4rehearsal-a", "IQ3_XXS-q4rehearsal-a", feed_family("q4rehearsal-a"), notes)
91        self.assertEqual(problems, [])
92        a = cfg["args"]
93        self.assertEqual(cfg["exe"], "component:strata-engine")
94        self.assertEqual(a[a.index("--native") + 1], str(t.files[0]))
95        self.assertNotIn("--ple-gguf", a)
96        self.assertNotIn("--mtp", a, "the Flash-Next draft layer is not a feed model's own")
97        self.assertEqual((cfg["mtp"], cfg["drafting"]), (False, "off"), "drafter: none -> no drafter at any start")
98        self.assertEqual(a[a.index("--expert-profile") + 1], str(t.pack / "expert-profile-4x256.bin"))
99        self.assertEqual(self.profiles, [(t.src / "data" / "expert-profile.bin", t.files[0], t.pack)])
100        self.assertIn("This model's shape differs from Flash-Next, so a neutral expert profile is used.", notes)
101        self.assertEqual((a[a.index("--ple-io") + 1], cfg["backend"]), ("ram", "sycl"))
102        self.assertNotIn("shape_title", cfg)
103
104    def test_a_model_of_its_own_shape_names_its_engine_and_may_be_one_file(self):
105        t = Tree(self.root, "ud-q4_k_xl-q4rehearsal-b", ["q4lite4.gguf"])
106        fam = feed_family("q4rehearsal-b", shape="q4_lite")
107        cfg, problems = t.plan("q4rehearsal-b", "UD-Q4_K_XL-q4rehearsal-b", fam)
108        self.assertEqual(problems, [])
109        self.assertEqual(cfg["exe"], "component:strata-q4-lite")
110        self.assertEqual(cfg["shape_title"], "Qwen4 Rehearsal")
111        self.assertEqual(cfg["args"][cfg["args"].index("--native") + 1], str(t.files[0]))
112        self.assertEqual(adopt.model_files(t.models, "q4rehearsal-b", fam), t.files)
113        self.assertEqual(adopt.model_files(t.models, "qwen", {}), [], "a built-in GSQ-RCO family still needs its numbered shards")
114
115    def test_a_feed_model_with_a_drafter_still_gets_no_flash_next_draft_layer(self):
116        t = Tree(self.root, "iq3_xxs-q4rehearsal-a", ["Q4R-IQ3_XXS-00001-of-00002.gguf", "Q4R-IQ3_XXS-00002-of-00002.gguf"])
117        cfg, _ = t.plan("q4rehearsal-a", "IQ3_XXS-q4rehearsal-a", feed_family("q4rehearsal-a", drafter="mtp"))
118        self.assertNotIn("--mtp", cfg["args"])
119        self.assertNotIn("drafting", cfg)
120
121    def test_a_family_neither_built_in_nor_of_the_feed_is_refused_as_before(self):
122        t = Tree(self.root, "x", ["Q4R-00001-of-00002.gguf", "Q4R-00002-of-00002.gguf"])
123        cfg, problems = t.plan("q4rehearsal-a", "X", {"title": "x", "tag": "x-"})
124        self.assertIsNone(cfg)
125        self.assertEqual(problems, ["Strata can write the settings itself only for the Qwen3.8-Flash-Next, Swift, Coder and Gyro files, not for q4rehearsal-a"])
126
127    def test_the_built_in_families_are_what_they_were(self):
128        t = Tree(self.root, "q2_0", ["Qwen3.8-Flash-Next-Q2_0-00001-of-00002.gguf", "Qwen3.8-Flash-Next-Q2_0-00002-of-00002.gguf"])
129        cfg, problems = t.plan("qwen", "Q2_0", setup.FAMILIES["qwen"])
130        self.assertEqual(problems, [])
131        self.assertEqual(cfg["args"], ["--pack", str(t.pack), "--native", str(t.files[0]), "--ple-gguf", str(t.files[-1]),
132                                       "--expert-profile", str(t.src / "data" / "expert-profile.bin"), "--expert-cache", "auto", "--prefill", "auto",
133                                       "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(t.data / "mtp" / "rt"), "--max-context", "32768", "--kv", "int8",
134                                       "--ple-io", "ram", "--vram-reserve-mib", "1024"])
135        self.assertEqual(sorted(cfg), ["args", "backend", "cwd", "exe", "lib_dirs", "log", "model_name", "port", "tokenizer"])
136        self.assertEqual(self.profiles, [], "a built-in family never reads its GGUF for the profile")
137
138
139class AppArcPath(unittest.TestCase):
140    """The app: tools/strata_mcp.py plans `--backend sycl` for a feed model on an Arc, and setup.py's CONTROL mode fetches a shape engine, packs and writes the config."""
141
142    def setUp(self):
143        self.tmp = tempfile.TemporaryDirectory()
144        self.addCleanup(self.tmp.cleanup)
145        self.root = Path(self.tmp.name)
146        fams = {"q4rehearsal-a": feed_family("q4rehearsal-a"), "q4rehearsal-b": feed_family("q4rehearsal-b", shape="q4_lite")}
147        models = {"IQ3_XXS-q4rehearsal-a": {"about": "x", "download_gb": 75.8, "ram_gb": 40, "arena_gb": 40, "families": ("q4rehearsal-a",), "shards": 2,
148                                             "file": "Q4R-IQ3_XXS-{i:05d}-of-00002.gguf", "quant": "IQ3_XXS", "vision": False, "budget": True},
149                  "UD-Q4_K_XL-q4rehearsal-b": {"about": "x", "download_gb": 3.5, "ram_gb": 8, "arena_gb": 3, "families": ("q4rehearsal-b",), "shards": 1,
150                                                "file": "q4lite4.gguf", "quant": "UD-Q4_K_XL", "vision": False, "budget": True}}
151        for p in (mock.patch.dict(setup.FAMILIES, fams), mock.patch.dict(setup.MODELS, models)):
152            p.start()
153            self.addCleanup(p.stop)
154
155    def test_the_arc_install_plan_takes_a_feed_model(self):
156        folder = self.root / "q4"
157        folder.mkdir()
158        for i in (1, 2):
159            (folder / f"Q4R-IQ3_XXS-{i:05d}-of-00002.gguf").write_bytes(b"x")
160        self.assertTrue(intel_app.can_set_up("q4rehearsal-a", setup.FAMILIES["q4rehearsal-a"]))
161        self.assertFalse(intel_app.can_set_up("deepseek41", {"title": "DeepSeek"}))
162        s = M.Strata(ROOT)
163        s._setup, s._setup_tried = setup, True                              # the tables with the feed models in them (as feed_models_setup adds them)
164        s.hardware = lambda fresh=False: {"ram_gb": 64.0, "gpus": [dict(A750)], "cpu": {"avx2": True}, "engine_vendor": "intel"}
165        s.disk_free = lambda p: 1000.0
166        with mock.patch.object(M.sys, "platform", "linux"), mock.patch.object(M, "WIN", False):
167            _plan, args = M.Tools(s).install_plan("q4rehearsal-a", "IQ3_XXS-q4rehearsal-a", 32768, "no", "int8", None, None, None, None, None, None, str(folder), "dflash2")
168        self.assertEqual(args[args.index("--family") + 1], "q4rehearsal-a")
169        self.assertEqual(args[-2:], ["--backend", "sycl"])
170        self.assertNotIn("--drafter", args)
171
172    def test_setup_control_mode_fetches_the_shape_engine_and_writes_its_config(self):
173        folder, data, home = self.root / "b", self.root / "Strata-data", self.root / "install"
174        for d in (folder, data, home):
175            d.mkdir()
176        (folder / "q4lite4.gguf").write_bytes(b"x")
177        fetched = []
178
179        def fake_pack(args):
180            pack = Path(args.prepare_pack)
181            (pack / "tokenizer").mkdir(parents=True, exist_ok=True)
182            (pack / "tokenizer" / "vocab.json").write_text("{}")
183            (pack / "index.txt").write_text("x")
184            return 0
185        a = mock.Mock(family="q4rehearsal-b", model="UD-Q4_K_XL-q4rehearsal-b", gguf_dir=str(folder), models_dir=None, data_dir=None, context=32768, kv="int8",
186                      port=None, host=None, api_key=None, browser=None, check=False, yes=True, move_data=False, set_default_data_dir=False, prepare_pack=None, feed=None)
187        with mock.patch.object(setup, "CONTROL", True), mock.patch.object(setup, "_CONTROL_HOME", home), \
188                mock.patch.object(setup, "data_folder_for", lambda a: (data, [])), mock.patch.object(setup, "prepare_pack_only", fake_pack), \
189                mock.patch.object(setup, "shape_engine_fetch", lambda a: fetched.append(dict(setup.SHAPE_ENGINE))), \
190                mock.patch.object(setup_config, "neutral_profile_if_other_shape", lambda shipped, first, pack, G, say=print: Path(pack) / "expert-profile-4x256.bin"), \
191                mock.patch.object(intel_app, "arc_cards", lambda root="": [dict(A750)]), \
192                mock.patch("strata_cli.launch.adopt.intel_driver", lambda: "i915"), \
193                mock.patch.object(intel_app, "supported_here", lambda platform=None: True):
194            self.assertEqual(setup.intel_control_setup(a), 0)
195        self.assertEqual(fetched, [{"shape": "q4_lite", "title": "Qwen4 Rehearsal"}])
196        cfg = json.loads((home / "strata-q4rehearsal-b-ud-q4_k_xl-q4rehearsal-b.json").read_text(encoding="utf-8"))
197        self.assertEqual((cfg["exe"], cfg["backend"], cfg["drafting"], cfg["mtp"]), ("component:strata-q4-lite", "sycl", "off", False))
198        self.assertEqual(cfg["shape_title"], "Qwen4 Rehearsal")
199
200
201if __name__ == "__main__":
202    unittest.main()