115 lines
9.4 KiB
Python
115 lines
9.4 KiB
Python
"""Independent STRA161 offline integer/decode oracle; imports no candidate code."""
|
|
import hashlib, json, re, struct
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parents[4]
|
|
OUT=Path(__file__).with_name('fixtures.json')
|
|
MULT=[23703573157769,20109073645365,8052911324071]
|
|
VOCAB=[20000003,20000023,20000033,20000047,20000059,20000063,20000069,20000077,20000081,20000093,20000107,20000147,20000153,20000159,20000161,20000171]
|
|
OFF=[0,20000003,40000026,60000059,80000106,100000165,120000228,140000297,160000374,180000455,200000548,220000655,240000802,260000955,280001114,300001275]
|
|
EOS=248044
|
|
MASK=(1<<64)-1
|
|
CODE=[-127,-104,-83,-65,-49,-35,-22,-10,1,13,25,38,53,69,89,113]
|
|
def mixed(ctx):
|
|
v=0
|
|
for x,m in zip(ctx,MULT):v^=(x*m)&MASK
|
|
return v
|
|
def rows(token,prev):
|
|
ctx=[token];cut=False
|
|
for t in reversed(prev):
|
|
cut=cut or t<0 or t==EOS
|
|
ctx.append(EOS if cut else t)
|
|
return [(mixed(ctx[:2 if h<8 else 3])%VOCAB[h])+OFF[h] for h in range(16)]
|
|
def words(raw):
|
|
out=[]
|
|
for b in range(5):
|
|
d=struct.unpack('<e',raw[b*18:b*18+2])[0]
|
|
qs=raw[b*18+2:b*18+18]
|
|
out.extend(struct.unpack('<I',struct.pack('<f',d*CODE[q&15]))[0] for q in qs)
|
|
out.extend(struct.unpack('<I',struct.pack('<f',d*CODE[q>>4]))[0] for q in qs)
|
|
return out
|
|
# An independently generated original-source oracle predating this candidate.
|
|
inc=(ROOT/'engine/strata/src/kernels/ple_oracle_vectors.inc').read_text()
|
|
cases=[]
|
|
for c in range(6):
|
|
def arr(name):return [int(x) for x in re.search(r'case'+str(c)+'_'+name+r'\[\d+\] = \{(.*?)\};',inc,re.S).group(1).replace('\n','').split(',') if x.strip()]
|
|
ts,pv,want=arr('tokens'),arr('prev'),arr('rows')
|
|
for i,t in enumerate(ts):
|
|
# The retained source parity harness passes these original literal predecessor arrays unchanged.
|
|
prev=pv[2*i:2*i+2]; got=rows(t,prev)
|
|
assert got==want[16*i:16*i+16],(c,i,got,want[16*i:16*i+16])
|
|
cases.append({'name':f'original-{c}-{i}','token':t,'prev_oldest_first':prev,'rows':got})
|
|
for name,t,prev in [('zero',0,[0,0]),('oldest-null',8,[-1,7]),('newest-null',8,[7,-1]),('oldest-eos',9,[EOS,7]),('newest-eos',9,[7,EOS]),('tokenizer-eos-not-ple-eos',9,[7,248046]),('current-eos-keeps-context',EOS,[11,22]),('max-vocabulary',248319,[248318,248319])]:cases.append({'name':name,'token':t,'prev_oldest_first':prev,'rows':rows(t,prev)})
|
|
# Finite synthetic encoded rows, no actual model payload. Exact dyadic scale*integer product.
|
|
decode=[]
|
|
for name,scales in [('split-nibbles',[0x3c00,0xbc00,0x3800,1,0x8000]),('scale-domains',[0,0x0400,0x7bff,0xfbff,0x3555])]:
|
|
raw=b''.join(struct.pack('<H',s)+bytes(((15-j)<<4)|j for j in range(16)) for s in scales)
|
|
decode.append({'name':name,'row_hex':raw.hex(),'expected_f32_words':words(raw)})
|
|
source_paths=['engine/strata/src/kernels/ngram.cpp','engine/strata/src/kernels/ple_oracle_vectors.inc','crates/model-format/src/qwen4exp.rs','engine/strata/src/kernels/cuda/ple.cu','engine/strata/src/kernels/cuda/native_ple_postops.cu']
|
|
data={'schema':'stra161-independent-reference-v1','provenance':'Original source and preexisting independent PLE literal vectors, no candidate imports','sources':{p:hashlib.sha256((ROOT/p).read_bytes()).hexdigest() for p in source_paths},'multipliers':MULT,'vocab_sizes':VOCAB,'offsets':OFF,'ple_eos':EOS,'tokenizer_eos':248046,'hash_cases':cases,'raw_u64_wrap_case':{'context':[MASK,MASK-1,MASK-2],'mixed2':mixed([MASK,MASK-1]),'mixed3':mixed([MASK,MASK-1,MASK-2]),'scope':'recurrence arithmetic only; invalid token ids must still refuse before read'},'decode_cases':decode,'row_ranges':[{'row':r,'start':90*r,'end':90*(r+1)} for r in [0,1,320001535]],'invalid_token_ids':[-1,248320,4294967295],'invalid_row_ids':[320001536,(1<<64)-1],'float_qualification':'Pending chosen original upstream operation order; no fitted tolerance or CUDA parity claim'}
|
|
|
|
# CPU-only source-ordered scalar probes. Host libm identity is explicit; these are
|
|
# NOT CUDA expf/rsqrt approximations and cannot qualify installed-driver parity.
|
|
import ctypes, platform
|
|
libm=ctypes.CDLL(None)
|
|
for symbol,argc in [('sqrtf',1),('expf',1),('fmaf',3)]:
|
|
f=getattr(libm,symbol);f.restype=ctypes.c_float;f.argtypes=[ctypes.c_float]*argc
|
|
def f32(v):return struct.unpack('<f',struct.pack('<f',v))[0]
|
|
def word(v):return struct.unpack('<I',struct.pack('<f',v))[0]
|
|
def sigmoid(v):return f32(1.0/f32(1.0+libm.expf(f32(-v))))
|
|
def gate(s):
|
|
s=f32(s);mag=libm.sqrtf(max(abs(s),f32(1e-6)))
|
|
sign=float((s>0)-(s<0));return sigmoid(f32(sign*mag))
|
|
def silu(v):return f32(v/f32(1.0+libm.expf(f32(-v))))
|
|
def bf16(v):
|
|
i=word(v);return ((i+((i>>16)&1)+0x7fff)>>16)&0xffff
|
|
fp={'profile':'CPU source-ordered probes of default ple.cu(native_postops=false,native_bf16=false), NOT CUDA parity','host':platform.platform(),'libm':'current process C sqrtf/expf/fmaf via ctypes; Darwin libSystem','acceptance':{'integer_decode':{'abs':0,'rel':0,'ulp':0},'CPU_projection_norm_gate_broadcast_conv_residual':{'abs':0,'rel':0,'ulp':0,'scope':'exact frozen finite F32 words for these source-ordered CPU probes only; do not apply to a different reduction/libm/GPU backend'},'CUDA_floating_stages':'Unqualified: requires independently justified backend-specific bounds or source/order/compile equivalence; no guessed abs/rel/ULP'},'gate':[{'input_word':word(x),'expected_word':word(gate(x))} for x in [-1.,-1e-9,-0.,0.,1e-9,1.]],'bf16_round':[{'input_word':word(x),'expected_bf16':bf16(x)} for x in [0.,-0.,1.,1.+2**-8,1.+3*2**-8,-1.-2**-8]],'constant_norm':[],'conv':[],'residual_rival':{}}
|
|
for x,gamma in [(0.,1.),(1.,1.),(-1.,0.5),(0.25,-2.)]:
|
|
# 2560 repeated values: f32 square, double sum (exact on this fixture),
|
|
# double division, materialized F32 mean then F32 epsilon/sqrt/divide,
|
|
# source left-to-right x*scale*gamma.
|
|
mean=f32(float(f32(x*x))*2560/2560)
|
|
scale=f32(1.0/libm.sqrtf(f32(mean+f32(1e-6))))
|
|
fp['constant_norm'].append({'input_word':word(x),'gamma_word':word(gamma),'mean_word':word(mean),'scale_word':word(scale),'expected_word':word(f32(f32(x*scale)*gamma)),'columns':2560})
|
|
for h,current,taps in [([1.,2.,3.],4.,[0.5,-1.,2.,-0.25]),([-1.,0.,1.],-2.,[1.,0.5,-0.25,2.])]:
|
|
acc=0.
|
|
for x,w in zip(h+[current],taps):acc=libm.fmaf(w,x,acc)
|
|
fp['conv'].append({'history_rows':[0,3,6],'history_words':[word(x) for x in h],'current_word':word(current),'tap_words':[word(x) for x in taps],'tap_index':'k+4*channel','acc_word':word(acc),'silu_word':word(silu(acc))})
|
|
a=silu(1.);R=16777216.;g=-16777216.
|
|
fp['residual_rival']={'R_word':word(R),'gated_word':word(g),'conv_word':word(a),'default_left_word':word(f32(f32(R+g)+a)),'native_right_word':word(f32(R+f32(g+a)))}
|
|
|
|
def from_bf16(v):return struct.unpack('<f',struct.pack('<I',v<<16))[0]
|
|
def xor_reduce(v):
|
|
v=list(v)
|
|
for off in [16,8,4,2,1]:v=[f32(v[i]+v[i^off]) for i in range(32)]
|
|
return v
|
|
fp['projection']=[]
|
|
for name,entries in [('activation-rounding',[(0,1.+2**-8),(511,1.+3*2**-8),(512,-0.25),(2559,2.)]),('reduction-order',[(0,16777216.),(1,1.),(512,-16777216.),(2559,1.)])]:
|
|
x=[0.]*2560
|
|
for i,v in entries:x[i]=f32(v)
|
|
partial=[]
|
|
for t in range(256):
|
|
a=0.
|
|
for pair in range(t,1280,256):
|
|
a=libm.fmaf(1.,x[2*pair],a);a=libm.fmaf(1.,x[2*pair+1],a)
|
|
partial.append(a)
|
|
reduced=[xor_reduce(partial[j:j+32])[0] for j in range(0,256,32)]
|
|
key=xor_reduce(reduced+[0.]*24)[0]
|
|
value=f32(sum(from_bf16(bf16(v)) for v in x))
|
|
fp['projection'].append({'name':name,'columns':2560,'weights_default_bf16':0x3f80,'activation_default_word':0,'activation_nonzero':[[i,word(v)] for i,v in entries],'key_mmvf_block256_expected_word':word(key),'value_bf16_activation_double_expected_word':word(value)})
|
|
|
|
data['float_source_probes']=fp
|
|
OUT.write_text(json.dumps(data,indent=2)+'\n')
|
|
lines=['// Independent original-source literals frozen before STRA161 candidate.','// Generated offline by stra161_reference/reference.py; imports no candidate.','#![allow(dead_code)]','pub struct HashCase { pub name: &\'static str, pub token: u32, pub prev: [i32; 2], pub rows: [u32; 16] }','pub const HASH_CASES: &[HashCase] = &[']
|
|
for c in cases:lines.append(' HashCase { name: '+json.dumps(c['name'])+', token: '+str(c['token'])+', prev: '+str(c['prev_oldest_first'])+', rows: '+str(c['rows'])+' },')
|
|
lines+= ['];','pub struct DecodeCase { pub name: &\'static str, pub encoded: [u8; 90], pub expected_words: [u32; 160] }','pub const DECODE_CASES: &[DecodeCase] = &[']
|
|
for c in decode:lines.append(' DecodeCase { name: '+json.dumps(c['name'])+', encoded: '+str(list(bytes.fromhex(c['row_hex'])))+', expected_words: '+str(c['expected_f32_words'])+' },')
|
|
lines += ['];','pub const RAW_WRAP_CONTEXT: [u64; 3] = '+str(data['raw_u64_wrap_case']['context'])+';','pub const RAW_WRAP_MIXED: [u64; 2] = '+str([data['raw_u64_wrap_case']['mixed2'],data['raw_u64_wrap_case']['mixed3']])+';','// Raw wrap fixture is primitive-only: invalid token IDs must still refuse.','// Gate probes: CPU host C libm only; not installed CUDA proof.','pub const GATE_CASES: &[(u32, u32)] = &[']
|
|
for c in fp['gate']:lines.append(f" ({c['input_word']}, {c['expected_word']}),")
|
|
lines+= ['];','pub const BF16_ROUND_CASES: &[(u32, u16)] = &[']
|
|
for c in fp['bf16_round']:lines.append(f" ({c['input_word']}, {c['expected_bf16']}),")
|
|
lines += ['];','pub const RESIDUAL_RIVAL: [u32; 5] = '+str(list(fp['residual_rival'].values()))+';']
|
|
rs=OUT.parent.parent/'stra161_reference.rs';rs.write_text('\n'.join(lines)+'\n')
|
|
import subprocess
|
|
subprocess.run(['rustfmt','--edition','2024',str(rs)],check=True)
|
|
print(json.dumps({'frozen_hash_cases':len(cases),'independent_original_cases':19,'json_sha':hashlib.sha256(OUT.read_bytes()).hexdigest(),'rust_sha':hashlib.sha256(rs.read_bytes()).hexdigest(),'gate':fp['gate'],'residual_rival':fp['residual_rival']}))
|