import json, math, time, os, hashlib, sys, threading
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from transformers import AutoModelForCausalLM
sys.dont_write_bytecode=True
from autor18_sae_reader import ResidualReader

quick=os.environ.get('P11_SAE_QUICK')=='1'
root=Path(os.environ.get('P11_SAE_ROOT','p11-sae'))
train_only=os.environ.get('P11_SAE_TRAIN_ONLY')=='1'
startup_start=time.perf_counter()
meta=json.loads((root/'extraction.json').read_text(encoding='utf-8'))
assert meta['train_tokens']==(4096 if quick else 20_000_000) and meta['validation_tokens']==(1024 if quick else 99_968)
def sha256_file(path):
 digest=hashlib.sha256()
 with path.open('rb') as f:
  for block in iter(lambda:f.read(8*1024*1024),b''):digest.update(block)
 return digest.hexdigest()
for split in ('train','validation'):
 assert sha256_file(root/f'{split}-residual.f16')==meta['activation_sha256'][split]
torch.set_num_threads(2); device='cuda' if torch.cuda.is_available() else 'cpu'
train=ResidualReader(root/'train-residual.f16',meta['train_tokens'])
val=ResidualReader(root/'validation-residual.f16',meta['validation_tokens'])
# Escala escalar fija estimada en train; no se ajusta con validación.
sample=np.asarray(train.read(0,min(100_000,len(train))),dtype=np.float32)
mean=sample.mean(axis=0); scale=float(np.sqrt(np.mean((sample-mean)**2)));assert scale>0
del sample
normalization_hash=hashlib.sha256(mean.tobytes()+np.float64(scale).tobytes()).hexdigest()
np.savez(root/'normalization.npz',mean=mean,scale=scale)
mean_t=torch.tensor(mean,device=device);scale_t=torch.tensor(scale,device=device)
startup_duration=time.perf_counter()-startup_start
print('datos y normalización listos, segundos:',startup_duration,'dispositivo:',device,flush=True)

class SAE(nn.Module):
 def __init__(self,d,features,k,kind):
  super().__init__();self.encoder=nn.Linear(d,features);self.decoder=nn.Linear(features,d,bias=False)
  self.bias=nn.Parameter(torch.zeros(d));self.k=k;self.kind=kind
  with torch.no_grad():
   self.decoder.weight.copy_(F.normalize(self.decoder.weight,dim=0))
   self.encoder.weight.copy_(self.decoder.weight.T);self.encoder.bias.zero_()
 def forward(self,x):
  pre=self.encoder(x-self.bias);z=F.relu(pre)
  if self.kind=='topk':
   values,indices=torch.topk(z,self.k,dim=-1);z=torch.zeros_like(z).scatter(-1,indices,values)
  return self.decoder(z)+self.bias,z,pre

batch_size=256 if quick else 4096;n=meta['train_tokens'];steps=math.ceil(n/batch_size)
window=4 if quick else 1000
results_file=root/'training-results.json'
snapshots=root/'training-records';snapshots.mkdir(exist_ok=True)
old=sorted(snapshots.glob('*.json'))
completed_before=results_file.exists()
source=results_file if completed_before else old[-1] if old else None
results=json.loads(source.read_text(encoding='utf-8')) if source else []
def save_results():
 records=sorted(snapshots.glob('*.json'));index=int(records[-1].stem)+1 if records else 1
 target=snapshots/f'{index:06d}.json';tmp=snapshots/f'{index:06d}.{os.getpid()}.tmp'
 with tmp.open('x',encoding='utf-8') as stream:
  json.dump(results,stream,indent=2);stream.flush();os.fsync(stream.fileno())
 tmp.rename(target)
configurations=[(features,kind,setting) for features in (1536,3072)
                for kind,settings in (('l1',(0.0005,0.002)),('topk',(32,64))) for setting in settings]
for features,kind,setting in configurations:
  k=int(setting) if kind=='topk' else 32
  coefficient=float(setting) if kind=='l1' else 0.0
  variant=f'{kind}-{features}-'+(f'k{k}' if kind=='topk' else f'l1-{coefficient:g}')
  identity={'tokens_sha256':meta['train_ids_sha256'],'validation_tokens_sha256':meta['validation_ids_sha256'],'model_revision':meta['revision'],
            'layer':meta['layer'],'sequence':meta['sequence'],'dtype':meta['dtype'],'activation_sha256':meta['activation_sha256'],
            'normalization_sha256':normalization_hash,
            'kind':kind,'features':features,'k':k,'l1':coefficient,'batch_size':batch_size,'steps':steps,'algorithm':'sae-v4-scaled-reinit-auxk'}
  existing=[r for r in results if r['kind']==kind and r['features']==features and r['k']==(k if kind=='topk' else None) and r['l1']==coefficient]
  if existing:
   assert len(existing)==1 and existing[0]['training_identity']==identity
   assert sha256_file(root/existing[0]['checkpoint_file'])==existing[0]['checkpoint_sha256']
   continue
  torch.manual_seed(1806);model=SAE(768,features,k,kind).to(device)
  opt=torch.optim.Adam(model.parameters(),lr=3e-4)
  counts=torch.zeros(features,device=device);dead_candidates=torch.zeros(features,dtype=torch.bool,device=device);rng=np.random.default_rng(1806)
  order=rng.permutation(steps);start_time=time.time();last_loss=None
  watch=None
  timed_load=0.;timed_compute=0.;timed_tokens=0
  if device=='cuda':torch.cuda.reset_peak_memory_stats()
  progress_dir=root/f'progress-{variant}';progress_dir.mkdir(exist_ok=True)
  snapshots_model=sorted(progress_dir.glob('*.json'));resume=0
  if snapshots_model:
   manifest=json.loads(snapshots_model[-1].read_text(encoding='utf-8'))
   progress_file=progress_dir/manifest['file']
   assert sha256_file(progress_file)==manifest['sha256']
   checkpoint=torch.load(progress_file,weights_only=True,map_location=device)
   assert checkpoint['identity']==identity
   resume=int(checkpoint['step']);assert resume==manifest['step'] and 0<=resume<steps and resume%window==0
   model.load_state_dict(checkpoint['model']);opt.load_state_dict(checkpoint['optimizer'])
   dead_candidates=checkpoint['dead_candidates'].to(device)
   watch=checkpoint.get('watch')
  for step,index in enumerate(order[resume:],start=resume):
   measured=step-resume<100
   if measured and device=='cuda':torch.cuda.synchronize()
   if measured:t_load=time.perf_counter()
   begin=int(index)*batch_size;end=min(n,begin+batch_size)
   x=(torch.tensor(np.array(train.read(begin,end),dtype=np.float32),device=device)-mean_t)/scale_t
   assert torch.isfinite(x).all(), f'activación no finita en bloque {begin}:{end}'
   if measured:
    if device=='cuda':torch.cuda.synchronize()
    timed_load+=time.perf_counter()-t_load;t_compute=time.perf_counter();timed_tokens+=end-begin
   recon,z,pre=model(x);mse=(recon-x).square().mean()
   loss=mse + coefficient*z.sum(-1).mean()
   # Solo candidatos inactivos durante una ventana completa; dejan de serlo al activarse.
   dead=dead_candidates
   if kind=='topk' and step>0 and dead.any():
    aux=F.relu(pre).masked_fill(~dead[None,:],-torch.inf)
    kaux=min(32,int(dead.sum()));v,i=aux.topk(kaux,dim=-1)
    zaux=torch.zeros_like(aux).scatter(-1,i,v)
    loss=loss+(model.decoder(zaux)-(x-recon).detach()).square().mean()/32
   assert torch.isfinite(loss), f'pérdida no finita en {variant}, paso {step+1}'
   opt.zero_grad(set_to_none=True);loss.backward()
   if watch is not None:
    watch_idx=watch['indices'].to(device)
    encoder_before=model.encoder.weight[watch_idx].detach().clone()
   opt.step()
   with torch.no_grad():
    model.decoder.weight.copy_(F.normalize(model.decoder.weight,dim=0));counts+=(z>0).sum(0)
    dead_candidates &= ~(z>0).any(0)
    if watch is not None:
     changes=torch.linalg.vector_norm(model.encoder.weight[watch_idx]-encoder_before,dim=1)
     probe=watch['probe'].to(device);probe_mse=(model(probe)[0]-probe).square().mean()
     diagnostic={'variant':variant,'reset_step':watch['reset_step'],'update_step':step+1,'reset_count':len(watch_idx),
                 'repeated_candidates':watch['repeated_candidates'],'probe':'primeras filas del lote de reinicio, entrenamiento',
                 'mse_after_reset_before_update':watch['mse_before'],'mse_after_next_update':float(probe_mse),
                 'encoder_update_norm_mean':float(changes.mean()),'encoder_update_norm_max':float(changes.max()),
                 'encoder_norm_mean_after_update':float(torch.linalg.vector_norm(model.encoder.weight[watch_idx],dim=1).mean())}
     diag_dir=root/'restart-diagnostics';diag_dir.mkdir(exist_ok=True)
     dest=diag_dir/f'{variant}-{watch["reset_step"]:08d}-{os.getpid()}.json'
     tmp=dest.with_suffix('.tmp');assert not dest.exists() and not tmp.exists()
     with tmp.open('x',encoding='utf-8') as stream:
      json.dump(diagnostic,stream,indent=2);stream.flush();os.fsync(stream.fileno())
     tmp.rename(dest)
     print('reinicio',json.dumps(diagnostic),flush=True);watch=None
   if measured:
    if device=='cuda':torch.cuda.synchronize()
    timed_compute+=time.perf_counter()-t_compute
    if step-resume==99 or step+1==steps:
     duration=timed_load+timed_compute
     performance={'variant':variant,'start_step':resume,'end_step':step+1,'tokens':timed_tokens,'load_seconds':timed_load,
                  'compute_seconds':timed_compute,'tokens_per_second':timed_tokens/duration,
                  'peak_reserved_bytes':torch.cuda.max_memory_reserved() if device=='cuda' else None,
                  'startup_seconds':startup_duration,'pid':os.getpid()}
     perf_dir=root/'performance';perf_dir.mkdir(exist_ok=True)
     dest=perf_dir/f'{variant}-{resume:08d}-{os.getpid()}.json';tmp=dest.with_suffix('.tmp')
     assert not dest.exists() and not tmp.exists()
     with tmp.open('x',encoding='utf-8') as stream:
      json.dump(performance,stream,indent=2);stream.flush();os.fsync(stream.fileno())
     tmp.rename(dest)
     print('primeros lotes',variant,'tokens',timed_tokens,'segundos carga',round(timed_load,3),
           'segundos cálculo',round(timed_compute,3),'tokens/s',round(timed_tokens/duration,1),
           'pico reservado',torch.cuda.max_memory_reserved() if device=='cuda' else None,flush=True)
   last_loss=float(mse.detach())
   if (step+1)%window==0 and step+1<steps:
    print(variant,step+1,'/',steps,'mse',last_loss,'sin activaciones',int((counts==0).sum()),flush=True)
    # Reinicia unidades inactivas usando residuos del lote, y borra sus momentos Adam.
    with torch.no_grad():
     idx=torch.where(counts==0)[0]
     if idx.numel():
      repeated_candidates=int(dead_candidates[idx].sum())
      dead_candidates[idx]=True
      residual=(x-recon)[torch.arange(len(idx),device=device)%len(x)]
      directions=F.normalize(residual,dim=1)
      zero=torch.linalg.vector_norm(residual,dim=1)<1e-12
      if zero.any():
       fallback=F.one_hot(idx[zero]%x.shape[-1],num_classes=x.shape[-1]).to(directions.dtype)
       directions[zero]=fallback
      # Encoder pequeño evita que muchos reinicios correlacionados dominen de golpe.
      model.decoder.weight[:,idx]=directions.T;model.encoder.weight[idx]=0.02*directions;model.encoder.bias[idx]=0
      for param,axis in ((model.decoder.weight,1),(model.encoder.weight,0),(model.encoder.bias,0)):
       for key in ('exp_avg','exp_avg_sq'):
        state=opt.state[param].get(key)
        if state is not None:
         if axis==1:state[:,idx]=0
         else:state[idx]=0
      probe=x[:min(256,len(x))].detach()
      watch={'indices':idx.detach().cpu(),'probe':probe.cpu(),'reset_step':step+1,
             'repeated_candidates':repeated_candidates,'mse_before':float((model(probe)[0]-probe).square().mean())}
    progress_file=progress_dir/f'{step+1:08d}.pt';tmp=progress_dir/f'{step+1:08d}.{os.getpid()}.tmp'
    if progress_file.exists():
     # Un .pt sin manifiesto es un archivo huérfano de una interrupción anterior.
     orphan=progress_dir/f'{step+1:08d}.{os.getpid()}.orphan'
     assert not orphan.exists();progress_file.rename(orphan)
    torch.save({'step':step+1,'model':model.state_dict(),'optimizer':opt.state_dict(),'dead_candidates':dead_candidates,'watch':watch,'identity':identity},tmp)
    with tmp.open('r+b') as stream:stream.flush();os.fsync(stream.fileno())
    tmp.rename(progress_file)
    manifest=progress_dir/f'{step+1:08d}.json';mtmp=progress_dir/f'{step+1:08d}.{os.getpid()}.json.tmp'
    with mtmp.open('x',encoding='utf-8') as stream:
     json.dump({'step':step+1,'file':progress_file.name,'sha256':sha256_file(progress_file)},stream);stream.flush();os.fsync(stream.fileno())
    mtmp.rename(manifest)
    counts.zero_()
  model.eval();counts_eval=torch.zeros(features,device=device);l0=0.;sse=0.;sst=0.;seen=0
  with torch.no_grad():
   for begin in range(0,len(val),batch_size):
    x=(torch.tensor(np.array(val.read(begin,min(begin+batch_size,len(val))),dtype=np.float32),device=device)-mean_t)/scale_t
    rec,z,_=model(x);counts_eval+=(z>0).sum(0);l0+=float((z>0).sum());sse+=float((rec-x).square().sum());sst+=float(x.square().sum());seen+=len(x)
  result={'kind':kind,'features':features,'k':k if kind=='topk' else None,'l1':coefficient,
   'tokens_seen':n,'validation_tokens':seen,'l0':l0/seen,'normalized_mse':sse/sst,
   'dead_fraction':float((counts_eval==0).float().mean()),'activation_counts':counts_eval.cpu().tolist(),
   'last_train_mse':last_loss,'seconds':time.time()-start_time,'training_identity':identity}
  final_path=root/f'sae-{variant}.pt';tmp=final_path.with_suffix('.tmp')
  torch.save({'state_dict':model.state_dict(),'kind':kind,'features':features,'k':k,'mean':torch.tensor(mean),'scale':scale},tmp)
  with tmp.open('r+b') as stream:stream.flush();os.fsync(stream.fileno())
  tmp.replace(final_path)
  result['checkpoint_file']=final_path.name
  result['checkpoint_sha256']=sha256_file(final_path)
  results.append(result);save_results()
  print(json.dumps({key:value for key,value in result.items() if key!='activation_counts'}),flush=True)

# Sustitución del residual en validación: mismo GPT-2, pesos congelados.
if train_only:
 print('Entrenamiento verificado; evaluación de pérdida del modelo aún pendiente.',flush=True)
 raise SystemExit(0)
if completed_before:
 assert len(results)==len(configurations) and all('recovered' in result for result in results)
 print('Resultados ya completos y checkpoints verificados',flush=True)
 raise SystemExit(0)
repo='openai-community/gpt2';rev=meta['revision']
if device=='cuda':torch.cuda.reset_peak_memory_stats()
memory_samples=[]
monitor_stop=threading.Event()
def monitor_global():
 path=root/f'evaluation-telemetry-{os.getpid()}.jsonl'
 with path.open('a',encoding='utf8') as stream:
  while not monitor_stop.wait(0.5):
   free,total=torch.cuda.mem_get_info()
   stream.write(json.dumps({'time':time.time(),'global_used_bytes':total-free,'global_free_bytes':free,
    'own_peak_reserved_bytes':torch.cuda.max_memory_reserved()})+'\n')
   stream.flush()
monitor=None
if device=='cuda':
 monitor=threading.Thread(target=monitor_global,daemon=True);monitor.start()
def memory_snapshot(stage):
 if device=='cuda':
  torch.cuda.synchronize()
  free,total=torch.cuda.mem_get_info()
  memory_samples.append({'stage':stage,'global_used_bytes':total-free,'global_free_bytes':free,
   'own_allocated_bytes':torch.cuda.memory_allocated(),'own_reserved_bytes':torch.cuda.memory_reserved(),
   'own_peak_reserved_bytes':torch.cuda.max_memory_reserved()})
  path=root/f'evaluation-memory-{os.getpid()}.json';tmp=path.with_suffix('.tmp')
  tmp.write_text(json.dumps(memory_samples,indent=2),encoding='utf8');tmp.replace(path)
memory_snapshot('antes de cargar GPT')
lm=AutoModelForCausalLM.from_pretrained(repo,revision=rev,local_files_only=False,torch_dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
memory_snapshot('GPT cargado')
ids=np.memmap(root/'validation-ids.i32',dtype='<i4',mode='r',shape=(meta['validation_tokens'],))
def eval_loss(replacement):
 def hook(mod,args,out):
  x=out[0] if isinstance(out,tuple) else out
  y=replacement(x)
  return (y,)+out[1:] if isinstance(out,tuple) else y
 handle=lm.transformer.h[6].register_forward_hook(hook) if replacement else None
 total=0.;count=0
 try:
  with torch.inference_mode():
   # 128 secuencias de validación, independientes del corpus train.
   for start in range(0,128*(8 if quick else 128),128*8):
    x=torch.tensor(np.asarray(ids[start:start+128*8]).reshape(-1,128).copy(),device=device,dtype=torch.long)
    logits=lm(x,use_cache=False).logits
    loss=F.cross_entropy(logits[:,:-1].float().reshape(-1,logits.shape[-1]),x[:,1:].reshape(-1),reduction='sum')
    total+=float(loss);count+=x.shape[0]*127
 finally:
  if handle:handle.remove()
 return total/count
baseline=eval_loss(None);identity_loss=eval_loss(lambda x:x)
assert abs(identity_loss-baseline)<1e-5, 'el hook de identidad altera la pérdida'
zero=eval_loss(lambda x:torch.zeros_like(x))
memory_snapshot('controles')
for result in results:
 state=torch.load(root/result['checkpoint_file'],weights_only=True,map_location=device)
 sae=SAE(768,state['features'],state['k'],state['kind']).to(device);sae.load_state_dict(state['state_dict']);sae.eval()
 def replace(x):
  y=(x.float()-mean_t)/scale_t;return (sae(y)[0]*scale_t+mean_t).to(x.dtype)
 loss=eval_loss(replace);result.update(base_loss=baseline,identity_loss=identity_loss,zero_loss=zero,reconstruction_loss=loss,
  recovered=(zero-loss)/(zero-baseline) if abs(zero-baseline)>1e-8 else None)
 memory_snapshot(result['checkpoint_file'])
 save_results()
 print('loss recovery',{key:value for key,value in result.items() if key!='activation_counts'},flush=True)
assert len(results)==len(configurations) and all('recovered' in result for result in results)
tmp=root/f'training-results.{os.getpid()}.tmp'
with tmp.open('x',encoding='utf-8') as stream:
 json.dump(results,stream,indent=2);stream.flush();os.fsync(stream.fileno())
tmp.rename(results_file)
if monitor is not None:
 monitor_stop.set();monitor.join()
