Skip to content

3.3 Oracles, golden and differential tests, gradcheck as a test

Everything built in AI Engineering up to the modern transformer block got its gradients from the autograd of Tensor, broadcasting backward, and no_grad and The op library and gradcheck_all: each op’s vector-Jacobian product was written once and composed. The C kernels and the Rust engine later in that book have no autograd and no torch to lean on. FlashAttention’s backward, a fused RMSNorm, a SwiGLU kernel: each is a forward and a backward written by hand, and each is checked against the Python reference. That only works if a numerical kernel can be tested with nothing but an oracle, which is what this section shows, and what the oracle suites of the modern-block chapter, from Pre-LN and RMSNorm to Llama-family model, do.

Concepts from other sections (14)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Vector-Jacobian product (VJP): u⊤Ju^\top J, one step of reverse-mode differentiation. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange in Mathematics
  • RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm in AI Engineering
  • SwiGLU: a gated MLP, (Swish(xW)⊙xV)W2(\text{Swish}(xW) \odot xV)W_2, that replaced the ReLU feed-forward block. Read more: 5.3 Model landscape and lifecycle in AI Engineering
  • Upstream gradient: G=∂L/∂YG = \partial L / \partial Y, the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
  • causal mask: the rule j≤qoff+ij \le q_{\text{off}} + i; each position reads itself and the past. Read more: 11.2 Masks: causal, padding, sliding window, additive in AI Engineering
  • central difference: D0(h)=f(x+h)−f(x−h)2hD_0(h) = \frac{f(x+h) - f(x-h)}{2h}, a second-order approximation of f′(x)f'(x). Read more: 7.1 Derivatives and Finite Differences in Mathematics
  • central differences: the numerical derivative (f(x+ϵ)−f(x−ϵ))/2ϵ(f(x + \epsilon) - f(x - \epsilon))/2\epsilon, used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all in AI Engineering
  • softmax VJP: dS=P∘(dP−D)dS = P \circ (dP - D) with Di=∑jPij dPijD_i = \sum_j P_{ij}\,dP_{ij}, the backward of a row-wise softmax. Read more: 11.1 Scaled dot-product attention (forward and backward) in AI Engineering
  • sigmoid: σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}}, mapping the real line into (0,1)(0, 1), with σ′=σ(x)σ(−x)\sigma' = \sigma(x)\sigma(-x). Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
  • FlashAttention: attention computed tile by tile with an online softmax, so the score matrix is never stored. Read more: 22.5 FlashAttention forward in C in AI Engineering
  • Golden fixture: frozen JSON vectors of Hugging Face ids that both the Python and Rust implementations are checked against. Read more: 7.5 Fast BPE in Rust in AI Engineering
  • Product rule / quotient rule: (fg)′=f′g+fg′(fg)' = f'g + fg' and (f/g)′=(f′g−fg′)/g2(f/g)' = (f'g - fg')/g^2, the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1 in Mathematics
  • Mutation testing: judging a test suite by planting small faults (mutants) in the code and counting how many the suite catches; it measures whether tests check behavior, which line coverage cannot. Read more: Chapter 3: The Testing Mentality
  • logits: unnormalized log-scores that softmax turns into probabilities; here the table stores ln⁡P(j∣i)\ln P(j \mid i). Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering

This section builds on TDD, unit tests, and mutation testing for how a suite is judged and on Property-based tests for laws and models. It uses the central-difference idea from Partial derivatives, gradients, and gradcheck in Mathematics, and two of its ops come from Pre-LN and RMSNorm and Gated MLPs. The kata is kernels.py: four forward passes (linear, rmsnorm, swiglu, attention) and their hand-written backward passes, in numpy. Its oracle suite is test_oracles.py, which catches all ten planted faults. The suite runs with pytest and numpy; TINYLLM_FIXTURES names the directory that holds the torch-recorded golden values:

Terminal window
TINYLLM_FIXTURES=/path/to/fixtures uv run --no-project --with pytest --with numpy \
python -m pytest -q primers/craft.05

Try to derive each backward yourself before reading it.

Learning objectives

  • Name the three oracles (golden values, gradcheck, differential tests) and what each can and cannot catch.
  • Derive the backward of a linear layer, RMSNorm, SwiGLU, and attention from L=∑f(x)⊙gL = \sum f(x) \odot g.
  • Write a float64 gradcheck with a random upstream gradient and justify its tolerance.
  • Explain why a shape check is not an oracle, using the transposed weight gradient.

A test needs an oracle: something other than the code under test that knows the right answer. This section uses three, and every kernel from here on is tested with them. The notation is small:

SymbolMeaningType / shape
ffthe op under test, x↦yx \mapsto yfunction
ggan upstream gradient, the shape of yyarray
L=∑f(x)⊙gL = \sum f(x) \odot ga scalar whose gradient with respect to xx is the VJP of ff at ggfloat
ϵ\epsilonthe central-difference step, 10−610^{-6} in float64float
eie_ithe unit vector of element iiarray

A golden test compares with numbers that an independent implementation produced and a maintainer recorded: here torch’s float64 forward values and autograd gradients for fixed inputs (oracles.npz). It catches every bug that changes those numbers, including the ones that keep the shape. Its weakness is coverage: it only knows the recorded inputs. The suite reads the file through TINYLLM_FIXTURES, never through a hard-coded path.

The second oracle covers any input. For any differentiable ff and any gg, the VJP is the gradient of L(x)=∑f(x)⊙gL(x) = \sum f(x) \odot g:

∂L∂xi≈L(x+ϵei)−L(x−ϵei)2ϵ,error O(ϵ2)+O(u/ϵ).\frac{\partial L}{\partial x_i} \approx \frac{L(x + \epsilon e_i) - L(x - \epsilon e_i)}{2\epsilon}, \qquad \text{error } O(\epsilon^2) + O(u / \epsilon).

In float64 (u≈1.1×10−16u \approx 1.1 \times 10^{-16}) the step ϵ=10−6\epsilon = 10^{-6} balances truncation and rounding near 10−1010^{-10}, so a tolerance of 10−610^{-6} relative is safe for a correct backward and far below any real bug. A random gg (not all ones) matters: with g=1g = 1 a backward that sums where it should weigh can still pass. Check every input of the op (x, W, and b for a linear layer), with shapes where a transposed gradient would not fit and with square ones where it would.

The third oracle is a second implementation. Two implementations of the same contract must agree: the causal mask against attention over each query’s prefix, chunked against whole, C against Python, Rust against Python. A differential test needs no recorded numbers, so it covers any input that can be generated. When both sides come from the same author, one side must also be checked against another oracle, or two equally wrong implementations pass together.

Exact comparison fails for correct code as soon as two implementations sum in a different order. Use the dtype’s rounding: float64 differences near 10−1510^{-15} relative for a few operations, more for long reductions (with K\sqrt{K} growth, as Error analysis, condition numbers, and tolerance budgets explains). Too loose a tolerance hides real bugs: a missing 1/d1/\sqrt{d} is a factor of 2 for d=4d = 4, but a dropped term of size 10−310^{-3} needs a tolerance below that.

Working it by hand: the transposed gradient

Section titled “Working it by hand: the transposed gradient”

The bug that motivates all three oracles is small enough to work by hand. Take y=xW⊤y = x W^\top with x=(1,2)x = (1, 2) and W=(1031)W = \begin{pmatrix} 1 & 0 \\ 3 & 1 \end{pmatrix}, so y=(1⋅1+2⋅0, 1⋅3+2⋅1)=(1,5)y = (1 \cdot 1 + 2 \cdot 0,\ 1 \cdot 3 + 2 \cdot 1) = (1, 5). With upstream g=(1,0)g = (1, 0):

  • ∂L/∂W=g⊤x=(10)(1,2)=(1200)\partial L / \partial W = g^\top x = \begin{pmatrix} 1 \\ 0 \end{pmatrix} (1, 2) = \begin{pmatrix} 1 & 2 \\ 0 & 0 \end{pmatrix}: only row 0 of WW made y0y_0.
  • The transposed bug x⊤g=(1020)x^\top g = \begin{pmatrix} 1 & 0 \\ 2 & 0 \end{pmatrix} has the same 2×22 \times 2 shape and is wrong.
  • The central difference on W0,1W_{0,1} gives L(W0,1±ϵ)=1±2ϵL(W_{0,1} \pm \epsilon) = 1 \pm 2\epsilon, so the quotient is 22, matching the correct entry and not the transposed one (0).

A shape check passes both; the golden file and the gradcheck reject the bug. Shapes are not an oracle.

The kata, primers/craft.05/kernels.py, works in numpy float64, and its docstring is the spec:

def linear(x, W, b): ... # x @ W.T + b
def linear_backward(x, W, gy): ... # (gx, gW, gb)
def rmsnorm(x, w, eps=1e-6): ... # x / sqrt(mean(x^2) + eps) * w (L7.1)
def rmsnorm_backward(x, w, gy, eps=1e-6): ... # (gx, gw)
def swiglu(a, b): ... # silu(a) * b (L7.2)
def swiglu_backward(a, b, gh): ... # (ga, gb)
def attention(q, k, v, causal=False): ... # softmax(q k^T / sqrt(d)) v (L5.1)
def attention_backward(q, k, v, go, causal=False): ... # (gq, gk, gv)

The attention op is the one from Scaled dot-product attention. The oracle suite, primers/craft.05/test_oracles.py, imports the kata as kernels and uses no torch, no autograd, and no unseeded randomness. It applies four oracles, each catching some planted faults:

OracleFor
golden: every forward and every gradient equals oracles.npz (linear, linear_sq, rmsnorm, swiglu, attn, attn_causal)all four ops, square and non-square
gradcheck: central differences of ∑f⊙g\sum f \odot g for every input, random ggevery backward, on generated inputs
differential: causal attention equals attention over each query’s prefixthe mask
stability: scores of 300 give finite outputs (the mean of the values)the softmax’s max subtraction

A correct solution reproduces the hand-worked case (gW=g⊤xg_W = g^\top x, not x⊤gx^\top g), matches the golden file in every value and gradient, and comes with a suite made of oracles (golden values read through TINYLLM_FIXTURES, a gradcheck, no torch or autograd) that accepts a correct implementation and fails at least once against each of the 10 planted faults.

Seven steps take you from the definition to the kata and its suite.

  1. Derive each backward from L=∑f(x)⊙gL = \sum f(x) \odot g. For y=xW⊤+by = xW^\top + b, ∂L/∂Woi=∑ngnoxni\partial L/\partial W_{oi} = \sum_n g_{no} x_{ni}, so gW=g⊤xg_W = g^\top x with the shape of WW; gx=gWg_x = gW; gb=∑ngng_b = \sum_n g_n. Every backward of the kata comes from writing LL out and differentiating one index at a time.
  2. RMSNorm’s rms depends on xx. With n=x/rn = x/r and u=g⊙wu = g \odot w, differentiating through rr adds −n mean(u⊙n)-n\,\mathrm{mean}(u \odot n): gx=(u−n mean(u⊙n))/rg_x = (u - n\,\mathrm{mean}(u \odot n))/r. Treating rr as a constant drops that term.
  3. SwiGLU’s gate derivative is the product rule. dda aσ(a)=σ+aσ(1−σ)\frac{d}{da}\, a\sigma(a) = \sigma + a\sigma(1 - \sigma).
  4. Attention’s backward is three chain-rule steps. gv=P⊤gog_v = P^\top g_o; gP=gov⊤g_P = g_o v^\top; the softmax VJP is gS=P⊙(gP−∑jP⊙gP)g_S = P \odot (g_P - \sum_j P \odot g_P); then gq=gSk/dg_q = g_S k/\sqrt d and gk=gS⊤q/dg_k = g_S^\top q/\sqrt d.
  5. Keep the forward numerically safe. Subtract the row maximum before exp, and write the sigmoid as 12(1+tanh⁡(a/2))\frac12(1 + \tanh(a/2)), so neither overflows.
  6. Test with three independent oracles. Golden values from torch for fixed inputs, square and non-square; a float64 gradcheck with random upstream gg for every input; and a differential test of the causal mask against prefix attention. Each covers what the others cannot.
  7. Choose shapes and inputs that expose the faults. A square WW lets a transposed gradient fit; a non-square WW makes a wrong product fail on shape. Large aa makes SwiGLU’s missing term large; scores of 300 make an unshifted softmax overflow.

The linear, RMSNorm, and SwiGLU backwards follow directly from steps 1 to 3:

def linear_backward(x, W, gy):
gx = gy @ W # [N, o] @ [o, i] -> [N, i]
gW = gy.T @ x # [o, N] @ [N, i] -> [o, i]: the shape of W, NOT x.T @ gy
gb = gy.sum(axis=0) # summed over the batch: each example contributes
return gx, gW, gb
def rmsnorm_backward(x, w, gy, eps=1e-6):
r = _rms(x, eps) # sqrt(mean(x^2) + eps), per row
n = x / r
gw = (gy * n).reshape(-1, x.shape[-1]).sum(axis=0) # w is shared by every row
u = gy * w
gx = (u - n * np.mean(u * n, axis=-1, keepdims=True)) / r # the second term: r depends on x
return gx, gw
def _sigmoid(a):
return 0.5 * (1.0 + np.tanh(0.5 * a)) # no overflow for large |a|
def swiglu_backward(a, b, gh):
s = _sigmoid(a)
ga = gh * b * (s + a * s * (1.0 - s)) # product rule on a * sigmoid(a)
gb = gh * a * s
return ga, gb

Attention follows step 4, with step 5’s max subtraction in the shared probability helper:

def _probs(q, k, causal):
S = q @ np.swapaxes(k, -1, -2) / np.sqrt(q.shape[-1])
if causal:
Tq, Tk = S.shape[-2], S.shape[-1]
# key j visible to query i iff j <= i: the diagonal is visible, so no row is empty
S = np.where(np.arange(Tk)[None, :] <= np.arange(Tq)[:, None], S, -np.inf)
S = S - S.max(axis=-1, keepdims=True) # max subtraction: exp never overflows
P = np.exp(S) # hidden keys: exp(-inf) = 0
return P / P.sum(axis=-1, keepdims=True)
def attention_backward(q, k, v, go, causal=False):
P = _probs(q, k, causal) # recomputed, as a fused kernel would
gv = np.swapaxes(P, -1, -2) @ go
gP = go @ np.swapaxes(v, -1, -2)
gS = P * (gP - np.sum(P * gP, axis=-1, keepdims=True)) # softmax VJP; zero where P is zero
scale = 1.0 / np.sqrt(q.shape[-1])
gq = gS @ k * scale
gk = np.swapaxes(gS, -1, -2) @ q * scale # gS transposed: keys index the columns
return gq, gk, gv

The backward recomputes PP instead of storing it, which is what FlashAttention does to save memory. Masked keys have P=0P = 0, so the softmax VJP gives them zero gradient without any extra masking. The full kata is kernels.py.

The gradcheck helper is the oracle that needs no recorded numbers:

RNG = np.random.Generator(np.random.PCG64(5)) # seeded: the same inputs every run
def gradcheck(f, xs, grads, eps=1e-6, tol=1e-6):
"""Central differences of the scalar f(*xs) against grads, element by element."""
for i, (x, g) in enumerate(zip(xs, grads)):
assert g.shape == x.shape, f"input {i}: gradient shape {g.shape} != {x.shape}"
for idx in np.ndindex(x.shape):
old = x[idx]
x[idx] = old + eps
hi = f(*xs)
x[idx] = old - eps
lo = f(*xs)
x[idx] = old # restore before the next element
num = (hi - lo) / (2 * eps)
assert abs(num - g[idx]) <= tol * (1 + abs(num)), f"input {i} at {idx}: {g[idx]} vs {num}"

The tolerance 10−610^{-6} relative (plus absolute near 0) sits between the ∼10−10\sim 10^{-10} error of a correct central difference in float64 and the size of any real bug, as derived in Gradcheck as a test.

The tests, grouped by oracle:

@pytest.mark.parametrize("p", ["linear", "linear_sq"]) # non-square and square W
def test_linear_golden(p):
x, W, b, g = FIX[p + ".x"], FIX[p + ".W"], FIX[p + ".b"], FIX[p + ".g"]
np.testing.assert_allclose(K.linear(x, W, b), FIX[p + ".y"], atol=1e-12)
for got, name in zip(K.linear_backward(x, W, g), ("gx", "gW", "gb")):
np.testing.assert_allclose(got, FIX[f"{p}.{name}"], atol=1e-12, err_msg=name)
# ... test_rmsnorm_golden, test_swiglu_golden, and test_attention_golden for "attn" and
# "attn_causal" compare every forward and gradient the same way
def test_linear_gradcheck_square_and_not():
for o in (4, 3): # o == i: square W; o != i: not
x, W, b, g = RNG.normal(size=(2, 4)), RNG.normal(size=(o, 4)), RNG.normal(size=o), RNG.normal(size=(2, o))
gx, gW, gb = K.linear_backward(x, W, g)
gradcheck(lambda x, W, b: float(np.sum(K.linear(x, W, b) * g)), [x, W, b], [gx, gW, gb])
def test_swiglu_gradcheck():
a, b, g = RNG.normal(size=(2, 6)) * 3, RNG.normal(size=(2, 6)), RNG.normal(size=(2, 6)) # large a
ga, gb = K.swiglu_backward(a, b, g)
gradcheck(lambda a, b: float(np.sum(K.swiglu(a, b) * g)), [a, b], [ga, gb])
# ... test_rmsnorm_gradcheck and test_attention_gradcheck (causal and not) in the same form
def test_causal_equals_prefix_attention(): # differential: the mask vs. the definition
q, k, v = RNG.normal(size=(5, 3)), RNG.normal(size=(5, 3)), RNG.normal(size=(5, 2))
full = K.attention(q, k, v, causal=True)
for i in range(5):
np.testing.assert_allclose(full[i], K.attention(q[i : i + 1], k[: i + 1], v[: i + 1])[0], atol=1e-12)
def test_large_scores_stay_finite(): # stability: scores of 300 * 300 * 3 / sqrt(3)
q = np.full((2, 3), 300.0)
k = np.full((4, 3), 300.0)
v = RNG.normal(size=(4, 2))
o = K.attention(q, k, v)
assert np.isfinite(o).all()
np.testing.assert_allclose(o, np.tile(v.mean(axis=0), (2, 1)), atol=1e-12) # equal scores: the mean of v

The golden fixture (oracles.npz, torch’s float64 forwards and autograd gradients for fixed inputs) is read through the TINYLLM_FIXTURES directory. Every gradcheck uses a random upstream gg, never ones. The stability test knows its exact answer without any oracle file: when all scores are equal, softmax is uniform and the output is the mean of the values. The full suite is test_oracles.py.

Three oracles beat one. Golden values catch everything on their inputs, including non-square bugs, but only there; gradcheck covers any input but costs two forward passes per element; the differential test checks the mask’s meaning with no numbers recorded at all. A fault one misses, another catches.

Checking runs in float64, whatever the kernel’s dtype. Central differences in float32 have errors near 10−310^{-3}, too large to separate a correct backward from a slightly wrong one; the reference runs in float64 so the tolerance can be tight.

The gradcheck goes element by element rather than along a random projection. Perturbing each element costs O(size)O(\text{size}) forward passes, fine for the small shapes here; production tools (torch.autograd.gradcheck fast mode) project onto random directions to scale.

One tradeoff is accepted: golden files must be regenerated if a contract changes, and they tie the suite to torch’s conventions. That is the point, because those are the conventions the C and Rust ports must match.

The table lists the ten planted faults, followed by three mistakes in the suite itself:

PitfallSymptomHow the solution avoids it
A transposed weight gradient, x⊤gx^\top g for g⊤xg^\top xright shape on a square WW, wrong valuesgW = gy.T @ x; caught by the linear_sq golden case and the square gradcheck
gW⊤g W^\top for the input gradientfits only a square WWgx = gy @ W; caught by the non-square golden case and gradcheck
Averaging the bias gradient over the batchevery bias learns NN times too slowlygb = gy.sum(axis=0); caught by the golden test
RMSNorm’s backward treating the rms as a constantthe gradient misses the −n⋅mean(un)-n \cdot \mathrm{mean}(u n) termthe second term in gx; caught by test_rmsnorm_gradcheck
SwiGLU’s gate derivative as σ(a)\sigma(a) alonewrong by aσ(1−σ)a \sigma (1 - \sigma), small near 0the product rule s + a * s * (1 - s); caught by the gradcheck with aa scaled by 3
A softmax backward without the row sumgq and gk off by a term that vanishes only when gg is uniformgP - sum(P * gP); caught by gradchecks with random gg
Losing 1/d1/\sqrt{d} in the query gradientgq too large by d\sqrt{d}scale on both gq and gk; caught by the golden test
gSqg_S q for gS⊤qg_S^\top q in the key gradientfits square scores onlynp.swapaxes(gS, -1, -2) @ q; caught by the causal golden case and the gradcheck
A softmax without the max subtractioninf / inf at scores near 700 in float64S - S.max(...); caught by test_large_scores_stay_finite
A causal mask that hides the diagonalquery 0 sees nothing: NaNj <= i; caught by the causal golden case and the prefix differential
g = ones in a gradchecksum-instead-of-weigh bugs passevery gradcheck draws gg from the seeded generator
A tolerance tighter than float64 roundingthe correct kata failsgradcheck at 10−610^{-6} relative, golden at 10−1210^{-12} absolute
Comparing shapes onlyevery transposed bug on square inputs survivesevery test compares values

Warning: The transposed weight gradient is the most important fault on the list. On a square matrix it has the right shape and plausible magnitudes, and training with it still moves the loss, just in the wrong direction for most weights.

This section combined mutation testing and faults from pitfalls from TDD, unit tests, and mutation testing, the model property of Property-based tests (which is a differential oracle), and central differences from Partial derivatives, gradients, and gradcheck. The same three oracles carry forward:

Each piece of the suite has a production counterpart:

  • The gradcheck corresponds to torch.autograd.gradcheck and gradgradcheck (torch/autograd/gradcheck.py), which add complex inputs, a fast mode that uses a random projection instead of every element, and second derivatives.
  • Golden files correspond to PyTorch OpInfo (torch/testing/_internal/common_methods_invocations.py), where one description per op drives forward, backward, dtype, and device tests.
  • Differential tests correspond to FlashAttention’s tests (flash-attention/tests/test_flash_attn.py), which compare the fused kernel against a float64 reference with a tolerance set from the reference’s own float32 error.
  • Tolerances correspond to torch.testing.assert_close and its per-dtype defaults (PyTorch testing docs).
  • Barr et al., “The Oracle Problem in Software Testing: A Survey” (IEEE TSE, 2015).
  • McKeeman, “Differential Testing for Software” (1998).
  • The PyTorch torch.autograd.gradcheck documentation.
  • Oracle: something other than the code under test that knows the right answer.
  • Golden test: a comparison against numbers an independent implementation produced and a maintainer recorded.
  • Gradcheck: a comparison of a hand-written gradient against central differences of ∑f(x)⊙g\sum f(x) \odot g.
  • Differential test: a check that two implementations of the same contract agree on generated inputs.
  • VJP (vector-Jacobian product): the gradient of ∑f(x)⊙g\sum f(x) \odot g with respect to xx; what a backward pass computes.
  • Tolerance: the allowed difference between result and oracle, set from the dtype’s rounding.
  • A test needs an oracle. Golden files (torch’s numbers), a second implementation (differential), and a mathematical identity (central differences for a gradient) are the three used for every kernel from here on.
  • A hand-written backward is where the subtle bugs live: a transposed weight gradient has the right shape on a square matrix and the wrong values. Shapes are not an oracle.
  • Gradcheck is a test: central differences of ∑f(x)⊙g\sum f(x) \odot g for a random upstream gg check every input’s gradient, in float64, with a tolerance that float64 rounding cannot break.
  • Tolerances are part of the oracle: too tight and the correct kata fails; too loose and a lost 1/d1/\sqrt{d} survives.
  • A good oracle suite catches every one of the ten planted faults, the transposed weight gradient above all.
  1. Why can a transposed weight gradient pass a shape check, and which oracle catches it?

    Answer

    On a square WW (o=io = i), x⊤gx^\top g and g⊤xg^\top x are both o×io \times i, so the shape is right and the values are the transpose. The worked example shows the difference: the correct gWg_W is (1200)\begin{pmatrix} 1 & 2 \\ 0 & 0 \end{pmatrix}, the transposed one (1020)\begin{pmatrix} 1 & 0 \\ 2 & 0 \end{pmatrix}. The square golden case (linear_sq) and the gradcheck with o=4o = 4 both compare values and fail.

  2. Why must the gradcheck’s upstream gg be random rather than all ones?

    Answer

    With g=1g = 1 every output is weighted equally, so a backward that sums where it should weigh by gg gives the same numbers. The softmax VJP is the clearest case: with uniform gPg_P the row-sum term cancels exactly, so a backward that forgets it passes. A random gg makes each output’s weight distinct.

  3. What does test_causal_equals_prefix_attention check that the golden causal case does not?

    Answer

    It checks the meaning of the mask on generated inputs: causal attention for query ii must equal plain attention over keys 0..i0..i. The golden case only covers the recorded inputs. A mask that hides the diagonal gives query 0 no keys, so its row is NaN and the differential fails.

  4. Why is the gradcheck tolerance 10−610^{-6} and not 10−1210^{-12} or 10−310^{-3}?

    Answer

    A correct central difference in float64 with ϵ=10−6\epsilon = 10^{-6} has error near 10−1010^{-10} (truncation O(ϵ2)O(\epsilon^2) plus rounding O(u/ϵ)O(u/\epsilon)), so 10−1210^{-12} would reject correct code. 10−310^{-3} would let a small missing term survive, for example SwiGLU’s aσ(1−σ)a\sigma(1 - \sigma) near a=0a = 0. 10−610^{-6} sits safely between.

  5. Why does attention_backward recompute PP instead of taking it from the forward?

    Answer

    The kata mirrors how a fused kernel works: storing PP costs Tq×TkT_q \times T_k memory per head, while recomputing it from qq and kk costs one more matrix product. FlashAttention makes the same trade. Recomputing also keeps the backward’s signature a function of the inputs alone, which makes it easy to test.