10.1 Partial derivatives, gradients, and gradcheck
Every neural network you train is a function of many arrays, and every training step needs the derivative of a scalar loss with respect to every element of every one of them. Later, in AI Engineering, you will write an autograd engine and a library of about 40 differentiable ops, each with a hand-written backward rule (Tensor, broadcasting backward, and no_grad and The op library and gradcheck_all). A backward rule is a claim: “this array is the gradient of the loss with respect to that input.” Claims need a referee.
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.
- 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 in AI Engineering
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all in AI Engineering - central difference: , a second-order approximation of . Read more: 7.1 Derivatives and Finite Differences
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- Vector-valued function: a function that traces a curve in space; its derivative is the tangent (velocity) vector, and is arc length. Read more: Chapter 10: Calculus 3
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- truncation error: the error from dropping the higher terms of the Taylor series. Read more: 7.1 Derivatives and Finite Differences
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Backpropagation: reverse-mode automatic differentiation that computes all parameter gradients in one backward pass. Read more: Chapter 2: Deep Learning in AI Engineering
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all in AI Engineering
- forward difference: , a first-order approximation of . Read more: 7.1 Derivatives and Finite Differences
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- 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 in AI Engineering - Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs. Read more: 14.2 Scalar reverse mode: the Value graph
The referee is the definition of the derivative, applied one coordinate at a time: perturb one weight by , rerun the forward pass, divide. Derivatives and Finite Differences gave you the one-coordinate version as central_diff. This section turns it into the gradient of a scalar function of several arrays, and into the check that compares that numerical gradient with an analytic one. The system’s {tinyllm} gradcheck --suite all command runs the whole op library through this check, so every backward rule you write later passes through the file you build here.
The solution lives in gradcheck.py (numerical_grad, gradcheck, and its GradcheckReport), with the typed interface in course/contracts/py/tinyllm/num/gradcheck.pyi. It makes one call to central_diff from diff.py per coordinate, and nothing else.
Learning objectives
- Compute partial derivatives and the gradient of a scalar function of several arrays, arranged in each input’s shape.
- Build a numerical gradient from one central difference per element, and explain its cost ( evaluations) and why it is exact on quadratics.
- Apply the mixed tolerance and explain why neither a pure absolute nor a pure relative test works.
- Write a gradient check that rejects real backward-pass bugs (a transposed gradient, a factor of 2, one forgotten element, a NaN) and reports the element furthest past its tolerance.
- Explain why the check perturbs float64 copies rather than the caller’s arrays.
Notation
Section titled “Notation”The section uses a small set of symbols throughout; this table pairs each one with the Python type it becomes.
| Symbol | Meaning | Type / shape |
|---|---|---|
| a scalar function of arrays (a loss) | Callable[..., float] | |
| the -th input array; one element, a multi-index | float64[...] | |
| the partial derivative with respect to that element | float | |
| the gradient with respect to , same shape as | float64[...] | |
the finite-difference step (eps), default | float | |
| , | one element of the analytic and of the numerical gradient | float |
| rtol, atol | relative and absolute tolerances, defaults and | float |
| the array that is 1 at position and 0 elsewhere | same shape as |
Partial derivatives
Section titled “Partial derivatives”Start with a function of two numbers, . Freeze and differentiate in : . Freeze and differentiate in : . Formally,
which is just the one-variable derivative from Calculus 1, taken along the direction. A partial derivative measures how responds to one input when nothing else moves, and that is exactly the question a training step asks of each weight.
The gradient
Section titled “The gradient”The gradient lists every partial derivative: . For a function of arrays there is one partial derivative per element, and the gradient with respect to is arranged in ‘s shape, so that a training step is simply .
Two facts make the gradient the right object. First, for a small change in the inputs, changes by about , the dot product of the gradient with . That is a first-order Taylor expansion, as in Taylor series, remainder bounds, and range reduction. Second, among all directions of length 1 that dot product is largest along the gradient, so is the direction of steepest descent, which gradient descent exploits. Note that a gradient is only defined for a scalar . The derivative of a vector-valued function is a matrix, the Jacobian, which is the subject of the next section.
Central differences, one coordinate at a time
Section titled “Central differences, one coordinate at a time”The numerical gradient follows directly from the definition. For each input and each element ,
This is central_diff applied to the one-variable function at , with step . That is exactly how numerical_grad is written: it never re-derives the formula, it calls central_diff. The error analysis carries over too. Truncation error is and rounding error about ; with and values of size 1, both are near , comfortably under the tolerances you will see shortly. On a quadratic, with gradient , the third derivative is zero and the numerical gradient is exact up to rounding.
Three details decide whether this is trustworthy. Copies: perturb float64 copies of the inputs, never the caller’s arrays, because those are the model’s parameters. Restore: put each element back before moving to the next, or every later partial derivative is taken at the wrong point. Promote: an integer array cannot hold (it rounds back to , and the gradient comes out 0), and float32 moves only in steps of about , so the step actually taken is not .
The cost is evaluations of for input elements. That is fine for tests on small inputs and hopeless for training, which is why backpropagation exists.
When is a gradient right?
Section titled “When is a gradient right?”Having a numerical gradient, you need a rule for when an analytic gradient agrees with it. Compare elementwise, with a mixed test:
Near zero the absolute term dominates: with atol , a numerical gradient of is indistinguishable from 0. For large gradients the relative term does: gives an allowance of at . Each pure test fails somewhere. A pure relative test would reject a correct analytic 0 against a numerical . A pure absolute test would accept a gradient of 100 that is off by 0.5 percent at a loose atol, or reject a correct one at a tight atol.
A NaN in either gradient must fail. Every comparison with NaN is false, so the natural diff > tol would let it pass; test not (diff <= tol) instead.
The report says ok, the largest absolute error, the largest relative error , and where to look: the input and multi-index of the element whose error is the largest multiple of its own allowance. That is not the same as the largest absolute error. An error of on a gradient of 1000 is within tolerance; an error of on a gradient of is a bug.
Working it by hand
Section titled “Working it by hand”Take at , with the large step so the arithmetic is easy by hand. The gradient is . The table shows both perturbations for each element:
| Element | quotient | analytic | ||
|---|---|---|---|---|
| 4 | ||||
| 4 |
Both are exact even at : is quadratic in and linear in , so the central difference has no truncation error. Notice the restore at work: the row is evaluated at , not at the 0.9 left over from the row before. Now suppose a backward pass returned , losing a factor of 2 on . It fails at element 0, because .
Designing the interface
Section titled “Designing the interface”The whole module is one dataclass and two functions:
@dataclassclass GradcheckReport: ok: bool; max_abs_err: float; max_rel_err: float; worst_input: int; worst_index: tupledef numerical_grad(f, inputs: list[ArrayLike], eps: float = 1e-6) -> list[NDArray]: ...def gradcheck(f, inputs: list[ArrayLike], analytic: list[ArrayLike], eps: float = 1e-6, rtol: float = 1e-5, atol: float = 1e-7) -> GradcheckReport: ...numerical_grad returns one float64 array per input, in that input’s shape. gradcheck raises ValueError for mismatched lists or shapes, because those are bugs in the caller rather than numeric disagreements, and reports everything else. f must return a single number.
A correct solution has to handle a specific set of cases, each tied to something that matters downstream. They are compact enough to list in one table:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| Hand example | unit | the worked example: at , ok | pins the definition |
| Quadratics | property | numerical gradient of equals to | central differences are exact there |
| Matrix and several inputs | golden | of is and | layers have weights and inputs |
| Transposed gradient | unit | a transposed weight gradient is not ok, worst input 0 | the most common backward bug |
| Gradient off by 2 | unit | instead of is rejected, worst at the largest element, relative error 0.5 | a lost factor keeps every sign right |
| One zeroed element | unit | one zeroed element of the second input is found at | the report says where to look |
| Mixed tolerance | boundary | the mixed test at gradients and 100 | both regimes of the tolerance |
| Worst element | unit | the worst element is the one furthest past its allowance | not the largest absolute error |
| NaN gradient | boundary | a NaN analytic gradient is not ok | NaN comparisons are always false |
| Caller’s arrays | unit | they come back bit for bit | they are the model’s parameters |
| Integer and float32 inputs | boundary | exact gradients; sees float64 | steps survive the dtype |
| Defaults | unit | step , rtol , atol | what the op library relies on |
| Mismatched arguments | boundary | wrong counts and shapes raise ValueError | caller bugs are not numeric errors |
| Non-scalar | boundary | a vector-valued raises; a 1-element array is fine | gradients are for scalars |
Building it step by step
Section titled “Building it step by step”The design falls out of the principles above in six steps, and it is worth predicting each one before reading it.
- A partial derivative is a one-variable derivative with everything else frozen. So the numerical gradient is
central_diffapplied to a one-variable function that writes into one element and calls : no new difference formula, just a loop over elements. - The loop must not touch the caller’s arrays and must take steps that are representable, which forces float64 copies made once at the start.
- Each element is perturbed in place in the copy, and must be restored before the next one, even if raises. A
try/finallyguarantees that. - Iterating over a flat view (
reshape(-1)of a contiguous copy) visits every element of any shape, and writing into a flat view of a zero array of the same shape produces the gradient already in the input’s shape. - The comparison is elementwise. To make NaN fail, the code tests the negation of “passes” rather than “exceeds”.
- The location to report is the element with the largest ratio of error to allowance, across all inputs, with ties going to the first in row-major order and the first input.
Here are the scalar guard and the numerical gradient:
def _scalar(v) -> float: a = np.asarray(v) if a.size != 1: # a 1-element array is accepted; a vector is a caller bug raise ValueError(f"f must return one number, got an array of shape {a.shape}") return float(a.reshape(()))
def numerical_grad(f, inputs, eps=1e-6): if len(inputs) == 0: raise ValueError("inputs is empty: there is nothing to differentiate") if not (math.isfinite(eps) and eps > 0): raise ValueError(f"eps must be finite and > 0, got {eps}") # Private float64 copies: an int array would round x + eps back to x, and # float32 would round it to the nearest 6e-8 * |x|. xs = [np.array(x, dtype=np.float64, copy=True) for x in inputs] grads = [] for k, x in enumerate(xs): # every input, not just the first g = np.zeros_like(x) flat, gflat = x.reshape(-1), g.reshape(-1) # views into x and g for i in range(flat.size): orig = flat[i]
def along(t: float, i: int = i) -> float: flat[i] = t # writes through the view into xs[k] return _scalar(f(*xs)) # f sees all inputs, one element moved
try: gflat[i] = central_diff(along, orig, eps) finally: flat[i] = orig # restore before the next coordinate grads.append(g) return gradscentral_diff evaluates along(x + eps) and along(x - eps) and divides by (x + eps) - (x - eps), the step actually representable in float64, rather than by . On the worked example it returns for both elements.
gradcheck validates the shapes, computes the numerical gradient once, and then folds each input’s comparison into the report:
num = numerical_grad(f, inputs, eps) ok, max_abs, max_rel = True, 0.0, 0.0 worst = (-1.0, 0, tuple(0 for _ in num[0].shape)) for k, (a, n) in enumerate(zip(ana, num)): if a.size == 0: continue with np.errstate(divide="ignore", invalid="ignore"): diff = np.abs(a - n) # A nan never passes: compare the negation, since nan <= x is False. # One failing element anywhere makes the whole check fail. ok = ok and not (~(diff <= atol + rtol * np.abs(n))).any() diff = np.where(np.isnan(diff), np.inf, diff) # a nan is the worst error max_abs = max(max_abs, float(diff.max())) rel = diff / np.maximum( np.abs(n), atol if atol > 0 else np.finfo(float).tiny ) max_rel = max(max_rel, float(rel.max())) # How far each element is past its own allowance (> 1 fails). ratio = np.where(diff == 0, 0.0, diff / (atol + rtol * np.abs(n))) i = int(np.argmax(ratio)) # first maximum in row-major order if ratio.reshape(-1)[i] > worst[0]: # strict: earlier inputs win ties worst = ( float(ratio.reshape(-1)[i]), k, tuple(int(j) for j in np.unravel_index(i, a.shape)), )The report then carries ok, the two maxima, and worst_input, worst_index. The full solution is in gradcheck.py.
Why this design
Section titled “Why this design”The cost is evaluations of for input elements and extra memory for the copies and gradients. That is the price of checking every element, and it is acceptable because checks run on small inputs.
Central rather than forward differences is not a matter of taste. A forward difference has error , about at the default step, which is above atol and would make correct gradients fail. Central differences have error and are exact on quadratics.
The worst element is ranked by its ratio to the allowance because that ratio is what decides pass or fail, so the element with the largest ratio is the one a person should look at. The largest absolute error is often a correct large gradient.
You could instead check for random , which costs 2 evaluations instead of , but it cannot say which element is wrong. Element-by-element is the right default for debugging backward rules; the directional form appears under further reading below.
One tradeoff is accepted deliberately: the atol floor makes a gradient of indistinguishable from 0. Below the finite-difference noise, the comparison has no information.
What can go wrong
Section titled “What can go wrong”Most bugs in a gradient checker make it too lenient, which is the worst failure mode a referee can have. The common ones, and how the solution avoids each, are these:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
combining the per-element verdicts wrongly (all instead of any) | a transposed or partly zeroed gradient is reported ok | ok is false as soon as any element of any input fails |
| not restoring an element before the next one | every later partial derivative is taken at a shifted point | restores flat[i] = orig in a finally (step 3) |
| perturbing the caller’s arrays in place | the model’s weights change during a check | perturbs private copies xs |
| perturbing in the caller’s dtype | gradient 0 for int inputs; two digits for float32 | copies with dtype=np.float64 (step 2) |
diff > tol as the failure test | a NaN gradient passes | tests ~(diff <= tol) (step 5) |
| a one-sided difference per coordinate | errors near instead of ; quadratics no longer exact | calls central_diff |
| dividing by (the versus confusion) | every numerical gradient halved | lets central_diff divide by the actual step xp - xm |
| differentiating or comparing only the first input | the input gradient is never checked | loops over every input in both functions |
| reporting the largest absolute error as the worst | the report points at a correct large gradient | ranks by diff / (atol + rtol * abs(n)) (step 6) |
Warning: The NaN case is the easiest to miss because the buggy test looks correct.
diff > tolreads as “fails when too large”, but a NaN is never larger than anything, so a backward pass that produces NaN would sail through.
Where this leads
Section titled “Where this leads”This section looks back to Derivatives and Finite Differences: numerical_grad calls central_diff(along, x_i, eps) for every element. Looking forward, Jacobians, the multivariable chain rule, and numeric JVP/VJP builds vjp_numeric(f, x, u) as numerical_grad of the scalar . In AI Engineering, The op library and gradcheck_all uses F.gradcheck_all() to check every op’s backward with this gradcheck, behind the system’s {tinyllm} gradcheck --suite all command, and the model test suites from Encoder-decoder with teacher forcing through Llama-family model gradcheck every new backward rule. Back in this book, gradient descent steps along .
Further reading
Section titled “Further reading”- PyTorch
torch.autograd.gradcheckandgradgradcheck(torch/autograd/gradcheck.py): the production equivalent ofgradcheck, adding complex inputs, sparse and batched layouts, second derivatives, and a fast mode (fast_mode=True) that checks random projections instead of every element, at 2 evaluations per random pair instead of . The next section builds the pieces. - JAX
jax.test_util.check_grads(jax/_src/public_test_util.py): checks forward and reverse mode up to a chosen order. numpy.isclose(numpy/_core/numeric.py): the same mixed testatol + rtol * abs(n), with the same asymmetry (relative to the second argument).- OpenStax, Calculus Volume 3 (free), sections 4.3 and 4.6 on partial derivatives and the gradient.
- Nocedal and Wright, Numerical Optimization, section 8.1, on finite-difference gradients.
- The PyTorch autograd notes on
gradcheck.
Key terms
Section titled “Key terms”- Partial derivative: the ordinary derivative of along one coordinate with every other coordinate frozen.
- Gradient: the collection of all partial derivatives of a scalar function, one per input element, arranged in the input’s shape.
- Numerical gradient: an approximation of the gradient by one central difference per element, costing evaluations of .
- Mixed tolerance: the pass rule , absolute near zero and relative for large values.
- Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance.
Summary
Section titled “Summary”- A partial derivative is an ordinary derivative along one coordinate with every other coordinate frozen; the gradient collects one per input element, in the input’s shape.
- A numerical gradient is one central difference per element, evaluations of for elements, exact on quadratics.
- An element passes when : absolute near zero, relative for large gradients.
gradcheckmust reject the bugs backward passes really have (a transposed gradient, a factor of 2, one forgotten element, a NaN) and point at the element furthest past its tolerance.- It perturbs float64 copies, so the caller’s parameters are untouched and integer or float32 inputs still get exact steps.
Review questions
Section titled “Review questions”-
Why does
numerical_gradcopy the inputs to float64 instead of perturbing them in their own dtype?Answer
Two reasons. The caller’s arrays are model parameters and must not change. And an integer array cannot hold , while float32 moves only in steps of about , so the step actually taken would be 0 or far from .
-
What goes wrong without the
finally: flat[i] = orig?Answer
After element , the copy would hold (the last value
central_diffwrote). Every later partial derivative would then be taken at a shifted point; in the worked example the row would be evaluated at . -
Why is
okcomputed asnot (~(diff <= tol)).any()and notnot (diff > tol).any()?Answer
Every comparison with NaN is false.
diff > tolis false for a NaN, so a NaN gradient would count as passing.diff <= tolis also false for a NaN, so its negation is true and the check fails, as it should. -
An element has , ; another has , . Which is reported as worst?
Answer
The second. The first has allowance and error , ratio about 0.5 (passes). The second has allowance about and error , ratio about 1800.
-
Why would forward differences make correct gradients fail at the default tolerances?
Answer
A forward difference has truncation error , about at , which exceeds atol for small gradients. Central differences have error , near after rounding, well inside the tolerance.