"""Shared export machinery for every model page.

ONNX has no autograd, so a gradient has to be part of the exported graph. VGG16's backward pass is
written out by hand in export_vgg16.py. For everything else, `export_graph` traces any function
(including `torch.func.grad` of a model) into plain aten ops with make_fx. It then rewrites the few
backward ops the ONNX exporter can't translate into forward ops that compute the same thing:
convolution_backward → conv_transpose2d (or conv2d for a transposed conv), max-pool backward → scatter_add, nearest-upsample
backward → block sums, bilinear-upsample backward → transposed interpolation matrices. The result is an ordinary
inference graph that onnxruntime-web can run.

Every export also saves its inputs and PyTorch's outputs to export/testvecs/, and validate.py checks
the ONNX graphs against them.
"""
import collections
import hashlib
import math
import pathlib

import numpy as np
import onnx
import torch
import torch.nn.functional as F
from onnx import TensorProto, helper, numpy_helper
from onnx.external_data_helper import set_external_data
from torch._decomp import core_aten_decompositions
from torch.fx.experimental.proxy_tensor import make_fx

ROOT = pathlib.Path(__file__).resolve().parent.parent
WEB_MODELS = ROOT / "web" / "models"
CACHE = ROOT / "export" / "cache"
TESTVECS = ROOT / "export" / "testvecs"
aten = torch.ops.aten


def _conv_backward(grad, inp, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, mask):
    assert inp.dim() == 4
    if transposed:
        # the input gradient of a transposed convolution is an ordinary convolution with the same weights
        assert groups == 1
        return F.conv2d(grad, weight, None, stride, padding, dilation), None, None
    # output_padding recovers the input size that the forward stride rounded away
    op = [inp.shape[2 + i] - ((grad.shape[2 + i] - 1) * stride[i] - 2 * padding[i]
                              + dilation[i] * (weight.shape[2 + i] - 1) + 1) for i in range(2)]
    return F.conv_transpose2d(grad, weight, None, stride, padding, op, groups, dilation), None, None


def _maxpool_backward(grad, inp, kernel, stride, padding, dilation, ceil_mode, indices):
    n, c, h, w = inp.shape
    out = torch.zeros(n, c, h * w, dtype=grad.dtype)
    return out.scatter_add(2, indices.flatten(2), grad.flatten(2)).view(n, c, h, w)


def _maxpool_with_indices(x, kernel, stride=(), padding=(0, 0), dilation=(1, 1), ceil_mode=False):
    # Max over shifted strided slices + argmax. onnxruntime-web's WebGPU MaxPool doesn't produce the
    # Indices output, which the backward pass needs, so the indices are computed here instead.
    assert not ceil_mode and tuple(dilation) == (1, 1)
    kh, kw = kernel if len(kernel) == 2 else (kernel[0], kernel[0])
    sh, sw = (stride if len(stride) == 2 else (stride[0], stride[0])) if len(stride) else (kh, kw)
    ph, pw = padding if len(padding) == 2 else (padding[0], padding[0])
    n, c, h, w = x.shape
    oh, ow = (h + 2 * ph - kh) // sh + 1, (w + 2 * pw - kw) // sw + 1
    xp = F.pad(x, (pw, pw, ph, ph), value=float("-inf"))
    views = [xp[:, :, i:i + sh * (oh - 1) + 1:sh, j:j + sw * (ow - 1) + 1:sw] for i in range(kh) for j in range(kw)]
    val, arg = torch.stack(views, -1).max(-1)
    rows = torch.arange(oh, device=x.device).view(oh, 1) * sh + arg // kw - ph
    cols = torch.arange(ow, device=x.device) * sw + arg % kw - pw
    return val, rows * w + cols


def _upsample_nearest_backward(grad, output_size, input_size, scales_h=None, scales_w=None):
    # integer nearest upsampling copies each input pixel into an sh×sw block: its gradient is the block sum
    n, c, h, w = input_size
    sh, sw = grad.shape[2] // h, grad.shape[3] // w
    assert sh * h == grad.shape[2] and sw * w == grad.shape[3], "only integer scale factors"
    return grad.reshape(n, c, h, sh, w, sw).sum((3, 5))


def _bilinear_matrix(n_out, n_in, align_corners, scale=None):
    """The [n_out, n_in] matrix of 1-D bilinear interpolation, as PyTorch computes it."""
    a = np.zeros((n_out, n_in), np.float32)
    for i in range(n_out):
        if align_corners:
            src = i * (n_in - 1) / (n_out - 1) if n_out > 1 else 0.0
        else:
            ratio = 1.0 / scale if scale else n_in / n_out
            src = max(0.0, (i + 0.5) * ratio - 0.5)
        i0 = min(int(np.floor(src)), n_in - 1)
        i1 = min(i0 + 1, n_in - 1)
        lam = src - i0
        a[i, i0] += 1 - lam
        a[i, i1] += lam
    return a


def _upsample_bilinear_backward(grad, output_size, input_size, align_corners, scales_h=None, scales_w=None):
    # bilinear resizing is out = A_h · x · A_wᵀ per channel, so its gradient is A_hᵀ · g · A_w
    n, c, h, w = input_size
    ah = torch.from_numpy(_bilinear_matrix(output_size[0], h, align_corners, scales_h)).to(grad.device)
    aw = torch.from_numpy(_bilinear_matrix(output_size[1], w, align_corners, scales_w)).to(grad.device)
    return torch.einsum("oh,ncop,pw->nchw", ah, grad, aw)


def _upsample_bilinear(x, output_size, align_corners, scales_h=None, scales_w=None):
    # bilinear resizing as two small constant matrix products: both the default decomposition and the
    # ONNX exporter turn it into index gathers, which run several times slower on WebGPU
    ah = torch.from_numpy(_bilinear_matrix(output_size[0], x.shape[2], align_corners, scales_h)).to(x.device)
    aw = torch.from_numpy(_bilinear_matrix(output_size[1], x.shape[3], align_corners, scales_w)).to(x.device)
    return torch.einsum("oh,nchw,pw->ncop", ah, x, aw)


DECOMPOSITIONS = dict(core_aten_decompositions())
DECOMPOSITIONS[aten.upsample_bilinear2d.default] = _upsample_bilinear
DECOMPOSITIONS[aten.upsample_bilinear2d_backward.default] = _upsample_bilinear_backward
DECOMPOSITIONS[aten.upsample_nearest2d_backward.default] = _upsample_nearest_backward
DECOMPOSITIONS[aten.max_pool2d_with_indices.default] = _maxpool_with_indices
DECOMPOSITIONS[aten.convolution_backward.default] = _conv_backward
DECOMPOSITIONS[aten.max_pool2d_with_indices_backward.default] = _maxpool_backward


def math_sdpa(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, **_):
    """Attention as matmul + softmax, so its backward traces into ops ONNX has."""
    s = (q @ k.transpose(-2, -1)) * (scale or 1 / math.sqrt(q.shape[-1]))
    if is_causal:
        L, S = q.shape[-2], k.shape[-2]
        s = s.masked_fill(torch.ones(L, S, dtype=torch.bool, device=q.device).triu(1), float("-inf"))
    if attn_mask is not None:
        s = s.masked_fill(~attn_mask, float("-inf")) if attn_mask.dtype == torch.bool else s + attn_mask
    return s.softmax(-1) @ v


F.scaled_dot_product_attention = math_sdpa


def export_graph(fn, args, path, input_names, output_names, testvec=True, optimize=True):
    """Trace fn(*args) (which may take gradients) to aten ops and save it as an ONNX graph.

    optimize=False skips the ONNX optimiser, whose constant folding stores transposed copies of
    weight matrices (used by backward passes) as new tensors that share_weights can't deduplicate.
    """
    path = pathlib.Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    gm = make_fx(fn, decomposition_table=DECOMPOSITIONS)(*args).eval()
    left = [str(n.target) for n in gm.graph.nodes if n.op == "call_function" and "backward" in str(n.target)]
    assert not left, f"untranslated backward ops: {left}"
    # uninitialised buffers that decompositions allocate and then fill: zeros are equivalent and exportable
    for n in gm.graph.nodes:
        if n.op == "call_function" and n.target in (aten.empty_permuted.default, aten.empty.memory_format):
            n.target, n.args = aten.zeros.default, (n.args[0],)
            n.kwargs = {k: v for k, v in n.kwargs.items() if k in ("dtype", "device")}
    gm.recompile()
    torch.onnx.export(gm, tuple(args), str(path), dynamo=True, optimize=optimize,
                      input_names=input_names, output_names=output_names, external_data=False)
    if testvec:
        outs = fn(*args)
        outs = outs if isinstance(outs, (tuple, list)) else (outs,)
        vec = {f"in:{n}": a.detach().cpu().numpy() for n, a in zip(input_names, args)}
        vec.update({f"out:{n}": o.detach().cpu().numpy() for n, o in zip(output_names, outs)})
        out = TESTVECS / path.parent.name / (path.stem + ".npz")
        out.parent.mkdir(parents=True, exist_ok=True)
        np.savez(out, **vec)
    return path


@torch.no_grad()
def fold_bn(conv, bn):
    """Fold an eval-mode BatchNorm into the conv before it, in place; returns an Identity for bn.

    Done before tracing so every graph sees the same conv weights and share_weights can store them once.
    """
    k = bn.weight / torch.sqrt(bn.running_var + bn.eps)
    conv.weight.mul_(k.view(-1, 1, 1, 1))
    bias = (conv.bias if conv.bias is not None else torch.zeros_like(bn.running_mean)) - bn.running_mean
    conv.bias = torch.nn.Parameter(bias * k + bn.bias, requires_grad=False)
    return torch.nn.Identity()


def quantize_weights(path, min_size=1_000_000):
    """Store big 2-D float initializers as int8 with one scale per output unit + DequantizeLinear.

    The scale runs along the axis that indexes output units: axis 1 for the B input of MatMul
    ([in, out]), axis 0 otherwise (Gemm with transB, embedding tables read by Gather).
    """
    model = onnx.load(str(path))
    g = model.graph
    consumers = collections.defaultdict(list)
    for n in g.node:
        for i, name in enumerate(n.input):
            consumers[name].append((n.op_type, i))
    keep, nodes = [], []
    for t in g.initializer:
        w = numpy_helper.to_array(t)
        if t.data_type != TensorProto.FLOAT or w.ndim != 2 or w.size < min_size:
            keep.append(t)
            continue
        axis = 1 if ("MatMul", 1) in consumers[t.name] else 0
        scale = (np.abs(w).max(axis=1 - axis) / 127.0).astype(np.float32)
        scale[scale == 0] = 1.0
        q = np.clip(np.round(w / np.expand_dims(scale, 1 - axis)), -127, 127).astype(np.int8)
        keep += [numpy_helper.from_array(q, t.name + "_q"), numpy_helper.from_array(scale, t.name + "_scale"),
                 numpy_helper.from_array(np.zeros_like(scale, dtype=np.int8), t.name + "_zp")]
        nodes.append(helper.make_node("DequantizeLinear", [t.name + "_q", t.name + "_scale", t.name + "_zp"],
                                      [t.name], axis=axis, name=t.name + "_dequant"))
    del g.initializer[:]
    g.initializer.extend(keep)
    old = list(g.node)
    del g.node[:]
    g.node.extend(nodes + old)
    onnx.save(model, str(path))
    return len(nodes)


def share_weights(paths, bin_name, min_bytes=4096):
    """Move every initializer of at least min_bytes out of the graphs into one binary file.

    Identical tensors (the same weights traced into several graphs) are stored once. A matrix that is
    the transpose of one already stored (the optimiser pre-transposes weights for MatMul in one graph
    and not in another) is read from the stored bytes and turned back by one Transpose node. The browser
    downloads the .bin once and hands it to every session through the `externalData` option.
    """
    paths = [pathlib.Path(p) for p in paths]
    bin_path = paths[0].parent / bin_name
    stored, blob = {}, bytearray()
    key = lambda dtype, dims, raw: hashlib.sha1(f"{dtype}{list(dims)}".encode() + raw).hexdigest()
    for p in paths:
        model = onnx.load(str(p))
        transposes = []
        for t in model.graph.initializer:
            arr = numpy_helper.to_array(t)
            raw = arr.tobytes()
            if len(raw) < min_bytes:
                continue
            k = key(t.data_type, t.dims, raw)
            if k not in stored and arr.ndim == 2:
                kt = key(t.data_type, arr.shape[::-1], np.ascontiguousarray(arr.T).tobytes())
                if kt in stored:
                    # store nothing new: read the transposed copy and transpose it back at run time
                    name = t.name
                    t.name = name + "__T"
                    t.dims[:] = list(arr.shape[::-1])
                    transposes.append(helper.make_node("Transpose", [t.name], [name], perm=[1, 0], name=name + "__transpose"))
                    k = kt
            if k not in stored:
                blob += b"\0" * (-len(blob) % 64)
                stored[k] = (len(blob), len(raw))
                blob += raw
            offset, length = stored[k]
            set_external_data(t, bin_name, offset, length)
            t.data_location = TensorProto.EXTERNAL
            for f in ("raw_data", "float_data", "int32_data", "int64_data", "double_data"):
                t.ClearField(f)
        if transposes:
            nodes = list(model.graph.node)
            del model.graph.node[:]
            model.graph.node.extend(transposes + nodes)
        onnx.save(model, str(p))
    bin_path.write_bytes(bytes(blob))
    return bin_path, len(blob)


def content_version(path):
    """A short hash of a weight file, used as meta.json's version so browsers never keep stale weights."""
    return hashlib.sha1(pathlib.Path(path).read_bytes()).hexdigest()[:12]


class OnnxNet(torch.nn.Module):
    """Runs a small ONNX inference graph with torch ops, so it can be traced and differentiated.

    Covers what the face models here use: Conv, (Leaky)Relu, Mul, Add, Sigmoid, global AveragePool,
    Transpose, Concat, nearest Resize, Softmax, and Reshape/Resize with constant shapes (int64
    initializers and Concats of them are folded into Python ints, since reading shapes from tensors
    during tracing is data-dependent). Keeps every intermediate value in self.values.
    """

    def __init__(self, path):
        super().__init__()
        m = onnx.load(str(path))
        self.nodes = list(m.graph.node)
        self.input = m.graph.input[0].name
        self.outputs = [o.name for o in m.graph.output]
        self.consts, self.ints = {}, {}
        for i, t in enumerate(m.graph.initializer):
            a = numpy_helper.to_array(t)
            if t.data_type == TensorProto.INT64:
                self.ints[t.name] = [int(d) for d in a.ravel()]
            else:
                self.register_buffer(f"c{i}", torch.from_numpy(a.copy()))
                self.consts[t.name] = f"c{i}"
        # fold Concats of int constants (Resize sizes)
        for n in self.nodes:
            if n.op_type == "Concat" and n.input and all(i in self.ints for i in n.input):
                self.ints[n.output[0]] = [d for i in n.input for d in self.ints[i]]

    def forward(self, x):
        v = {self.input: x}
        get = lambda name: v[name] if name in v else getattr(self, self.consts[name])
        for n in self.nodes:
            if n.output[0] in self.ints:
                continue
            a = {at.name: helper.get_attribute_value(at) for at in n.attribute}
            op = n.op_type
            if op == "Reshape":
                x0 = get(n.input[0])
                y = x0.reshape(x0.shape[0], *self.ints[n.input[1]][1:])
            elif op == "Resize":
                x0 = get(n.input[0])
                assert a.get("mode", b"nearest") == b"nearest"
                sizes = self.ints.get(n.input[3]) if len(n.input) > 3 and n.input[3] else None
                y = F.interpolate(x0, size=sizes[2:]) if sizes else F.interpolate(x0, scale_factor=2.0)
            else:
                ins = [get(i) for i in n.input if i]
                if op == "Conv":
                    t, l, bt, r = a.get("pads", [0, 0, 0, 0])
                    y = F.conv2d(F.pad(ins[0], (l, r, t, bt)), ins[1], ins[2] if len(ins) > 2 else None,
                                 a.get("strides", [1, 1]), 0, a.get("dilations", [1, 1]), a.get("group", 1))
                elif op == "LeakyRelu":
                    y = torch.where(ins[0] >= 0, ins[0], ins[0] * a.get("alpha", 0.01))
                elif op == "Relu":
                    y = torch.relu(ins[0])
                elif op == "Mul":
                    y = ins[0] * ins[1]
                elif op == "Add":
                    y = ins[0] + ins[1]
                elif op == "Sigmoid":
                    y = torch.sigmoid(ins[0])
                elif op == "AveragePool":
                    assert a["kernel_shape"] == list(ins[0].shape[2:]), "only global average pooling"
                    y = ins[0].mean((2, 3), keepdim=True)
                elif op == "Transpose":
                    y = ins[0].permute(*a["perm"])
                elif op == "Concat":
                    y = torch.cat(ins, a["axis"])
                elif op == "Softmax":
                    y = torch.softmax(ins[0], a.get("axis", -1))
                else:
                    raise NotImplementedError(op)
            v[n.output[0]] = y
        self.values = v
        outs = [v[o] for o in self.outputs]
        return outs[0] if len(outs) == 1 else tuple(outs)

