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 / amd-exec / torch_gdn_probe.py

82 lines · 4916 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Optional CPU-only independent reference instrument; never a production dependency."""
4import pathlib
5import runpy
6import sys
7# Import torch from the supplied oracle path, never from this directory's test modules.
8sys.path=[p for p in sys.path if pathlib.Path(p).resolve()!=pathlib.Path(__file__).parent.resolve()]
9sys.path.insert(0,sys.argv[1])
10import torch
11print('REFERENCE torch',torch.__version__,'device=cpu hardware=NOT_RUN')
12torch.set_num_threads(1)
13x=torch.tensor([1.0,2.0],dtype=torch.bfloat16)
14print('DTYPE product/sum/epsilon/rsqrt/output',*(str(v.dtype) for v in (x*x,(x*x).sum(),(x*x).sum()+1e-6,torch.rsqrt((x*x).sum()+1e-6),x*torch.rsqrt((x*x).sum()+1e-6))))
15x=torch.arange(0x7f80,dtype=torch.int16).view(torch.bfloat16)
16a=x+1e-6
17full=(x.float()+1e-6).bfloat16()
18rounded=(x.float()+torch.tensor(1e-6,dtype=torch.bfloat16).float()).bfloat16()
19f=int((a.view(torch.int16)!=full.view(torch.int16)).sum())
20r=int((a.view(torch.int16)!=rounded.view(torch.int16)).sum())
21print('EPSILON all-positive-finite-BF16',x.numel(),'full-FP32-scalar-mismatches',f,'BF16-scalar-mismatches',r)
22print('EPSILON BF16 scalar bits',hex(int(torch.tensor(1e-6,dtype=torch.bfloat16).view(torch.int16))<<16))
23assert r==0 and f>0
24print('CONTROL unrounded-epsilon CAUGHT')
25if len(sys.argv)>2 and sys.argv[2]=='suite':
26 import base64
27 import struct
28 gdn=runpy.run_path(str(pathlib.Path(__file__).with_name('gdn.py')))
29 check=gdn['ref']['check']
30 scalar=torch.tensor([0x425e],dtype=torch.int16).view(torch.bfloat16)
31 cpu=torch.rsqrt(scalar)
32 correctly_rounded=torch.rsqrt(scalar.double()).bfloat16()
33 cpu_bits=int(cpu.view(torch.int16)[0])<<16
34 correct_bits=int(correctly_rounded.view(torch.int16)[0])<<16
35 interval=gdn['ibf16'](gdn['rsqbound'](gdn['finite'](0x425e0000)))
36 assert interval==(gdn['finite'](correct_bits),)*2
37 assert cpu_bits==0x3e0a0000 and correct_bits==0x3e090000
38 assert not interval[0]<=gdn['finite'](cpu_bits)<=interval[1]
39 print('OBSERVED ARM torch BF16 rsqrt input=425e0000 CPU=3e0a0000 FP64-rounded=3e090000 Decimal120+ISA interval=',interval)
40 print('CONTROL CPU-BF16-rsqrt-outside-ISA-envelope CAUGHT; CPU fallback bit parity is NOT claimed')
41 for args in gdn['QK_CASES']:
42 case=gdn['qk_fixture'](*args); memory=bytearray(base64.b64decode(case['memory']))
43 xp,op=(a[1] for a in case['args'])
44 x=torch.frombuffer(memory,dtype=torch.float32,count=4096,offset=xp).view(32,128).bfloat16()
45 variance=(x*x).sum(dim=-1,keepdim=True)+1e-6
46 cpu_inv=torch.rsqrt(variance)
47 # This is explicitly a correctly-rounded primitive reference, NOT the
48 # ARM BF16 torch fallback. Never widen the device oracle to admit it.
49 inv=torch.rsqrt(variance.double()).bfloat16()
50 print('OBSERVED CPU-rsqrt-vs-FP64-rounded differing-heads',int((cpu_inv!=inv).sum()))
51 normalized=(x*inv).float()
52 normalized[:16]=normalized[:16]*torch.tensor(struct.unpack('<f',struct.pack('<I',gdn['QSCALE']))[0])
53 for head in range(args[0]):
54 struct.pack_into('<128I',memory,op+head*512,*(b&0xffffffff for b in normalized[head].view(torch.int32).tolist()))
55 check(memory,case)
56 print('PASS torch-BF16-boundaries with FP64-rounded-rsqrt instrument',case['label'])
57 # Torch's library reduction tree is not the declared Omega accumulation order.
58 # Use independent Torch primitive operations in that explicitly declared order.
59 for kind in ('zero','no-beta','no-decay','dense'):
60 for head in range(3):
61 old,values,expected,out_expected=gdn['state_head'](head,kind)
62 def tensor(bits):
63 data=bytearray(struct.pack('<'+str(len(bits))+'I',*bits))
64 return torch.frombuffer(data,dtype=torch.float32).clone()
65 state=tensor(old).view(128,128)
66 value=tensor(values)
67 decay,beta=tensor(gdn['state_scalars'](head,kind))
68 key=tensor([gdn['qk_value'](head//3,r,False) for r in range(128)])
69 query=tensor([gdn['qk_value'](head//3,r,True) for r in range(128)])
70 state=state*decay
71 kv=torch.zeros(128,dtype=torch.float32)
72 for r in range(128): kv=kv+state[r]*key[r]
73 delta=(value-kv)*beta
74 output=torch.zeros(128,dtype=torch.float32)
75 for r in range(128):
76 state[r]=state[r]+key[r]*delta
77 output=output+state[r]*query[r]
78 output=output.bfloat16().float()
79 actual=[b&0xffffffff for b in state.flatten().view(torch.int32).tolist()]
80 out_actual=[b&0xffffffff for b in output.view(torch.int32).tolist()]
81 assert actual==expected and out_actual==out_expected,(kind,head)
82 print('PASS torch-recurrent-rounding-boundaries kind='+kind+' heads=3 every-state/output-bit')