okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ddbfa1d5c
main
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 16uses 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 : 46return 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.""" 51return 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.""" 56try : 57text = (Path (rocm_root )/ "include" / "hipblaslt" / "hipblaslt-version.h" ).read_text (encoding = "utf-8" ) 58parts = [int (re .search (rf"#define\s+HIPBLASLT_VERSION_ { k } \s+(\d+)" ,text ).group (1 ))for k in ("MAJOR" ,"MINOR" ,"PATCH" )] 59except (OSError ,AttributeError ,ValueError ): 60return None 61return 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).""" 66try : 67with open (path ,encoding = "utf-8" )as f : 68head = [f .readline ().strip (),f .readline ().strip ()] 69except OSError : 70return False 71return 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.""" 76found = {} 77try : 78entries = sorted (Path (folder ).iterdir ()) 79except OSError : 80return found 81for path in entries : 82m = _NAME .match (path .name ) 83if m and path .is_file (): 84found [(m .group (1 ),int (m .group (2 )))]= path 85return 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/``. 92Returns the file names copied. An architecture without a table for that version is left out (plain hipBLAS stays for it); a 93table whose header disagrees with its name is an error, because the engine would refuse it on every start.""" 94import shutil 95stage ,copied = Path (stage ), [] 96if version is None : 97return copied 98have = tables_in (source ) 99for arch in archs : 100path = have .get ((arch ,version )) 101if path is None : 102continue 103if not header_ok (path ,arch ,version ): 104raise SystemExit (f" { path } : the second line does not say ' { HEADER } { arch } { version } '" ) 105 (stage / TABLE_DIR ).mkdir (parents = True ,exist_ok = True ) 106shutil .copy2 (path ,stage / TABLE_DIR / path .name ) 107copied .append (path .name ) 108return 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).""" 113have = tables_in (source ) 114return {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 119table in tuning/ must be named <arch>-hipblaslt-<that version>.txt for an architecture of the package with a header that says the same.""" 120stage ,problems = Path (stage ), [] 121version = package_version (stage ) 122if version is None : 123problems .append ("BUILD.json has no hipblaslt_version (packaging/stage_tuning.py writes it): a start could not match a tuning table to this hipBLASLt" ) 124folder = stage / TABLE_DIR 125if folder .is_dir (): 126for path in sorted (folder .iterdir ()): 127m = _NAME .match (path .name ) 128if not m : 129problems .append (f"tuning/ { path . name } is not named <arch>-hipblaslt-<version>.txt" ) 130elif m .group (1 )not in archs : 131problems .append (f"tuning/ { path . name } is for { m . group ( 1 ) } , which this package has no code for" ) 132elif version is not None and int (m .group (2 ))!= version : 133problems .append (f"tuning/ { path . name } is for hipBLASLt { m . group ( 2 ) } , this package carries { version } " ) 134elif not header_ok (path ,m .group (1 ),int (m .group (2 ))): 135problems .append (f"tuning/ { path . name } : the header line does not say ' { HEADER } { m . group ( 1 ) } { m . group ( 2 ) } '" ) 136return problems 137 138 139# ------------------------------------------------------------------------------------------------- start side 140 141@dataclass 142class Decision : 143path :Path | None # the table to hand the engine, or None 144message :str # one plain line for the log ("" when there is nothing to say) 145level :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).""" 150environ = os .environ if environ is None else environ 151word = str (environ .get (SWITCH ,"" )).strip ().lower () 152if word in OFF_WORDS : 153return "off" 154if word in ON_WORDS : 155return "on" 156if word in ("" ,"auto" ): 157value = (cfg or {}).get ("hipblaslt_table" ) 158return "off" if value is False else "on" if value is True else "auto" 159return "auto" 160 161 162def switched_off (environ = None ,cfg :dict | None = None )-> bool : 163return 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.""" 168try : 169value = json .loads ((Path (folder )/ "BUILD.json" ).read_text (encoding = "utf-8-sig" )).get ("hipblaslt_version" ) 170except (OSError ,ValueError ,AttributeError ): 171return None 172return 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.""" 177environ = os .environ if environ is None else environ 178for source in (environ , (cfg or {}).get ("env" )or {}): 179value = source .get (ENGINE_VAR ) 180if isinstance (value ,str )and value .strip (): 181return value .strip () 182return 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). 187Never raises; an empty message means there is nothing worth a line (not an AMD package, or the person chose already).""" 188folder = Path (folder ) 189if switched_off (environ ,cfg ): 190return Decision (None ,f"hipBLASLt tuning table: off ( { SWITCH } =off); the prompt's dense matrix products use plain hipBLAS" ) 191chosen = user_choice (environ ,cfg ) 192if chosen : 193return Decision (None ,f"hipBLASLt tuning table: { chosen } (set by you; the engine checks it against this GPU and hipBLASLt)" ) 194tuning = folder / TABLE_DIR 195if not tuning .is_dir (): 196return Decision (None ,"" )# a package without tables (CUDA, Metal, an older HIP package): nothing to say 197version = package_version (folder ) 198archs = [a for a in archs_present if isinstance (a ,str )] 199if version is None : 200return 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" ) 202if not archs : 203return Decision (None ,"hipBLASLt tuning table: not used, this PC's AMD GPU architecture could not be read; plain hipBLAS" ,"warn" ) 204tables = tables_in (tuning ) 205for arch in dict .fromkeys (archs ): 206path = tables .get ((arch ,version )) 207if path is None : 208continue 209if not header_ok (path ,arch ,version ): 210return Decision (None ,f"hipBLASLt tuning table: { path . name } is not used, its header does not match its name; plain hipBLAS" ,"warn" ) 211if mode (environ ,cfg )== "auto" and not (AUTO_USES_TABLE or arch in AUTO_ARCHS ): 212return Decision (None ,f"hipBLASLt tuning table: { path . name } is in this package and not used by default (faster prompts, but answers can differ " 213f"in the last digits); { SWITCH } =on uses it" ) 214return Decision (path ,f"hipBLASLt tuning table: { path . name } (faster prompts; { SWITCH } =off turns it off)" ) 215other = sorted ({v for (a ,v )in tables if a in archs }) 216if other : 217return Decision (None ,f"hipBLASLt tuning table: not used, this engine carries hipBLASLt { version } and the tables for { ', ' . join ( dict . fromkeys ( archs )) } " 218f"are for { ', ' . join ( str ( v ) for v in other ) } (solution ids are valid for one version only); plain hipBLAS" ,"warn" ) 219return 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 = -> dict : 223"""``cfg`` for a start from engine package ``folder``. One log line through ``say`` for an AMD package (nothing for other backends). 224The 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 227and a table the person named are left as they are).""" 228if cfg .get ("backend" )not in (None ,"hip" ): 229return cfg 230folder = Path (folder ) 231if not (folder / TABLE_DIR ).is_dir ()and package_version (folder )is None : 232return cfg # not a package with tables or a hipBLASLt version: nothing to decide 233if archs_present is None : 234archs_present = present_archs (cfg ) 235decision = resolve (folder ,archs_present ,environ = environ ,cfg = cfg ) 236if decision .message : 237say (("[strata] " if decision .level == "info" else "[strata] note: " )+ decision .message ) 238value = cfg .get ("hipblaslt_table" ) 239env_now = os .environ if environ is None else environ 240if 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 ): 241out = dict (cfg ) 242out ["env" ]= {** (cfg .get ("env" )or {}),SWITCH :"on" if value else "off" } 243return out 244return 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 249config's "gpu" picks one card of several when the list is per card (Linux).""" 250try : 251from strata_control import engine_component as ec 252archs = ec .hip_archs_present () 253except Exception : 254return [] 255gpu = (cfg or {}).get ("gpu" ) 256picked = gpu if isinstance (gpu ,list )else [gpu ]if isinstance (gpu ,int )and not isinstance (gpu ,bool )else [] 257chosen = [archs [i ]for i in picked if 0 <= i < len (archs )]if os .name != "nt" else [] 258return chosen or archs