advanced27 min studyLesson 519 in Engineering

Transform the derivative graph with shapes and saved values intact

Read reverse-mode tensor IR as a shape-aware program transformation, preserving cotangent accumulation, broadcasts, residuals, and effects.

On this page

What you’ll understand

  • Derive matrix-product cotangent shapes and the reduction required by bias broadcasting.
  • Identify primal values that a reverse program must preserve or recompute correctly.
  • Separate a correct derivative transform from an optimized or numerically identical lowering.

Automatic differentiation can be implemented as a transformation of an intermediate program, not merely a symbolic formula attached to its final output. The transform introduces tangent or cotangent values, saved primal residuals, reductions, and accumulations. Those new operations must obey tensor shape and effect contracts just like the original graph. A derivative expression with the right-looking symbols can still be wrong if it forgets a broadcast reduction, loses an old value through mutation, or recomputes a stateful operation with different behavior.

Derive the reverse program from each operation's contract

Consider Y=XW plus a row-broadcast bias, where X has shape [B,K], W [K,M], and b [M]. An incoming cotangent G has shape [B,M], matching Y. The matrix-product rule yields an X cotangent of shape [B,K] and a W cotangent of shape [K,M]. The bias contribution must sum G over the broadcast batch dimension to return shape [M]. Simply passing the entire [B,M] G as the bias gradient violates the input's shape contract.

If an input feeds multiple downstream uses, its cotangent contributions must accumulate rather than overwrite each other. For a scalar loss x²+x, both the square path and the direct path contribute to the same input. In an SSA reverse program, each accumulation can have its own result value, while buffer lowering may implement it with an update only when alias and scheduling analysis permit that. The mathematical derivative rule and its storage implementation remain separate correctness obligations.

X‾=GWT,W‾=XTG,b‾j=∑i=1BGij\overline X=GW^{\mathsf T},\qquad \overline W=X^{\mathsf T}G,\qquad \overline b_j=\sum_{i=1}^{B}G_{ij}
This ideal real-valued VJP assumes Y=XW+row-broadcast(b), positive integer dimensions, and an incoming cotangent G of shape [B,M]. Bars denote cotangents of a scalar objective. Floating-point accumulation order and the framework's derivative conventions are additional parts of the numerical contract.↔ Scroll wide equations horizontally.

Saved primal values are dependencies of the reverse program

The W cotangent needs X, and the X cotangent needs W. If a forward operation later mutates storage that held one of these values, the reverse transform cannot silently use the changed contents in place of the required primal. It must preserve the relevant old value, choose a valid recomputation, or reject an unsupported mutation pattern. Shape metadata alone will not expose this error: the stale and correct residuals can have identical shapes while producing different derivatives.

Recomputation also interacts with effects. Repeating a pure deterministic subexpression can reconstruct a residual under its declared numerical contract; repeating a random draw without the corresponding state or key discipline may produce a different value. Repeating I/O can duplicate effects. JAX's documented JVP and VJP transforms make the linear-map direction explicit, while supported custom rules add their own contracts. A custom backward rule that returns the right shape but the wrong linear map is not repaired by successful compilation.

f(x)=x2+x,x‾=(2x+1)y‾f(x)=x^2+x,\qquad \overline x=(2x+1)\overline y
This scalar real-valued example assumes ordinary differentiability and an incoming scalar cotangent y-bar. It shows addition of two path contributions. It does not claim that the derivative of discrete rounded execution is the same mathematical object as the framework's standard floating-point AD convention.↔ Scroll wide equations horizontally.

Validate both the transformed program and its lowering

Check derivative shapes first, then use small exact examples, adjoint checks, or suitable finite-difference comparisons within a declared smooth domain. Test nontrivial incoming cotangents instead of always ones, since some incorrect transpose or reduction rules can accidentally agree under uniform seeds. Separately test supported aliasing, branches, and state. An IR verifier establishes structural properties; a numerical comparison gives evidence for tested cases. Neither automatically proves every custom rule, shape family, or backend lowering correct.

The network lab supplies one sigmoid primal expression for a hand-derived reverse rule. Reset, set both x=1,w=2, predict logit 1.5 and output about 0.8176, then Play or Step. Derive the sigmoid factor y(1−y), then multiply by w or x for the respective cotangent with seed one. Reset and set both x=1,w=1 for comparison. The instrument displays the primal network, not an AD tape, saved-tensor analysis, or a compiler-generated backward graph.

Check a matrix-product reverse graph

Use X=[[1,2],[3,4]], W=[[2],[−1]], scalar bias b=0 broadcast to two rows, and loss equal to the sum of all Y=XW+b entries. Treat these as exact real-valued calculations; all dimensions are explicit.

  1. Compute the primal Y=[[1×2+2×(−1)],[3×2+4×(−1)]]=[[0],[2]]. The loss is two, and its incoming Y cotangent is G=[[1],[1]].

  2. Compute X-bar=GWᵀ=[[2,−1],[2,−1]], with the same [2,2] shape as X. Compute W-bar=XᵀG=[[4],[6]], with shape [2,1].

  3. Reduce the broadcast bias contribution over the two rows: b-bar=1+1=2. Returning G itself for the bias would have the wrong shape and would omit the required accumulation.

The result

The reverse program returns cotangents [[2,−1],[2,−1]], [[4],[6]], and scalar two. The bias reduction and preserved primal inputs are explicit analysis obligations.

Explore the model

Interactive lab

Interactive lab · network

Derive cotangents from a displayed primal

Reset → set both x=1,w=2; predict y≈0.8176, y(1−y)≈0.1491, input cotangent ≈0.2983 and weight cotangent ≈0.1491 for seed one. Play or Step, then compare fresh x=1,w=1. This scalar display does not execute AD or compiler analysis.

Derive cotangents from a displayed primalOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. 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 forAn AD transform introduces shape, accumulation, residual, and effect obligations beyond the primal output.

Check your understanding

A [B,M] result adds a bias shaped [M] by broadcasting across rows. Given result cotangent G shaped [B,M], what is the bias cotangent?

Try it yourself

For f(x)=x²+x at x=3 with incoming cotangent y-bar=2, compute the input cotangent. A buggy reverse pass retains only the square path. What value does it return, and which missing graph feature explains the difference?

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

Give me a hint

The square and direct uses contribute separately to the same input; multiply their sum by the incoming cotangent.

Compare with the solution

The correct derivative factor is 2×3+1=7, so x-bar=7×2=14. Keeping only the square contribution gives 2×3×2=12. The missing two is the direct path's contribution, showing why cotangent accumulation across multiple uses is necessary. This is a graph-transformation error even though the result has the correct scalar shape and could pass a structural verifier.

Take it with you

  • Reverse tensor programs must preserve cotangent shapes and broadcast reductions.
  • Saved primal values, aliasing, and effects constrain valid recomputation.
  • Structural verification and targeted derivative checks supply different kinds of evidence.

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.