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 / tests / runtime / artifact_format_gate.py

182 lines · 10121 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Host-only byte/refusal differential. JSON is an output mirror, never admission."""
4import argparse
5import ctypes as C
6import hashlib
7import json
8import os
9from concurrent.futures import ThreadPoolExecutor
10from pathlib import Path
11import random
12import shlex
13import subprocess
14import tempfile
15
16ROOT = Path(__file__).resolve().parents[2]
17SUFFIX = ('.manifest', '.text.bin', '.cubin', '.qmd0.bin', '.qmd1.bin', '.cbank_args.bin', '.json', '.sha256')
18SEED = 0xA17FAC7
19class Param(C.Structure):
20 _fields_ = [('offset', C.c_uint32), ('size', C.c_uint32), ('pointer', C.c_uint8)]
21class Artifact(C.Structure):
22 _fields_ = [(k, C.c_char_p) for k in ('op','shape','bounds','contract_name','contract_id_hex','semantic_spec_id_hex','kernel_function','precision','accumulation','tolerance')] + [
23 ('text', C.POINTER(C.c_uint8)), ('text_len', C.c_size_t), ('params', C.POINTER(Param)), ('nparams', C.c_size_t)] + [
24 (k,C.c_uint32) for k in ('gpr_count','grid_x','grid_y','block_x','block_y','block_z','shared_bytes','cbank_offset')] + [
25 ('cbank_args',C.POINTER(C.c_uint32)),('cbank_words',C.c_size_t),('qmd0',C.POINTER(C.c_uint32)),('qmd1',C.POINTER(C.c_uint32))] + [
26 (k,C.c_char_p) for k in ('min_driver','requires','source_commit','tool_version','qualification')]
27
28def strict_pairs(items):
29 out={}
30 for k,v in items:
31 if k in out: raise ValueError('duplicate JSON key: '+k)
32 out[k]=v
33 return out
34
35def parse_json(raw):
36 return json.loads(raw, object_pairs_hook=strict_pairs,
37 parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x)))
38
39def fixture():
40 text=(C.c_uint8*16)()
41 params=(Param*1)(Param(896,8,1))
42 q0=(C.c_uint32*96)();q1=(C.c_uint32*96)();cb=(C.c_uint32*2)()
43 q1[52]=12; q1[34]=1|(1<<16);q1[35]=1|(16<<8)|(1<<17)
44 q1[36]=(0x04b44808 & ~0x7ff)|8;q1[39]=q1[40]=q1[41]=1
45 a=Artifact(b'matmul',b'm=1,k=1,n=1',b'm<=16',b'fixture',b'a'*64,b'b'*64,b'fixture',b'bf16',b'fp32',b'0',text,16,params,1,
46 16,1,1,1,1,1,0,896,cb,2,q0,q1,b'580.173.02',b'sm_121',b'UNKNOWN',b'artifact-format/1',b'host-only')
47 return a,(text,params,q0,q1,cb)
48
49def run(cmd):
50 print('+',shlex.join(map(str,cmd)),flush=True)
51 subprocess.run(cmd,cwd=ROOT,check=True)
52
53def build(out, replacements=()):
54 lib=out/'artifact.so'
55 cc=shlex.split(os.environ.get('CC','cc'))
56 sources=['src/omega_native_artifact.c','tests/runtime/artifact_oracle.c','src/omega_cubin.c','src/omega_blackwell_realize.c','src/omega_blackwell_encoder.c','src/sha256.c']
57 repl=dict(replacements)
58 sources += [str(repl.get(p.name,p)) for p in sorted((ROOT/'src').glob('cudapp_om_*.c'))]
59 sources += [str(p) for p in sorted((ROOT/'src').glob('cudapp_freest_*.c'))]
60 flags=['-fPIC','-O0','-std=c11','-D_GNU_SOURCE','-Isrc']
61 cache=ROOT/'build/artifact-format/objects';cache.mkdir(parents=True,exist_ok=True)
62 deps=b''.join(p.read_bytes() for p in sorted((ROOT/'src').glob('*.h')))
63 deps+=(ROOT/'src/omega_native_artifact.c').read_bytes()+(ROOT/'src/omega_native_artifact_om.inc').read_bytes()
64 def compile_one(source):
65 path=ROOT/source
66 digest=hashlib.sha256(path.read_bytes()+deps+repr(cc+flags).encode()).hexdigest()
67 obj=cache/(path.stem+'-'+digest+'.o')
68 if not obj.exists():run(cc+flags+['-c',str(path),'-o',str(obj)])
69 return str(obj)
70 with ThreadPoolExecutor(max_workers=3) as workers:objects=list(workers.map(compile_one,sources))
71 run(cc+['-shared','-Wl,-z,defs','-o',str(lib)]+objects+['-lpthread','-lm'])
72 return lib
73
74def bind(lib):
75 dll=C.CDLL(str(lib))
76 for name in ('omega_native_artifact_export','artifact_c_export'):
77 f=getattr(dll,name);f.argtypes=[C.POINTER(Artifact),C.c_char_p,C.c_void_p,C.c_void_p,C.c_size_t];f.restype=C.c_int
78 for name in ('omega_native_artifact_admit','artifact_c_admit'):
79 f=getattr(dll,name);f.argtypes=[C.c_char_p,C.c_char_p,C.c_void_p,C.c_void_p,C.c_size_t];f.restype=C.c_int
80 return dll
81
82def invoke(f,*args):
83 ident=C.create_string_buffer(65);err=C.create_string_buffer(256)
84 rc=f(*args,ident,err,256)
85 return rc,ident.value
86
87def remove(p):
88 for s in SUFFIX: Path(str(p)+s).unlink(missing_ok=True)
89
90def rehash(raw):
91 try:
92 start=raw.index(b'\nop=')+1;end=raw.index(b'provenance_tool=',start)
93 p=raw.index(b'artifact_id=')+12; e=raw.index(b'\n',p)
94 if e-p!=64:return raw
95 return raw[:p]+hashlib.sha256(raw[start:end]).hexdigest().encode()+raw[e:]
96 except ValueError:return raw
97
98def codec(dll):
99 f=dll.omega_artifact_format
100 f.argtypes=[C.POINTER(C.c_uint64),C.c_void_p,C.c_uint64,C.c_void_p,C.c_uint64]
101 c=dll.artifact_c_json_escape
102 c.argtypes=[C.c_char_p,C.c_void_p,C.c_size_t];c.restype=C.c_size_t
103 for raw in [b'']+[bytes([i]) for i in range(1,256)]+[b'\xc3\xa9',b'quote"slash\\']:
104 b=(C.c_uint8*65536)();s=(C.c_uint64*128)();ok=C.c_uint64()
105 for i,v in enumerate(raw):b[i]=v
106 s[0]=2;s[10]=0;s[50]=len(raw)
107 assert f(C.byref(ok),b,65536,s,128)==0 and ok.value==1
108 emitted=bytes(b[32768:32768+s[1]])
109 expected=(C.c_uint8*2048)()
110 n=c(raw,expected,2048)
111 assert b' "shape": '+bytes(expected[:n])+b',\n' in emitted
112 try:decoded=raw.decode('utf-8')
113 except UnicodeDecodeError:
114 try:parse_json(emitted)
115 except UnicodeDecodeError:pass
116 else:raise AssertionError('legacy invalid UTF-8 became valid')
117 else:assert parse_json(emitted)['shape']==decoded
118 for invalid in (b'{"x":1,"x":2}',b'{"x":"\\q"}',b'{"x":"\\uZZZZ"}'):
119 try:parse_json(invalid)
120 except (ValueError,UnicodeDecodeError):pass
121 else:raise AssertionError('strict independent parser accepted adversarial JSON')
122 print('ARTIFACT-FORMAT codec PASS byte-domain=256 valid-utf8 strict-escapes duplicate-keys invalid-utf8-classified',flush=True)
123
124def corpus(dll,directory,flip=False,cases=6000):
125 rng=random.Random(SEED); a,keep=fixture()
126 om=directory/'om';oracle=directory/'cc'
127 mutations=[b'plain',b'quote"slash\\',b'x'*127,b'x'*128,b'x'*8192,b'bad\nvalue',b'bad\rvalue',b'\x7f',b'\x01',b'\xc3\xa9']
128 fields=('shape','bounds','contract_name','precision','accumulation','tolerance','requires','source_commit','tool_version','qualification','kernel_function','contract_id_hex','semantic_spec_id_hex','min_driver','op')
129 valid=[]
130 for i in range(256):
131 a,keep=fixture();key=fields[i%len(fields)]
132 value=mutations[(i//len(fields))%len(mutations)] if i else b'm=1,k=1,n=1'
133 if i:setattr(a,key,value)
134 ro=invoke(dll.omega_native_artifact_export,C.byref(a),os.fsencode(om));rc=invoke(dll.artifact_c_export,C.byref(a),os.fsencode(oracle))
135 assert ro==rc,('export',i,key,value[:40],ro,rc)
136 if ro[0]==0:
137 for s in SUFFIX:
138 ob=Path(str(om)+s).read_bytes();cb=Path(str(oracle)+s).read_bytes()
139 if flip and i==0 and s=='.manifest':cb=bytes([cb[0]^1])+cb[1:]
140 assert ob==cb,('bytes',i,s)
141 js=parse_json(Path(str(om)+'.json').read_bytes())
142 assert js['artifact_id'].encode()==ro[1]
143 if key in js:assert js[key]==value.decode('utf-8')
144 valid.append(Path(str(om)+'.manifest').read_bytes())
145 remove(om);remove(oracle)
146 a,keep=fixture();assert invoke(dll.omega_native_artifact_export,C.byref(a),os.fsencode(om))[0]==0
147 base=Path(str(om)+'.manifest').read_bytes();mp=Path(str(om)+'.manifest')
148 lines=base.splitlines(keepends=True)
149 for i in range(cases):
150 kind=i%12;r=bytearray(base)
151 if kind==0:r=bytearray(valid[rng.randrange(len(valid))])
152 elif kind==1:r[rng.randrange(len(r))]^=rng.randrange(1,256)
153 elif kind==2:r=r[:rng.randrange(len(r))]
154 elif kind==3:r+=rng.choice([b'\n',b'{}',b'\x00',b'op=matmul\n'])
155 elif kind==4:
156 j=rng.randrange(1,len(lines));r=bytearray(b''.join(lines[:j]+[lines[j]]+lines[j:]))
157 elif kind==5:r=bytearray(base.replace(b'contract_id='+b'a'*64,b'contract_id='+b'G'*64))
158 elif kind==6:r=bytearray(base.replace(b'shape=m=1,k=1,n=1',b'shape='+b'x'*rng.randrange(127,9000)))
159 elif kind==7:r=bytearray(rng.choice([b'{',b'{"a":1,"a":2}',b'"\\uZZZZ"',b'[NaN]',b'{"bad":"\\q"}']))
160 elif kind==8:
161 j=rng.randrange(1,len(lines));k=rng.randrange(1,len(lines));z=lines.copy();z[j],z[k]=z[k],z[j];r=bytearray(b''.join(z))
162 elif kind==9:r=bytearray(base.replace(b'grid=1,1,1',b'grid='+rng.choice([b'-1,1,1',b'4294967296,1,1',b'01,1,1',b'1,1,2'])))
163 elif kind==10:r=bytearray(base.replace(b'text_sha256=',b'text_sha256=z'))
164 if kind in (0,5,6,9,10):r=bytearray(rehash(bytes(r)))
165 mp.write_bytes(r)
166 driver=rng.choice([None,b'580.173.02',b'1.0.0',b'bad',b'999.0.0',b'1.'+b'1'*100+b'.0'])
167 ro=invoke(dll.omega_native_artifact_admit,os.fsencode(om),driver);rc=invoke(dll.artifact_c_admit,os.fsencode(om),driver)
168 assert ro==rc,('admit',i,kind,ro,rc,bytes(r)[:100])
169 print(f'ARTIFACT-FORMAT PASS export=256 admission={cases} seed={SEED:#x} byte-exact strict-json',flush=True)
170
171def main():
172 ap=argparse.ArgumentParser();ap.add_argument('--library',type=Path);ap.add_argument('--flip',action='store_true');args=ap.parse_args()
173 out=ROOT/'build/artifact-format';out.mkdir(parents=True,exist_ok=True)
174 lib=args.library or build(out)
175 dll=bind(lib);codec(dll)
176 with tempfile.TemporaryDirectory(prefix='artifact-format-') as td:corpus(dll,Path(td),args.flip)
177 if not args.library and not args.flip:
178 red=subprocess.run([os.sys.executable,__file__,'--library',str(lib),'--flip'],cwd=ROOT,capture_output=True,text=True)
179 (out/'negative-control.log').write_text(red.stdout+red.stderr)
180 assert red.returncode==1 and "('bytes', 0, '.manifest')" in red.stderr,'flipped expected byte was not caught at the expected comparison'
181 print('ARTIFACT-FORMAT negative-control PASS expected-byte-flip rc=1')
182if __name__=='__main__':main()