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
CUDApp / tests / amd-exec / token_ref.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Token-kernel independent numerical oracle and generated notebook instruments.""" |
| 4 | import base64 |
| 5 | from fractions import Fraction |
| 6 | from functools import lru_cache |
| 7 | import json |
| 8 | import pathlib |
| 9 | import runpy |
| 10 | import struct |
| 11 | import subprocess |
| 12 | import sys |
| 13 | |
| 14 | HERE = pathlib.Path(__file__).parent |
| 15 | ref = runpy.run_path(str(HERE/'prep.py')) |
| 16 | finite,round32,fma,add,mul,point,imul,iadd,expbound,intervalrcp,rsqbound = ( |
| 17 | ref[n] for n in ('finite','round32','fma','add','mul','point','imul','iadd','expbound','intervalrcp','rsqbound')) |
| 18 | ONE,LOG2E = 0x3f800000,0x3fb8aa3b |
| 19 | COUNTS = (0,1,63,64,65,17408) |
| 20 | CONTROLS = ('mlpsilu-no-silu','mlpsilu-wrong-up') |
| 21 | |
| 22 | @lru_cache(None) |
| 23 | def sigmoid(g): |
| 24 | exponent = mul((g & 0x7fffffff)|0x80000000,LOG2E) |
| 25 | t = expbound(exponent) |
| 26 | answer = intervalrcp(iadd(point(ONE),t)) |
| 27 | return imul(answer,t) if g>>31 else answer |
| 28 | |
| 29 | |
| 30 | def mlp_case(n): |
| 31 | gp,up,op = 64,64+4*n+64,64+8*n+128 |
| 32 | image = bytearray([0xa5])*(op+4*n+64) |
| 33 | struct.pack_into('<3QI',image,0,gp,up,op,n) |
| 34 | gates = [round32(Fraction((i*17)%193-96,8)) for i in range(n)] |
| 35 | ups = [round32(Fraction((i*29)%257-128,16)) for i in range(n)] |
| 36 | special = [0,0x80000000,1,0x80000001,0x42c80000,0xc2c80000,0x4b000000,0xcb000000] |
| 37 | gates[:min(n,len(special))] = special[:n] |
| 38 | struct.pack_into('<'+str(n)+'I',image,gp,*gates) |
| 39 | struct.pack_into('<'+str(n)+'I',image,up,*ups) |
| 40 | intervals = [] |
| 41 | for i,(g,u) in enumerate(zip(gates,ups)): |
| 42 | lo,hi = imul(imul(point(g),sigmoid(g)),point(u)) |
| 43 | intervals.append([op+4*i,str(lo),str(hi)]) |
| 44 | return dict(label=f'N={n}',memory=base64.b64encode(image).decode(),intervals=intervals, |
| 45 | args=[['ptr',gp],['ptr',up],['ptr',op],['u32',n]],gx=(n+63)//64+1,gy=2,input_bytes=8*n+4, |
| 46 | timing_grid=[max(1,(n+63)//64),1]) |
| 47 | |
| 48 | |
| 49 | def check(actual,case): |
| 50 | before = base64.b64decode(case['memory']) |
| 51 | assert len(actual)==len(before),'token mismatch memory length' |
| 52 | untouched = bytearray(actual) |
| 53 | widest = Fraction(0) |
| 54 | for off in case.get('bf16_outputs',[]): |
| 55 | assert struct.unpack_from('<I',actual,off)[0]&0xffff==0, f'token mismatch BF16 output offset={off}' |
| 56 | for off,lo,hi in case['intervals']: |
| 57 | bits = struct.unpack_from('<I',actual,off)[0] |
| 58 | lo,hi = Fraction(lo),Fraction(hi) |
| 59 | assert bits & 0x7fffffff < 0x7f800000 and lo <= finite(bits) <= hi, f'token mismatch {case["label"]} offset={off} bits={bits:08x} interval={lo},{hi}' |
| 60 | widest = max(widest,hi-lo) |
| 61 | untouched[off:off+4] = before[off:off+4] |
| 62 | for off,lo,hi in case.get('half_intervals',[]): |
| 63 | bits=struct.unpack_from('<H',actual,off)[0]<<16 |
| 64 | lo,hi=Fraction(lo),Fraction(hi) |
| 65 | assert bits & 0x7fffffff < 0x7f800000 and lo<=finite(bits)<=hi, f'token mismatch BF16 interval offset={off}' |
| 66 | widest=max(widest,hi-lo) |
| 67 | untouched[off:off+2]=before[off:off+2] |
| 68 | for off,bits,width in case.get('exact',[]): |
| 69 | assert int.from_bytes(actual[off:off+width],'little') == bits, f'token mismatch exact offset={off}' |
| 70 | untouched[off:off+width] = before[off:off+width] |
| 71 | assert untouched==before,'token mismatch input/guard corruption' |
| 72 | return widest |
| 73 | |
| 74 | |
| 75 | def execute(exe,code,out,case): |
| 76 | path = out/'token.memory' |
| 77 | path.write_bytes(base64.b64decode(case['memory'])) |
| 78 | p = subprocess.run([exe,str(code),str(path),str(case['gx']*64),str(case['gy'])],capture_output=True,timeout=600) |
| 79 | assert p.returncode==0 and not p.stdout and not p.stderr,p |
| 80 | return check(path.read_bytes(),case) |
| 81 | |
| 82 | def midpoint_error(actual,case): |
| 83 | worst=Fraction(0) |
| 84 | for entries,width,shift in ((case['intervals'],4,0),(case.get('half_intervals',[]),2,16)): |
| 85 | for off,lo,hi in entries: |
| 86 | bits=int.from_bytes(actual[off:off+width],'little')<<shift |
| 87 | worst=max(worst,abs(finite(bits)-(Fraction(lo)+Fraction(hi))/2)) |
| 88 | return worst |
| 89 | |
| 90 | |
| 91 | def export(name,cases,controls,out,factory,parameters): |
| 92 | payload = dict(name=name,cases=cases,controls=list(controls),timing=len(cases)-1) |
| 93 | serialized = json.dumps(payload,separators=(',',':')).encode() |
| 94 | (out/(name+'-intervals.json')).write_bytes(serialized+b'\n') |
| 95 | section = runpy.run_path(str(HERE/'section.py')) |
| 96 | generated = section['generate'](name,factory,parameters,controls,(HERE/'notebook_section.py').read_text()) |
| 97 | namespace = section['fresh_namespace'](generated,name+'.py') |
| 98 | missing_math = ' import math\n' |
| 99 | assert generated.count(missing_math)==1 |
| 100 | try: section['fresh_namespace'](generated.replace(missing_math,'',1),name+'-no-math.py') |
| 101 | except AssertionError as error: |
| 102 | assert str(error).startswith('unresolved notebook global math in '),error |
| 103 | print(f'CONTROL notebook-{name}-missing-math CAUGHT fresh-loader-namespace {error}',flush=True) |
| 104 | else: raise AssertionError('missing math import escaped') |
| 105 | actual = namespace['_make_payload']() |
| 106 | assert actual == payload, f'generated fixture mismatch {name}' |
| 107 | # A missing case must not escape the fixture/oracle parity check. |
| 108 | bad = dict(actual,cases=actual['cases'][:-1]) |
| 109 | try: assert bad == payload, f'generated fixture mismatch {name}' |
| 110 | except AssertionError: |
| 111 | print(f'CONTROL notebook-{name}-fixture-drift CAUGHT',flush=True) |
| 112 | else: raise AssertionError('generated fixture drift escaped') |
| 113 | size = len(generated.encode()) |
| 114 | assert size < 15000, f'notebook section size alarm: {name} bytes={size} target<15000 (relay cell~60000)' |
| 115 | (out/(name+'.py')).write_text(generated) |
| 116 | print(f'PASS notebook-{name} code_bytes={size} fresh-loader-namespace/all-function-globals in-cell-fixtures/oracle=host-identical every-case/no-embedded-images hardware=NOT_RUN',flush=True) |
| 117 | |
| 118 | |
| 119 | def mutate(src,out): |
| 120 | text = (src/'mlpsilu.isa').read_text() |
| 121 | changes = {'mlpsilu-no-silu':('I 5 267 8 8 5','I 8 267 1 8'), |
| 122 | 'mlpsilu-wrong-up':('I 7 0 0 2 0 0 20 0 4 0 127 0 9','I 7 0 0 2 0 0 20 0 2 0 127 0 9')} |
| 123 | for name,(old,new) in changes.items(): |
| 124 | assert text.count(old)==1,name |
| 125 | (out/(name+'.isa')).write_text(text.replace(old,new)) |
| 126 | |
| 127 | |
| 128 | def suite(exe,out): |
| 129 | cases = [mlp_case(n) for n in COUNTS] |
| 130 | for case in cases: |
| 131 | widest = execute(exe,out/'mlpsilu.text',out,case) |
| 132 | print(f'PASS mlpsilu {case["label"]} all-outputs/manual-interval all-inputs/guards overdispatch=XY widest_interval={widest}',flush=True) |
| 133 | for name in CONTROLS: |
| 134 | try: execute(exe,out/(name+'.text'),out,cases[-1]) |
| 135 | except AssertionError as error: |
| 136 | assert str(error).startswith('token mismatch'),error |
| 137 | print(f'CONTROL {name} CAUGHT {str(error).split(":")[0]}',flush=True) |
| 138 | else: raise AssertionError(f'control escaped {name}') |
| 139 | export('mlpsilu',cases,CONTROLS,out,mlp_case,[(n,) for n in COUNTS]) |
| 140 | print(f'PASS token mlpsilu_counts={",".join(map(str,COUNTS))} mlpsilu_cases={len(cases)} hardware=NOT_RUN',flush=True) |
| 141 | |
| 142 | |
| 143 | if __name__ == '__main__': |
| 144 | if sys.argv[1]=='mutate': mutate(pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3])) |
| 145 | elif sys.argv[1]=='suite': suite(sys.argv[2],pathlib.Path(sys.argv[3])) |
| 146 | else: raise SystemExit('unknown token mode') |