Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/tools/ampere_nvdisasm.py # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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 4 reference, with the explicit documented target ABI/ISA spelling differences. 5 NVIDIA output is ephemeral; no driver is loaded and no oracle listings committed. 6 """ 7 import argparse 8 from concurrent.futures import ThreadPoolExecutor 9 import os 10 from pathlib import Path 11 import re 12 import struct 13 import subprocess 14 import tempfile 15 16 17 def 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 33 def 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 58 def 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 84 def 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("