"""The transformer's core math in plain NumPy, matching gpt.py step by step.

No PyTorch needed: use it to check your understanding, print intermediate shapes,
and run the tests on any machine.
"""
from __future__ import annotations

import numpy as np


def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
    x = x - x.max(axis=axis, keepdims=True)  # subtract the max for numerical stability
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)


def layer_norm(x: np.ndarray, gain: np.ndarray, eps: float = 1e-5) -> np.ndarray:
    mean = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)
    return (x - mean) / np.sqrt(var + eps) * gain


def gelu(x: np.ndarray) -> np.ndarray:
    """Exact GELU, x * Phi(x), via the error function (PyTorch's default)."""
    from math import erf, sqrt
    return 0.5 * x * (1.0 + np.vectorize(erf)(x / sqrt(2.0)))


def causal_mask(T: int) -> np.ndarray:
    return np.tril(np.ones((T, T), dtype=bool))


def attention_head(x: np.ndarray, Wq: np.ndarray, Wk: np.ndarray, Wv: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """One causal attention head. x: (T, C); W*: (C, hs). Returns (output (T, hs), weights (T, T))."""
    q, k, v = x @ Wq, x @ Wk, x @ Wv
    scores = q @ k.T / np.sqrt(k.shape[-1])              # how much each token "matches" each other token
    scores = np.where(causal_mask(len(x)), scores, -np.inf)
    weights = softmax(scores, axis=-1)                   # each row sums to 1
    return weights @ v, weights


def multi_head_attention(x: np.ndarray, Wqkv: np.ndarray, Wproj: np.ndarray, n_head: int) -> np.ndarray:
    """Vectorized multi-head attention, the same reshaping as gpt.py. x: (T, C); Wqkv: (C, 3C)."""
    T, C = x.shape
    hs = C // n_head
    q, k, v = np.split(x @ Wqkv, 3, axis=-1)                         # each (T, C)
    q, k, v = (a.reshape(T, n_head, hs).transpose(1, 0, 2) for a in (q, k, v))  # (nh, T, hs)
    scores = q @ k.transpose(0, 2, 1) / np.sqrt(hs)                  # (nh, T, T)
    scores = np.where(causal_mask(T)[None], scores, -np.inf)
    y = softmax(scores) @ v                                          # (nh, T, hs)
    y = y.transpose(1, 0, 2).reshape(T, C)                           # heads side by side
    return y @ Wproj


def block(x: np.ndarray, p: dict, n_head: int) -> np.ndarray:
    """Pre-norm transformer block: residual attention, then residual MLP."""
    x = x + multi_head_attention(layer_norm(x, p["ln1"]), p["Wqkv"], p["Wproj"], n_head)
    x = x + gelu(layer_norm(x, p["ln2"]) @ p["W1"]) @ p["W2"]
    return x


def init_block(C: int, rng: np.random.Generator) -> dict:
    s = 0.02
    return {"ln1": np.ones(C), "ln2": np.ones(C),
            "Wqkv": rng.normal(0, s, (C, 3 * C)), "Wproj": rng.normal(0, s, (C, C)),
            "W1": rng.normal(0, s, (C, 4 * C)), "W2": rng.normal(0, s, (4 * C, C))}


def cross_entropy(logits: np.ndarray, targets: np.ndarray) -> float:
    logp = logits - logits.max(axis=-1, keepdims=True)
    logp = logp - np.log(np.exp(logp).sum(axis=-1, keepdims=True))
    return float(-logp[np.arange(len(targets)), targets].mean())


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    T, C, H = 5, 8, 2
    x = rng.normal(size=(T, C))
    out, w = attention_head(x, *(rng.normal(size=(C, C // H)) for _ in range(3)))
    np.set_printoptions(precision=2, suppress=True)
    print("attention weights (row t = how token t mixes tokens 0..t):\n", w)
    print("block output shape:", block(x, init_block(C, rng), H).shape)
    print("loss of uniform guessing over 65 tokens:", cross_entropy(np.zeros((4, 65)), np.array([1, 2, 3, 4])),
          "= ln(65) =", round(float(np.log(65)), 4))
