IV-07 / Part II · Learning, Backpropagation and Optimization
Reverse-Mode Chain Rule and Gradient Accumulation
Trace loss sensitivities backward, accumulate all three q contributions, and distinguish a row VJP from a column gradient.
Review the ideas this chapter uses
The forward calculation tells us the loss at the current inputs. To improve a model later, we also need to know how that loss responds to each parameter. Repeating a complete calculation for every possible tiny change would hide the useful structure already present in our graph.
Instead, start from loss and carry sensitivities backward through each operation. At a shared node, several contributions arrive. They must be added before anything travels farther upstream. This small bookkeeping rule is the heart of the example, including the case where nonzero contributions cancel.
Accumulate every path before moving upstream
These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.
Complete results from this trace’s starting inputs
Starting inputs for these results
- x
- 2
- w
- 0.5
- b
- 1
- y
- 1
loss 2. adjQ 6. adjW 12. adjX 3. Forward: shared product q. Store q once. Its value is read by three outgoing operand edges.. q 1
Forward: shared product q
q=w*x
Store q once. Its value is read by three outgoing operand edges.
Inputs
- w
- 0.5
- x
- 2
Outputs
- q
- 1
Reverse accumulation on the actual DAG
One stored q has three outgoing edges: r_q, s_left and s_right. Each line names an operand slot. The highlighted trace edge follows Calculation step; Inspect operand edge selects a separate edge to examine.
s_left: ds/dq_left=q_right; local factor = . Completed reverse contribution = 2; accumulator 2 → 4.
Graph adjoints are final totals, including steps beyond the current selection. Use the reverse table and selected trace outputs for intermediate accumulators.
| Node | Value | Final loss adjoint |
|---|---|---|
| w | ||
| x | ||
| q | ||
| b | ||
| r | ||
| s | ||
| prediction | ||
| y | ||
| error | ||
| loss |
| Edge / operand ID | Stored source → consumer | Partial derivative | Local factor |
|---|---|---|---|
| q_w | w → q | dq/dw=x | |
| q_x | x → q | dq/dx=w | |
| r_q | q → r | dr/dq=1 | |
| r_b | b → r | dr/db=1 | |
| s_left | q → s | ds/dq_left=q_right | |
| s_right | q → s | ds/dq_right=q_left | |
| prediction_r | r → prediction | dp/dr=1 | |
| prediction_s | s → prediction | dp/ds=1 | |
| error_prediction | prediction → error | de/dp=1 | |
| error_y | y → error | de/dy=-1 | |
| loss_error | error → loss | dL/de=error |
| Edge | Downstream adjoint | Local factor | Contribution | Accumulator before | Accumulator after |
|---|---|---|---|---|---|
| loss_error | 1 | 2 | 0 | ||
| error_prediction | 2 | 1 | 0 | ||
| error_y | 2 | -1 | 0 | ||
| prediction_r | 2 | 1 | 0 | ||
| prediction_s | 2 | 1 | 0 | ||
| r_b | 2 | 1 | 0 | ||
| r_q | 2 | 1 | 0 | ||
| s_left | 2 | 1 | 2 | ||
| s_right | 2 | 1 | 4 | ||
| q_w | 6 | 2 | 0 | ||
| q_x | 6 | 0.5 | 0 |
Row order is x,w,b,y. J:[1,4] = [3, 12, 2, -2]. Seed [1,1] times J gives the row VJP [1,4]; transpose it for the input gradient column [4,1]. Inspect inputJacobian, seedRow, vjpRow and inputGradient below.
Inspect tensor shapes and full precision
All computed outputs
- loss
- 2
- adjQ
- 6
- adjW
- 12
- adjX
- 3
- prediction
- 3
- q
- 1
- r
- 2
- s
- 1
- error
- 2
- errorSquare
- 4
- x
- 2
- w
- 0.5
- b
- 1
- y
- 1
- local_q_w
- 2
- local_q_x
- 0.5
- local_r_q
- 1
- local_r_b
- 1
- local_s_left
- 1
- local_s_right
- 1
- local_prediction_r
- 1
- local_prediction_s
- 1
- local_error_prediction
- 1
- local_error_y
- -1
- local_loss_error
- 2
- contribution_loss_error
- 2
- before_loss_error
- 0
- after_loss_error
- 2
- contribution_error_prediction
- 2
- before_error_prediction
- 0
- after_error_prediction
- 2
- contribution_error_y
- -2
- before_error_y
- 0
- after_error_y
- -2
- contribution_prediction_r
- 2
- before_prediction_r
- 0
- after_prediction_r
- 2
- contribution_prediction_s
- 2
- before_prediction_s
- 0
- after_prediction_s
- 2
- contribution_r_b
- 2
- before_r_b
- 0
- after_r_b
- 2
- contribution_r_q
- 2
- before_r_q
- 0
- after_r_q
- 2
- contribution_s_left
- 2
- before_s_left
- 2
- after_s_left
- 4
- contribution_s_right
- 2
- before_s_right
- 4
- after_s_right
- 6
- contribution_q_w
- 12
- before_q_w
- 0
- after_q_w
- 12
- contribution_q_x
- 3
- before_q_x
- 0
- after_q_x
- 3
- adjLoss
- 1
- adjError
- 2
- adjPrediction
- 2
- adjR
- 2
- adjS
- 2
- adjB
- 2
- adjY
- -2
- qFromR
- 2
- qFromSLeft
- 2
- qFromSRight
- 2
- qAfterR
- 2
- qAfterSLeft
- 4
- qAfterSRight
- 6
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
loss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: loss; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjQ
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjQ; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 6 |
adjW
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjW; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 12 |
adjX
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjX; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 3 |
prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: prediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 3 |
q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: q; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: r; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: s; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: error; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
errorSquare
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: errorSquare; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 4 |
x
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: x; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
w
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: w; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
b
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: b; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
y
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: y; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_q_w
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_q_w; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
local_q_x
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_q_x; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
local_r_q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_r_q; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_r_b
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_r_b; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_s_left
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_s_left; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_s_right
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_s_right; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_prediction_r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_prediction_r; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_prediction_s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_prediction_s; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_error_prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_error_prediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
local_error_y
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_error_y; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | -1 |
local_loss_error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_loss_error; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_loss_error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_loss_error; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_loss_error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_loss_error; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_loss_error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_loss_error; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_error_prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_error_prediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_error_prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_error_prediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_error_prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_error_prediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_error_y
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_error_y; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | -2 |
before_error_y
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_error_y; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_error_y
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_error_y; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | -2 |
contribution_prediction_r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_prediction_r; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_prediction_r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_prediction_r; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_prediction_r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_prediction_r; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_prediction_s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_prediction_s; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_prediction_s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_prediction_s; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_prediction_s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_prediction_s; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_r_b
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_r_b; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_r_b
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_r_b; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_r_b
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_r_b; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_r_q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_r_q; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_r_q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_r_q; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_r_q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_r_q; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
contribution_s_left
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_s_left; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_s_left
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_s_left; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
after_s_left
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_s_left; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 4 |
contribution_s_right
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_s_right; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
before_s_right
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_s_right; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 4 |
after_s_right
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_s_right; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 6 |
contribution_q_w
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_q_w; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 12 |
before_q_w
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_q_w; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_q_w
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_q_w; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 12 |
contribution_q_x
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: contribution_q_x; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 3 |
before_q_x
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: before_q_x; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 0 |
after_q_x
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: after_q_x; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 3 |
adjLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjLoss; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 1 |
adjError
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjError; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjPrediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjPrediction; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjR
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjR; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjS
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjS; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjB
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjB; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
adjY
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjY; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | -2 |
qFromR
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromR; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
qFromSLeft
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromSLeft; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
qFromSRight
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromSRight; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
qAfterR
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterR; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 2 |
qAfterSLeft
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterSLeft; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 4 |
qAfterSRight
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterSRight; local_* denotes one operand edge.
| Storage index | Value |
|---|---|
| 0 | 6 |
forward_q.q
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_q: q=w*x
| Storage index | Value |
|---|---|
| 0 | 1 |
forward_r.r
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_r: r=q+b
| Storage index | Value |
|---|---|
| 0 | 2 |
forward_s.s
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_s: s=q_left*q_right; q_left=q_right=q
| Storage index | Value |
|---|---|
| 0 | 1 |
forward_prediction.prediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_prediction: prediction=r+s
| Storage index | Value |
|---|---|
| 0 | 3 |
forward_error.error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_error: error=prediction-y
| Storage index | Value |
|---|---|
| 0 | 2 |
forward_loss.errorSquare
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 4 |
forward_loss.loss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 2 |
seed_loss.adjLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · seed_loss: adjLoss=1; all other accumulators=0
| Storage index | Value |
|---|---|
| 0 | 1 |
seed_loss.adjQ
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · seed_loss: adjLoss=1; all other accumulators=0
| Storage index | Value |
|---|---|
| 0 | 0 |
reverse_loss_error.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_loss_error.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_loss_error.adjError
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_error_prediction.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_error_prediction.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_error_prediction.adjPrediction
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_error_y.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_y: adjY += adjError * local_error_y
| Storage index | Value |
|---|---|
| 0 | -2 |
reverse_error_y.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_y: adjY += adjError * local_error_y
| Storage index | Value |
|---|---|
| 0 | -2 |
reverse_error_y.adjY
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_y: adjY += adjError * local_error_y
| Storage index | Value |
|---|---|
| 0 | -2 |
reverse_prediction_r.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_r: adjR += adjPrediction * local_prediction_r
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_prediction_r.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_r: adjR += adjPrediction * local_prediction_r
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_prediction_r.adjR
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_r: adjR += adjPrediction * local_prediction_r
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_prediction_s.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_prediction_s.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_prediction_s.adjS
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_b.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_b.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_b.adjB
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_q.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_q.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_r_q.adjQ
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_s_left.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_s_left.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left
| Storage index | Value |
|---|---|
| 0 | 4 |
reverse_s_left.adjQ
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left
| Storage index | Value |
|---|---|
| 0 | 4 |
reverse_s_right.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right
| Storage index | Value |
|---|---|
| 0 | 2 |
reverse_s_right.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right
| Storage index | Value |
|---|---|
| 0 | 6 |
reverse_s_right.adjQ
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right
| Storage index | Value |
|---|---|
| 0 | 6 |
reverse_q_w.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w
| Storage index | Value |
|---|---|
| 0 | 12 |
reverse_q_w.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w
| Storage index | Value |
|---|---|
| 0 | 12 |
reverse_q_w.adjW
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w
| Storage index | Value |
|---|---|
| 0 | 12 |
reverse_q_x.contribution
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x
| Storage index | Value |
|---|---|
| 0 | 3 |
reverse_q_x.accumulator
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x
| Storage index | Value |
|---|---|
| 0 | 3 |
reverse_q_x.adjX
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x
| Storage index | Value |
|---|---|
| 0 | 3 |
inputJacobian
loss_component=1 × input_component=4 · float64 · display precision 8 · J=dL/d[x,w,b,y], in that order; scalar-output Jacobian row.
| Storage index | Value |
|---|---|
| 0 | 3 |
| 1 | 12 |
| 2 | 2 |
| 3 | -2 |
seedRow
seed_row=1 × loss_component=1 · float64 · display precision 8 · Unit row seed for reverse VJP.
| Storage index | Value |
|---|---|
| 0 | 1 |
vjpRow
seed_row=1 × input_component=4 · float64 · display precision 8 · seedRow * inputJacobian; row VJP.
| Storage index | Value |
|---|---|
| 0 | 3 |
| 1 | 12 |
| 2 | 2 |
| 3 | -2 |
inputGradient
input_component=4 × column=1 · float64 · display precision 8 · Transpose of vjpRow; column gradient in x,w,b,y order.
| Storage index | Value |
|---|---|
| 0 | 3 |
| 1 | 12 |
| 2 | 2 |
| 3 | -2 |
Seek reverse_r_q, reverse_s_left and reverse_s_right to see q accumulate. Try the cancellation values in the fifth exercise; the table records -1/4 → -1/8 → 0 before q sends anything to w or x.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
The primary summary shows loss and the completed adjoints for . Seek seed_loss, then the reverse edges. In particular, compare reverse_r_q, reverse_s_left, and reverse_s_right. The selected trace and reverse table show the partial accumulators; the graph labels clearly summarize the completed reverse pass. Editing an input starts a fresh trace, and Reset example restores the worked numbers.
Keep forward values and backward sensitivities separate
The model is unchanged:
Here is input, weight, bias, target, prediction and signed error. Code names the last two prediction and error. All these stored values are scalars with logical shape [1,1]. A backward number is not a replacement value for any forward node.
An adjoint of a node , written , means : the total loss derivative with respect to that stored value. The bar is notation for sensitivity, not an average. Code calls it adjV, for example adjQ. An accumulator is the running sum used to build that adjoint as its contributions arrive.
At defaults , the forward values are , , , , , and . Save those operands first: local derivative factors in the backward pass use the values from this same forward calculation. No learning rate, parameter update or second model evaluation is involved.
The chain rule supplies one backward message
Suppose a node is an operand of a later node . If a change in changes at rate , and loss changes with at rate , their composed effect is the product
This is the scalar chain rule. For several operand edges leaving , add one such contribution per edge. The symbol += in the trace means “add the right-hand value to the existing accumulator.” It must not be replaced by assignment that discards earlier messages.
First seed loss with , since loss changes with itself at rate one. All other accumulators begin at zero. This seed is an instruction about which output we differentiate; it does not assert that the numerical loss equals one. Our loss is two.
For the half-square, the local factor is . Therefore
Error subtracts target from prediction, so its two local factors are and :
Prediction adds and . Each receives the full prediction adjoint, not half of it:
The forward addition is not an averaging operation, so dividing the backward sensitivity by two would change the derivative.
Accumulate the three q contributions
The linear branch sends to bias. It also sends to . Starting from zero, the accumulator becomes two.
The square has two distinct operand slots, s_left and s_right. Each slot’s local derivative is the other operand, currently . Each therefore sends to the same stored . The declared accumulation order is linear branch, left square slot, right square slot:
| Arrival at q | Downstream adjoint | Local factor | Contribution | Before | After |
|---|---|---|---|---|---|
r_q | |||||
s_left | |||||
s_right |
Only now is ready. Sending the first partial sum upstream would miss later contributions. Sending the last contribution alone would discard the earlier ones. Putting the already combined square factor on each square edge would count the square twice.
Finally has local factors toward and toward :
The complete result is , , , . Input and target derivatives are useful for understanding dependencies, even though a future optimizer normally updates parameters rather than the observed data .
Why the order is backward
A topological order evaluates each node after all its inputs. A reverse topological pass processes a node’s backward rule after all its consumers have contributed to that node. It is a dependency requirement, not a visual animation preference.
Here we first seed loss, then process loss_error, error_prediction, error_y, prediction_r, and prediction_s. Both branch adjoints are ready. Next come r_b, r_q, s_left, and s_right. Only after those do q_w and q_x use the completed accumulator.
The two independent branches could be visited in another mathematically valid order. This lesson declares one exact order so you can inspect every partial sum. Floating-point addition may depend on order for other inputs; the trace never silently substitutes a different reduction. Every arrow, local factor and reverse-table row reads the same numerical result that supplied the selected operation.
Cancellation does not mean the model fits
Change to . Work forward without borrowing the default’s adjoints:
Thus . The linear contribution to is . Each square contribution multiplies two negatives:
The running accumulator is . Consequently and . But bias receives , and target receives . Loss remains positive. A zero derivative in some directions does not establish zero loss or a minimum in all directions.
This example is a smooth polynomial everywhere. Its zero derivative is cancellation, not a nondifferentiable corner and not an excuse to omit any edge.
Check the result by a separate algebraic route
Substitute the graph into its error to obtain
The derivative of error with respect to the stored is . The half-square contributes , so
At , this gives . At , the factor is zero. This algebra explains the same cancellation without assuming any trace implementation is correct. It is a hand derivation, not a report of executed validation.
For another edge case set . Then , and . Square contributions are zero, but the linear contribution is negative one. Therefore , , , and . A flat square branch leaves the direct linear path intact.
Row VJP and column gradient describe the same sensitivities
Collect inputs in a column , shape [4,1]. The superscript means transpose: exchange rows and columns. The Jacobian records output derivatives with respect to input components. For our scalar loss it is the row
at the default, shape [1,4]. A vector-Jacobian product, abbreviated VJP, multiplies a seed row by this Jacobian. Our seed row is [1], shape [1,1]. Its product with has shape [1,4]. Transposing that row gives the input gradient column , shape [4,1].
Rows enumerate input components in the column gradient; columns enumerate those same components in the Jacobian and VJP row. The declared order is always . These are four differentiated inputs, not four samples. The inspector exposes inputJacobian, seedRow, vjpRow, and inputGradient so the orientation is visible. No matrix engine is needed for four scalar derivatives.
Read the explicit reverse program
The reference initializes accumulators, iterates over the declared reverse operand edges, multiplies a downstream adjoint by its local factor, and adds the result. Forward values and parameters remain unchanged. Comments identify the seed and shared-node bookkeeping.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV-07: explicit reverse-topological chain rule with tied-slot accumulation."""
from dag_reference import (DEFAULT_DAG, EDGES, REVERSE_EDGES, adjoint_key, finite,
forward_dag, guarded, step, tensor, result, run)
DEFAULT_IV07 = dict(DEFAULT_DAG)
@guarded
def derive_iv07(state):
"""Accumulate each real operand edge once; do not optimize or use autograd."""
outputs, steps = forward_dag(state)
adjoints = {"loss": 1, "error": 0, "prediction": 0, "r": 0, "s": 0,
"q": 0, "x": 0, "w": 0, "b": 0, "y": 0}
steps.append(step("seed_loss", "Reverse: seed loss", "adjLoss=1; all other accumulators=0",
"A unit change of loss changes itself by one unit. No parameter is updated.",
{"loss": outputs["loss"]}, {"adjLoss": 1, "adjQ": 0}))
for identifier in REVERSE_EDGES:
_, source, target, _ = next(edge for edge in EDGES if edge[0] == identifier)
downstream = adjoints[target]
local = outputs["local_" + identifier]
prior = adjoints[source]
contribution = finite(downstream * local, "contribution_" + identifier)
accumulator = finite(prior + contribution, "after_" + identifier)
adjoints[source] = accumulator
outputs["contribution_" + identifier] = contribution
outputs["before_" + identifier] = prior
outputs["after_" + identifier] = accumulator
steps.append(step("reverse_" + identifier, "Reverse edge: " + identifier,
f"{adjoint_key(source)} += {adjoint_key(target)} * local_{identifier}",
f"Add this one {target} → {source} contribution. Do not propagate from q until r_q, s_left and s_right have all arrived.",
{"downstreamAdjoint": downstream, "localFactor": local, "prior": prior},
{"contribution": contribution, "accumulator": accumulator, adjoint_key(source): accumulator}))
outputs.update({adjoint_key(node): value for node, value in adjoints.items()})
outputs.update(qFromR=outputs["contribution_r_q"], qFromSLeft=outputs["contribution_s_left"],
qFromSRight=outputs["contribution_s_right"], qAfterR=outputs["after_r_q"],
qAfterSLeft=outputs["after_s_left"], qAfterSRight=outputs["after_s_right"])
# Primary lab summary emphasizes reverse quantities; retain identical TS key order.
ordered = {"loss": outputs["loss"], "adjQ": outputs["adjQ"], "adjW": outputs["adjW"], "adjX": outputs["adjX"], **outputs}
values = [outputs[key] for key in ("adjX", "adjW", "adjB", "adjY")]
extra = [tensor("inputJacobian", [1, 4], ["loss_component", "input_component"], values, "J=dL/d[x,w,b,y], in that order; scalar-output Jacobian row."),
tensor("seedRow", [1, 1], ["seed_row", "loss_component"], [1], "Unit row seed for reverse VJP."),
tensor("vjpRow", [1, 4], ["seed_row", "input_component"], values, "seedRow * inputJacobian; row VJP."),
tensor("inputGradient", [4, 1], ["input_component", "column"], values, "Transpose of vjpRow; column gradient in x,w,b,y order.")]
return result(ordered, steps, extra)
if __name__ == "__main__":
run(derive_iv07, DEFAULT_IV07)
The actual sibling helper is shown too; it supplies the same forward operations, edge definitions, finite checks and JSON serialization. NumPy provides binary64 scalars rather than autograd.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Book IV-06/07: explicit scalar DAG and small JSON/tensor helpers.
No autodiff engine: every operand edge and its local derivative is declared.
Keep this sibling beside iv06.py and iv07.py for their later execution.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np
DEFAULT_DAG = {"x": 2, "w": 0.5, "b": 1, "y": 1}
EDGES = [
("q_w", "w", "q", "dq/dw=x"),
("q_x", "x", "q", "dq/dx=w"),
("r_q", "q", "r", "dr/dq=1"),
("r_b", "b", "r", "dr/db=1"),
("s_left", "q", "s", "ds/dq_left=q_right"),
("s_right", "q", "s", "ds/dq_right=q_left"),
("prediction_r", "r", "prediction", "dp/dr=1"),
("prediction_s", "s", "prediction", "dp/ds=1"),
("error_prediction", "prediction", "error", "de/dp=1"),
("error_y", "y", "error", "de/dy=-1"),
("loss_error", "error", "loss", "dL/de=error"),
]
REVERSE_EDGES = ["loss_error", "error_prediction", "error_y", "prediction_r", "prediction_s",
"r_b", "r_q", "s_left", "s_right", "q_w", "q_x"]
class ParseFault(ValueError):
"""Owned JSON syntax/profile failure, separate from numerical validation."""
_JSON_INT = int
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as error:
if type(error) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
number = np.float64(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not np.isfinite(number):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return number
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return {"status": "unavailable", "code": error.code, "reason": str(error)}
except (OverflowError, FloatingPointError) as error:
return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
except (TypeError, AttributeError) as error:
return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}
return call
def adjoint_key(node):
return "adj" + node[0].upper() + node[1:]
def step(identifier, label, equation, explanation, inputs, outputs):
return {"id": identifier, "label": label, "equation": equation, "explanation": explanation,
"inputs": {key: float(finite(value, key)) for key, value in inputs.items()},
"outputs": {key: float(finite(value, key)) for key, value in outputs.items()}}
def forward_dag(state):
# JSON objects supply own keys; require a concrete dict and never fill missing fields.
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "State must be a JSON object.")
values = {}
for key in DEFAULT_DAG:
if key not in state:
raise NumericalFault("NONFINITE", f"{key} must be an own finite field.")
value = finite(state[key], key)
if value < -100 or value > 100:
raise NumericalFault("INVALID_INPUT", f"{key} must be between -100 and 100.")
values[key] = value
x, w, b, y = (values[key] for key in DEFAULT_DAG)
# Store the product once; both square slots read precisely this q.
q = finite(w * x, "q")
r = finite(q + b, "r")
s = finite(q * q, "s")
prediction = finite(r + s, "prediction")
error = finite(prediction - y, "error")
error_square = finite(error * error, "errorSquare")
loss = finite(error_square / np.float64(2), "loss")
outputs = {"loss": loss, "prediction": prediction, "q": q, "r": r, "s": s,
"error": error, "errorSquare": error_square, "x": x, "w": w, "b": b, "y": y,
"local_q_w": x, "local_q_x": w, "local_r_q": 1, "local_r_b": 1,
"local_s_left": q, "local_s_right": q, "local_prediction_r": 1,
"local_prediction_s": 1, "local_error_prediction": 1, "local_error_y": -1,
"local_loss_error": error}
steps = [
step("forward_q", "Forward: shared product q", "q=w*x", "Store q once. Its value is read by three outgoing operand edges.", {"w": w, "x": x}, {"q": q}),
step("forward_r", "Forward: linear branch r", "r=q+b", "The linear branch keeps a direct path from q to prediction.", {"q": q, "b": b}, {"r": r}),
step("forward_s", "Forward: tied product s", "s=q_left*q_right; q_left=q_right=q", "s_left and s_right are distinct operand slots reading the same q node.", {"q_left": q, "q_right": q}, {"s": s}),
step("forward_prediction", "Forward: combine branches", "prediction=r+s", "Both branches contribute to one scalar prediction.", {"r": r, "s": s}, {"prediction": prediction}),
step("forward_error", "Forward: signed error", "error=prediction-y", "The target enters here, after prediction.", {"prediction": prediction, "y": y}, {"error": error}),
step("forward_loss", "Forward: half-squared loss", "loss=error*error/2", "This unary half-square has one error edge with local derivative error.", {"error": error}, {"errorSquare": error_square, "loss": loss}),
]
return outputs, steps
def tensor(identifier, shape, axes, values, provenance):
# All shapes here are fixed by the lesson, not user-provided tensor shapes.
return {"id": identifier, "shape": shape, "axes": axes, "dtype": "float64",
"values": [float(finite(value, identifier)) for value in values],
"provenance": provenance, "precision": 8}
def result(outputs, steps, extra_tensors=None):
tensors = [tensor(key, [1, 1], ["scalar_row", "scalar_column"], [value],
f"Explicit scalar DAG: {key}; local_* denotes one operand edge.")
for key, value in outputs.items()]
for operation in steps:
for key, value in operation["outputs"].items():
tensors.append(tensor(f'{operation["id"]}.{key}', [1, 1], ["scalar_row", "scalar_column"],
[value], f'{operation["id"]}: {operation["equation"]}'))
return {"status": "defined", "outputs": {key: float(finite(value, key)) for key, value in outputs.items()},
"steps": steps, "tensors": tensors + (extra_tensors or [])}
def run(derive, defaults):
"""Later owner CLI: default, complete JSON argument, or '-' for JSON stdin."""
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
else:
output = derive(state)
else:
state = dict(defaults)
output = derive(state)
# Direct DAG calls retain extra-field compatibility; the CLI admits only declared fields.
if output["status"] == "defined" and any(key not in defaults for key in state):
output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": "Only the declared scalar fields are supported."}
print(json.dumps(output, allow_nan=False, separators=(",", ":")))
Keep both files together. The default CLI has no state argument; a complete JSON argument replaces all four inputs. A dash reads a complete JSON object from stdin. For example:
python3 code/python/p02/iv07.py '{"x":2,"w":-0.25,"b":1,"y":1}'
Missing required fields, nonfinite values or inputs outside [-100,100] make the result unavailable. The CLI accepts only the declared fields; direct TypeScript and Python derivation calls ignore extra fields. Numerical operations use their full stored precision; presentation rounding is never fed back into arithmetic.
What to remember before an update
The five questions distinguish an adjoint from a parameter value, add the current contributions, propagate the current weight derivative, explain the target sign, and interpret cancellation. If the arithmetic surprises you, inspect the first edge whose contribution differs rather than changing several inputs at once.
- Seed the loss derivative with one, independently of the loss value.
- Multiply a downstream adjoint by one local operand factor per edge.
- Add every incoming contribution before propagating a shared node upstream.
- Keep the Jacobian/VJP row distinct from its transposed gradient column.
- Zero sensitivity in one direction can coexist with positive loss.
For background, revisit computational graphs, the chain rule and gradients and directional derivatives. Next, a complete training-step lesson uses hand-derived gradients to propose and apply a simultaneous parameter update; the backward pass alone has not yet changed this model.