The neural notebook
← All chapters

IV-30 / Part VII · Transformer Blocks

Residual Connections and Gradient Paths

Add an identical-shaped skip path to a linear token branch, calculate a real scalar probe, and hand-derive the input, weight and bias gradients.

Review the ideas this chapter uses

Suppose a token already has two useful feature coordinates. A new branch calculates a change to those coordinates, but we would also like a direct path for the original values. A residual connection, also called a skip connection, adds the original input to the branch output. This chapter follows that addition forward and then follows both paths backward, including a case where their gradients cancel completely.

Learning objective: Calculate residual addition and its gradient contributions.

IV-29 — Head Concatenation and Output Projection supplies the preceding attention output; here we isolate the addition using a small, hand-set linear branch. IV-09 — Backpropagation Through a Multi-Neuron Layer reviews reverse accumulation. Book II’s III.6 — Chain rule explains the chain rule, and Book III’s III-41 — Composition and Learned Representations gives the broader neural-network composition context.

Open the branch and compare the two paths

Compute it yourself

Residual Connections and Gradient Paths

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
B
1
T
3
x000
1
x001
0
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
w00
0.5
w01
0
w10
0
w11
-0.5
b0
0
b1
0
g000
1
g001
2
g010
1
g011
2
g020
1
g021
2
g100
1
g101
2
g110
1
g111
2
g120
1
g121
2
residual
1
L5
B1
T3
residual1
Input token rows X
Branch weights W
Branch bias b
Upstream derivative g

L 5. B 1. T 3. residual 1. Validate all residual-probe inputs. All 33 fields, including inactive slots, are checked before selecting the active prefix. g is the fixed editable upstream derivative of a signed linear probe, not a target or probability.. B 1. T 3. D 2. residual 1

Validate all residual-probe inputs

D=2; X,g[B,T,D]; W[InputD,OutputD]; Y=residual*X+XW+b; L=sum(g*Y)

All 33 fields, including inactive slots, are checked before selecting the active prefix. g is the fixed editable upstream derivative of a signed linear probe, not a target or probability.

Inputs

B
1
T
3
x000
1
x001
0
x010
0
x011
1
x020
1
x021
1
x100
1
x101
1
x110
-1
x111
0
x120
0
x121
2
w00
0.5
w01
0
w10
0
w11
-0.5
b0
0
b1
0
g000
1
g001
2
g010
1
g011
2
g020
1
g021
2
g100
1
g101
2
g110
1
g111
2
g120
1
g121
2
residual
1

Outputs

B
1
T
3
D
2
residual
1

Two forward paths and their actual gradient contributions

Showing batch 0, token 0, feature 0. Selectors change the view only; the graded live question always uses batch 0, token 0, feature 0. Trace navigation selects a saved operation independently.

Selected trace operation: setup. Matching saved rows below are marked current. Operations outside this view remain available in Calculation step above.

X: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Active feature-last token rows; all stored slots validated before selection.

X: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
010
101
211

VJP means vector–Jacobian product. A Jacobian is a table of output derivatives with respect to inputs. This backward product combines that table with the upstream derivatives g: for each input feature, multiply each output’s g by its derivative and add the contributions. The branch and identity contributions are shown separately below.

Saved residual_0_0_0: skip=1×(1)=1; Y[0,0,0]=1+(0.5)=1.5. The addition helper requires equal [B,T,D] dimensions and equal axis names.

Saved backward_0_0_0: for input feature 0, branch VJP=0.5+(0)=0.5; identity VJP=1; total dX=1.5. This is the derivative of the actual signed scalar L=5 with fixed g, with no parameter update.

W: shared row weights

InputD=2 × OutputD=2 · float64 · precision 8. Feature-last row weights: F_e=X_0*W_0e+X_1*W_1e+b_e.

W: shared row weights; actual saved binary64 values without display rounding
Input featureOutput feature 0Output feature 1
00.50
10-0.5

b: shared bias

OutputD=2 · float64 · precision 8. Shared output-feature bias.

b: shared bias; actual saved binary64 values without display rounding
Bias rowOutput feature 0Output feature 1
000

g: batch 0; upstream derivative

B=1 × T=3 × D=2 · float64 · precision 8. Editable fixed upstream derivative dL/dY of the actual linear probe L.

g: batch 0; upstream derivative; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
012
112
212

Forward branch, identity path and exact-shape sum

branch products and bias additions, batch 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput x0Input x1Input w0Input w1Input biasResult product0Result product1Result sumResult branch
branch_0_0_0000100.5000.500.50.5
branch_0_0_1001100-0.500000
branch_0_1_0010010.5000000
branch_0_1_1011010-0.500-0.5-0.5-0.5
branch_0_2_0020110.5000.500.50.5
branch_0_2_1021110-0.500-0.5-0.5-0.5
residual additions, batch 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput xInput branchInput residualResult skipResult value
residual_0_0_000010.5111.5
residual_0_0_100100100
residual_0_1_001000100
residual_0_1_10111-0.5110.5
residual_0_2_002010.5111.5
residual_0_2_10211-0.5110.5

F: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. XW+b: each branch coordinate saves both products, their sum and the bias addition.

F: batch 0; actual saved binary64 values without display rounding
TokenOutput feature 0Output feature 1
00.50
10-0.5
20.5-0.5

Skip: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. residual*X: exact 0/1 switch for the identity path.

Skip: batch 0; actual saved binary64 values without display rounding
TokenOutput feature 0Output feature 1
010
101
211

Y: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Exact named-shape addition of Skip and F; no broadcasting.

Y: batch 0; actual saved binary64 values without display rounding
TokenOutput feature 0Output feature 1
01.50
100.5
21.50.5

Actual scalar probe, all batches and tokens

L=sum g×Y starts at zero and visits batch, token, then feature in ascending order. g may be signed and is neither a target nor a probability. The saved previous/product/running columns expose every contribution.

linear probe products and running sums; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput gInput yInput previousResult productResult running
probe_0_0_000011.501.51.5
probe_0_0_1001201.501.5
probe_0_1_0010101.501.5
probe_0_1_101120.51.512.5
probe_0_2_002011.52.51.54
probe_0_2_102120.5415

Backward branch and identity contributions

input VJP products and additions, batch 0; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput g0Input g1Input w0Input w1Input gInput residualResult product0Result product1Result branchGradientResult skipGradientResult gradient
backward_0_0_0000120.50110.500.511.5
backward_0_0_1001120-0.5210-1-121
backward_0_1_0010120.50110.500.511.5
backward_0_1_1011120-0.5210-1-121
backward_0_2_0020120.50110.500.511.5
backward_0_2_1021120-0.5210-1-121

dXBranch: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. g times row weights transposed: sum_e g[b,t,e]*W[d,e].

dXBranch: batch 0; actual saved binary64 values without display rounding
TokenInput feature 0Input feature 1
00.5-1
10.5-1
20.5-1

dXSkip: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. residual*g: separate identity-path VJP.

dXSkip: batch 0; actual saved binary64 values without display rounding
TokenInput feature 0Input feature 1
012
112
212

dX: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Exact named-shape addition of dXBranch and dXSkip; no broadcasting.

dX: batch 0; actual saved binary64 values without display rounding
TokenInput feature 0Input feature 1
01.51
11.51
21.51

Shared parameter sums across all active rows

For each fixed input/output pair, dW adds X×g from every active batch and token; db adds g. These cross-token sums come from parameter reuse. Forward token rows stay separate. The sums do not divide by B or T, and changing only the residual switch leaves them unchanged.

shared weight gradient products and running sums; actual saved binary64 values without display rounding
Saved stepInput bInput tInput dInput eInput xInput gInput previousResult productResult running
weight_grad_0_0_0_0000011011
weight_grad_0_1_0_0010001101
weight_grad_0_2_0_0020011112
weight_grad_0_0_0_1000112022
weight_grad_0_1_0_1010102202
weight_grad_0_2_0_1020112224
weight_grad_0_0_1_0001001000
weight_grad_0_1_1_0011011011
weight_grad_0_2_1_0021011112
weight_grad_0_0_1_1001102000
weight_grad_0_1_1_1011112022
weight_grad_0_2_1_1021112224
shared bias gradient running sums; actual saved binary64 values without display rounding
Saved stepInput bInput tInput eInput gInput previousResult running
bias_grad_0_0_0000101
bias_grad_0_1_0010112
bias_grad_0_2_0020123
bias_grad_0_0_1001202
bias_grad_0_1_1011224
bias_grad_0_2_1021246

dW: shared gradient

InputD=2 × OutputD=2 · float64 · precision 8. Sum_b,t X[b,t,d]*g[b,t,e], without averaging.

dW: shared gradient; actual saved binary64 values without display rounding
Input featureOutput feature 0Output feature 1
024
124

db: shared gradient

OutputD=2 · float64 · precision 8. Sum_b,t g[b,t,e], without averaging.

db: shared gradient; actual saved binary64 values without display rounding
Bias rowOutput feature 0Output feature 1
036

Try W=-I with residual on: branch and identity VJPs cancel exactly. W=I doubles g. An extra gradient path is useful but cannot guarantee a stable or nonzero gradient.

Inspect tensor shapes and full precision

All computed outputs

L
5
B
1
T
3
residual
1
y000
1.5
y001
0
y010
0
y011
0.5
y020
1.5
y021
0.5
dx000
1.5
dx001
1
dx010
1.5
dx011
1
dx020
1.5
dx021
1
gw00
2
gw01
4
gw10
2
gw11
4
gb0
3
gb1
6
setup_B
1
setup_T
3
setup_D
2
setup_residual
1
branch_0_0_0_product0
0.5
branch_0_0_0_product1
0
branch_0_0_0_sum
0.5
branch_0_0_0_branch
0.5
branch_0_0_1_product0
0
branch_0_0_1_product1
0
branch_0_0_1_sum
0
branch_0_0_1_branch
0
branch_0_1_0_product0
0
branch_0_1_0_product1
0
branch_0_1_0_sum
0
branch_0_1_0_branch
0
branch_0_1_1_product0
0
branch_0_1_1_product1
-0.5
branch_0_1_1_sum
-0.5
branch_0_1_1_branch
-0.5
branch_0_2_0_product0
0.5
branch_0_2_0_product1
0
branch_0_2_0_sum
0.5
branch_0_2_0_branch
0.5
branch_0_2_1_product0
0
branch_0_2_1_product1
-0.5
branch_0_2_1_sum
-0.5
branch_0_2_1_branch
-0.5
residual_0_0_0_skip
1
residual_0_0_0_value
1.5
residual_0_0_1_skip
0
residual_0_0_1_value
0
residual_0_1_0_skip
0
residual_0_1_0_value
0
residual_0_1_1_skip
1
residual_0_1_1_value
0.5
residual_0_2_0_skip
1
residual_0_2_0_value
1.5
residual_0_2_1_skip
1
residual_0_2_1_value
0.5
probe_0_0_0_product
1.5
probe_0_0_0_running
1.5
probe_0_0_1_product
0
probe_0_0_1_running
1.5
probe_0_1_0_product
0
probe_0_1_0_running
1.5
probe_0_1_1_product
1
probe_0_1_1_running
2.5
probe_0_2_0_product
1.5
probe_0_2_0_running
4
probe_0_2_1_product
1
probe_0_2_1_running
5
backward_0_0_0_product0
0.5
backward_0_0_0_product1
0
backward_0_0_0_branchGradient
0.5
backward_0_0_0_skipGradient
1
backward_0_0_0_gradient
1.5
backward_0_0_1_product0
0
backward_0_0_1_product1
-1
backward_0_0_1_branchGradient
-1
backward_0_0_1_skipGradient
2
backward_0_0_1_gradient
1
backward_0_1_0_product0
0.5
backward_0_1_0_product1
0
backward_0_1_0_branchGradient
0.5
backward_0_1_0_skipGradient
1
backward_0_1_0_gradient
1.5
backward_0_1_1_product0
0
backward_0_1_1_product1
-1
backward_0_1_1_branchGradient
-1
backward_0_1_1_skipGradient
2
backward_0_1_1_gradient
1
backward_0_2_0_product0
0.5
backward_0_2_0_product1
0
backward_0_2_0_branchGradient
0.5
backward_0_2_0_skipGradient
1
backward_0_2_0_gradient
1.5
backward_0_2_1_product0
0
backward_0_2_1_product1
-1
backward_0_2_1_branchGradient
-1
backward_0_2_1_skipGradient
2
backward_0_2_1_gradient
1
weight_grad_0_0_0_0_product
1
weight_grad_0_0_0_0_running
1
weight_grad_0_1_0_0_product
0
weight_grad_0_1_0_0_running
1
weight_grad_0_2_0_0_product
1
weight_grad_0_2_0_0_running
2
weight_grad_0_0_0_1_product
2
weight_grad_0_0_0_1_running
2
weight_grad_0_1_0_1_product
0
weight_grad_0_1_0_1_running
2
weight_grad_0_2_0_1_product
2
weight_grad_0_2_0_1_running
4
weight_grad_0_0_1_0_product
0
weight_grad_0_0_1_0_running
0
weight_grad_0_1_1_0_product
1
weight_grad_0_1_1_0_running
1
weight_grad_0_2_1_0_product
1
weight_grad_0_2_1_0_running
2
weight_grad_0_0_1_1_product
0
weight_grad_0_0_1_1_running
0
weight_grad_0_1_1_1_product
2
weight_grad_0_1_1_1_running
2
weight_grad_0_2_1_1_product
2
weight_grad_0_2_1_1_running
4
bias_grad_0_0_0_running
1
bias_grad_0_1_0_running
2
bias_grad_0_2_0_running
3
bias_grad_0_0_1_running
2
bias_grad_0_1_1_running
4
bias_grad_0_2_1_running
6

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

X

B=1 × T=3 × D=2 · float64 · display precision 8 · Active feature-last token rows; all stored slots validated before selection.

Storage indexValue
01
10
20
31
41
51

W

InputD=2 × OutputD=2 · float64 · display precision 8 · Feature-last row weights: F_e=X_0*W_0e+X_1*W_1e+b_e.

Storage indexValue
00.5
10
20
3-0.5

b

OutputD=2 · float64 · display precision 8 · Shared output-feature bias.

Storage indexValue
00
10

g

B=1 × T=3 × D=2 · float64 · display precision 8 · Editable fixed upstream derivative dL/dY of the actual linear probe L.

Storage indexValue
01
12
21
32
41
52

F

B=1 × T=3 × D=2 · float64 · display precision 8 · XW+b: each branch coordinate saves both products, their sum and the bias addition.

Storage indexValue
00.5
10
20
3-0.5
40.5
5-0.5

Skip

B=1 × T=3 × D=2 · float64 · display precision 8 · residual*X: exact 0/1 switch for the identity path.

Storage indexValue
01
10
20
31
41
51

Y

B=1 × T=3 × D=2 · float64 · display precision 8 · Exact named-shape addition of Skip and F; no broadcasting.

Storage indexValue
01.5
10
20
30.5
41.5
50.5

dXBranch

B=1 × T=3 × D=2 · float64 · display precision 8 · g times row weights transposed: sum_e g[b,t,e]*W[d,e].

Storage indexValue
00.5
1-1
20.5
3-1
40.5
5-1

dXSkip

B=1 × T=3 × D=2 · float64 · display precision 8 · residual*g: separate identity-path VJP.

Storage indexValue
01
12
21
32
41
52

dX

B=1 × T=3 × D=2 · float64 · display precision 8 · Exact named-shape addition of dXBranch and dXSkip; no broadcasting.

Storage indexValue
01.5
11
21.5
31
41.5
51

dW

InputD=2 × OutputD=2 · float64 · display precision 8 · Sum_b,t X[b,t,d]*g[b,t,e], without averaging.

Storage indexValue
02
14
22
34

db

OutputD=2 · float64 · display precision 8 · Sum_b,t g[b,t,e], without averaging.

Storage indexValue
03
16

Open Input token rows X, Branch weights W, Branch bias b or Upstream derivative g before editing a matrix. B, T and the residual selector stay visible. All 33 named fields are checked, including inactive batches and tokens. A valid edit starts a fresh trace and resets graded answers. The native view selectors below change only which saved coordinates you inspect.

Reset gives F=(0.5,0),(0,-0.5),(0.5,-0.5), Skip=X, and Y=(1.5,0),(0,0.5),(1.5,0.5). The signed linear probe sums products 1.5,0,0,1,1.5,1 in that order, yielding L=5. This is an illustrative scalar probe, not a training loss or a probability. g=(1,2) at every active row.

For each reset row, the branch VJP is (0.5,-1), the identity VJP is (1,2), and dX=(1.5,1). Shared dW has rows (2,4),(2,4), and db=(3,6). Turning the identity path off gives L=-1 and dX=(0.5,-1) per token while F,dW,db stay unchanged. No parameter update or training is performed.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. For the actual scalar probe L=sum(g×Y), what does the residual identity path contribute to dX?
2. Can tensors [1,2,2] with axes [B,T,D] and [1,1,4] with axes [B,T,D] be added by sameShapeAdd?
3. Using the current starting inputs, saved residual_0_0_0 has x=1, residual=1, branch=0.5. What is Y[0,0,0]?
4. Hold X,W,b,g,B,T fixed and toggle only residual. Which quantities must remain unchanged?
5. Counterexample: choose W=-I (w00=w11=-1,w01=w10=0) and residual=1. What is dX for any finite edited g?

Start with reset: one sequence, three tokens and two features. Open the initially closed native groups Input token rows X, Branch weights W, Branch bias b and Upstream derivative g before editing their entries; small dimension and residual controls remain visible. Inspect batch zero, token zero, output feature zero, then follow its branch, residual and backward records. Turn the residual switch off while keeping every number fixed. The branch F stays fixed, but Y and its input gradient change. Reset before using the arithmetic below.

These are authored teaching inputs, not trained parameters. The upstream array g is editable, so the backward result belongs to the particular scalar calculation defined below. Selecting another table coordinate changes what you inspect; it does not choose which coordinate an exercise grades.

Name the axes before adding

A tensor is an array with named dimensions. B is the number of sequences in a batch, T the number of token positions in each sequence, and D=2 the number of features per token. Indices b,t,d start at zero; e names an output feature. A parameter is a reusable weight or bias; every token uses the same W and bias.

RecordShapeNamed axes and meaning
X, g[B,T,2]B,T,D: input rows and fixed upstream derivatives
W[2,2]InputD,OutputD: input feature d to output feature e
b, db[2]OutputD: bias and its accumulated gradient
F, Skip, Y[B,T,2]B,T,D: branch, skip contribution and sum
dXBranch, dXSkip, dX[B,T,2]B,T,D: input-gradient contributions and total
dW[2,2]InputD,OutputD: shared weight gradients

The symbol b in a subscript is a batch index; b in the expression XW+b is the two-entry bias vector. The source fields b0 and b1 identify its features. L is one scalar, a single number, rather than another token tensor.

Book II/III’s column-vector convention uses a matrix multiplying a column from the left. Here each token is a row and multiplies W from the right. For the same linear map, this row-weight matrix is the transpose of the earlier column-weight matrix. Its entry W[d,e] carries input d to output e. The input width two matches W’s first dimension; the output width two permits residual addition.

Addition demands the same dimensions and named axes. Equal element counts are insufficient: [1,2,2] and [1,1,4] both contain four numbers but describe different coordinates. Swapping named token and feature axes also changes meaning. The helper rejects mismatches instead of flattening or broadcasting, which would silently repeat or mispair entries.

Every forward product and addition

Let a be the residual switch, exactly zero or one. For each token,

F[b,t,e]=X[b,t,0]W[0,e]+X[b,t,1]W[1,e]+be,Skip[b,t,e]=aX[b,t,e],Y=Skip+F.F[b,t,e]=X[b,t,0]W[0,e]+X[b,t,1]W[1,e]+b_e, \qquad Skip[b,t,e]=aX[b,t,e],\qquad Y=Skip+F.

Multiply first, add the two products, then add the bias. The reset rows of X are (1,0), (0,1), (1,1); W has rows (1/2,0), (0,−1/2), and both biases are zero. With a=1, all six calculations are:

Token t, output eProduct 0Product 1Product sumPlus bias = FSkipSkip + F = Y
0,01·(1/2)=1/20·0=01/2+0=1/21/2+0=1/21·1=11+1/2=3/2
0,11·0=00·(−1/2)=00+0=00+0=01·0=00+0=0
1,00·(1/2)=01·0=00+0=00+0=01·0=00+0=0
1,10·0=01·(−1/2)=−1/20−1/2=−1/2−1/2+0=−1/21·1=11−1/2=1/2
2,01·(1/2)=1/21·0=01/2+0=1/21/2+0=1/21·1=11+1/2=3/2
2,11·0=01·(−1/2)=−1/20−1/2=−1/2−1/2+0=−1/21·1=11−1/2=1/2

Thus F has rows (1/2,0), (0,−1/2), (1/2,−1/2), while Y has (3/2,0), (0,1/2), (3/2,1/2). No operation here reads another token’s X. An attention branch can mix tokens internally, but this deliberately linear branch does not.

A real scalar gives the backward arrows meaning

A gradient measures a scalar’s local sensitivity to an input or parameter. To specify that scalar, choose a fixed array g with Y’s shape and calculate the linear probe

L=∑b,t,dg[b,t,d]Y[b,t,d].L=\sum_{b,t,d}g[b,t,d]Y[b,t,d].

“Probe” means a diagnostic scalar calculation. g is neither a target nor a probability; it is exactly the upstream derivative dL/dY. We hold g fixed when differentiating X, W and bias. There is no squared error, averaging, parameter update or training step hidden in L. Signed g and signed L are legal.

At reset every g row is (1,2). The source visits b, then t, then d in ascending order:

b,t,dg·YPreviousRunning total
0,0,01·(3/2)=3/203/2
0,0,12·0=03/23/2
0,1,01·0=03/23/2
0,1,12·(1/2)=13/25/2
0,2,01·(3/2)=3/25/24
0,2,12·(1/2)=145

With a=0, Y=F instead: products are 1/2,0,0,−1,1/2,−1, and the successive totals are 1/2,1/2,1/2,−1/2,0,−1. Hence L=−1. The skip added six to this particular probe: 1·1+2·0+1·0+2·1+1·1+2·1=6.

Derive both input-gradient paths

The backward view calls this a vector–Jacobian product, abbreviated VJP. A Jacobian is the table of output derivatives with respect to inputs. Multiplying by the upstream derivatives g and summing the output contributions gives the input gradient; it is the chain-rule calculation below.

The derivative of addition sends g to each input of the addition. Through the identity skip, changing X[d] changes only the same output coordinate, giving a·g[d]. Through the branch, X[d] influences both outputs via W[d,0] and W[d,1]. Chain-rule contributions add:

∂L∂X[b,t,d]=g[b,t,0]W[d,0]+g[b,t,1]W[d,1]⏟branch+a g[b,t,d]⏟skip.\frac{\partial L}{\partial X[b,t,d]} =\underbrace{g[b,t,0]W[d,0]+g[b,t,1]W[d,1]}_{\text{branch}} +\underbrace{a\,g[b,t,d]}_{\text{skip}}.

For each reset token, feature zero has products 1·(1/2)=1/2 and 2·0=0, branch sum 1/2, skip 1·1=1, total 3/2. Feature one has products 1·0=0 and 2·(−1/2)=−1, branch sum −1, skip 1·2=2, total 1. All three dX rows are therefore (3/2,1). With a=0 the skip gradients vanish and all rows become (1/2,−1). These are derivatives of L, not guesses from the size or sign of Y.

Why do the parameter gradients sum over tokens? A single weight is reused, so changing it changes several paths to L. Differentiating the expanded probe gives

∂L∂W[d,e]=∑b,tX[b,t,d]g[b,t,e],∂L∂be=∑b,tg[b,t,e].\frac{\partial L}{\partial W[d,e]}=\sum_{b,t}X[b,t,d]g[b,t,e],\qquad \frac{\partial L}{\partial b_e}=\sum_{b,t}g[b,t,e].
ParameterToken 0 contributionToken 1 contributionToken 2 contributionRunning totals from zero
W[0,0]1·1=10·1=01·1=11,1,2
W[0,1]1·2=20·2=01·2=22,2,4
W[1,0]0·1=01·1=11·1=10,1,2
W[1,1]0·2=01·2=21·2=20,2,4
b01111,2,3
b12222,4,6

So dW has rows (2,4),(2,4), and db=(3,6). For B=2, continue through the second sequence in b/t order. This accumulation is shared-parameter reuse, not forward communication between tokens or batches. Toggling only a changes neither dW nor db: the skip uses neither parameter.

A path is not a stability guarantee

Let I be the two-by-two identity matrix, with diagonal ones and off-diagonal zeros. Set W=−I, meaning diagonal entries −1 and off-diagonal entries zero, with a=1. The branch gradient is −g and the skip gradient is g, so dX=0 exactly in real arithmetic. With zero bias, Y=X−X=0 too. Conversely W=I gives dX=2g. Residual addition provides a direct derivative term; the other term can cancel or amplify it. It does not guarantee stable gradients in a deep network or improve this untrained toy’s predictions.

B is bounded to 1–2, T to 1–3, D stays two, and stored X/W/bias/g entries must be finite numbers in [−4,4]. All stored slots, including inactive batch/token entries, remain validated. Invalid input is unavailable rather than silently clipped or coerced. Lab tables expose stored binary64 (64-bit floating-point) values without additional display rounding. The reset fractions above are exactly representable; arbitrary decimal edits can round, and nearly cancelling terms can lose relative accuracy.

Read the actual wrapper and helper

The chapter wrapper, iv30.py:

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-30 — Residual Connections and Gradient Paths.

Prerequisites: IV-29 and IV-09. X[B,T,2] uses feature-last token rows, while
W[InputD,OutputD] has row-weight orientation: F=XW+b. The switch a=residual
selects Skip=aX; Y=Skip+F requires identical dimensions AND named axes.
The actual signed scalar is L=sum(g*Y), not a target loss or a squared error.
Editable g is the fixed upstream derivative of this linear probe.

Hand default: F=(.5,0),(0,-.5),(.5,-.5); Y=(1.5,0),(0,.5),(1.5,.5),
L=1.5+0+0+1+1.5+1=5; dX=(1.5,1) per token;
dW=((2,4),(2,4)), db=(3,6). Without the skip, L=-1 and dX=(.5,-1).
These are manual derivations, not executed outputs. No update or training.
Keep component_reference.py beside this program. Runtime validation is deferred.
"""
from types import MappingProxyType
import numpy as np
from component_reference import (
    RESIDUAL_DEFAULTS, component_state, component_trace, finite, guarded,
    run, same_shape_add, tensor,
)

DEFAULT_IV30 = MappingProxyType(dict(RESIDUAL_DEFAULTS))


@guarded
def derive_iv30(state):
    """Save every branch, residual, probe product and actual gradient contribution."""
    s = component_state(state, 30)
    B, T, residual = s["B"], s["T"], s["residual"]
    shape, axes = [B, T, 2], ["B", "T", "D"]
    trace = component_trace()
    trace.add("setup", "Validate all inputs before selecting active token rows",
              "D=2; F=XW+b; Skip=residual*X; Y=Skip+F; L=sum(g*Y)",
              "Every inactive X/g scalar is validated too. g is a signed upstream derivative, not a target.",
              s, dict(B=B, T=T, D=2, residual=residual))
    X, g = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    W, bias = np.empty((2, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d], g[b, t, d] = s[f"x{b}{t}{d}"], s[f"g{b}{t}{d}"]
    for d in range(2):
        bias[d] = s[f"b{d}"]
        for e in range(2):
            W[d, e] = s[f"w{d}{e}"]
    F, Skip = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                # This d indexes the OUTPUT feature; W columns produce F_d.
                x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                w0, w1, offset = float(W[0, d]), float(W[1, d]), float(bias[d])
                product0 = finite(x0 * w0, "branch product0")
                product1 = finite(x1 * w1, "branch product1")
                summed = finite(product0 + product1, "branch sum")
                branch = finite(summed + offset, "branch")
                F[b, t, d] = branch
                trace.add(f"branch_{b}_{t}_{d}", f"Branch output [{b},{t},{d}]",
                          "product0=x0*w0; product1=x1*w1; sum=product0+product1; branch=sum+bias",
                          "The two products are added before this output feature's bias. Each token uses the same W and b.",
                          dict(b=b, t=t, d=d, x0=x0, x1=x1, w0=w0, w1=w1, bias=offset),
                          dict(product0=product0, product1=product1, sum=summed, branch=branch))
    for b in range(B):
        for t in range(T):
            for d in range(2):
                Skip[b, t, d] = finite(residual * float(X[b, t, d]), "skip")
    f_record = tensor("F", shape, axes, F.reshape(-1).tolist(), "Explicit two-product affine branch XW+b, independently for each token.")
    skip_record = tensor("Skip", shape, axes, Skip.reshape(-1).tolist(), "residual*X: the identity path is present exactly when residual=1.")
    # The actual Y comes from the named-shape helper, never NumPy broadcasting.
    y_record = same_shape_add("Y", skip_record, f_record)
    Y = np.array(y_record["values"], dtype=np.float64).reshape(shape)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                trace.add(f"residual_{b}_{t}_{d}", f"Residual output [{b},{t},{d}]",
                          "skip=residual*x; value=skip+branch",
                          "Both operands have identical dimensions and axis labels; no broadcasting or token mixing.",
                          dict(b=b, t=t, d=d, x=float(X[b, t, d]), branch=float(F[b, t, d]), residual=residual),
                          dict(skip=float(Skip[b, t, d]), value=float(Y[b, t, d])))
    L = 0.0
    for b in range(B):
        for t in range(T):
            for d in range(2):
                upstream, y, previous = float(g[b, t, d]), float(Y[b, t, d]), L
                product = finite(upstream * y, "probe product")
                L = finite(previous + product, "probe running sum")
                trace.add(f"probe_{b}_{t}_{d}", f"Scalar probe contribution [{b},{t},{d}]",
                          "product=g*y; running=previous+product",
                          "Accumulate the actual signed scalar in ascending batch/token/feature order, starting at zero.",
                          dict(b=b, t=t, d=d, g=upstream, y=y, previous=previous), dict(product=product, running=L))
    dXBranch = np.empty(shape, dtype=np.float64)
    dXSkip = np.empty(shape, dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                # Here d indexes INPUT: its derivative uses row W[d,:], not a column.
                g0, g1 = float(g[b, t, 0]), float(g[b, t, 1])
                w0, w1, upstream = float(W[d, 0]), float(W[d, 1]), float(g[b, t, d])
                product0 = finite(g0 * w0, "backward product0")
                product1 = finite(g1 * w1, "backward product1")
                branch_gradient = finite(product0 + product1, "branch gradient")
                skip_gradient = finite(residual * upstream, "skip gradient")
                gradient = finite(branch_gradient + skip_gradient, "input gradient")
                dXBranch[b, t, d], dXSkip[b, t, d] = branch_gradient, skip_gradient
                trace.add(f"backward_{b}_{t}_{d}", f"Input gradient [{b},{t},{d}]",
                          "product0=g0*w0; product1=g1*w1; branchGradient=product0+product1; skipGradient=residual*g; gradient=branchGradient+skipGradient",
                          "Chain-rule contributions add. W=-I cancels the identity gradient; W=I doubles it. Stability is not guaranteed.",
                          dict(b=b, t=t, d=d, g0=g0, g1=g1, w0=w0, w1=w1, g=upstream, residual=residual),
                          dict(product0=product0, product1=product1, branchGradient=branch_gradient,
                               skipGradient=skip_gradient, gradient=gradient))
    branch_gradient_record = tensor("dXBranch", shape, axes, dXBranch.reshape(-1).tolist(), "Branch VJP: g0*W[d,0]+g1*W[d,1].")
    skip_gradient_record = tensor("dXSkip", shape, axes, dXSkip.reshape(-1).tolist(), "Identity-path VJP: residual*g_d.")
    gradient_record = same_shape_add("dX", branch_gradient_record, skip_gradient_record)
    dX = np.array(gradient_record["values"], dtype=np.float64).reshape(shape)
    dW, db = np.empty((2, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
    for d in range(2):
        for e in range(2):
            running = 0.0
            for b in range(B):
                for t in range(T):
                    x, upstream, previous = float(X[b, t, d]), float(g[b, t, e]), running
                    product = finite(x * upstream, "weight gradient product")
                    running = finite(previous + product, "weight gradient running sum")
                    trace.add(f"weight_grad_{b}_{t}_{d}_{e}", f"Shared weight gradient W[{d},{e}], token {b},{t}",
                              "product=x*g; running=previous+product",
                              "All tokens/batches reuse this parameter; accumulate its actual contributions in ascending b,t order.",
                              dict(b=b, t=t, d=d, e=e, x=x, g=upstream, previous=previous),
                              dict(product=product, running=running))
            dW[d, e] = running
    for e in range(2):
        running = 0.0
        for b in range(B):
            for t in range(T):
                upstream, previous = float(g[b, t, e]), running
                running = finite(previous + upstream, "bias gradient running sum")
                trace.add(f"bias_grad_{b}_{t}_{e}", f"Shared bias gradient b[{e}], token {b},{t}",
                          "running=previous+g",
                          "Bias has derivative one at each use, so add the same-output upstream derivatives.",
                          dict(b=b, t=t, e=e, g=upstream, previous=previous), dict(running=running))
        db[e] = running
    summary = dict(L=L, B=B, T=T, residual=residual)
    for prefix, values in (("y", Y), ("dx", dX)):
        for b in range(B):
            for t in range(T):
                for d in range(2):
                    summary[f"{prefix}{b}{t}{d}"] = float(values[b, t, d])
    for d in range(2):
        for e in range(2):
            summary[f"gw{d}{e}"] = float(dW[d, e])
    for e in range(2):
        summary[f"gb{e}"] = float(db[e])
    tensors = [
        tensor("X", shape, axes, X.reshape(-1).tolist(), "Active feature-last token inputs."),
        tensor("W", [2, 2], ["InputD", "OutputD"], W.reshape(-1).tolist(), "Shared row weights: input feature d, output feature e."),
        tensor("b", [2], ["OutputD"], bias.tolist(), "Shared branch output bias."),
        tensor("g", shape, axes, g.reshape(-1).tolist(), "Fixed editable upstream derivative for L=sum(g*Y)."),
        f_record, skip_record, y_record,
        branch_gradient_record, skip_gradient_record, gradient_record,
        tensor("dW", [2, 2], ["InputD", "OutputD"], dW.reshape(-1).tolist(), "Shared parameter gradients accumulated in b,t order."),
        tensor("db", [2], ["OutputD"], db.tolist(), "Shared bias gradients accumulated in b,t order."),
    ]
    return trace.result(summary, tensors)


if __name__ == "__main__":
    run(derive_iv30, DEFAULT_IV30)

The shared helper, component_reference.py:

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.

"""Part VII component kernels: real NumPy storage, explicit float operations.

Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    """Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


RESIDUAL_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
    g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
    g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
    residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
    x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
    gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))


def component_state(state, stage):
    """Validate all 33/19 own fields, including inactive X/g, before selecting."""
    if type(stage) is not int or stage not in (30, 31):
        raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
    defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return dict(status="unavailable", code=error.code, reason=str(error))
        except (OverflowError, FloatingPointError) as error:
            return dict(status="unavailable", code="NONFINITE", reason=str(error))
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class ComponentTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        # Finite clones detach each saved operand/result from mutable arrays/state.
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Aliases first, then ALL flattened step outputs in their insertion order.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def component_trace():
    return ComponentTrace()


def tensor(identifier, shape, axes, values, provenance):
    """Platform-style float64 boundary: explicit named shape and dense flat list."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if type(values) is not list or len(values) != math.prod(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
                values=flat, provenance=provenance, precision=8)


def same_shape_add(identifier, left, right):
    """Add validated float64 TensorRecords; equal element count is insufficient."""
    checked = []
    for n, record in enumerate((left, right)):
        if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
            raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
        checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
                              record.get("values"), record.get("provenance")))
    a, b = checked
    if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
    values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
    return tensor(identifier, a["shape"], a["axes"], values,
                  f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")


def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
    """Normalize one width-two token; no chapter bounds on derived IV33 rows.

    Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
    then deliberately omit it from RMS arithmetic and feature trace inputs.
    """
    if kind not in ("layer", "rms"):
        raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
    checked = []
    for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
        if type(values) is not list or len(values) != 2:
            raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
        checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
    x, gamma, beta = checked
    epsilon = finite(epsilon, "epsilon")
    if epsilon <= 0:
        raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
    statistics = {}
    if kind == "layer":
        # Population variance: two centered squares, then sum, then divide by 2.
        statistics["sum"] = finite(x[0] + x[1], "feature sum")
        statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
        statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
        statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
        statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
        statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
        statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
        statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
        source = [statistics["centered0"], statistics["centered1"]]
    else:
        # RMS uses original features, with neither mean subtraction nor beta.
        statistics["square0"] = finite(x[0] * x[0], "square0")
        statistics["square1"] = finite(x[1] * x[1], "square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
        statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
        statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
        source = list(x)
    trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
              "mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
              "meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
              "Only this token's two features contribute. Epsilon stays inside the square root.",
              dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
    normalized, values = [], []
    for d in range(2):
        n = finite(source[d] / statistics["denominator"], "normalized feature")
        scaled = finite(gamma[d] * n, "scaled feature")
        value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
        normalized.append(n)
        values.append(value)
        inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
        if kind == "layer":
            inputs["beta"] = beta[d]
        trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled",
                  "LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
                  inputs, dict(normalized=n, scaled=scaled, value=value))
    return dict(values=values, normalized=normalized, statistics=statistics)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; one JSON argument replaces all; '-' reads stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    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 fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    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:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

derive_iv30 first calls component_state to validate the complete state. np.empty allocates actual float64 arrays X, g, W and bias; the following loops fill their active entries before reading them. Each float(...) retrieves a scalar operand; product0, product1, summed and branch implement the four branch operations above. The helper’s same_shape_add produces the actual Y after checking both named shapes. Backward loops calculate dX, then accumulate dW and db; trace.result collects ordered outputs and detached records. Flattening arrays for tensor storage does not change their declared axis order. branch_0_0_0 records two products, their sum and the bias addition. residual_0_0_0 records skip and final value; probe_0_0_0 records product and running L; backward_0_0_0 records branch and skip gradients before their sum. Parameter accumulation uses weight_grad_b_t_d_e and bias_grad_b_t_e records. Read the comments and trace operands alongside the formulas, rather than feeding hand-rounded numbers back into the calculation. These raw imports show the executable sources.

Five exercises matched to the lab

The lab provides graded questions and corrective feedback. Reset calculations are worked below; for a live arithmetic question use its named saved coordinate even after changing inspector selectors.

  1. residual-path: What does the identity path contribute backward? It adds a·g to the branch input gradient. g is the fixed derivative of the specified linear probe with respect to Y, not a target. With a=0 only the skip contribution disappears.
  2. shape-add: Can [1,2,2] and [1,1,4] be added? No: their token and feature dimensions differ despite both containing four values. Addition requires equal dimensions and equal axis names; changing B,T,D to B,D,T also fails. Dense finite float64 storage is required. Neither flattening nor broadcasting repairs a mismatch.
  3. live-branch: Calculate the saved Y[0,0,0]. In residual_0_0_0, multiply the saved residual switch by its saved x, then add its saved branch. At reset this is 1·1+1/2=3/2. After edits use that current record, independently of inspector selectors, rather than a memorized reset answer.
  4. residual-toggle: Predict a residual-only edit. Holding X,W,bias,g fixed while switching a can change Y,L,dX. F,dW,db stay fixed because their formulas contain no a.
  5. cancellation: Does a direct path ensure a nonzero gradient? W=−I and a=1 give −g+g=0 for dX. A direct path is present even when the total derivative vanishes; counting paths cannot establish stability.

Recap and bridge

Residual addition pairs identical named coordinates. Backward accumulation adds the branch derivative and identity derivative. Shared weights collect contributions from every token without mixing their forward values. A direct path can cancel another path. Next, IV-31 — Layer Normalization and RMS Normalization introduces feature normalization, which changes the values within a token before later block operations.