# HOJA DE RUTA DEL FUTURO · PASO 1 · TRAMO A (AJEDREZ · 1-oct-2026): rehacer el ONNX de Maia-3-5M para el juguete.
# Por qué existe: B2 exportó SOLO la cabeza de jugadas («el valor WDL se puede agregar después», exportar_onnx.py) y el paso 1
# pide W/D/L para la nota de rendirse y tablas (B3 §5). Aquí salen las DOS cabezas (jugadas + valor), en fp32 y en int8 (pesos de
# MatMul/Gemm a 8 bits, como B2: las Conv cuantizadas no existen en el WASM del navegador), y cada ONNX se COMPRUEBA contra
# PyTorch en las MISMAS 2.000 posiciones de B2 (125 de cada casilla franja × control) y contra la política guardada en el rastro.
# También deja los FIXTURES para las pruebas del juguete (pruebas/datos/): las 2.000 posiciones con su política de referencia y
# los tokens exactos de Python, para que maia.js se mida byte a byte.
import sys, os, json, time, hashlib
import numpy as np, pandas as pd, torch, chess, onnx, onnxruntime as ort
from onnxruntime.quantization import quantize_dynamic, QuantType

torch.set_num_threads(2)
RAIZ = "/home/claude/paso1"; OUT = f"{RAIZ}/modelos"; FIX = f"{RAIZ}/fixtures"; os.makedirs(OUT, exist_ok=True); os.makedirs(FIX, exist_ok=True)
SUBIDAS = "/mnt/user-data/uploads/MASGAB ENGINE V1/investigaciones/ajedrez-del-futuro"
A = pd.read_parquet(f"{SUBIDAS}/b2-mediciones/06-resultados/posiciones-A-posiciones.parquet")
M = pd.read_parquet(f"{SUBIDAS}/b2-mediciones/06-resultados/maia-maia3-5m.parquet").set_index("id")
PRUEBA = A.groupby("casilla").head(125).reset_index(drop=True)      # las 2.000 de B2 (exportar_onnx.py): 125 por casilla
assert len(PRUEBA) == 2000

sys.path.insert(0, f"{RAIZ}/maia3")
from types import SimpleNamespace
from maia3.model_registry import MODEL_SPECS
from maia3.dataset import tokenize_board, get_historical_tokens
from maia3.utils import get_all_possible_moves, mirror_move
from maia3.uci import load_model
spec = next(s for s in MODEL_SPECS if s.name == "maia3-5m")
cfg = SimpleNamespace(**spec.config, device="cpu", use_amp=False, trust_checkpoint=False, checkpoint_path=f"{SUBIDAS}/descargas/maia3-5m.pt")
mdl = load_model(cfg)
TODAS = get_all_possible_moves(); DIC = {m: i for i, m in enumerate(TODAS)}
assert len(TODAS) == 4352
# RMSNorm escrito a mano para que la exportación lo entienda (como B2): la misma cuenta, x · rsqrt(media(x²) + eps) · peso.
for mod in mdl.modules():
    if isinstance(mod, torch.nn.RMSNorm):
        def fwd(x, mod=mod):
            eps = mod.eps if mod.eps is not None else torch.finfo(x.dtype).eps
            y = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
            return y * mod.weight if mod.weight is not None else y
        mod.forward = fwd


class Envoltura(torch.nn.Module):
    # Las dos cabezas que el juguete usa: logits de las 4.352 jugadas y logits del valor [pierde, tablas, gana] del que mueve.
    def __init__(self, m): super().__init__(); self.m = m
    def forward(self, tokens, self_elo, oppo_elo):
        lm, lv, _ = self.m(tokens, self_elo, oppo_elo)
        return lm, lv


def tablero(r):
    b = chess.Board()
    for u in r.historia_uci.split(): b.push_uci(u)
    assert b.fen() == r.fen
    return b


def historia(b):
    # Como el UCI de Maia-3 con --use_uci_history y como B2: las 8 últimas posiciones, cada una tokenizada a SU turno, la más vieja primero.
    hist, w = [], b.copy()
    for _ in range(cfg.history):
        hist.append(tokenize_board(w))
        if not w.move_stack: break
        w.pop()
    return hist[::-1]


def compacto(tok):
    # Los tokens (64 × 97) como 8 cadenas de 64 letras: la letra es el índice del token (0 = vacío, 1…12 = la pieza), en hex.
    t = tok.numpy(); filas = []
    for h in range(cfg.history):
        bloque = t[:, 12 * h:12 * (h + 1)]
        idx = np.where(bloque.sum(1) > 0, bloque.argmax(1) + 1, 0)
        filas.append("".join("%x" % i for i in idx))
    assert float(t[:, 96].max()) == 0.0 and t.shape == (64, 97)
    return filas


env = Envoltura(mdl).eval()
T, es, eo, legs, legs_uci, hum, fix_pos = [], [], [], [], [], [], []
for r in PRUEBA.itertuples():
    b = tablero(r)
    tok = get_historical_tokens(historia(b), cfg, 0.0, 0.0, 0.0, 0.0)
    T.append(tok); es.append(r.elo); eo.append(r.elo_rival)
    u = [m.uci() for m in b.legal_moves]; legs_uci.append(u); hum.append(r.humana)
    legs.append([DIC[mirror_move(x) if b.turn == chess.BLACK else x] for x in u])
    ref = M.loc[f"A:{r.casilla}:{r.orden}"]
    fix_pos.append({"id": f"A:{r.casilla}:{r.orden}", "fen": r.fen, "historia": r.historia_uci, "elo": int(r.elo), "eloRival": int(r.elo_rival),
                    "humana": r.humana, "favorita": ref.arg, "politica": json.loads(ref.politica), "entropia": round(float(ref.entropia_bits), 6),
                    "pMax": round(float(ref.p_max), 6), "wdl": [round(float(ref.wdl_gana), 6), round(float(ref.wdl_tablas), 6), round(float(ref.wdl_pierde), 6)],
                    "tokens": compacto(tok)})
X, E1, E2 = torch.stack(T), torch.tensor(es), torch.tensor(eo)
t0 = time.time()
with torch.no_grad():
    salidas = [env(X[k:k + 200], E1[k:k + 200], E2[k:k + 200]) for k in range(0, len(X), 200)]
lt = np.concatenate([s[0].numpy() for s in salidas]); lv_t = np.concatenate([s[1].numpy() for s in salidas])
print("PyTorch fp32:", round(time.time() - t0, 1), "s para 2.000", flush=True)

# Posiciones tempranas (0 a 9 jugadas desde el inicio) para la prueba de los tokens: la muestra no las tiene y el juguete sí las juega
# (ahí la historia se rellena con la posición más vieja). Una partida fija, sin azar.
TEMPRANA = "e2e4 c7c5 g1f3 d7d6 d2d4 c5d4 f3d4 g8f6 b1c3".split()
fix_temprano = []
for n in range(len(TEMPRANA) + 1):
    b = chess.Board()
    for u in TEMPRANA[:n]: b.push_uci(u)
    tok = get_historical_tokens(historia(b), cfg, 0.0, 0.0, 0.0, 0.0)
    with torch.no_grad():
        lm, lv = env(tok.unsqueeze(0), torch.tensor([1500]), torch.tensor([1500]))
    u = [m.uci() for m in b.legal_moves]; ix = [DIC[mirror_move(x) if b.turn == chess.BLACK else x] for x in u]
    p = torch.softmax(lm[0, ix].double(), 0).numpy(); loss, draw, win = torch.softmax(lv[0].double(), 0).tolist()
    fix_temprano.append({"fen": b.fen(), "historia": " ".join(TEMPRANA[:n]), "elo": 1500, "eloRival": 1500, "tokens": compacto(tok),
                         "politica": {j: round(float(q), 5) for j, q in zip(u, p) if q >= 1e-4}, "favorita": u[int(p.argmax())],
                         "wdl": [round(win, 6), round(draw, 6), round(loss, 6)]})


def politicas(logits):
    # De los logits a la política sobre las legales (softmax en doble, como B2) y la favorita.
    out = []
    for i, ix in enumerate(legs):
        lg = logits[i][ix].astype(np.float64); e = np.exp(lg - lg.max()); p = e / e.sum()
        out.append(dict(zip(legs_uci[i], p)))
    return out


def wdl(lv):
    e = np.exp(lv.astype(np.float64) - lv.max(1, keepdims=True)); return e / e.sum(1, keepdims=True)   # [pierde, tablas, gana]


def comparar(nombre, pols, w):
    # Contra PyTorch fresco (misma favorita, |ΔP| máximo) y contra la política del rastro de B2 (lo que la prueba del juguete usará).
    pt = politicas(lt); wt = wdl(lv_t)
    fav = [max(p, key=p.get) for p in pols]; fav_t = [max(p, key=p.get) for p in pt]
    dP_t = max(max(abs(p[j] - q[j]) for j in p) for p, q in zip(pols, pt))
    dP_ref = []; fav_ref_ok = 0
    for i, p in enumerate(pols):
        ref = fix_pos[i]["politica"]
        dP_ref.append(max(abs(p[j] - ref.get(j, 0.0)) for j in p))
        fav_ref_ok += (fav[i] == fix_pos[i]["favorita"])
    dW = float(np.abs(w - wt).max())
    return {"misma_favorita_que_pytorch": round(float(np.mean([a == b for a, b in zip(fav, fav_t)])), 4),
            "misma_favorita_que_rastro_b2": round(fav_ref_ok / 2000, 4),
            "dP_max_vs_pytorch": round(float(dP_t), 5), "dP_max_vs_rastro_b2": round(float(max(dP_ref)), 5),
            "dP_p99_vs_rastro_b2": round(float(np.percentile(dP_ref, 99)), 5),
            "acierto_humana": round(float(np.mean([f == h for f, h in zip(fav, hum)])), 4), "dWDL_max_vs_pytorch": round(dW, 5)}


informe = {"posiciones": 2000, "pytorch": comparar("pytorch", politicas(lt), wdl(lv_t))}
print("pytorch", json.dumps(informe["pytorch"]), flush=True)
# El acierto de PyTorch fresco debe ser el de B2 (0,5485) y su política la del rastro (dP ≈ 0): si no, algo cambió y se para aquí.
assert informe["pytorch"]["acierto_humana"] == 0.5485, informe["pytorch"]
# (El rastro guarda la política con 5 decimales y solo P ≥ 1e-4: la diferencia con PyTorch fresco cabe en 1,1e-4 por el redondeo.)
assert informe["pytorch"]["dP_max_vs_rastro_b2"] <= 1.1e-4, informe["pytorch"]

ruta32 = f"{OUT}/maia3-5m-fp32.onnx"
torch.onnx.export(env, (X[:2], E1[:2], E2[:2]), ruta32, input_names=["tokens", "self_elo", "oppo_elo"], output_names=["logits", "valor"],
                  dynamic_axes={"tokens": {0: "n"}, "self_elo": {0: "n"}, "oppo_elo": {0: "n"}, "logits": {0: "n"}, "valor": {0: "n"}},
                  opset_version=17, dynamo=False)
onnx.checker.check_model(onnx.load(ruta32))
ruta8 = f"{OUT}/maia3-5m-int8.onnx"
quantize_dynamic(ruta32, ruta8, weight_type=QuantType.QInt8, op_types_to_quantize=["MatMul", "Gemm"])
# fp16 como B2 (pesos grandes a 16 bits con un Cast a 32 delante; ORT lo pliega al cargar y calcula en fp32): MEDIDO aquí porque el int8
# no cumple |ΔP| ≤ 0,02 (variantes_int8.py) y el fundador decide con las dos cifras del teléfono.
from onnx import helper, numpy_helper, TensorProto
m16 = onnx.load(ruta32); nuevos, casts = [], []
for ini in m16.graph.initializer:
    if ini.data_type == TensorProto.FLOAT and np.prod(ini.dims) >= 16:
        nuevos.append(numpy_helper.from_array(numpy_helper.to_array(ini).astype(np.float16), ini.name + "__fp16"))
        casts.append(helper.make_node("Cast", [ini.name + "__fp16"], [ini.name], to=TensorProto.FLOAT))
    else: nuevos.append(ini)
del m16.graph.initializer[:]; m16.graph.initializer.extend(nuevos); viejos = list(m16.graph.node); del m16.graph.node[:]; m16.graph.node.extend(casts + viejos)
ruta16 = f"{OUT}/maia3-5m-fp16.onnx"; onnx.save(m16, ruta16); onnx.checker.check_model(onnx.load(ruta16))
for v, ruta in (("fp32", ruta32), ("fp16", ruta16), ("int8", ruta8)):
    s = ort.InferenceSession(ruta, providers=["CPUExecutionProvider"]); nombres = [i.name for i in s.get_inputs()]
    t0 = time.time(); lm, lv = [], []
    for k in range(0, 2000, 200):
        o = s.run(None, dict(zip(nombres, [X[k:k + 200].numpy(), E1[k:k + 200].numpy(), E2[k:k + 200].numpy()]))); lm.append(o[0]); lv.append(o[1])
    lm, lv = np.concatenate(lm), np.concatenate(lv)
    informe[v] = {"MB": round(os.path.getsize(ruta) / 1e6, 2), "sha256": hashlib.sha256(open(ruta, "rb").read()).hexdigest(),
                  "ms_por_posicion_nube_ort_cpu": round((time.time() - t0) / 2000 * 1000, 1), **comparar(v, politicas(lm), wdl(lv))}
    print(v, json.dumps(informe[v]), flush=True)
    # Lo que la prueba del juguete va a exigir, medido aquí primero con el ORT de CPU: favorita ≥ 97 % · |ΔP| ≤ 0,02.
    informe[v]["aprueba_favorita_97"] = informe[v]["misma_favorita_que_rastro_b2"] >= 0.97
    informe[v]["aprueba_dP_002"] = informe[v]["dP_max_vs_rastro_b2"] <= 0.02
    informe[v]["MB_gzip"] = round(len(__import__("gzip").compress(open(ruta, "rb").read(), 9)) / 1e6, 2)
json.dump(informe, open(f"{RAIZ}/onnx-comprobacion-paso1.json", "w"), indent=1)
json.dump({"_porque": "Las 2.000 posiciones de B2 (125 por casilla) con la política de referencia del rastro (maia-maia3-5m.parquet, PyTorch fp32) y los tokens exactos de Python; las 10 tempranas son para la historia corta.",
           "fuente": "investigaciones/ajedrez-del-futuro/b2-mediciones/06-resultados (posiciones-A-posiciones.parquet · maia-maia3-5m.parquet)", "historia": cfg.history,
           "tempranas": fix_temprano, "posiciones": fix_pos}, open(f"{FIX}/maia-2000.json", "w"), ensure_ascii=False, separators=(",", ":"))
print("fixture MB:", round(os.path.getsize(f"{FIX}/maia-2000.json") / 1e6, 2))
print("HECHO", json.dumps(informe, indent=1))
