"""Implement scalar reverse-mode autodiff and backpropagate a small network.

Requires Python 3.10 or newer and NumPy. Run:
    python3 09-chain-rule-autodiff-backprop.py
Install PyTorch for the optional --torch comparison. Predict the shared
product gradient and the inactive ReLU gradient before running the checks.
"""

import argparse

import numpy as np


class Scalar:
    """A real scalar with one saved derivative for each incoming edge."""

    def __init__(self, value, inputs=()):
        self.value = float(value)
        self.inputs = inputs

    def __add__(self, other):
        return Scalar(self.value + other.value, ((self, 1.0), (other, 1.0)))

    def __mul__(self, other):
        return Scalar(
            self.value * other.value,
            ((self, other.value), (other, self.value)),
        )


def backward(output):
    """Return a fresh map of adjoints for a small, acyclic scalar graph."""
    forward_order = []
    seen = set()

    def visit(node):
        if node in seen:
            return
        seen.add(node)
        for parent, _ in node.inputs:
            visit(parent)
        forward_order.append(node)

    visit(output)
    adjoints = {output: 1.0}
    for node in reversed(forward_order):
        upstream = adjoints.get(node, 0.0)
        for parent, local_derivative in node.inputs:
            adjoints[parent] = (
                adjoints.get(parent, 0.0) + upstream * local_derivative
            )
    return adjoints


def network_loss_and_gradients(x, targets, parameters):
    """Evaluate mean half-squared loss and gradients for one output per row."""
    w1, b1, w2, b2 = parameters
    z = x @ w1.T + b1
    hidden = np.maximum(z, 0)
    prediction = hidden @ w2.T + b2
    residual = prediction - targets
    loss = 0.5 * np.mean(residual**2)

    output_grad = residual / len(x)
    preactivation_grad = (output_grad @ w2) * (z > 0)
    dw2 = output_grad.T @ hidden
    db2 = output_grad.sum(axis=0)
    dw1 = preactivation_grad.T @ x
    db1 = preactivation_grad.sum(axis=0)
    return loss, (dw1, db1, dw2, db2), preactivation_grad @ w1


def central_difference(x, targets, parameters, parameter_index, step=1e-5):
    """Check a parameter array entry by entry on this deterministic fixture."""
    parameter = parameters[parameter_index]
    approximation = np.empty_like(parameter)
    for entry in np.ndindex(parameter.shape):
        plus = list(parameters)
        minus = list(parameters)
        plus[parameter_index] = parameter.copy()
        minus[parameter_index] = parameter.copy()
        plus[parameter_index][entry] += step
        minus[parameter_index][entry] -= step
        loss_plus, _, _ = network_loss_and_gradients(x, targets, plus)
        loss_minus, _, _ = network_loss_and_gradients(x, targets, minus)
        approximation[entry] = (loss_plus - loss_minus) / (2 * step)
    return approximation


def check_scalar_graph():
    a = Scalar(2.0)
    b = Scalar(3.0)
    shared = a * b
    loss = shared * shared + Scalar(3.0) * shared
    gradients = backward(loss)
    assert loss.value == 54.0
    assert gradients[shared] == 15.0
    assert gradients[a] == 45.0
    assert gradients[b] == 30.0
    assert backward(loss) == gradients

    cancellation = shared * shared + Scalar(-12.0) * shared
    assert backward(cancellation)[shared] == 0.0

    # A weighted pair of vector outputs implements the same VJP as J.T @ g.
    weighted_outputs = Scalar(2.0) * shared + Scalar(-1.0) * (a + b)
    vjp = backward(weighted_outputs)
    jacobian = np.array([[3.0, 2.0], [1.0, 1.0]])
    np.testing.assert_allclose([vjp[a], vjp[b]], jacobian.T @ [2.0, -1.0])
    print("Shared node and VJP checks passed. Input gradients were 45 and 30.")


def check_torch(x, targets, parameters):
    import torch

    dtype = torch.float64
    a, b = (torch.tensor(v, dtype=dtype, requires_grad=True) for v in (2.0, 3.0))
    outputs = torch.stack((a * b, a + b))
    gradients = torch.autograd.grad(outputs, (a, b), outputs.new_tensor([2, -1]))
    assert tuple(g.item() for g in gradients) == (5.0, 3.0)
    assert a.grad is None and b.grad is None

    x_tensor = torch.tensor(x, dtype=dtype, requires_grad=True)
    target_tensor = torch.tensor(targets, dtype=dtype)
    params = tuple(torch.tensor(p, dtype=dtype, requires_grad=True) for p in parameters)

    def loss():
        w1, b1, w2, b2 = params
        hidden = (x_tensor @ w1.T + b1).relu()
        prediction = hidden @ w2.T + b2
        return 0.5 * (prediction - target_tensor).square().mean()

    expected_loss, expected_grads, expected_input_grad = network_loss_and_gradients(
        x, targets, parameters
    )
    expected = (*expected_grads, expected_input_grad)
    leaves = (*params, x_tensor)
    optimizer = torch.optim.SGD(params, lr=0.01)

    first_loss = loss()
    np.testing.assert_allclose(first_loss.item(), expected_loss)
    first_loss.backward()
    for leaf, gradient in zip(leaves, expected, strict=True):
        np.testing.assert_allclose(leaf.grad.numpy(), gradient, atol=1e-12)

    loss().backward()
    for leaf, gradient in zip(leaves, expected, strict=True):
        np.testing.assert_allclose(leaf.grad.numpy(), 2 * gradient, atol=1e-12)

    optimizer.zero_grad(set_to_none=True)
    x_tensor.grad = None
    assert all(leaf.grad is None for leaf in leaves)
    loss().backward()
    for leaf, gradient in zip(leaves, expected, strict=True):
        np.testing.assert_allclose(leaf.grad.numpy(), gradient, atol=1e-12)

    zero = torch.tensor(0.0, dtype=dtype, requires_grad=True)
    zero.relu().backward()
    assert zero.grad.item() == 0.0
    print("PyTorch seed, network parity, accumulation, clearing and ReLU checks passed.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--torch", action="store_true", help="Check PyTorch parity.")
    args = parser.parse_args()
    check_scalar_graph()

    x = np.array([[2.0, -1.0], [1.0, 2.0]])
    targets = np.array([[2.0], [0.0]])
    parameters = (
        np.array([[1.0, 2.0], [-1.0, 1.0]]),
        np.array([1.0, 1.0]),
        np.array([[3.0, -2.0]]),
        np.array([1.0]),
    )
    loss, gradients, input_grad = network_loss_and_gradients(
        x[:1], targets[:1], parameters
    )
    assert loss == 2.0
    expected = ([[12, -6], [0, 0]], [6, 0], [[2, 0]], [2])
    for gradient, hand_result in zip(gradients, expected, strict=True):
        np.testing.assert_allclose(gradient, hand_result)
    np.testing.assert_allclose(input_grad, [[6, 12]])

    duplicated_loss, duplicated_gradients, _ = network_loss_and_gradients(
        x[[0, 0]], targets[[0, 0]], parameters
    )
    assert duplicated_loss == loss
    for original, duplicated in zip(gradients, duplicated_gradients, strict=True):
        np.testing.assert_allclose(duplicated, original)

    batch_loss, batch_gradients, _ = network_loss_and_gradients(x, targets, parameters)
    for index, gradient in enumerate(batch_gradients):
        numerical = central_difference(x, targets, parameters, index)
        np.testing.assert_allclose(gradient, numerical, rtol=1e-7, atol=1e-7)
    print(f"Hand example and batch finite differences passed. Batch loss: {batch_loss}.")

    if args.torch:
        check_torch(x, targets, parameters)

    # Try it yourself:
    # 1. Replace the linear branch's coefficient with -12 and predict the sum.
    # 2. Duplicate the first row and compare mean with sum reduction.
    # 3. Use an output seed of [1, 0] to recover the first Jacobian row.


if __name__ == "__main__":
    main()
