#!/usr/bin/env python3 """Independent HF reference for pinned Turion v2 / Sigma v5 (no author-code imports). Commands: render-check (CPU) or hf-run (GPU/disposable pod). P300 score criteria lists are translated to numeric-key mappings before rendering (a REAX extension; the pinned DI kit has only choice/noul). Native choice/noul requests are unchanged. Full fp32 uses CPU offload when requested: a 31B fp32 decoder exceeds a 96GB GPU. It is never replaced by a 'fp32 head only' arm. Author code is needed only for a separate on-pod reference cross-check, not by this script. """ from __future__ import annotations import argparse import hashlib import itertools import json import math from pathlib import Path import string import time TEMPS = {"choice": 1.1796636220762406, "noul": 1.1812733428401507, "score": 1.1213598082322136} def serial(v): return "" if v is None else v if isinstance(v, str) else json.dumps(v, ensure_ascii=False) def native_question(q): q = dict(q) if q.get("type") == "score" and isinstance(q.get("criteria"), list): q["criteria"] = {str(i): value for i,value in enumerate(q["criteria"])} return q def options(q, family): q = native_question(q) t = q.get("type", "choice") c = q.get("criteria") if t == "noul": return ["true", "false"], ["yes", "no"] if family == "turion" else [serial((c or {}).get(k)) or v for k,v in (("true","Yes"),("false","No"))] if isinstance(c, dict): ks = list(c) return ks, [serial(c[k]) if family == "turion" else serial(c[k]) or k for k in ks] if family == "turion" and t == "choice" and isinstance(c, list): keys, values = [], [] for value in c: if isinstance(value, dict): keys.append(str(value.get("key") or value.get("id") or value.get("name"))) values.append(serial(value.get("desc") or value.get("description") or "")) else: keys.append(str(value)); values.append("") return keys, values if family == "turion" and t == "score" and not c: return [str(i) for i in range(6)], [""]*6 raise ValueError("native criteria must be a mapping") def codebook(tok, family, limit=255): codes, ids = [], [] words = set("AM AN AS AT BE BY DO GO HE HI IF IN IS IT ME MY NO OF OH OK ON OR OX SO TO UP US WE YE YO".split()) prefix = tok.encode("Answer:", add_special_tokens=False) for code in list(string.ascii_uppercase) + [a+b for a in string.ascii_uppercase for b in string.ascii_uppercase]: if family == "turion": enc = tok.encode(code, add_special_tokens=False) valid = code not in words and len(enc)==1 else: enc = tok.encode("Answer: "+code, add_special_tokens=False) valid = len(enc)==len(prefix)+1 and enc[:-1]==prefix if valid and enc[-1] not in ids: codes.append(code); ids.append(enc[-1]) if len(ids)==limit: return codes, ids raise ValueError("not enough native option codes") def rendered(tok, family, state, questions, codes): """-> {qid: [first_ids, optional_reversed_ids]}; independently restates author prompt equations.""" state = serial(state) questions = {qid:native_question(q) for qid,q in questions.items()} asked = [serial(q.get("instructions") or q.get("question") or "") if family=="turion" else serial(q.get("instructions")) for q in questions.values()] enc = lambda text: tok.encode(text, add_special_tokens=False) def chat(messages): return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False) if family == "sigma": mark = "\ue000decision-prompt\ue000" head, tail = chat([{"role":"user","content":mark}]).split(mark) per = max(16000//max(len(asked),1),200) shown = asked[:16000//per] lines = ["Questions about this state:"] for i,q in enumerate(shown,1): q=q.strip() if len(q)>per: q=q[:per].rstrip()+"…" first,*rest=q.split("\n") lines.append(f"{i}. {first}") lines.extend(" "+line if line.strip() else "" for line in rest) if len(shown)cap for arms in prompts.values() for ids in arms): raise ValueError('maximum context length exceeded') actual=engine.encode_request(rows[0].state,qs) if engine else None except ValueError as exc: for row in rows: if engine is None: output.write(json.dumps({'key':row.key,'http':422,'ms':0,'answer':None,'error':str(exc)})+'\n') report['refused']+=1 continue for row in rows: arms=prompts[row.qid] keys,_=options(row.question,args.family) if engine: item=actual[row.qid].payload mine=[item.ids]+([item.reverse_ids] if item.reverse_ids is not None else []) report['mismatches']+=mine!=arms else: import torch t=time.perf_counter();dists=[] temp=TEMPS[row.qtype] if args.family=='turion' else 1.0 for ids in arms: if args.family=='turion' and len(keys)==1: dists.append([1.0]);continue device=model.get_input_embeddings().weight.device x=torch.tensor([ids],device=device) with torch.inference_mode(): values=frozen_code_logits(model,x,code_ids[:len(keys)],family=args.family).double().cpu().tolist() dists.append(probabilities(values,temp)) probs=dists[0] if len(dists)==1 else [(a+b)/2 for a,b in zip(dists[0],dists[1][::-1])] output.write(json.dumps({'key':row.key,'http':200,'ms':1000*(time.perf_counter()-t), 'answer':answer(row.question,args.family,probs),'error':None})+'\n');output.flush() digest.update(json.dumps(arms).encode());report['rendered']+=1 report.update(seconds=round(time.time()-started,2),ids_sha256=digest.hexdigest()) if model is not None: report.update(torch=torch.__version__,transformers=transformers.__version__) Path(args.out+'.info.json').write_text(json.dumps(report,indent=1)+'\n') if engine: Path(args.out).write_text(json.dumps(report,indent=1)+'\n') print(json.dumps(report));return int(bool(report['mismatches'])) if __name__=='__main__': raise SystemExit(main())