advanced26 min studyLesson 504 in Engineering

A custom rule must be a compatible linear derivative map

Specify primal domains, tangent and cotangent shapes, seed linearity, higher-order support, and explicit surrogate conventions before overriding differentiation.

On this page

What you’ll understand

  • Test a derivative rule's linearity in its seed at fixed primal input.
  • Separate a true derivative from a declared surrogate or boundary convention.
  • Explain why first-order correctness does not automatically establish higher-order support.

Custom derivatives let a runtime differentiate an operation whose implementation it cannot inspect or whose stable derivative needs special treatment. The replacement is a mathematical and runtime contract. It must agree with the primal function where a true derivative is claimed, preserve shapes and seed linearity, and state what happens at invalid or nonsmooth inputs. A function named backward is not enough to establish any of those properties.

Specify the primal function and its valid derivative domain

Start with the real-valued primal map, input and output shapes, dtype assumptions, and the domain where it is differentiable. A square root has a different derivative domain from a polynomial, while an approximate iterative solver can represent either its executed iterations or a separately defined implicit solution map. Those are different mathematical targets. A stable analytic rule can avoid an unstable implementation path without changing the derivative target, but a clipped or straight-through sensitivity generally defines a surrogate and should be labeled as such rather than presented as the ordinary derivative.

A custom JVP accepts an input tangent and returns an output tangent; a custom reverse rule accepts output cotangents and returns compatible input cotangents. Required residuals must correspond to the same forward evaluation. PyTorch 2.9's custom Function guidance describes saved context, mutation marking, and explicit double-backward support. JAX's pinned autodiff documentation likewise treats derivative transformations as composable operations. Framework conventions differ, so distinguish mathematical requirements from the selected version's registration and transform-support rules. Avoid assuming a custom backward automatically supports forward-mode transformations or every higher-order composition.

f(x)=x3,Tx(v)=3x2v(x,v∈R)f(x)=x^3,\qquad T_x(v)=3x^2v\quad(x,v\in\mathbb R)
This is a true JVP for a real dimensionless cubic on all real inputs. At fixed x it is linear in tangent v; changing x changes the derivative map. A custom surrogate would need a different explicit interpretation.↔ Scroll wide equations horizontally.

Linearity is necessary but not sufficient

At a fixed differentiable input, derivative propagation must be linear in the incoming seed. A rule that squares a tangent or clips an output cotangent violates that requirement unless the operation being defined is explicitly another non-derivative procedure. Zero, sum, and scaled-seed checks can expose such errors cheaply. Passing them still does not prove the derivative is correct: multiplying every tangent by the wrong constant is linear too. Combine algebraic contracts with hand-derived examples and independent numerical directional checks on valid smooth inputs.

Boundary conventions require equal care. A framework may select a particular subgradient for a nonsmooth primitive, but that does not make the original function classically differentiable there. Invalid-domain forward operations can also produce undefined gradients even if a later mask hides their output. A custom rule should not silently invent physical meaning for NaN or out-of-domain values. State whether unsupported inputs raise an error, propagate an invalid result, or use a declared approximation, and verify that the convention composes as intended with batching and higher-order derivatives.

Tx(αv+βw)=αTx(v)+βTx(w),Tx(0)=0T_x(\alpha v+\beta w)=\alpha T_x(v)+\beta T_x(w),\qquad T_x(0)=0
These are necessary real-linear seed conditions for a derivative at fixed x, with matching tangent shapes. They do not prove agreement with the primal function or establish a derivative at a nonsmooth or invalid-domain point.↔ Scroll wide equations horizontally.

Test composition, not only one backward result

Test several inputs, seeds, scales, shapes, and degenerate cases allowed by the contract. Check accumulation through repeated uses and whether saved intermediates preserve the graph dependencies needed for a second derivative. If higher-order support is absent, reject it explicitly rather than returning a plausible constant by accident. A rule can be correct for one scalar seed of one and fail when the output is batched or weighted. Keep versioned tests around the actual public transformation combinations the application uses, including any limitations on sparse layouts or mutation.

The quadratic lab supplies a true analytic rule to compare against. Reset, set BOTH a=1 and x=1, predict slope two, then Play or Step. Reset and re-set BOTH a=2 and x=1; predict slope four. For either fixed input, compute two-seed linearity on paper using slope times v. Edits retain t; playback traces y=ax² and does not install a custom rule or run a checker. A correct demonstration for this scalar family does not validate a cubic, solver, boundary convention, or arbitrary custom kernel.

A rule can pass seed one and still violate the derivative contract

At x=2 for f(x)=x³, compare the correct tangent rule 12v with an incorrect rule 12v². Use seeds one, two, and their sum three.

  1. The correct outputs are 12,24,36, and 12+24=36, so additivity holds for these seeds.

  2. The incorrect outputs are 12,48,108. Although seed one matches, 12+48=60 differs from the result 108 for seed three.

  3. The squared-seed rule is nonlinear in v and cannot be this derivative map. Even a linear alternative would still need agreement with the primal function, not just this additivity test.

The result

Testing only a scalar backward seed of one would miss this error. Seed linearity and primal agreement are separate requirements.

Explore the model

Interactive lab

Interactive lab · function

A known analytic rule for seed checks

For EACH run Reset, set BOTH a and x, predict, then Play or Step. Compare (1,1), slope two, with (2,1), slope four; multiply each fixed slope by paper seeds. Edits retain t. The y=ax² instrument does not register custom derivatives, check seed linearity automatically, or differentiate another function.

A known analytic rule for seed checksThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA valid local derivative is linear in its seed, but a custom rule must also match the declared primal and supported transform contract.

Check your understanding

A custom JVP is linear in its seed but equals twice the true derivative at every smooth input. What has the linearity test established?

Try it yourself

For f(x)=sqrt(x) on x>0, give the JVP at x=4 with seed v=3. Explain why claiming the same finite formula at x=0 requires a separate domain or convention discussion.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Use 1/(2sqrt(x)) on the positive domain, then inspect the boundary rather than substituting blindly.

Compare with the solution

At x=4 the derivative is 1/4, so the JVP is 3/4. At zero this finite positive-domain formula is not a finite ordinary derivative; the domain boundary and singular slope need an explicit supported convention or rejection. A custom implementation must not hide that change in meaning.

Take it with you

  • A custom derivative needs an explicit primal, domain, shape, and transform contract.
  • Seed linearity is necessary and does not replace agreement with the function.
  • Surrogates, boundary conventions, and higher-order limitations must be stated and tested.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.