Files

80 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Replace named .entry blocks of a sealed PTX with the same entries compiled from the modified .cu.
Why a splice and not a re-seal: three of the sealed files were built with CUDA 13.0.88 (no such toolkit is installed), and every
file's anonymous-namespace entry names embed a hash of the compile command, so a fresh full compile renames entries the Rust side
looks up and may reorder unrelated kernels. Only the q8_1 quantizer entries change here; every other byte of the sealed file stays.
The replaced entry is renamed to the sealed entry's name (all occurrences inside the block), its parameter list must equal the old
one, and it may not reference anything outside itself (no call, no global/const symbol).
splice_ptx.py OLD.ptx NEW.ptx OUT.ptx ENTRY [ENTRY ...]
ENTRY = NAME the same exported name in both files
| suffix:TAIL the entry whose name ends with TAIL in each file (the hashed anonymous-namespace names)
OUT keeps the trailing NUL of OLD (the sealed files end with one) and the header (.version/.target) of OLD.
"""
import re
import sys
def blocks(text):
out = {}
for m in re.finditer(r'^(?:\.visible )?\.entry (\S+?)\(', text, re.M):
name = m.group(1)
end = text.index('\n}\n', m.start()) + 3
out[name] = (m.start(), end)
return out
def params(block):
head = block[: block.index('\n{')]
return re.findall(r'\.param \.(\w+)(?: \.ptr[^ ]*)?(?: \.align \d+)? (\S+?)[,\s)]', head)
def main(argv):
if len(argv) < 5:
print(__doc__)
return 2
old_path, new_path, out_path, *entries = argv[1:]
old_raw = open(old_path, 'rb').read()
nul = old_raw.endswith(b'\0')
old = old_raw.rstrip(b'\0').decode('ascii')
new = open(new_path, 'rb').read().rstrip(b'\0').decode('ascii')
ob, nb = blocks(old), blocks(new)
for spec in entries:
if spec.startswith('suffix:'):
tail = spec[7:]
o = [n for n in ob if n.endswith(tail)]
n_ = [n for n in nb if n.endswith(tail)]
if len(o) != 1 or len(n_) != 1:
raise SystemExit(f'{spec}: {len(o)} entries in the sealed file, {len(n_)} in the new one (want 1 and 1)')
old_name, new_name = o[0], n_[0]
else:
old_name = new_name = spec
if old_name not in ob or new_name not in nb:
raise SystemExit(f'{spec}: missing in the {"sealed" if old_name not in ob else "new"} file')
a, b = nb[new_name]
block = new[a:b]
if new_name != old_name:
block = block.replace(new_name, old_name)
# the new text must stand alone
body = block[block.index('\n{'):]
for pattern in (r'\bcall\b', r'\.func\b', r'^\s*\.(?:global|const|extern)\b', r'generic\(', r'\bmov\.u64\s+%rd\d+,\s*[A-Za-z_$]'):
if re.search(pattern, body, re.M):
raise SystemExit(f'{spec}: the new entry references outside itself ({pattern!r})')
oa, obnd = ob[old_name]
old_block = old[oa:obnd]
pn, po = [p[0] for p in params(block)], [p[0] for p in params(old_block)]
if pn != po:
raise SystemExit(f'{spec}: parameter types differ: sealed {po}, new {pn}')
launch = lambda t: re.findall(r'^\.(?:maxntid|minnctapersm|reqntid|maxnreg)[^\n]*', t[: t.index('\n{')], re.M)
if launch(block) != launch(old_block):
raise SystemExit(f'{spec}: launch bounds differ: sealed {launch(old_block)}, new {launch(block)}')
old = old[:oa] + block + old[obnd:]
ob = blocks(old)
print(f'{old_name[:90]}: {obnd - oa} -> {len(block)} bytes')
open(out_path, 'wb').write(old.encode('ascii') + (b'\0' if nul else b''))
if __name__ == '__main__':
sys.exit(main(sys.argv))