Files
leleka/scripts/cuda-stubs/literal_diff.py
T

206 lines
9.9 KiB
Python
Executable File

#!/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/<file>.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()