import os, json, hashlib, time
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from huggingface_hub import hf_hub_download

torch.set_num_threads(2)
repo='openai-community/gpt2'; rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
src=Path(os.environ.get('P11_SAE_DATA','p11-sae-data'))
quick=os.environ.get('P11_SAE_QUICK')=='1'
root=Path(os.environ.get('P11_SAE_ROOT','p11-sae'));root.mkdir(parents=True,exist_ok=True)
def sha256_file(path):
 h=hashlib.sha256()
 with path.open('rb') as f:
  for block in iter(lambda:f.read(8*1024*1024),b''):h.update(block)
 return h.hexdigest()
def latest_checkpoint(directory,legacy):
 candidates=sorted(directory.glob('*.json'))
 return candidates[-1] if candidates else legacy if legacy.exists() else None
def save_checkpoint(directory,end,record):
 checkpoint=directory/f'{end:012d}.json';tmp=directory/f'{end:012d}.{os.getpid()}.tmp'
 assert not checkpoint.exists(), f'checkpoint duplicado: {checkpoint}'
 with tmp.open('x',encoding='utf-8') as file:
  json.dump(record,file);file.flush();os.fsync(file.fileno())
 tmp.rename(checkpoint)
manifest=json.loads((src/'manifest.json').read_text(encoding='utf-8'))
for name,meta in manifest['files'].items():
 assert sha256_file(src/name)==meta['sha256']
tok=AutoTokenizer.from_pretrained(repo,revision=rev,local_files_only=False)
def make_tokens(files,limit,dest):
 # Reproduce el prefijo ya escrito y compara su hash antes de añadir bytes.
 # Así un corte en medio de un documento también se puede reanudar.
 size=dest.stat().st_size if dest.exists() else 0
 assert size%4==0 and size//4<=limit
 existing=size//4
 existing_hash=sha256_file(dest) if existing else None
 count=0;h=hashlib.sha256();verified=(existing==0)
 with dest.open('ab') as f:
  for path in files:
   for record in pq.ParquetFile(path).iter_batches(batch_size=128,columns=['text']):
    texts=record.column(0).to_pylist()
    pieces=tok(texts,add_special_tokens=False,truncation=False)['input_ids']
    for ids in pieces:
     if not ids: continue
     a=np.asarray(ids+[tok.eos_token_id],dtype='<i4')[:limit-count]
     if count<existing:
      k=min(len(a),existing-count);h.update(a[:k].tobytes());count+=k;a=a[k:]
      if count==existing:
       assert h.hexdigest()==existing_hash, 'el prefijo guardado no coincide con la tokenización reproducida'
       verified=True
     if len(a):
      assert verified
      f.write(a.tobytes());h.update(a.tobytes());count+=len(a)
     if count==limit:return count,h.hexdigest()
 return count,h.hexdigest()
train_n=4096 if quick else 20_000_000
val_n=1024 if quick else 99_968
count,trainhash=make_tokens(sorted(src.glob('train*.parquet')),train_n,root/'train-ids.i32')
assert count==train_n
vcount,valhash=make_tokens([src/'validation-00000-of-00001.parquet'],val_n,root/'validation-ids.i32')
assert vcount==val_n
print('tokens',count,trainhash,vcount,valhash,flush=True)
device='cuda' if torch.cuda.is_available() else 'cpu'
weight_path=Path(hf_hub_download(repo,'model.safetensors',revision=rev,local_files_only=False))
assert sha256_file(weight_path)=='248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707'
model=AutoModelForCausalLM.from_pretrained(repo,revision=rev,local_files_only=False,torch_dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
print('device',device,'gpu',torch.cuda.get_device_name() if device=='cuda' else 'CPU',
      'gpu_free_total_bytes',torch.cuda.mem_get_info() if device=='cuda' else None,flush=True)
identity={'model':repo,'revision':rev,'layer':6,'sequence':128,'storage_dtype':'float16',
          'model_dtype':'float16' if device=='cuda' else 'float32'}
capture={}
def hook(mod,args,result):capture['residual']=(result[0] if isinstance(result,tuple) else result).detach()
handle=model.transformer.h[6].register_forward_hook(hook)
activation_hashes={}
try:
 for name,n in [('train',count),('validation',vcount)]:
  ids=np.memmap(root/(name+'-ids.i32'),dtype='<i4',mode='r',shape=(n,))
  # El resto incompleto no se procesa; ambos tamaños son divisibles por 128.
  assert n%128==0
  path=root/(name+'-residual.f16');progress_path=root/(name+'-progress.json')
  checkpoints=root/(name+'-checkpoints');checkpoints.mkdir(exist_ok=True)
  expected_hash=trainhash if name=='train' else valhash
  latest=latest_checkpoint(checkpoints,progress_path)
  progress=json.loads(latest.read_text(encoding='utf-8')) if latest else None
  if progress:
   assert progress['tokens_sha256']==expected_hash and progress['n']==n and progress['identity']==identity and path.stat().st_size==n*768*2
   done=int(progress['done']);assert 0<=done<=n and (done%2048==0 or done==n)
  else:done=0
  digest=hashlib.sha256()
  if done:
   remaining=done*768*2
   with path.open('rb') as source:
    while remaining:
     block=source.read(min(8*1024*1024,remaining));assert block
     digest.update(block);remaining-=len(block)
   assert digest.hexdigest()==progress['prefix_sha256'], 'el prefijo de activaciones ha cambiado'
  activations=path.open('r+b' if progress else 'w+b',buffering=0)
  if not progress:activations.truncate(n*768*2)
  for start in range(done,n,128*16):
   end=min(n,start+128*16);x=torch.tensor(np.asarray(ids[start:end]).reshape(-1,128).copy(),device=device,dtype=torch.long)
   with torch.inference_mode():model.transformer(input_ids=x,use_cache=False)
   values=capture['residual'].float().cpu().numpy().reshape(-1,768).astype('<f2')
   assert np.isfinite(values).all(), f'activación no finita en {name} desde {start}'
   block=values.tobytes();activations.seek(start*768*2)
   assert activations.write(block)==len(block);digest.update(block)
   activations.flush();os.fsync(activations.fileno())
   save_checkpoint(checkpoints,end,{'tokens_sha256':expected_hash,'n':n,'done':end,'identity':identity,'prefix_sha256':digest.hexdigest()})
   if start==done or (start//2048+1)%100==0 or end==n:
    print('bloque',name,start,end,'/',n,'shape',list(values.shape),
          'gpu_free_total_bytes',torch.cuda.mem_get_info() if device=='cuda' else None,flush=True)
  activations.flush();activations.close();activation_hashes[name]=digest.hexdigest();del ids
finally:handle.remove()
meta={'repo':repo,'revision':rev,'weights_sha256':'248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707',
 'dataset_revision':manifest['revision'],'train_tokens':count,'validation_tokens':vcount,'train_ids_sha256':trainhash,
 'validation_ids_sha256':valhash,'activation_sha256':activation_hashes,'sequence':128,'layer':6,'dtype':'float16' if device=='cuda' else 'float32 model / float16 stored','device':device,'quick':quick}
root.joinpath('extraction.json').write_text(json.dumps(meta,indent=2),encoding='utf-8')
print('extraccion completa',meta,flush=True)
