File size: 13,640 Bytes
a7e82fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/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)<len(asked): lines.append(f"(and {len(asked)-len(shown)} more questions)")
        block="\n".join(lines)+"\n\nState:\n"+(state.strip() or "(empty)")
        user=("Read the questions and the state below, then decide the question at the end. "
              "Reply with the letter of one option.\n\n"+block)
        if len(enc(head+user+"\n\n"))<=3000:
            user += "\n\nRead the questions and the state again.\n\n"+block
        prefix=enc(head+user+"\n\n")
    result={}
    for qid,q in questions.items():
        ks,vs=options(q,family)
        if not 0<len(ks)<=len(codes): raise ValueError("option count exceeds native code book")
        if family=="turion" and len(ks)==1:
            result[qid]=[[]]
            continue
        instruction=asked[list(questions).index(qid)]
        if family=="sigma":
            suffix=f"Question: {instruction}\nOptions:\n"+"\n".join(f"{c}. {v}" for c,v in zip(codes,vs))
            result[qid]=[prefix+enc(suffix.rstrip()+tail+"Answer:")]
            continue
        hint={"choice":"Choose the single best option.","noul":"Answer yes or no.",
              "score":"Choose the score that fits best (0 = lowest, 5 = highest)."}[q["type"]]
        def one(keys,values):
            header="\n".join("- "+x.strip() for x in asked if x and x.strip()) or "- "+(instruction.strip() or "(no instructions)")
            lines=[f"{c}) {k}: {v}" if v and v.strip()!=k.strip() else f"{c}) {k}" for c,k,v in zip(codes,keys,values)]
            user=(f"Questions about this state:\n{header}\n\nState:\n{state if state.strip() else '(empty)'}\n\n"
                  f"Question:\n{instruction.strip() or '(no instructions)'}\n{hint}\n\nOptions:\n"+"\n".join(lines)+
                  f"\n\nAnswer with the code of one option ({codes[0]} to {codes[len(keys)-1]}).")
            if len(questions)==1 and len(user)<=12000: user += "\n\nThe same request again:\n\n"+user
            return enc(chat([{"role":"system","content":"You are a decision engine. Read the state, then answer the question by choosing exactly one option. Reply with the option code only."},
                             {"role":"user","content":user}]))
        result[qid]=[one(["yes","no"],["",""])] if q["type"]=="noul" else [one(ks,vs)]
        if len(questions)==1 and q["type"]=="choice" and len(ks)==2:
            result[qid].append(one(ks[::-1],vs[::-1]))
    return result


def probabilities(values, temperature):
    values=[float(v)/temperature for v in values]
    exps=[math.exp(v-max(values)) for v in values]
    return [v/sum(exps) for v in exps]


def frozen_code_logits(model, input_ids, code_ids, attention_mask=None, family="turion"):
    """Author HF Turion path: fp32 LM rows @ final normalized state; scale and softcap in fp32.

    Sigma uses the full HF LM output, including its dtype rounding. Only the last position is
    evaluated; no full sequence x vocabulary logits allocation. Standard transformers only.
    """
    import torch
    if family=="sigma":
        return model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False,
                     logits_to_keep=1).logits[0,-1,code_ids].float()
    decoder=model.get_decoder()
    hs=decoder(input_ids=input_ids, attention_mask=attention_mask, use_cache=False).last_hidden_state
    h=hs[0,-1].float()
    head=model.get_output_embeddings().weight[code_ids].float().to(h.device)
    cfg=getattr(model.config,"text_config",model.config)
    z=head @ h
    z*=float(getattr(cfg,"logit_scale",1.0) or 1.0)
    cap=getattr(cfg,"final_logit_softcapping",None)
    return float(cap)*torch.tanh(z/float(cap)) if cap else z


def answer(q, family, probs):
    keys,_=options(q,family)
    dist=dict(zip(keys,probs))
    result={"type":q["type"],"probabilities":dist,"confidence":max(probs)}
    if q["type"]=="noul": result["noul"]=dist["true"]
    elif q["type"]=="score": result["score"]=sum(i*p for i,p in enumerate(probs))
    else: result["choice"]=max(dist,key=dist.get)
    return result


def groups(args):
    from bench import sets
    rows=sets.load(args.set,args.data_dir,args.limit,args.data_file)
    by_req={}
    for row in rows: by_req.setdefault(row.req or row.key,[]).append(row)
    return by_req.values()


def main(argv=None):
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('command',choices=['render-check','hf-run'])
    p.add_argument('--family',choices=['turion','sigma'],required=True)
    p.add_argument('--model-dir',required=True)
    p.add_argument('--set',default='p300')
    p.add_argument('--data-dir');p.add_argument('--data-file');p.add_argument('--limit',type=int,default=0)
    p.add_argument('--dtype',choices=['bfloat16','float32'],default='bfloat16')
    p.add_argument('--attn',choices=['sdpa','eager'],default='sdpa')
    p.add_argument('--device',default='cuda:0');p.add_argument('--cpu-offload',action='store_true')
    p.add_argument('--gpu-memory',default='72GiB');p.add_argument('--cpu-memory',default='90GiB')
    p.add_argument('--max-input-tokens',type=int);p.add_argument('--out',required=True)
    args=p.parse_args(argv)
    from transformers import AutoTokenizer
    tok=AutoTokenizer.from_pretrained(args.model_dir,trust_remote_code=False)
    codes,code_ids=codebook(tok,args.family)
    cap=args.max_input_tokens or (65536 if args.family=='turion' else 131072)
    engine=None;model=None
    if args.command=='render-check':
        from engine.backends.turion_sigma import NativeEncoder
        engine=NativeEncoder(tok,args.family,args.model_dir,cap)
    else:
        import torch, transformers
        torch.set_num_threads(4)
        if args.dtype == 'float32':
            # The adjudicator must use actual IEEE fp32 matmuls, not a TF32 shortcut.
            torch.set_float32_matmul_precision('highest')
            torch.backends.cuda.matmul.allow_tf32 = False
            torch.backends.cudnn.allow_tf32 = False
        kwargs=dict(dtype=getattr(torch,args.dtype),attn_implementation=args.attn,trust_remote_code=False)
        if args.cpu_offload:
            kwargs.update(device_map='auto',max_memory={0:args.gpu_memory,'cpu':args.cpu_memory},offload_buffers=True)
        else: kwargs['device_map']={'':args.device}
        # Gemma 4 multimodal checkpoint, official transformers class; no repo code.
        from transformers import AutoModelForImageTextToText
        model=AutoModelForImageTextToText.from_pretrained(args.model_dir,**kwargs).eval()
    report={'family':args.family,'command':args.command,'rendered':0,'refused':0,'mismatches':0,'dtype':args.dtype,'attn':args.attn}
    digest=hashlib.sha256();started=time.time()
    mode='w'
    with open(args.out,mode) as output:
        for rows in groups(args):
            qs={row.qid:row.question for row in rows}
            try:
                prompts=rendered(tok,args.family,rows[0].state,qs,codes)
                if any(len(ids)>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())