REAX-1.4 / engine /bench /native_gemma_reference.py
decisionmodels's picture
Engine tree (REAX Engine reax14-release-20261126, 2cccfee) and run instructions
a7e82fd verified
Raw History Blame Contribute Delete
14 kB
"""Independent HF reference for pinned Sieve / OneJev native text serving.
Author source is never imported or executed. The renderer is a second transcription
of the cited format contract; Sieve attention uses HF dense eager/SDPA masks rather
than the engine's compact attention callback. Public P300 only, c1, all softcapped
label projections fp32. Full-fp32 loads can offload layers to CPU on one 96 GB GPU.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
from pathlib import Path
import time
# The safe metadata reader implements only literal pickletools opcodes; no unpickling.
from engine.contracts.safe_literals import read_literal_head
def text(v, depth=0):
if v is None:
return ''
if isinstance(v, (str, float, int, bool)):
return str(v)
pad = ' ' * depth
if isinstance(v, list):
return '\n'.join(pad + '- ' + text(x, depth + 1).lstrip() for x in v)
parts = []
for k, x in v.items():
parts.append(pad + k + (':\n' + text(x, depth + 1) if isinstance(x, (list, dict)) else ': ' + text(x)))
return '\n'.join(parts)
def render_request(tok, model_dir, family, state, questions):
"""qid -> (keys, [(ids, prefix boundary, rotation)], token ids, temperature)."""
for q in questions.values():
kind, c = q.get('type'), q.get('criteria')
if kind == 'choice' and (not isinstance(c, dict) or not c):
raise ValueError('choice criteria must be a nonempty object')
if kind == 'noul' and c is not None and not isinstance(c, dict):
raise ValueError('noul criteria must be an object')
if kind == 'score' and (not isinstance(c, list) or len(c) < (2 if family == 'sieve' else 1)):
raise ValueError('score criteria must be an ordered list')
if kind not in ('choice', 'score', 'noul'):
raise ValueError('unknown question type')
if family == 'sieve' and q.get('instructions') is None:
raise ValueError('Sieve instructions are required')
enc = lambda s: tok.encode(s, add_special_tokens=False)
if family == 'sieve':
meta = read_literal_head(Path(model_dir) / 'head.pt')
fmt = meta['format']
special = ['<pad>', '<eos>', '<bos>', '<unk>', '<mask>', '<|tool>', '<tool|>', '<|tool_call>', '<tool_call|>',
'<|tool_response>', '<tool_response|>', '<|"|>', '<|think|>', '<|channel>', '<channel|>', '<|turn>',
'<turn|>', '<|image>', '<|audio>', '<|image|>', '<|audio|>', '<image|>', '<audio|>', '<|video|>']
pattern = re.compile('|'.join(re.escape(v) for v in sorted(special, key=len, reverse=True)))
data = lambda s: enc(pattern.sub(lambda m: '<¦' + m.group()[1:], s))
instructions = [data(text(q['instructions'])) for q in questions.values()]
prefix = enc('<bos><|turn>system\n' + fmt['system'] + '<turn|>\n<|turn>user\n') + enc(fmt['header'])
for ins in instructions:
prefix.extend(enc('- ') + ins + enc('\n'))
prefix += enc('\nContext:\n') + data(text(state))
result = {}
for (qid, q), ins in zip(questions.items(), instructions):
kind, c = q['type'], q.get('criteria')
if kind == 'choice':
keys = list(c)
descriptions = [k if v is None or v == '' else k + ': ' + text(v) for k, v in c.items()]
elif kind == 'noul':
keys, c = ['false', 'true'], c or {}
descriptions = [word if c.get(k) is None or c.get(k) == '' else word + ': ' + text(c[k])
for word, k in [('no', 'false'), ('yes', 'true')]]
else:
keys, descriptions = [str(i) for i in range(len(c))], [text(x) for x in c]
if len(keys) > len(fmt['label_ids']):
raise ValueError('more options than readout labels')
arms = []
shift = len(keys)//2 if kind == 'choice' and len(keys)>1 and q.get('permute') is not False else 0
for rot in [0, shift] if shift else [0]:
ids = prefix + enc('\n\nQuestion: ') + ins + enc('\nOptions:\n')
for j, desc in enumerate(descriptions[rot:] + descriptions[:rot]):
ids += enc('(') + [fmt['label_ids'][j]] + enc(') ') + data(desc) + enc('\n')
ids += enc(fmt['tail'])
arms.append((ids, len(prefix) if len(questions) > 1 else 0, rot))
n = len(keys)
bucket = '2' if n<=2 else '3-4' if n<=4 else '5-9' if n<=9 else '10-25' if n<=25 else '26+'
empty = state is None or isinstance(state,str) and not state.strip() or isinstance(state,(dict,list)) and not state
sk = 'empty' if empty else 'struct' if isinstance(state,(dict,list)) else 'text'
table = (meta.get('temperatures') or {}).get('table', {})
t = next((table[k] for k in [f'{kind}:{bucket}:{sk}',f'{kind}:{bucket}',kind] if k in table),meta['temperature'])
result[qid] = (keys, arms, fmt['label_ids'][:n], t)
return result
cfg = json.loads((Path(model_dir)/'decision_config.json').read_text())
def entry(v):
return '' if v is None else v.strip() if isinstance(v,str) else json.dumps(v,ensure_ascii=False,indent=2)
def head(q):
c, kind = q.get('criteria'), q['type']
if kind == 'noul':
c = c or {}
ins = entry(q.get('instructions')) or 'Is the statement true, or is the answer to the question yes?'
opts = []
for lab,key,word,default in [('A','true','yes','the statement is true / the answer is yes'),
('B','false','no','the statement is false / the answer is no')]:
d = entry(c[key]) if c.get(key) is not None else default
opts.append(lab+'. '+word+(': '+d if d else ''))
elif kind == 'choice':
ins = entry(q.get('instructions')) or 'Which option applies to the state?'
opts = [lab+'. '+k+(': '+entry(v) if entry(v) else '') for lab,(k,v) in zip(cfg['labels'],c.items())]
else:
ins = entry(q.get('instructions')) or 'Which level describes the state?'
opts = [lab+'. level '+str(i)+(': '+entry(v) if entry(v) else '') for i,(lab,v) in enumerate(zip(cfg['labels'],c))]
return ('Rate the state: ' if kind=='score' else 'Question: ')+ins+'\nOptions:\n'+'\n'.join(opts)
headers = []
for q in questions.values():
h = head(q)
if h not in headers:headers.append(h)
st = '' if state is None else state if isinstance(state,str) else json.dumps(state,ensure_ascii=False,separators=(',',':'))
body = '\n\n'.join(s for s in headers+[st] if s)
result = {}
for qid,q in questions.items():
keys = ['true','false'] if q['type']=='noul' else list(q['criteria']) if q['type']=='choice' else [str(i) for i in range(len(q['criteria']))]
n = len(keys)
prompt = body+ ('\n\n' if body else '')+head(q)+'\n'+('Answer with one letter.' if n<=26 else 'Answer with one label.')
prompt = '<bos><|turn>user\n'+prompt.strip()+'<turn|>\n<|turn>model\n<|channel>thought\n<channel|>'
ids = enc(prompt)
if n>len(cfg['labels']) or len(ids)>cfg['max_prompt_tokens']:raise ValueError('native template limit exceeded')
result[qid] = (keys,[(ids,0,0)],[enc(lab)[0] for lab in cfg['labels'][:n]],1.)
return result
def render_check(model_dir, family, data_dir, out):
from transformers import AutoTokenizer
from bench import sets
from engine.contracts.native_gemma import NativeEncoder
tok = AutoTokenizer.from_pretrained(model_dir,local_files_only=True,trust_remote_code=False)
eng = NativeEncoder(model_dir,family,tok)
items = sets.load('p300',data_dir)
mismatch, refused, n = [], [], 0
digest = hashlib.sha256()
for it in items:
qs = {it.qid:it.question}
try:
reference=render_request(tok,model_dir,family,it.state,qs)
candidate=eng.encode_request(it.state,qs)
except (ValueError,TypeError,KeyError) as exc:
refused.append({'key':it.key,'error':str(exc)});continue
r=reference[it.qid];e=candidate[it.qid].payload
expected=[(a.ids,a.prefix_tokens,a.rotate) for a in e.arms]
if (r[1],r[2],r[3]) != (expected,e.label_ids,e.temperature):mismatch.append(it.key)
digest.update(json.dumps(r[1]).encode());n+=1
report={'family':family,'items':len(items),'rendered':n,'refused':refused,'mismatches':mismatch,'digest':digest.hexdigest()}
Path(out).write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
return bool(mismatch)
def hf_run(a):
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer
from safetensors import safe_open
from bench import sets
tok=AutoTokenizer.from_pretrained(a.model_dir,local_files_only=True,trust_remote_code=False)
opts={'device_map':{'':a.device}}
if a.cpu_offload:
if a.dtype!='float32':raise ValueError('offload intended for full-fp32 reference')
opts={'device_map':'auto','max_memory':{0:'80GiB','cpu':'160GiB'}}
full=AutoModelForCausalLM.from_pretrained(a.model_dir,dtype=getattr(torch,a.dtype),attn_implementation=a.attention,
local_files_only=True,trust_remote_code=False,use_safetensors=True,**opts).eval()
lm=full.model
for attr in ['language_model','text_model']:
if hasattr(lm,attr):lm=getattr(lm,attr);break
index=json.loads((Path(a.model_dir)/'model.safetensors.index.json').read_text())['weight_map']
key=next(k for k in index if k.endswith('embed_tokens.weight'))
rows={}
def weights(token_ids):
k=tuple(token_ids)
if k not in rows:
with safe_open(str(Path(a.model_dir)/index[key]),framework='pt',device='cpu') as f:
view=f.get_slice(key)
rows[k]=torch.cat([view[i:i+1] for i in token_ids]).float().to(a.device)
return rows[k]
items=sets.load('p300',a.data_dir)
succeeded=refused=0;t0=time.perf_counter()
with open(a.out,'w') as output,torch.inference_mode():
for it in items:
start=time.perf_counter()
try:
q=it.question
keys,arms,label_ids,temp=render_request(tok,a.model_dir,a.family,it.state,{it.qid:q})[it.qid]
zs=[]
for ids,prefix,rot in arms:
n=len(ids);masks=None
if a.family=='sieve':
i=torch.arange(n,device=a.device)
qi,ki=i[:,None],i[None,:]
global_mask=torch.ones((n,n),dtype=torch.bool,device=a.device) if not prefix else (ki<prefix)|(qi>=prefix)
local=(ki<=qi)&((qi-ki)<lm.config.sliding_window)
masks={k:torch.where(v[None,None],0.,torch.finfo(getattr(torch,a.dtype)).min).to(getattr(torch,a.dtype))
for k,v in [('full_attention',global_mask),('sliding_attention',local)]}
h=lm(input_ids=torch.tensor([ids],device=a.device),attention_mask=masks,use_cache=False).last_hidden_state[0,-1]
z=h.to(a.device).float()@weights(label_ids).T
c=float(lm.config.final_logit_softcapping or 0)
if c:z=c*torch.tanh(z/c)
zs.append(torch.roll(z,rot))
z=zs[0] if len(zs)==1 else sum(torch.log_softmax(z,-1) for z in zs)/2
if a.family=='onejev':
values=[v/temp for v in z.cpu().tolist()]; peak=max(values)
masses=[math.exp(v-peak) for v in values];p=[v/sum(masses) for v in masses]
else:
p=torch.softmax(z/temp,-1).cpu().tolist()
probs=dict(zip(keys,p))
if q['type']=='noul':answer={'type':'noul','noul':probs['true']}
elif q['type']=='choice':answer={'type':'choice','choice':max(probs,key=probs.get),'confidence':(max(p)-1/len(p))/(1-1/len(p)) if len(p)>1 else 1.,'probabilities':probs}
else:
mode=max(range(len(p)),key=p.__getitem__);d=sum(abs(i-(len(p)-1)/2) for i in range(len(p)))/len(p)
answer={'type':'score','score':sum(i*v for i,v in enumerate(p)),'confidence':max(0,1-sum(v*abs(i-mode) for i,v in enumerate(p))/d) if d else 1.,'probabilities':probs}
record={'key':it.key,'http':200,'ms':(time.perf_counter()-start)*1000,'answer':answer,'error':None};succeeded+=1
except (ValueError,TypeError,KeyError) as exc:
record={'key':it.key,'http':422,'ms':0,'answer':None,'error':str(exc)};refused+=1
output.write(json.dumps(record)+'\n');output.flush()
report={'family':a.family,'dtype':a.dtype,'attention':a.attention,'answered':succeeded,'refused':refused,'seconds':time.perf_counter()-t0,
'torch':torch.__version__,'full_class':type(full).__name__,'offload':a.cpu_offload}
Path(a.out+'.info.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('command',choices=['render-check','hf-run'])
ap.add_argument('--family',choices=['sieve','onejev'],required=True)
ap.add_argument('--model-dir',required=True)
ap.add_argument('--data-dir',required=True)
ap.add_argument('--out',required=True)
ap.add_argument('--dtype',choices=['bfloat16','float32'],default='bfloat16')
ap.add_argument('--attention',choices=['sdpa','eager'],default='sdpa')
ap.add_argument('--device',default='cuda:0')
ap.add_argument('--cpu-offload',action='store_true')
a=ap.parse_args()
if a.command=='render-check':return render_check(a.model_dir,a.family,a.data_dir,a.out)
return hf_run(a)
if __name__=='__main__':
raise SystemExit(main())