"""Diagnóstico GRPO corto en train; nunca usa el examen GSM8K reservado."""
import argparse
import hashlib
import importlib.util
import json
import os
import time
import uuid
from pathlib import Path

import numpy as np
import torch

parser=argparse.ArgumentParser()
parser.add_argument('--group',type=int,choices=[4,8],required=True)
parser.add_argument('--beta',type=float,choices=[0.,.02],required=True)
args=parser.parse_args()
source=Path(__file__).with_name('grpo.py')
protocol_path=Path(__file__).with_name('diagnostico-protocolo.json')
protocol=json.loads(protocol_path.read_text(encoding='utf8'))
spec=importlib.util.spec_from_file_location('grpo',source)
lab=importlib.util.module_from_spec(spec);spec.loader.exec_module(lab)
indices=protocol['indices']
questions=[lab.dataset['train'][i]['question'] for i in indices]
digest=hashlib.sha256(json.dumps(questions,ensure_ascii=False,separators=(',',':')).encode('utf8')).hexdigest()
if digest!=protocol['questions_sha256']:raise ValueError('Los ocho problemas han cambiado')
out=Path(os.environ.get('P08_GRPO_DIAGNOSTIC_DIR','p08-grpo-diagnosticos'))/f'g{args.group}-beta{args.beta:g}'
out.mkdir(parents=True,exist_ok=True)
manifest={'group':args.group,'beta':args.beta,'indices':indices,'seed':0,'groups':8,'updates_per_group':2,
          'max_new_tokens':128,'sampling':protocol['sampling'],
          'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),
          'protocol_sha256':hashlib.sha256(protocol_path.read_bytes()).hexdigest(),
          'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
          'sft_sha256':hashlib.sha256((lab.ADAPTER/'adapter_model.safetensors').read_bytes()).hexdigest(),
          'model':lab.MODEL,'revision':lab.REV,'data_revision':lab.DATA_REV,'gpu':torch.cuda.get_device_name(),
          'torch':torch.__version__,'dtype':'bfloat16','normalization':'poblacional, epsilon 1e-8',
          'loss_reduction':'BNPO: media por token válido',
          'scope':'ocho problemas train; diagnóstico corto, no examen ni época'}
manifest_path=out/'manifest.json'
if manifest_path.exists() and json.loads(manifest_path.read_text(encoding='utf8'))!=manifest:
    raise ValueError('El manifiesto del diagnóstico cambió')
manifest_path.write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf8')
checkpoints=sorted((p for p in out.glob('checkpoint-*') if (p/'state.pt').is_file()),
                   key=lambda p:int(p.name.split('-')[-1]))
checkpoint=checkpoints[-1] if checkpoints else None
torch.manual_seed(0)
policy=lab.load(True,checkpoint or lab.ADAPTER)
policy.load_adapter(lab.ADAPTER,adapter_name='reference',is_trainable=False)
policy.set_adapter('default')
params=[p for p in policy.parameters() if p.requires_grad]
optimizer=torch.optim.AdamW(params,lr=1e-6,weight_decay=0)
history=[];start=0
if checkpoint:
    state=torch.load(checkpoint/'state.pt',map_location='cpu',weights_only=True)
    start=int(state['step']);history=state['history'];optimizer.load_state_dict(state['optimizer'])
    torch.set_rng_state(state['cpu_rng']);torch.cuda.set_rng_state(state['cuda_rng'])
    if len(history)!=start:raise ValueError('Historial y checkpoint no coinciden')
print('Diagnóstico GRPO PID',os.getpid(),'G',args.group,'beta',args.beta,'desde',start,flush=True)
for step,index in enumerate(indices[start:],start+1):
    began=time.perf_counter();row=lab.dataset['train'][index]
    sequences,mask,prefix,texts,records=lab.sample(policy,row,args.group,True)
    rewards=torch.tensor([r['correct']+.1*r['format'] for r in records],device='cuda')
    advantage=(rewards-rewards.mean())/(rewards.std(unbiased=False)+1e-8)
    with torch.no_grad():
        old,_=lab.token_stats(policy,sequences,mask,prefix)
        policy.set_adapter('reference',inference_mode=True)
        reference,_=lab.token_stats(policy,sequences,mask,prefix)
        policy.set_adapter('default')
    for _ in range(2):
        logp,entropy=lab.token_stats(policy,sequences,mask,prefix)
        valid=mask.bool();ratio=torch.exp(torch.where(valid,logp-old,0.))
        clipped=ratio.clamp(1-lab.CLIP,1+lab.CLIP)
        delta=torch.where(valid,reference-logp,0.);kl=torch.expm1(delta)-delta
        loss=((-torch.minimum(ratio*advantage[:,None],clipped*advantage[:,None])+args.beta*kl)*mask).sum()/mask.sum()
        loss.backward();torch.nn.utils.clip_grad_norm_(params,1)
        optimizer.step();optimizer.zero_grad(set_to_none=True)
    torch.cuda.synchronize()
    entry={'step':step,'train_index':index,'reward':float(rewards.mean()),
           'kl_est':float((kl.detach()*mask).sum()/mask.sum()),
           'entropy':float((entropy.detach()*mask).sum()/mask.sum()),
           'length':float(mask.sum(1).float().mean()),
           'clip_fraction':float(((((ratio.detach()<1-lab.CLIP)&(advantage[:,None]<0))|
                                   ((ratio.detach()>1+lab.CLIP)&(advantage[:,None]>0)))*mask).sum()/mask.sum()),
           'zero_variance':bool(rewards.std(unbiased=False)==0),
           'truncated_fraction':float(np.mean([r['truncated'] for r in records])),
           'correct':[r['correct'] for r in records],'format':[r['format'] for r in records],
           'sample':texts[0],'seconds':time.perf_counter()-began}
    history.append(entry)
    staging=out/f'inprogress-{uuid.uuid4().hex}';policy.save_pretrained(staging,selected_adapters=['default'])
    with (staging/'state.pt').open('wb') as file:
        torch.save({'step':step,'optimizer':optimizer.state_dict(),'cpu_rng':torch.get_rng_state(),
                    'cuda_rng':torch.cuda.get_rng_state(),'history':history},file)
        file.flush();os.fsync(file.fileno())
    staging.rename(out/f'checkpoint-{step}')
    print('grupo',step,'/',len(indices),'segundos',entry['seconds'],'recompensa',entry['reward'],flush=True)
panel={'manifest':manifest,'history':history}
temporary=out/'panel.json.tmp'
with temporary.open('w',encoding='utf8') as file:
    json.dump(panel,file,ensure_ascii=False,indent=2);file.flush();os.fsync(file.fileno())
os.replace(temporary,out/'panel.json')
print('Diagnóstico guardado:',out/'panel.json',flush=True)
