From c280730262e75176dce7870f97c58ede1ffb8ff0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 17:00:26 +0200 Subject: [PATCH] docs(cuda): flag-policy audit of every ported .cu against CMake (unsealed assets without a plan entry, sealed precise builds of fast-math Originals, corrected window re-seal candidates); add literal_diff.py Co-Authored-By: Claude Sonnet 5.5 --- docs/cuda-seal-plan-additions-window.json | 51 +++++- docs/cuda-seal-plan-additions.json | 114 +++++++++++- scripts/cuda-stubs/check-cu.py | 3 +- scripts/cuda-stubs/literal_diff.py | 205 ++++++++++++++++++++++ 4 files changed, 362 insertions(+), 11 deletions(-) create mode 100755 scripts/cuda-stubs/literal_diff.py diff --git a/docs/cuda-seal-plan-additions-window.json b/docs/cuda-seal-plan-additions-window.json index 9fe8c747..70591354 100644 --- a/docs/cuda-seal-plan-additions-window.json +++ b/docs/cuda-seal-plan-additions-window.json @@ -163,19 +163,19 @@ "note": "engine/strata/CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags of scripts/build-original-verify-ptx.sh (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.", "candidate_resealed_assets": [ { - "ptx": "mtp_original_full_head_native.ptx", - "derived_from": "native_mmvq / head_dispatch (quantize_q8_1 + MMVQ)" + "ptx": "mtp_original_full_head_native.ptx / mtp_original_tail.ptx / mtp_original_full_checks.ptx", + "derived_from": "native_mmvq (quantize_q8_1 + MMVQ)" }, { "ptx": "mtp_original_full_bf16.ptx", "derived_from": "native_bf16" }, { - "ptx": "mtp_original_full_router.ptx / mtp_original_full_router_legacy.ptx", + "ptx": "mtp_original_full_router.ptx", "derived_from": "native_router" }, { - "ptx": "mtp_original_full_gr_norm.ptx / mtp_original_full_gr_post.ptx / mtp_original_full_fused_gr.ptx", + "ptx": "mtp_original_full_gr_norm.ptx / mtp_original_full_gr_post.ptx", "derived_from": "native_gr_norm / native_gr_postops" }, { @@ -183,13 +183,48 @@ "derived_from": "native_moe" }, { - "ptx": "mtp_original_full_attention.ptx / qsa_decode_postops.ptx / qsa_prompt_postops.ptx / qsa_prompt_select.ptx", - "derived_from": "native_flash_attn / native_qsa / native_qsa_indexer / native_qsa_score" + "ptx": "mtp_original_full_qnorm.ptx / mtp_original_full_qsa_gate.ptx / qsa_native_gate.ptx", + "derived_from": "native_qsa" }, { - "ptx": "ple_native_batch.ptx", + "ptx": "qsa_decode_postops.ptx", + "derived_from": "native_qsa norm + native_rope" + }, + { + "ptx": "original_verify_qsa.ptx / qsa_prompt_indexer.ptx", + "derived_from": "native_qsa_indexer" + }, + { + "ptx": "ple_native_batch.ptx / ple_prompt_device.ptx", "derived_from": "native_ple_postops" + }, + { + "ptx": "mtp_original_prefill_mmq.ptx / mtp_original_prefill_fixup.ptx / mtp_original_prefill_quant.ptx", + "derived_from": "ggml mmq instances + quantize.cu, built by the Original's strata_mmq target with -use_fast_math" } - ] + ], + "not_candidates_original_is_precise": [ + { + "ptx": "mtp_original_full_attention.ptx", + "derived_from": "qsa_decode_attn.cu" + }, + { + "ptx": "qsa_prompt_postops.ptx", + "derived_from": "prefill/kernels.cu" + }, + { + "ptx": "qsa_prompt_select.ptx", + "derived_from": "qsa_select.cu (the Original verifier scores with qsa_select, not native_qsa_score)" + }, + { + "ptx": "mtp_original_full_router_legacy.ptx", + "derived_from": "router_top10.cu" + }, + { + "ptx": "mtp_original_full_fused_gr.ptx", + "derived_from": "fused_gr.cu" + } + ], + "correction": "The first version of this list named mtp_original_full_attention, qsa_prompt_postops, qsa_prompt_select, mtp_original_full_router_legacy and mtp_original_full_fused_gr; a function-level comparison against the Original shows those derive from sources that are NOT in the CMake fast-math list, and it missed the assets listed above." } } diff --git a/docs/cuda-seal-plan-additions.json b/docs/cuda-seal-plan-additions.json index 10484c0b..32cae81a 100644 --- a/docs/cuda-seal-plan-additions.json +++ b/docs/cuda-seal-plan-additions.json @@ -170,5 +170,117 @@ ], "note": "Not wired: s_gemv_legacy.rs plans geometry/admission; no Module owner yet. s2_gemv_fast's constant table is statically initialised in the source." } - ] + ], + "flags_policy_audit": { + "audited": "2026-10-14 with scripts/cuda-stubs/literal_diff.py (SOURCES=1) over every crates/cuda-driver/src/*.cu, against engine/strata/CMakeLists.txt", + "cmake_policy": { + "per_source_use_fast_math": [ + "native_mmvq", + "native_bf16", + "native_gr_norm", + "native_moe", + "native_gdn", + "native_gr_postops", + "native_router", + "native_gdn_preprocess", + "native_qsa", + "native_rope", + "native_ple_postops", + "native_flash_attn", + "native_qsa_indexer", + "native_qsa_score" + ], + "cmake_lines": "engine/strata/CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)", + "strata_mmq_extended_lambda_use_fast_math": [ + "src/prefill/moe_mmq.cu", + "src/prefill/ggml_cuda_host.cu", + "ggml-cuda/quantize.cu", + "ggml-cuda/template-instances/mmq-instance-*.cu" + ], + "everything_else": "default nvcc flags (no --use_fast_math); strata_next_kar* add CUDA_STANDARD 17 only" + }, + "unsealed_assets_without_an_entry_in_the_three_additions_files": [ + { + "cu": "mmq_original_group_swiglu.cu", + "original": "prefill/moe_mmq.cu swiglu_kernel / copy16_kernel", + "required": "--extended-lambda -use_fast_math (strata_mmq). swiglu_kernel computes g / (1 + __expf(-g)) * u, so the division is rcp.approx under fast math; a precise build is NOT the Original", + "entries": [ + "leleka_original_mmq_swiglu", + "leleka_original_mmq_gather", + "leleka_original_mmq_gu_finite" + ], + "note": "leleka_original_mmq_gu_finite is a port-side integer exponent scan, not an Original kernel" + }, + { + "cu": "mmq_original_group_mul.cu / mmq_original_group_fixup.cu / mmq_original_formats.cu / mmq_original_formats_fixup.cu", + "original": "ggml-cuda mmq.cuh instances (strata_mmq)", + "required": "-use_fast_math (the .cu headers already say so); 66 mul_mat_q + 66 stream-k fixup instantiations are exactly the (type,width) set of ffi.rs mmq_original_group_function" + }, + { + "cu": "mtp_original_scalar_gr.cu", + "original": "kernels/cuda/fused_gr.cu", + "required": "default (precise)" + }, + { + "cu": "mtp_original_scalar_norm.cu", + "original": "native_qsa.cu norm<1024> + native_rope.cu apply", + "required": "--use_fast_math" + }, + { + "cu": "mtp_original_session_native_rope.cu", + "original": "native_rope.cu apply", + "required": "--use_fast_math" + }, + { + "cu": "mtp_original_session_legacy_rope.cu", + "original": "rope.cu rope_neox_kernel", + "required": "default (precise)" + }, + { + "cu": "original_sampler.cu (= mtp_original_full_coupled.cu = native_head_sampler.cu text)", + "original": "kernels/cuda/sampler.cu", + "required": "default (precise)" + }, + { + "cu": "native_parity.cu", + "original": "iq_kernels.cu", + "required": "default (precise); test harness only" + }, + { + "cu": "native_head_native.cu / native_head_iq.cu / native_head_sampler.cu", + "original": "native_mmvq.cu / iq_kernels.cu / sampler.cu", + "required": "native_head_native: --use_fast_math (native_mmvq); the other two precise. These are byte/semantic twins of the sealed mtp_original_full_head_* sources and are not referenced by any Rust asset" + }, + { + "cu": "kar_decode_levels.cu", + "original": "none (gpu/kar/src/kar_expert.cu pairing; spec in crates/model-format/src/kar_kernel_model.rs)", + "required": "precise: --ftz=false --prec-div=true --prec-sqrt=true --fmad=true; the multiply uses explicit __fmul_rn/__fadd_rn" + } + ], + "sealed_assets_built_precise_whose_original_is_fast_math": [ + "mtp_original_tail (native_mmvq)", + "mtp_original_full_checks (native_mmvq)", + "mtp_original_full_head_native (native_mmvq)", + "mtp_original_full_bf16 (native_bf16)", + "mtp_original_full_router (native_router)", + "mtp_original_full_gr_norm (native_gr_norm)", + "mtp_original_full_gr_post (native_gr_postops)", + "mtp_original_full_combine (native_moe)", + "mtp_original_full_qnorm / mtp_original_full_qsa_gate / qsa_native_gate (native_qsa)", + "qsa_decode_postops (native_qsa norm + native_rope)", + "original_verify_qsa / qsa_prompt_indexer (native_qsa_indexer)", + "ple_native_batch / ple_prompt_device (native_ple_postops)", + "moe_route_top10 (native_router)", + "mtp_original_prefill_mmq / _fixup / _quant (strata_mmq -use_fast_math: the q8_1 quantizer divides)" + ], + "sealed_assets_whose_original_is_precise": [ + "mtp_original_full_attention (qsa_decode_attn)", + "qsa_prompt_postops (prefill/kernels.cu)", + "qsa_prompt_select (qsa_select.cu)", + "mtp_original_full_router_legacy (router_top10)", + "mtp_original_full_fused_gr (fused_gr)", + "mtp_original_full_s2 / mtp_original_full_shared / mtp_original_full_verify / mtp_original_full_element / mtp_original_full_gr_write / mtp_original_full_head_iq / mtp_original_full_head_sampler / mtp_original_full_coupled / mtp_original_full_quant80" + ], + "stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json and scripts/build-original-verify-ptx.sh pin 13.0.88" + } } diff --git a/scripts/cuda-stubs/check-cu.py b/scripts/cuda-stubs/check-cu.py index a1cedff4..f00e40b6 100755 --- a/scripts/cuda-stubs/check-cu.py +++ b/scripts/cuda-stubs/check-cu.py @@ -16,7 +16,6 @@ STUBS = os.path.join(ROOT, 'scripts', 'cuda-stubs') SRC = os.path.join(ROOT, 'crates', 'cuda-driver', 'src') INCLUDES = [ STUBS, - SRC, os.path.join(ROOT, 'engine', 'strata', 'include'), os.path.join(ROOT, 'engine', 'strata', 'third_party', 'ggml'), os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-cuda'), @@ -28,7 +27,7 @@ WARN = ['-Wall', '-Wno-unknown-pragmas', '-Wno-unused-function', '-Wno-unused-va '-Wno-unused-local-typedef', '-Wno-pass-failed', '-Wno-missing-braces', '-Wno-sign-compare', '-Wno-unused-value', '-Wno-unused-const-variable', '-Wno-deprecated-declarations', '-Wno-unknown-attributes', '-Wno-macro-redefined', '-Wno-pragma-once-outside-header', '-Wno-ignored-attributes', '-Wno-unused-lambda-capture', '-Wno-tautological-compare', - '-Wno-unused-parameter', '-Wno-sometimes-uninitialized', '-Wno-undefined-internal', '-Wno-uninitialized'] + '-Wno-unused-parameter', '-Wno-unused-command-line-argument', '-Wno-sometimes-uninitialized', '-Wno-undefined-internal', '-Wno-uninitialized'] ASM_RE = re.compile(r'\b(?:__asm__|__asm|asm)\b\s*(?:__volatile__|volatile)?\s*(?:goto\s*)?\(') def scan_string(s, i): diff --git a/scripts/cuda-stubs/literal_diff.py b/scripts/cuda-stubs/literal_diff.py new file mode 100755 index 00000000..478326c5 --- /dev/null +++ b/scripts/cuda-stubs/literal_diff.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Function-level literalness check of a ported .cu against the Original CUDA sources (engine/strata/src + include). + +usage: scripts/cuda-stubs/literal_diff.py crates/cuda-driver/src/.cu [-v] + SOURCES=1 ... print which Original files the matched functions come from (flag-policy audit) + RESID=n ... show n residual port lines that exist nowhere in the Original (default 60) + +Comments and whitespace are normalised away; each port function is matched to an Original function with an identical +body (LITERAL, possibly renamed), else to the closest one and the remaining diff is printed (DIFFERS). Wrappers +(extern "C" entries, baked template arguments) show up as DIFFERS and must be justified by hand.""" +# normalise a CUDA source: strip comments, collapse whitespace, one statement per line (prep for diff) +import re, sys +def norm(t): + t = re.sub(r'/\*.*?\*/', ' ', t, flags=re.S) + out = [] + for line in t.split('\n'): + # strip // comments (naive: not inside strings; sources have none with //) + i = line.find('//') + while i >= 0 and line[:i].count('"') % 2 == 1: + i = line.find('//', i + 1) + if i >= 0: line = line[:i] + out.append(line) + t = '\n'.join(out) + lines = [] + for line in t.split('\n'): + if line.lstrip().startswith('#'): + lines.append('\x00' + line.strip() + '\x00') + else: + lines.append(line) + t = '\n'.join(lines) + res = [] + for chunk in re.split(r'(\x00[^\x00]*\x00)', t): + if chunk.startswith('\x00'): + res.append('\n' + re.sub(r'\s+', ' ', chunk.strip('\x00')) + '\n') + else: + c = re.sub(r'\s+', ' ', chunk) + c = re.sub(r'\s*([;{}])\s*', r'\1\n', c) + c = re.sub(r'\s*,\s*', ', ', c) + res.append(c) + t = ''.join(res) + t = re.sub(r'\n+', '\n', t) + # drop trailing spaces + return '\n'.join(l.strip() for l in t.split('\n') if l.strip()) + '\n' + +"""Function-level literalness check of a port .cu against the Original corpus. +usage: fcmp.py port.cu [--orig file ...] [-v] (corpus default: engine/strata/src + include)""" +import re, sys, os, difflib, collections, glob, pickle, tempfile +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) + +def extract(text): + """-> list of (name, head, body, order) for every function definition in normalised text""" + funcs = [] + stack = [] # kinds + i = 0; n = len(text); head_start = 0 + pend = [] # indices of open braces with info + while i < n: + c = text[i] + if c == '"' or c == "'": + j = i + 1 + while j < n and text[j] != c: + j += 2 if text[j] == '\\' else 1 + i = j + 1; continue + if c == '\n' and text[head_start:i].lstrip().startswith('#'): + head_start = i + 1; i += 1; continue + if c in ';}': + if c == '}': + if stack: + kind, start, hd = stack.pop() + if kind == 'fn': + funcs.append((hd[0], hd[1], text[start:i + 1].strip())) + head_start = i + 1; i += 1; continue + if c == '{': + head = text[head_start:i].strip() + head = re.sub(r'(?m)^#.*$', '', head).strip() + if re.match(r'^(inline\s+)?namespace\b', head) or re.match(r'^extern\s+"C"$', head) or re.match(r'^(template\s*<.*?>\s*)?(typedef\s+)?(struct|class|union|enum)\b', head, re.S) or head.endswith('=') or head.endswith('='): + stack.append(('ns', i, None)) + elif '(' in head and re.search(r'\)\s*(const|noexcept|__restrict__)*\s*$', head) and all(k[0] == 'ns' for k in stack) and not re.match(r'^(if|for|while|switch|else|do)\b', head): + # function head: name = identifier before first '(' that is at paren depth 0 and not an attribute macro + m = re.search(r'([~\w:]+|operator\s*\(\s*\))\s*\(', re.sub(r'__launch_bounds__\s*\([^)]*\)', '', head)) + name = m.group(1) if m else '?' + params = head[head.find('(', m.end() - 1 if m else 0):] if m else head + stack.append(('fn', i, (name.split('::')[-1], head))) + else: + stack.append(('blk', i, None)) + head_start = i + 1; i += 1; continue + i += 1 + return funcs + +def load(path): + return extract(norm(open(path, encoding='utf-8', errors='replace').read())) + +def body_of(f): + name, head, full = f + return full[full.index('{'):] # body from first brace (head excluded, kept separately) + +def params_of(head, name): + k = head.find(name + '(') if name + '(' in head else head.find('(') + k2 = head.find('(', k) + d = 0; j = k2 + while j < len(head): + if head[j] == '(': d += 1 + elif head[j] == ')': + d -= 1 + if d == 0: break + j += 1 + return head[k2:j + 1], head[:k] + head[j + 1:] + +def corpus(): + cache = os.path.join(tempfile.gettempdir(), '_leleka_literal_corpus.pkl') + paths = [] + for base in ('engine/strata/src', 'engine/strata/include'): + for dp, dn, fn in os.walk(os.path.join(ROOT, base)): + for f in fn: + if f.endswith(('.cu', '.cuh', '.hpp', '.h', '.cpp')): paths.append(os.path.join(dp, f)) + paths.sort() + key = [(p, os.path.getmtime(p)) for p in paths] + if os.path.exists(cache): + k, data = pickle.load(open(cache, 'rb')) + if k == key: return data + data = [] + for p in paths: + for f in load(p): + data.append((os.path.relpath(p, ROOT), f)) + pickle.dump((key, data), open(cache, 'wb')) + return data + +def main(): + a = sys.argv[1:] + verbose = '-v' in a; a = [x for x in a if x != '-v'] + port = a[0] + data = corpus() + if '--orig' in a: + extra = a[a.index('--orig') + 1:] + data = [(os.path.relpath(p, ROOT), f) for p in [os.path.join(ROOT, e) for e in extra] for f in load(p)] + byname = collections.defaultdict(list); bybody = collections.defaultdict(list) + for src, f in data: + byname[f[0]].append((src, f)); bybody[re.sub(r'\s+', '', body_of(f))].append((src, f)) + res = [] + for f in load(os.path.join(ROOT, port) if not os.path.isabs(port) else port): + name, head, full = f + pb = body_of(f); pbn = re.sub(r'\s+', '', pb) + pp, ppre = params_of(head, name) + hit = bybody.get(pbn) + if hit: + same_params = [h for h in hit if re.sub(r'\s+', '', params_of(h[1][1], h[1][0])[0]) == re.sub(r'\s+', '', pp)] + if same_params: + s, o = same_params[0] + tag = 'LITERAL' if o[0] == name else 'LITERAL(renamed %s)' % o[0] + res.append((name, tag, s + ('' if len(hit) == 1 else ' +%d' % (len(hit) - 1)), None)); continue + s, o = hit[0] + res.append((name, 'BODY-LITERAL, PARAMS DIFFER from ' + o[0], s, '- ' + params_of(o[1], o[0])[0] + '\n+ ' + pp)); continue + # best candidate: same stripped name, else similarity + stem = re.sub(r'^(leleka_|original_|mtp_|native_head_)+', '', name) + cands = [c for c in byname.get(name, [])] or [c for k, v in byname.items() if k.endswith(stem) or stem.endswith(k) for c in v] + if not cands: + toks = set(re.findall(r'\w+', pb)) + sc = [] + for src, o in data: + ot = set(re.findall(r'\w+', body_of(o))) + if not ot: continue + j = len(toks & ot) / len(toks | ot) + sc.append((j, src, o)) + sc.sort(key=lambda x: -x[0]) + cands = [(s, o) for j, s, o in sc[:3] if j > 0.5] + best = None + for s, o in cands: + r = difflib.SequenceMatcher(None, body_of(o), pb, autojunk=False).quick_ratio() + if best is None or r > best[0]: best = (r, s, o) + if best is None: + res.append((name, 'NO-ORIGINAL-FOUND', '', None)); continue + r, s, o = best + # refine ratio on the best by line-diff + ol = body_of(o).split('\n'); pl = pb.split('\n') + d = list(difflib.unified_diff(ol, pl, 'orig:' + s + ':' + o[0], 'port:' + name, n=1, lineterm='')) + pd = params_of(o[1], o[0])[0] + if re.sub(r'\s+', '', pd) != re.sub(r'\s+', '', pp): + d = ['PARAMS:', '- ' + pd, '+ ' + pp] + d + res.append((name, 'DIFFERS from %s::%s' % (s, o[0]), s, '\n'.join(d))) + if os.environ.get('SOURCES'): + cnt = collections.Counter() + for name, tag, src, d in res: + if tag.startswith('LITERAL') or tag.startswith('BODY-LIT') or tag.startswith('DIFFERS'): + cnt[src.split(' +')[0]] += 1 + print(dict(cnt)); return + # residual: port lines outside the LITERAL functions that exist nowhere in the Original corpus + ptxt = norm(open(os.path.join(ROOT, port) if not os.path.isabs(port) else port, encoding='utf-8', errors='replace').read()) + for f in load(os.path.join(ROOT, port) if not os.path.isabs(port) else port): + if any(r[0] == f[0] and r[1].startswith('LITERAL') for r in res): + ptxt = ptxt.replace(f[2], '').replace(f[1], '') + allorig = set() + paths_all = [] + for base in ('engine/strata/src', 'engine/strata/include', 'engine/strata/third_party/ggml'): + for dp, dn, fn in os.walk(os.path.join(ROOT, base)): + for fnm in fn: + if fnm.endswith(('.cu', '.cuh', '.hpp', '.h', '.cpp')): paths_all.append(os.path.join(dp, fnm)) + for p in paths_all: + for l in norm(open(p, encoding='utf-8', errors='replace').read()).split('\n'): allorig.add(re.sub(r'\s+', '', l)) + resid = [l for l in ptxt.split('\n') if l.strip() and re.sub(r'\s+', '', l) not in allorig] + for name, tag, src, d in res: + print('%-60s %s [%s]' % (name, tag, src)) + if d and (verbose or tag.startswith('DIFFERS') or tag.startswith('BODY-LIT')): + print('\n'.join(' ' + l for l in d.split('\n')[:80])) + print('--- residual port lines not found anywhere in the Original (%d):' % len(resid)) + for l in resid[:int(os.environ.get('RESID', '60'))]: print(' | ' + l[:200]) +main()