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
9.8 KiB153 linesraw
1"""Write a run config from model files that are already prepared, for graphics cards the installer (setup.py) does not set up.
2
3setup.py's Linux paths know NVIDIA (CUDA) and AMD (HIP); an Intel Arc card goes to a different, container-based setup (`--backend sycl`, docs/INTEL_ARC.md)
4that this Terminal does not run. When setup says it cannot set this card up, and the model's files AND its prepared pack are already on disk (a box that was
5prepared before, "use model files I already have"), the run config is simple enough to write here: the same arguments setup writes for the GSQ-RCO models,
6with the engine named as the component (`component:strata-engine`). Nothing is downloaded, prepared or compiled; if a file is missing the person is told which.
7
8Only the GSQ-RCO families (qwen, swift, coder), Gyro (one GGUF with its n-gram table inside), Unsloth's sets and the models of the signed feed (strata_control/feed_models.py:
9a qwen4exp model laid out like Unsloth's sets, or a model of its own shape on that shape's engine component) are adopted this way; images stay off.
10"""
11
12from __future__ import annotations
13
14import json
15import re
16from pathlib import Path
17
18SHARD = re.compile(r"^(?P<stem>.+)-(?P<i>\d{5})-of-(?P<n>\d{5})\.gguf$")
19FAMILIES = ("qwen", "swift", "coder", "gyro", "unsloth")      # the catalog offers Gyro-S / Gyro-M on an Arc card too (round 8, N11); Unsloth's sets since round 0214 (ENG-AMD: UD-IQ1_M ran on an Arc A750)
20UNSUPPORTED = ("no nvidia gpu found", "no amd gpu", "nvidia gpu", "not supported", "cannot be used")
21
22
23def setup_cannot_handle_this_card(message: str) -> bool:
24    low = (message or "").lower()
25    return ("no nvidia gpu found" in low or "no amd gpu strata can use" in low or "nvidia-smi did not answer" in low
26            or "no mac model installer" in low)
27
28
29def intel_driver() -> str:
30    """The kernel driver of the first Intel graphics card: "i915" (an A-series Arc) or "xe" (a B-series Arc), "" when it cannot be read."""
31    import glob
32    import os
33    for card in sorted(glob.glob("/sys/class/drm/card[0-9]/device")):
34        try:
35            if Path(card, "vendor").read_text().strip() != "0x8086":
36                continue
37            return os.path.basename(os.path.realpath(os.path.join(card, "driver")))
38        except OSError:
39            continue
40    return ""
41
42
43def find_shards(folder: Path) -> list[Path]:
44    """The shards of one GGUF set in `folder` (-00001-of-0000N ... -0000N-of-0000N), sorted; [] if the set is incomplete."""
45    found: dict[tuple[str, int], dict[int, Path]] = {}
46    for p in sorted(Path(folder).glob("*.gguf")):
47        m = SHARD.match(p.name)
48        if m:
49            found.setdefault((m.group("stem"), int(m.group("n"))), {})[int(m.group("i"))] = p
50    for (_stem, n), items in found.items():
51        if set(items) == set(range(1, n + 1)):
52            return [items[i] for i in range(1, n + 1)]
53    return []
54
55
56def find_single(folder: Path) -> list[Path]:
57    """The one model file of a Gyro folder (a single GGUF, not a picture reader); [] when there is none or several."""
58    files = [p for p in sorted(Path(folder).glob("*.gguf")) if not p.name.lower().startswith("mmproj")]
59    return files if len(files) == 1 else []
60
61
62def model_files(folder: Path, family: str, family_def: dict | None = None) -> list[Path]:
63    """The model files plan() runs: Gyro's one file; a GGUF set's shards; a feed model's shards, or its one file when it is a single GGUF."""
64    if family == "gyro":
65        return find_single(folder)
66    return find_shards(folder) or (find_single(folder) if (family_def or {}).get("feed") else [])
67
68
69def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path, context: int, kv: str | None, model_name: str, family_def: dict,
70         log: Path, backend: str | None, vram_gb: float = 0.0, notes: list | None = None, pack_name: str | None = None) -> tuple[dict | None, list[str]]:
71    """(config, problems): the config to write, or None with plain-words problems (what is missing). `pack_name`: the pack folder under
72    packs/ (default the model's name in lower case; Gyro's is its tag, gyro-gyro-s)."""
73    problems: list[str] = []
74    feed = bool((family_def or {}).get("feed"))     # a model of the signed feed (Qwen4 day): the Unsloth layout, its own shape's engine when it has one
75    if family not in FAMILIES and not feed:
76        # no full stop: the caller joins the problems with "; " and ends the sentence (a "gyro.." came out of the old text, round 8, N11)
77        return None, [f"Strata can write the settings itself only for the Qwen3.8-Flash-Next, Swift, Coder and Gyro files, not for {family}"]
78    shards = model_files(model_dir, family, family_def)
79    if not shards:
80        problems.append(f"the model file is not in {model_dir}" if family == "gyro" else
81                        f"the model files are not all in {model_dir} (every -0000N-of-0000N.gguf shard is needed)")
82    pack = Path(data_dir) / "packs" / (pack_name or model.lower())
83    if not (pack / "experts.bin").exists() and not (pack / "index.txt").exists():
84        problems.append(f"the prepared pack {pack} is missing (this installer cannot prepare it for this graphics card)")
85    tokenizer = pack / "tokenizer"
86    if not tokenizer.exists():
87        problems.append(f"the tokenizer {tokenizer} is missing")
88    profile = src / "data" / (family_def.get("profile") or "expert-profile.bin")
89    if not profile.exists():
90        problems.append(f"the expert profile {profile} is missing")
91    if problems:
92        return None, problems
93    if feed:
94        # a model of another shape than the shipped profile's (48 x 512) gets a neutral profile in its pack folder, as setup.py does for it (the owner's line)
95        import sys
96        tools = str(Path(src) / "tools")
97        if tools not in sys.path:
98            sys.path.insert(0, tools)
99        from gguf_reader import GGUFFile
100        from strata_control.setup_config import neutral_profile_if_other_shape
101        profile = neutral_profile_if_other_shape(profile, shards[0], pack, GGUFFile, (lambda line: notes.append(line.strip())) if notes is not None else (lambda line: None))
102    mtp = Path(data_dir) / "mtp" / "rt"
103    args = ["--pack", str(pack), "--native", str(shards[0])]
104    if family != "unsloth" and not feed and (len(shards) > 1 or family == "gyro"):            # Gyro's one file holds the n-gram table too
105        args += ["--ple-gguf", str(shards[-1])]      # (Unsloth's 3-6 shards: the engine finds the n-gram table by its tensor name, as setup.py writes the config; it is shard 2, 3 or the last one by set)
106    if backend == "metal":
107        # a Mac: the Metal defaults metal/setup_mac.py writes for a model that streams from the SSD (one token per step, no draft layer, the GGUF mapped in place)
108        args += ["--expert-profile", str(profile), "--expert-cache", "64", "--prefill", "auto", "--spec", "2", "--suffix-draft", "0",
109                 "--max-context", str(context), "--mmap-experts"]
110    else:
111        args += ["--expert-profile", str(profile), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5"]
112        if mtp.exists() and not feed:                    # the Flash-Next draft layer is not a feed model's own (a feed entry carries no MTP head yet)
113            args += ["--mtp", str(mtp)]
114        args += ["--max-context", str(context), "--kv", kv or ("int8" if context > 8192 else "fp16")]
115        if backend == "sycl":
116            # an Intel Arc, as sycl/setup_intel.py writes it: an A-series card on i915 loads the experts into a RAM arena and the CPU computes the misses
117            # (--ple-io ram); every other Arc (xe: the B70) streams the experts from the GGUF into VRAM (--stream-experts); both keep a VRAM reserve
118            reserve = "1024" if context <= 32768 else "2048"
119            if vram_gb:                                  # 0.2.2: a card a few hundred MiB short gets a smaller context / reserve (vram_fit)
120                from strata_control import vram_fit
121                fr = vram_fit.plan(model, vram_gb, context, kv or "int8", int(reserve), "auto", "intel", title=model, ctx_fixed=True)   # the context was settled by max_context or the person
122                if fr.changed:
123                    args[args.index("--max-context") + 1] = str(fr.ctx)
124                    reserve = str(fr.reserve_mib)
125                    if fr.prefill:
126                        args[args.index("--prefill") + 1] = fr.prefill
127                    if notes is not None:
128                        notes.append(fr.line)
129            if intel_driver() == "i915":
130                args += ["--ple-io", "ram", "--vram-reserve-mib", reserve]
131            else:
132                args += ["--stream-experts", "--vram-reserve-mib", reserve]
133    exe = "component:strata-engine"
134    if feed and family_def.get("shape"):
135        from strata_control import shape_engine
136        exe = shape_engine.reference(family_def["shape"])          # the engine of the model's shape (strata_control/shape_engine.py), installed beside the Strata engine
137    cfg = {"exe": exe, "args": args, "cwd": str(src), "tokenizer": str(tokenizer), "model_name": model_name,
138           "log": str(log), "lib_dirs": [], "port": 8080}
139    if backend == "metal":
140        cfg["env"] = {"STRATA_METAL_STREAM": "1"}
141    if feed and family_def.get("shape") and family_def.get("title"):
142        cfg["shape_title"] = family_def["title"]                  # the engine's refusal at a start names the model (as setup.py writes it)
143    if feed and family_def.get("drafter") == "none":
144        cfg["mtp"] = False                                         # the feed says this model has no draft layer: no drafter at any start (as setup_config writes it)
145        cfg["drafting"] = "off"
146    if backend:
147        cfg["backend"] = backend
148    return cfg, []
149
150
151def write(path: Path, cfg: dict) -> None:
152    Path(path).parent.mkdir(parents=True, exist_ok=True)
153    Path(path).write_text(json.dumps(cfg, indent=1) + "\n", encoding="utf-8")