"""Qwen3 híbrido, tres condiciones MATH por lotes vLLM, guardado por problema."""
import argparse
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import random
import time
os.environ.setdefault('VLLM_NO_USAGE_STATS','1')
os.environ.setdefault('DO_NOT_TRACK','1')
os.environ.setdefault('VLLM_WORKER_MULTIPROC_METHOD','spawn')
os.environ.setdefault('VLLM_USE_V2_MODEL_RUNNER','0')
os.environ.setdefault('VLLM_USE_FLASHINFER_SAMPLER','0')
from transformers import AutoTokenizer,GenerationConfig
import math_eval
from math_eval import grade

REV='70d244cc86ccca08cf5af4e1e306ecf908b1ad5e'
DATA_REV='6e4ed1a2a79af7d8630a6b768ec859cb5af4d3be'
DATA_SHA='35dc41080a3680858b27fa7e0533d2d547825316fc5dafe5d316f4ccc5a06132'
CONDITIONS={'sin_pensamiento':None,'pensamiento_256':256,'pensamiento_1024':1024}
WEIGHTS={'model-00001-of-00002.safetensors':'169ad53ec313c3a34b06c0809216e4fc072cce444a5d4ff2b59690d064130ed5',
         'model-00002-of-00002.safetensors':'912becff8d60672aa8628ef08c05898d9adf17c2ad4ae3caf99b065622fdeff9'}

def digest(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
    return h.hexdigest()

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--model-path',required=True);ap.add_argument('--data',required=True);ap.add_argument('--output',required=True)
    ap.add_argument('--count',type=int,default=200);ap.add_argument('--answer-tokens',type=int,default=256)
    ap.add_argument('--batch',type=int,default=4);ap.add_argument('--kv-cache-mib',type=int,default=1024)
    ap.add_argument('--gpu-memory-utilization',type=float,default=.55);ap.add_argument('--eager',action='store_true')
    args=ap.parse_args();base=Path(args.model_path);data=Path(args.data);out=Path(args.output)
    if base.name!=REV or digest(data)!=DATA_SHA or not 1<=args.count<=200 or args.batch<1 or args.answer_tokens<1 or args.kv_cache_mib<1:
        ap.error('Modelo, datos o parámetros inválidos')
    rows=[json.loads(s) for s in data.read_text(encoding='utf8').splitlines() if s.strip()][:args.count]
    if len(rows)!=args.count:raise ValueError('Datos insuficientes')
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True)
    close=tok.encode('</think>',add_special_tokens=False)
    opening=tok.encode('<think>',add_special_tokens=False)
    if len(close)!=1 or len(opening)!=1:raise ValueError('El backend requiere tokens individuales de apertura y cierre')
    eos=GenerationConfig.from_pretrained(base,local_files_only=True).eos_token_id
    eos_ids=set(eos if isinstance(eos,list) else [eos])|{tok.eos_token_id}
    weights={name:digest(base/name) for name in WEIGHTS}
    if weights!=WEIGHTS:raise ValueError('Los pesos no coinciden con la revisión fijada')
    protocol={'revision':REV,'weights':weights,'data_revision':DATA_REV,'data_sha256':DATA_SHA,
              'model_metadata_sha256':{name:digest(base/name) for name in
                                       ('config.json','generation_config.json','tokenizer.json','tokenizer_config.json','vocab.json','merges.txt')},
              'rows':[0,args.count-1],'conditions':CONDITIONS,'answer_tokens':args.answer_tokens,
              'math_verify':importlib.metadata.version('math-verify'),'code_sha256':digest(__file__),
              'grader_sha256':digest(math_eval.__file__),'backend':'vllm','vllm':importlib.metadata.version('vllm'),
              'seed_rule':'920000 + problem; answer after thought uses offset 10000000',
              'seed_pairing':'Misma semilla para cada problema entre condiciones, sin prometer secuencias iguales',
              'think_open_token_id':opening[0],'think_close_token_id':close[0],
              'temperature':.6,'top_p':.95,'top_k':-1,'batch':args.batch,'kv_cache_mib':args.kv_cache_mib,
              'gpu_memory_utilization':args.gpu_memory_utilization,'max_model_length':2048,'eager':args.eager,
              'token_count_note':'Pensamiento excluye cierre/EOS final; el cierre añadido se cuenta aparte. La respuesta cuenta los IDs devueltos por vLLM, que puede omitir el token de parada.',
              'timing':'Se guardan duración completa de cada lote y tiempo amortizado dividido entre solicitudes; no es latencia aislada.'}
    out.mkdir(parents=True,exist_ok=True);meta=out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo diferente')
    if not meta.exists():meta.write_text(json.dumps(protocol,ensure_ascii=False,indent=2),encoding='utf8')
    from vllm import LLM,SamplingParams
    llm=LLM(model=str(base),tokenizer=str(base),dtype='bfloat16',max_model_len=2048,max_num_seqs=args.batch,
            kv_cache_memory_bytes=args.kv_cache_mib*1024*1024,gpu_memory_utilization=args.gpu_memory_utilization,
            enforce_eager=args.eager,seed=2026)
    def run(items,params):
        started=time.perf_counter();outputs=llm.generate([{'prompt_token_ids':x['ids']} for x in items],params,use_tqdm=False)
        elapsed=time.perf_counter()-started
        for item in items:
            item['seconds']+=elapsed/len(items);item['batch_wall_seconds']+=elapsed
        if len(outputs)!=len(items):raise ValueError('Lote incompleto')
        return [x.outputs[0] for x in outputs]
    for name,cap in CONDITIONS.items():
        for start in range(0,args.count,args.batch):
            pending=[]
            for i in range(start,min(start+args.batch,args.count)):
                path=out/f'{i:03d}-{name}.json';row=rows[i]
                if path.exists():
                    saved=json.loads(path.read_text(encoding='utf8'))
                    if (saved['problem']!=i or saved['condition']!=name or saved['unique_id']!=row['unique_id'] or
                        saved['level']!=row['level'] or saved['gold']!=row['answer'] or
                        saved['thought_tokens']!=len(saved['thought_token_ids']) or saved['answer_tokens']!=len(saved['answer_token_ids']) or
                        saved['seconds']<0 or saved['batch_wall_seconds']<saved['seconds'] or
                        tok.decode(saved['thought_token_ids'],skip_special_tokens=True)!=saved['thought'] or
                        tok.decode(saved['answer_token_ids'],skip_special_tokens=True)!=saved['answer'] or
                        saved['unexpected_thought']!=(cap is None and opening[0] in saved['answer_token_ids'])):
                        raise ValueError('Fila previa incompatible')
                    continue
                prompt='Solve the problem and give the final answer in a LaTeX box.\n'+row['problem']
                ids=tok.apply_chat_template([{'role':'user','content':prompt}],add_generation_prompt=True,
                                            enable_thinking=cap is not None,tokenize=True,return_dict=True)['input_ids']
                if len(ids)+(cap or 0)+(len(close) if cap is not None else 0)+args.answer_tokens>2048:raise ValueError('Contexto insuficiente')
                pending.append({'problem':i,'row':row,'path':path,'ids':list(ids),'input_tokens':len(ids),
                                'thought':[],'thought_raw':[],'forced':False,'seconds':0.,'batch_wall_seconds':0.,
                                'thought_finish_reason':None,'thought_stop_reason':None})
            if not pending:continue
            if cap is not None:
                params=[SamplingParams(temperature=.6,top_p=.95,top_k=-1,max_tokens=cap,stop_token_ids=close,
                                       seed=920000+x['problem']) for x in pending]
                for item,completion in zip(pending,run(pending,params)):
                    if completion.finish_reason not in ('stop','length'):raise ValueError('Fin de pensamiento no reconocido')
                    tokens=list(completion.token_ids);closed=completion.stop_reason==close[0] or bool(tokens and tokens[-1]==close[0])
                    item['thought_raw']=list(tokens)
                    if tokens and (tokens[-1]==close[0] or tokens[-1] in eos_ids):tokens.pop()
                    item['thought']=tokens;item['forced']=not closed;item['ids'].extend(tokens+close)
                    item['thought_finish_reason']=completion.finish_reason;item['thought_stop_reason']=completion.stop_reason
            params=[SamplingParams(temperature=.6,top_p=.95,top_k=-1,max_tokens=args.answer_tokens,
                                   seed=920000+x['problem']+(10000000 if cap is not None else 0)) for x in pending]
            for item,completion in zip(pending,run(pending,params)):
                if completion.finish_reason not in ('stop','length'):raise ValueError('Fin de respuesta no reconocido')
                answer_ids=list(completion.token_ids);answer=tok.decode(answer_ids,skip_special_tokens=True);row=item['row']
                record={'problem':item['problem'],'unique_id':row['unique_id'],'level':row['level'],'condition':name,
                        'gold':row['answer'],'thought':tok.decode(item['thought'],skip_special_tokens=True),'answer':answer,
                        'thought_token_ids':item['thought'],'thought_raw_token_ids':item['thought_raw'],'answer_token_ids':answer_ids,
                        'correct':grade(row['answer'],answer),'input_tokens':item['input_tokens'],'thought_tokens':len(item['thought']),
                        'answer_tokens':len(answer_ids),'closing_tokens':len(close) if cap is not None else 0,
                        'forced_close':item['forced'],'thought_finish_reason':item['thought_finish_reason'],
                        'thought_stop_reason':item['thought_stop_reason'],'answer_finish_reason':completion.finish_reason,
                        'answer_stop_reason':completion.stop_reason,'seconds':item['seconds'],'batch_wall_seconds':item['batch_wall_seconds'],
                        'unexpected_thought':cap is None and opening[0] in answer_ids}
                tmp=item['path'].with_suffix('.tmp');tmp.write_text(json.dumps(record,ensure_ascii=False),encoding='utf8');os.replace(tmp,item['path'])
            print(name,'hasta',min(start+args.batch,args.count),'de',args.count,flush=True)
    summary={}
    for name in CONDITIONS:
        group=[json.loads((out/f'{i:03d}-{name}.json').read_text(encoding='utf8')) for i in range(args.count)]
        values=[int(r['correct'] is True) for r in group];known=[r for r in group if r['correct'] is not None];rng=random.Random(73)
        boot=sorted(sum(rng.choice(values) for _ in values)/len(values) for _ in range(2000))
        summary[name]={'accuracy_abstentions_counted_zero':sum(values)/len(values),
                       'accuracy_among_parsed':sum(r['correct'] is True for r in known)/len(known) if known else None,
                       'abstentions':sum(r['correct'] is None for r in group),'bootstrap_95':[boot[49],boot[1949]],
                       'unexpected_thought':sum(r['unexpected_thought'] for r in group),
                       'forced_close':sum(r['forced_close'] for r in group),
                       'thought_limit':sum(r['thought_finish_reason']=='length' for r in group),
                       'answer_limit':sum(r['answer_finish_reason']=='length' for r in group),
                       'mean_thought_tokens':sum(r['thought_tokens'] for r in group)/len(group),
                       'mean_seconds':sum(r['seconds'] for r in group)/len(group),
                       'mean_batch_wall_seconds':sum(r['batch_wall_seconds'] for r in group)/len(group)}
    reference=[json.loads((out/f'{i:03d}-sin_pensamiento.json').read_text(encoding='utf8')) for i in range(args.count)]
    summary['paired_differences']={}
    for name in ('pensamiento_256','pensamiento_1024'):
        other=[json.loads((out/f'{i:03d}-{name}.json').read_text(encoding='utf8')) for i in range(args.count)]
        diffs=[int(b['correct'] is True)-int(a['correct'] is True) for a,b in zip(reference,other)];rng=random.Random(73)
        boot=sorted(sum(rng.choice(diffs) for _ in diffs)/len(diffs) for _ in range(2000))
        summary['paired_differences'][name]={'mean':sum(diffs)/len(diffs),'bootstrap_95':[boot[49],boot[1949]]}
    (out/'summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf8')
    print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True)

if __name__=='__main__':main()
