advanced26 min studyLesson 506 in Engineering

The executed branch has a derivative only under local path assumptions

Trace conditional and loop differentiation, distinguish piecewise derivatives from boundary conventions, and avoid undefined operations hidden behind a later mask.

On this page

What you’ll understand

  • Calculate a derivative on a locally stable executed branch.
  • Explain why a branch boundary may lack a classical derivative.
  • Distinguish differentiating executed iterations from differentiating a convergence limit.

Programs contain decisions and loops, so their local derivative depends on what execution means near the current input. Away from a branch boundary, the chosen path can represent a smooth function in a neighborhood. At a boundary, an apparently ordinary backward value may be only the selected branch's convention. Loops add another question: are we differentiating a fixed sequence of updates, the executed stopping rule, or an ideal solution the iterations approximate?

A path can be smooth while the whole piecewise map is not

Consider f(x)=x² for x≥0 and f(x)=−x for x<0. At positive x the local derivative is 2x; at negative x it is −1. At zero the left and right derivatives differ, so the full map has no ordinary derivative there. Executing the nonnegative branch can still produce a branch-rule sensitivity of zero under an implementation's convention. That returned number does not prove differentiability. A finite perturbation that crosses the boundary can observe a different path and should not be interpreted using only the original branch's local Taylor rule.

PyTorch 2.9 records the graph of executed operations and recreates it each iteration, allowing ordinary dynamic control flow within its supported operations. Compiled transformations can impose different restrictions on Python decisions or loop primitives, so inspect the pinned runtime's rules. The predicate is not generally differentiated as if a Boolean comparison were a smooth arithmetic function. At a locally constant predicate, differentiating the active branch can be correct; at a switching boundary or discontinuity, a separate mathematical or surrogate convention is necessary.

f(x)={x2x≥0−xx<0,f′(x)={2xx>0−1x<0f(x)=\begin{cases}x^2&x\geq0\\-x&x<0\end{cases},\qquad f'(x)=\begin{cases}2x&x>0\\-1&x<0\end{cases}
All values are real and dimensionless. The derivative expression deliberately excludes zero, where the left derivative −1 and right derivative zero disagree. A framework's branch convention at zero is not a classical derivative of this map.↔ Scroll wide equations horizontally.

A loop's derivative target must be explicit

For a fixed number of differentiable iterations, chain the derivative of each update. The intermediate states and their tangent or cotangent dependencies form the actual computation. If an input-dependent stopping condition changes the iteration count, nearby inputs can follow a different trace. A runtime that differentiates the executed trace does not automatically differentiate the discrete change in iteration count. The derivative of a converged mathematical solution, when it exists, can require an implicit-differentiation argument rather than simply calling a fixed iteration's derivative the solution's sensitivity.

Stateful effects inside loops add the same replay and mutation obligations as elsewhere. A random draw, external lookup, or global update can change the computation during rematerialization. A mask applied after division by zero can leave invalid operations in the differentiated graph; hiding their forward outputs does not necessarily remove NaN gradients. Arrange valid-domain computation before the undefined operation, using supported selection and indexing semantics, rather than relying on multiplication by zero afterward. Test both branches and their boundary neighborhoods, not only one convenient successful path.

y0=1,yk+1=xyk (k=0,1,2),y3=x3,dy3dx=3x2y_0=1,\quad y_{k+1}=xy_k\ (k=0,1,2),\qquad y_3=x^3,\quad\frac{dy_3}{dx}=3x^2
This real dimensionless loop has exactly three fixed iterations. Its derivative does not describe an arbitrary data-dependent stopping rule or a limit as iteration count tends to infinity.↔ Scroll wide equations horizontally.

A boundary check should name what failed

Check a branch-sensitive program at smooth interior points, then separately characterize boundaries and invalid inputs. A gradient check at a kink can disagree even if the runtime follows its declared convention correctly; conversely, one passing interior check says nothing about the other branch. Record which mathematical target a test validates. For iterative solvers, compare several tolerances and iteration counts against a trusted target while measuring both residual and derivative error. A small primal residual alone need not prove that an unrolled derivative approximates the desired solution derivative accurately.

The quadratic lab displays only the smooth x² branch family. Reset, explicitly set BOTH a=1 and x=1, predict slope two, then Play or Step. Reset and re-set BOTH a=1 and x=0; its analytic slope is zero. Edits retain t and the animation traces a fixed quadratic. The instrument has no conditional or stopping predicate, so its zero slope cannot certify differentiability of the piecewise f at zero. Compute the left-branch derivative −1 on paper and explain why the mismatch, rather than the smooth lab picture, determines the boundary conclusion.

Differentiate the branch that is locally stable

Use the piecewise f(x)=x² for x≥0 and −x for x<0. Compare x=2, x=−2, and the boundary x=0; then consider the fixed three-iteration multiplication loop at x=2.

  1. At x=2, f=4 and derivative is four. At x=−2, f=2 and derivative is minus one because small enough perturbations keep that branch active.

  2. At zero, the function is continuous but its one-sided derivatives are −1 and zero, so there is no ordinary derivative. A returned active-branch value would need its convention stated.

  3. The fixed loop gives y3=2³=8 and derivative 3×2²=12. That result uses exactly three iterations and does not analyze what an input-dependent stopping rule might do.

The result

Interior branch derivatives, a boundary convention, and a fixed unrolled loop answer different derivative questions.

Explore the model

Interactive lab

Interactive lab · function

A smooth branch does not prove a piecewise boundary

For EACH run Reset, set BOTH a and x, predict, then Play or Step. Compare (1,1), slope two, with (1,0), slope zero. Edits retain t. This instrument plots only y=ax²: it has no alternate branch, mask, loop, or stopping condition and cannot establish the piecewise function's derivative at zero.

A smooth branch does not prove a piecewise boundaryThis 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 local branch derivative must not be mistaken for differentiability across a switching boundary.

Check your understanding

A runtime returns zero from the nonnegative branch of the stated piecewise function at x=0. What follows?

Try it yourself

A fixed loop starts y0=1 and applies y←xy four times. Give its output and derivative at x=2. Why does this not automatically give the derivative of a loop that stops whenever y first exceeds a threshold?

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 fixed count produces a polynomial; a stopping rule can change the count as the input changes.

Compare with the solution

The fixed output is x⁴=16 and derivative 4x³=32 at two. A threshold loop can execute a different number of updates for nearby x, creating another piecewise program with switching boundaries. Its derivative target and stopping behavior must be analyzed separately.

Take it with you

  • Executed-path differentiation needs locally valid smooth operations.
  • Branch and stopping boundaries can require explicit nonclassical conventions.
  • Differentiating fixed iterations is different from differentiating a mathematical solution limit.

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.