Files
leleka/scripts/cuda-stubs/check-cu.py
T

194 lines
8.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""Syntax / semantics check of the ported CUDA sources on a host without nvcc.
usage: scripts/cuda-stubs/check-cu.py [-j N] [-v] [--fast-math] [--keep DIR] [file.cu ...]
(no file: every crates/cuda-driver/src/*.cu except third_party)
Pipeline per file: clang++ -E (stub headers first on the include path, then the nvcc -I set of
scripts/build-original-verify-ptx.sh) -> every `asm volatile(...)` replaced by cuda_stub_asm(<operand exprs>)
(operand expressions stay type-checked, PTX text is not examined) -> clang++ -fsyntax-only -std=c++17.
Exit status 1 when any file fails. See cuda_stub.h for what a pass does and does not prove.
"""
import argparse, concurrent.futures, os, re, subprocess, sys, tempfile
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
STUBS = os.path.join(ROOT, 'scripts', 'cuda-stubs')
SRC = os.path.join(ROOT, 'crates', 'cuda-driver', 'src')
INCLUDES = [
STUBS,
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'),
os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-include'),
os.path.join(SRC, 'third_party', 'llamacpp', 'ggml-src'),
]
COMMON = ['-std=c++17', '-D__NVCC__=1', '-D__CUDACC_RELAXED_CONSTEXPR__=1', '-D__CUDACC_EXTENDED_LAMBDA__=1']
WARN = ['-Wall', '-Wno-unknown-pragmas', '-Wno-unused-function', '-Wno-unused-variable', '-Wno-unused-but-set-variable',
'-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-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):
q = s[i]; i += 1
while i < len(s):
if s[i] == '\\': i += 2; continue
if s[i] == q: return i + 1
i += 1
return i
def match_paren(s, i):
"""s[i] == '(' ; return index after the matching ')'."""
depth = 0
while i < len(s):
c = s[i]
if c in '"\'': i = scan_string(s, i); continue
if c == '(': depth += 1
elif c == ')':
depth -= 1
if depth == 0: return i + 1
i += 1
raise ValueError('unbalanced asm')
def split_top(body, sep):
parts, depth, cur, i = [], 0, [], 0
while i < len(body):
c = body[i]
if c in '"\'':
j = scan_string(body, i); cur.append(body[i:j]); i = j; continue
if c in '([{': depth += 1
elif c in ')]}': depth -= 1
if c == sep and depth == 0 and not (sep == ':' and (body[i + 1:i + 2] == ':' or body[i - 1:i] == ':')):
parts.append(''.join(cur)); cur = []
else:
cur.append(c)
i += 1
parts.append(''.join(cur))
return parts
OPERAND_RE = re.compile(r'(?:\[\s*\w+\s*\]\s*)?"[^"]*"\s*\(')
def operands(section):
out, i = [], 0
while True:
m = OPERAND_RE.search(section, i)
if not m: return out
end = match_paren(section, m.end() - 1)
out.append(section[m.end():end - 1])
i = end
def rewrite_asm(text):
out, pos = [], 0
while True:
m = ASM_RE.search(text, pos)
if not m:
out.append(text[pos:]); break
before = text[:m.start()].rstrip()
# only asm STATEMENTS: an asm label on a declaration (Darwin's __DARWIN_ALIAS) follows a declarator, never ; { } or a linemarker
if not (re.search(r'\bvolatile|__volatile__', m.group(0)) or before[-1:] in ('', ';', '{', '}') or re.search(r'^#.*$', before.split('\n')[-1])):
out.append(text[pos:m.end()]); pos = m.end(); continue
out.append(text[pos:m.start()])
end = match_paren(text, m.end() - 1)
body = text[m.end():end - 1]
parts = split_top(body, ':')
ops = []
for sec in parts[1:3]:
ops += operands(sec)
out.append('cuda_stub_asm(' + ', '.join('(' + o.replace('\n', ' ') + ')' for o in ops) + ')' + '\n' * body.count('\n'))
pos = end
return ''.join(out)
PRINTF_CALL = re.compile(r'(?<=[;{}):,(])(\s*)printf(\s*\()')
def rewrite_printf(text):
"""clang only lowers device printf when it compiles the device side; a host-only pass sees a call to a host function."""
return PRINTF_CALL.sub(r'\1cuda_stub_printf\2', text)
def rewrite_launches(text):
"""K<<<a, b, c, d>>>(args) -> (cuda_stub_cfg(a, b, c, d), K(args))"""
while True:
i = text.find('<<<')
if i < 0: return text
j = text.index('>>>', i)
cfg = text[i + 3:j]
k = i
while k > 0 and text[k - 1] in ' \t\n': k -= 1
end_name = k
if text[k - 1] == '>': # explicit template arguments
depth = 0
while k > 0:
k -= 1
if text[k] == '>': depth += 1
elif text[k] == '<':
depth -= 1
if depth == 0: break
while k > 0 and (text[k - 1].isalnum() or text[k - 1] in '_:'): k -= 1
name = text[k:end_name]
a = j + 3
while text[a] in ' \t\n': a += 1
b = match_paren(text, a)
text = text[:k] + '(cuda_stub_cfg(' + cfg.replace('\n', ' ') + '), ' + name + text[a:b] + ')' + text[b:]
SHARED_INIT_RE = re.compile(r'__shared__[^;{}()]*?\b\w+(?:\[[^\]]*\])*\s*=[^=]')
def lint(path):
"""nvcc rejects a __shared__ variable with an initializer; the stub cannot see that (it erases __shared__)."""
msgs = []
for n, line in enumerate(open(path, encoding='utf-8', errors='replace'), 1):
code = line.split('//')[0]
if SHARED_INIT_RE.search(code) and 'static_assert' not in code:
msgs.append(f'{path}:{n}: error: __shared__ variable with an initializer (nvcc: "initializer not allowed for __shared__ variable")')
return msgs
def check(path, fast_math, keep, cuda=True):
inc = []
for d in INCLUDES: inc += ['-I', d]
extra = ['-D__USE_FAST_MATH__=1'] if fast_math else []
lang = ['-x', 'cuda', '--cuda-host-only', '-nocudainc', '-nocudalib'] if cuda else ['-x', 'c++']
pre = subprocess.run(['clang++', '-E'] + lang + ['-include', 'cuda_runtime.h'] + COMMON + extra + inc + [path], capture_output=True, text=True)
if pre.returncode != 0:
return path, False, pre.stderr, 0
src = rewrite_asm(pre.stdout)
if cuda: src = rewrite_printf(src)
if not cuda: src = rewrite_launches(src)
fd, tmp = tempfile.mkstemp(suffix='.ii', dir=keep)
os.write(fd, src.encode()); os.close(fd)
try:
r = subprocess.run(['clang++', '-fsyntax-only'] + (['-x', 'cuda-cpp-output', '--cuda-host-only', '-nocudainc', '-nocudalib'] if cuda else ['-x', 'c++-cpp-output']) + COMMON + WARN + [tmp], capture_output=True, text=True)
finally:
if not keep: os.unlink(tmp)
nwarn = r.stderr.count('warning:')
lm = lint(path)
return path, r.returncode == 0 and not lm, r.stderr + '\n'.join(lm), nwarn
def main():
ap = argparse.ArgumentParser()
ap.add_argument('files', nargs='*')
ap.add_argument('-j', type=int, default=os.cpu_count() or 4)
ap.add_argument('-v', action='store_true', help='print diagnostics of passing files too')
ap.add_argument('--fast-math', action='store_true')
ap.add_argument('--plain', action='store_true', help='C++-only pass (qualifiers erased) instead of clang\'s CUDA frontend')
ap.add_argument('--keep', help='directory to keep the rewritten translation units in')
ap.add_argument('--max-errors', type=int, default=12)
a = ap.parse_args()
files = a.files or sorted(os.path.join(SRC, f) for f in os.listdir(SRC) if f.endswith('.cu'))
bad = 0
with concurrent.futures.ThreadPoolExecutor(a.j) as ex:
for path, ok, err, nwarn in ex.map(lambda p: check(os.path.abspath(p), a.fast_math, a.keep, not a.plain), files):
name = os.path.relpath(path, ROOT)
if ok:
print(f'ok {name}' + (f' ({nwarn} warnings)' if nwarn else ''))
if a.v and err: print(err)
else:
bad += 1
print(f'FAIL {name}')
errs = [l for l in err.splitlines() if 'error:' in l]
print('\n'.join(' ' + l for l in errs[:a.max_errors]) or err[:2000])
if len(errs) > a.max_errors: print(f' ... {len(errs) - a.max_errors} more errors')
print(f'{len(files) - bad}/{len(files)} files pass')
return 1 if bad else 0
if __name__ == '__main__':
sys.exit(main())