6.3 The op library and gradcheck_all
Tensor, broadcasting backward, and no_grad built a Tensor that knows + - * / @ ** and indexing. A model needs more: a nonlinearity between layers, a softmax over the vocabulary, an embedding lookup for token ids, a mean for LayerNorm, a dropout mask. Written inline in each model, each of those is a chance to get a VJP wrong silently, because a wrong gradient still trains, just badly.
Concepts from other sections (26)
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.
- LayerNorm: per-row normalization by the population mean and variance with inside the square root, then an affine map. Read more: 6.5 Module system and basic layers
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- vector-Jacobian product (VJP): the function mapping an output gradient to input gradients without forming the Jacobian. Read more: 6.2 Tensor, broadcasting backward, and no_grad
- activation function: a nonlinear function applied elementwise between linear layers. Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement - softmax VJP: with , the backward of a row-wise softmax. Read more: 11.1 Scaled dot-product attention (forward and backward)
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
- Inner product: . Read more: 9.6 Inner products, projections, cosine similarity, and top-k in Mathematics
- Standard normal: the distribution with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics in Mathematics
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller in Mathematics
- Inverse permutation: (
inv_perm): the map from each assignment to its sorted slot, used to put outputs back. Read more: 13.8 Mixture of Experts - embedding table: the matrix whose row is the learned vector for token , shared across every window. Read more: 8.2 Bengio’s neural probabilistic language model
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- Pure function: a function whose output depends only on its inputs and which mutates nothing. Read more: Chapter 4: Coding and Design Patterns in Software Engineering
- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch. Read more: 6.6 Training loop and the autograd bigram
- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix. Read more: Chapter 9: Linear Algebra in Mathematics
- subgradient: a valid gradient choice at a non-differentiable point, such as a tie in max pooling. Read more: 14.1 Conv layers and pooling on autograd
- GELU: , the input weighted by the standard normal CDF; its tanh approximation is a different function. Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- Transformation (JAX): a function such as
jit,grad,vmap, orpmapthat takes a pure function and returns a compiled, differentiated, batched, or parallel version of it. Read more: 16.3 Embeddings, small models, and platforms - fully masked row: a row whose entries are all ; by contract its softmax is all zeros. Read more: 22.4 Softmax in C: three-pass and online two-pass
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP in Mathematics
- Directional derivative: , the rate of change of along a unit vector . Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange in Mathematics
This section puts every op in one library, functional.py (imported as F), with one VJP each, checks each against torch and against numerical differentiation, and gives the system’s CLI the gradcheck verb that the chapter’s end-to-end run starts with. From here on, model code (the layers of Module system and basic layers, the statistical and recurrent models, the Transformer) composes these ops and never writes a backward pass. The most important thing you will build is not any one op but gradcheck_all, a check that is strong enough to fail on a planted 0.1% error.
The section builds on several pieces of Mathematics: the activation functions and their derivatives from Activation Functions and Their Derivatives; stable softmax, log-softmax, and logsumexp from Stable numerics; the softmax VJPs and unbroadcast from Matrix differentials, the trace trick, and closed-form VJPs; dual numbers from Dual numbers and forward-mode autodiff; gradcheck from Partial derivatives, gradients, and gradcheck; and PCG32 from Modular arithmetic, hashing, and PCG32. The solution is functional.py, with 25 ops (activations, reductions, shape, selection, the softmax family, dropout, matmul) and gradcheck_all(), plus the gradcheck --suite all verb in entry/python/tinyllm/cli_train.py. The contract is functional.pyi.
The CLI verb is simple to state (spec/cli-roles.md): tinyllm gradcheck --suite all calls F.gradcheck_all(rtol=1e-5), prints one line per op, and ends with {"suite": "all", "checks": N, "failed": K, "max_rel_err": E, "worst": "<op>"}. It exits 0 only when failed is 0.
Learning objectives
- Write the closed-form VJP of elementwise ops, reductions (including
maxwith ties andvarwith a correction), shape ops, and selection ops.- Explain why the softmax-family VJPs are computed from the stable outputs, and verify one by hand.
- Implement inverted dropout with an explicit generator and a fixed draw count.
- Build a gradient checker that can actually fail, and explain each of its three defenses.
Families of VJPs
Section titled “Families of VJPs”The notation for this section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| an op’s input | Tensor, any shape | |
| its output | Tensor | |
| , | upstream gradient and the gradient handed back | shapes of , |
| the reduced axes of a reduction | tuple of ints | |
| number of elements reduced into each output | int | |
| along one axis | same shape as | |
| inner product along the softmax axis | ||
| , | standard normal density and CDF (gelu) | functions |
| dropout probability | float in | |
| the -th uniform draw of a PCG32 | float in | |
random output weights inside gradcheck_all | shape of | |
| central-difference step, | float |
Elementwise ops
Section titled “Elementwise ops”For applied entry by entry, . The derivatives are the standard ones: (reuse the output), , , , (0 at the kink, as in torch), , and two gelu forms: exact and the tanh approximation . approximate="none" or "tanh" picks one; anything else is an error, because Hugging Face configs name exactly these two.
Reductions put axes back
Section titled “Reductions put axes back”sum(x, axis=A) adds every input element into one output with weight 1, so is copied back over . Without keepdims the output lost those axes; np.expand_dims(g, A) restores them as size 1, and broadcasting copies. mean is sum times with the size of the reduced axes only.
max routes the gradient to the entries equal to the maximum. With ties, torch (amax) splits it equally, so the shares still add up to . var with correction is : is the population variance LayerNorm uses, the sample variance. Its gradient is ; the terms through vanish because .
Shape ops move gradients back
Section titled “Shape ops move gradients back”reshape reshapes to the input shape. transpose(a, b) is its own inverse. permute(dims) is undone by the inverse permutation, argsort(dims), not by applying dims again. concat splits at the cumulative sizes of its inputs, and stack takes slice along the stacking axis for input .
Selection ops add
Section titled “Selection ops add”where(cond, a, b) sends to where cond holds and to elsewhere, then unbroadcasts each. masked_fill(x, mask, v) sends nothing to the filled positions: an attention mask must not train the scores it hid. gather(x, idx, axis) (torch’s semantics) and embedding(W, ids) read entries, possibly the same one twice, so their VJPs are scatter-adds (np.add.at). Both check their indices, because NumPy would read -1 as the last row and never complain.
The softmax family, stably
Section titled “The softmax family, stably”Forward values come from the stable forms (subtract the max first). The VJPs use the outputs:
and for , . None of these ever computes of a raw logit, so a logit of 1000 is as safe as one of 1. A row masked entirely to has softmax zeros (the rule from Stable numerics) and therefore a zero gradient.
Inverted dropout
Section titled “Inverted dropout”During training each element is kept with probability and scaled by , so the expected output equals the input and evaluation needs no rescaling: in eval mode, or with , dropout returns its input object and draws nothing. The mask uses one uniform per element in C order, , from the PCG32 the caller passes in. The draw count is fixed (exactly x.size draws per call), which is what lets a resumed run in Safetensors for every dtype, atomic checkpoints, and the token stream reproduce the same masks. drops everything, with no division by zero.
A gradient check that can fail
Section titled “A gradient check that can fail”For each op, gradcheck_all draws float64 inputs from PCG32(0), keeps them away from kinks (relu at 0, max ties), and compares the analytic gradient of with central differences through gradcheck at rtol. The weights are random on purpose: for every , so the gradient of the plain sum is zero and any softmax VJP, right or wrong, would pass.
Central differences resolve relative errors near . A smaller error in an elementwise derivative is caught by a second check, forward-mode dual numbers, which are exact to rounding and flag a gap above . Ops are looked up in the module when the check runs, so a monkeypatched op is the one checked.
Working it by hand
Section titled “Working it by hand”Three of these VJPs are worth computing on paper before you see the code.
Start with softmax. Take . Then , the sum is 6, and . With the upstream gradient (the loss looks only at the first output), the VJP runs in three steps:
- .
- .
- Multiply by : .
The entries sum to zero. Raising every logit by the same amount leaves softmax unchanged, so no direction along can change the loss. You can check by perturbation: , whose derivative at is .
Next, a tie in max. is reached twice, and torch’s amax gives each maximal entry half: for .
Finally, variance. For , and the squared deviations are , so var is with correction 0 and with correction 1. The walkthrough below traces each of these through the code.
Designing the API
Section titled “Designing the API”# python/tinyllm/autograd/functional.py (from tinyllm.autograd import functional as F)exp, log, tanh, sigmoid, relu, silu; gelu(x, approximate="none" | "tanh")sum(x, axis=None, keepdims=False); mean(...); max(...); var(x, axis=None, keepdims=False, correction=0)reshape(x, shape); transpose(x, a, b); permute(x, dims); concat(xs, axis=0); stack(xs, axis=0)where(cond, a, b); gather(x, idx, axis); embedding(weight, ids); masked_fill(x, mask, value)softmax(x, axis=-1); log_softmax(x, axis=-1); logsumexp(x, axis=-1, keepdims=False)dropout(x, p, training, rng); matmul(a, b)def gradcheck_all(rtol: float = 1e-5) -> dict[str, GradcheckReport]sum, max, and mean shadow Python builtins inside the module, so the solution calls builtins.max where it needs the builtin. Float32 inputs give float32 outputs and gradients: derivative arrays and masks are cast to the input’s dtype.
A correct library has to satisfy a set of checks, each tied to something later in the book. It must reproduce the hand-worked softmax backward and give max([1, 3, 3]) the gradient , for torch parity in max pooling. Its values and gradients must equal torch 2.14 on 45 golden cases, since the models of the Transformer, objectives, and modern decoder block chapters are ported from torch. Every VJP must pass central differences in float64, because a wrong VJP trains badly rather than visibly. Twelve ops must map float32 in to float32 out, including a float32 gradient through dropout, so Python agrees with the float32 C kernels of the kernels chapter. must be 0, torch’s convention.
Selection ops must accumulate: a repeated token gets both rows of gradient (every embedding table depends on this), and an index gathered twice gets gradient 2 (the cross-entropy gather in Losses with a fused backward depends on that). embedding rejects -1, n, and float ids with a ValueError, so tokenizer bugs fail where they enter.
Dropout has four checks. In eval mode it returns the input object and draws nothing, so evaluation is deterministic. At about 75% of elements are kept and survivors are scaled by , so the expected output is the input. The mask is exactly for the same-seed uniforms, with exactly x.size draws, so a resumed run replays the masks. gives zeros, and is an error, so config errors fail early.
The numerics checks: an all-masked softmax row gives zeros and a zero gradient, which padded rows in Masks produce; logsumexp([1000, 1000]) and its gradient come out without overflow, because trained logits are large; and the variance correction gives 1.25 and , with an error (LayerNorm uses the population variance). where and masked_fill must send gradients to the chosen operand and none to filled positions, as attention masks require. Only "none" and "tanh" are accepted for gelu. Every op returns a constant under no_grad. And gradcheck_all must return one ok report per op, 33 names in all, and must flag both a 0.1% softmax error and a sigmoid error, because a checker that always passes is worse than none.
Building it step by step
Section titled “Building it step by step”The reasoning chain
Section titled “The reasoning chain”- One op, one forward, one VJP, one
from_opcall. TheTensoralready handles graph bookkeeping, dtype casting of gradients, and shape checks. So an op only has to compute its forward with NumPy and return a closure that maps to . No op calls another op’s backward, which keeps every VJP independently checkable. - Elementwise ops share one pattern. , so a helper that takes
fanddfcovers tanh, sigmoid, relu, silu, and both gelus.expandlogare written out becauseexpreuses its output as its derivative andlog’s derivative is a division. - A reduction’s VJP is “put the axes back, then broadcast”. Normalize the axis argument once (negative axes, tuples,
None), sonp.expand_dims(g, axes)can restore exactly the reduced axes as size 1. Thensumbroadcasts,maxmultiplies by an equal-share mask, andvarmultiplies by . - Shape ops invert themselves. Each forward is a pure rearrangement, so the backward applies the inverse rearrangement to : reshape back, swap the same two axes, transpose by the inverse permutation, split at cumulative sizes, take slice .
- Selection ops scatter with
np.add.atand check their indices. Any op that reads an entry more than once must add each contribution back. Index validation sits in one helper sogatherandembeddingreject-1the same way. - The softmax family reuses the stable forward. The VJPs are written in terms of the output , which the stable forward already produced, so backward never exponentiates a raw logit.
- Dropout’s randomness is an explicit input. Taking the generator as an argument and drawing exactly
x.sizeuniforms makes the mask a pure function of the generator state, which is what makes training resumable bit for bit. - The checker must be able to fail. A random output weighting defeats the softmax blind spot, kinks are pushed out of reach, and a second, exact check (duals) covers errors below what central differences resolve. Looking ops up at call time makes the checker check whatever is actually installed.
Lifting and the elementwise helper
Section titled “Lifting and the elementwise helper”def _t(x) -> Tensor: """x as a Tensor: Tensors pass through, anything else is a constant.""" if isinstance(x, Tensor): return x a = np.asarray(x) # a float array keeps its dtype; ints and bools become float32 constants return Tensor(a, dtype=a.dtype if a.dtype.kind == "f" else np.float32)
def _elementwise(x, f, df, name: str) -> Tensor: """y = f(x) with vjp g * df(x), both in x's dtype.""" x = _t(x) a = x.data y = np.asarray(f(a), dtype=a.dtype) # M01.3 helpers may return float64 return from_op(y, (x,), lambda g: (g * np.asarray(df(a), dtype=a.dtype),), name)
def exp(x): x = _t(x) y = np.exp(x.data) return from_op(y, (x,), lambda g: (g * y,), "exp") # d e^x = e^x: reuse the output
def gelu(x, approximate="none"): if approximate == "none": return _elementwise(x, act.gelu_erf, act.dgelu_erf, "gelu") if approximate == "tanh": return _elementwise(x, act.gelu_tanh, act.dgelu_tanh, "gelu_tanh") raise ValueError(f"approximate must be 'none' or 'tanh', got {approximate!r}")The two dtype=a.dtype casts are the whole float32 story for elementwise ops: without them a float64 derivative array would promote the gradient, and a float64 forward would promote every later activation. relu uses act.drelu, which is , so as in torch.
Reductions
Section titled “Reductions”Axis normalization comes first, because every reduction’s backward depends on knowing exactly which axes disappeared.
def _axes(axis, ndim: int) -> tuple[int, ...]: """axis as a sorted tuple of non-negative axes (None: every axis).""" if axis is None: return tuple(range(ndim)) ax = (axis,) if isinstance(axis, (int, np.integer)) else tuple(axis) out = [] for a in ax: a = int(a) if not -ndim <= a < builtins.max(ndim, 1): # builtins.max: F.max shadows it raise ValueError(f"axis {a} is out of range for {ndim} dimensions") out.append(a % ndim if ndim else 0) return tuple(sorted(set(out))) # sorted: expand_dims inserts in order
def _expand(g, axes, keepdims: bool): """An upstream gradient of a reduction, with the reduced axes put back as size 1.""" return g if keepdims else np.expand_dims(g, axes)
def sum(x, axis=None, keepdims=False): x = _t(x) axes = _axes(axis, x.ndim) shape = x.shape y = np.sum(x.data, axis=axes, keepdims=keepdims) # Every input element contributed with weight 1: copy g back over the axes. # .copy(): broadcast_to returns a read-only view, and backward adds into gradients return from_op( y, (x,), lambda g: (np.broadcast_to(_expand(g, axes, keepdims), shape).copy(),), "sum" )
def mean(x, axis=None, keepdims=False): x = _t(x) axes = _axes(axis, x.ndim) n = math.prod(x.shape[a] for a in axes) # the REDUCED count, not x.size if n == 0: raise ValueError("mean over an empty axis") return sum(x, axis, keepdims) * (1.0 / n) # two existing ops: no new VJP to get wrong
def max(x, axis=None, keepdims=False): x = _t(x) axes = _axes(axis, x.ndim) a = x.data y = np.max(a, axis=axes, keepdims=keepdims)
def vjp(g): ym = np.max(a, axis=axes, keepdims=True) hit = (a == ym).astype(a.dtype) # 1 at every maximal entry # Ties share the gradient equally (torch.amax), so it still sums to g. share = hit / np.sum(hit, axis=axes, keepdims=True) return (share * _expand(g, axes, keepdims),)
return from_op(y, (x,), vjp, "max")
def var(x, axis=None, keepdims=False, correction=0): x = _t(x) axes = _axes(axis, x.ndim) n = math.prod(x.shape[a] for a in axes) if n - correction <= 0: # n = 1 with Bessel's correction divides by 0 raise ValueError(f"var over {n} elements with correction {correction}") a = x.data d = a - np.mean(a, axis=axes, keepdims=True) y = np.sum(d * d, axis=axes, keepdims=keepdims) / (n - correction) # d/dx_i of sum_j (x_j - mu)^2 is 2 (x_i - mu): the terms through mu sum # to zero because sum_j (x_j - mu) = 0. return from_op( y.astype(a.dtype, copy=False), (x,), lambda g: (_expand(g, axes, keepdims) * (2.0 / (n - correction)) * d,), "var", )On max([1, 3, 3]), hit = [0, 1, 1], its sum is 2, and share = [0, 0.5, 0.5], exactly as computed by hand. On var([1, 2, 3, 4]), d = [-1.5, -0.5, 0.5, 1.5], , divided by or .
Shape ops
Section titled “Shape ops”def reshape(x, shape): x = _t(x) s = x.shape return from_op(x.data.reshape(tuple(shape)), (x,), lambda g: (g.reshape(s),), "reshape")
def transpose(x, a, b): x = _t(x) # swapping the same two axes again is the inverse return from_op(np.swapaxes(x.data, a, b), (x,), lambda g: (np.swapaxes(g, a, b),), "transpose")
def permute(x, dims): x = _t(x) dims = tuple(int(d) % builtins.max(x.ndim, 1) for d in dims) if sorted(dims) != list(range(x.ndim)): raise ValueError(f"dims {dims} is not a permutation of {x.ndim} axes") inv = tuple(int(i) for i in np.argsort(dims)) # undo the permutation in backward return from_op(np.transpose(x.data, dims), (x,), lambda g: (np.transpose(g, inv),), "permute")
def concat(xs, axis=0): ts = [_t(x) for x in xs] # ... empty list is an error sizes = [t.shape[axis] for t in ts] cuts = np.cumsum(sizes)[:-1] # split points are CUMULATIVE sizes return from_op(np.concatenate([t.data for t in ts], axis=axis), ts, lambda g: tuple(np.split(g, cuts, axis=axis)), "concat")
def stack(xs, axis=0): ts = [_t(x) for x in xs] # ... empty list is an error y = np.stack([t.data for t in ts], axis=axis) ax = axis % y.ndim # normalized against the OUTPUT's rank return from_op(y, ts, lambda g: tuple(np.take(g, i, axis=ax) for i in range(len(ts))), "stack")For permute(x, (2, 0, 1)), output axis 0 is input axis 2. Applying (2, 0, 1) again would rotate further; argsort((2, 0, 1)) = (1, 2, 0) is the permutation that brings each axis home.
Selection ops
Section titled “Selection ops”def _int_index(idx, n: int, what: str): """An integer index array checked against [0, n).""" a = np.asarray(idx) if a.size and not np.issubdtype(a.dtype, np.integer): raise ValueError(f"{what} must be integers, got dtype {a.dtype}") a = a.astype(np.int64) if a.size and (a.min() < 0 or a.max() >= n): # numpy would wrap -1 silently raise ValueError(f"{what} must lie in [0, {n}), got min {a.min()} and max {a.max()}") return a
def embedding(weight, ids): w = _t(weight) # ... weight must be 2-D [n, d] i = _int_index(ids, w.shape[0], "ids") W = w.data
def vjp(g): out = np.zeros_like(W) np.add.at(out, i, g) # a token that appears twice gets both rows of gradient return (out,)
return from_op(W[i], (w,), vjp, "embedding")
def gather(x, idx, axis): x = _t(x) ax = axis % x.ndim i = _int_index(idx, x.shape[ax], "gather index") # ... idx must have x's rank (torch.gather semantics) a = x.data
def vjp(g): out = np.zeros_like(a) # Full coordinates of every output element, with axis replaced by the # index: add.at so a position picked twice gets both gradients. coords = list(np.indices(i.shape, sparse=True)) coords[ax] = i np.add.at(out, tuple(coords), g) return (out,)
return from_op(np.take_along_axis(a, i, axis=ax), (x,), vjp, "gather")
def masked_fill(x, mask, value): x = _t(x) m = np.broadcast_to(np.asarray(mask, dtype=bool), x.shape) y = np.where(m, np.asarray(value, dtype=x.dtype), x.data) # a filled position's output does not depend on x: its gradient is zero return from_op(y, (x,), lambda g: (np.where(m, np.zeros((), dtype=g.dtype), g),), "masked_fill")gather’s backward needs the full coordinate of every output element: np.indices(i.shape, sparse=True) gives open grids for every axis, and replacing the gathered axis with i turns them into the input coordinates take_along_axis read. where follows the same idea with two operands: g where cond holds goes to a, the rest to b, and each is unbroadcast to its operand’s shape, because where(cond, a, b) broadcasts all three. A zero is built with g’s dtype so the gradient is not promoted.
The softmax family
Section titled “The softmax family”def softmax(x, axis=-1): x = _t(x) y = np.asarray(stable.softmax(x.data, axis=axis), dtype=x.dtype) # M09.2: max subtracted return from_op(y, (x,), lambda g: (softmax_vjp(g, y, axis),), "softmax")
def log_softmax(x, axis=-1): x = _t(x) y = np.asarray(stable.log_softmax(x.data, axis=axis), dtype=x.dtype) return from_op(y, (x,), lambda g: (log_softmax_vjp(g, y, axis),), "log_softmax")
def logsumexp(x, axis=-1, keepdims=False): x = _t(x) a = x.data y = np.asarray(stable.logsumexp(a, axis=axis, keepdims=keepdims), dtype=x.dtype) ax = axis % builtins.max(x.ndim, 1) # d logsumexp(x) / dx_i = softmax(x)_i, computed stably, never exp(x) / exp(y) return from_op(y, (x,), lambda g: (_expand(g, (ax,), keepdims) * np.asarray(stable.softmax(a, axis=ax), dtype=a.dtype),), "logsumexp")The VJPs themselves live in vjp.py:
def softmax_vjp(g, y, axis=-1): # y * (g - <g, y>): uses only the output, so a masked row (y = 0) gives 0 return y * (g - np.sum(g * y, axis=axis, keepdims=True))
def log_softmax_vjp(g, y, axis=-1): # y is log-softmax, so exp(y) is softmax: never exp of a raw logit return g - np.exp(y) * np.sum(g, axis=axis, keepdims=True)Trace the hand example through it: , , np.sum(g * y) = 1/6, g - 1/6 = [5/6, -1/6, -1/6], and times that is .
Dropout and matmul
Section titled “Dropout and matmul”def dropout(x, p, training, rng): if not 0.0 <= p <= 1.0: raise ValueError(f"dropout p must be in [0, 1], got {p}") x = _t(x) if not training or p == 0.0: return x # the same object, and no draws consumed u = np.asarray(rng.uniforms(x.data.size), dtype=np.float64).reshape(x.shape) # C order keep = u >= p # P(keep) = 1 - p # Inverted dropout: scale at training time so evaluation is the identity. scale = 0.0 if p == 1.0 else 1.0 / (1.0 - p) # p = 1: all zeros, no division by 0 m = (keep * scale).astype(x.dtype) # the mask in x's dtype: no float64 leak return from_op(x.data * m, (x,), lambda g: (g * m,), "dropout")
def matmul(a, b): return _t(a) @ b # L0.1's VJP, unchangedReturning x itself in eval mode (rather than a copy through from_op) means evaluation draws nothing from the generator, so whether an evaluation ran between two training steps cannot change the next training mask.
gradcheck_all
Section titled “gradcheck_all”def gradcheck_all(rtol: float = 1e-5) -> dict[str, GradcheckReport]: reports = {} rng = PCG32(0) # fixed inputs: the check is reproducible for name, fn, shapes, (lo, hi) in _cases(): # 33 cases, ops looked up via globals() xs = [lo + (hi - lo) * rng.uniforms(math.prod(s)).reshape(s) for s in shapes] # Keep kinks out of reach: relu at 0 and max ties have no derivative. xs = [np.where(np.abs(x) < 0.05, x + 0.1, x) for x in xs] out_shape = fn(*[Tensor(x, dtype=np.float64) for x in xs]).shape # random weights, centred on 0: sum(softmax) = 1 would make a plain sum blind w = rng.uniforms(math.prod(out_shape)).reshape(out_shape) - 0.5
def f(*arrays, fn=fn, w=w) -> float: # default args bind this iteration's fn, w return float(np.sum(fn(*[Tensor(a, dtype=np.float64) for a in arrays]).data * w))
ts = [Tensor(x, requires_grad=True, dtype=np.float64) for x in xs] fn(*ts).backward(w) # analytic gradient of sum(y * w) analytic = [t.grad if t.grad is not None else np.zeros_like(t.data) for t in ts] rep = gradcheck(f, xs, analytic, rtol=rtol) # M04.1 central differences # elementwise ops: forward-mode duals are exact to rounding if name in _DUAL and _dual_error(name, fn) > 1e-9: rep = dataclasses.replace(rep, ok=False) reports[name] = rep return reportsThree details make it a real test. _cases() reads ops from globals() when it runs, so if a test (or a debugging session) replaces F.softmax, the replacement is what gets checked. Dropout is checked with a _Rng whose uniforms restarts PCG32(7) on every call, so every evaluation of f sees the same mask and the op is a fixed linear map that finite differences can probe. And _dual_error evaluates each elementwise op’s backward at four points against dual.derivative of an independent forward-mode formula (sigmoid written as , gelu through dual_erf), so a error, invisible to central differences at , still fails.
The CLI verb wraps it:
reports = F.gradcheck_all(rtol=1e-5)failed = sorted(name for name, r in reports.items() if not r.ok)worst = max(reports, key=lambda n: reports[n].max_rel_err) if reports else ""# ... one "ok <op> max_rel_err ..." or "FAIL <op> ..." line per opresult = {"suite": a.suite, "checks": len(reports), "failed": len(failed), "max_rel_err": float(max((r.max_rel_err for r in reports.values()), default=0.0)), "worst": worst}if failed: raise CheckFailed(result, f"gradcheck failed for {', '.join(failed)}") # exit 1The full solution is functional.py; the verb is cmd_gradcheck in cli_train.py.
Why this design
Section titled “Why this design”Every VJP costs about as much as its forward: one pass over the input for elementwise ops and reductions, a scatter-add for selection, a matmul pair for matmul. gradcheck_all is expensive by design (two forward passes per input element for central differences) and runs on tiny shapes, so the whole suite takes well under a second.
Closed-form VJPs are preferred to composing primitives. softmax could be built as exp(x - max) / sum(exp(...)) from existing ops and differentiated automatically, but that graph has four nodes, keeps four intermediate arrays, and its backward passes through exp of shifted logits; the closed form keeps one array (the output) and is stable by construction. mean is the one place composition wins: sum * (1/n) is exactly right and adds no new VJP.
Equal-share ties are preferred to first-index ties. Routing the whole gradient to the first maximum is also a valid subgradient, but it disagrees with torch’s amax, and torch parity is how later chapters port models. Giving every tie the full gradient is simply wrong: the shares then sum to .
An explicit generator is preferred to a global RNG. np.random global state would make dropout masks depend on everything else that ever drew a number. Passing the PCG32 in and fixing the draw count makes masks reproducible across a crash and resume, and portable to Rust. And two independent checks are better than one: central differences catch structural errors (a missing transpose, a wrong sign) on every op, while duals catch tiny analytic errors on elementwise ops. Either alone misses a class of bugs.
One tradeoff is accepted: selection ops allocate a dense zero gradient the size of the table (a [50257, 768] embedding gets a dense gradient even if a batch touches 100 rows). Sparse gradients are left to production frameworks.
What can go wrong
Section titled “What can go wrong”| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
out[ids] = g in embedding or gather | frequent tokens train slower than rare ones | np.add.at in both VJPs |
| trusting ids | -1 silently trains the last row of the table | _int_index rejects non-integers and values outside |
ties in max: every maximal entry gets the full gradient, or only the first | gradients double, or disagree with torch | share = hit / sum(hit) |
the logsumexp VJP as exp(x) / exp(y) | inf / inf = nan at logit 1000 | the VJP multiplies by stable.softmax(a) |
| feeding the softmax VJP the input instead of the output | wrong gradients everywhere, nan on masked rows | softmax_vjp(g, y, axis) closes over the stable output |
a gradcheck_all that cannot fail (no dual check, or a loose tolerance) | gradcheck --suite all passes with a broken op | random output weights, a dual check at , and rtol=1e-5 |
| float64 leaking from a mask or a derivative array | a float32 model becomes float64, twice the memory | every derivative, mask, and zero is cast to the input’s or the gradient’s dtype |
Warning: Checking softmax with the gradient of
sum(y)proves nothing: that gradient is identically zero, so every VJP whose rows sum to zero passes. Always weight the output randomly.
Where this leads
Section titled “Where this leads”This section drew on the Tensor and from_op of Tensor, broadcasting backward, and no_grad and, from Mathematics, on the activation derivatives, the stable softmax forwards, softmax_vjp, log_softmax_vjp, and unbroadcast, derivative on dual numbers (the second check in gradcheck_all), the central-difference gradcheck, and PCG32 (dropout’s uniforms and gradcheck_all’s inputs).
Within the chapter, Linear, LayerNorm, Embedding, and Dropout in Module system and basic layers are compositions of F ops; BigramLogits.forward in Training loop and the autograd bigram is F.embedding, and the trainer reshapes with F.reshape; and the checkpoint tests of Safetensors for every dtype, atomic checkpoints, and the token stream compute their training loss as F.mean of a squared error.
Later, Conv layers and pooling on autograd uses reshape and relu around its conv and pooling ops; Vision transformer encoder uses GELU variants and residual sums in every block; Contrastive image-text: CLIP and SigLIP builds its similarity losses from normalization, matmul, and log-softmax; Whisper encoder applies GELU after each stem conv and inside every block; and Whisper decoder and checkpoint weights composes F ops for decoding. Every later model, from Bengio’s neural probabilistic language model through the recurrent, attention origins, Transformer, objectives, and modern decoder block chapters, is written in F and never defines its own backward.
Further reading
Section titled “Further reading”- Griewank and Walther, Evaluating Derivatives (2nd ed.), ch. 3 and 4.
- PyTorch
tools/autograd/derivatives.yaml, read as a table of VJPs: a generated backward for about 2,000 ops, double-backward, and forward-mode formulas. torch.autograd.gradcheckandgradgradcheck(torch/autograd/gradcheck.py): complex inputs, sparse layouts, second derivatives, and a fast mode with random projections.torch.nn.functional.dropout(aten/src/ATen/native/Dropout.cpp) and JAXrandom.bernoulli: a Philox counter-based RNG on GPU, fused into matmul epilogues.- Fused softmax and log-softmax kernels (
aten/src/ATen/native/SoftMax.cpp): one pass over the row with an online max, as in Softmax in C: three-pass and online two-pass.
Key terms
Section titled “Key terms”- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. - reduction: an op that collapses axes (
sum,mean,max,var); its VJP restores the reduced axes and broadcasts. - scatter-add: adding each upstream contribution into its source position with
np.add.at, so repeated reads accumulate. - inverted dropout: zeroing elements with probability and scaling survivors by during training, so evaluation is the identity.
- central differences: the numerical derivative , used as an oracle for analytic gradients.
- dual numbers: forward-mode autodiff values that carry an exact derivative alongside each number.
Summary
Section titled “Summary”- Every op is one NumPy forward plus one closed-form VJP joined by
from_op; nothing in the library calls another op’s backward. - Reductions put the reduced axes back before broadcasting the gradient, a maximum shares its gradient among ties, and a mean divides by the reduced count only.
- Selection ops route gradient by addition: a token or index used twice gets both gradients, and an out-of-range id is an error where it enters.
- The softmax family’s VJPs are computed from the stable outputs, so logits of 1000 and fully masked rows give finite gradients.
gradcheck_allchecks every op against central differences with a random output weighting, plus forward-mode duals for the elementwise ops, and it fails on a planted 0.1% or error.
Review questions
Section titled “Review questions”-
Why does
gradcheck_allweight the output by random instead of differentiatingsum(y)?Answer
For softmax, for every input, so the true gradient of the plain sum is zero, and any VJP whose output sums to zero along the axis (including many wrong ones) would match central differences of a constant. Random weights make the scalar depend on every output differently, so every part of the VJP is exercised.
-
Why does the
maxVJP divide the hit mask by its sum?Answer
When entries tie for the maximum, the subgradient that matches torch’s
amaxgives each of , so the shares sum to as the chain rule requires. Without the division each tie gets the full gradient and the total is . -
What goes wrong if
permute’s backward appliesdimsagain instead ofargsort(dims)?Answer
A permutation applied twice is not the identity unless it is its own inverse (a swap). For
(2, 0, 1)applying it twice gives(1, 2, 0)of the original, so the gradient comes back with axes in the wrong order: wrong values for any shape, and a shape error whenever the axis sizes differ. -
Why does dropout in eval mode return its input object instead of
x * 1?Answer
Two reasons: evaluation must be deterministic and free, and it must not consume generator draws. Returning
xdraws nothing, builds no node, and leaves the generator where it was, so the next training step’s mask is the same whether or not an evaluation happened in between. -
Why does
gradcheck_allshift inputs with away from zero?Answer
Central differences assume the function is smooth between and . At relu’s kink an input within of 0 gives a numerical slope near while the analytic VJP says 0 or 1, so a correct op would be reported as broken. Moving every input at least 0.05 from zero (far more than ) keeps each probe on one side of the kink, and the check stays sharp everywhere else.
-
In the hand-worked softmax example, why must the entries of sum to zero?
Answer
Softmax is invariant to adding the same constant to every logit, so moving along cannot change any output or the loss. The directional derivative along that vector, which is the sum of the entries of , must therefore be zero.