"""Precompute a three-move Othello tree with real MetaOthello probes.

Weights: aviralchawla/metaothello revision 988a3ef4b3de2e27c406990472ec5aabc1a3d052,
MIT. model.py is the unmodified upstream implementation at commit 5c9869d.
Usage: python othello_generate.py --weights DIR --output othello-data.json
Requires torch and numpy. DIR contains epoch_250.ckpt and classic_board_L1..L8.
Only previously evaluated sequences are exposed by the browser widget.
"""
import argparse,json
from pathlib import Path
import numpy as np
import torch
from metaothello_model import GPT,GPTConfig

p=argparse.ArgumentParser();p.add_argument('--weights',required=True);p.add_argument('--output',default='othello-data.json');args=p.parse_args()
directory=Path(args.weights);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model=GPT(GPTConfig(66,59,n_layer=8,n_head=8,n_embd=512)).to(device)
model.load_state_dict(torch.load(directory/'epoch_250.ckpt',map_location=device,weights_only=True));model.eval()
probes=[]
for k in range(1,9):
    state=torch.load(directory/f'classic_board_L{k}.ckpt',map_location=device,weights_only=True)
    probe=torch.nn.Linear(512,192).to(device);probe.load_state_dict(state,strict=False) if 'weight' in state else probe.load_state_dict({k.removeprefix('proj.'):v for k,v in state.items()})
    probe.eval();probes.append(probe)
directions=[(dr,dc) for dr in [-1,0,1] for dc in [-1,0,1] if (dr,dc)!=(0,0)]
def flips(board,move,color):
    r,c=divmod(move,8)
    if board[r,c]!=0:return []
    result=[]
    for dr,dc in directions:
        x,y=r+dr,c+dc;line=[]
        while 0<=x<8 and 0<=y<8 and board[x,y]==-color:
            line.append((x,y));x+=dr;y+=dc
        if line and 0<=x<8 and 0<=y<8 and board[x,y]==color:result+=line
    return result
def legal(board,color):return [i for i in range(64) if flips(board,i,color)]
def play(board,move,color):
    result=board.copy();r,c=divmod(move,8);result[r,c]=color
    for x,y in flips(board,move,color):result[x,y]=color
    return result
initial=np.zeros((8,8),dtype=int);initial[3,3]=initial[4,4]=1;initial[3,4]=initial[4,3]=-1

# Sondas absolutas separadas: una sola posición por partida independiente.
# Se usan longitudes 6–30, evitando entrenar en las aperturas del visualizador.
rng=np.random.default_rng(14);examples=[]
while len(examples)<1200:
    board=initial.copy();color=-1;seq=[];length=int(rng.integers(6,31))
    for _ in range(length):
        options=legal(board,color)
        if not options:break
        move=int(rng.choice(options));board=play(board,move,color);color=-color;seq.append(move)
    if len(seq)==length:examples.append((seq,board.ravel().copy()))

features=[None]*len(examples)
for length in range(6,31):
    ids=[i for i,(seq,_) in enumerate(examples) if len(seq)==length]
    for start in range(0,len(ids),32):
        group=ids[start:start+32];tokens=torch.tensor([[v+1 for v in examples[i][0]] for i in group],device=device)
        captured=[];handles=[block.register_forward_hook(lambda module,inputs,out:captured.append(out.detach())) for block in model.blocks]
        with torch.no_grad():model(tokens)
        for h in handles:h.remove()
        state=torch.stack([h[:,-1,:] for h in captured],dim=1).cpu().numpy()
        for idx,value in zip(group,state):features[idx]=value
    print('extracción de sondas absolutas, longitud',length,flush=True)
features=np.asarray(features);boards=np.asarray([b for _,b in examples]);train=1000
ridge=np.eye(513)*.5;ridge[-1,-1]=0
absolute=[];absolute_scores=[];relative_scores=[]
for k,probe in enumerate(probes):
    A=np.c_[features[:,k,:],np.ones(len(features))]
    target=np.eye(3)[boards[:train]+1].reshape(train,-1)
    coefficients=np.linalg.solve(A[:train].T@A[:train]+ridge,A[:train].T@target)
    absolute.append(coefficients)
    prediction=(A[train:]@coefficients).reshape(-1,64,3).argmax(2)-1
    absolute_scores.append(float((prediction==boards[train:]).mean()))
    with torch.no_grad():
        relative=probe(torch.as_tensor(features[train:,k,:],device=device)).reshape(-1,64,3).argmax(2).cpu().numpy()-1
    mover=np.array([-1 if len(examples[i][0])%2 else 1 for i in range(train,len(examples))])
    relative_scores.append(float((relative*mover[:,None]==boards[train:]).mean()))
print('exactitudes en 200 partidas independientes: absolutas',absolute_scores,'relativas',relative_scores,flush=True)

nodes=[]
def tree(board,color,seq):
    if seq:nodes.append((board.copy(),color,seq.copy()))
    if len(seq)==3:return
    for move in legal(board,color):tree(play(board,move,color),-color,seq+[move])
tree(initial,-1,[])
payload=[]
for index,(board,color,seq) in enumerate(nodes):
    tokens=torch.tensor([[move+1 for move in seq]],device=device);captured=[];handles=[]
    for block in model.blocks:
        handles.append(block.register_forward_hook(lambda module,inputs,out:captured.append(out.detach())))
    with torch.no_grad():base=model(tokens)[0][0,-1]
    for h in handles:h.remove()
    layers=[];square=seq[-1]
    for k,(state,probe) in enumerate(zip(captured,probes)):
        with torch.no_grad():
            prediction=probe(state[0,-1]).reshape(64,3).argmax(1).cpu().numpy()-1
            weights=probe.weight.reshape(64,3,512);direction=weights[square,2]-weights[square,0]
            direction=direction/torch.linalg.vector_norm(direction)
            prediction_edited=probe(state[0,-1]+6*direction).reshape(64,3).argmax(1).cpu().numpy()-1
            vec=state[0,-1].cpu().numpy();edited_vec=(state[0,-1]+6*direction).cpu().numpy()
            absolute_prediction=(np.r_[vec,1]@absolute[k]).reshape(64,3).argmax(1)-1
            absolute_edited=(np.r_[edited_vec,1]@absolute[k]).reshape(64,3).argmax(1)-1
            def edit(module,inputs,out):
                result=out.clone();result[:,-1,:]+=6*direction;return result
            hook=model.blocks[k].register_forward_hook(edit)
            try:changed=model(tokens)[0][0,-1]
            finally:hook.remove()
        layers.append({'relative':prediction.tolist(),'edited_relative':prediction_edited.tolist(),
                       'absolute':absolute_prediction.tolist(),'edited_absolute':absolute_edited.tolist(),
                       'edited_logits':changed[1:65].cpu().tolist()})
    payload.append({'sequence':seq,'board':board.ravel().tolist(),'next_color':color,
      'legal':legal(board,color),'square':square,'logits':base[1:65].cpu().tolist(),'layers':layers})
    print('nodo',index+1,'/',len(nodes),flush=True)
out=Path(args.output);out.parent.mkdir(parents=True,exist_ok=True)
out.write_text(json.dumps({'nodes':payload,'model_revision':'988a3ef4b3de2e27c406990472ec5aabc1a3d052',
 'absolute_train_games':train,'absolute_test_games':len(examples)-train,'absolute_accuracy':absolute_scores,
 'relative_accuracy':relative_scores,'intervention_scale':6,'max_moves':3},separators=(',',':')),encoding='utf-8')
