okami.mom/strata

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

Niko1221rc1 merge ple128 (78316c8df)79a5ad042

main
7.1 KiB175 linesraw
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."""
29    out = []
30    i, n = 0, len(text)
31    while i < n:
32        c = text[i]
33        if text.startswith("//", i):
34            j = text.find("\n", i)
35            j = n if j < 0 else j
36            out.append(" " * (j - i))
37            i = j
38        elif text.startswith("/*", i):
39            j = text.find("*/", i + 2)
40            j = n if j < 0 else j + 2
41            out.append("".join(ch if ch == "\n" else " " for ch in text[i:j]))
42            i = j
43        elif c == '"' or c == "'":
44            j = i + 1
45            while j < n and text[j] != c:
46                j += 2 if text[j] == "\\" else 1
47            j = min(j + 1, n)
48            out.append("".join(ch if ch == "\n" else " " for ch in text[i:j]))
49            i = j
50        else:
51            out.append(c)
52            i += 1
53    return "".join(out)
54
55
56def _body_end(code: str, open_brace: int) -> int:
57    depth = 0
58    for k in range(open_brace, len(code)):
59        if code[k] == "{":
60            depth += 1
61        elif code[k] == "}":
62            depth -= 1
63            if depth == 0:
64                return k
65    return 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."""
70    code = _strip(text)
71    lines = text.splitlines()
72    bad: list[tuple[int, str]] = []
73    spans: list[tuple[int, int, str]] = []
74    for m in STATIC_LAMBDA.finditer(code):
75        o = m.end() - 1
76        spans.append((o, _body_end(code, o), "a function-local static initialised by a lambda"))
77    for m in CALL_ONCE.finditer(code):
78        o = code.find("{", m.end())
79        if o >= 0:
80            spans.append((o, _body_end(code, o), "std::call_once"))
81    for c in CALL.finditer(code):
82        line = text.count("\n", 0, c.start()) + 1
83        ctx = " ".join(lines[max(0, line - 2):line])
84        if "attr-scope: process" in ctx:
85            continue
86        for lo, hi, why in spans:
87            if lo < c.start() < hi:
88                bad.append((line, why))
89                break
90    return bad
91
92
93def scan() -> list[str]:
94    found = []
95    for d in SCAN_DIRS:
96        base = ROOT / d
97        if not base.exists():
98            continue
99        for p in sorted(base.rglob("*")):
100            if p.suffix in SUFFIXES and p.is_file():
101                try:
102                    text = p.read_text(encoding="utf-8", errors="replace")
103                except OSError:
104                    continue
105                if not CALL.search(text):
106                    continue
107                for line, why in find_violations(text):
108                    found.append(f"{p.relative_to(ROOT).as_posix()}:{line}: cudaFuncSetAttribute inside {why} (per PROCESS, but the attribute is per DEVICE)")
109    return found
110
111
112def test_the_tree_has_no_process_wide_attribute_setup():
113    assert 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) {
120    constexpr size_t sm = (size_t) K * N * sizeof(float);
121    static const bool once = [] {
122        cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, 1, PF>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm);
123        return true;
124    }();
125    (void) once;
126}
127"""
128OLD_RB = """
129static void f(cudaStream_t st) {
130    static const bool once = []() -> bool {
131        cudaFuncSetAttribute(k, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
132        return 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) {
147    static std::mutex mu; int dev = 0; cudaGetDevice(&dev);
148    std::lock_guard<std::mutex> lk(mu);
149    if (!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)
156    static 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():
166    assert find_violations(OLD_PF), "the gr_down_pf_launch form must be flagged"
167    assert find_violations(OLD_RB), "a lambda with a trailing return type must be flagged"
168    assert find_violations(CALL_ONCE_SAMPLE), "std::call_once must be flagged"
169
170
171def test_detector_keeps_the_allowed_forms():
172    assert find_violations(PER_DEVICE_OK) == []
173    assert find_violations(HELPER_OK) == []
174    assert find_violations(MARKED_OK) == []
175    assert find_violations(COMMENT_ONLY) == []