interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / tools / ampere_nvdisasm.py

257 lines · 11648 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Verifier only: compare every decoded instruction/operand against the SM121
4reference, with the explicit documented target ABI/ISA spelling differences.
5NVIDIA output is ephemeral; no driver is loaded and no oracle listings committed.
6"""
7import argparse
8from concurrent.futures import ThreadPoolExecutor
9import os
10from pathlib import Path
11import re
12import struct
13import subprocess
14import tempfile
15
16
17def decode(exe, target, data):
18 with tempfile.NamedTemporaryFile(suffix=".bin") as f:
19 f.write(data)
20 f.flush()
21 result = subprocess.run([exe, "-b", target, "-hex", f.name], text=True,
22 stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
23 if result.returncode:
24 raise RuntimeError(f"nvdisasm {target} refused: {result.stderr.strip()}")
25 instructions = re.findall(r"/\*[0-9a-fA-F]+\*/\s+([^;\n]+);", result.stdout)
26 if len(instructions) * 16 != len(data):
27 raise RuntimeError(f"{target}: decoded instruction count does not cover entire buffer")
28 if re.search(r"INVALID|\.WORD|\?\?", "\n".join(instructions), re.I):
29 raise RuntimeError(f"{target}: invalid instruction or operand")
30 return instructions
31
32
33def normalize(text, target):
34 text = re.sub(r"\s+", " ", text.strip())
35 text = re.sub(r"desc\[UR(?:Z|\d+)\]", "", text)
36 text = text.replace("+URZ", "")
37 text = text.replace("LDCU", "ULDC")
38 if target == "SM121" and text.startswith("ULDC"):
39 # SM121's LDCU uses an explicit zero uniform base; SM86's ULDC
40 # encodes a direct cbank byte offset.
41 text = text.replace("[URZ+", "[").replace("[URZ]", "[0x0]")
42 if re.fullmatch(r"ULDC\.64 UR\d+, c\[0x0\]\[0x358\]", text):
43 # Reserved Blackwell descriptor load: not consumed on Ampere,
44 # whose shorter CB0 must not be read at this offset.
45 return "NOP"
46 if text.startswith("F2FP."):
47 text = text.replace(".F32", "")
48 if target == "SM121" and re.search(r"\b(?:LDC|ULDC)(?:\.| )", text):
49 def parameter(match):
50 offset = int(match[1], 16)
51 if offset >= 0x380:
52 offset = offset - 0x380 + 0x160
53 return f"c[0x0][0x{offset:x}]"
54 text = re.sub(r"c\[0x0\]\[0x([0-9a-f]+)\]", parameter, text)
55 return text
56
57
58def compare(exe, reference, actual, ops=()):
59 expected = [normalize(x, "SM121") for x in decode(exe, "SM121", reference)]
60 # Op21's IR contract is MMIO.GPU. Historical SM121 incorrectly emits EF;
61 # repair that legacy encoder separately, never treat the two as aliases.
62 # This target-specific expectation retains every register/address operand.
63 for i, op in enumerate(ops):
64 if op == 21:
65 expected[i] = re.sub(r"\bLDG\.E\.EF\b", "LDG.E.MMIO.GPU", expected[i])
66 if op == 14:
67 # SM86 omits the two discarded carry outputs; SM121 prints PT.
68 # Real predicate outputs are not removed and must still match.
69 expected[i] = expected[i].replace(", PT, PT,", ",", 1)
70 if op in (54, 55):
71 # SM86 BSSY/BSYNC are reconvergence-barrier operations. SM121's
72 # explicit RECONVERGENT qualifier is not an SM86 mnemonic;
73 # retain each barrier register, guard, and exact join address.
74 expected[i] = re.sub(r"\b(BSSY|BSYNC)\.RECONVERGENT\b", r"\1", expected[i])
75 observed = [normalize(x, "SM86") for x in decode(exe, "SM86", actual)]
76 if expected != observed:
77 for i, (a, b) in enumerate(zip(expected, observed)):
78 if a != b:
79 raise RuntimeError(f"instruction {i}: expected {a!r}, observed {b!r}")
80 raise RuntimeError("decoded lengths differ")
81 return observed
82
83
84def main():
85 parser = argparse.ArgumentParser()
86 parser.add_argument("corpus", type=Path)
87 parser.add_argument("--nvdisasm", default=os.environ.get("NVDISASM", "/usr/local/cuda/bin/nvdisasm"))
88 args = parser.parse_args()
89 pairs = sorted(args.corpus.glob("*.sm86.bin"))
90 if not pairs:
91 raise RuntimeError("empty SM86 corpus")
92 coverage = set()
93 mutation = None
94 uniform_dst_mutation = None
95 mmio_mutation = None
96 subtraction_mutation = None
97 branch_mutation = None
98 reconvergence_mutation = None
99 sync_barrier_mutation = None
100 carry_mutation = None
101 mismatches = []
102 # compare() is a pure function of (reference, code, ops); kernels that several producers
103 # emit identically are decoded once, and the distinct ones run concurrently (nvdisasm is
104 # a separate process per call). Every pair is still checked and reported by its own name.
105 loaded = []
106 for actual in pairs:
107 prefix = str(actual)[:-len("sm86.bin")]
108 reference = Path(prefix + "sm121.bin").read_bytes()
109 code = actual.read_bytes()
110 metadata = Path(prefix + "ir").read_bytes()
111 if len(metadata) % 8:
112 raise RuntimeError("malformed IR metadata")
113 loaded.append((actual, reference, code, metadata))
114
115 def check(key):
116 reference, code, metadata = key
117 ops = [op for op, _ in struct.iter_unpack("=II", metadata)]
118 try:
119 return compare(args.nvdisasm, reference, code, ops), None
120 except RuntimeError as error:
121 return None, error
122
123 unique = list(dict.fromkeys((reference, code, metadata) for _, reference, code, metadata in loaded))
124 with ThreadPoolExecutor(max_workers=os.cpu_count() or 1) as pool:
125 results = dict(zip(unique, pool.map(check, unique)))
126 for actual, reference, code, metadata in loaded:
127 ops = [op for op, _ in struct.iter_unpack("=II", metadata)]
128 decoded, error = results[(reference, code, metadata)]
129 if error is not None:
130 mismatches.append(f"{actual.name}: {error}")
131 continue
132 coverage.update(ops)
133 if mutation is None:
134 for i, text in enumerate(decoded):
135 if re.search(r"^(?:@!?P\d+ )?[A-Z0-9_.]+ R\d+,", text):
136 changed = bytearray(code)
137 # Corrupt a real GPR destination, not padding or an ignored bit.
138 changed[i * 16 + 2] ^= 1
139 mutation = (reference, bytes(changed), ops)
140 break
141 if uniform_dst_mutation is None:
142 for i, text in enumerate(decoded):
143 if text == "IMAD R12, R8, UR2, R16":
144 changed = bytearray(code)
145 # Reintroduce the old bug: a uniform SOURCE selected UR2's
146 # physical index for the GPR destination instead of R12.
147 changed[i * 16 + 2] = 2
148 uniform_dst_mutation = (reference, bytes(changed), ops)
149 break
150 if mmio_mutation is None and 21 in ops:
151 changed = bytearray(code)
152 i = ops.index(21)
153 # Historical EF word must not satisfy the Ampere MMIO contract.
154 struct.pack_into("<I", changed, i * 16 + 8, 202250496)
155 mmio_mutation = (reference, bytes(changed), ops)
156 if subtraction_mutation is None and 31 in ops:
157 changed = bytearray(code)
158 changed[ops.index(31) * 16 + 7] &= 0x7f
159 subtraction_mutation = (reference, bytes(changed), ops)
160 if branch_mutation is None and 46 in ops:
161 changed = bytearray(code)
162 changed[ops.index(46) * 16 + 4] ^= 0x10
163 branch_mutation = (reference, bytes(changed), ops)
164 if reconvergence_mutation is None and 54 in ops:
165 changed = bytearray(code)
166 changed[ops.index(54) * 16 + 4] ^= 0x10
167 reconvergence_mutation = (reference, bytes(changed), ops)
168 if sync_barrier_mutation is None and 55 in ops:
169 changed = bytearray(code)
170 changed[ops.index(55) * 16 + 2] ^= 1
171 sync_barrier_mutation = (reference, bytes(changed), ops)
172 if carry_mutation is None and 14 in ops:
173 changed = bytearray(code)
174 changed[ops.index(14) * 16 + 10] ^= 2
175 carry_mutation = (reference, bytes(changed), ops)
176 if mismatches:
177 raise RuntimeError("\n".join(mismatches))
178 missing = set(range(60)) - coverage
179 if missing:
180 raise RuntimeError(f"opcode coverage missing: {sorted(missing)}")
181 if mutation is None:
182 raise RuntimeError("no operand-bearing instruction for negative control")
183 try:
184 compare(args.nvdisasm, *mutation)
185 except RuntimeError:
186 pass
187 else:
188 raise RuntimeError("negative control BROKEN: mutated register encoding passed")
189 if uniform_dst_mutation is None:
190 raise RuntimeError("uniform-source nonidentity GPR-map regression missing")
191 try:
192 compare(args.nvdisasm, *uniform_dst_mutation)
193 except RuntimeError:
194 pass
195 else:
196 raise RuntimeError("negative control BROKEN: old uniform-destination bug passed")
197 if mmio_mutation is None:
198 raise RuntimeError("MMIO contract regression missing")
199 try:
200 compare(args.nvdisasm, *mmio_mutation)
201 except RuntimeError:
202 pass
203 else:
204 raise RuntimeError("negative control BROKEN: EF load satisfied MMIO contract")
205 if subtraction_mutation is None:
206 raise RuntimeError("subtraction modifier regression missing")
207 try:
208 compare(args.nvdisasm, *subtraction_mutation)
209 except RuntimeError:
210 pass
211 else:
212 raise RuntimeError("negative control BROKEN: FADD satisfied the FSUB contract")
213 if branch_mutation is None:
214 raise RuntimeError("Ampere branch displacement regression missing")
215 try:
216 compare(args.nvdisasm, *branch_mutation)
217 except RuntimeError:
218 pass
219 else:
220 raise RuntimeError("negative control BROKEN: wrong branch destination accepted")
221 if reconvergence_mutation is None:
222 raise RuntimeError("Ampere reconvergence join regression missing")
223 try:
224 compare(args.nvdisasm, *reconvergence_mutation)
225 except RuntimeError:
226 pass
227 else:
228 raise RuntimeError("negative control BROKEN: wrong reconvergence join accepted")
229 if sync_barrier_mutation is None:
230 raise RuntimeError("Ampere reconvergence barrier regression missing")
231 try:
232 compare(args.nvdisasm, *sync_barrier_mutation)
233 except RuntimeError:
234 pass
235 else:
236 raise RuntimeError("negative control BROKEN: wrong reconvergence barrier accepted")
237 if carry_mutation is None:
238 raise RuntimeError("Ampere discarded-carry regression missing")
239 try:
240 compare(args.nvdisasm, *carry_mutation)
241 except RuntimeError:
242 pass
243 else:
244 raise RuntimeError("negative control BROKEN: unexpected carry output accepted")
245 refused = list(args.corpus.glob("*.refused"))
246 refused_markers = {imm for file in refused for op, imm in struct.iter_unpack("=II", file.read_bytes())
247 if (op, imm) in {(16, 0x51303832), (37, 0x46453433)}}
248 if refused_markers != {0x51303832, 0x46453433}:
249 raise RuntimeError("native FP8 QMMA and E4M3 conversion refusal coverage missing")
250 print(f"SM86 offline oracle: {len(pairs)} kernels, every opcode/operand matched; mutated operand refused;")
251 print(f"native FP8 refusals: {len(refused)} kernels. Device qualification: NOT_RUN")
252 print("MMIO policy, subtraction sign, branch target, reconvergence join/barrier controls refused")
253 print("IADD3's discarded PT outputs retained semantically; unexpected carry output refused")
254
255
256if __name__ == "__main__":
257 main()