#!/usr/bin/env python3
"""ST-GCN++ -> ONNX export with ZERO Transpose nodes (RV1106 NPU friendly).

Why: the original export (``export_onnx.py``) still contained Transpose nodes
(data_bn permutes, ``adjacency.t()`` and the ``permute`` inside the matmul
patch of ``AdaptiveGraphConv``).  The RV1106 NPU cannot execute those
(32x42 pixel block exceeds the NPU limit), the toolkit falls back to CPU for
those nodes, and the converted rv1106 model ignores its input at runtime
(constant logits for every window, verified on the board 2026-09-19).

This export rewrites the forward pass so the graph contains only
Conv / BatchNorm / ReLU / MatMul / MaxPool / GlobalAveragePool / Flatten /
Gemm / Mul / Add:

* ``data_bn`` (BatchNorm1d over the flattened C*V axis) is folded into a
  per-(channel, vertex) affine ``x * scale + shift``,
* the adaptive adjacency ``base + 0.10 * tanh(residual)`` is pre-computed per
  block and stored *transposed* as a constant buffer,
* ``einsum("vw,nctw->nctv")`` becomes ``reshape + matmul + reshape`` over
  flattened (n, c, t) rows.

Numerically the graph is identical; the script asserts that in the floating
point domain (PyTorch self-check + comparison against the v1 ONNX when it is
present).

Usage::

    /root/mmpose-venv/bin/python export_onnx_v2.py --models 2d
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import torch
from torch import nn

REPO = Path("/root/handwash-st-gcn")
sys.path.insert(0, str(REPO / "stgcnpp_window_training" / "scripts"))

from train_window_stgcnpp import AdaptiveGraphConv, HandSTGCNPlusPlus  # noqa: E402

MODELS = {
    "2d": {
        "checkpoint": REPO / "stgcnpp_window_training/checkpoints/"
        "v2_handwash7_finetune_single_run_20260914/best.pt",
        "input_channels": 3,
    },
    "3d": {
        "checkpoint": REPO / "stgcnpp_window_training/checkpoints/"
        "world3d_grid_mmap_y75_p60_r270_20260916/finetune_best.pt",
        "input_channels": 4,
    },
}
# clip per model, same reasoning as export_onnx.py (INT8 input range)
CLIPS = {"2d": 5.0, "3d": 2.0}
FRAMES = 32
VERTICES = 42


# ---------------------------------------------------------------------------
# forward-pass rewrites (no permute / no transpose anywhere)
# ---------------------------------------------------------------------------

def patched_gcn_forward(self: AdaptiveGraphConv, value: torch.Tensor) -> torch.Tensor:
    """``einsum("vw,nctw->nctv", A, x) + 1x1 conv`` without Transpose/Einsum.

    ``_adjacency_t`` is a constant buffer holding ``A.t()`` so the vertex mix
    is a plain matmul over flattened (n, c, t) rows.
    """
    batch, channels, frames, vertices = value.shape
    flat = value.reshape(batch * channels * frames, vertices)
    mixed = torch.matmul(flat, self._adjacency_t)
    return self.projection(mixed.reshape(batch, channels, frames, vertices))


def patched_model_forward(self: HandSTGCNPlusPlus, value: torch.Tensor) -> torch.Tensor:
    """``HandSTGCNPlusPlus.forward`` with the data_bn permutes folded away."""
    batch, channels, frames, vertices = value.shape
    scale = self._data_bn_scale.reshape(1, channels, 1, vertices)
    shift = self._data_bn_shift.reshape(1, channels, 1, vertices)
    value = value * scale + shift
    for block in self.blocks:
        value = block(value)
    return self.head(value)


AdaptiveGraphConv.forward = patched_gcn_forward
HandSTGCNPlusPlus.forward = patched_model_forward


class ClippedModel(nn.Module):
    """ST-GCN++ with a ``Clip`` node in front of the input tensor."""

    def __init__(self, base: nn.Module, clip: float) -> None:
        super().__init__()
        self.model = base
        self.clip = float(clip)

    def forward(self, value: torch.Tensor) -> torch.Tensor:
        return self.model(torch.clamp(value, -self.clip, self.clip))


# ---------------------------------------------------------------------------
# export
# ---------------------------------------------------------------------------

def load_model(entry: dict) -> HandSTGCNPlusPlus:
    checkpoint = torch.load(entry["checkpoint"], map_location="cpu")
    model = HandSTGCNPlusPlus(len(checkpoint["labels"]), input_channels=entry["input_channels"])
    model.load_state_dict(checkpoint["model_state"], strict=True)
    model.eval()

    # freeze the adaptive adjacency per block into a constant transposed buffer
    with torch.no_grad():
        gcn_modules = [m for m in model.modules() if isinstance(m, AdaptiveGraphConv)]
        for module in gcn_modules:
            adjacency = module.base_adjacency + 0.10 * torch.tanh(module.topology_residual)
            module.register_buffer("_adjacency_t", adjacency.t().contiguous())

        # fold data_bn (BatchNorm1d over C*V) into a per-(channel, vertex) affine
        bn = model.data_bn
        scale = bn.weight.detach() / torch.sqrt(bn.running_var + bn.eps)
        shift = bn.bias.detach() - bn.running_mean * scale
        model.register_buffer("_data_bn_scale", scale.clone())
        model.register_buffer("_data_bn_shift", shift.clone())

    print(f"    loaded {len(checkpoint['model_state'])} tensors, "
          f"input_channels={entry['input_channels']}, labels={checkpoint['labels']}, "
          f"folded {len(gcn_modules)} adjacency modules + data_bn")
    return model


def export(tag: str, entry: dict, output_dir: Path, clip: float, stem: str) -> tuple[Path, np.ndarray]:
    model = load_model(entry)
    wrapped = ClippedModel(model, clip).eval() if clip > 0 else model.eval()
    probe = np.random.RandomState(1234).randn(1, entry["input_channels"], FRAMES, VERTICES)
    probe = probe.astype(np.float32)
    probe[0, 0, 0, 0] = 40.0  # true extreme so the Clip node is exercised
    dummy = torch.from_numpy(probe)

    onnx_path = output_dir / f"{stem}.onnx"
    torch.onnx.export(
        wrapped, dummy, str(onnx_path), opset_version=12,
        input_names=["input"], output_names=["logits"],
        do_constant_folding=True, dynamic_axes=None,
    )
    with torch.no_grad():
        torch_logits = wrapped(dummy).numpy()
    np.save(output_dir / f"probe_{tag}_v2.npy", probe)
    print(f"    onnx: {onnx_path.name} ({onnx_path.stat().st_size / 1024:.1f} KB), clip=±{clip}")
    return onnx_path, torch_logits


def verify(onnx_path: Path, probe_path: Path, torch_logits: np.ndarray,
           reference: Path | None) -> None:
    import onnx
    import onnxruntime as ort

    onnx.checker.check_model(str(onnx_path))
    graph = onnx.load(str(onnx_path))
    ops = sorted({node.op_type for node in graph.graph.node})
    transposes = [node.name for node in graph.graph.node if node.op_type == "Transpose"]
    print(f"    opset={graph.opset_import[0].version}  nodes={len(graph.graph.node)}  ops={ops}")
    print(f"    Transpose nodes: {len(transposes)}" + (f"  {transposes}" if transposes else "  (none)"))

    probe = np.load(probe_path)
    session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    got = session.run(None, {"input": probe})[0]
    delta = float(np.max(np.abs(got - torch_logits)))
    print(f"    onnxruntime vs pytorch: max |diff| = {delta:.3e}, shape={got.shape}")
    if delta > 1e-4:
        raise SystemExit("ONNX export deviates from PyTorch!")

    if reference is not None and reference.is_file():
        ref_session = ort.InferenceSession(str(reference), providers=["CPUExecutionProvider"])
        ref = ref_session.run(None, {"input": probe})[0]
        delta_ref = float(np.max(np.abs(got - ref)))
        print(f"    v2 vs v1 ONNX: max |diff| = {delta_ref:.3e}")
        if delta_ref > 1e-4:
            raise SystemExit("v2 export deviates from the v1 export!")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-dir", type=Path, default=Path(__file__).parent / "output")
    parser.add_argument("--clip", type=float, default=None, help="override the clip of every model (0 = no Clip node)")
    parser.add_argument("--stem", default=None, help="output file stem (default handwash_stgcn_<tag>_v2)")
    parser.add_argument("--models", nargs="+", default=list(MODELS), choices=list(MODELS))
    args = parser.parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)

    for tag in args.models:
        entry = MODELS[tag]
        clip = args.clip if args.clip is not None else CLIPS[tag]
        stem = args.stem or f"handwash_stgcn_{tag}_v2"
        print(f"==> {tag}: {entry['checkpoint'].name}")
        onnx_path, torch_logits = export(tag, entry, args.output_dir, clip, stem)
        reference = args.output_dir / f"handwash_stgcn_{tag}.onnx" if clip > 0 else None
        verify(onnx_path, args.output_dir / f"probe_{tag}_v2.npy", torch_logits, reference)
    print("done")


if __name__ == "__main__":
    main()
