"""Generación reanudable 2000×16; escoger el lote tras un piloto aislado.

El directorio de salida contiene un manifiesto fijo y JSONL. Cada problema se
escribe de forma durable. Un lote parcial se regenera con el mismo contexto y
semilla y solo continúa si los registros conservados son idénticos.
"""
import argparse, hashlib, json, os, re, uuid
from decimal import Decimal, InvalidOperation
from pathlib import Path

MODEL='Qwen/Qwen2.5-1.5B-Instruct'
REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
DATA_REV='740312add88f781978c0658806c59bc2815b9866'
TRAIN_2000_SHA256='52c3f48b4b2c914768a55b9a116fb12b684d5ffc055651282668e1724b5816bb'

def extract(text):
    number=r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?![\d,]|\.\d)'
    hits=re.findall(r'####\s*\$?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'\\boxed\{\s*('+number+r')\s*\}',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?answer\s+is\s*[:$]?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?final\s+(?:number|answer)\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits: hits=re.findall(r'(?i)\b(?:the\s+)?final\s+numerical\s+answer\s+(?:is\s*)?[:]?\s*\*{0,2}\$?\s*('+number+r')',text)
    if not hits:
        match=re.fullmatch(r'\s*\$?\s*('+number+r')\s*(?:[A-Za-z%]+)?[.\s]*',text)
        hits=[match.group(1)] if match else []
    try: return str(Decimal(hits[-1].replace(',','')).normalize()) if hits else None
    except InvalidOperation: return None

def cut(ids,eos):
    pos=next((i for i,t in enumerate(ids) if t in eos),None)
    return (ids[:pos],pos+1,False) if pos is not None else (ids,len(ids),True)

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

def atomic_write(path, content):
    # La sustitución protege ante interrupción del proceso; no certifica la
    # durabilidad de metadatos ante un apagón del sistema.
    path=Path(path)
    temporary=path.with_name(path.name+'.tmp-'+uuid.uuid4().hex)
    with temporary.open('xb') as f:
        f.write(content);f.flush();os.fsync(f.fileno())
    os.replace(temporary,path)

def check_problem(i, rows, data, count, seed_per_problem=False):
    if len(rows)!=16 or sorted(r.get('sample') for r in rows)!=list(range(16)):
        raise ValueError(f'Checkpoint incompleto o duplicado para problema {i}')
    reference=extract(data[i]['answer']); start=(i//count)*count
    if reference is None: raise ValueError('Referencia no extraída')
    for r in rows:
        answer=extract(r['text'])
        if (r['problem']!=i or r['question']!=data[i]['question'] or r['reference']!=reference
            or r['answer']!=answer or r['label']!=(None if answer is None else int(answer==reference))
            or r['batch_start']!=start or r['seed']!=150000+(16*i if seed_per_problem else start)
            or type(r['tokens_entrada']) is not int or r['tokens_entrada']<1
            or type(r['tokens_salida']) is not int or not 1<=r['tokens_salida']<=256
            or type(r['truncated']) is not bool or (r['truncated'] and r['tokens_salida']!=256)):
            raise ValueError(f'Checkpoint incoherente para problema {i}')

def assemble(path, by_key, problems):
    if set(by_key)!={(i,j) for i in range(problems) for j in range(16)}:
        raise ValueError('No se puede ensamblar: faltan registros')
    h=hashlib.sha256()
    temporary=path.with_name(path.name+'.tmp-'+uuid.uuid4().hex) if not path.exists() else None
    stream=temporary.open('xb') if temporary else None
    try:
        for key in sorted(by_key):
            line=(json.dumps(by_key[key],ensure_ascii=False)+'\n').encode('utf8')
            h.update(line)
            if stream: stream.write(line)
        if stream: stream.flush();os.fsync(stream.fileno())
    finally:
        if stream: stream.close()
    if path.exists():
        if digest(path)!=h.hexdigest(): raise ValueError('Resultado ensamblado distinto de los checkpoints')
    else: os.replace(temporary,path)
    print('JSONL completo',problems*16,'filas; SHA256',h.hexdigest(),flush=True)

def self_test():
    assert extract('#### 1,200.00')=='1.2E+3'
    assert extract('no answer') is None
    assert extract('The final numerical answer is: **72**.')=='72'
    assert cut([3,2,2],{2})==([3],2,False)
    assert cut([3,4],{2})==([3,4],2,True)
    print('CPU: extractor, EOS y truncado correctos')

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--batch',type=int,default=64)
    ap.add_argument('--problems',type=int,default=2000,help='2000 para la campaña; una escala menor exige otra ruta')
    ap.add_argument('--backend',choices=['sdpa','eager','flash_attention_2'],default='sdpa')
    ap.add_argument('--output',default='orm_train_samples.jsonl')
    ap.add_argument('--model-path',help='Snapshot local de la revisión fijada')
    ap.add_argument('--records',help='JSON de las primeras 2000 preguntas y respuestas del split fijado')
    ap.add_argument('--self-test',action='store_true')
    args=ap.parse_args()
    if args.self_test: return self_test()
    if args.model_path and Path(args.model_path).name!=REV:
        ap.error('El snapshot local debe identificar la revisión fijada en su nombre')
    if args.problems!=2000 and args.output=='orm_train_samples.jsonl':
        ap.error('Una prueba corta debe usar una ruta propia')
    if args.problems<1 or args.problems>2000 or args.batch<16 or args.batch%16 or args.problems%(args.batch//16):
        ap.error('El lote debe ser múltiplo de 16 y dividir el número de problemas')
    import torch, transformers
    from huggingface_hub import snapshot_download
    from transformers import AutoTokenizer,AutoModelForCausalLM
    if not torch.cuda.is_available(): raise RuntimeError('Se requiere GPU CUDA')
    raw_records=Path(args.records).read_bytes() if args.records else None
    if raw_records:
        data=json.loads(raw_records.decode('utf8'))
    else:
        from datasets import load_dataset
        ds=load_dataset('openai/gsm8k','main',revision=DATA_REV,split='train')
        data=[{'question':r['question'],'answer':r['answer']} for r in ds.select(range(2000))]
    if len(data)<args.problems: raise ValueError('Faltan problemas de entrenamiento')
    canonical=json.dumps(data[:args.problems],ensure_ascii=False,separators=(',',':')).encode('utf8')
    if args.problems==2000 and hashlib.sha256(canonical).hexdigest()!=TRAIN_2000_SHA256:
        raise ValueError('Los 2000 problemas no coinciden con la revisión fijada')
    source=Path(args.model_path or snapshot_download(MODEL,revision=REV))
    files=['config.json','generation_config.json','tokenizer_config.json','tokenizer.json','merges.txt','vocab.json','model.safetensors']
    hashes={name:digest(source/name) for name in files}
    protocol={'model':MODEL,'revision':REV,'dataset_revision':DATA_REV,'split':'train',
              'problems':args.problems,'samples_per_problem':16,'batch':args.batch,'backend':args.backend,
              'dtype':'bfloat16','seed_rule':'150000+primer_indice', 'temperature':.8,
              'top_p':.9,'top_k':0,'repetition_penalty':1.1,'max_new_tokens':256,
              'padding':'left','pad_token':'<|im_start|>',
              'torch':torch.__version__,'transformers':transformers.__version__,
              'cuda_version':torch.version.cuda,'gpu':torch.cuda.get_device_name(),
              'compute_capability':list(torch.cuda.get_device_capability()),
              'code_sha256':digest(__file__),'data_sha256':hashlib.sha256(canonical).hexdigest(),
              'model_and_tokenizer_sha256':hashes}
    path=Path(args.output); meta=path.with_suffix(path.suffix+'.protocol.json')
    parts=path.with_suffix(path.suffix+'.parts')
    if (path.exists() or parts.exists()) and not meta.exists(): raise ValueError('Archivo previo sin manifiesto; usa ruta nueva')
    if meta.exists():
        if json.loads(meta.read_text(encoding='utf8'))!=protocol: raise ValueError('Protocolo distinto; usa ruta nueva')
    else: atomic_write(meta,json.dumps(protocol,ensure_ascii=False,indent=2).encode('utf8'))
    parts.mkdir(exist_ok=True)
    count=args.batch//16
    old=[]
    for file in sorted(parts.glob('problem-*.json')):
        suffix=file.stem.removeprefix('problem-')
        if len(suffix)!=4 or not suffix.isdigit() or not 0<=int(suffix)<args.problems:
            raise ValueError(f'Archivo de checkpoint inesperado: {file.name}')
        i=int(suffix); rows=json.loads(file.read_text(encoding='utf8'))
        check_problem(i,rows,data,count);old.extend(rows)
    by_key={(r['problem'],r['sample']):r for r in old}
    done=set(by_key)
    if len(done)!=len(old) or any(not 0<=i<args.problems or not 0<=j<16 for i,j in done):
        raise ValueError('Duplicados o índices fuera de rango')
    if path.exists() and len(done)!=args.problems*16: raise ValueError('Resultado final sin checkpoints completos')
    if len(done)==args.problems*16:
        assemble(path,by_key,args.problems)
        return
    tok=AutoTokenizer.from_pretrained(source,padding_side='left',local_files_only=True)
    tok.pad_token='<|im_start|>'
    model=AutoModelForCausalLM.from_pretrained(source,dtype=torch.bfloat16,
                                                attn_implementation=args.backend,local_files_only=True).to('cuda').eval()
    eos=model.generation_config.eos_token_id
    eos=set(eos if isinstance(eos,list) else [eos])
    for start in range(0,args.problems,count):
        expected={(i,j) for i in range(start,start+count) for j in range(16)}
        if expected<=done: continue
        prompts=[]
        for i in range(start,start+count):
            msg='Solve step by step. '+data[i]['question']+'\nGive the final numerical answer on its own line as #### followed by the number.'
            prompt=tok.apply_chat_template([{'role':'user','content':msg}],tokenize=False,add_generation_prompt=True)
            assert tok.pad_token_id in tok(prompt,add_special_tokens=False)['input_ids']
            prompts.extend([prompt]*16)
        inputs=tok(prompts,padding=True,add_special_tokens=False,return_tensors='pt').to('cuda')
        torch.manual_seed(150000+start)
        with torch.inference_mode():
            out=model.generate(**inputs,do_sample=True,temperature=.8,top_p=.9,top_k=0,
                               repetition_penalty=1.1,max_new_tokens=256,pad_token_id=tok.pad_token_id)
        records=[]
        input_lengths=inputs['attention_mask'].sum(dim=1).cpu().tolist()
        for index,ids in enumerate(out[:,inputs['input_ids'].shape[1]:].tolist()):
            i=start+index//16; j=index%16
            content,length,truncated=cut(ids,eos)
            text=tok.decode(content,skip_special_tokens=True)
            answer,reference=extract(text),extract(data[i]['answer'])
            if reference is None: raise ValueError('Referencia no extraída')
            records.append({'problem':i,'sample':j,'question':data[i]['question'],'text':text,
                            'reference':reference,'answer':answer,'label':None if answer is None else int(answer==reference),
                            'tokens_entrada':input_lengths[index],
                            'tokens_salida':length,'truncated':truncated,'batch_start':start,'seed':150000+start})
        for record in records:
            key=(record['problem'],record['sample'])
            if key in by_key and by_key[key]!=record:
                raise ValueError('La regeneración del lote parcial no coincide con el checkpoint; no se modifica')
        for i in range(start,start+count):
            group=[r for r in records if r['problem']==i]
            if all((i,r['sample']) in done for r in group): continue
            check_problem(i,group,data,count)
            atomic_write(parts/f'problem-{i:04}.json',json.dumps(group,ensure_ascii=False).encode('utf8'))
            for r in group:
                key=(i,r['sample']);by_key[key]=r;done.add(key)
        print('problemas',start+count,'de',args.problems,'; filas',len(records),flush=True)
    assemble(path,by_key,args.problems)

if __name__=='__main__': main()
