File size: 14,023 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
"""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())