"""
ML coding interview prep: reference implementations + self-tests
================================================================
Run:  python ml_coding_prep.py      (needs numpy, torch; sklearn only for the metric tests)

Each section is one commonly asked question. Practice: delete a function body,
re-implement it in 20-30 minutes, then run this file to check it.

  A. Transformer core (PyTorch, plus one NumPy version)
     A1 scaled dot-product attention (+ causal / padding mask)
     A2 multi-head attention in NumPy
     A3 RMSNorm / LayerNorm (PyTorch + NumPy)
     A4 RoPE (PyTorch + NumPy)
     A5 attention with GQA/MQA + KV cache
     A6 SwiGLU FFN + pre-norm block + tiny decoder LM + generate()
  B. Decoding
     B1 temperature / top-k / top-p sampling (PyTorch + NumPy)
     B2 beam search
  C. Fundamentals (NumPy)
     C1 stable softmax + cross-entropy + gradient
     C2 2-layer MLP forward/backward + gradient check
     C3 logistic regression (NumPy GD + PyTorch training loop)
     C4 k-means (k-means++ init)
     C5 Adam / AdamW
  D. Post-training
     D1 LoRA linear
     D2 DPO loss (+ response log-prob with the shift)
     D3 GRPO loss
  E. RecSys / retrieval
     E1 in-batch softmax (two-tower) + logQ correction + duplicate masking
     E2 ROC-AUC (rank-based, ties), NDCG@k
     E3 factorization machine (NumPy + PyTorch)
  F. Debugging round: checklist of commonly planted bugs (bottom of file)
"""
import math

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


# =============================================================================
# A1. Scaled dot-product attention
# =============================================================================
# --8<-- [start:sdpa]
def sdpa(q, k, v, attn_mask=None, is_causal=False):
    """
    q: (B, H, Tq, D), k/v: (B, H, Tk, D)
    attn_mask: bool, True = attend, broadcastable to (B, H, Tq, Tk)
    is_causal: bottom-right aligned, so query i sits at absolute position Tk - Tq + i.
               The same code is then correct for prefill (Tq == Tk) and for
               KV-cache decoding (Tq = 1, Tk = cache length).
    """
    d = q.size(-1)
    scores = q @ k.transpose(-2, -1) / math.sqrt(d)  # (B, H, Tq, Tk)
    Tq, Tk = q.size(-2), k.size(-2)
    if is_causal:
        causal = torch.ones(Tq, Tk, dtype=torch.bool, device=q.device).tril(diagonal=Tk - Tq)
        scores = scores.masked_fill(~causal, float("-inf"))
    if attn_mask is not None:
        scores = scores.masked_fill(~attn_mask, float("-inf"))
    attn = scores.softmax(dim=-1)  # softmax over KEYS (last dim)
    return attn @ v  # (B, H, Tq, D)
# --8<-- [end:sdpa]


# =============================================================================
# A2. Multi-head self-attention in NumPy
# =============================================================================
# --8<-- [start:mha_numpy]
def mha_numpy(x, Wq, Wk, Wv, Wo, n_heads, causal=True):
    """x: (B, T, d_model); Wq/Wk/Wv/Wo: (d_model, d_model). Returns (B, T, d_model)."""
    B, T, d = x.shape
    hd = d // n_heads

    def split_heads(t):  # (B, T, d) -> (B, T, H, hd) -> (B, H, T, hd)
        return t.reshape(B, T, n_heads, hd).transpose(0, 2, 1, 3)

    q, k, v = split_heads(x @ Wq), split_heads(x @ Wk), split_heads(x @ Wv)
    scores = q @ k.transpose(0, 1, 3, 2) / np.sqrt(hd)  # (B, H, T, T)
    if causal:
        scores = np.where(np.tril(np.ones((T, T), dtype=bool)), scores, -np.inf)
    attn = softmax(scores, axis=-1)  # stable softmax from C1
    out = (attn @ v).transpose(0, 2, 1, 3).reshape(B, T, d)  # merge heads back
    return out @ Wo
# --8<-- [end:mha_numpy]


# =============================================================================
# A3. Norms
# =============================================================================
# --8<-- [start:norms]
class RMSNorm(nn.Module):
    """y = x / sqrt(mean(x^2) + eps) * g.  No mean subtraction, no bias (Llama-style)."""

    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))

    def forward(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight


class LayerNorm(nn.Module):
    """Normalizes over the LAST dim (features), not over the batch (that is BatchNorm)."""

    def __init__(self, d, eps=1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))
        self.bias = nn.Parameter(torch.zeros(d))

    def forward(self, x):
        mu = x.mean(-1, keepdim=True)
        var = x.var(-1, keepdim=True, unbiased=False)  # biased variance, same as PyTorch
        return (x - mu) / torch.sqrt(var + self.eps) * self.weight + self.bias
# --8<-- [end:norms]


# --8<-- [start:norms_np]
def rms_norm_np(x, g, eps=1e-6):
    return x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps) * g


def layer_norm_np(x, g, b, eps=1e-5):
    mu = x.mean(-1, keepdims=True)
    var = x.var(-1, keepdims=True)  # NumPy's var is the biased (population) variance by default
    return (x - mu) / np.sqrt(var + eps) * g + b
# --8<-- [end:norms_np]


# =============================================================================
# A4. RoPE (rotate-half convention, as in HF Llama)
# =============================================================================
# --8<-- [start:rope]
def rope_cache(max_len, head_dim, base=10000.0):
    inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))  # (D/2,)
    t = torch.arange(max_len).float()
    freqs = torch.outer(t, inv_freq)  # (T, D/2)
    emb = torch.cat([freqs, freqs], dim=-1)  # (T, D)
    return emb.cos(), emb.sin()


def rotate_half(x):
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([-x2, x1], dim=-1)


def apply_rope(x, cos, sin):
    """x: (B, H, T, D); cos/sin: (T, D), ALREADY sliced to the absolute positions of x."""
    return x * cos + rotate_half(x) * sin
# --8<-- [end:rope]


# --8<-- [start:rope_np]
def apply_rope_np(x, positions, base=10000.0):
    """x: (..., T, D) with D even; positions: (T,) absolute positions. Rotate-half convention."""
    D = x.shape[-1]
    inv_freq = 1.0 / base ** (np.arange(0, D, 2) / D)  # (D/2,)
    ang = np.outer(positions, inv_freq)  # (T, D/2)
    cos = np.concatenate([np.cos(ang)] * 2, axis=-1)  # (T, D)
    sin = np.concatenate([np.sin(ang)] * 2, axis=-1)
    x1, x2 = x[..., : D // 2], x[..., D // 2:]
    return x * cos + np.concatenate([-x2, x1], axis=-1) * sin
# --8<-- [end:rope_np]


# =============================================================================
# A5. Attention with GQA / MQA + KV cache
# =============================================================================
# --8<-- [start:attention]
class Attention(nn.Module):
    """
    n_kv_heads == n_heads -> MHA; 1 -> MQA; in between -> GQA.
    The KV cache stores the UN-repeated k/v (n_kv_heads), which is exactly GQA's memory saving.
    """

    def __init__(self, d_model, n_heads, n_kv_heads=None):
        super().__init__()
        self.n_heads = n_heads
        self.n_kv = n_kv_heads or n_heads
        assert d_model % n_heads == 0 and n_heads % self.n_kv == 0
        self.hd = d_model // n_heads
        self.wq = nn.Linear(d_model, n_heads * self.hd, bias=False)
        self.wk = nn.Linear(d_model, self.n_kv * self.hd, bias=False)
        self.wv = nn.Linear(d_model, self.n_kv * self.hd, bias=False)
        self.wo = nn.Linear(n_heads * self.hd, d_model, bias=False)

    def forward(self, x, cos, sin, cache=None):
        B, T, _ = x.shape
        # view as (B, T, H, D) THEN transpose; a direct .view(B, H, T, D) scrambles tokens
        q = self.wq(x).view(B, T, self.n_heads, self.hd).transpose(1, 2)
        k = self.wk(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        v = self.wv(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)  # rotate BEFORE caching
        if cache is not None:
            if "k" in cache:
                k = torch.cat([cache["k"], k], dim=2)
                v = torch.cat([cache["v"], v], dim=2)
            cache["k"], cache["v"] = k, v
        rep = self.n_heads // self.n_kv
        if rep > 1:
            k = k.repeat_interleave(rep, dim=1)
            v = v.repeat_interleave(rep, dim=1)
        out = sdpa(q, k, v, is_causal=True)  # (B, H, T, D)
        out = out.transpose(1, 2).contiguous().view(B, T, -1)  # .contiguous() needed before view
        return self.wo(out)
# --8<-- [end:attention]


# =============================================================================
# A6. SwiGLU FFN, pre-norm block, tiny decoder-only LM
# =============================================================================
# --8<-- [start:block]
class SwiGLU(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.w1 = nn.Linear(d, hidden, bias=False)  # gate
        self.w3 = nn.Linear(d, hidden, bias=False)  # up
        self.w2 = nn.Linear(hidden, d, bias=False)  # down

    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))


class Block(nn.Module):
    """Pre-norm: x + f(norm(x)). The residual adds to the UN-normalized x."""

    def __init__(self, d, n_heads, n_kv_heads, ffn_mult=4):
        super().__init__()
        self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
        self.attn = Attention(d, n_heads, n_kv_heads)
        self.ffn = SwiGLU(d, ffn_mult * d)

    def forward(self, x, cos, sin, cache=None):
        x = x + self.attn(self.norm1(x), cos, sin, cache)
        x = x + self.ffn(self.norm2(x))
        return x
# --8<-- [end:block]


# --8<-- [start:tinylm]
class TinyLM(nn.Module):
    def __init__(self, vocab, d=64, n_layers=2, n_heads=4, n_kv_heads=2, max_len=256):
        super().__init__()
        self.emb = nn.Embedding(vocab, d)
        self.blocks = nn.ModuleList([Block(d, n_heads, n_kv_heads) for _ in range(n_layers)])
        self.norm = RMSNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.head.weight = self.emb.weight  # weight tying
        # nn.Embedding defaults to N(0, 1); tied to the head, that makes the initial logits'
        # std ~ sqrt(d) and the initial loss far above ln(V). GPT-2 style std=0.02 fixes it.
        nn.init.normal_(self.emb.weight, std=0.02)
        cos, sin = rope_cache(max_len, d // n_heads)
        self.register_buffer("cos", cos, persistent=False)
        self.register_buffer("sin", sin, persistent=False)

    def forward(self, idx, caches=None, start_pos=0):
        T = idx.size(1)
        x = self.emb(idx)
        cos = self.cos[start_pos:start_pos + T]  # the position offset matters with a cache
        sin = self.sin[start_pos:start_pos + T]
        for i, blk in enumerate(self.blocks):
            x = blk(x, cos, sin, None if caches is None else caches[i])
        return self.head(self.norm(x))  # (B, T, V)

    def lm_loss(self, idx, pad_id=None):
        """Next-token loss: the logits at position t predict token t+1."""
        logits = self(idx)[:, :-1]
        targets = idx[:, 1:]
        return F.cross_entropy(
            logits.reshape(-1, logits.size(-1)),
            targets.reshape(-1),
            ignore_index=-100 if pad_id is None else pad_id,
        )

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, use_cache=True, **sample_kw):
        if not use_cache:  # O(T^2) per step: recompute the whole prefix every time
            for _ in range(max_new_tokens):
                nxt = sample(self(idx)[:, -1], **sample_kw)
                idx = torch.cat([idx, nxt], dim=1)
            return idx
        caches = [dict() for _ in self.blocks]
        logits = self(idx, caches, start_pos=0)[:, -1]  # prefill
        pos = idx.size(1)
        for step in range(max_new_tokens):
            nxt = sample(logits, **sample_kw)  # (B, 1)
            idx = torch.cat([idx, nxt], dim=1)
            if step == max_new_tokens - 1:
                break
            logits = self(nxt, caches, start_pos=pos)[:, -1]  # decode: feed ONE token
            pos += 1
        return idx
# --8<-- [end:tinylm]


# =============================================================================
# B1. Sampling
# =============================================================================
# --8<-- [start:sample]
def sample(logits, temperature=1.0, top_k=0, top_p=1.0, generator=None):
    """
    logits: (B, V) -> token ids (B, 1)
    Order: temperature -> top-k -> top-p -> renormalize -> sample.
    top-p keeps the smallest prefix whose mass reaches p, INCLUDING the boundary token
    (a token is removed only if the mass strictly before it already >= p). Top-1 is never removed.
    """
    if temperature == 0:
        return logits.argmax(dim=-1, keepdim=True)
    logits = logits / temperature
    if top_k > 0:
        kth = torch.topk(logits, min(top_k, logits.size(-1)), dim=-1).values[..., -1:]
        logits = logits.masked_fill(logits < kth, float("-inf"))
    if top_p < 1.0:
        sorted_logits, sorted_idx = logits.sort(dim=-1, descending=True)
        probs = sorted_logits.softmax(dim=-1)
        mass_before = probs.cumsum(dim=-1) - probs
        sorted_logits = sorted_logits.masked_fill(mass_before >= top_p, float("-inf"))
        logits = torch.full_like(logits, float("-inf")).scatter(-1, sorted_idx, sorted_logits)
    return torch.multinomial(logits.softmax(dim=-1), 1, generator=generator)
# --8<-- [end:sample]


# --8<-- [start:sample_np]
def sample_np(logits, temperature=1.0, top_k=0, top_p=1.0, rng=None):
    """logits: (V,) for one position -> one token id. Same order and boundary rule as sample()."""
    rng = rng or np.random.default_rng()
    if temperature == 0:
        return int(np.argmax(logits))
    z = logits / temperature
    if top_k > 0:
        kth = np.sort(z)[-min(top_k, len(z))]
        z = np.where(z < kth, -np.inf, z)
    if top_p < 1.0:
        order = np.argsort(-z)  # descending
        p_sorted = softmax(z[order])
        mass_before = np.cumsum(p_sorted) - p_sorted
        z[order[mass_before >= top_p]] = -np.inf  # keeps the boundary token
    return int(rng.choice(len(z), p=softmax(z)))
# --8<-- [end:sample_np]


# =============================================================================
# B2. Beam search
# =============================================================================
# --8<-- [start:beam_search]
@torch.no_grad()
def beam_search(model, prompt, beam_width, max_new_tokens):
    """
    prompt: (1, T). Keeps the beam_width partial sequences with the highest cumulative
    log-prob. All beams go through the model as one batch.
    Returns (best sequence (1, T + max_new_tokens), its total log-prob).
    """
    seqs = prompt  # (K, T), K = 1 at the start
    scores = torch.zeros(1)  # cumulative log-prob of each beam
    for _ in range(max_new_tokens):
        logp = model(seqs)[:, -1].log_softmax(dim=-1)  # (K, V)
        V = logp.size(-1)
        total = (scores[:, None] + logp).view(-1)  # (K * V,) every beam x every next token
        top = torch.topk(total, min(beam_width, total.numel()))
        beam_idx, token = top.indices // V, top.indices % V
        seqs = torch.cat([seqs[beam_idx], token[:, None]], dim=1)
        scores = top.values
    return seqs[:1], scores[0].item()  # topk sorts, so beam 0 is the best
# --8<-- [end:beam_search]


# =============================================================================
# C1. Stable softmax / cross-entropy (NumPy)
# =============================================================================
# --8<-- [start:softmax_ce]
def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)  # shift for stability
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)


def log_softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)
    return z - np.log(np.exp(z).sum(axis=axis, keepdims=True))  # log-sum-exp trick


def cross_entropy(logits, y):
    """logits (N, C), y (N,) int. Returns the mean loss and dL/dlogits = (softmax - onehot) / N."""
    N = logits.shape[0]
    loss = -log_softmax(logits)[np.arange(N), y].mean()
    grad = softmax(logits)
    grad[np.arange(N), y] -= 1.0
    return loss, grad / N
# --8<-- [end:softmax_ce]


# =============================================================================
# C2. 2-layer MLP with manual backprop (NumPy)
# =============================================================================
# --8<-- [start:mlp]
class MLP:
    def __init__(self, d_in, d_h, d_out, seed=0):
        rng = np.random.default_rng(seed)
        self.params = {
            "W1": rng.standard_normal((d_in, d_h)) * np.sqrt(2.0 / d_in),  # He init for ReLU
            "b1": np.zeros(d_h),
            "W2": rng.standard_normal((d_h, d_out)) * np.sqrt(2.0 / d_h),
            "b2": np.zeros(d_out),
        }

    def forward(self, X):
        p = self.params
        self.X = X
        self.h_pre = X @ p["W1"] + p["b1"]
        self.h = np.maximum(0.0, self.h_pre)
        return self.h @ p["W2"] + p["b2"]

    def backward(self, dout):
        p = self.params
        dW2 = self.h.T @ dout
        db2 = dout.sum(0)
        dh = dout @ p["W2"].T
        dh_pre = dh * (self.h_pre > 0)
        dW1 = self.X.T @ dh_pre
        db1 = dh_pre.sum(0)
        return {"W1": dW1, "b1": db1, "W2": dW2, "b2": db2}
# --8<-- [end:mlp]


# --8<-- [start:grad_check]
def grad_check(model, X, y, eps=1e-5):
    """Central differences in float64; the relative error should be ~1e-7 or smaller."""
    _, dlogits = cross_entropy(model.forward(X), y)
    grads = model.backward(dlogits)
    worst = 0.0
    for name, P in model.params.items():
        num = np.zeros_like(P)
        it = np.nditer(P, flags=["multi_index"])
        for _ in it:
            i = it.multi_index
            old = P[i]
            P[i] = old + eps
            lp, _ = cross_entropy(model.forward(X), y)
            P[i] = old - eps
            lm, _ = cross_entropy(model.forward(X), y)
            P[i] = old
            num[i] = (lp - lm) / (2 * eps)
        rel = np.abs(num - grads[name]).max() / max(1e-12, np.abs(num).max() + np.abs(grads[name]).max())
        worst = max(worst, rel)
    return worst
# --8<-- [end:grad_check]


# =============================================================================
# C3. Logistic regression (NumPy, batch GD)
# =============================================================================
# --8<-- [start:logreg]
def sigmoid(z):
    out = np.empty_like(z, dtype=float)
    pos = z >= 0
    out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
    ez = np.exp(z[~pos])  # avoids overflow for large negative z
    out[~pos] = ez / (1.0 + ez)
    return out


def logistic_regression(X, y, lr=0.5, epochs=500, l2=0.0):
    """Loss = mean BCE + l2/2 ||w||^2. Gradient = X^T (p - y) / N + l2 w."""
    N, d = X.shape
    w, b = np.zeros(d), 0.0
    for _ in range(epochs):
        p = sigmoid(X @ w + b)
        w -= lr * (X.T @ (p - y) / N + l2 * w)
        b -= lr * (p - y).mean()
    return w, b
# --8<-- [end:logreg]


# --8<-- [start:logreg_torch]
def logistic_regression_torch(X, y, lr=0.5, epochs=500, l2=0.0):
    """The same model trained with autograd: the standard PyTorch training loop."""
    X = torch.as_tensor(X, dtype=torch.float32)
    y = torch.as_tensor(y, dtype=torch.float32)
    model = nn.Linear(X.shape[1], 1)
    opt = torch.optim.SGD(model.parameters(), lr=lr, weight_decay=l2)
    for _ in range(epochs):
        opt.zero_grad()  # gradients accumulate by default
        logits = model(X).squeeze(-1)
        loss = F.binary_cross_entropy_with_logits(logits, y)  # stable: works on logits, not sigmoid
        loss.backward()
        opt.step()
    return model
# --8<-- [end:logreg_torch]


# =============================================================================
# C4. k-means with k-means++ init (NumPy)
# =============================================================================
# --8<-- [start:kmeans]
def kmeans(X, k, n_iter=100, seed=0):
    rng = np.random.default_rng(seed)
    N = len(X)
    C = [X[rng.integers(N)]]
    for _ in range(1, k):  # k-means++: sample proportional to the squared distance
        d2 = ((X[:, None, :] - np.array(C)[None]) ** 2).sum(-1).min(1)
        C.append(X[rng.choice(N, p=d2 / d2.sum())])
    C = np.array(C)

    def assign(C):
        # ||x||^2 - 2 x.c + ||c||^2 avoids building an (N, k, d) tensor
        d2 = (X ** 2).sum(1, keepdims=True) - 2 * X @ C.T + (C ** 2).sum(1)
        return d2.argmin(1)

    for _ in range(n_iter):
        labels = assign(C)
        # an empty cluster keeps its old center
        newC = np.array([X[labels == j].mean(0) if np.any(labels == j) else C[j] for j in range(k)])
        if np.allclose(newC, C):
            break
        C = newC
    return C, assign(C)
# --8<-- [end:kmeans]


# =============================================================================
# C5. Adam / AdamW (NumPy)
# =============================================================================
# --8<-- [start:adamw]
class AdamW:
    """weight_decay=0 -> Adam. AdamW decouples the decay from the adaptive update
    (Adam + L2 in the loss would get rescaled by 1/sqrt(v))."""

    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
        self.params = params  # dict name -> np.ndarray, updated in place
        self.lr, self.b1, self.b2, self.eps, self.wd = lr, betas[0], betas[1], eps, weight_decay
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads):
        self.t += 1
        for k, p in self.params.items():
            g = grads[k]
            self.m[k] = self.b1 * self.m[k] + (1 - self.b1) * g
            self.v[k] = self.b2 * self.v[k] + (1 - self.b2) * g * g
            m_hat = self.m[k] / (1 - self.b1 ** self.t)  # bias correction
            v_hat = self.v[k] / (1 - self.b2 ** self.t)
            p -= self.lr * (m_hat / (np.sqrt(v_hat) + self.eps) + self.wd * p)
# --8<-- [end:adamw]


# =============================================================================
# D1. LoRA
# =============================================================================
# --8<-- [start:lora]
class LoRALinear(nn.Module):
    """W x + (alpha / r) * B A x, with A random and B = 0, so training starts exactly at the base model."""

    def __init__(self, base: nn.Linear, r=8, alpha=16, dropout=0.0):
        super().__init__()
        self.base = base
        for p in self.base.parameters():
            p.requires_grad_(False)
        self.A = nn.Parameter(torch.randn(r, base.in_features) / math.sqrt(base.in_features))
        self.B = nn.Parameter(torch.zeros(base.out_features, r))
        self.scale = alpha / r
        self.drop = nn.Dropout(dropout)
        self.merged = False

    def forward(self, x):
        out = self.base(x)
        if not self.merged:
            out = out + (self.drop(x) @ self.A.T @ self.B.T) * self.scale
        return out

    @torch.no_grad()
    def merge(self):  # zero inference overhead after merging
        self.base.weight += self.scale * (self.B @ self.A)
        self.merged = True
# --8<-- [end:lora]


# =============================================================================
# D2. DPO
# =============================================================================
# --8<-- [start:dpo]
def response_logprob(logits, input_ids, response_mask):
    """
    Sum of log p(token) over RESPONSE tokens only.
    logits (B, T, V), input_ids (B, T), response_mask (B, T) with 1 on response tokens.
    The shift is the classic bug: logits[:, t] predicts input_ids[:, t+1].
    """
    logits = logits[:, :-1]
    targets = input_ids[:, 1:]
    mask = response_mask[:, 1:].float()
    logp = logits.log_softmax(-1).gather(-1, targets.unsqueeze(-1)).squeeze(-1)
    return (logp * mask).sum(-1)


def dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta=0.1):
    """
    Inputs are sequence log-probs (B,). Reference log-probs come from a frozen model
    (computed under torch.no_grad). Loss = -log sigmoid(beta * (Δ_chosen - Δ_rejected)).
    """
    chosen_reward = beta * (pi_chosen - ref_chosen)
    rejected_reward = beta * (pi_rejected - ref_rejected)
    loss = -F.logsigmoid(chosen_reward - rejected_reward).mean()
    return loss, chosen_reward.detach(), rejected_reward.detach()
# --8<-- [end:dpo]


# =============================================================================
# D3. GRPO
# =============================================================================
# --8<-- [start:grpo]
def grpo_loss(logp_new, logp_old, logp_ref, rewards, mask, group_size, clip_eps=0.2, beta=0.04):
    """
    logp_*: (B*G, T) per-token log-probs of the SAMPLED tokens; rewards: (B*G,); mask: (B*G, T).
    Advantage = group-normalized reward (no value network), shared by all tokens of a response.
    The KL uses the k3 estimator exp(ref - new) - (ref - new) - 1 (unbiased, always >= 0).
    Aggregation = original GRPO (mean over tokens per sequence, then over sequences).
    """
    r = rewards.view(-1, group_size)
    adv = (r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + 1e-6)
    adv = adv.view(-1, 1)  # broadcast over tokens
    ratio = torch.exp(logp_new - logp_old)
    pg = -torch.min(ratio * adv, ratio.clamp(1 - clip_eps, 1 + clip_eps) * adv)
    log_ratio_ref = logp_ref - logp_new
    kl = torch.exp(log_ratio_ref) - log_ratio_ref - 1
    per_tok = (pg + beta * kl) * mask
    return (per_tok.sum(1) / mask.sum(1).clamp(min=1)).mean()
# --8<-- [end:grpo]


# =============================================================================
# E1. In-batch softmax for two-tower retrieval
# =============================================================================
# --8<-- [start:in_batch]
def in_batch_softmax_loss(q, d, temperature=0.05, log_q=None, item_ids=None):
    """
    q, d: (B, dim) query / positive-item embeddings; row i of d is the positive for q[i],
    all other rows are negatives.
    log_q: (B,) log sampling probability of each in-batch item. Popular items show up as
           negatives more often, so subtract log_q (sampling-bias correction, Yi et al. 2019).
    item_ids: (B,) masks duplicates of the same item, so a positive is not used as its own negative.
    """
    q, d = F.normalize(q, dim=-1), F.normalize(d, dim=-1)
    logits = q @ d.T / temperature  # (B, B)
    if log_q is not None:
        logits = logits - log_q[None, :]
    if item_ids is not None:
        dup = (item_ids[None, :] == item_ids[:, None]) & ~torch.eye(len(q), dtype=torch.bool)
        logits = logits.masked_fill(dup, float("-inf"))
    labels = torch.arange(len(q))
    return F.cross_entropy(logits, labels)
# --8<-- [end:in_batch]


# =============================================================================
# E2. Ranking metrics
# =============================================================================
# --8<-- [start:auc]
def roc_auc(y_true, scores):
    """AUC = P(score_pos > score_neg) via Mann-Whitney U; ties get the average rank. O(N log N)."""
    y_true, scores = np.asarray(y_true), np.asarray(scores, dtype=float)
    _, inv, counts = np.unique(scores, return_inverse=True, return_counts=True)
    avg_rank = np.cumsum(counts) - (counts - 1) / 2.0  # 1-based average rank of each unique score
    ranks = avg_rank[inv]
    n_pos = y_true.sum()
    n_neg = len(y_true) - n_pos
    return (ranks[y_true == 1].sum() - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)
# --8<-- [end:auc]


# --8<-- [start:ndcg]
def ndcg_at_k(rel_in_ranked_order, k, gain="exp"):
    """
    rel_in_ranked_order: graded relevance of ALL candidates, in the order the model ranked them.
    The ideal ranking is computed over all candidates, not just the top-k retrieved.
    gain='exp' -> 2^rel - 1 (common in papers); 'linear' -> rel (sklearn's ndcg_score).
    """
    rel = np.asarray(rel_in_ranked_order, dtype=float)
    g = (2 ** rel - 1) if gain == "exp" else rel
    disc = 1.0 / np.log2(np.arange(2, len(rel) + 2))
    dcg = (g[:k] * disc[:k]).sum()
    ideal = np.sort(g)[::-1]
    idcg = (ideal[:k] * disc[:k]).sum()
    return dcg / idcg if idcg > 0 else 0.0
# --8<-- [end:ndcg]


# =============================================================================
# E3. Factorization machine
# =============================================================================
# --8<-- [start:fm]
def fm_forward(x, w0, w, V):
    """
    y = w0 + sum_i w_i x_i + sum_{i<j} <v_i, v_j> x_i x_j
    x: (B, n) features, w: (n,), V: (n, k) latent vectors.
    The pairwise term costs O(n k) instead of O(n^2 k):
        sum_{i<j} <v_i, v_j> x_i x_j = 0.5 * sum_f [ (sum_i v_if x_i)^2 - sum_i v_if^2 x_i^2 ]
    """
    linear = w0 + x @ w
    s = x @ V  # (B, k)
    s2 = (x ** 2) @ (V ** 2)  # (B, k)
    return linear + 0.5 * (s ** 2 - s2).sum(axis=1)
# --8<-- [end:fm]


# --8<-- [start:fm_torch]
class FM(nn.Module):
    """Trainable factorization machine over dense features x: (B, n) -> logits (B,)."""

    def __init__(self, n, k):
        super().__init__()
        self.w0 = nn.Parameter(torch.zeros(1))
        self.w = nn.Parameter(torch.zeros(n))
        self.V = nn.Parameter(torch.randn(n, k) * 0.01)

    def forward(self, x):
        s = x @ self.V  # (B, k)
        s2 = (x * x) @ (self.V * self.V)  # (B, k)
        return self.w0 + x @ self.w + 0.5 * (s * s - s2).sum(-1)
# --8<-- [end:fm_torch]


# =============================================================================
# F. Debugging round checklist (planted bugs that show up again and again)
# =============================================================================
DEBUG_CHECKLIST = """
Crash bugs
  - .view() after .transpose() without .contiguous()
  - head reshape: .view(B, H, T, D) directly instead of .view(B, T, H, D).transpose(1, 2)
  - mask dtype/shape mismatch, mask on the wrong device
Silent bugs (training runs but is wrong)
  - softmax over the wrong dim (dim=-2 instead of -1)
  - missing / sqrt(head_dim), or dividing by sqrt(d_model)
  - causal mask inverted (triu vs tril), or masked_fill with 0 instead of -inf
  - mask applied AFTER the softmax
  - LM loss not shifted (logits[:, t] must predict token t+1); padding not ignored
  - F.cross_entropy fed probabilities instead of logits (double softmax)
  - residual added to norm(x) instead of x; norm over the wrong dim
  - KV cache / RoPE / learned position embedding with the position offset reset to 0 at each decode step
  - optimizer.zero_grad() missing or misplaced; optimizer.step() before backward()
  - gradient accumulation without dividing the loss by accum_steps
  - model.eval() / model.train() not toggled (dropout on during eval)
  - reference model not frozen / ref log-probs computed with grad (DPO, GRPO)
  - weight tying broken by re-initializing one side
How to find them fast
  - overfit one tiny batch: the loss should go to ~0
  - the initial loss should be ~ln(vocab) for an LM
  - assert shapes after every reshape; compare against F.scaled_dot_product_attention
  - check that KV-cache logits == full-recompute logits
"""


# =============================================================================
# Tests
# =============================================================================
def _ok(name):
    print(f"[PASS] {name}")


def test_sdpa():
    torch.manual_seed(0)
    q, k, v = (torch.randn(2, 4, 7, 16) for _ in range(3))
    ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    assert torch.allclose(sdpa(q, k, v, is_causal=True), ref, atol=1e-5)
    pad = torch.ones(2, 1, 1, 7, dtype=torch.bool)
    pad[1, ..., 5:] = False  # sequence 1 has 2 padding keys
    ref = F.scaled_dot_product_attention(q, k, v, attn_mask=pad)
    assert torch.allclose(sdpa(q, k, v, attn_mask=pad), ref, atol=1e-5)
    _ok("A1 sdpa matches F.scaled_dot_product_attention (causal + padding mask)")


def test_mha_numpy():
    rng = np.random.default_rng(0)
    B, T, d, H = 2, 6, 16, 4
    x = rng.standard_normal((B, T, d))
    Wq, Wk, Wv, Wo = (rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(4))
    ours = mha_numpy(x, Wq, Wk, Wv, Wo, H, causal=True)
    xt = torch.tensor(x)
    split = lambda t: t.view(B, T, H, d // H).transpose(1, 2)
    q, k, v = (split(xt @ torch.tensor(W)) for W in (Wq, Wk, Wv))
    ref = sdpa(q, k, v, is_causal=True).transpose(1, 2).reshape(B, T, d) @ torch.tensor(Wo)
    assert np.allclose(ours, ref.numpy(), atol=1e-10)
    _ok("A2 NumPy multi-head attention matches the PyTorch version")


def test_norms():
    torch.manual_seed(0)
    x = torch.randn(3, 5, 32)
    assert torch.allclose(RMSNorm(32)(x), nn.RMSNorm(32, eps=1e-6)(x), atol=1e-6)
    assert torch.allclose(LayerNorm(32)(x), F.layer_norm(x, (32,)), atol=1e-5)
    g, b = torch.randn(32), torch.randn(32)
    ln = nn.LayerNorm(32)
    with torch.no_grad():
        ln.weight.copy_(g); ln.bias.copy_(b)
    assert np.allclose(layer_norm_np(x.numpy(), g.numpy(), b.numpy()), ln(x).detach().numpy(), atol=1e-5)
    assert np.allclose(rms_norm_np(x.numpy(), g.numpy()), (RMSNorm(32)(x) * g).detach().numpy(), atol=1e-5)
    _ok("A3 RMSNorm / LayerNorm (PyTorch and NumPy) match PyTorch")


def test_rope_relative():
    torch.manual_seed(0)
    cos, sin = rope_cache(64, 16)
    q, k = torch.randn(1, 1, 1, 16), torch.randn(1, 1, 1, 16)

    def score(m, n):
        qm = apply_rope(q, cos[m:m + 1], sin[m:m + 1])
        kn = apply_rope(k, cos[n:n + 1], sin[n:n + 1])
        return (qm * kn).sum()

    assert torch.allclose(score(5, 2), score(40, 37), atol=1e-4)
    x = torch.randn(2, 3, 10, 16)
    ours = apply_rope_np(x.numpy().astype(np.float64), np.arange(10))
    assert np.allclose(ours, apply_rope(x, cos[:10], sin[:10]).numpy(), atol=1e-5)
    _ok("A4 RoPE depends only on the relative position; NumPy version matches")


def test_kv_cache():
    torch.manual_seed(0)
    model = TinyLM(vocab=50).eval()
    prompt = torch.randint(0, 50, (2, 5))
    # 1) cached step logits == full-recompute logits at every position
    seq = torch.randint(0, 50, (2, 12))
    full = model(seq)
    caches = [dict() for _ in model.blocks]
    step_logits = [model(seq[:, :5], caches, start_pos=0)]
    for t in range(5, 12):
        step_logits.append(model(seq[:, t:t + 1], caches, start_pos=t))
    assert torch.allclose(torch.cat(step_logits, dim=1), full, atol=1e-5)
    # 2) greedy generation identical with / without the cache
    a = model.generate(prompt, 10, use_cache=True, temperature=0)
    b = model.generate(prompt, 10, use_cache=False, temperature=0)
    assert torch.equal(a, b)
    # 3) the cache holds n_kv_heads (GQA), not n_heads
    assert caches[0]["k"].shape == (2, 2, 12, 16)
    _ok("A5/A6 KV cache == full recompute; the GQA cache stores n_kv_heads")


def test_lm_trains():
    torch.manual_seed(0)
    model = TinyLM(vocab=20, d=32, n_layers=1, n_heads=4, n_kv_heads=4)
    data = torch.arange(20).repeat(4, 2)[:, :24]  # deterministic pattern 0,1,2,...
    init = model.lm_loss(data).item()
    assert abs(init - math.log(20)) < 1.5  # initial loss ~ ln(V)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    for _ in range(200):
        opt.zero_grad()
        loss = model.lm_loss(data)
        loss.backward()
        opt.step()
    assert loss.item() < 0.1
    _ok(f"A6 tiny LM overfits a pattern (loss {init:.2f} -> {loss.item():.3f})")


def test_sampling():
    torch.manual_seed(0)
    logits = torch.tensor([[2.0, 1.0, 0.5, -1.0, -3.0]]).repeat(4000, 1)
    assert (sample(logits, top_k=1) == 0).all()
    assert (sample(logits, top_p=1e-3) == 0).all()  # top-1 is never removed
    s = sample(logits, top_k=2)
    assert set(s.unique().tolist()) == {0, 1}
    # p(0)=0.61, p(1)=0.22 -> top_p=0.7 keeps {0, 1} (boundary token included)
    s = sample(logits, top_p=0.7)
    assert set(s.unique().tolist()) == {0, 1}
    rng = np.random.default_rng(0)
    z = logits[0].numpy().astype(np.float64)
    assert sample_np(z, top_k=1, rng=rng) == 0 and sample_np(z, top_p=1e-3, rng=rng) == 0
    assert {sample_np(z, top_p=0.7, rng=rng) for _ in range(2000)} == {0, 1}
    assert {sample_np(z, top_k=2, rng=rng) for _ in range(2000)} == {0, 1}
    _ok("B1 temperature / top-k / top-p sampling (PyTorch and NumPy)")


def test_beam_search():
    torch.manual_seed(0)
    model = TinyLM(vocab=5, d=16, n_layers=1, n_heads=2, n_kv_heads=2).eval()
    with torch.no_grad():  # sharpen the random model so sequences differ clearly
        model.emb.weight.mul_(30)
    prompt = torch.tensor([[1, 2]])
    # width 1 == greedy decoding
    seq, _ = beam_search(model, prompt, beam_width=1, max_new_tokens=4)
    assert torch.equal(seq, model.generate(prompt, 4, use_cache=False, temperature=0))
    # a beam wide enough to keep every prefix finds the exact best sequence (brute force)
    import itertools

    def total_logp(cont):
        s = torch.cat([prompt, torch.tensor([cont])], dim=1)
        lp = model(s)[0, :-1].log_softmax(-1)
        return sum(lp[prompt.size(1) - 1 + i, t].item() for i, t in enumerate(cont))

    best = max(itertools.product(range(5), repeat=3), key=total_logp)
    seq, score = beam_search(model, prompt, beam_width=25, max_new_tokens=3)
    assert seq[0, 2:].tolist() == list(best) and math.isclose(score, total_logp(best), abs_tol=1e-4)
    _ok("B2 beam search: width 1 == greedy; a full-width beam finds the exact best sequence")


def test_cross_entropy():
    rng = np.random.default_rng(0)
    z = rng.standard_normal((6, 4)) * 50  # large logits: must not overflow
    y = rng.integers(0, 4, 6)
    loss, grad = cross_entropy(z, y)
    zt = torch.tensor(z, requires_grad=True)
    lt = F.cross_entropy(zt, torch.tensor(y))
    lt.backward()
    assert np.isclose(loss, lt.item()) and np.allclose(grad, zt.grad.numpy())
    _ok("C1 stable cross-entropy + gradient match PyTorch")


def test_mlp():
    rng = np.random.default_rng(0)
    X, y = rng.standard_normal((8, 5)), rng.integers(0, 3, 8)
    err = grad_check(MLP(5, 7, 3), X, y)
    assert err < 1e-6, err
    # train on a nonlinear problem with our AdamW
    X = rng.standard_normal((400, 2))
    y = (X[:, 0] * X[:, 1] > 0).astype(int)  # XOR-like
    model = MLP(2, 32, 2, seed=1)
    opt = AdamW(model.params, lr=1e-2)
    for _ in range(500):
        _, g = cross_entropy(model.forward(X), y)
        opt.step(model.backward(g))
    acc = (model.forward(X).argmax(1) == y).mean()
    assert acc > 0.95, acc
    _ok(f"C2 MLP grad check (rel err {err:.1e}); XOR-like acc {acc:.2f}")


def test_logreg():
    rng = np.random.default_rng(0)
    X = rng.standard_normal((500, 3))
    y = (X @ np.array([2.0, -1.0, 0.5]) + 0.3 > 0).astype(float)
    w, b = logistic_regression(X, y)
    acc = ((sigmoid(X @ w + b) > 0.5) == y).mean()
    assert acc > 0.97
    assert np.isfinite(sigmoid(np.array([-1000.0, 1000.0]))).all()
    torch.manual_seed(0)
    model = logistic_regression_torch(X, y)
    acc_t = ((model(torch.tensor(X, dtype=torch.float32)).squeeze(-1) > 0).numpy() == y).mean()
    assert acc_t > 0.97
    _ok(f"C3 logistic regression acc {acc:.3f} (NumPy GD), {acc_t:.3f} (PyTorch loop)")


def test_kmeans():
    rng = np.random.default_rng(0)
    centers = np.array([[0, 0], [8, 8], [-8, 8]])
    X = np.concatenate([c + rng.standard_normal((100, 2)) for c in centers])
    truth = np.repeat(np.arange(3), 100)
    _, labels = kmeans(X, 3)
    for j in range(3):  # each true blob maps to exactly one cluster
        assert len(np.unique(labels[truth == j])) == 1
    assert len(np.unique(labels)) == 3
    _ok("C4 k-means++ recovers 3 blobs")


def test_adamw():
    rng = np.random.default_rng(0)
    w0 = rng.standard_normal((3, 4))
    ours = {"w": w0.copy()}
    opt = AdamW(ours, lr=0.1, weight_decay=0.01)
    wt = torch.tensor(w0.copy(), requires_grad=True)
    topt = torch.optim.AdamW([wt], lr=0.1, weight_decay=0.01)
    for _ in range(5):
        g = rng.standard_normal((3, 4))
        opt.step({"w": g})
        wt.grad = torch.tensor(g)
        topt.step()
    assert np.allclose(ours["w"], wt.detach().numpy(), atol=1e-6)
    _ok("C5 AdamW matches torch.optim.AdamW")


def test_lora():
    torch.manual_seed(0)
    base = nn.Linear(16, 8)
    lora = LoRALinear(base, r=4, alpha=8)
    x = torch.randn(5, 16)
    assert torch.allclose(lora(x), base(x))  # B = 0 at init
    trainable = [n for n, p in lora.named_parameters() if p.requires_grad]
    assert trainable == ["A", "B"]
    with torch.no_grad():
        lora.B.normal_()
    before = lora(x)
    lora.merge()
    assert torch.allclose(lora(x), before, atol=1e-5)
    _ok("D1 LoRA: identity at init, only A/B trainable, merge is exact")


def test_dpo():
    torch.manual_seed(0)
    logits = torch.randn(2, 6, 10)
    ids = torch.randint(0, 10, (2, 6))
    mask = torch.tensor([[0, 0, 1, 1, 1, 1], [0, 0, 0, 1, 1, 0]])
    lp = response_logprob(logits, ids, mask)
    manual = sum(logits[0, t - 1].log_softmax(-1)[ids[0, t]] for t in range(2, 6))
    assert torch.allclose(lp[0], manual)
    c, r = torch.tensor([-5.0, -6.0], requires_grad=True), torch.tensor([-5.0, -6.0], requires_grad=True)
    loss, _, _ = dpo_loss(c, r, c.detach(), r.detach())
    assert torch.isclose(loss, torch.tensor(math.log(2)))  # policy == ref -> log 2
    loss.backward()
    assert (c.grad < 0).all() and (r.grad > 0).all()  # descent raises chosen, lowers rejected
    _ok("D2 response log-prob shift; DPO loss = log 2 at init, correct gradient sign")


def test_grpo():
    torch.manual_seed(0)
    G, T = 4, 5
    lp = torch.randn(G, T).log_softmax(-1).requires_grad_(True)
    mask = torch.ones(G, T)
    same = torch.ones(G)
    loss = grpo_loss(lp, lp.detach(), lp.detach(), same, mask, G)
    assert abs(loss.item()) < 1e-6  # equal rewards + on-policy + policy == ref -> 0
    rewards = torch.tensor([1.0, 0.0, 0.0, 0.0])
    loss = grpo_loss(lp, lp.detach(), lp.detach(), rewards, mask, G)
    loss.backward()
    assert (lp.grad[0] < 0).all() and (lp.grad[1:] > 0).all()
    _ok("D3 GRPO: zero loss when rewards tie; pushes up the high-reward sample")


def test_in_batch():
    torch.manual_seed(0)
    q = torch.randn(8, 16)
    good = in_batch_softmax_loss(q, q.clone(), temperature=0.05)
    bad = in_batch_softmax_loss(q, torch.randn(8, 16), temperature=0.05)
    assert good < 0.05 and bad > good
    ids = torch.tensor([0, 0, 1, 2, 3, 4, 5, 6])  # rows 0 and 1 are the same item
    d = q.clone()
    d[1] = d[0]
    assert in_batch_softmax_loss(q, d, item_ids=ids) < in_batch_softmax_loss(q, d)
    _ok("E1 in-batch softmax; duplicate masking lowers the false-negative loss")


def test_metrics():
    from sklearn.metrics import ndcg_score, roc_auc_score

    rng = np.random.default_rng(0)
    y = rng.integers(0, 2, 200)
    s = rng.integers(0, 10, 200).astype(float)  # many ties
    assert np.isclose(roc_auc(y, s), roc_auc_score(y, s))
    rel = np.array([3, 2, 3, 0, 1, 2])
    scores = np.arange(len(rel))[::-1].astype(float)  # the model ranks items in the given order
    for k in (3, 6):
        assert np.isclose(ndcg_at_k(rel, k, gain="linear"), ndcg_score([rel], [scores], k=k))
    assert np.isclose(ndcg_at_k([3, 2, 1], 3), 1.0)
    _ok("E2 AUC (with ties) and NDCG@k match sklearn")


def test_fm():
    rng = np.random.default_rng(0)
    B, n, k = 5, 7, 3
    x = rng.standard_normal((B, n))
    w0, w, V = 0.3, rng.standard_normal(n), rng.standard_normal((n, k))
    naive = w0 + x @ w + np.array([
        sum(V[i] @ V[j] * x[b, i] * x[b, j] for i in range(n) for j in range(i + 1, n)) for b in range(B)
    ])
    assert np.allclose(fm_forward(x, w0, w, V), naive)
    fm = FM(n, k).double()
    with torch.no_grad():
        fm.w0.fill_(w0); fm.w.copy_(torch.tensor(w)); fm.V.copy_(torch.tensor(V))
    assert np.allclose(fm(torch.tensor(x)).detach().numpy(), naive)
    _ok("E3 factorization machine: the O(nk) form (NumPy and PyTorch) equals the pairwise sum")


if __name__ == "__main__":
    for t in [test_sdpa, test_mha_numpy, test_norms, test_rope_relative, test_kv_cache, test_lm_trains,
              test_sampling, test_beam_search, test_cross_entropy, test_mlp, test_logreg, test_kmeans,
              test_adamw, test_lora, test_dpo, test_grpo, test_in_batch, test_metrics, test_fm]:
        t()
    print("\nAll tests passed.")
