"""Muestras pareadas GSM8K para comparar tamaños con el mismo protocolo HF.

La referencia y las preguntas proceden de las 200 filas de m23-l03. El coste
2*N*(entrada+salida) es aproximado y no mide atención ni operaciones enteras.
La inferencia es reanudable por problema; no mezcla backends en una campaña.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import time
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer
import answer_extract_v2 as extractor

REVISIONS={'7ae557604adf67be50417f59c2c2f167def9a775','989aa7980e4cf806f80c7fef2b1adb7bc71aa306'}

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 save(path,payload):
    tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(payload,ensure_ascii=False),encoding='utf8');tmp.replace(path)

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--model-path',required=True);ap.add_argument('--samples',required=True)
    ap.add_argument('--output',required=True);ap.add_argument('--count',type=int,default=200)
    ap.add_argument('--n',type=int,default=16);args=ap.parse_args();base=Path(args.model_path)
    if base.name not in REVISIONS or not 1<=args.count<=200 or args.n<1:ap.error('Revisión o cantidad incorrecta')
    if not torch.cuda.is_available():raise RuntimeError('Se requiere CUDA')
    with gzip.open(args.samples,'rt',encoding='utf8') as f: old=[json.loads(line) for line in f if line.strip()]
    rows=sorted((r for r in old if r['problema']<args.count and r['muestra']==0),key=lambda r:r['problema'])
    if [r['problema'] for r in rows]!=list(range(args.count)):raise ValueError('Preguntas incompletas')
    out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
    meta={'revision':base.name,'weights_sha256':digest(base/'model.safetensors'),
          'config_sha256':{name:digest(base/name) for name in ('config.json','tokenizer.json','tokenizer_config.json','generation_config.json')},
          'questions_sha256':digest(args.samples),
          'extractor_sha256':digest(extractor.__file__),'code_sha256':digest(__file__),'count':args.count,'n':args.n,
          'seed_rule':'630000 + 1000*problem + sample','temperature':.8,'top_p':.9,'top_k':0,
          'repetition_penalty':1.1,'max_tokens':256,'torch':torch.__version__,'gpu':torch.cuda.get_device_name()}
    manifest=out/'protocol.json'
    if manifest.exists() and json.loads(manifest.read_text(encoding='utf8'))!=meta:raise ValueError('Protocolo diferente')
    if not manifest.exists():save(manifest,meta)
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True);tok.pad_token=tok.eos_token
    model=AutoModelForCausalLM.from_pretrained(base,dtype=torch.bfloat16,local_files_only=True).to('cuda').eval()
    params=sum(p.numel() for p in model.parameters());eos=model.generation_config.eos_token_id
    eos_ids=set(eos if isinstance(eos,list) else [eos]) | {tok.eos_token_id}
    for row in rows:
        i=row['problema'];file=out/f'problem-{i:04d}.json'
        if file.exists():
            saved=json.loads(file.read_text(encoding='utf8'))
            if saved['question']!=row['pregunta'] or len(saved['samples'])!=args.n:raise ValueError('Checkpoint incompatible')
            continue
        prompt='Solve step by step. '+row['pregunta']+'\nGive the final numerical answer on its own line as #### followed by the number.'
        enc=tok.apply_chat_template([{'role':'user','content':prompt}],add_generation_prompt=True,tokenize=True,return_tensors='pt',return_dict=True).to('cuda')
        generated=[]
        for sample in range(args.n):
            torch.manual_seed(630000+1000*i+sample);torch.cuda.synchronize();start=time.perf_counter()
            with torch.inference_mode():
                result=model.generate(**enc,do_sample=True,temperature=.8,top_p=.9,top_k=0,repetition_penalty=1.1,
                                      max_new_tokens=256,pad_token_id=tok.eos_token_id)
            torch.cuda.synchronize();elapsed=time.perf_counter()-start
            tokens=result[0,enc['input_ids'].shape[1]:].tolist();stop=next((j for j,t in enumerate(tokens) if t in eos_ids),None)
            if stop is not None:tokens=tokens[:stop+1]
            truncated=stop is None and len(tokens)>=256;text=tok.decode(tokens,skip_special_tokens=True)
            answer=extractor.extract(text,truncated=truncated)
            generated.append({'text':text,'answer':answer,'correct':None if answer is None else int(answer==row['referencia']),
                              'input_tokens':int(enc['attention_mask'].sum()),'output_tokens':len(tokens),
                              'truncated':truncated,'seconds':elapsed})
        save(file,{'problem':i,'question':row['pregunta'],'reference':row['referencia'],'parameters':params,'samples':generated})
        print('problema',i,'muestras',len(generated),flush=True)

if __name__=='__main__':main()
