okami.mom/strata

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

Niko1221Merge f-0213-shape (61d883315): a new-shape Qwen4 engine ships as its own component strata-q4-<shape> beside the Strata engine, picked by the model (owner 11-08: separate components; wording approved 'A ok, 1 yes, 2 later, 3 yes') - feed member shape_engines, setup/launch/update/Mac paths, strata --geometry checked against the signed manifest at install, older Controls never offer the model; l620 e2e (Flash-Next engine hash unchanged), Windows long-path install, Mac m1002 rund5d5b0837

main
17.8 KiB276 linesraw
1"""The Mac's model rules: which packs a Mac can run, whether one stays resident or streams its experts from the SSD, the
2Metal defaults of a run config. ONE definition, read by metal/setup_mac.py (a Mac that builds the engine itself), by setup.py's
3Control mode (the app and the Terminal on a Mac: model files only, the engine is a component) and by tools/strata_mcp.py (the
4model list, the fit words and the recommendation both show). Pure: nothing here downloads, builds or starts anything.
5
6Unified memory: a Mac has one pool. Metal keeps a share of it resident (GPU_SHARE; on a big Mac the memory less what macOS and
7its file cache keep), a pack that does not fit streams its experts from the SSD (the engine decides by itself).
8"""
9from __future__ import annotations
10
11import platform
12import subprocess
13from pathlib import Path
14
15MIN_MACOS = (15, 0)        # MTLResidencySet (the engine keeps every buffer resident through one)
16
17# The Mac's packs.  shard1_gb: the file the GPU maps (resident in unified memory while the model runs); the n-gram
18# table (shard 2, 28.8 GB) is read from the SSD a few rows at a time.  tested: measured on the M5 Max (docs/MAC.md).
19# Round 0214: ONE switch for Unsloth's v3.1 sets that have Q5_0 expert downs (UD-IQ2_XS and UD-Q2_K_XL: one layer, UD-Q3_K_XL: 20, the v3.1 UD-IQ4_XS: 33).  The Metal engine
20# has no Q5_0 down kernel yet (moe.metal's DN_SET stops at Q5_1 / Q8_0 / Q2_0 / IQ4_NL), so those four are listed with "missing" (the Terminal's menu leaves them out, --model
21# names them and says so) until the METAL stream lands the kernel and flips this to True.  The other new sets use kernels the Mac has.  UD-IQ1_S needs no entry (never offered).
22METAL_Q5_0_DOWN = True
23_NO_Q5_0 = {} if METAL_Q5_0_DOWN else {"missing": "the Q5_0 expert kernels"}
24MAC_MODELS = {
25    "Q2_0": {"shard1_gb": 37.6, "tested": True},
26    "IQ3_XXS": {"shard1_gb": 47.0, "tested": True},
27    "IQ3_S": {"shard1_gb": 54.8, "tested": True},
28    # Unsloth's ~4-6-bit files (family "unsloth", 4-6 shards cutting through layers): setup repacks the experts and
29    # dense tensors into one GGUF for the GPU (metal/tools/metal_repack.py); shard1_gb is that file, the n-gram
30    # table stays in its shard on the SSD
31    # (the sets below are the v3.1 files: shard1_gb = their download less the 28.8 GB n-gram table; nothing of them was run on a Mac yet)
32    "UD-IQ1_M": {"shard1_gb": 39.2, "tested": False, "family": "unsloth", "shards": 3},
33    "UD-Q2_0": {"shard1_gb": 41.7, "tested": False, "family": "unsloth", "shards": 3},
34    "UD-IQ2_XS": {"shard1_gb": 47.0, "tested": False, "family": "unsloth", "shards": 3, **_NO_Q5_0},
35    "UD-Q2_K_XL": {"shard1_gb": 50.8, "tested": False, "family": "unsloth", "shards": 4, **_NO_Q5_0},
36    "UD-IQ3_XXS": {"shard1_gb": 54.8, "tested": False, "family": "unsloth", "shards": 4},
37    "UD-Q3_K_XL": {"shard1_gb": 60.7, "tested": False, "family": "unsloth", "shards": 4, **_NO_Q5_0},
38    "UD-IQ4_XS-v31": {"shard1_gb": 64.9, "tested": False, "family": "unsloth", "shards": 4, **_NO_Q5_0},
39    "UD-Q4_K_XL": {"shard1_gb": 82.6, "tested": True, "family": "unsloth", "shards": 4},
40    "UD-Q5_K_XL": {"shard1_gb": 103.9, "tested": True, "family": "unsloth", "shards": 6},
41    "UD-Q6_K_XL": {"shard1_gb": 114.8, "tested": True, "family": "unsloth", "shards": 6},
42    # agentionai's Gyro files (family "gyro", docs/GYRO.md): ONE file with the n-gram table inside (58.5 / 92.0 GB to download);
43    # shard1_gb is what the GPU needs of it, without that table (the engine reads the table from the SSD a few rows at a time).
44    # The trellis experts run on the Metal engine from the release that added metal/kernels' TQ types (docs/MAC.md).
45    "Gyro-S": {"shard1_gb": 29.7, "tested": True, "family": "gyro", "shards": 1, "file_gb": 58.5},
46    "Gyro-M": {"shard1_gb": 63.2, "tested": False, "family": "gyro", "shards": 1, "file_gb": 92.0},
47}
48
49# The recommended sizes (owner's decision): IQ3_S is the default where it stays resident, UD-Q4_K_XL the higher-quality one
50RECOMMENDED = ("IQ3_S", "UD-Q4_K_XL")   # the owner's recommended sizes (UD-IQ4_XS is not offered on Mac yet)
51# a pack that does not fit Metal's share streams its experts from the SSD (the engine decides by itself, f-mac-ssd):
52# measured on a 32 GB M4 Mac mini, one token per step (MTP is slower there: its layer's memory is worth more as cache)
53STREAM_MEASURED = {"Q2_0": "~14 tok/s", "IQ3_XXS": "~10 tok/s"}
54STREAM_COPY_GAIN = "decoding about 15%, prompts about 25%"   # without the experts' copy, on the 32 GB M4 (IQ3_XXS)
55# A streaming Mac with this much memory keeps most of the experts in its arena (the 128 GB M5 Max: 80% of UD-Q5_K_XL's):
56# there the draft layer pays, and a longer window pays more because every window costs a fixed hand-shake per layer
57# (UD-Q5_K_XL, story: 28 tok/s without MTP, 41.8 at --spec 2, 50.6 at --spec 3). Smaller Macs stream without it.
58STREAM_MTP_FROM_GB = 96
59STREAM_SPEC = 3
60# A resident IQ3_S or Q2_0 pack runs a 3-token window with --spec-min-p 0.5 (the draft layer extends the window only when sure):
61# M5 Max, MTP, 5 interleaved pairs, identical tokens, over --spec 2: IQ3_S story / code / JSON / agent turn -0.9% / +2.5% / +16.7% /
62# +4.9%; Q2_0 +0.4% / +11.5% / +6.3% / +1.9% (phaseA-tests/mac-q/RESULTS.md sections 14 and 15).  Other sets are not measured: --spec 2.
63# The expert-pruned Coder (256 experts, IQ1_M) story / code / JSON / agent turn -2.5% / +7.1% / +9.3% / +12.5%, 5 pairs, identical tokens
64# (section 31.1 of the same file; it has no Mac setup entry yet, the name is what a config for it would pass).
65SPEC3_MODELS = ("IQ3_S", "Q2_0", "CODER")
66SPEC3_MIN_P = "0.5"
67# STRATA_METAL_F16 (the fp16 decode windows, PR 4807) is the ENGINE's default for a resident IQ3_S or Q2_0 pack since 0.2.13 (metal window.cpp
68# f16_auto_for, found from the GGUF file name).  M5 Max: decode +9 to +15% (Q2_0) and +9 to +12% (IQ3_S); top-1 agreement 97.1% / 96.2%, mean KL
69# 0.009 / 0.016; the 61-task suite passed the same tasks.  STRATA_METAL_F16=0 in the config's env turns it off.  Setup writes nothing for it.
70
71
72def spec_args(model: str, stream: bool, mtp: bool) -> list[str]:
73    """The window flags for a Mac config: --spec 3 --spec-min-p 0.5 for a resident IQ3_S or Q2_0 pack, STREAM_SPEC when the model
74    streams from the SSD with the draft layer, else --spec 2."""
75    if stream and mtp:
76        return ["--spec", str(STREAM_SPEC)]
77    if mtp and not stream and (model or "").upper() in SPEC3_MODELS:
78        return ["--spec", "3", "--spec-min-p", SPEC3_MIN_P]
79    return ["--spec", "2"]
80# beside the mapped file: the prompt kernels' buffers (chunks of 2,048 rows), the KV cache, the draft layer, the
81# Q8_0 copies of the hyper-connection matrices and the macOS desktop
82OVERHEAD_GB = 8.0
83# the share of the unified memory Metal lets one process keep resident (recommendedMaxWorkingSetSize): 107.5 of 128 GB
84# measured on the M5 Max; 3/4 is the conservative rule for the other sizes
85GPU_SHARE = 0.75
86# what a Mac of BIG_MAC_GB or more leaves to macOS, its file cache and the user's other programs when the pack stays RESIDENT
87# (the engine's resident_cap in arena_budget.h, the same rule).  A resident pack is mapped file pages: clean, so macOS can
88# drop them, never compress them.  Measured on the 128 GB M5 Max, UD-Q4_K_XL resident (wired 91.7 GB, 67%) with a 40 GB file
89# write and a 16 GB program beside it: no swap-out, nothing compressed.  (The streaming arena is anonymous memory and gets a
90# tighter cap in the engine: 40% left, from the same measurements.)
91RESIDENT_LEAVE_SHARE = 0.30
92BIG_MAC_GB = 64.0
93GIB_GB = 1.073741824    # a GiB in GB: ram_gb is binary, the model sizes are decimal
94CONTEXTS = [8192, 32768, 65536, 131072]
95MAC_ABOUT = {"UD-IQ1_M": "~1-bit (Unsloth Dynamic v3.1), the smallest download",
96             "UD-Q2_0": "2-bit (Unsloth Dynamic v3.1)",
97             "UD-IQ2_XS": "2-bit i-quant (Unsloth Dynamic v3.1)",
98             "UD-Q2_K_XL": "2-bit (Unsloth Dynamic v3.1) with some 3-bit experts",
99             "UD-IQ3_XXS": "3-bit i-quant (Unsloth Dynamic v3.1)",
100             "UD-Q3_K_XL": "3-bit (Unsloth Dynamic v3.1) with some 4-bit experts",
101             "UD-IQ4_XS-v31": "~4-bit i-quant (Unsloth Dynamic v3.1), a newer file than UD-IQ4_XS with other tensor types",
102                          "Q2_0": "2-bit, the fastest", "IQ3_XXS": "3-bit i-quant, better quality",
103             "IQ3_S": "3.5-bit i-quant, the best quality (matches the full model), the slowest",
104             "UD-Q4_K_XL": "Unsloth ~4.5-bit (111 GB download)", "UD-Q5_K_XL": "Unsloth ~5.5-bit (158 GB download)",
105             "UD-Q6_K_XL": "Unsloth ~6.5-bit (169 GB download)",
106             "Gyro-S": "agentionai's trellis experts, the smallest (58 GB download, the n-gram table is inside it)",
107             "Gyro-M": "agentionai's trellis experts, about IQ3_XXS quality in less memory (92 GB download)"}
108TESTED_CONTEXT = 32768     # needles and the KL harness ran to 32K on the Mac
109# Below this much unified memory the app says a model does not fit (a Mac this small was never run: 32 GB is the smallest that was).
110# The Terminal keeps its rule of recommending and never forcing: the person can still pick one there.
111MIN_STREAM_RAM_GB = 16.0
112
113
114def _sysctl(name: str, run=subprocess.run) -> str:
115    try:
116        return run(["sysctl", "-n", name], capture_output=True, text=True, timeout=10).stdout.strip()
117    except (OSError, subprocess.SubprocessError):
118        return ""
119
120
121def mac_info(run=subprocess.run) -> dict:
122    """The chip, its unified memory, macOS, the architecture and the Command Line Tools."""
123    chip = _sysctl("machdep.cpu.brand_string", run) or "unknown chip"
124    try:
125        ram = int(_sysctl("hw.memsize", run) or 0) / 2 ** 30   # GB as Apple sells them (128 GB = 2^37 bytes)
126    except ValueError:
127        ram = 0.0
128    try:
129        ver = run(["sw_vers", "-productVersion"], capture_output=True, text=True, timeout=10).stdout.strip()
130    except (OSError, subprocess.SubprocessError):
131        ver = ""
132    try:
133        clt = run(["xcode-select", "-p"], capture_output=True, text=True, timeout=10)
134        clt_path = clt.stdout.strip() if clt.returncode == 0 else ""
135    except (OSError, subprocess.SubprocessError):
136        clt_path = ""
137    # platform.machine() is the PYTHON's build: an Intel Python running through Rosetta says x86_64 on an M1 Max (#3894). The chip name
138    # (Rosetta passes "Apple M1 Max" through) and hw.optional.arm64 say what the Mac is.
139    python_arm = platform.machine() == "arm64"
140    mac_arm = python_arm or _sysctl("hw.optional.arm64", run) == "1" or chip.startswith("Apple")
141    return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": mac_arm, "rosetta_python": mac_arm and not python_arm,
142            "clt": clt_path, "perf_cores": int(_sysctl("hw.perflevel0.physicalcpu", run) or 0)}
143
144
145def macos_tuple(ver: str) -> tuple:
146    try:
147        return tuple(int(x) for x in ver.split(".")[:2])
148    except ValueError:
149        return (0, 0)
150
151
152def mac_problems(info: dict, need_compiler: bool = True) -> list[str]:
153    """What stops the setup on this Mac (each with what to do). The app brings a ready-made engine and compiles nothing:
154    need_compiler=False leaves the Command Line Tools out."""
155    p = []
156    if not info["arm64"]:
157        p.append(f"this Mac has an Intel CPU ({info['chip']}): the Metal engine needs Apple Silicon (M1 or newer)")
158    if macos_tuple(info["macos"]) < MIN_MACOS:
159        p.append(f"macOS {info['macos'] or '?'}: the Metal engine needs macOS {MIN_MACOS[0]} or newer (System Settings "
160                 "> General > Software Update)")
161    if need_compiler and not info["clt"]:
162        p.append("the Command Line Tools are missing (the compiler the engine is built with): run "
163                 "`xcode-select --install`, then this setup again")
164    return p
165
166
167def gpu_budget_gb(ram_gb: float) -> float:
168    """The most a resident pack may hold, in GB: Metal's working set, and on a big Mac the RAM less what macOS and the file
169    cache keep (the engine's resident_cap: min of the two)."""
170    ws = ram_gb * GPU_SHARE * GIB_GB
171    if ram_gb >= BIG_MAC_GB:
172        return min(ws, ram_gb * GIB_GB * (1.0 - RESIDENT_LEAVE_SHARE))
173    return ws
174
175
176# The families the Mac app (setup.py's mac_control_setup and the app's model list) installs: the GSQ-RCO Qwen files, Unsloth's sets (several shards:
177# metal/tools/metal_repack.py writes one GGUF for the GPU) and Gyro.  A set with "missing" is left out (METAL_Q5_0_DOWN above).
178APP_FAMILIES = ("qwen", "unsloth", "gyro")
179#: the signed feed's models that run on a Mac (strata_control/feed_models.py adds them; empty without a feed list)
180FEED_FAMILIES: list = []
181
182
183def all_families() -> tuple:
184    """The families the Mac app and Terminal offer: the built-in ones, then the signed feed's."""
185    return (*APP_FAMILIES, *FEED_FAMILIES)
186# What the repack and the pack work in beside the shards (the Mac install path counts it; the repacked file is MAC_MODELS' shard1_gb).
187REPACK_WORK_GB = 6.0
188
189
190def app_sizes(family: str) -> list[str]:
191    """The sizes the Mac app offers for a family: every MAC_MODELS entry of it that the Metal engine can run."""
192    return [m for m, d in MAC_MODELS.items() if d.get("family", "qwen") == family and not d.get("missing")]
193
194
195def repacked_gb(model: str) -> float:
196    """The disk the repacked GGUF takes (GB): shard1_gb for a many-shard Unsloth set, 0 for a file the engine maps as it is."""
197    d = MAC_MODELS.get(model, {})
198    return float(d["shard1_gb"]) if d.get("family") == "unsloth" and int(d.get("shards", 2)) > 2 else 0.0
199
200
201def install_disk_gb(model: str, download_left_gb: float) -> float:
202    """The free disk an install needs: what is still to download, the repacked file, and room to work."""
203    return float(download_left_gb) + repacked_gb(model) + REPACK_WORK_GB
204
205
206def model_need_gb(model: str) -> float:
207    return MAC_MODELS[model]["shard1_gb"] + OVERHEAD_GB
208
209
210def streams(model: str, ram_gb: float) -> bool:
211    """The pack does not fit Metal's share of the memory: the engine streams its experts from the SSD."""
212    return model_need_gb(model) > gpu_budget_gb(ram_gb)
213
214
215def recommend_model(ram_gb: float) -> tuple[str, list[str]]:
216    """The default pack and the notes that go with it. IQ3_S and UD-Q4_K_XL are the recommended sizes (RECOMMENDED):
217    the default is IQ3_S when it stays resident, with UD-Q4_K_XL named as the higher-quality choice where it fits too;
218    below that the largest pack that stays resident (IQ3_XXS, Q2_0); nothing fits: Q2_0 streamed from the SSD."""
219    if not streams("IQ3_S", ram_gb):
220        notes = []
221        if not streams("UD-Q4_K_XL", ram_gb):
222            notes.append("UD-Q4_K_XL (recommended too) also fits this Mac: higher quality than IQ3_S (92.8% top-1 against "
223                         "Q8_0 where IQ3_S has 87.9%), about 20% slower on a story; choose it with --model UD-Q4_K_XL")
224        return "IQ3_S", notes
225    for m in ("IQ3_XXS", "Q2_0"):
226        if not streams(m, ram_gb):
227            return m, []
228    return "Q2_0", [f"{ram_gb:.0f} GB of memory: no pack fits whole, so the engine streams the experts from the SSD "
229                    f"(automatic; measured on a 32 GB M4: Q2_0 {STREAM_MEASURED['Q2_0']}, IQ3_XXS "
230                    f"{STREAM_MEASURED['IQ3_XXS']}; smaller Macs are untested). Recommended: Q2_0, without the MTP "
231                    "draft layer (slower when streaming)"]
232
233
234def model_note(model: str, ram_gb: float) -> list[str]:
235    """What a chosen pack risks on this Mac (said, never refused)."""
236    notes = []
237    if streams(model, ram_gb):
238        notes.append(f"{model} needs ~{model_need_gb(model):.0f} GB of the {gpu_budget_gb(ram_gb):.0f} GB Metal keeps "
239                     "resident on this Mac: its experts stream from the SSD (automatic)"
240                     + (f"; measured on a 32 GB M4: {STREAM_MEASURED[model]}" if model in STREAM_MEASURED else
241                        "; not measured streaming"))
242    if MAC_MODELS[model].get("missing"):
243        notes.append(f"{model} does not run on this Metal engine yet ({MAC_MODELS[model]['missing']} are missing): the "
244                     "engine will stop when it loads; kept as you chose (for testing a newer engine)")
245    elif not MAC_MODELS[model]["tested"]:
246        notes.append(f"{model} has not been measured on a Mac yet")
247    return notes
248
249
250def recommend_context(ram_gb: float) -> int:
251    return 32768 if ram_gb < 96 else 65536
252
253
254def stream_mtp(stream: bool, ram_gb: float) -> bool:
255    """Whether the config carries the MTP draft layer: always when the model is resident; when it streams, only on a
256    Mac with STREAM_MTP_FROM_GB or more (a 32 GB M4 is faster without it)."""
257    return (not stream) or ram_gb >= STREAM_MTP_FROM_GB
258
259
260def engine_args(pack: Path, shards: list, rt: Path, ctx: int, stream: bool = False, ram_gb: float = 0.0,
261                profile: Path | str = "data/expert-profile.bin", model: str = "") -> list[str]:
262    """The Metal defaults: --spec 2 with the MTP draft layer (measured best on the M5 Max, docs/MAC.md) and the Q8_0
263    hyper-connection read (the engine's default on Metal; STRATA_HC_Q8=0 in the config's env gives the exact BF16
264    read).  Streaming from the SSD: one token per step, no draft layer (measured faster on the 32 GB M4); a streaming
265    Mac with STREAM_MTP_FROM_GB or more keeps the draft layer and uses --spec STREAM_SPEC."""
266    mtp = stream_mtp(stream, ram_gb) and not MAC_MODELS.get(model, {}).get("no_mtp")       # a feed model whose entry says "drafter: none" has no draft layer
267    args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(shards[1] if len(shards) > 1 else shards[0])]       # one file: its own PLE table
268    if shards[0].name.endswith("-metal.gguf"):         # the repacked file: it is its own dense GGUF
269        args += ["--native-dense-gguf", str(shards[0])]
270    args += [
271            "--expert-profile", str(profile), "--expert-cache", "64",
272            "--prefill", "auto", *spec_args(model, stream, mtp)]
273    args += ["--suffix-draft", "0"] if stream else []
274    args += ["--mtp", str(rt)] if mtp else []
275    return args + ["--max-context", str(ctx),
276                   "--mmap-experts"]   # what the Metal engine does anyway (the GGUF mapped in place); the server says so