okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
27.1 KiB556 linesraw
1"""Main / Helper / Off for every graphics card: ONE place for the app, `strata launch`, setup and the server.
2
3A card has one of three roles:
4* Main   - the card that runs the LAST stage of the layer split: the output head, the draft layer and the check of its guesses. Exactly one.
5* Helper - holds a share of the model, so more of it fits on graphics cards instead of being read from the drive.
6* Off    - Strata does not touch it.
7
8The engine takes the cards in stage order (`"gpu": [helper, ..., main]` with `"gpu_order": "as_given"`), so the Main card is the LAST one. This
9module turns roles into that list (and back), recommends roles, and words the few warnings a person could not work out alone.
10The app has the same rules in apps/host/src/lib/gpu-roles.ts; both run tests/data/gpu_roles_vectors.json.
11
12Pure functions, no I/O.
13"""
14
15from __future__ import annotations
16
17from typing import Any, Callable
18
19from strata_control import gpu_fit
20
21ROLES = ("main", "helper", "off")
22OFF_AT_OR_BELOW_GB = 8.0          # owner rule: a card with 8 GB or less starts Off (it is not a helper unless the person turns it on)
23SAME_SPEED = 1.05                 # serve/server.py ordered_gpus: cards within 5% of each other are the same card
24MEMORY_GUARD_SPEED = 0.5          # a card with more memory takes Main from a faster one only when it is at least half as fast (#1576)
25
26CPU_ONLY_LINE = "Performance is degraded on CPU only."
27NO_CARD_LINE = "This engine needs a graphics card to start. Turn one on."
28
29
30def _idx(c: dict) -> int:
31    return int(c.get("index", 0))
32
33
34def _mem(c: dict) -> float:
35    return float(c.get("vram_gb") or 0)
36
37
38def _speed(c: dict) -> float:
39    v = c.get("speed")
40    return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0 else 0.0
41
42
43def rnd_(x: float) -> int:
44    return round(x)
45
46
47def _shares(c: dict) -> bool:
48    return gpu_fit._shares_memory(c)
49
50
51def _can_run(c: dict) -> bool:
52    return c.get("usable") is not False
53
54
55def short_name(c: dict) -> str:
56    n = str(c.get("name") or f"GPU {_idx(c) + 1}")
57    for junk in ("NVIDIA GeForce ", "NVIDIA ", "GeForce ", "AMD Radeon ", "AMD ", "Intel(R) ", "Intel "):
58        if n.startswith(junk):
59            n = n[len(junk):]
60            break
61    return n.strip()
62
63
64def gpu_label(c: dict) -> str:
65    """The number the screens show: GPU 1 is card 0 (Monitor, the model picker, the loaded list)."""
66    return f"GPU {_idx(c) + 1}"
67
68
69def rows(cards: list[dict], vendor: str | None = None) -> list[dict]:
70    """The cards shown as rows: every card the engine's make can name, in card order. The other make is `gpu_fit.for_vendor(...)[1]` (a muted line)."""
71    vendor = vendor or gpu_fit.pick_vendor(cards)
72    mine = gpu_fit.for_vendor(cards, vendor)[0]
73    return sorted(mine, key=_idx)
74
75
76def _eligible(cs: list[dict]) -> list[dict]:
77    """The cards that can be Main: run Strata, have memory of their own and at least MIN_CARD_GB of it; an integrated chip only when it is the
78    only device (a Strix Halo PC, a mini PC)."""
79    real = [c for c in cs if _can_run(c) and not _shares(c) and _mem(c) >= gpu_fit.MIN_CARD_GB]
80    if real:
81        return real
82    return [c for c in cs if _can_run(c)]
83
84
85def pick_main(cs: list[dict]) -> tuple[dict | None, str]:
86    """(the Main card, why) why: only | faster | same | memory. The faster card, cards within 5% being the same card (the one with more memory,
87    then, for identical cards, the HIGHEST number - so the engine order stays [0, 1] - else the lower number); a card with clearly more memory wins when it is at least half as fast (#1576)."""
88    pool = _eligible(cs)
89    if not pool:
90        return None, "none"
91    if len(pool) == 1:
92        return pool[0], "only"
93    top = max(_speed(c) for c in pool)
94    group = [c for c in pool if _speed(c) * SAME_SPEED >= top] if top > 0 else list(pool)
95    main = sorted(group, key=lambda c: (-round(_mem(c)), _idx(c)))[0]
96    why = "faster" if len(group) == 1 else "same"
97    if len(group) > 1 and len({(str(c.get("name")), rnd_(_mem(c))) for c in group}) == 1:
98        main = max(group, key=_idx)       # identical cards: the HIGHEST number is Main, so the engine order stays [0, 1] as it always was
99    if top <= 0 and len({round(_mem(c)) for c in pool}) > 1:
100        why = "memory"              # speeds unknown: the card with the most memory
101    bigger = [c for c in pool if round(_mem(c)) > round(_mem(main)) and (top <= 0 or _speed(c) >= MEMORY_GUARD_SPEED * top)]
102    if bigger:
103        main = sorted(bigger, key=lambda c: (-round(_mem(c)), _idx(c)))[0]
104        why = "memory"
105    return main, why
106
107
108def recommend(cards: list[dict], vendor: str | None = None) -> dict[str, Any]:
109    """The recommended roles: {"roles": {index: role}, "main": index|None, "why": code, "reasons": {index: code}}.
110    The best card is Main, every other card starts as Helper, EXCEPT a card with 8 GB or less when a bigger card is there (or it has under 4 GB), an integrated chip beside a card with memory of
111    its own, and a card the engine cannot run: those start Off."""
112    cs = rows(cards, vendor)
113    main, why = pick_main(cs)
114    roles: dict[int, str] = {}
115    reasons: dict[int, str] = {}
116    # An 8 GB card is a poor Helper beside a bigger card, but a perfectly good one when 8 GB is all there is: two GTX 1080s are a working
117    # 16 GB pool (#3655). A card with 8 GB or less starts Off only when a bigger usable card is there, or when it is too small to help.
118    has_bigger = any(_can_run(c) and not _shares(c) and round(_mem(c)) > OFF_AT_OR_BELOW_GB for c in cs)
119    for c in cs:
120        i = _idx(c)
121        if main is not None and c is main:
122            roles[i], reasons[i] = "main", why
123        elif not _can_run(c):
124            roles[i], reasons[i] = "off", "cannot_run"
125        elif _shares(c) and main is not None:
126            roles[i], reasons[i] = "off", "igpu"
127        elif round(_mem(c)) <= OFF_AT_OR_BELOW_GB and (has_bigger or _mem(c) < gpu_fit.MIN_CARD_GB):
128            roles[i], reasons[i] = "off", "small"
129        else:
130            roles[i], reasons[i] = "helper", "helper"
131    return {"roles": roles, "main": _idx(main) if main is not None else None, "why": why, "reasons": reasons}
132
133
134def _on(roles: dict[int, str]) -> list[int]:
135    return [i for i, r in roles.items() if r != "off"]
136
137
138def normalize(roles: dict[int, str], cards: list[dict]) -> dict[int, str]:
139    """Exactly one Main among the cards that are on: none -> the fastest card that is on; more than one -> the first keeps it. A lone card that
140    is on is Main."""
141    cs = {_idx(c): c for c in cards}
142    out = {i: (r if r in ROLES else "off") for i, r in roles.items() if i in cs}
143    on = _on(out)
144    mains = [i for i in on if out[i] == "main"]
145    if on and not mains:
146        best = sorted(on, key=lambda i: (-_speed(cs[i]), -round(_mem(cs[i])), i))[0]
147        out[best] = "main"
148    for extra in mains[1:]:
149        out[extra] = "helper"
150    if len(on) == 1:
151        out[on[0]] = "main"
152    return out
153
154
155def set_role(roles: dict[int, str], cards: list[dict], idx: int, role: str) -> tuple[dict[int, str], str | None]:
156    """One click: the new roles and a code for the quiet line the app/Terminal may show (None: nothing to say).
157    Codes: old_main_helper:<i> (the old Main became a Helper), promoted:<i> (this card became Main because the Main left), only_main (refused)."""
158    cs = {_idx(c): c for c in cards}
159    out = dict(roles)
160    note: str | None = None
161    if idx not in cs or role not in ROLES:
162        return out, None
163    if role == "main":
164        old = next((i for i in out if i != idx and out[i] == "main"), None)
165        out[idx] = "main"
166        if old is not None:
167            out[old] = "helper"
168            note = f"old_main_helper:{old}"
169    elif role == "helper":
170        if out.get(idx) == "main":
171            others = sorted([i for i in out if i != idx and out[i] == "helper"], key=lambda i: (-_speed(cs[i]), i))
172            if not others:
173                return out, "only_main"
174            out[idx] = "helper"
175            out[others[0]] = "main"
176            note = f"promoted:{others[0]}"
177        else:
178            out[idx] = "helper"
179    else:
180        was_main = out.get(idx) == "main"
181        out[idx] = "off"
182        if was_main:
183            nxt = sorted([i for i in out if out[i] == "helper"], key=lambda i: (-_speed(cs[i]), i))
184            if nxt:
185                out[nxt[0]] = "main"
186                note = f"promoted:{nxt[0]}"
187    on = _on(out)
188    if len(on) == 1:
189        out[on[0]] = "main"
190    elif on and not any(out[i] == "main" for i in on):
191        out[on[0]] = "main"
192    return out, note
193
194
195def order(roles: dict[int, str], cards: list[dict]) -> list[int]:
196    """The engine's card list: Helpers (slowest first, ties by number), then the Main card LAST; Off cards left out."""
197    cs = {_idx(c): c for c in cards}
198    roles = normalize(roles, cards)
199    helpers = sorted([i for i, r in roles.items() if r == "helper"], key=lambda i: (_speed(cs[i]), i))
200    return helpers + [i for i, r in roles.items() if r == "main"]
201
202
203def mirror(roles: dict[int, str], cards: list[dict]) -> dict[str, Any]:
204    """What a writer stores: "gpu_roles" plus the legacy mirror older engines and the Monitor read. Nothing on: "gpu": [] and "gpu_none": true."""
205    roles = normalize(roles, cards)
206    lst = order(roles, cards)
207    out: dict[str, Any] = {"gpu_roles": {str(i): roles[i] for i in sorted(roles)}}
208    if lst:
209        out["gpu"] = lst[0] if len(lst) == 1 else lst
210        out["gpu_order"] = "as_given"
211    else:
212        out["gpu"] = []
213        out["gpu_none"] = True
214    out["gpu_cards"] = {str(_idx(c)): "|".join(x for x in (short_name(c), str(c.get("bus") or "")) if x) for c in cards if _idx(c) in roles}
215    return out
216
217
218def parse_roles(text: str, cards: list[dict] | None = None) -> dict[int, str]:
219    """`1=main,0=helper,2=off` (also `1:main`) -> {1: "main", 0: "helper", 2: "off"}. ValueError with a plain message otherwise."""
220    out: dict[int, str] = {}
221    for part in str(text or "").replace(";", ",").split(","):
222        part = part.strip()
223        if not part:
224            continue
225        sep = "=" if "=" in part else ":" if ":" in part else None
226        if sep is None:
227            raise ValueError(f"{part!r}: write each card as number=role, e.g. 1=main,0=helper,2=off")
228        k, v = (x.strip().lower() for x in part.split(sep, 1))
229        if not k.isdigit() or v not in ROLES:
230            raise ValueError(f"{part!r}: a card number and one of main, helper, off, e.g. 1=main")
231        if int(k) in out:
232            raise ValueError(f"card {k} is named twice")
233        out[int(k)] = v
234    if not out:
235        raise ValueError("no cards named; write e.g. 1=main,0=helper")
236    mains = [i for i, r in out.items() if r == "main"]
237    if len(mains) > 1:
238        raise ValueError("only one card can be Main")
239    if cards is not None:
240        known = {_idx(c) for c in cards}
241        missing = [i for i in out if i not in known]
242        if missing:
243            raise ValueError("no card " + ", ".join(str(i) for i in missing) + " on this computer (cards: " + ", ".join(str(i) for i in sorted(known)) + ")")
244    return out
245
246
247def roles_from_text(text: str, cards: list[dict]) -> dict[int, str]:
248    """A command line's roles: the cards named get their role; every card NOT named is Off (an explicit command means only what was named);
249    no Main named -> the fastest named card that is on becomes Main."""
250    named = parse_roles(text, cards)
251    full = {_idx(c): named.get(_idx(c), "off") for c in cards}
252    return normalize(full, cards)
253
254
255def speed_stage_order(order: list[int], speeds: dict[int, float], vram_mib: "dict[int, int] | Callable[[], dict[int, int] | None] | None" = None) -> tuple[list[int], str, tuple[int, int] | None]:
256    """THE decision of the card order of an automatic layer split (#1352, #1576, #1760), shared by the start (serve/server.py ordered_gpus) and the plan
257    (`from_legacy`, strata launch --plan): the same function, so the plan can never name a different Main card than the run.
258    `order`: the cards as the config lists them.  `speeds`: {index: multiprocessors x max clock}, every card of `order`.  `vram_mib`: {index: MiB}, or a function
259    that returns it (asked only when a reorder is on the table; None / missing cards: no VRAM check).
260    Returns (order, why, vram) with why:
261      "same"       the speeds are within 5% of each other (#1760): the config's order is kept;
262      "kept"       the order is already speed order: nothing to change;
263      "kept-vram"  the faster card has less total VRAM than the card the config ends on (#1576): the config's order is kept; vram = (that card's MiB, the config's last card's MiB);
264      "faster-last" the cards are put in speed order, the faster card LAST (it runs the head, the draft layer and the verify; a prompt chunk waits on it)."""
265    gl = list(order)
266    if len(gl) < 2:
267        return gl, "same", None
268    if max(speeds[i] for i in gl) < SAME_SPEED * min(speeds[i] for i in gl):
269        return gl, "same", None     # #1760: cards within 5% of each other are the same card (two 5070 Ti read 1.2% apart on the clock): keep the order
270    out = sorted(gl, key=lambda i: speeds[i])
271    if out == gl:
272        return gl, "kept", None
273    vram = vram_mib() if callable(vram_mib) else vram_mib
274    if vram is not None and all(i in vram for i in gl) and vram[out[-1]] < vram[gl[-1]]:
275        return gl, "kept-vram", (vram[out[-1]], vram[gl[-1]])
276    return out, "faster-last", None
277
278
279def from_legacy(gpu: Any, cards: list[dict], gpu_order: str | None = None, speed_order: bool = True) -> dict[int, str]:
280    """Roles of an old "gpu" setting, for display: the LAST card of the engine's order is Main, earlier ones are Helpers, unlisted cards are Off.
281    `gpu` None / "" / []: the recommendation (nothing was chosen)."""
282    items: list[int] = []
283    if isinstance(gpu, (list, tuple)):
284        items = [int(x) for x in gpu]
285    elif gpu is not None and str(gpu).strip() != "":
286        items = [int(x) for x in str(gpu).split(",") if x.strip() != ""]
287    cs = {_idx(c): c for c in cards}
288    items = [i for i in items if i in cs]
289    if not items:
290        return dict(recommend(cards)["roles"])
291    if len(items) > 1 and gpu_order != "as_given" and speed_order and all(_speed(cs[i]) for i in items):
292        # the engine's own decision (serve/server.py ordered_gpus calls the same function): the faster card last (#1352), unless the speeds are within 5% (#1760)
293        # or the faster card has less VRAM than the one the list ends on (#1576)
294        vram = {i: int(_mem(cs[i]) * 1024) for i in items} if all(_mem(cs[i]) for i in items) else None
295        items = speed_stage_order(items, {i: _speed(cs[i]) for i in items}, vram)[0]
296    roles = {i: "off" for i in cs}
297    for i in items[:-1]:
298        roles[i] = "helper"
299    roles[items[-1]] = "main"
300    return roles
301
302
303def is_recommended(roles: dict[int, str], cards: list[dict], vendor: str | None = None) -> bool:
304    rec = recommend(cards, vendor)["roles"]
305    return {i: r for i, r in roles.items() if i in rec} == rec
306
307
308# ---- warnings: only what a person could not know -------------------------------------------------------------------------------------------
309
310def warnings(roles: dict[int, str], cards: list[dict], *, spill_gb: float = 0.0, engine_runs_cpu_only: bool = False) -> list[dict]:
311    """[{"code", "card"|None, "text", "fix": {"card": i, "role": r}|None}] - one short line each, never blocking.
312    * igpu_main      built-in graphics as Main (fix: the real card becomes Main)
313    * cannot_run     a card the engine cannot run is on (fix: turn it off)
314    * low_memory     too little memory for the chosen setup (part of the model would be read from the drive)
315    * cpu_only       every card is Off"""
316    cs = {_idx(c): c for c in cards}
317    out: list[dict] = []
318    for i in sorted(roles):
319        c, role = cs.get(i), roles[i]
320        if c is None or role == "off":
321            continue
322        if not _can_run(c):
323            out.append({"code": "cannot_run", "card": i, "text": f"{short_name(c)} cannot run Strata.", "fix": {"card": i, "role": "off"}})
324        elif role == "main" and _shares(c) and any(not _shares(x) and _can_run(x) for x in cs.values()):
325            real = sorted([x for x in cs.values() if not _shares(x) and _can_run(x)], key=lambda x: (-_speed(x), -_mem(x), _idx(x)))[0]
326            out.append({"code": "igpu_main", "card": i, "text": f"{short_name(c)} is built-in graphics; it is slow as Main.",
327                        "fix": {"card": _idx(real), "role": "main"}})
328    if not _on(roles):
329        out.append({"code": "cpu_only", "card": None, "text": CPU_ONLY_LINE if engine_runs_cpu_only else NO_CARD_LINE, "fix": None})
330    elif spill_gb >= 1.0:
331        out.append({"code": "low_memory", "card": None, "text": f"Not enough memory for this setup: about {spill_gb:.0f} GB is read from the drive.", "fix": None})
332    return out
333
334
335def spill_for(roles: dict[int, str], cards: list[dict], memory_gb: float | None, ram_gb: float | None) -> float:
336    """About how many GB of the model would be read from the drive with the cards that are on (0 when unknown): gpu_fit's arithmetic, every
337    extra card costing its own dense layers."""
338    if not memory_gb or not ram_gb:
339        return 0.0
340    cs = {_idx(c): c for c in cards}
341    on = [cs[i] for i in _on(roles) if i in cs and not _shares(cs[i])]
342    vram = sum(_mem(c) for c in on) - gpu_fit.SPLIT_CARD_OVERHEAD_GB * max(0, len(on) - 1)
343    return float(gpu_fit.fit(float(memory_gb), float(ram_gb), max(0.0, vram))["spill_gb"])
344
345
346def note_text(code: str | None, cards: list[dict]) -> str:
347    """The quiet line for a `set_role` code."""
348    if not code:
349        return ""
350    cs = {_idx(c): c for c in cards}
351    kind, _, arg = code.partition(":")
352    c = cs.get(int(arg)) if arg.isdigit() else None
353    name = short_name(c) if c else "That card"
354    if kind == "old_main_helper":
355        return f"{name} is now a Helper."
356    if kind == "promoted":
357        return f"{name} is now Main."
358    if kind == "only_main":
359        return "The only card that is on has to be Main."
360    return ""
361
362
363# ---- the sentence above the cards ----------------------------------------------------------------------------------------------------------
364
365def sentence(cards: list[dict], vendor: str | None = None) -> str:
366    """One plain line for the recommendation: who is Main and why, who helps, who starts Off."""
367    cs = rows(cards, vendor)
368    rec = recommend(cards, vendor)
369    byi = {_idx(c): c for c in cs}
370    if rec["main"] is None:
371        return "No graphics card that Strata can use was found."
372    m = byi[rec["main"]]
373    if len(cs) == 1:
374        return f"Strata will use your {short_name(m)}."
375    helpers = [byi[i] for i, r in rec["roles"].items() if r == "helper"]
376    why = {"same": "the cards are alike", "memory": "it has more memory", "faster": "it is faster", "only": "it is the only card"}[rec["why"]]
377    s = f"{short_name(m)} is Main: {why}."
378    if helpers:
379        s += " " + " and ".join(short_name(h) for h in helpers) + (" help." if len(helpers) > 1 else " helps.")
380    for i, r in rec["roles"].items():
381        if r == "off":
382            code = rec["reasons"][i]
383            c = byi[i]
384            s += f" {short_name(c)} starts Off: " + ("Strata cannot run it." if code == "cannot_run" else "built-in graphics." if code == "igpu" else f"{OFF_AT_OR_BELOW_GB:.0f} GB or less.")
385    return s
386
387
388# ---- reading saved settings (server, launch, app) ---------------------------------------------------------------------------------------
389
390def _int_list(g: Any) -> list[int]:
391    if g is None or g == "":
392        return []
393    items = g if isinstance(g, (list, tuple)) else str(g).split(",")
394    return [int(str(x).strip()) for x in items if str(x).strip() != ""]
395
396
397def parse_saved(value: Any) -> dict[int, str] | None:
398    """A saved "gpu_roles" object -> {index: role}; None when it is not one (the setting is then ignored)."""
399    if not isinstance(value, dict) or not value:
400        return None
401    out: dict[int, str] = {}
402    for k, v in value.items():
403        try:
404            i = int(str(k).strip())
405        except ValueError:
406            return None
407        if str(v).lower() not in ROLES:
408            return None
409        out[i] = str(v).lower()
410    if sum(1 for r in out.values() if r == "main") > 1:
411        return None
412    return out
413
414
415def saved_roles(cfg: dict) -> tuple[dict[int, str] | None, str | None]:
416    """(the roles a run settings dict carries, a problem line or None). Roles win when the legacy "gpu" is the mirror of them, or when "gpu" is
417    missing; a "gpu" that was edited by hand (it names other cards, or another Main) wins and the roles are ignored (#3256: a file that names
418    its GPUs keeps them)."""
419    roles = parse_saved(cfg.get("gpu_roles"))
420    if roles is None:
421        return None, ("run settings: gpu_roles is not {card: main|helper|off} with one main; ignored" if cfg.get("gpu_roles") is not None else None)
422    try:
423        gl = _int_list(cfg.get("gpu"))
424    except ValueError:
425        return None, "run settings: gpu is not a card number or a list; gpu_roles ignored"
426    on = [i for i, r in roles.items() if r != "off"]
427    main = next((i for i, r in roles.items() if r == "main"), None)
428    if cfg.get("gpu_none") and not on:
429        return roles, None
430    if not gl:
431        return (roles, None) if on else (None, None)
432    if sorted(gl) != sorted(on) or (main is not None and gl[-1] != main):
433        return None, "run settings: gpu was edited by hand, gpu_roles ignored"
434    return roles, None
435
436
437def engine_order(roles: dict[int, str], speeds: dict[int, float] | None = None) -> list[int]:
438    """The card list of saved roles for the server: Helpers slowest first (ties by number), then Main. Used where only numbers and
439    (maybe) measured speeds are known."""
440    sp = speeds or {}
441    helpers = sorted([i for i, r in roles.items() if r == "helper"], key=lambda i: (sp.get(i, 0.0), i))
442    return helpers + sorted(i for i, r in roles.items() if r == "main")
443
444
445def describe(roles: dict[int, str], cards: list[dict], *, card_numbers: bool = False) -> str:
446    """`Main: GPU 2 RTX 4070 Ti. Helper: GPU 1 RTX 3060.` (the line setup prints; the screens count from 1: GPU 1 is card 0).
447    `card_numbers`: each card also names the number `--gpu` takes, as `strata launch --plan` prints them: `GPU 2 (--gpu 1) RTX 4070 Ti`."""
448    cs = {_idx(c): c for c in cards}
449    parts = []
450    for role, word in (("main", "Main"), ("helper", "Helper"), ("off", "Off")):
451        label = (lambda i: f"GPU {i + 1} (--gpu {i})") if card_numbers else (lambda i: f"GPU {i + 1}")
452        names = [f"{label(i)} {short_name(cs[i])}" if i in cs else label(i) for i in sorted(roles) if roles[i] == role]
453        if names:
454            parts.append(f"{word}: {', '.join(names)}.")
455    return " ".join(parts)
456
457
458# ---- the cards the environment leaves visible ------------------------------------------------------------------------------------------------
459
460def _ordinals(value: str | None, indexes: list[int]) -> list[int] | None:
461    """The card numbers a visibility list (``1,0``) names, in its order, over `indexes` (the cards in ordinal order). An entry that is not a card ends the list, as
462    the CUDA and HIP runtimes read it. None: not set, or it names cards by something other than a number (a UUID), which this cannot map."""
463    if value is None:
464        return None
465    if not value.strip():
466        return []
467    out: list[int] = []
468    for tok in value.split(","):
469        tok = tok.strip()
470        if not tok.lstrip("-").isdigit():
471            return None
472        n = int(tok)
473        if n < 0 or n >= len(indexes):
474            break
475        out.append(indexes[n])
476    return out
477
478
479def env_visible(indexes: list[int], vendor: str | None, environ: dict | None = None, *, alike: bool = False) -> list[int] | None:
480    """The card numbers (the numbers `--gpu` takes) that CUDA_VISIBLE_DEVICES leaves visible (NVIDIA), or ROCR_VISIBLE_DEVICES and then HIP_VISIBLE_DEVICES (AMD); None when
481    nothing restricts them or the list cannot be read (a UUID, or CUDA's own card order when the cards differ and CUDA_DEVICE_ORDER is not PCI_BUS_ID).
482    `alike`: the cards are all one model, so their order does not matter."""
483    import os
484    env = os.environ if environ is None else environ
485    cards = sorted(indexes)
486    if vendor == "amd":
487        seen: list[int] | None = None
488        for name in ("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"):
489            raw = env.get(name)
490            if raw is None:
491                continue
492            got = _ordinals(raw, seen if seen is not None else cards)
493            if got is None:
494                return None
495            seen = got
496        return seen
497    if vendor != "nvidia":
498        return None
499    raw = env.get("CUDA_VISIBLE_DEVICES")
500    if raw is not None and raw.strip() and len(cards) > 1 and not alike and str(env.get("CUDA_DEVICE_ORDER") or "").strip().upper() != "PCI_BUS_ID":
501        return None                                          # numbers in CUDA's own card order (fastest first) cannot be told from nvidia-smi's here
502    return _ordinals(raw, cards)
503
504
505def visible_cards(cards: list[dict], vendor: str | None, environ: dict | None = None, keep: set[int] | frozenset[int] = frozenset()) -> list[dict]:
506    """`cards` without the ones the environment hides (env_visible); a card in `keep` (named with --gpu, which the server sets the visibility from) stays."""
507    vis = env_visible([_idx(c) for c in cards], vendor, environ, alike=len({(str(c.get("name")), rnd_(_mem(c))) for c in cards}) <= 1)
508    if vis is None:
509        return list(cards)
510    return [c for c in cards if _idx(c) in vis or _idx(c) in keep]
511
512
513# ---- speed of each card (the same measure the engine orders a split by: multiprocessors x max clock) ------------------------------------
514
515def nvidia_speeds(timeout: float = 20.0) -> dict[int, float]:
516    """{nvidia-smi number: SMs x max clock} from the CUDA driver API in a child process (no toolkit needed); {} when it cannot say."""
517    import os
518    import subprocess
519    import sys
520    code = ("import ctypes,sys,os\n"
521            "os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'\n"
522            "lib=ctypes.CDLL('nvcuda.dll' if os.name=='nt' else 'libcuda.so.1')\n"
523            "assert lib.cuInit(0)==0\n"
524            "n=ctypes.c_int()\n"
525            "assert lib.cuDeviceGetCount(ctypes.byref(n))==0\n"
526            "for i in range(n.value):\n"
527            "    d=ctypes.c_int()\n"
528            "    assert lib.cuDeviceGet(ctypes.byref(d),i)==0\n"
529            "    sm=ctypes.c_int(); mhz=ctypes.c_int()\n"
530            "    lib.cuDeviceGetAttribute(ctypes.byref(sm),16,d)\n"
531            "    lib.cuDeviceGetAttribute(ctypes.byref(mhz),13,d)\n"
532            "    print(i,sm.value,mhz.value)\n")
533    try:
534        env = dict(os.environ)
535        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
536        env.pop("CUDA_VISIBLE_DEVICES", None)
537        r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, errors="replace", timeout=timeout, env=env)
538        out = {}
539        for line in r.stdout.splitlines():
540            i, sm, khz = (int(x) for x in line.split())
541            if sm > 0 and khz > 0:
542                out[i] = float(sm) * float(khz)
543        return out
544    except (OSError, ValueError, subprocess.SubprocessError):
545        return {}
546
547
548def add_speeds(gpus: list[dict]) -> None:
549    """Puts "speed" on the NVIDIA cards of a hardware report (in place); a card it cannot measure keeps none."""
550    nv = [g for g in gpus if str(g.get("vendor")) == "nvidia"]
551    if not nv:
552        return
553    sp = nvidia_speeds()
554    for g in nv:
555        if g.get("index") in sp:
556            g["speed"] = sp[g["index"]]