Files
leleka/scripts/q8/splice_ptx.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 4654f01b15 q8_1 scale and sum stay finite in the sealed quantizers (plan 1.1; upstream 2b726ba6, f6601bf8, 7a0e3023, e372d4ff)
A q8_1 block stores d = amax / 127 and the sum of its 32 activations as fp16: one massive activation (amax > 8.3 M, or a sum past 65504)
rounded to inf and the dot products then read inf * 0 = NaN (NonFiniteMmqOutput here, "!!!!" upstream). The quantizers now clamp both
to the largest finite half and keep the codes inside int8 (strata/kernels/q8_1_finite.hpp); a NaN input still gives a NaN sum.
Finite blocks are stored bit for bit as before.

Sites: head_quant (mtp_original_full_head_native, native_head_native), mtp_original_quantize (mtp_original_tail, mtp_original_full_checks),
quantize_q8_1_kernel (mtp_original_full_head_iq, native_head_iq: the routed experts' input and SwiGLU output) and the opt-in chain
swiglu+quantize (chain_window). Not taken: the MMQ prompt quantizers (ggml quantize_mmq_q8_1, mtp_prefill_q8), which upstream did not clamp.

The sealed PTX are patched entry by entry (scripts/q8): three were built with CUDA 13.0.88, which is not installed, and a recompile
renames the hashed anonymous-namespace entries; only the quantizer entries change, every other byte is the sealed one. Pins, the seal
plan digests and the sm_86 companions (sm86_assets.py build) follow. tools/q8-probe compares old and new PTX on the GPU.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-26 18:27:20 +01:00

80 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""Replace named .entry blocks of a sealed PTX with the same entries compiled from the modified .cu (docs/upstream-port-plan.md row 1.1).
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))