okami.mom/strata

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

Niko1221Version 0.2.10 / engine 0.1.56 follow-through: test_tui2_023_versions and AGENTS.md follow the bump; the '0.2.9.1' tags that meant this release now read 0.2.10; the test comment names 0.2.9.1 as the unpublished DeepSeek hotfix labelf31abf7bd

main
16.6 KiB294 linesraw
1"""Which graphics cards a model should use: ONE place for the app, `strata launch` and setup.
2
3The rule (owner decision):
41. First try the model on ONE card (the largest) plus system RAM, the normal hybrid mode.
52. Only when that does not fit, or would be too tight, offer to add the second card as a layer split.
63. Let the person choose: every option comes with plain numbers and a recommended one is pre-selected (recommend, never force).
7
8The memory arithmetic is native-fit.ts `fitOn` (apps/host/src/lib/native-fit.ts) with the same constants (a test keeps them equal):
9the experts are held first in the graphics memory beyond about DENSE_GB (the dense weights, buffers and a 32K cache), then in RAM beyond
10about SYSTEM_ROOM_GB left for the system; whatever is left would be read from the SSD (`spill_gb`). A split adds the memory of the extra
11cards but every extra card holds its own dense layers and prompt buffers, so each one costs SPLIT_CARD_OVERHEAD_GB of that (an estimate:
12docs/MULTI_GPU.md says each card "holds the dense weights of its layers and its own prompt buffers").
13
14Cards that count: not integrated (an iGPU shares the system RAM and is ignored), at least MIN_CARD_GB of graphics memory, flagged usable by
15the caller's own driver checks (NVIDIA RTX 20 or newer, a supported AMD card, ...). A card needs SPLIT_MIN_VRAM_GB to share a model.
16Pure functions, no I/O: setup.py, strata_cli/launch and tools/strata_mcp.py import it.
17"""
18
19from __future__ import annotations
20
21from typing import Any
22
23DENSE_GB = 5.0                 # = native-fit.ts DENSE_GB
24SYSTEM_ROOM_GB = 10.0          # = native-fit.ts SYSTEM_ROOM_GB
25DENSE_EXTRA_GB = 1.0           # = native-fit.ts DENSE_EXTRA_GB
26SPLIT_CARD_OVERHEAD_GB = 2.0   # each extra card of a split: its own dense layers and prompt buffers
27SPLIT_MIN_VRAM_GB = 8.0        # setup.py SPLIT_MIN_VRAM_GB: a card sharing a model needs this much
28SPLIT_PROMPT_VRAM_GB = 12.0    # setup.py SPLIT_PROMPT_VRAM_GB (#448): a smaller second card caps the prompt chunk
29MIN_CARD_GB = 4.0              # under this a card cannot hold the dense weights: ignored (an iGPU, a display card)
30FITS_SPARE_RAM_GB = 4.0        # RAM left beyond the experts below which "fits" becomes "tight"
31SPLIT_PROMPT_GAIN = "about 20% faster"   # setup.py's own words for prompts read on two cards (docs/MULTI_GPU.md)
32
33
34def _round1(x: float) -> float:
35    return round(float(x) * 10) / 10
36
37
38# ---- one engine, one vendor -----------------------------------------------------------------------------------------------
39# Every Strata engine package drives the cards of ONE vendor (CUDA: NVIDIA, HIP: AMD, SYCL: Intel, Metal: Apple). A model is never split
40# across vendors, and two models at once, one per vendor, is not supported yet. So the cards offered for running and splitting are the
41# ones the engine can drive; a better card of the other vendor is mentioned in one plain line (recommend, never force).
42BACKEND_VENDOR = {"cuda": "nvidia", "hip": "amd", "sycl": "intel", "metal": "apple"}
43VENDOR_NAME = {"nvidia": "NVIDIA", "amd": "AMD", "intel": "Intel", "apple": "Apple"}
44SECOND_MODEL_SENTENCE = ("Running two models at the same time, one on each make of graphics card, is not supported yet. "
45                         "Strata runs one model at a time on the cards of one make.")
46
47
48def vendor_of_backend(backend: str | None) -> str | None:
49    return BACKEND_VENDOR.get(str(backend or "").lower())
50
51
52def _vendor(card: dict) -> str | None:
53    v = card.get("vendor")
54    return str(v).lower() if v else None
55
56
57def pick_vendor(cards: list[dict], backend: str | None = None) -> str | None:
58    """The make of card the engine drives: the installed (or detected) engine's, else the only make among the cards that count; with more
59    than one make, NVIDIA (the engine setup picks first), else the make of the card with the most memory. None: no card names a make."""
60    named = vendor_of_backend(backend)
61    if named:
62        return named
63    keep, _ = usable_cards(cards)
64    makes = {_vendor(c) for c in keep if _vendor(c)}
65    if len(makes) <= 1:
66        return next(iter(makes), None)
67    if "nvidia" in makes:
68        return "nvidia"
69    return _vendor(keep[0])
70
71
72def for_vendor(cards: list[dict], vendor: str | None) -> tuple[list[dict], list[dict]]:
73    """(the cards the engine of that make can drive, the cards of other makes). A card that names no make goes with the engine's."""
74    if not vendor:
75        return list(cards or []), []
76    mine = [c for c in cards or [] if _vendor(c) in (None, vendor)]
77    return mine, [c for c in cards or [] if _vendor(c) not in (None, vendor)]
78
79
80def _short_name(c: dict, vendor: str) -> str:
81    n = str(c.get("name") or "graphics card")
82    for junk in ("NVIDIA GeForce ", "NVIDIA ", "AMD Radeon ", "AMD ", "Intel "):
83        if n.startswith(junk):
84            n = n[len(junk):]
85            break
86    return f"{VENDOR_NAME.get(vendor, vendor.title())} {n}".strip()
87
88
89# ---- UD-Q4_K_XL on a Strix Halo (0.2.10) ------------------------------------------------------------------------------------------------
90# REMOVE this block, its three callers (setup.py "size:", strata_cli/launch/cmd.py apply_defaults, tests/terminal/test_strix_q4_note.py) when the
91# stall is fixed in the engine (STRIX-2Q). The numbers are the 0.2.9 release notes'.
92STRIX_Q4_MODEL = "UD-Q4_K_XL"
93STRIX_Q4_NOTE = ("UD-Q4_K_XL on a Ryzen AI Max (Strix Halo) can stop on the first request after a start, with no CPU or disk activity: 7 of 30 "
94                 "starts did on the 0.1.55 engine and 2 of 5 on 0.1.54. If it happens, stop the engine and start it again. UD-IQ4_XS ran 99 "
95                 "starts in the same setup without stopping; choose it if you want to be sure. Nothing is refused.")
96
97
98def is_strix_halo_card(card: dict) -> bool:
99    """A Ryzen AI Max (Strix Halo, gfx1151, Radeon 8060S / 8050S / 8040S) from the fields the hardware readers give."""
100    if not isinstance(card, dict):
101        return False
102    text = " ".join(str(card.get(k) or "") for k in ("name", "arch", "gfx")).lower()
103    return "gfx1151" in text or "strix halo" in text or any(x in text for x in ("8060s", "8050s", "8040s"))
104
105
106def strix_q4_stall_note(model, cards) -> str | None:
107    """The plain warning for UD-Q4_K_XL on a Strix Halo, else None. Warn only."""
108    if str(model or "").lower() != STRIX_Q4_MODEL.lower():
109        return None
110    return STRIX_Q4_NOTE if any(is_strix_halo_card(c) for c in cards or []) else None
111
112
113def other_vendor_note(cards: list[dict], vendor: str | None) -> str | None:
114    """One plain line when the other make's best card is bigger than the best card the engine can use, else None:
115    "This computer also has an AMD R9700 (32 GB). The AMD build of Strata can use it - it fits bigger models." """
116    if not vendor:
117        return None
118    mine, others = for_vendor(usable_cards(cards)[0], vendor)
119    others = [c for c in others if _vendor(c) and not _shares_memory(c)]
120    if not others:
121        return None
122    intel = [c for c in others if _vendor(c) == "intel"]
123    if intel:
124        # Intel Arc cards beside another make: always said (the engine for one make runs at a time; the person chooses which), never refused
125        total = sum(float(c.get("vram_gb") or 0) for c in intel)
126        cards = (f"{len(intel)} Intel Arc cards ({total:.0f} GB together)" if len(intel) > 1
127                 else f"an {_short_name(intel[0], 'intel')} ({total:.0f} GB)")
128        return (f"This computer also has {cards}. Strata uses the {VENDOR_NAME.get(vendor, vendor)} card; to use the Intel card"
129                f"{'s' if len(intel) > 1 else ''} instead, add --backend intel (it is remembered; --backend auto goes back).")
130    if vendor == "intel":
131        names = ", ".join(sorted({_short_name(c, _vendor(c)) for c in others}))
132        return (f"This computer also has {names}. Strata uses the Intel cards; --backend auto goes back to the PC's own choice "
133                "(NVIDIA first).")
134    best = max(others, key=lambda c: float(c.get("vram_gb") or 0))
135    mine_best = max((float(c.get("vram_gb") or 0) for c in mine), default=0.0)
136    if float(best.get("vram_gb") or 0) <= mine_best:
137        return None
138    other = _vendor(best)
139    return (f"This computer also has an {_short_name(best, other)} ({float(best.get('vram_gb') or 0):.0f} GB). "
140            f"The {VENDOR_NAME.get(other, other.title())} build of Strata can use it — it fits bigger models.")
141
142
143def memory_needed(variant: dict) -> float:
144    """RAM + VRAM the model asks for (native-fit.ts memoryNeeded)."""
145    if isinstance(variant.get("memory_gb"), (int, float)):
146        return float(variant["memory_gb"])
147    if variant.get("mem_total") and isinstance(variant.get("ram_needed_gb"), (int, float)):
148        return float(variant["ram_needed_gb"])
149    return _round1(float(variant.get("experts_gb") or variant.get("ram_needed_gb") or 0) + DENSE_EXTRA_GB)
150
151
152def fit(memory_gb: float, ram_gb: float | None, vram_gb: float) -> dict[str, Any]:
153    """native-fit.ts `fitOn` for a given memory need: where the weights go. Keys: vram_use_gb, ram_use_gb, spill_gb, spare_ram_gb, known."""
154    vram = float(vram_gb or 0)
155    if not ram_gb or ram_gb <= 0:
156        return {"vram_use_gb": 0.0, "ram_use_gb": 0.0, "spill_gb": 0.0, "spare_ram_gb": 0.0, "known": False}
157    experts = max(0.0, memory_gb - DENSE_EXTRA_GB)
158    on_gpu = max(0.0, min(experts, vram - DENSE_GB))
159    ram_room = max(0.0, float(ram_gb) - SYSTEM_ROOM_GB)
160    spill = max(0.0, experts - on_gpu - ram_room)
161    in_ram = max(0.0, experts - on_gpu - spill)
162    return {"vram_use_gb": _round1(min(vram, DENSE_GB + on_gpu) if vram > 0 else 0.0),
163            "ram_use_gb": _round1(in_ram + (DENSE_EXTRA_GB if vram <= 0 else 0)), "spill_gb": _round1(spill),
164            "spare_ram_gb": _round1(max(0.0, ram_room - in_ram)), "known": True}
165
166
167def verdict(f: dict) -> str:
168    """fits / tight / spills: all in memory with room to spare / all in memory but little RAM left / part of it is read from the SSD."""
169    if not f.get("known"):
170        return "unknown"
171    if f["spill_gb"] >= 1.0:
172        return "spills"
173    return "fits" if f["spare_ram_gb"] >= FITS_SPARE_RAM_GB or f["ram_use_gb"] <= 0 else "tight"
174
175
176def _shares_memory(c: dict) -> bool:
177    """An integrated chip or a unified-memory chip (Apple, Strix Halo): its memory is the system RAM."""
178    return bool(c.get("integrated") or c.get("uma") or c.get("unified_memory") or c.get("unified_gb") or str(c.get("vendor")) == "apple")
179
180
181def usable_cards(cards: list[dict]) -> tuple[list[dict], list[dict]]:
182    """(cards that count, cards ignored with a plain reason in 'why_ignored'). Largest memory first, then the card number.
183
184    A chip that shares the system memory is ignored when the computer has a card with memory of its own (it adds nothing to it); when it is
185    the only device (a Mac, a Strix Halo PC) it is the one that counts. A card under MIN_CARD_GB cannot hold the dense weights."""
186    flagged = [c for c in (cards or []) if c.get("usable") is not False]
187    has_real = any(not _shares_memory(c) and float(c.get("vram_gb") or 0) >= MIN_CARD_GB for c in flagged)
188    keep, ignored = [], []
189    for c in cards or []:
190        vram = float(c.get("vram_gb") or 0)
191        why = None
192        if c.get("usable") is False:
193            why = c.get("problem") or "Strata cannot use this card"
194        elif _shares_memory(c):
195            if has_real:
196                why = "it shares the system memory (an integrated graphics chip), so it adds nothing"
197        elif vram < MIN_CARD_GB:
198            why = f"only {vram:.0f} GB of graphics memory"
199        if why:
200            ignored.append({**c, "why_ignored": why})
201        else:
202            keep.append(c)
203    keep.sort(key=lambda c: (-round(float(c.get("vram_gb") or c.get("unified_gb") or 0)), c.get("index", 0)))
204    return keep, ignored
205
206
207def _name(c: dict) -> str:
208    n = str(c.get("name") or f"card {c.get('index')}")
209    for junk in ("NVIDIA GeForce ", "NVIDIA ", "AMD Radeon ", "AMD "):
210        n = n.replace(junk, "")
211    return n + (f" (card {c.get('index')})" if c.get("_dup") else "")
212
213
214def own_memory_gb(c: dict) -> float:
215    """The graphics memory a card adds BESIDE the RAM.  A discrete card: its VRAM.  A chip that shares the system memory (Strix Halo, an APU): only
216    its BIOS carve-out (`dedicated_gb`; 0 when the report does not give it) - its "shared" pool is the RAM itself, and counting it as VRAM as well as
217    as RAM made a model look like it fit twice (setup.py low_ram_vram does the same)."""
218    if c.get("uma") or c.get("integrated"):
219        return float(c.get("dedicated_gb") or 0)
220    return float(c.get("vram_gb") or 0)
221
222
223def _option(key: str, cards: list[dict], memory_gb: float, ram_gb: float | None) -> dict[str, Any]:
224    n = len(cards)
225    total = sum(own_memory_gb(c) for c in cards)
226    eff = total - SPLIT_CARD_OVERHEAD_GB * (n - 1)
227    f = fit(memory_gb, ram_gb, eff)
228    v = verdict(f)
229    names = " + ".join(_name(c) for c in cards)
230    label = f"{names} + RAM" if n == 1 else f"{names} + RAM (layer split)"
231    have = (eff + max(0.0, float(ram_gb or 0) - SYSTEM_ROOM_GB))
232    if v == "unknown":
233        words = "memory of this computer unknown"
234    elif v == "spills":
235        words = f"does not fit in memory: about {f['spill_gb']:.0f} GB is read from the SSD while answering (slower)"
236    elif v == "tight":
237        words = f"fits, but tight: needs {memory_gb:.0f} GB of the {have:.0f} GB available"
238    else:
239        words = f"fits: needs {memory_gb:.0f} GB of the {have:.0f} GB available"
240    notes = []
241    if n >= 2:
242        notes.append(f"prompts are read {SPLIT_PROMPT_GAIN}; the cards share the layers (docs/MULTI_GPU.md)")
243        small = [c for c in cards[1:] if float(c.get("vram_gb") or 0) < SPLIT_PROMPT_VRAM_GB - 0.5]
244        if small and float(cards[0].get("vram_gb") or 0) >= SPLIT_PROMPT_VRAM_GB - 0.5:
245            notes.append(f"{_name(small[0])} is small: it can make prompts slower than the first card alone")
246    return {"key": key, "cards": [c.get("index") for c in cards], "label": label, "verdict": v, "summary": f"{label}: {words}",
247            "words": words, "vram_gb": _round1(total), "spill_gb": f["spill_gb"], "ram_use_gb": f["ram_use_gb"],
248            "spare_ram_gb": f["spare_ram_gb"], "notes": notes, "recommended": False}
249
250
251_RANK = {"fits": 0, "tight": 1, "unknown": 2, "spills": 3}
252
253
254def options(memory_gb: float, ram_gb: float | None, cards: list[dict], vendor: str | None = None) -> dict[str, Any]:
255    """The choices for this model on this computer: {"options": [...], "recommended": key, "ignored": [...], "cards": n counted}.
256
257    Options (best known first): the largest card alone; with two or more cards that can share a model, the two largest as a layer split
258    (and all of them when there are more than two); then every other card alone. Exactly one option is recommended:
259    the single largest card when the model fits it (with RAM); otherwise the split if it fits better (a smaller verdict or less SSD use);
260    otherwise the single largest card again (nothing better to offer)."""
261    vendor = vendor or pick_vendor(cards)
262    mine, others = for_vendor(cards, vendor)
263    keep, ignored = usable_cards(mine)
264    ignored = ignored + [{**c, "why_ignored": f"it needs the {VENDOR_NAME.get(_vendor(c), _vendor(c))} build of Strata, and this engine drives "
265                                              f"{VENDOR_NAME.get(vendor, vendor)} cards"} for c in others]
266    out: dict[str, Any] = {"options": [], "recommended": None, "ignored": ignored, "cards": len(keep), "vendor": vendor,
267                           "other_vendor_note": other_vendor_note(cards, vendor)}
268    if not keep:
269        return out
270    names = [str(c.get("name")) for c in keep]
271    keep = [{**c, "_dup": names.count(str(c.get("name"))) > 1} for c in keep]       # two cards of one model: told apart by their number
272    opts = [_option("single", [keep[0]], memory_gb, ram_gb)]
273    share = [c for c in keep if float(c.get("vram_gb") or 0) >= SPLIT_MIN_VRAM_GB - 0.5]
274    if len(share) >= 2:
275        opts.append(_option("split", share[:2], memory_gb, ram_gb))
276        if len(share) > 2:
277            opts.append(_option("split-all", share, memory_gb, ram_gb))
278    for c in keep[1:]:
279        opts.append(_option(f"single-{c.get('index')}", [c], memory_gb, ram_gb))
280    single = opts[0]
281    best = single
282    if single["verdict"] != "fits":
283        for o in opts[1:]:
284            if len(o["cards"]) > 1 and (_RANK[o["verdict"]], o["spill_gb"]) < (_RANK[best["verdict"]], best["spill_gb"]):
285                best = o
286    best["recommended"] = True
287    out["options"], out["recommended"] = opts, best["key"]
288    return out
289
290
291def recommended_cards(memory_gb: float, ram_gb: float | None, cards: list[dict], vendor: str | None = None) -> list[int]:
292    """The card numbers of the recommended option (empty: no usable card)."""
293    res = options(memory_gb, ram_gb, cards, vendor)
294    return next((o["cards"] for o in res["options"] if o["recommended"]), [])