okami.mom/strata

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

Niko1221Merge f-clean-1c (3c32937a2): launcher speed settings become engine defaults (parallel stack, GDN stack, gfx12 chunked scan, HC_Q8 on UD files, Metal fp16 for resident IQ3_S/Q2_0, hipBLASLt table on gfx1151 only); row 8 held (cleanup step 1c)ddbfa1d5c

main
14.4 KiB258 linesraw
1"""The hipBLASLt tuning tables that ship inside the AMD engine packages, and the one rule that decides whether a start uses one.
2
3A table (tools/hip/<arch>-hipblaslt-<version>.txt) lists, per dense GEMM shape of the prompt path, the hipBLASLt solution that was
4fastest on that GPU architecture. Its solution ids are valid for one architecture and one hipBLASLt version only; the engine checks both
5(src/prefill/gemm.cu) and falls back to plain hipBLAS for anything else, so a wrong table can never change a result, it only wastes the
6speed-up. The table picks a GEMM algorithm: it does not change what the model is asked to compute.
7
8Package side (packaging/stage_tuning.py, tools/hip/package_windows.py): ``tuning/<arch>-hipblaslt-<version>.txt`` inside the engine package,
9one per architecture of the package that has a table for the hipBLASLt version the package bundles, and ``hipblaslt_version`` in its BUILD.json.
10The files are listed (and hashed, and signed) in engine-component.json like every other file of the package.
11
12Start side (serve/server.py with_component_engine, setup.py in the app): ``resolve`` reads the package, the GPUs in this PC and the switch,
13and returns the table to use or the reason there is none. Nobody sets STRATA_HIPBLASLT_TUNING by hand:
14
15* ``STRATA_HIPBLASLT_TABLE`` (or ``"hipblaslt_table"`` in the run config): ``off`` / false never uses the packaged table, ``on`` / true
16  uses it when it matches, ``auto`` (unset) follows ``AUTO_USES_TABLE`` below;
17* a ``STRATA_HIPBLASLT_TUNING`` the person set themselves (environment or run config) always wins and is not touched;
18* a table for another hipBLASLt version than the package bundles is not used, and the log says which versions it has.
19"""
20from __future__ import annotations
21
22import json
23import os
24import re
25from dataclasses import dataclass
26from pathlib import Path
27
28SWITCH = "STRATA_HIPBLASLT_TABLE"            # on | auto | off
29#: What "auto" (the switch unset) does. A table changes which hipBLASLt solution runs the prompt's dense GEMMs, so their floating-point sums
30#: round differently: on an R9700 (gfx1201, Q2_0) the answers with a table are NOT bit-identical to plain hipBLAS, see phaseA-tests/notes-021-hip.md.
31#: A default that changes bits needs the owner's decision, so the packages carry their tables and the switch ("on") uses them, but "auto" is
32#: off until that decision. Flipping this one constant turns the tables on for every package that carries one.
33AUTO_USES_TABLE = False
34#: The owner's decision (2026-10-19): "auto" uses the table on these architectures only. gfx1151 (Strix Halo): a community A/B measured
35#: 251 -> 529 prompt tok/s (2.11x) with the table; on gfx1201 the gain was ~1% and decode lost ~2% (notes-021-hip.md), so it stays opt-in there.
36AUTO_ARCHS = ("gfx1151",)
37ENGINE_VAR = "STRATA_HIPBLASLT_TUNING"       # what the engine reads: the path of one table
38TABLE_DIR = "tuning"                         # inside an engine package
39HEADER = "STRATA_HIPBLASLT_TUNING_V1"
40OFF_WORDS = ("off", "0", "no", "false", "none", "disable", "disabled")
41ON_WORDS = ("on", "1", "yes", "true", "force", "enable", "enabled")
42_NAME = re.compile(r"^(gfx[0-9a-f]+)-hipblaslt-(\d+)\.txt$")
43
44
45def table_name(arch: str, version: int) -> str:
46    return f"{arch}-hipblaslt-{version}.txt"
47
48
49def version_number(major: int, minor: int, patch: int) -> int:
50    """hipblasLtGetVersion's number: 1.5.0 -> 100500, 1.2.2 -> 100202."""
51    return major * 100000 + minor * 100 + patch
52
53
54def version_from_header(rocm_root) -> int | None:
55    """The hipBLASLt version of a ROCm tree, from include/hipblaslt/hipblaslt-version.h (what a package build has at hand); None when absent."""
56    try:
57        text = (Path(rocm_root) / "include" / "hipblaslt" / "hipblaslt-version.h").read_text(encoding="utf-8")
58        parts = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR", "PATCH")]
59    except (OSError, AttributeError, ValueError):
60        return None
61    return version_number(*parts)
62
63
64def header_ok(path: Path, arch: str, version: int) -> bool:
65    """The file's own second line must name the same architecture and version as its file name (the engine checks it again)."""
66    try:
67        with open(path, encoding="utf-8") as f:
68            head = [f.readline().strip(), f.readline().strip()]
69    except OSError:
70        return False
71    return f"{HEADER} {arch} {version}" in head
72
73
74def tables_in(folder) -> dict[tuple[str, int], Path]:
75    """{(arch, version): path} for every table file in a folder."""
76    found = {}
77    try:
78        entries = sorted(Path(folder).iterdir())
79    except OSError:
80        return found
81    for path in entries:
82        m = _NAME.match(path.name)
83        if m and path.is_file():
84            found[(m.group(1), int(m.group(2)))] = path
85    return found
86
87
88# ------------------------------------------------------------------------------------------------- package side
89
90def stage_tables(stage, archs, version: int | None, source) -> list[str]:
91    """Copy the tables for ``archs`` and hipBLASLt ``version`` from the repo folder ``source`` (tools/hip) into ``stage/tuning/``.
92    Returns the file names copied. An architecture without a table for that version is left out (plain hipBLAS stays for it); a
93    table whose header disagrees with its name is an error, because the engine would refuse it on every start."""
94    import shutil
95    stage, copied = Path(stage), []
96    if version is None:
97        return copied
98    have = tables_in(source)
99    for arch in archs:
100        path = have.get((arch, version))
101        if path is None:
102            continue
103        if not header_ok(path, arch, version):
104            raise SystemExit(f"{path}: the second line does not say '{HEADER} {arch} {version}'")
105        (stage / TABLE_DIR).mkdir(parents=True, exist_ok=True)
106        shutil.copy2(path, stage / TABLE_DIR / path.name)
107        copied.append(path.name)
108    return copied
109
110
111def missing_report(archs, version: int | None, source) -> dict[str, list[int]]:
112    """For each architecture without a table for ``version``: the versions the repo does have for it (so a build can say it)."""
113    have = tables_in(source)
114    return {a: sorted(v for (arch, v) in have if arch == a) for a in archs if version is None or (a, version) not in have}
115
116
117def check_stage(stage, archs) -> list[str]:
118    """What is wrong with the tuning of a staged HIP package (empty list: fine): BUILD.json must say which hipBLASLt it carries, and every
119    table in tuning/ must be named <arch>-hipblaslt-<that version>.txt for an architecture of the package with a header that says the same."""
120    stage, problems = Path(stage), []
121    version = package_version(stage)
122    if version is None:
123        problems.append("BUILD.json has no hipblaslt_version (packaging/stage_tuning.py writes it): a start could not match a tuning table to this hipBLASLt")
124    folder = stage / TABLE_DIR
125    if folder.is_dir():
126        for path in sorted(folder.iterdir()):
127            m = _NAME.match(path.name)
128            if not m:
129                problems.append(f"tuning/{path.name} is not named <arch>-hipblaslt-<version>.txt")
130            elif m.group(1) not in archs:
131                problems.append(f"tuning/{path.name} is for {m.group(1)}, which this package has no code for")
132            elif version is not None and int(m.group(2)) != version:
133                problems.append(f"tuning/{path.name} is for hipBLASLt {m.group(2)}, this package carries {version}")
134            elif not header_ok(path, m.group(1), int(m.group(2))):
135                problems.append(f"tuning/{path.name}: the header line does not say '{HEADER} {m.group(1)} {m.group(2)}'")
136    return problems
137
138
139# ------------------------------------------------------------------------------------------------- start side
140
141@dataclass
142class Decision:
143    path: Path | None            # the table to hand the engine, or None
144    message: str                 # one plain line for the log ("" when there is nothing to say)
145    level: str = "info"          # info | warn
146
147
148def mode(environ=None, cfg: dict | None = None) -> str:
149    """"on", "off" or "auto": the environment switch first, then the run config's "hipblaslt_table" (true / false)."""
150    environ = os.environ if environ is None else environ
151    word = str(environ.get(SWITCH, "")).strip().lower()
152    if word in OFF_WORDS:
153        return "off"
154    if word in ON_WORDS:
155        return "on"
156    if word in ("", "auto"):
157        value = (cfg or {}).get("hipblaslt_table")
158        return "off" if value is False else "on" if value is True else "auto"
159    return "auto"
160
161
162def switched_off(environ=None, cfg: dict | None = None) -> bool:
163    return mode(environ, cfg) == "off"
164
165
166def package_version(folder) -> int | None:
167    """hipblaslt_version in the package's BUILD.json (an int, 100500), else None."""
168    try:
169        value = json.loads((Path(folder) / "BUILD.json").read_text(encoding="utf-8-sig")).get("hipblaslt_version")
170    except (OSError, ValueError, AttributeError):
171        return None
172    return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None
173
174
175def user_choice(environ=None, cfg: dict | None = None) -> str | None:
176    """A STRATA_HIPBLASLT_TUNING the person set (environment first, then the run config's env): theirs to keep, even if the file is gone."""
177    environ = os.environ if environ is None else environ
178    for source in (environ, (cfg or {}).get("env") or {}):
179        value = source.get(ENGINE_VAR)
180        if isinstance(value, str) and value.strip():
181            return value.strip()
182    return None
183
184
185def resolve(folder, archs_present, *, environ=None, cfg: dict | None = None) -> Decision:
186    """The table for an installed AMD engine package ``folder`` on a PC whose GPUs are ``archs_present`` (in the order the engine sees them).
187    Never raises; an empty message means there is nothing worth a line (not an AMD package, or the person chose already)."""
188    folder = Path(folder)
189    if switched_off(environ, cfg):
190        return Decision(None, f"hipBLASLt tuning table: off ({SWITCH}=off); the prompt's dense matrix products use plain hipBLAS")
191    chosen = user_choice(environ, cfg)
192    if chosen:
193        return Decision(None, f"hipBLASLt tuning table: {chosen} (set by you; the engine checks it against this GPU and hipBLASLt)")
194    tuning = folder / TABLE_DIR
195    if not tuning.is_dir():
196        return Decision(None, "")                      # a package without tables (CUDA, Metal, an older HIP package): nothing to say
197    version = package_version(folder)
198    archs = [a for a in archs_present if isinstance(a, str)]
199    if version is None:
200        return Decision(None, "hipBLASLt tuning table: not used, this engine package does not say which hipBLASLt it carries "
201                              "(BUILD.json hipblaslt_version); the prompt's dense matrix products use plain hipBLAS", "warn")
202    if not archs:
203        return Decision(None, "hipBLASLt tuning table: not used, this PC's AMD GPU architecture could not be read; plain hipBLAS", "warn")
204    tables = tables_in(tuning)
205    for arch in dict.fromkeys(archs):
206        path = tables.get((arch, version))
207        if path is None:
208            continue
209        if not header_ok(path, arch, version):
210            return Decision(None, f"hipBLASLt tuning table: {path.name} is not used, its header does not match its name; plain hipBLAS", "warn")
211        if mode(environ, cfg) == "auto" and not (AUTO_USES_TABLE or arch in AUTO_ARCHS):
212            return Decision(None, f"hipBLASLt tuning table: {path.name} is in this package and not used by default (faster prompts, but answers can differ "
213                                  f"in the last digits); {SWITCH}=on uses it")
214        return Decision(path, f"hipBLASLt tuning table: {path.name} (faster prompts; {SWITCH}=off turns it off)")
215    other = sorted({v for (a, v) in tables if a in archs})
216    if other:
217        return Decision(None, f"hipBLASLt tuning table: not used, this engine carries hipBLASLt {version} and the tables for {', '.join(dict.fromkeys(archs))} "
218                              f"are for {', '.join(str(v) for v in other)} (solution ids are valid for one version only); plain hipBLAS", "warn")
219    return Decision(None, f"hipBLASLt tuning table: none for {', '.join(dict.fromkeys(archs))} with hipBLASLt {version}; plain hipBLAS")
220
221
222def apply(cfg: dict, folder, archs_present=None, *, environ=None, say=print) -> dict:
223    """``cfg`` for a start from engine package ``folder``. One log line through ``say`` for an AMD package (nothing for other backends).
224    The engine finds ``tuning/<arch>-hipblaslt-<version>.txt`` beside itself (src/prefill/gemm.cu: gfx1151 on its own, any card with
225    ``STRATA_HIPBLASLT_TABLE=on``), so no table path is put in the config any more.  What the engine cannot see is the run config's
226    ``"hipblaslt_table"``: a true / false there is passed as ``env[STRATA_HIPBLASLT_TABLE]`` = on / off (a copy; the shell's own switch
227    and a table the person named are left as they are)."""
228    if cfg.get("backend") not in (None, "hip"):
229        return cfg
230    folder = Path(folder)
231    if not (folder / TABLE_DIR).is_dir() and package_version(folder) is None:
232        return cfg                                      # not a package with tables or a hipBLASLt version: nothing to decide
233    if archs_present is None:
234        archs_present = present_archs(cfg)
235    decision = resolve(folder, archs_present, environ=environ, cfg=cfg)
236    if decision.message:
237        say(("[strata] " if decision.level == "info" else "[strata] note: ") + decision.message)
238    value = cfg.get("hipblaslt_table")
239    env_now = os.environ if environ is None else environ
240    if isinstance(value, bool) and SWITCH not in (cfg.get("env") or {}) and not str(env_now.get(SWITCH, "")).strip() and not user_choice(environ, cfg):
241        out = dict(cfg)
242        out["env"] = {**(cfg.get("env") or {}), SWITCH: "on" if value else "off"}
243        return out
244    return cfg
245
246
247def present_archs(cfg: dict | None = None) -> list[str]:
248    """The AMD architectures of the GPUs the engine will use, as ``strata_control.engine_component.hip_archs_present`` lists them; the run
249    config's "gpu" picks one card of several when the list is per card (Linux)."""
250    try:
251        from strata_control import engine_component as ec
252        archs = ec.hip_archs_present()
253    except Exception:
254        return []
255    gpu = (cfg or {}).get("gpu")
256    picked = gpu if isinstance(gpu, list) else [gpu] if isinstance(gpu, int) and not isinstance(gpu, bool) else []
257    chosen = [archs[i] for i in picked if 0 <= i < len(archs)] if os.name != "nt" else []
258    return chosen or archs