okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1#!/usr/bin/env python3 2"""The settings register: every STRATA_* environment setting the engine reads, in one file (data/settings-register.json). 3 4python tools/settings_register.py # regenerate data/settings-register.json (keeps the hand-kept fields) 5python tools/settings_register.py --check # scan only; print what is missing from / extra in the register; exit 1 on a difference 6python tools/settings_register.py --names # print the names the engine reads, one per line 7python tools/settings_register.py --no-git # regenerate without the git history fields (fast) 8python tools/settings_register.py --docs # write docs/SETTINGS.md from the register 9 10What counts as "the engine reads it": the name is the string literal argument of a ``getenv`` call or of one of the engine's env 11helpers (``env_on``, ``env_int``, ``pipe_dbg_env`` ...) in src/, include/, metal/src/ or sycl/src/. Calls that write or remove a 12variable (``_putenv_s``, ``put_env``, ``set_env``, ``unset_env``) are not reads; they are listed as ``engine_sets``. 13 14Automatic fields (rebuilt on every run): backends, reads, parse, code_default, default_state, engine_sets, launch_sets, launch_reads, 15doc_mentions, first/last commit and the first release that has the name. 16 17Hand-kept fields (copied over from the old file on every run, never written by the scan): status, owner, note, retire_after, retired_in. 18``status`` is one of STATUSES below. A new name comes in with status "" and the test refuses an empty status until somebody sets it. 19 20Only the standard library is used. 21""" 22from __future__import annotations 23 24import argparse 25import collections 26import json 27import os 28import re 29import subprocess 30import sys 31from pathlib import Path 32 33ROOT = Path (__file__ ).resolve ().parent .parent 34REGISTER = ROOT / "data" / "settings-register.json" 35SETTINGS_PAGE = "docs/SETTINGS.md" 36 37ENGINE_DIRS = ("src" ,"include" ,"metal/src" ,"sycl/src" ) 38LAUNCH_PATHS = ("strata_control" ,"strata_cli" ,"setup.py" ,"apps/host/server" ,"serve" ) 39DOC_PATHS = ("docs" ,"README.md" ,"AGENTS.md" ) 40LAUNCH_EXT = (".py" ,".mjs" ,".js" ,".cjs" ,".ts" ) 41SKIP_PARTS = ("node_modules" ,"/tests/" ,"/test/" ,"__pycache__" ) 42 43STATUSES = ("default" ,"rollback" ,"opt-in" ,"research" ,"retire-candidate" ,"unsure" ,"retired" ) 44HAND_FIELDS = ("status" ,"owner" ,"note" ,"retire_after" ,"retired_in" ) 45 46NAME_RE = re .compile (r"STRATA_[A-Z0-9_]+" ) 47# a call whose first argument is the name literal: getenv, env_on, env_int, pipe_dbg_env, il_env_on, kva_env_flag ... 48CALL_RE = re .compile (r'(\w*(?:getenv|env\w*|\w*_env\w*)\s*\(\s*)"(STRATA_[A-Z0-9_]+)"' ) 49WRITE_FN_RE = re .compile (r"put|set_env|unset|setenv" ) 50 51FLAG_FNS = {"env_on" ,"env_flag" ,"il_env_on" ,"kva_env_flag" ,"env_tri" } 52INT_FNS = {"env_int" ,"env_int_or" ,"kva_env_i64" ,"a_env" ,"env_count" ,"lanes_env" } 53FLOAT_FNS = {"env_num" ,"env_f" } 54 55HIP_MACROS = {"STRATA_USE_HIP" ,"__HIPCC__" ,"STRATA_HIP_GFX906" ,"FNX_HIP" ,"__HIP_PLATFORM_AMD__" ,"STRATA_HIPBLASLT_AVAILABLE" , 56"STRATA_ROCBLAS_AVAILABLE" ,"__HIP_DEVICE_COMPILE__" ,"STRATA_PREFILL_MMQ_HIP" } 57CUDA_ONLY_MACROS = {"__CUDA_ARCH__" ,"CUDART_VERSION" ,"__NVPTX__" ,"STRATA_EXPERIMENTAL_SM60" } 58METAL_MACROS = {"STRATA_METAL" ,"STRATA_GPU_METAL" ,"__APPLE__" } 59 60 61# ---------------------------------------------------------------- file walking 62 63def _files (rel_paths ,exts = None ): 64for rel in rel_paths : 65base = ROOT / rel 66if base .is_file (): 67yield base 68continue 69for dirpath ,dirnames ,filenames in os .walk (base ): 70dirnames [:]= [d for d in dirnames if d not in ("node_modules" ,"__pycache__" ,".git" )] 71for fn in filenames : 72if exts and not fn .endswith (exts ): 73continue 74yield Path (dirpath )/ fn 75 76 77def _rel (p :Path )-> str : 78return p .relative_to (ROOT ).as_posix () 79 80 81def _read_lines (p :Path ): 82try : 83return p .read_text (encoding = "utf-8" ,errors = "replace" ).split ("\n" ) 84except OSError : 85return [] 86 87 88# ---------------------------------------------------------------- preprocessor reachability (CUDA / HIP / Metal) 89 90_TOKEN = re .compile (r"!|&&|\|\||\(|\)|defined\s*\(\s*(\w+)\s*\)|defined\s+(\w+)|[A-Za-z_]\w*|\d+" ) 91 92 93def _eval (expr :str ,cfg :str ): 94"""Three-valued evaluation of a preprocessor condition for one build flavour; None is unknown (treated as possibly true).""" 95toks = [] 96for m in _TOKEN .finditer (expr ): 97toks .append (m ) 98pos = 0 99 100def val (sym :str ): 101if sym in HIP_MACROS : 102return cfg == "hip" 103if sym in CUDA_ONLY_MACROS : 104return cfg == "cuda" 105if sym in METAL_MACROS : 106return cfg == "metal" 107return None 108 109def primary (): 110nonlocal pos 111if pos >= len (toks ): 112return None 113m = toks [pos ] 114t = m .group (0 ) 115if t == "!" : 116pos += 1 117v = primary () 118return None if v is None else (not v ) 119if t == "(" : 120pos += 1 121v = orx () 122if pos < len (toks )and toks [pos ].group (0 )== ")" : 123pos += 1 124return v 125pos += 1 126if t .startswith ("defined" ): 127return val (m .group (1 )or m .group (2 )) 128if t .isdigit (): 129return None if t not in ("0" ,"1" )else (t == "1" ) 130return val (t ) 131 132def andx (): 133nonlocal pos 134v = primary () 135while pos < len (toks )and toks [pos ].group (0 )== "&&" : 136pos += 1 137w = primary () 138v = False if (v is False or w is False )else (None if (v is None or w is None )else True ) 139return v 140 141def orx (): 142nonlocal pos 143v = andx () 144while pos < len (toks )and toks [pos ].group (0 )== "||" : 145pos += 1 146w = andx () 147v = True if (v is True or w is True )else (None if (v is None or w is None )else False ) 148return v 149 150# comparisons (">=", "<") make the whole condition unknown; the tokenizer skips them, so give up on such a line 151if re .search (r"[<>=]=?|[+\-*/]" ,re .sub (r"&&|\|\||!defined|!\s*\(|!\s*\w" ,"" ,expr )): 152return None 153return orx () 154 155 156def _pp_states (lines ): 157"""For every line, the set of build flavours in which it can be compiled: a subset of {"cuda", "hip", "metal"}.""" 158flavours = ("cuda" ,"hip" ,"metal" ) 159stack = []# each: (cond_values {cfg: bool|None}, parent_alive set) for the current branch 160out = [] 161alive = set (flavours ) 162for line in lines : 163s = line .lstrip () 164if s .startswith ("#" ): 165d = re .sub (r"^#\s*" ,"" ,s ) 166m = re .match (r"(ifdef|ifndef|if|elif|else|endif)\b(.*)" ,d ) 167if m : 168kw ,rest = m .group (1 ),re .sub (r"(//.*|/\*.*)$" ,"" ,m .group (2 )).strip () 169if kw in ("if" ,"ifdef" ,"ifndef" ): 170if kw == "ifdef" : 171cond = {c :_eval (f"defined( { rest . split ()[ 0 ] } )" if rest .split ()else "" ,c )for c in flavours } 172elif kw == "ifndef" : 173cond = {c :_eval (f"!defined( { rest . split ()[ 0 ] } )" if rest .split ()else "" ,c )for c in flavours } 174else : 175cond = {c :_eval (rest ,c )for c in flavours } 176stack .append ({"parent" :set (alive ),"cond" :cond ,"taken" : {c : (cond [c ]is True )for c in flavours }}) 177alive = {c for c in stack [- 1 ]["parent" ]if cond [c ]is not False } 178elif kw == "elif" and stack : 179top = stack [- 1 ] 180cond = {c :_eval (rest ,c )for c in flavours } 181alive = {c for c in top ["parent" ]if cond [c ]is not False and not top ["taken" ][c ]} 182for c in flavours : 183top ["taken" ][c ]= top ["taken" ][c ]or cond [c ]is True 184elif kw == "else" and stack : 185top = stack [- 1 ] 186alive = {c for c in top ["parent" ]if not top ["taken" ][c ]} 187elif kw == "endif" and stack : 188top = stack .pop () 189alive = set (top ["parent" ]) 190out .append (alive ) 191return out 192 193 194# ---------------------------------------------------------------- engine scan 195 196def _backend_of (path :str ,flavours :set [str ])-> list [str ]: 197p = path 198if p .startswith ("sycl/src" ): 199return ["sycl" ] 200if p .startswith ("metal/src" ): 201return ["metal" ] 202if "/cpu/" in p or p .endswith (("_cpu.cpp" ,"_cpu.hpp" )): 203return ["cpu" ] 204fl = flavours 205if fl >= {"cuda" ,"hip" }: 206res = ["cuda-hip" ] 207elif fl == {"cuda" }: 208res = ["cuda" ] 209elif fl == {"hip" }: 210res = ["hip" ] 211elif fl == {"metal" }: 212res = ["metal" ] 213elif not fl : 214res = ["cuda-hip" ] 215else : 216res = ["cuda-hip" ]if "cuda" in fl or "hip" in fl else sorted (fl ) 217base = os .path .basename (p ).lower () 218if res == ["cuda-hip" ]: 219if "hipblaslt" in base or "rocblas" in base or "/hip" in p or "hip_" in base : 220res = ["hip" ] 221elif re .search (r"sm\d\d|nv_defaults|nvfp4|cublas|/nvidia" ,p .lower ())and "hip" not in base : 222res = ["cuda" ] 223return res 224 225 226_INT_RE = re .compile (r"\b(atoi|stoi|strtol|strtoll|strtoul|strtoull|atol|atoll|stoll|stoul|stoull)\b" ) 227_FLOAT_RE = re .compile (r"\b(atof|strtod|strtof|stof|stod)\b" ) 228_NUM = r"-?(?:0x[0-9a-fA-F]+|\d[\d.']*(?:e[+-]?\d+)?)[fFuUlL]*" 229 230 231def _num_clean (s :str )-> str : 232return re .sub (r"[fFuUlL]+$" ,"" ,s .replace ("'" ,"" )) 233 234 235def _analyze (lines ,i ,name ,fn ,col ): 236"""parse kind and code default for one read. i is the 0-based line index, col the column where the call starts.""" 237fn0 = fn .strip ().rstrip ("(" ).strip () 238short = fn0 .split ("::" )[- 1 ] 239first = lines [i ][col :] 240# arguments of a helper that takes a default: env_int("X", 5) 241argm = re .match (r'[^"]*"' + re .escape (name )+ r'"\s*,\s*([^),;]+(?:\([^)]*\))?[^),;]*)\)' ,first ) 242if short in FLAG_FNS or short in INT_FNS or short in FLOAT_FNS or short == "pipe_dbg_env" : 243arg = argm .group (1 ).strip ()if argm else None 244if short == "il_env_on" : 245return "flag" ,"on" ,"set to 0 turns it off" 246if short in ("env_on" ,"env_flag" ): 247return "flag" ,"off" ,"unset is off" 248if short == "kva_env_flag" : 249d = None if arg is None else ("on" if arg in ("true" ,"1" )else "off" if arg in ("false" ,"0" )else None ) 250return "flag" ,d ,arg 251if short == "env_tri" : 252return "flag" ,None ,"unset / 0 / non-zero" 253if short in INT_FNS : 254return "int" ,None , (_num_clean (arg )if arg else None ) 255if short in FLOAT_FNS : 256return "float" ,None , (_num_clean (arg )if arg else None ) 257if short == "pipe_dbg_env" : 258return "debug-gated" ,None ,"read only when STRATA_PIPELINE_DEBUG=1" 259# std::getenv: look at the rest of the statement and the next two lines 260win = [first ] 261for k in range (1 ,4 ): 262if i + k < len (lines ): 263win .append (lines [i + k ]) 264text = "\n" .join (win ) 265cut = re .search (r'getenv\(\s*"STRATA_' ,text [len (first .split (name ,1 )[0 ])+ len (name ):]) 266if cut : 267text = text [:len (first .split (name ,1 )[0 ])+ len (name )+ cut .start ()] 268prev = lines [i - 1 ]if i > 0 else "" 269kind = None 270if _FLOAT_RE .search (text ): 271kind = "float" 272elif _INT_RE .search (text ): 273kind = "int" 274elif re .search (r"'0'|\"0\"|!=\s*nullptr|==\s*nullptr|!=\s*NULL|==\s*NULL|\[0\]|\*\w+\s*(?:!=|==)|&&|\|\||\bif\s*\(|!\w" ,text ): 275kind = "flag" 276else : 277kind = "string" 278default_state = None 279code_default = None 280if kind == "flag" : 281# Only the exact shapes are read; anything else stays None ("not readable from the call"). 282t = re .sub (r"\s+" ," " ,text ) 283on = (re .search (r"(?:==\s*(?:nullptr|NULL)|!\s*\w+)\s*\|\|\s*\(?\w+(?:\[0\]|\s*\[\s*0\s*\])\s*!=\s*'0'" ,t )# unset or not "0" 284or re .search (r"!\(\s*\w+\s*&&\s*\w+\[0\]\s*==\s*'0'\s*\)" ,t )# !(e && e[0]=='0') 285or re .search (r"(?:==\s*(?:nullptr|NULL)|!\s*\w+)\s*\|\|\s*std::strcmp\(\s*\w+\s*,\s*\"0\"\s*\)\s*!=\s*0" ,t ) 286or re .search (r"\b\w+\s*&&\s*\w+\[0\]\s*==\s*'0'\s*\)?\s*(?:return|\{)" ,t ))# if (e && e[0]=='0') off 287off = (re .search (r"!=\s*(?:nullptr|NULL)\s*&&\s*\(?\w+\[0\]\s*!=\s*'0'" ,t ) 288or re .search (r"!=\s*(?:nullptr|NULL)\s*&&\s*\*?\w+\s*!=\s*'0'" ,t ) 289or re .search (r"\b\w+\s*&&\s*\w+\[0\]\s*(?:!=\s*'0'|==\s*'1')" ,t ) 290or re .search (r"return\s+\w+\s*&&\s*std::atoi\(\s*\w+\s*\)\s*!=\s*0" ,t ) 291or re .search (r"!=\s*(?:nullptr|NULL)\s*&&\s*std::atoi\(" ,t )) 292if on and not off : 293default_state = "on" 294elif off and not on : 295default_state = "off" 296elif not on and not off : 297# presence only: getenv("X") != nullptr (set = on) / == nullptr (set = off) 298pres = re .match (r'getenv\("' + re .escape (name )+ r'"\)\s*(!=|==)\s*(?:nullptr|NULL)\b(?!\s*&&)' ,t ) 299if pres : 300default_state = "off" if pres .group (1 )== "!=" else "on" 301elif kind in ("int" ,"float" ): 302m = re .search (r"\)\s*:\s*(" + _NUM + r")" ,text )or re .search (r"\?\s*[^:;]*:\s*(" + _NUM + r")\s*[;,)]" ,text ) 303if m : 304code_default = _num_clean (m .group (1 )) 305else : 306m = re .search (r"=\s*(" + _NUM + r")\s*;\s*$" ,prev ) 307if m and re .search (r"\bif\s*\(" ,text ): 308code_default = _num_clean (m .group (1 )) 309return kind ,default_state ,code_default 310 311 312def scan_engine (): 313reads = collections .defaultdict (list ) 314sets = collections .defaultdict (list ) 315for p in _files (ENGINE_DIRS ): 316rel = _rel (p ) 317lines = _read_lines (p ) 318if not any ("STRATA_" in l for l in lines ): 319continue 320states = None 321for i ,l in enumerate (lines ): 322if "STRATA_" not in l : 323continue 324for m in CALL_RE .finditer (l ): 325fn ,name = m .group (1 ),m .group (2 ) 326if states is None : 327states = _pp_states (lines ) 328if WRITE_FN_RE .search (fn ): 329sets [name ].append ({"file" :rel ,"line" :i + 1 }) 330continue 331kind ,dstate ,dflt = _analyze (lines ,i ,name ,fn ,m .start ()) 332reads [name ].append ({ 333"file" :rel ,"line" :i + 1 , 334"backend" :_backend_of (rel ,states [i ])[0 ], 335"fn" :fn .strip ().rstrip ("(" ).strip ().split ("::" )[- 1 ], 336"parse" :kind ,"default_state" :dstate ,"code_default" :dflt , 337 }) 338return reads ,sets 339 340 341# ---------------------------------------------------------------- launch code 342 343_SET_PATTERNS = [ 344re .compile (r"""["'`]NAME["'`]\s*:\s*(?P<v>[^,}\n]+)""" ),# {"NAME": "1"} 345re .compile (r"""\(\s*["']NAME["']\s*,\s*(?P<v>[^)\n]+)\)""" ),# ("NAME", "1") 346re .compile (r"""\[\s*["']NAME["']\s*\]\s*=(?!=)\s*(?P<v>[^\n]+)""" ),# env["NAME"] = x 347re .compile (r"""setdefault\(\s*["']NAME["']\s*,\s*(?P<v>[^)\n]+)\)""" ), 348re .compile (r"""\.NAME\s*=(?!=)\s*(?P<v>[^\n;]+)""" ),# process.env.NAME = x 349re .compile (r"""(?<![A-Z0-9_])NAME=(?P<v>[^\s"'`,;)\]]+)""" ),# NAME=1 in a string / command 350re .compile (r"""["'`]NAME["'`]\s*,\s*(?P<v>["'`][^"'`\n]*["'`])""" ),# ["NAME", "1"] / env.set("NAME","1") 351] 352 353 354def _is_test (rel :str )-> bool : 355b = os .path .basename (rel ) 356return (b .startswith ("test_" )or b .endswith (("_test.py" ,".test.mjs" ,".test.js" ,".spec.mjs" ))or b == "conftest.py" 357or any (s in "/" + rel for s in SKIP_PARTS )) 358 359 360def scan_launch (names ): 361sets = collections .defaultdict (list ) 362reads = collections .defaultdict (list ) 363named = collections .defaultdict (set ) 364for p in _files (LAUNCH_PATHS ,LAUNCH_EXT ): 365rel = _rel (p ) 366if _is_test (rel ): 367continue 368lines = _read_lines (p ) 369in_doc = False 370for i ,l in enumerate (lines ): 371was_doc = in_doc 372if p .suffix == ".py" and l .count ('"""' )% 2 == 1 : 373in_doc = not in_doc 374if "STRATA_" not in l : 375continue 376stripped = l .strip () 377is_comment = stripped .startswith (("#" ,"//" ,"*" ,"/*" ))or was_doc or (in_doc and not was_doc and '"""' in l and False ) 378for nm in set (re .findall (r"STRATA_[A-Z0-9_]+(?![A-Z0-9_])" ,l )): 379if nm not in names : 380continue 381named [nm ].add (rel ) 382got = None 383if not is_comment : 384for pat in _SET_PATTERNS : 385m = re .search (pat .pattern .replace ("NAME" ,re .escape (nm )),l ) 386if m : 387got = m .group ("v" ).strip ().rstrip (",;" ).strip () 388break 389if got is not None and (got .startswith (("\"STRATA_" ,"'STRATA_" ))or "\\d" in got or got .endswith (":" )or got in ('"reason"' ,'"when"' ,'"value"' )): 390got = None 391if got is not None and not re .search (r"environ\.get|getenv|\.get\(" ,l [:l .find (nm )]): 392sets [nm ].append ({"file" :rel ,"line" :i + 1 ,"value" :got [:80 ]}) 393elif not is_comment and re .search (r"environ\.get|environ\[|getenv|process\.env|env\.get|env\[" ,l ): 394reads [nm ].append ({"file" :rel ,"line" :i + 1 }) 395return sets ,reads ,named 396 397 398# ---------------------------------------------------------------- engine default tables 399 400DEFAULT_TABLE_FILES = ("src/core/arch_defaults.cpp" ,"src/core/nv_defaults.cpp" ,"src/core/amd_community.cpp" ,"src/core/gfx12_extra.cpp" , 401"src/core/defaults_026.cpp" ) 402 403 404_ARCH_LABELS = ( 405 (re .compile (r"gfx_arch_is_gfx12\b|gfx12\b" ),"gfx12" ), 406 (re .compile (r'gfx_arch_is_gfx1151|"gfx1151"' ),"gfx1151" ), 407 (re .compile (r'"gfx1103"|"gfx1150"' ),"gfx1103/gfx1150" ), 408 (re .compile (r"mj\s*==\s*8\s*&&\s*mn\s*==\s*6" ),"sm_86" ), 409 (re .compile (r"mj\s*==\s*6\s*&&\s*mn\s*==\s*0" ),"sm_60" ), 410 (re .compile (r"mj\s*==\s*12\s*&&\s*mn\s*==\s*1" ),"sm_121" ), 411 (re .compile (r"nv_kq_default_env|cc_major_of\(min_major\)" ),"NVIDIA cc>=8" ), 412) 413 414 415def scan_engine_defaults (names ): 416"""Entries of the engine's own default tables: {"STRATA_X", "v"} / push_back({"STRATA_X", "v"}). The engine applies them for a GPU 417architecture when the person has not set the name. "arch" is the nearest architecture test above the entry (a label, to be checked 418by eye; "windows" is added when a Windows-only test sits between that test and the entry).""" 419out = collections .defaultdict (list ) 420for rel in DEFAULT_TABLE_FILES : 421p = ROOT / rel 422lines = _read_lines (p ) 423for i ,l in enumerate (lines ): 424for m in re .finditer (r'\{\s*"(STRATA_[A-Z0-9_]+)"\s*,\s*"([^"]*)"\s*\}' ,l ): 425if m .group (1 )not in names : 426continue 427label ,win = "" ,False 428for k in range (i ,max (- 1 ,i - 80 ),- 1 ): 429if re .search (r"\bwin\s*&&|\bwindows\b\s*(?:&&|\))|!windows" ,lines [k ])and not label : 430win = True 431hit = next ((lab for rx ,lab in _ARCH_LABELS if rx .search (lines [k ])),None ) 432if hit : 433label = hit 434break 435if lines [k ].startswith (("std::vector" ,"bool " ,"void " ))and k != i : 436break 437out [m .group (1 )].append ({"file" :rel ,"line" :i + 1 ,"value" :m .group (2 ),"arch" : (label + (" (Windows)" if win and label else "" ))or "?" }) 438return out 439 440 441# ---------------------------------------------------------------- docs 442 443def scan_docs (names ): 444out = collections .defaultdict (list ) 445for p in _files (DOC_PATHS , (".md" ,)): 446rel = _rel (p ) 447if rel == SETTINGS_PAGE :# the generated page lists the names itself; it is not a source of documentation 448continue 449for i ,l in enumerate (_read_lines (p )): 450if "STRATA_" not in l : 451continue 452for nm in set (re .findall (r"STRATA_[A-Z0-9_]+(?![A-Z0-9_])" ,l )): 453if nm in names : 454out [nm ].append (f" { rel } : { i + 1 } " ) 455return out 456 457 458# ---------------------------------------------------------------- git history 459 460def _git (* args ): 461return subprocess .run (["git" ,"-C" ,str (ROOT ),* args ],capture_output = True ,text = True ,encoding = "utf-8" ,errors = "replace" ).stdout 462 463 464def _tag_of_commits (): 465"""{commit: first release tag that contains it}, from the release tags in date order.""" 466tags = [t for t in _git ("tag" ,"--sort=creatordate" ).split ()if re .fullmatch (r"v\d+\.\d+\.\d+(\.\d+)?" ,t )] 467seen = set () 468first = {} 469for t in tags : 470revs = _git ("rev-list" ,t ).split () 471for c in revs : 472if c not in seen : 473seen .add (c ) 474first [c ]= t 475return first 476 477 478def scan_git (names ): 479"""first and last commit that adds or removes a line holding the name, in the engine directories.""" 480out = _git ("log" ,"--reverse" ,"--no-color" ,"-U0" ,"--format=@@C %H %cs" ,"-G" ,"STRATA_[A-Z0-9_]+" ,"-p" ,"--" ,* ENGINE_DIRS ) 481tagmap = _tag_of_commits () 482first ,last = {}, {} 483cur = None 484for line in out .split ("\n" ): 485if line .startswith ("@@C " ): 486_ ,h ,d = line .split (" " ,2 ) 487cur = (h ,d ) 488continue 489if cur is None or not line or line [0 ]not in "+-" or line .startswith (("+++" ,"---" )): 490continue 491for nm in set (NAME_RE .findall (line )): 492if nm in names : 493if line [0 ]== "+" and nm not in first : 494first [nm ]= cur 495last [nm ]= cur 496res = {} 497for nm in names : 498f ,l = first .get (nm ),last .get (nm ) 499res [nm ]= { 500"first_commit" :f [0 ][:10 ]if f else None ,"first_date" :f [1 ]if f else None ,"since" :tagmap .get (f [0 ])if f else None , 501"last_commit" :l [0 ][:10 ]if l else None ,"last_date" :l [1 ]if l else None , 502 } 503return res 504 505 506 507# ---------------------------------------------------------------- the settings page (docs/SETTINGS.md) 508 509_BACKEND_WORDS = {"cuda-hip" :"NVIDIA and AMD" ,"cuda" :"NVIDIA" ,"hip" :"AMD" ,"sycl" :"Intel Arc" ,"metal" :"Mac" ,"cpu" :"CPU" } 510 511 512def _where (e ): 513have = set (e ["backends" ]) 514if "cuda-hip" in have : 515have -= {"cuda" ,"hip" } 516words = [_BACKEND_WORDS [b ]for b in ("cuda-hip" ,"cuda" ,"hip" ,"sycl" ,"metal" ,"cpu" )if b in have ] 517return ", " .join (words ) 518 519 520def _kind (e ): 521return {"flag" :"on / off" ,"int" :"number" ,"float" :"number" ,"string" :"text" ,"debug-gated" :"on / off" }.get (e ["parse" ],e ["parse" ]) 522 523 524def _doc_links (e ,limit = 3 ): 525seen ,out = set (), [] 526for m in e ["doc_mentions" ]: 527f = m .rsplit (":" ,1 )[0 ] 528if f in seen or f .startswith (("docs/work" ,"docs/paper" )): 529continue 530seen .add (f ) 531out .append (f"[ { os . path . basename ( f ) } ]( { os . path . relpath ( f , 'docs' ). replace ( os . sep , '/' ) if f . startswith ( 'docs/' ) else '../' + f } )" ) 532if len (out )== limit : 533break 534return ", " .join (out )or "-" 535 536 537def render_page (entries ): 538optin = [e for e in entries if e .get ("status" )== "opt-in" ] 539roll = [e for e in entries if e .get ("status" )== "rollback" ] 540out = [ 541"# Engine settings" , 542"" , 543"<!-- Generated from data/settings-register.json by tools/settings_register.py --docs. Do not edit by hand; change the register. -->" , 544"" , 545"The engine reads its settings from environment variables whose names start with `STRATA_`. The Terminal and the app choose what" , 546"your hardware needs, so most people never set one. This page lists the ones meant for people: switches that are off until you" , 547"turn them on, and switches that take a newer default back to the earlier behaviour. The other settings are for measuring and" , 548"debugging and are kept in `data/settings-register.json`." , 549"" , 550"A number or a word is set like any environment variable, for example `STRATA_KVA=1`. In the Terminal, `strata launch --set NAME=value`" , 551"puts it in the model's run configuration." , 552"" , 553f"## Switches you can turn on ( { len ( optin ) } )" , 554"" , 555"Off unless you set them. The last column says where each one is described." , 556"" , 557"| Setting | Value | Applies to | Described in |" , 558"|---|---|---|---|" , 559 ] 560for e in optin : 561out .append (f"| ` { e [ 'name' ] } ` | { _kind ( e ) } | { _where ( e ) } | { _doc_links ( e ) } |" ) 562out += [ 563"" , 564f"## Switches that go back to earlier behaviour ( { len ( roll ) } )" , 565"" , 566"These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which" , 567"version made it the default." , 568"" , 569"| Setting | Value | Applies to | Named in the engine since | Described in |" , 570"|---|---|---|---|---|" , 571 ] 572for e in roll : 573out .append (f"| ` { e [ 'name' ] } ` | { _kind ( e ) } | { _where ( e ) } | { e . get ( 'since' ) or '-' } | { _doc_links ( e ) } |" ) 574out .append ("" ) 575return "\n" .join (out ) 576 577 578# ---------------------------------------------------------------- build 579 580def engine_names ()-> set [str ]: 581reads ,_ = scan_engine () 582return set (reads ) 583 584 585def _merge_parse (sites ): 586kinds = [s ["parse" ]for s in sites ] 587kind = next ((k for k in ("int" ,"float" ,"flag" ,"string" ,"debug-gated" )if k in kinds ),"string" ) 588if len (set (kinds ))> 1 : 589kind = collections .Counter (kinds ).most_common (1 )[0 ][0 ] 590states = [s ["default_state" ]for s in sites if s ["default_state" ]] 591dstate = collections .Counter (states ).most_common (1 )[0 ][0 ]if states else None 592dflts = [s ["code_default" ]for s in sites if s ["code_default" ]and s ["parse" ]in ("int" ,"float" )] 593dflt = collections .Counter (dflts ).most_common (1 )[0 ][0 ]if dflts else None 594return kind ,dstate ,dflt 595 596 597def build (with_git = True ): 598reads ,esets = scan_engine () 599names = set (reads ) 600lsets ,lreads ,lnamed = scan_launch (names ) 601edefs = scan_engine_defaults (names ) 602docs = scan_docs (names ) 603git = scan_git (names )if with_git else {} 604old = {} 605if REGISTER .exists (): 606try : 607old = {e ["name" ]:e for e in json .loads (REGISTER .read_text (encoding = "utf-8" ))["settings" ]} 608except (OSError ,ValueError ,KeyError ): 609old = {} 610entries = [] 611for nm in sorted (names ): 612sites = reads [nm ] 613kind ,dstate ,dflt = _merge_parse (sites ) 614backends = sorted ({s ["backend" ]for s in sites }) 615e = { 616"name" :nm , 617"backends" :backends , 618"reads" : [{"file" :s ["file" ],"line" :s ["line" ],"backend" :s ["backend" ],"fn" :s ["fn" ]}for s in sites ], 619"parse" :kind , 620"default_state" :dstate , 621"code_default" :dflt , 622"engine_sets" :esets .get (nm , []), 623"engine_defaults" :edefs .get (nm , []), 624"launch_files" :sorted (lnamed .get (nm , [])), 625"launch_sets" :lsets .get (nm , []), 626"launch_reads" :lreads .get (nm , []), 627"doc_mentions" :docs .get (nm , []), 628 } 629if with_git : 630e .update (git .get (nm , {})) 631elif nm in old : 632for k in ("first_commit" ,"first_date" ,"since" ,"last_commit" ,"last_date" ): 633if k in old [nm ]: 634e [k ]= old [nm ][k ] 635for k in HAND_FIELDS : 636e [k ]= old .get (nm , {}).get (k ,"" ) 637entries .append (e ) 638# entries that the engine no longer reads but were retired on purpose stay (status "retired" with retired_in) 639for nm ,o in sorted (old .items ()): 640if nm not in names and o .get ("status" )== "retired" and o .get ("retired_in" ): 641entries .append (o ) 642entries .sort (key = lambda e :e ["name" ]) 643return {"version" :1 ,"scanned" :list (ENGINE_DIRS ),"launch" :list (LAUNCH_PATHS ),"statuses" :list (STATUSES ),"settings" :entries } 644 645 646def write (doc ): 647REGISTER .parent .mkdir (parents = True ,exist_ok = True ) 648REGISTER .write_text (json .dumps (doc ,indent = 1 ,ensure_ascii = False )+ "\n" ,encoding = "utf-8" ,newline = "\n" ) 649 650 651def main (argv = None ): 652ap = argparse .ArgumentParser (description = __doc__ .split ("\n" )[0 ]) 653ap .add_argument ("--check" ,action = "store_true" ) 654ap .add_argument ("--names" ,action = "store_true" ) 655ap .add_argument ("--no-git" ,action = "store_true" ) 656ap .add_argument ("--docs" ,action = "store_true" ,help = "write docs/SETTINGS.md from the register (opt-in and rollback entries)" ) 657a = ap .parse_args (argv ) 658if a .names : 659"\n" .join (sorted (engine_names ()))) 660return 0 661if a .check : 662have = engine_names () 663entries = json .loads (REGISTER .read_text (encoding = "utf-8" ))["settings" ] 664reg = {e ["name" ]for e in entries } 665retired = {e ["name" ]for e in entries if e .get ("status" )== "retired" and e .get ("retired_in" )}# kept on purpose: not read any more 666missing ,extra = sorted (have - reg ),sorted (reg - have - retired ) 667for n in missing : 668"not in the register:" ,n ) 669for n in extra : 670"in the register, not read by the engine:" ,n ) 671return 1 if (missing or extra )else 0 672if a .docs : 673entries = json .loads (REGISTER .read_text (encoding = "utf-8" ))["settings" ] 674 (ROOT / SETTINGS_PAGE ).write_text (render_page (entries ),encoding = "utf-8" ,newline = "\n" ) 675f"wrote { ROOT / SETTINGS_PAGE } " ) 676return 0 677doc = build (with_git =not a .no_git ) 678write (doc ) 679f"wrote { REGISTER } with { len ( doc [ 'settings' ]) } settings" ) 680return 0 681 682 683if __name__ == "__main__" : 684sys .exit (main ())