okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
79a5ad042
main
1"""cudaFuncSetAttribute / hipFuncSetAttribute must never run inside a once-per-PROCESS initializer. 2 3The dynamic shared memory opt-in (cudaFuncAttributeMaxDynamicSharedMemorySize) and the carveout belong to the DEVICE, not to the process. A layer split or a 4tensor-parallel run launches the same kernel on several cards; a function-local `static const bool once = [] { cudaFuncSetAttribute(...); return true; }();` 5(or a std::call_once) sets it on the first card that gets there and leaves the others at the 48 KB default: the second card's launch fails with "invalid 6argument", and inside a CUDA graph capture that shows up as "operation failed due to a previous error during capture" (the int3 line, 2 x RTX PRO 6000, 0 tokens). 7 8Allowed: a per-device flag (`static bool done[64]; ... done[dev]`), a per-device table, or calling it on every launch. A site that really is process-wide 9(a single-device tool) can say so with a comment `// attr-scope: process` on the line of the call or the line before it. 10 11Run: python -m pytest tools/test_func_attr_scope.py (CPU only, reads src/ and include/) 12""" 13from __future__import annotations 14 15import re 16from pathlib import Path 17 18ROOT = Path (__file__ ).resolve ().parents [1 ] 19CALL = re .compile (r"\b(?:cuda|hip)FuncSetAttribute\s*\(" ) 20# a function-local static initialised by an immediately invoked lambda: `static [const] <type> name = [..](..) [-> T] {` 21STATIC_LAMBDA = re .compile (r"\bstatic\s+(?:const\s+|constexpr\s+)?(?:\w+(?:::\w+)*)\s+\w+\s*=\s*\[[^\]]*\]\s*(?:\([^)]*\))?\s*(?:->\s*[\w:<>\s*&]+)?\s*\{" ) 22CALL_ONCE = re .compile (r"\bstd::call_once\s*\(" ) 23SCAN_DIRS = ("src" ,"include" ) 24SUFFIXES = {".cu" ,".cuh" ,".cpp" ,".hpp" ,".h" ,".cc" } 25 26 27def _strip (text :str )-> str : 28"""Comments and string literals blanked out (same length), so braces inside them do not count.""" 29out = [] 30i ,n = 0 ,len (text ) 31while i < n : 32c = text [i ] 33if text .startswith ("//" ,i ): 34j = text .find ("\n" ,i ) 35j = n if j < 0 else j 36out .append (" " * (j - i )) 37i = j 38elif text .startswith ("/*" ,i ): 39j = text .find ("*/" ,i + 2 ) 40j = n if j < 0 else j + 2 41out .append ("" .join (ch if ch == "\n" else " " for ch in text [i :j ])) 42i = j 43elif c == '"' or c == "'" : 44j = i + 1 45while j < n and text [j ]!= c : 46j += 2 if text [j ]== "\\" else 1 47j = min (j + 1 ,n ) 48out .append ("" .join (ch if ch == "\n" else " " for ch in text [i :j ])) 49i = j 50else : 51out .append (c ) 52i += 1 53return "" .join (out ) 54 55 56def _body_end (code :str ,open_brace :int )-> int : 57depth = 0 58for k in range (open_brace ,len (code )): 59if code [k ]== "{" : 60depth += 1 61elif code [k ]== "}" : 62depth -= 1 63if depth == 0 : 64return k 65return len (code ) 66 67 68def find_violations (text :str )-> list [tuple [int ,str ]]: 69"""[(line, why)] for every attribute call inside a once-per-process initializer.""" 70code = _strip (text ) 71lines = text .splitlines () 72bad :list [tuple [int ,str ]]= [] 73spans :list [tuple [int ,int ,str ]]= [] 74for m in STATIC_LAMBDA .finditer (code ): 75o = m .end ()- 1 76spans .append ((o ,_body_end (code ,o ),"a function-local static initialised by a lambda" )) 77for m in CALL_ONCE .finditer (code ): 78o = code .find ("{" ,m .end ()) 79if o >= 0 : 80spans .append ((o ,_body_end (code ,o ),"std::call_once" )) 81for c in CALL .finditer (code ): 82line = text .count ("\n" ,0 ,c .start ())+ 1 83ctx = " " .join (lines [max (0 ,line - 2 ):line ]) 84if "attr-scope: process" in ctx : 85continue 86for lo ,hi ,why in spans : 87if lo < c .start ()< hi : 88bad .append ((line ,why )) 89break 90return bad 91 92 93def scan ()-> list [str ]: 94found = [] 95for d in SCAN_DIRS : 96base = ROOT / d 97if not base .exists (): 98continue 99for p in sorted (base .rglob ("*" )): 100if p .suffix in SUFFIXES and p .is_file (): 101try : 102text = p .read_text (encoding = "utf-8" ,errors = "replace" ) 103except OSError : 104continue 105if not CALL .search (text ): 106continue 107for line ,why in find_violations (text ): 108found .append (f" { p . relative_to ( ROOT ). as_posix () } : { line } : cudaFuncSetAttribute inside { why } (per PROCESS, but the attribute is per DEVICE)" ) 109return found 110 111 112def test_the_tree_has_no_process_wide_attribute_setup (): 113assert scan ()== [] 114 115 116# ---- the detector itself: the two sites that failed on two RTX PRO 6000 cards, and the forms that must stay allowed 117OLD_PF = """ 118template <int K, int PF> 119static void gr_down_pf_launch(const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 120constexpr size_t sm = (size_t) K * N * sizeof(float); 121static const bool once = [] { 122cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, 1, PF>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm); 123return true; 124}(); 125(void) once; 126} 127""" 128OLD_RB = """ 129static void f(cudaStream_t st) { 130static const bool once = []() -> bool { 131cudaFuncSetAttribute(k, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 132return true; 133}(); 134} 135""" 136CALL_ONCE_SAMPLE = """ 137void g() { static std::once_flag f; std::call_once(f, [] { cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, 65536); }); } 138""" 139PER_DEVICE_OK = """ 140static bool attrs[64] = {}; 141int dev = 0; cudaGetDevice(&dev); 142if (!attrs[dev]) { cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, 65536); attrs[dev] = true; } 143static const bool env = [] { const char* e = getenv("X"); return e != nullptr; }(); // a once-lambda without the call is fine 144""" 145HELPER_OK = """ 146template <class F> static void set_attr_once_per_device(bool (&done)[64], F&& set) { 147static std::mutex mu; int dev = 0; cudaGetDevice(&dev); 148std::lock_guard<std::mutex> lk(mu); 149if (!done[dev]) { set(); done[dev] = true; } 150} 151static void h() { static bool done[64] = {}; set_attr_once_per_device(done, [] { cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, 65536); }); } 152""" 153MARKED_OK = """ 154static void tool() { 155// attr-scope: process (a single-device test tool) 156static const bool once = [] { cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, 65536); return true; }(); 157} 158""" 159COMMENT_ONLY = """ 160// static const bool once = [] { cudaFuncSetAttribute(k, a, 1); return true; }(); 161const char* s = "static const bool once = [] { cudaFuncSetAttribute(k, a, 1); return true; }();"; 162""" 163 164 165def test_detector_flags_the_failing_forms (): 166assert find_violations (OLD_PF ),"the gr_down_pf_launch form must be flagged" 167assert find_violations (OLD_RB ),"a lambda with a trailing return type must be flagged" 168assert find_violations (CALL_ONCE_SAMPLE ),"std::call_once must be flagged" 169 170 171def test_detector_keeps_the_allowed_forms (): 172assert find_violations (PER_DEVICE_OK )== [] 173assert find_violations (HELPER_OK )== [] 174assert find_violations (MARKED_OK )== [] 175assert find_violations (COMMENT_ONLY )== []