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 / evidence / MAX-INTEROP / G2 / tools / cubin_variants.py

335 lines · 16008 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Gate-2 load-matrix fixtures (diagnostic, host only).
3
4Builds cubin variants that separate the candidate causes of CUDApp#68's
5cuModuleLoadData error 200: missing program headers, missing capmerc/merc
6sections, missing .note.nv.tkinfo, .nv.callgraph, symtab sh_info, the
7remaining ptxas-only metadata (E5), and container versus machine code (F, G:
8each kernel's SASS inside the other writer's container).
9Writes variants/<name>.cubin and variants/MATRIX.tsv (name, fn, mode,
10expectation, sha256, what it isolates).
11"""
12import hashlib
13import struct
14import sys
15from pathlib import Path
16
17HERE = Path(__file__).resolve().parent
18CTL = HERE / "ctl.cubin"
19STALE = Path("/dev/shm/cudapp-max/evidence/MAX-INTEROP/68/matmul-16x16x8.cubin")
20MAIN = HERE / "omega-main-artifact/matmul-16x16x8.cubin"
21SM80 = Path.home() / "workspace/maxinterop/max-source/max/kernels/test/gpu/device_context/data/vec_add.sm80.cubin"
22OUT = HERE / "variants"
23FN = "omega_matmul_bf16"
24
25SH = struct.Struct("<IIQQQQIIQQ") # name type flags addr off size link info align entsize
26PH = struct.Struct("<IIQQQQQQ") # type flags off vaddr paddr filesz memsz align
27SYM = struct.Struct("<IBBHQQ") # name info other shndx value size
28EXIT_OFFS, CRS_STACK, MAXREG, REGCOUNT = 0x1C, 0x1E, 0x1B, 0x2F # EIATTR codes (cuobjdump 13.0 names)
29ISA_CLASS = 0x02 # EICOMPAT_ATTR_ISA_CLASS in .nv.compat (cuobjdump 13.0); ptxas 13.0 sm_121/a/f writes 1, CUDApp 2
30
31
32class Elf:
33 def __init__(self, raw: bytes):
34 self.b = bytearray(raw)
35 assert self.b[:4] == b"\x7fELF" and self.b[4] == 2, "not ELF64"
36
37 def u(self, fmt, off):
38 return struct.unpack_from(fmt, self.b, off)[0]
39
40 def p(self, fmt, off, v):
41 struct.pack_into(fmt, self.b, off, v)
42
43 @property
44 def shoff(self):
45 return self.u("<Q", 0x28)
46
47 @property
48 def shnum(self):
49 return self.u("<H", 0x3C)
50
51 def shdrs(self):
52 return [list(SH.unpack_from(self.b, self.shoff + i * 64)) for i in range(self.shnum)]
53
54 def name_of(self, hdrs, i):
55 st = hdrs[self.u("<H", 0x3E)]
56 s = st[4] + hdrs[i][0]
57 return bytes(self.b[s : self.b.index(0, s)]).decode()
58
59 def index(self, name):
60 h = self.shdrs()
61 return next(i for i in range(len(h)) if self.name_of(h, i) == name)
62
63 def set_sh(self, i, field, value):
64 h = self.shdrs()
65 h[i][field] = value
66 SH.pack_into(self.b, self.shoff + i * 64, *h[i])
67
68 def add_section(self, name, typ, flags, align, data, link=0, info=0, entsize=0):
69 """Append a section at the end; shstrtab and the header table move to EOF."""
70 h = self.shdrs()
71 sx = self.u("<H", 0x3E)
72 old = bytes(self.b[h[sx][4] : h[sx][4] + h[sx][5]])
73 new_name_off = len(old)
74 strtab = old + name.encode() + b"\0"
75 h[sx][4], h[sx][5] = self._append(strtab, 1), len(strtab)
76 off = self._append(data, max(align, 1))
77 h.append([new_name_off, typ, flags, 0, off, len(data), link, info, align, entsize])
78 shoff = self._append(b"".join(SH.pack(*r) for r in h), 8)
79 self.p("<Q", 0x28, shoff)
80 self.p("<H", 0x3C, len(h))
81 return len(h) - 1
82
83 def _append(self, data, align):
84 while len(self.b) % align:
85 self.b.append(0)
86 off = len(self.b)
87 self.b += data
88 return off
89
90 def data(self, i):
91 h = self.shdrs()[i]
92 return bytes(self.b[h[4] : h[4] + h[5]])
93
94 def replace(self, i, data, align):
95 """Move section i's contents to EOF; a caller moving a loaded section fixes its segment."""
96 self.set_sh(i, 4, self._append(data, max(align, 1)))
97 self.set_sh(i, 5, len(data))
98
99 def phdr(self, j):
100 return list(PH.unpack_from(self.b, self.u("<Q", 0x20) + j * 56))
101
102 def set_phdr(self, j, row):
103 PH.pack_into(self.b, self.u("<Q", 0x20) + j * 56, *row)
104
105 def text_phdr(self, text_off):
106 return next(j for j in range(self.u("<H", 0x38)) if self.phdr(j)[0] == 1 and self.phdr(j)[2] == text_off and self.phdr(j)[1] & 1)
107
108 def sym(self, k):
109 h = self.shdrs()[self.index(".symtab")]
110 return list(SYM.unpack_from(self.b, h[4] + k * 24))
111
112 def set_sym(self, k, row):
113 h = self.shdrs()[self.index(".symtab")]
114 SYM.pack_into(self.b, h[4] + k * 24, *row)
115
116
117def nvinfo(data):
118 """EIFMT_SVAL (4) entries carry a u16 size and a payload; the others a u16 value."""
119 out, o = [], 0
120 while o < len(data):
121 fmt, attr = data[o], data[o + 1]
122 n = struct.unpack_from("<H", data, o + 2)[0] if fmt == 4 else 0
123 out.append([fmt, attr, bytes(data[o + 4 : o + 4 + n]) if fmt == 4 else bytes(data[o + 2 : o + 4])])
124 o += 4 + n
125 assert o == len(data), "nv.info overrun"
126 return out
127
128
129def nvinfo_pack(entries):
130 return b"".join(bytes([f, a]) + (struct.pack("<H", len(v)) if f == 4 else b"") + v for f, a, v in entries)
131
132
133def exit_offsets(text):
134 """Offsets of EXIT (opcode bits 0..11 = 0x94d) in 16-byte sm_121 instructions."""
135 return [o for o in range(0, len(text), 16) if struct.unpack_from("<Q", text, o)[0] & 0xFFF == 0x94D]
136
137
138def set_attr(entries, attr, value):
139 hit = [e for e in entries if e[1] == attr]
140 assert len(hit) == 1, f"attr {attr:#x} occurs {len(hit)} times"
141 hit[0][2] = value
142 return entries
143
144
145def tkinfo_from(ctl: Elf):
146 h = ctl.shdrs()
147 i = ctl.index(".note.nv.tkinfo")
148 return bytes(ctl.b[h[i][4] : h[i][4] + h[i][5]]), h[i]
149
150
151def own_tkinfo(template: bytes):
152 """Same note header/fields as ptxas, tool strings replaced with CUDApp's."""
153 namesz, descsz, ntype = struct.unpack_from("<III", template, 0)
154 name = template[12 : 12 + namesz]
155 desc = bytearray(template[12 + ((namesz + 3) & ~3) :][:descsz])
156 # desc = six u32 (2, 0, off_tool, off_version, off_build, off_options) then a
157 # string blob that starts with NUL; offsets index the blob (read off ptxas 13.0.88).
158 head = list(struct.unpack_from("<6I", desc, 0))
159 blob = b"\0"
160 offs = []
161 for s in (b"cudapp", b"CUDApp omega_cubin sm_121", b"Build b5746b94", b"-arch sm_121"):
162 offs.append(len(blob))
163 blob += s + b"\0"
164 head[2:6] = offs
165 desc = struct.pack("<6I", *head) + blob
166 desc += b"\0" * ((-len(desc)) % 4)
167 return struct.pack("<III", namesz, len(desc), ntype) + name + b"\0" * ((-namesz) % 4) + desc
168
169
170def main():
171 OUT.mkdir(exist_ok=True)
172 ctl = Elf(CTL.read_bytes())
173 stale = STALE.read_bytes()
174 main_raw = MAIN.read_bytes()
175 tk, tkh = tkinfo_from(ctl)
176 cg_i = ctl.index(".nv.callgraph")
177 cgh = ctl.shdrs()[cg_i]
178 callgraph = bytes(ctl.b[cgh[4] : cgh[4] + cgh[5]])
179 rows = []
180
181 def emit(name, data, fn, mode, expect, isolates):
182 (OUT / f"{name}.cubin").write_bytes(data)
183 rows.append((name, fn, mode, expect, hashlib.sha256(data).hexdigest(), isolates))
184
185 # Positive control: ptxas 13.0.88 cubin for the same ABI.
186 emit("A-ctl", bytes(ctl.b), FN, "run", "PASS", "probe+driver+ABI known-good")
187 # Capmerc hypothesis: drop the trailing 7 capmerc/merc sections (indices 15..21;
188 # nothing in .symtab or the remaining sections points at them).
189 nomerc = Elf(bytes(ctl.b))
190 first_merc = nomerc.index(".nv.capmerc.text." + FN)
191 assert all(nomerc.name_of(nomerc.shdrs(), i).startswith(".nv.merc") or i == first_merc
192 for i in range(first_merc, nomerc.shnum))
193 nomerc.p("<H", 0x3C, first_merc)
194 emit("B-ctl-nomerc", bytes(nomerc.b), FN, "run", "PASS if capmerc not required", "capmerc/merc sections")
195 # The #68 evidence artifact (bb9be0b1, before PHDR commit 130a101f): no program headers.
196 # 2026-10-24 window 20261024T043818Z-aa5c86 returned 200 for this path (transcript only).
197 emit("C-omega-stale-nophdr", stale, FN, "reject", "REJECT 200 (seen 10-24, no receipt)", "program headers absent")
198 # Same kernel from main b5746b94 writer (PHDR + 5 headers), text/cbank bytes identical.
199 # 10-24 window 20261024T044814Z-4dc098 returned 200 for a PHDR build (/tmp/phdr-mat.cubin).
200 emit("D-omega-main", main_raw, FN, "run", "REJECT 200 expected (10-24 phdr-mat)", "current CUDApp writer")
201 # Symtab convention: ptxas sets symtab sh_info to the symbol count; CUDApp sets 2
202 # with a local symbol after the global one.
203 e = Elf(main_raw)
204 st = e.index(".symtab")
205 e.set_sh(st, 7, e.shdrs()[st][5] // 24)
206 emit("E1-omega-symfix", bytes(e.b), FN, "run", "UNKNOWN", "symtab sh_info")
207 # tkinfo hypothesis (omega-mv#864 body: ABI 8 without tkinfo -> 200 on other GPUs).
208 e = Elf(main_raw)
209 ti = e.add_section(".note.nv.tkinfo", tkh[1], tkh[2], tkh[8], tk)
210 e.set_sh(e.index(".note.nv.cuinfo"), 6, ti)
211 emit("E2-omega-tkinfo-ptxas", bytes(e.b), FN, "run", "UNKNOWN", ".note.nv.tkinfo (ptxas bytes)")
212 e = Elf(main_raw)
213 ti = e.add_section(".note.nv.tkinfo", tkh[1], tkh[2], tkh[8], own_tkinfo(tk))
214 e.set_sh(e.index(".note.nv.cuinfo"), 6, ti)
215 emit("E3-omega-tkinfo-own", bytes(e.b), FN, "run", "UNKNOWN", ".note.nv.tkinfo (own strings)")
216 e = Elf(main_raw)
217 ti = e.add_section(".note.nv.tkinfo", tkh[1], tkh[2], tkh[8], tk)
218 e.set_sh(e.index(".note.nv.cuinfo"), 6, ti)
219 e.add_section(".nv.callgraph", cgh[1], cgh[2], cgh[8], callgraph, link=e.index(".symtab"), entsize=cgh[9])
220 st = e.index(".symtab")
221 e.set_sh(st, 7, e.shdrs()[st][5] // 24)
222 emit("E4-omega-tkinfo-cg-symfix", bytes(e.b), FN, "run", "UNKNOWN", "all three metadata gaps")
223 # E5: E4 plus every remaining ptxas-only item except merc and .debug_frame:
224 # EXIT_INSTR_OFFSETS + CRS_STACK_SIZE, the two reserved-smem symbols, and
225 # .nv.constant0 sh_link/align as ptxas writes them.
226 ctl_text = ctl.data(ctl.index(".text." + FN))
227 assert exit_offsets(ctl_text) == [0x30, 0x780], "EXIT scan disagrees with cuobjdump on the control"
228 main_e = Elf(main_raw)
229 omega_text = main_e.data(main_e.index(".text." + FN))
230 omega_exits = exit_offsets(omega_text)
231 assert omega_exits == [0x400], omega_exits # nvdisasm 13.0: /*0400*/ EXIT
232 ki = e.index(".nv.info." + FN)
233 ents = nvinfo(e.data(ki))
234 at = next(n for n, x in enumerate(ents) if x[1] == 0x4A) + 1
235 ents[at:at] = [[4, EXIT_OFFS, struct.pack(f"<{len(omega_exits)}I", *omega_exits)], [4, CRS_STACK, b"\0" * 4]]
236 e.replace(ki, nvinfo_pack(ents), 4)
237 sti, sx = e.index(".symtab"), e.index(".strtab")
238 strtab = e.data(sx)
239 names = [len(strtab), len(strtab) + len(".nv.reservedSmem.offset0") + 1]
240 e.replace(sx, strtab + b".nv.reservedSmem.offset0\0__nv_reservedSMEM_offset_0_alias\0", 1)
241 syms = e.data(sti) + SYM.pack(names[0], 0x21, 0, 0, 0x40, 4) + SYM.pack(names[1], 0x20, 0xA0, e.index(".nv.shared.reserved.0"), 0x40, 0)
242 e.replace(sti, syms, 8)
243 e.set_sh(sti, 7, len(syms) // 24)
244 c0 = e.index(".nv.constant0." + FN)
245 e.set_sh(c0, 6, 0)
246 e.set_sh(c0, 8, 4)
247 emit("E5-omega-allmeta", bytes(e.b), FN, "run", "UNKNOWN", "E4 + exit offsets, crs, smem syms, cbank0 link/align")
248 e5 = bytes(e.b)
249 # F: the control's container without merc (B) carrying Omega's machine code.
250 # The text shrinks in place (0x880 -> 0x480); its segment, symbol size and
251 # EXIT offsets follow. REGCOUNT stays the control's 40: Omega's code writes R0..R31
252 # (peak 32), ptxas declares max register + 3 (control R37 -> 40, mma R15 -> 18). cbank0 is all zero in both.
253 f = Elf(bytes(nomerc.b))
254 ti = f.index(".text." + FN)
255 th = f.shdrs()[ti]
256 f.b[th[4] : th[4] + th[5]] = omega_text + b"\0" * (th[5] - len(omega_text))
257 f.set_sh(ti, 5, len(omega_text))
258 j = f.text_phdr(th[4])
259 ph = f.phdr(j)
260 ph[5] = ph[6] = len(omega_text)
261 f.set_phdr(j, ph)
262 k = th[7] # .text sh_info = the function symbol
263 s = f.sym(k)
264 s[5] = len(omega_text)
265 f.set_sym(k, s)
266 ki = f.index(".nv.info." + FN)
267 f.replace(ki, nvinfo_pack(set_attr(nvinfo(f.data(ki)), EXIT_OFFS, struct.pack(f"<{len(omega_exits)}I", *omega_exits))), 4)
268 emit("F-ctlcontainer-omega-sass", bytes(f.b), FN, "run", "UNKNOWN: load => Omega SASS accepted", "machine code vs container (ptxas container)")
269 # G: the current CUDApp container (D) carrying the control's machine code.
270 # The text moves to EOF (0x480 -> 0x880) with its segment; symbol size,
271 # REGCOUNT 40 and MAXREG 0xff follow the control's code. The old Omega
272 # bytes are zeroed, so each of F and G holds exactly one kernel's code.
273 g = Elf(main_raw)
274 ti = g.index(".text." + FN)
275 th = g.shdrs()[ti]
276 j = g.text_phdr(th[4])
277 g.replace(ti, ctl_text, 128)
278 g.b[th[4] : th[4] + th[5]] = b"\0" * th[5]
279 ph = g.phdr(j)
280 ph[2], ph[5], ph[6] = g.shdrs()[ti][4], len(ctl_text), len(ctl_text)
281 g.set_phdr(j, ph)
282 k = th[7]
283 s = g.sym(k)
284 s[5] = len(ctl_text)
285 g.set_sym(k, s)
286 mi = g.index(".nv.info")
287 g.replace(mi, nvinfo_pack(set_attr(nvinfo(g.data(mi)), REGCOUNT, struct.pack("<II", k, 40))), 4)
288 ki = g.index(".nv.info." + FN)
289 g.replace(ki, nvinfo_pack(set_attr(nvinfo(g.data(ki)), MAXREG, b"\xff\0")), 4)
290 emit("G-omegacontainer-ctl-sass", bytes(g.b), FN, "run", "UNKNOWN: load => CUDApp container accepted", "machine code vs container (CUDApp container)")
291 # H: register count and ISA class, the only E5-vs-F metadata differences left
292 # (static diff 2026-10-31: same text, tkinfo, cuinfo, cbank0, e_flags).
293 def with_meta(base, regs=None, maxreg=None, isa=None):
294 v = Elf(base)
295 def put(name, ents):
296 i = v.index(name)
297 h = v.shdrs()[i]
298 new = nvinfo_pack(ents)
299 assert len(new) == h[5]
300 v.b[h[4] : h[4] + h[5]] = new
301 if regs is not None:
302 ents = nvinfo(v.data(v.index(".nv.info")))
303 sym = struct.unpack_from("<I", next(x for x in ents if x[1] == REGCOUNT)[2])[0]
304 put(".nv.info", set_attr(ents, REGCOUNT, struct.pack("<II", sym, regs)))
305 if maxreg is not None:
306 put(".nv.info." + FN, set_attr(nvinfo(v.data(v.index(".nv.info." + FN))), MAXREG, struct.pack("<H", maxreg)))
307 if isa is not None:
308 put(".nv.compat", set_attr(nvinfo(v.data(v.index(".nv.compat"))), ISA_CLASS, struct.pack("<H", isa)))
309 return bytes(v.b)
310 e3 = (OUT / "E3-omega-tkinfo-own.cubin").read_bytes()
311 emit("H1-e5-reg40", with_meta(e5, regs=40, maxreg=40), FN, "run", "PASS if register count", "REGCOUNT+MAXREG 40 (peak+2 rounded to 8)")
312 emit("H2-e5-regcount40", with_meta(e5, regs=40), FN, "run", "UNKNOWN", "REGCOUNT 0x2f only")
313 emit("H3-e5-maxreg40", with_meta(e5, maxreg=40), FN, "run", "UNKNOWN", "MAXREG 0x1b only")
314 emit("H4-e5-reg34", with_meta(e5, regs=34, maxreg=34), FN, "run", "UNKNOWN", "REGCOUNT+MAXREG 34 (peak+2, ptxas rule)")
315 emit("H5-e5-isa1", with_meta(e5, isa=1), FN, "run", "715 if register count", "nv.compat ISA_CLASS 1 (ptxas value)")
316 emit("H6-e3-reg40", with_meta(e3, regs=40, maxreg=40), FN, "run", "PASS if tkinfo+regs suffice", "minimal writer fix: own tkinfo + regs 40")
317 emit("H7-d-reg40", with_meta(main_raw, regs=40, maxreg=40), FN, "reject", "REJECT 200 (no tkinfo)", "regs alone do not fix the load")
318 # Negative controls: each must be rejected.
319 emit("N1-ctl-truncated", bytes(ctl.b[:1500]), FN, "reject", "REJECT", "truncated image")
320 emit("N2-ctl-wrong-entry", bytes(ctl.b), "omega_matmul_bf16_missing", "reject", "REJECT (500 NOT_FOUND)", "entry name")
321 bad = Elf(bytes(ctl.b))
322 flags = bad.u("<I", 0x30)
323 bad.p("<I", 0x30, (flags & ~0xFF00) | (80 << 8))
324 emit("N3-ctl-eflags-sm80", bytes(bad.b), FN, "reject", "REJECT", "e_flags arch field")
325 if SM80.exists():
326 emit("N4-max-vecadd-sm80", SM80.read_bytes(), "vec_add", "reject", "REJECT (209 NO_BINARY_FOR_GPU)", "wrong-arch real cubin")
327 with open(OUT / "MATRIX.tsv", "w") as f:
328 f.write("name\tfn\tmode\texpect\tsha256\tisolates\n")
329 for r in rows:
330 f.write("\t".join(r) + "\n")
331 print((OUT / "MATRIX.tsv").read_text(), end="")
332
333
334if __name__ == "__main__":
335 sys.exit(main())