advanced26 min studyLesson 507 in Engineering

Differentiating a derivative needs its own graph

Calculate a Hessian-vector product, distinguish derivative-graph construction from retaining saved context, and state smoothness and custom-rule limitations.

On this page

What you’ll understand

  • Calculate the shape and value of a real Hessian-vector product.
  • Distinguish create_graph from retain_graph in PyTorch 2.9.
  • Explain why a higher-order transformation needs valid derivative dependencies and smoothness assumptions.

A gradient is itself a function of the input. Differentiating it asks for another transformation, with another set of dependencies and shapes. Keeping an old forward graph available is not automatically the same as recording the operations that produced the first derivative. Follow a small Hessian-vector product to separate these ideas before using higher-order flags as a general solution to memory or graph-lifetime errors.

A gradient has a Jacobian too

For a twice-differentiable scalar f:R^n→R, its gradient has n components and its Hessian is n×n. A Hessian-vector product H_f(x)v returns n components without requiring every Hessian entry to be materialized. It can be expressed as a JVP of the gradient in a fixed direction. A reverse derivative of the scalar gradient-dot-direction can also produce an adjoint product, with symmetry requiring the appropriate smoothness conditions. State whether v is fixed; differentiating a direction that depends on x adds another term.

A vector-valued original function has a higher-rank second derivative rather than one automatically canonical Hessian. Selecting an output cotangent first defines a scalar combination and therefore a particular Hessian question. The same shape discipline used for first-order JVPs and VJPs still applies. At nonsmooth boundaries, a framework can differentiate its chosen local rules without producing a classical second derivative of the original map. An apparently symmetric numerical matrix is evidence about those calculations, not a proof that the mathematical smoothness assumptions hold everywhere.

Hf(x)v=D(∇f)(x)[v],f:Rn→R,v∈RnH_f(x)v=D(\nabla f)(x)[v],\qquad f:\mathbb R^n\to\mathbb R,\quad v\in\mathbb R^n
This real dimensionless formula assumes a differentiable gradient at x and a fixed seed v. The result has n components. It does not assert existence of a Hessian at a kink or define one Hessian for an unseeded vector-valued output.↔ Scroll wide equations horizontally.

Two runtime flags preserve different information

PyTorch 2.9's create_graph option requests construction of a differentiable graph for derivative computations, enabling supported higher-order work. retain_graph controls freeing the graph resources used for that traversal. Retaining a first-order graph alone does not record the derivative operations as a new differentiable graph. The defaults and interactions belong to the documented API, but their purposes remain distinct. A repeated first-order backward, a derivative of the first gradient, and several independent loss evaluations have different schedules; choose the mechanism for the requested computation.

Custom rules can break higher-order dependencies by saving an intermediate in a form whose relationship to inputs is absent from the derivative graph or by detaching required values. PyTorch's custom-function guidance requires declaring unsupported double backward explicitly. More retention cannot repair a mathematically wrong rule or recreate a dependency deliberately removed from the graph. Memory also grows with the nested computation and live residuals, so a higher-order calculation needs its own budget. Validate a small analytic example before scaling to a large model whose failure is harder to localize.

f(x,y)=x2y+y3,Hf(x,y)=(2y2x2x6y)f(x,y)=x^2y+y^3,\qquad H_f(x,y)=\begin{pmatrix}2y&2x\\2x&6y\end{pmatrix}
This smooth real polynomial has dimensionless inputs and output. Its explicit 2×2 Hessian is symmetric; the example's symmetry follows from smoothness, not from a runtime flag or a universal property of arbitrary surrogate rules.↔ Scroll wide equations horizontally.

Verify the second-order target independently

Compare a hand-computed product with a directional difference of first derivatives at valid smooth points, using a scale range rather than one perturbation. Check the shape of the first gradient, seed, and returned product separately. If a result is unexpectedly constant or detached, inspect derivative graph connectivity before changing retention settings. For custom rules, test supported nested transformations explicitly. A first-order gradcheck does not establish every second-order path, and a passing symmetry check can miss a consistently wrong symmetric Hessian.

The function lab provides analytic curvature only for y=ax². Reset, explicitly set BOTH a=1 and x=0.5, predict slope one and paper curvature two, then Play or Step. Reset and re-set BOTH a=2 and x=0.5; predict slope two and curvature four. Edits retain t; playback traces the chosen curve and does not run a higher-order derivative graph. The display contains no create_graph or retain_graph behavior. Use the scalar formula to inspect one curvature claim while the worked two-variable calculation establishes the shaped product.

Multiply a two-variable Hessian without losing its shape

For f(x,y)=x²y+y³ at (1,2), use the fixed direction v=(1,−1). Calculate the first gradient and Hessian-vector product.

  1. The gradient is (2xy,x²+3y²), giving (4,13) at (1,2). This is an input-shaped two-vector.

  2. The Hessian is [[4,2],[2,12]]. Multiplying by (1,−1) gives (4−2,2−12)=(2,−10).

  3. The result is a directional change of the gradient, not a second scalar loss value. A runtime needs the supported graph of derivative operations to recover this dependency, not merely permission to reuse old saved tensors.

The result

The Hessian-vector product is (2,−10), while the first gradient is (4,13). Their different meanings survive even though both have two entries.

Explore the model

Interactive lab

Interactive lab · function

Curvature in one supported analytic family

For EACH run Reset, set BOTH a and x, predict, then Play or Step. At x=0.5 compare a=1 and a=2: slopes one and two; analytic curvatures 2a are two and four. Edits retain t. The quadratic instrument does not construct derivative graphs, manage saved contexts, or compute arbitrary Hessians.

Curvature in one supported analytic familyThis 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 higher-order target differentiates the derivative map; retaining earlier runtime resources is a separate concern.

Check your understanding

What does retain_graph alone fail to guarantee for a requested second derivative?

Try it yourself

For f(x,y)=x²+3y², give the Hessian and its product with v=(2,−1). Does knowing the Hessian is constant make retain_graph and create_graph identical options?

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

Give me a hint

Differentiate the gradient (2x,6y), then distinguish mathematical constancy from the runtime options' contracts.

Compare with the solution

The Hessian is [[2,0],[0,6]], so the product is (4,−6). The constant answer does not make the options equivalent: recording derivative dependencies and preserving saved traversal resources remain different runtime purposes, even when this analytic example is simple.

Take it with you

  • A Hessian-vector product is a shaped derivative of a gradient map.
  • Derivative-graph construction and graph-resource retention have different roles.
  • Smoothness, custom-rule support, and independent checks still matter at higher order.

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.