okami.mom/strata

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

Niko1221Merge f-028-arcb65-pipe: pipelined B-series (two Battlemage stages) is the default18200cffa

main
6.3 KiB127 linesraw
1"""--spec 2 for a run config on exactly two Intel Arc B-series (Battlemage) cards.
2
3On two B-series cards the SYCL engine runs the verify windows of the two cards overlapped (--pipeline-windows 2, on by
4default there).  Its answers are those of a width-2 draft window whatever --spec says: on 2x Arc Pro B65 the pipelined
5answers equal a serial --spec 2 in 100 of 100 agent requests, while a serial --spec 4 differs from them in 3 of 100 (an end
6token against a digit at a near-tie; a serial --spec 3 differs from --spec 4 in the same way).  So setup and the launcher
7write `--spec 2` for such a config: the same answers as the engine gives anyway, about 20% faster than the old
8`--spec 4` serial default (chat 73.9 against 60.7 tok/s), and no surprise between a serial and a pipelined start.
9
10Only the generated default changes.  Single cards, Arc A-series (Alchemist) cards, three or more cards, a config with no
11draft layer, and any config where the person set --spec (in "user_args", or a value other than setup's own 4 in "args") keep
12what they have.  The card generation is the PCI device id from sysfs, the same id the engine's architecture enum comes from
13(strata::intel_gpu_gen in sycl/include/strata/sycl_queue.hpp), never the marketing name.
14"""
15
16from __future__ import annotations
17
18import os
19from pathlib import Path
20from typing import Any
21
22from . import user_args
23
24SETUP_DEFAULT_SPEC = "4"      # what setup.py and the launcher write for every model
25TWO_CARD_SPEC = "2"
26# Battlemage: BMG-G21 (0xE20x: B580, B570, Pro B50) and BMG-G31 (0xE22x: Pro B70, B65, B60), driven by xe.  Alchemist (0x56A0..)
27# and anything else (an integrated GPU, i915) is not.  Same range as sycl_queue.hpp's name-less fallback.
28BATTLEMAGE_ID_RANGE = (0xE200, 0xE2FF)
29
30
31def is_battlemage(driver: str, devid: str) -> bool:
32    """True for an Arc B-series card: the xe driver and a PCI device id in the Battlemage range."""
33    if driver != "xe":
34        return False
35    try:
36        n = int(str(devid).lower().replace("0x", ""), 16)
37    except ValueError:
38        return False
39    return BATTLEMAGE_ID_RANGE[0] <= n <= BATTLEMAGE_ID_RANGE[1]
40
41
42def sysfs_cards(drm: str | os.PathLike = "/sys/class/drm") -> list[dict]:
43    """The Intel discrete cards in sysfs card order (the order setup's `--gpus` indexes and Level Zero follows on the tested
44    machines): [{"driver": "xe", "devid": "e222"}, ...].  Vendor 0x8086 under xe or i915; an i915 card with an id that is not an
45    Alchemist one is an integrated GPU and is left out, as in sycl/setup_intel.py."""
46    out = []
47    for card in sorted(Path(drm).glob("card[0-9]*")):
48        if "-" in card.name:
49            continue
50        dev = card / "device"
51        try:
52            vendor = (dev / "vendor").read_text().strip().lower()
53            devid = (dev / "device").read_text().strip().lower().replace("0x", "")
54            driver = os.path.basename(os.path.realpath(dev / "driver")) if (dev / "driver").exists() else ""
55        except OSError:
56            continue
57        if vendor != "0x8086" or driver not in ("xe", "i915"):
58            continue
59        if driver == "i915" and not devid.startswith("56"):
60            continue
61        out.append({"index": len(out), "driver": driver, "devid": devid})
62    return out
63
64
65def exactly_two_battlemage(cards: list[dict]) -> bool:
66    return len(cards) == 2 and all(is_battlemage(c.get("driver", ""), c.get("devid", "")) for c in cards)
67
68
69def _spec_group(args: list[str]) -> int:
70    """Index of the value after --spec in `args`, or -1."""
71    for i, a in enumerate(args):
72        if a == "--spec" and i + 1 < len(args):
73            return i + 1
74    return -1
75
76
77def plan(args: Any, user: Any, cards: list[dict], mtp_off: bool = False) -> tuple[list[str], str]:
78    """(new args, note): `args` with --spec 4 turned into --spec 2 when the run is on exactly two Battlemage cards, and ""
79    when nothing changed.  `user` is the config's "user_args"; `cards` the cards the run uses (exactly two to qualify);
80    `mtp_off` is the config's "mtp": false.  `args` is not changed in place."""
81    out = [str(a) for a in args] if isinstance(args, list) else []
82    if not exactly_two_battlemage(cards) or mtp_off:
83        return out, ""
84    if "--mtp" not in out:                                  # the pipeline needs the draft layer
85        return out, ""
86    if any(user_args.flag_of(g) == "--spec" for g in user_args.groups(user)):
87        return out, ""                                      # the person's own --spec wins
88    i = _spec_group(out)
89    if i < 0 or out[i] != SETUP_DEFAULT_SPEC:               # absent, or a value somebody chose
90        return out, ""
91    out[i] = TWO_CARD_SPEC
92    return out, ("Two Arc B-series cards: --spec 2 instead of 4. With both cards working on neighbouring windows the engine "
93                 "answers as a 2-token window anyway, and --spec 2 is about 20% faster here. To keep your own value, put "
94                 "\"--spec\" and its number in the config's \"user_args\".")
95
96
97def apply_for_launch(cfg: dict, sysfs: list[dict] | None = None) -> str:
98    """The launcher's run config: the cards in cfg["gpu"] (a list of two numbers after a layer split) looked up in sysfs, then
99    `apply_to_config`.  Nothing happens for a single card, another backend or a card list that sysfs cannot place."""
100    if cfg.get("backend") != "sycl":
101        return ""
102    gpu = cfg.get("gpu")
103    if not isinstance(gpu, (list, tuple)) or len(gpu) != 2:
104        return ""
105    try:
106        have = sysfs if sysfs is not None else sysfs_cards()
107        cards = [have[int(i)] for i in gpu if 0 <= int(i) < len(have)]
108    except (TypeError, ValueError):
109        return ""
110    return apply_to_config(cfg, cards) if len(cards) == 2 else ""
111
112
113def apply_to_config(cfg: dict, cards: list[dict]) -> str:
114    """`plan` on a run config (in place): changes cfg["args"], and the copy in cfg["args_written"] so a later setup run does not
115    take the change for the person's own edit.  Returns the note, "" when nothing changed."""
116    args, note = plan(cfg.get("args"), cfg.get("user_args"), cards, mtp_off=cfg.get("mtp") is False)
117    if not note:
118        return ""
119    cfg["args"] = args
120    written = cfg.get(user_args.WRITTEN_KEY)
121    if isinstance(written, list):
122        w = [str(a) for a in written]
123        i = _spec_group(w)
124        if i >= 0 and w[i] == SETUP_DEFAULT_SPEC:
125            w[i] = TWO_CARD_SPEC
126            cfg[user_args.WRITTEN_KEY] = w
127    return note