The neural notebook
← All chapters

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.

Compute it yourself

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
loss2
adjQ6
adjW12
adjX3

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 = 1. Completed reverse contribution = 2; accumulator 2 → 4.

Reverse contributions on a shared scalar DAGw and x produce q. q feeds r once and s twice, through s_left and s_right. r also reads b. r and s produce prediction; prediction minus y produces error; half its square produces loss. Values and edge factors are listed in the tables below.w0.5adj=12x2adj=3q1adj=6b1adj=2r2adj=2s1adj=2prediction3adj=2y1adj=-2error2adj=2loss2adj=1s_lefts_rightArrows point backward; node adjoints summarize the completed pass. The table records partial sums.

Graph adjoints are final totals, including steps beyond the current selection. Use the reverse table and selected trace outputs for intermediate accumulators.

Stored node values, logical shape [1,1]
NodeValueFinal loss adjoint
w0.512
x23
q16
b12
r22
s12
prediction32
y1-2
error22
loss21
One local factor for each operand edge
Edge / operand IDStored source → consumerPartial derivativeLocal factor
q_ww → qdq/dw=x2
q_xx → qdq/dx=w0.5
r_qq → rdr/dq=11
r_bb → rdr/db=11
s_leftq → sds/dq_left=q_right1
s_rightq → sds/dq_right=q_left1
prediction_rr → predictiondp/dr=11
prediction_ss → predictiondp/ds=11
error_predictionprediction → errorde/dp=11
error_yy → errorde/dy=-1-1
loss_errorerror → lossdL/de=error2
Reverse pass: each contribution is added exactly once, in declared order
EdgeDownstream adjointLocal factorContributionAccumulator beforeAccumulator after
loss_error12202
error_prediction21202
error_y2-1-20-2
prediction_r21202
prediction_s21202
r_b21202
r_q21202
s_left21224
s_right21246
q_w6212012
q_x60.5303

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 indexValue
02

adjQ

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjQ; local_* denotes one operand edge.

Storage indexValue
06

adjW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjW; local_* denotes one operand edge.

Storage indexValue
012

adjX

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjX; local_* denotes one operand edge.

Storage indexValue
03

prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: prediction; local_* denotes one operand edge.

Storage indexValue
03

q

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: q; local_* denotes one operand edge.

Storage indexValue
01

r

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: r; local_* denotes one operand edge.

Storage indexValue
02

s

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: s; local_* denotes one operand edge.

Storage indexValue
01

error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: error; local_* denotes one operand edge.

Storage indexValue
02

errorSquare

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: errorSquare; local_* denotes one operand edge.

Storage indexValue
04

x

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: x; local_* denotes one operand edge.

Storage indexValue
02

w

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: w; local_* denotes one operand edge.

Storage indexValue
00.5

b

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: b; local_* denotes one operand edge.

Storage indexValue
01

y

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: y; local_* denotes one operand edge.

Storage indexValue
01

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 indexValue
02

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 indexValue
00.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 indexValue
01

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 indexValue
01

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 indexValue
01

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 indexValue
01

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 indexValue
01

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 indexValue
01

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 indexValue
01

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 indexValue
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 indexValue
02

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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
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 indexValue
00

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 indexValue
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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
02

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 indexValue
00

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 indexValue
02

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 indexValue
02

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 indexValue
02

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 indexValue
04

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 indexValue
02

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 indexValue
04

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 indexValue
06

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 indexValue
012

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 indexValue
00

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 indexValue
012

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 indexValue
03

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 indexValue
00

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 indexValue
03

adjLoss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjLoss; local_* denotes one operand edge.

Storage indexValue
01

adjError

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjError; local_* denotes one operand edge.

Storage indexValue
02

adjPrediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjPrediction; local_* denotes one operand edge.

Storage indexValue
02

adjR

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjR; local_* denotes one operand edge.

Storage indexValue
02

adjS

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjS; local_* denotes one operand edge.

Storage indexValue
02

adjB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjB; local_* denotes one operand edge.

Storage indexValue
02

adjY

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: adjY; local_* denotes one operand edge.

Storage indexValue
0-2

qFromR

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromR; local_* denotes one operand edge.

Storage indexValue
02

qFromSLeft

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromSLeft; local_* denotes one operand edge.

Storage indexValue
02

qFromSRight

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qFromSRight; local_* denotes one operand edge.

Storage indexValue
02

qAfterR

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterR; local_* denotes one operand edge.

Storage indexValue
02

qAfterSLeft

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterSLeft; local_* denotes one operand edge.

Storage indexValue
04

qAfterSRight

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: qAfterSRight; local_* denotes one operand edge.

Storage indexValue
06

forward_q.q

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_q: q=w*x

Storage indexValue
01

forward_r.r

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_r: r=q+b

Storage indexValue
02

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 indexValue
01

forward_prediction.prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_prediction: prediction=r+s

Storage indexValue
03

forward_error.error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_error: error=prediction-y

Storage indexValue
02

forward_loss.errorSquare

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2

Storage indexValue
04

forward_loss.loss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2

Storage indexValue
02

seed_loss.adjLoss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · seed_loss: adjLoss=1; all other accumulators=0

Storage indexValue
01

seed_loss.adjQ

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · seed_loss: adjLoss=1; all other accumulators=0

Storage indexValue
00

reverse_loss_error.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error

Storage indexValue
02

reverse_loss_error.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error

Storage indexValue
02

reverse_loss_error.adjError

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_loss_error: adjError += adjLoss * local_loss_error

Storage indexValue
02

reverse_error_prediction.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction

Storage indexValue
02

reverse_error_prediction.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction

Storage indexValue
02

reverse_error_prediction.adjPrediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_prediction: adjPrediction += adjError * local_error_prediction

Storage indexValue
02

reverse_error_y.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_error_y: adjY += adjError * local_error_y

Storage indexValue
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 indexValue
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 indexValue
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 indexValue
02

reverse_prediction_r.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_r: adjR += adjPrediction * local_prediction_r

Storage indexValue
02

reverse_prediction_r.adjR

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_r: adjR += adjPrediction * local_prediction_r

Storage indexValue
02

reverse_prediction_s.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s

Storage indexValue
02

reverse_prediction_s.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s

Storage indexValue
02

reverse_prediction_s.adjS

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_prediction_s: adjS += adjPrediction * local_prediction_s

Storage indexValue
02

reverse_r_b.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b

Storage indexValue
02

reverse_r_b.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b

Storage indexValue
02

reverse_r_b.adjB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_b: adjB += adjR * local_r_b

Storage indexValue
02

reverse_r_q.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q

Storage indexValue
02

reverse_r_q.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q

Storage indexValue
02

reverse_r_q.adjQ

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_r_q: adjQ += adjR * local_r_q

Storage indexValue
02

reverse_s_left.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left

Storage indexValue
02

reverse_s_left.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left

Storage indexValue
04

reverse_s_left.adjQ

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_left: adjQ += adjS * local_s_left

Storage indexValue
04

reverse_s_right.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right

Storage indexValue
02

reverse_s_right.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right

Storage indexValue
06

reverse_s_right.adjQ

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_s_right: adjQ += adjS * local_s_right

Storage indexValue
06

reverse_q_w.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w

Storage indexValue
012

reverse_q_w.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w

Storage indexValue
012

reverse_q_w.adjW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_w: adjW += adjQ * local_q_w

Storage indexValue
012

reverse_q_x.contribution

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x

Storage indexValue
03

reverse_q_x.accumulator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x

Storage indexValue
03

reverse_q_x.adjX

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reverse_q_x: adjX += adjQ * local_q_x

Storage indexValue
03

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 indexValue
03
112
22
3-2

seedRow

seed_row=1 × loss_component=1 · float64 · display precision 8 · Unit row seed for reverse VJP.

Storage indexValue
01

vjpRow

seed_row=1 × input_component=4 · float64 · display precision 8 · seedRow * inputJacobian; row VJP.

Storage indexValue
03
112
22
3-2

inputGradient

input_component=4 × column=1 · float64 · display precision 8 · Transpose of vjpRow; column gradient in x,w,b,y order.

Storage indexValue
03
112
22
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.

1. What does final adjQ=6 mean?
2. Current q contributions are 2, 2, 2. Which is their accumulated adjQ?
3. Current adjQ=6 and local dq/dw=x=2. What is adjW?
4. Current error=2 and adjY=-2. Why is adjY the negative of error?
5. With x=2,w=-0.25,b=1,y=1, q contributions are -0.25,+0.125,+0.125. What follows?

The primary summary shows loss and the completed adjoints for q,w,xq,w,x. 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:

q=wx,r=q+b,s=q q,p=r+s,e=p−y,L=e2/2.q=wx,\quad r=q+b,\quad s=q\,q,\quad p=r+s,\quad e=p-y,\quad L=e^2/2.

Here xx is input, ww weight, bb bias, yy target, pp prediction and ee 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 vv, written vˉ\bar v, means ∂L/∂v\partial L/\partial v: 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 x=2,w=1/2,b=1,y=1x=2,w=1/2,b=1,y=1, the forward values are q=1q=1, r=2r=2, s=1s=1, p=3p=3, e=2e=2, and L=2L=2. 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 uu is an operand of a later node vv. If a change in uu changes vv at rate ∂v/∂u\partial v/\partial u, and loss changes with vv at rate vˉ\bar v, their composed effect is the product

contribution to uˉ=vˉ ∂v∂u.\text{contribution to }\bar u =\bar v\,\frac{\partial v}{\partial u}.

This is the scalar chain rule. For several operand edges leaving uu, 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 Lˉ=1\bar L=1, 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 e=2e=2. Therefore

eˉ=Lˉ e=(1)(2)=2.\bar e=\bar L\,e=(1)(2)=2.

Error subtracts target from prediction, so its two local factors are 11 and −1-1:

pˉ=eˉ⋅1=2,yˉ=eˉ⋅(−1)=−2.\bar p=\bar e\cdot1=2,\qquad \bar y=\bar e\cdot(-1)=-2.

Prediction adds rr and ss. Each receives the full prediction adjoint, not half of it:

rˉ=pˉ⋅1=2,sˉ=pˉ⋅1=2.\bar r=\bar p\cdot1=2,\qquad \bar s=\bar p\cdot1=2.

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 r=q+br=q+b sends 2⋅1=22\cdot1=2 to bias. It also sends 2⋅1=22\cdot1=2 to qq. Starting from zero, the qq 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 q=1q=1. Each therefore sends sˉq=(2)(1)=2\bar s q=(2)(1)=2 to the same stored qq. The declared accumulation order is linear branch, left square slot, right square slot:

Arrival at qDownstream adjointLocal factorContributionBeforeAfter
r_q2211220022
s_left2211222244
s_right2211224466

Only now is qˉ=6\bar q=6 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 2q2q on each square edge would count the square twice.

Finally q=wxq=wx has local factors x=2x=2 toward ww and w=1/2w=1/2 toward xx:

wˉ=qˉx=(6)(2)=12,xˉ=qˉw=(6)12=3.\bar w=\bar q x=(6)(2)=12,\qquad \bar x=\bar q w=(6)\frac12=3.

The complete result is wˉ=12\bar w=12, xˉ=3\bar x=3, bˉ=2\bar b=2, yˉ=−2\bar y=-2. Input and target derivatives are useful for understanding dependencies, even though a future optimizer normally updates parameters w,bw,b rather than the observed data x,yx,y.

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 qq 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 x=2,w=−1/4,b=1,y=1x=2,w=-1/4,b=1,y=1. Work forward without borrowing the default’s adjoints:

q=−12,r=−12+1=12,s=(−12)2=14,q=-\frac12,\quad r=-\frac12+1=\frac12,\quad s=\left(-\frac12\right)^2=\frac14, p=12+14=34,e=34−1=−14,L=(−1/4)22=132.p=\frac12+\frac14=\frac34,\quad e=\frac34-1=-\frac14,\quad L=\frac{(-1/4)^2}{2}=\frac1{32}.

Thus eˉ=pˉ=rˉ=sˉ=−1/4\bar e=\bar p=\bar r=\bar s=-1/4. The linear contribution to qq is −1/4-1/4. Each square contribution multiplies two negatives:

sˉq=(−14)(−12)=18.\bar s q=\left(-\frac14\right)\left(-\frac12\right)=\frac18.

The running accumulator is 0→−1/4→−1/8→00\to-1/4\to-1/8\to0. Consequently wˉ=0⋅2=0\bar w=0\cdot2=0 and xˉ=0⋅(−1/4)=0\bar x=0\cdot(-1/4)=0. But bias receives bˉ=−1/4\bar b=-1/4, and target receives yˉ=1/4\bar y=1/4. 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

e=(wx)2+wx+b−y=q2+q+b−y.e=(wx)^2+wx+b-y=q^2+q+b-y.

The derivative of error with respect to the stored qq is 2q+12q+1. The half-square contributes ee, so

qˉ=e(2q+1),wˉ=e(2q+1)x,xˉ=e(2q+1)w,bˉ=e,yˉ=−e.\bar q=e(2q+1),\quad \bar w=e(2q+1)x,\quad \bar x=e(2q+1)w,\quad \bar b=e,\quad\bar y=-e.

At q=1,e=2q=1,e=2, this gives qˉ=2(3)=6\bar q=2(3)=6. At q=−1/2q=-1/2, the factor 2q+12q+1 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 x=2,w=0,b=0,y=1x=2,w=0,b=0,y=1. Then q=r=s=p=0q=r=s=p=0, e=−1e=-1 and L=1/2L=1/2. Square contributions are zero, but the linear contribution is negative one. Therefore qˉ=−1\bar q=-1, wˉ=−2\bar w=-2, xˉ=0\bar x=0, bˉ=−1\bar b=-1 and yˉ=1\bar y=1. A flat square branch leaves the direct linear path intact.

Row VJP and column gradient describe the same sensitivities

Collect inputs in a column u=[x,w,b,y]Tu=[x,w,b,y]^T, shape [4,1]. The superscript TT means transpose: exchange rows and columns. The Jacobian records output derivatives with respect to input components. For our scalar loss it is the row

J=[∂L/∂x∂L/∂w∂L/∂b∂L/∂y]=[3122−2]J=\begin{bmatrix}\partial L/\partial x&\partial L/\partial w&\partial L/\partial b&\partial L/\partial y\end{bmatrix} =\begin{bmatrix}3&12&2&-2\end{bmatrix}

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 JJ has shape [1,4]. Transposing that row gives the input gradient column ∇uL\nabla_u L, 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 x,w,b,yx,w,b,y. 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.