IV-20 / Part IV · Sequence Models
Recurrent Networks and Backpropagation Through Time
Unroll a shared scalar recurrence, derive every backward contribution and simultaneous update, and distinguish full-loss derivatives from a truncated surrogate.
Review the ideas this chapter uses
A recurrent calculation produces a final state, but learning requires a reason to prefer one result over another. We will turn that final state into one prediction, compare it with one target, and ask how each shared parameter affected the mistake. The backward calculation revisits the actual forward states in reverse order. It does not run the input sequence backward through a new network.
Learning objective: Unroll a small RNN and differentiate through shared temporal weights.
Review ordered states in IV-19 — Sequences, Order and Recurrent State and the accumulation of derivative paths in IV-09 — Backpropagation Through a Multi-Neuron Layer. The shared-row mechanism in IV-18 — How Embeddings Learn From Gradients is another useful connection. For the underlying chain rule, see III.6 — Chain rule.
Follow one complete update
Trace old-snapshot BPTT, one update and a fresh complete loss
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
- x0
- 1
- x1
- 2
- x2
- -1
- wx
- 0.5
- wh
- 0.5
- b
- 0
- h0
- 0
- T
- 3
- activation
- 0
- order
- 0
- v
- 1
- c
- 0
- y
- 1
- eta
- 0.125
- horizon
- 3
initialLoss 0.3828125. finalLoss 0.0025255431780656437. usedHorizon 3. cut 0. initial: ordered active sequence. Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.. source0 0. source1 1. source2 2. T 3. h0 0
initial: ordered active sequence
permute three source identities; take leading T; initialize h0
Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.
Inputs
- x0
- 1
- x1
- 2
- x2
- -1
- wx
- 0.5
- wh
- 0.5
- b
- 0
- h0
- 0
- T
- 3
- activation
- 0
- order
- 0
- v
- 1
- c
- 0
- y
- 1
- eta
- 0.125
- horizon
- 3
Outputs
- source0
- 0
- source1
- 1
- source2
- 2
- T
- 3
- h0
- 0
Initial and freshly recomputed full sequence loss
Initial loss=0.3828125. Fresh final loss=0.0025255431780656437. Initial prediction=0.125, initial error=-0.875; fresh prediction=0.9289290048182011. Prediction is a real scalar, not a probability. One final-state squared loss, no time or batch averaging.
Full BPTT: these are derivatives of the full original sequence loss.
Used horizon=3; cut=0; saved h_cut=0. Boundary adjoint=-0.109375. The boundary is h0 itself, so its adjoint is the genuine initial-state derivative. Reported dH0=-0.109375.
Ordered source items and actual forward states
Source identity stays visible even for equal values. Permute all three items first, then use only the leading T=3. Inactive items cause no state update. h0=0 initializes this calculation.
Move left / Move right swaps adjacent source identities through the existing input controls. The native order selector above is the keyboard equivalent; all buttons also work by keyboard.
| Position | Source identity | Value | Prefix status | Move this source item |
|---|---|---|---|---|
| 1 | x0 | 1 | Active | |
| 2 | x1 | 2 | Active | |
| 3 | x2 | -1 | Active |
| Time | Source | Input | Previous state | wx × input | wh × previous | Product sum | Bias | z | Actual h | Stored slope |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Explicit initial state; no input consumed | 0 | Not an activation step | |||||||
| 1 | x0 | 1 | 0 | 0.5 | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 |
| 2 | x1 | 2 | 0.5 | 1 | 0.25 | 1.25 | 0 | 1.25 | 1.25 | 1 |
| 3 | x2 | -1 | 1.25 | -0.5 | 0.625 | 0.125 | 0 | 0.125 | 0.125 | 1 |
Tables show stored values. Tanh uses the stored slope 1−h², which may round to zero at saturation even when the finite real derivative is positive. Trace navigation highlights an actual operation; the controls remain the starting inputs.
| Time | dH_t | Slope | dZ | x_t | h previous | Old wx | Old wh | dWx_t | dWh_t | dB_t | Running dWx | Running dWh | Running dB | dH previous | dX ordered |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 3 | -0.875 | 1 | -0.875 | -1 | 1.25 | 0.5 | 0.5 | 0.875 | -1.09375 | -0.875 | 0.875 | -1.09375 | -0.875 | -0.4375 | -0.4375 |
| 2 | -0.4375 | 1 | -0.4375 | 2 | 0.5 | 0.5 | 0.5 | -0.875 | -0.21875 | -0.4375 | 0 | -1.3125 | -1.3125 | -0.21875 | -0.21875 |
| 1 | -0.21875 | 1 | -0.21875 | 1 | 0 | 0.5 | 0.5 | -0.21875 | 0 | -0.21875 | -0.21875 | -1.3125 | -1.53125 | -0.109375 | -0.109375 |
| Ordered position | Partial dX | Meaning |
|---|---|---|
| 1 | -0.109375 | Full original loss derivative |
| 2 | -0.21875 | Full original loss derivative |
| 3 | -0.4375 | Full original loss derivative |
Readout gradients: dV=error×old hT=-0.109375; dC=error=-0.875. Shared recurrent sums: dWx=-0.21875, dWh=-1.3125, dB=-1.53125.
| Parameter | Old value | Finished gradient | eta | eta × gradient | Updated value |
|---|---|---|---|---|---|
| wx | 0.5 | -0.21875 | 0.125 | -0.02734375 | 0.52734375 |
| wh | 0.5 | -1.3125 | 0.125 | -0.1640625 | 0.6640625 |
| b | 0 | -1.53125 | 0.125 | -0.19140625 | 0.19140625 |
| v | 1 | -0.109375 | 0.125 | -0.013671875 | 1.013671875 |
| c | 0 | -0.875 | 0.125 | -0.109375 | 0.109375 |
Fresh complete forward after the simultaneous update
Source identity stays visible even for equal values. Permute all three items first, then use only the leading T=3. Inactive items cause no state update. h0=0 initializes this calculation.
| Position | Source identity | Value | Prefix status |
|---|---|---|---|
| 1 | x0 | 1 | Active |
| 2 | x1 | 2 | Active |
| 3 | x2 | -1 | Active |
| Time | Source | Input | Previous state | wx × input | wh × previous | Product sum | Bias | z | Actual h | Stored slope |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | Explicit initial state; no input consumed | 0 | Not an activation step | |||||||
| 1 | x0 | 1 | 0 | 0.52734375 | 0 | 0.52734375 | 0.19140625 | 0.71875 | 0.71875 | 1 |
| 2 | x1 | 2 | 0.71875 | 1.0546875 | 0.477294921875 | 1.531982421875 | 0.19140625 | 1.723388671875 | 1.723388671875 | 1 |
| 3 | x2 | -1 | 1.723388671875 | -0.52734375 | 1.1444377899169922 | 0.6170940399169922 | 0.19140625 | 0.8085002899169922 | 0.8085002899169922 | 1 |
Tables show stored values. Tanh uses the stored slope 1−h², which may round to zero at saturation even when the finite real derivative is positive. Trace navigation highlights an actual operation; the controls remain the starting inputs.
The fresh full loss uses all five updated parameters and unchanged inputs, order, h0 and target, even after a truncated update. A decrease is not guaranteed. Trace navigation explains this saved calculation; controls remain its starting state. Finite updated parameters stay unclamped in the records.
Inspect tensor shapes and full precision
All computed outputs
- initialLoss
- 0.3828125
- finalLoss
- 0.0025255431780656437
- usedHorizon
- 3
- cut
- 0
- loss
- 0.3828125
- error
- -0.875
- prediction
- 0.125
- updatedPrediction
- 0.9289290048182011
- fullBPTT
- 1
- boundaryAdjoint
- -0.109375
- dWx
- -0.21875
- dWh
- -1.3125
- dB
- -1.53125
- dV
- -0.109375
- dC
- -0.875
- dH0
- -0.109375
- dX0
- -0.109375
- dX1
- -0.21875
- dX2
- -0.4375
- updatedWx
- 0.52734375
- updatedWh
- 0.6640625
- updatedB
- 0.19140625
- updatedV
- 1.013671875
- updatedC
- 0.109375
- initial_sequence_source0
- 0
- initial_sequence_source1
- 1
- initial_sequence_source2
- 2
- initial_sequence_T
- 3
- initial_sequence_h0
- 0
- initial_forward_1_previousState
- 0
- initial_forward_1_inputProduct
- 0.5
- initial_forward_1_recurrentProduct
- 0
- initial_forward_1_partialSum
- 0.5
- initial_forward_1_z
- 0.5
- initial_forward_1_state
- 0.5
- initial_forward_1_slope
- 1
- initial_forward_2_previousState
- 0.5
- initial_forward_2_inputProduct
- 1
- initial_forward_2_recurrentProduct
- 0.25
- initial_forward_2_partialSum
- 1.25
- initial_forward_2_z
- 1.25
- initial_forward_2_state
- 1.25
- initial_forward_2_slope
- 1
- initial_forward_3_previousState
- 1.25
- initial_forward_3_inputProduct
- -0.5
- initial_forward_3_recurrentProduct
- 0.625
- initial_forward_3_partialSum
- 0.125
- initial_forward_3_z
- 0.125
- initial_forward_3_state
- 0.125
- initial_forward_3_slope
- 1
- initial_readout_product
- 0.125
- initial_readout_prediction
- 0.125
- initial_readout_error
- -0.875
- initial_readout_square
- 0.765625
- initial_readout_loss
- 0.3828125
- backward_seed_usedHorizon
- 3
- backward_seed_cut
- 0
- backward_seed_fullBPTT
- 1
- backward_seed_dHT
- -0.875
- backward_seed_dV
- -0.109375
- backward_seed_dC
- -0.875
- backward_3_dZ
- -0.875
- backward_3_contributionWx
- 0.875
- backward_3_contributionWh
- -1.09375
- backward_3_contributionB
- -0.875
- backward_3_runningWx
- 0.875
- backward_3_runningWh
- -1.09375
- backward_3_runningB
- -0.875
- backward_3_dHprev
- -0.4375
- backward_3_dX
- -0.4375
- backward_2_dZ
- -0.4375
- backward_2_contributionWx
- -0.875
- backward_2_contributionWh
- -0.21875
- backward_2_contributionB
- -0.4375
- backward_2_runningWx
- 0
- backward_2_runningWh
- -1.3125
- backward_2_runningB
- -1.3125
- backward_2_dHprev
- -0.21875
- backward_2_dX
- -0.21875
- backward_1_dZ
- -0.21875
- backward_1_contributionWx
- -0.21875
- backward_1_contributionWh
- 0
- backward_1_contributionB
- -0.21875
- backward_1_runningWx
- -0.21875
- backward_1_runningWh
- -1.3125
- backward_1_runningB
- -1.53125
- backward_1_dHprev
- -0.109375
- backward_1_dX
- -0.109375
- boundary_boundaryAdjoint
- -0.109375
- boundary_dH0
- -0.109375
- update_decrement_wx
- -0.02734375
- update_updated_wx
- 0.52734375
- update_decrement_wh
- -0.1640625
- update_updated_wh
- 0.6640625
- update_decrement_b
- -0.19140625
- update_updated_b
- 0.19140625
- update_decrement_v
- -0.013671875
- update_updated_v
- 1.013671875
- update_decrement_c
- -0.109375
- update_updated_c
- 0.109375
- updated_sequence_source0
- 0
- updated_sequence_source1
- 1
- updated_sequence_source2
- 2
- updated_sequence_T
- 3
- updated_sequence_h0
- 0
- updated_forward_1_previousState
- 0
- updated_forward_1_inputProduct
- 0.52734375
- updated_forward_1_recurrentProduct
- 0
- updated_forward_1_partialSum
- 0.52734375
- updated_forward_1_z
- 0.71875
- updated_forward_1_state
- 0.71875
- updated_forward_1_slope
- 1
- updated_forward_2_previousState
- 0.71875
- updated_forward_2_inputProduct
- 1.0546875
- updated_forward_2_recurrentProduct
- 0.477294921875
- updated_forward_2_partialSum
- 1.531982421875
- updated_forward_2_z
- 1.723388671875
- updated_forward_2_state
- 1.723388671875
- updated_forward_2_slope
- 1
- updated_forward_3_previousState
- 1.723388671875
- updated_forward_3_inputProduct
- -0.52734375
- updated_forward_3_recurrentProduct
- 1.1444377899169922
- updated_forward_3_partialSum
- 0.6170940399169922
- updated_forward_3_z
- 0.8085002899169922
- updated_forward_3_state
- 0.8085002899169922
- updated_forward_3_slope
- 1
- updated_readout_product
- 0.8195540048182011
- updated_readout_prediction
- 0.9289290048182011
- updated_readout_error
- -0.07107099518179893
- updated_readout_square
- 0.005051086356131287
- updated_readout_loss
- 0.0025255431780656437
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
initial_X
B=1 × T=3 × D=1 · float64 · display precision 8 · Actual active ordered inputs; inactive positions omitted.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
initial_states
B=1 × State=4 × H=1 · float64 · display precision 8 · Explicit h0 followed by every actual recurrent state.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 0.5 |
| 2 | 1.25 |
| 3 | 0.125 |
initial_z
B=1 × T=3 × H=1 · float64 · display precision 8 · Actual preactivations.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 1.25 |
| 2 | 0.125 |
initial_slopes
B=1 × T=3 × H=1 · float64 · display precision 8 · Stored linear or 1-state² slopes; saturation can produce zero.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
initial_sourceIds
Position=3 · int32 · display precision 8 · Source identity at each ordered position, even when values coincide.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
initial_orderedValues
Position=3 · float64 · display precision 8 · Full permutation before selecting the active prefix.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
initial_sourceValues
Source=3 · float64 · display precision 8 · Original source values indexed by identity.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
updated_X
B=1 × T=3 × D=1 · float64 · display precision 8 · Actual active ordered inputs; inactive positions omitted.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
updated_states
B=1 × State=4 × H=1 · float64 · display precision 8 · Explicit h0 followed by every actual recurrent state.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 0.71875 |
| 2 | 1.723388671875 |
| 3 | 0.8085002899169922 |
updated_z
B=1 × T=3 × H=1 · float64 · display precision 8 · Actual preactivations.
| Storage index | Value |
|---|---|
| 0 | 0.71875 |
| 1 | 1.723388671875 |
| 2 | 0.8085002899169922 |
updated_slopes
B=1 × T=3 × H=1 · float64 · display precision 8 · Stored linear or 1-state² slopes; saturation can produce zero.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
updated_sourceIds
Position=3 · int32 · display precision 8 · Source identity at each ordered position, even when values coincide.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
updated_orderedValues
Position=3 · float64 · display precision 8 · Full permutation before selecting the active prefix.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
updated_sourceValues
Source=3 · float64 · display precision 8 · Original source values indexed by identity.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | -1 |
dH
B=1 × State=4 × H=1 · float64 · display precision 8 · Adjoints on the differentiated suffix, including the saved boundary adjoint. Earlier slots are stopped zeros.
| Storage index | Value |
|---|---|
| 0 | -0.109375 |
| 1 | -0.21875 |
| 2 | -0.4375 |
| 3 | -0.875 |
dZ
B=1 × T=3 × H=1 · float64 · display precision 8 · Active ordered preactivation partials; before cut, stopped zero.
| Storage index | Value |
|---|---|
| 0 | -0.21875 |
| 1 | -0.4375 |
| 2 | -0.875 |
dX
B=1 × T=3 × D=1 · float64 · display precision 8 · ORDERED active input partials; before cut, stopped zero, not full-loss derivatives.
| Storage index | Value |
|---|---|
| 0 | -0.109375 |
| 1 | -0.21875 |
| 2 | -0.4375 |
contributionWx
B=1 × T=3 × H=1 · float64 · display precision 8 · Per-time shared wx contributions.
| Storage index | Value |
|---|---|
| 0 | -0.21875 |
| 1 | -0.875 |
| 2 | 0.875 |
contributionWh
B=1 × T=3 × H=1 · float64 · display precision 8 · Per-time shared wh contributions.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | -0.21875 |
| 2 | -1.09375 |
contributionB
B=1 × T=3 × H=1 · float64 · display precision 8 · Per-time shared bias contributions.
| Storage index | Value |
|---|---|
| 0 | -0.21875 |
| 1 | -0.4375 |
| 2 | -0.875 |
parameters
Parameter=5 · float64 · display precision 8 · Old parameters in order wx,wh,b,v,c.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 0.5 |
| 2 | 0 |
| 3 | 1 |
| 4 | 0 |
gradients
Parameter=5 · float64 · display precision 8 · Old-snapshot original-loss gradients if full; otherwise fixed-boundary surrogate partials. Order wx,wh,b,v,c.
| Storage index | Value |
|---|---|
| 0 | -0.21875 |
| 1 | -1.3125 |
| 2 | -1.53125 |
| 3 | -0.109375 |
| 4 | -0.875 |
updatedParameters
Parameter=5 · float64 · display precision 8 · Actual simultaneous updated parameters, order wx,wh,b,v,c.
| Storage index | Value |
|---|---|
| 0 | 0.52734375 |
| 1 | 0.6640625 |
| 2 | 0.19140625 |
| 3 | 1.013671875 |
| 4 | 0.109375 |
lossHistory
Snapshot=2 · float64 · display precision 8 · Initial and freshly recomputed complete sequence loss. No guaranteed decrease.
| Storage index | Value |
|---|---|
| 0 | 0.3828125 |
| 1 | 0.0025255431780656437 |
Reset and compare horizons 3 and 1: the initial loss is the same, but dWx changes sign in this example. Set eta=0 to preserve every parameter, then inspect initial and updated forward records. All fifteen fields are validated.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Reset selects linear activation and a full backward horizon of three. Read the forward states, the final loss, the reverse contributions, the shared sums and the update in that order. Then inspect the fresh forward states after updating. They come from a new complete recurrence, not from changing the readout alone.
Controls describe the starting example. Trace frames explain saved arithmetic; selecting one does not replace the controls with intermediate parameters. An edit begins another calculation from its supplied initial state. Change only the horizon to one after following the full example: the forward loss stays the same while the declared backward problem changes.
One final-state objective
Reuse the recurrence
Here is the ordered active input at time t, the initial state, the shared parameters, z the preactivation and a the selected linear or tanh activation. The readout, a final affine calculation, uses weight v and bias c:
The target y is the desired scalar output, p the prediction, e its signed error and L the half-square loss. Prediction p is a real number, not a sigmoid probability. There is one loss at the final state, with no division by T or by the number of parameters.
Batch size B, input dimension D and hidden dimension H are all one. Active inputs X have shape [1,T,1]; states have [1,T+1,1], including . Preactivations, slopes and their time-aligned derivatives have [1,T,1]. Input derivatives have X’s same shape. Each shared parameter and its derivative is scalar. A gradient has the axes of its own variable; a time axis of contributions does not turn one shared weight into T weights.
Exactly fifteen fields are required: x0,x1,x2,wx,wh,b,h0,T,activation,order,v,c,y,eta,horizon. The first ten retain IV-19’s bounds and permutation-before-prefix rule. The added v,c,y are finite in , learning rate eta in , and horizon an integer 1 through 3. Inactive source slots remain validated. Unknown or missing fields, invalid choices and nonfinite arithmetic are rejected.
Complete the default forward pass
Reset gives ordered inputs , , , , , and . Linear activation preserves each sum:
Thus
Save these states before differentiating. In particular, the last recurrent-weight contribution will use the old . Recomputing that state after changing a weight would mix two different parameter snapshots.
Derive the reverse rule locally
Backpropagation through time, BPTT, applies the chain rule to an unrolled recurrence: separate state nodes for each time, all using the same parameter nodes. Write for the loss sensitivity arriving at , and for the sensitivity arriving at . The notation d names a derivative, not a parameter change.
Differentiating the loss and readout seeds the last state:
Let name the local activation slope. Linear activation gives one; tanh uses the recorded . At each visited time, multiply by that slope and then differentiate the affine operands:
The g symbols name this time’s contributions to the shared input weight, recurrent weight and bias. is sensitivity to the ordered input value. Every factor comes from the old forward snapshot. A product’s derivative with respect to one operand uses its other operand.
Only the final state has a direct loss here, so each earlier state receives its sensitivity through the next state. Additional time-local losses would require additional incoming contributions. They are absent from this objective.
Reverse all three default steps
All default slopes are one. Start at time three and work backward:
| Time t | Arriving dH | dZ = dH × slope | Previous-state derivative | Input derivative |
|---|---|---|---|---|
| 3 | ||||
| 2 | ||||
| 1 |
Therefore the ordered input derivatives are , and . These values describe sensitivity; inputs and the initial state are not updated.
Now add all uses of each shared parameter:
The summation sign means add the indicated time contributions. Capitalized derivative labels dWx,dWh,dB refer to the scalar parameters wx,wh,b. Reverse-order running totals make overwriting mistakes visible:
| After visiting time | Running dWx | Running dWh | Running dB |
|---|---|---|---|
| 3 | |||
| 2 | |||
| 1 |
Finally and . The last time’s positive input-weight contribution is not the full derivative: two earlier paths change the final sign. Sharing means sum the paths, as with repeated embedding rows; it does not mean overwrite a gradient with the last contribution.
Update simultaneously, then start forward again
Learning rate is code field eta. For any parameter , the update is ; a prime marks its new value. At all five updates use the completed old gradients:
Simultaneous means no gradient uses one of these updated values. Keep the inputs, order, T, activation, initial state and target unchanged. The fresh forward products are
The fresh prediction and error are
These are manual rational derivations, not measured decimal outputs. The displayed fresh loss must be evaluated from the complete updated recurrence. A gradient describes local change; an arbitrary finite learning rate carries no universal promise of decreasing loss.
Declare exactly what truncation differentiates
The horizon chooses how many final recurrence steps receive backward propagation:
Here u is the used count and k the cut time. Visit only . If k=0, all dependencies are retained: these are full-loss derivatives. If k is positive, treat saved as a stop-gradient constant for parameter differentiation. A stop-gradient retains a value in forward arithmetic while deliberately blocking backward propagation through its creation.
For reset inputs and horizon one, k=2 and the saved boundary is . The bar identifies its frozen baseline value. The differentiated surrogate objective, an explicitly changed derivative problem, is
Hold fixed when varying any parameter, even though the original sequence computed using those same parameters. At this baseline the surrogate and full objective have the same value, . Equal values at one point do not imply equal derivatives.
Only the last step contributes:
The input-weight sign is opposite to full BPTT’s . Readout derivatives dv and dc are unchanged. The boundary adjoint, the sensitivity arriving at the saved boundary, is
It is nonzero, but propagation past that boundary is stopped. Earlier ordered input derivatives and the propagated are zero under this policy. They are not asserted to be derivatives of the full original sequence loss. The last input derivative remains .
After a truncated update, the displayed fresh loss still recomputes the whole original forward sequence, including the states before the cut. It is not the surrogate with a permanently frozen boundary. Comparing the surrogate’s gradients with perturbations that freely recompute the boundary would compare different mathematical problems. Horizon at least T removes this distinction by selecting full BPTT.
Numerical limits and five exercises
Tanh’s stored slope can round to zero at saturation even when the real derivative is positive. All arithmetic is finite-checked; updated finite parameters are preserved rather than clipped back into their starting editor bounds. One update on this supplied example is not evidence of trained sequence understanding. III-39 — Reproducibility and Numerical Reliability gives the prior-book context for reproducibility and numerical reliability. With eta=0, gradients can remain nonzero while the parameters and fresh loss remain unchanged.
- Sharing. Why add contributions across time before updating? Each differentiated use is a path into the same shared parameter. Distinct states do not create distinct weights, and a sum need not be positive.
- Loss arithmetic. Reset. With final state , , and , what is the loss? The error is , its square is , and dividing by two gives . There is no sigmoid or extra time average.
- Current gradient. Read the current old-snapshot shared gradient. What is dWx? Reset with full BPTT gives ; the current completed sum is the answer after edits. Read the policy label too: full-loss derivative or fixed-boundary surrogate partial. The update subtracts eta times this sum.
- Truncation. Reset, then set horizon=1. Which input-weight partial and boundary adjoint appear? and boundary adjoint . Only the last time contributes; the earlier stopped zeros are not full-loss derivatives.
- Fresh-loss meaning. After a truncated update, what does the fresh final loss evaluate? The full original sequence from unchanged data and , using all five updated parameters. Reusing the baseline boundary would evaluate the surrogate instead. A truncated derivative carries no universal full-loss decrease guarantee.
Read the actual sources and carry the distinction forward
The raw chapter file and recurrent helper expose forward storage, local derivatives, accumulation, the declared cut and simultaneous update. Compare their comments and operands with the equations above.
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.
"""IV20: final-state squared loss, full/truncated BPTT and simultaneous SGD.
Truncation holds the saved boundary state fixed for parameter partials. Its
boundary adjoint is visible, but propagation before that boundary is stopped.
"""
import numpy as np
from recurrent_reference import RECURRENT_BOUNDS, RECURRENT_DEFAULTS, Trace, finite, fixed_state, forward, guarded, run, tensor
DEFAULT_IV20 = {**RECURRENT_DEFAULTS, "v": 1, "c": 0, "y": 1, "eta": 0.125, "horizon": 3}
@guarded
def derive_iv20(state):
"""Differentiate one old snapshot, update once, then recompute the full sequence."""
bounds = {**RECURRENT_BOUNDS, "v": (-2, 2), "c": (-2, 2), "y": (-2, 2),
"eta": (0, 1), "horizon": (1, 3)}
s = fixed_state(state, DEFAULT_IV20, bounds, ("T", "activation", "order", "horizon"))
T, trace = s["T"], Trace()
initial = forward(s, trace, "initial")
def readout(h, v, c, prefix):
product = finite(v * h, "v*hT")
prediction = finite(product + c, "prediction")
error = finite(prediction - s["y"], "error")
square = finite(error * error, "error square")
loss = finite(square / 2.0, "half squared loss")
trace.add(f"{prefix}_readout", f"{prefix}: final-state prediction and loss",
"product=v*hT; prediction=product+c; error=prediction-y; loss=error²/2",
"One scalar final-state loss, with no time or batch averaging. Prediction is a real number, not a sigmoid probability.",
dict(hT=h, v=v, c=c, y=s["y"]),
dict(product=product, prediction=prediction, error=error, square=square, loss=loss))
return dict(prediction=prediction, error=error, loss=loss)
before = readout(float(initial["states"][0, T, 0]), s["v"], s["c"], "initial")
used = min(s["horizon"], T)
cut = T - used
full_bptt = int(cut == 0)
dH = np.zeros((1, T + 1, 1), dtype=np.float64)
dZ = np.zeros((1, T, 1), dtype=np.float64)
dX = np.zeros((1, T, 1), dtype=np.float64)
contribution_wx = np.zeros((1, T, 1), dtype=np.float64)
contribution_wh = np.zeros((1, T, 1), dtype=np.float64)
contribution_b = np.zeros((1, T, 1), dtype=np.float64)
dH[0, T, 0] = finite(before["error"] * s["v"], "final state adjoint")
dv = finite(before["error"] * float(initial["states"][0, T, 0]), "readout gradient dV")
dc = before["error"]
trace.add("backward_seed",
"Full BPTT: seed the original loss derivative" if full_bptt else "Truncated surrogate: seed after saving a fixed boundary",
"usedHorizon=min(horizon,T); cut=T-usedHorizon; dH_T=error*v; dV=error*hT; dC=error",
"Differentiate the full original sequence objective using all old shared parameters." if full_bptt else
"Treat the current saved h_cut as a constant for parameter partials. Earlier input/state propagation is stopped; these are not full original-loss derivatives.",
dict(error=before["error"], v=s["v"], hT=initial["states"][0, T, 0],
horizon=s["horizon"], T=T, savedBoundary=initial["states"][0, cut, 0]),
dict(usedHorizon=used, cut=cut, fullBPTT=full_bptt, dHT=dH[0, T, 0], dV=dv, dC=dc))
dwx, dwh, db = 0.0, 0.0, 0.0
# Reverse only the declared suffix; untouched earlier slots remain exact zero.
for t in range(T, cut, -1):
i = t - 1
dZ[0, i, 0] = finite(float(dH[0, t, 0]) * float(initial["slopes"][0, i, 0]), "dZ")
dz = float(dZ[0, i, 0])
contribution_wx[0, i, 0] = finite(dz * float(initial["X"][0, i, 0]), "dWx contribution")
contribution_wh[0, i, 0] = finite(dz * float(initial["states"][0, i, 0]), "dWh contribution")
contribution_b[0, i, 0] = dz
dwx = finite(dwx + float(contribution_wx[0, i, 0]), "running dWx")
dwh = finite(dwh + float(contribution_wh[0, i, 0]), "running dWh")
db = finite(db + float(contribution_b[0, i, 0]), "running dB")
dH[0, i, 0] = finite(dz * s["wh"], "previous state adjoint")
dX[0, i, 0] = finite(dz * s["wx"], "ordered input derivative")
trace.add(f"backward_{t}", f"Reverse time {t}: add shared parameter contributions",
"dZ=dH*slope; dWx_t=dZ*x; dWh_t=dZ*previousState; dB_t=dZ; sums+=contributions; dHprev=dZ*oldWh; dX=dZ*oldWx",
"All local factors and running sums use the same old wx, wh, b, v, c. Time states are distinct; the parameter identities are shared.",
dict(t=t, dH=dH[0, t, 0], slope=initial["slopes"][0, i, 0], x=initial["X"][0, i, 0],
previousState=initial["states"][0, i, 0], wx=s["wx"], wh=s["wh"]),
dict(dZ=dz, contributionWx=contribution_wx[0, i, 0], contributionWh=contribution_wh[0, i, 0],
contributionB=contribution_b[0, i, 0], runningWx=dwx, runningWh=dwh, runningB=db,
dHprev=dH[0, i, 0], dX=dX[0, i, 0]))
boundary_adjoint = float(dH[0, cut, 0])
dh0 = float(dH[0, 0, 0]) if cut == 0 else 0.0
trace.add("boundary",
"Reached the genuine initial-state derivative" if full_bptt else "Stop propagation at the saved boundary",
"boundaryAdjoint=dH_cut; dH0=boundaryAdjoint if cut=0 else 0",
"This adjoint is the full loss sensitivity to h0." if full_bptt else
"boundaryAdjoint reports sensitivity to the saved boundary value, which may be nonzero. Do not propagate it to earlier states or inputs. Earlier zeros express stop-gradient in the declared surrogate.",
dict(savedBoundary=initial["states"][0, cut, 0], cut=cut),
dict(boundaryAdjoint=boundary_adjoint, dH0=dh0))
names = ("wx", "wh", "b", "v", "c")
parameters = np.array([s[name] for name in names], dtype=np.float64)
gradients = np.array([dwx, dwh, db, dv, dc], dtype=np.float64)
updated_parameters = np.empty(5, dtype=np.float64)
updated = dict(s)
update_inputs, update_outputs = dict(eta=s["eta"]), {}
# All old-snapshot derivatives are finished before constructing updated state.
for j, name in enumerate(names):
decrement = finite(s["eta"] * float(gradients[j]), f"eta*d{name}")
updated[name] = finite(s[name] - decrement, f"updated {name}")
updated_parameters[j] = updated[name]
update_inputs.update({f"old_{name}": s[name], f"gradient_{name}": gradients[j]})
update_outputs.update({f"decrement_{name}": decrement, f"updated_{name}": updated[name]})
trace.add("update", "One simultaneous update from the complete old gradient",
"thetaNew=thetaOld-eta*gradient for wx,wh,b,v,c",
"Finish every gradient before changing parameters. Inputs, order, h0 and target stay fixed. Finite updated parameters are not clipped to starting-control bounds. Controls remain the starting state.",
update_inputs, update_outputs)
after_forward = forward(updated, trace, "updated")
after = readout(float(after_forward["states"][0, T, 0]), updated["v"], updated["c"], "updated")
tensors = [*initial["tensors"], *after_forward["tensors"],
tensor("dH", [1, T + 1, 1], ["B", "State", "H"], dH,
"Adjoints on the differentiated suffix, including the saved boundary adjoint. Earlier slots are stopped zeros."),
tensor("dZ", [1, T, 1], ["B", "T", "H"], dZ, "Active ordered preactivation partials; before cut, stopped zero."),
tensor("dX", [1, T, 1], ["B", "T", "D"], dX, "ORDERED active input partials; before cut, stopped zero, not full-loss derivatives."),
tensor("contributionWx", [1, T, 1], ["B", "T", "H"], contribution_wx, "Per-time shared wx contributions."),
tensor("contributionWh", [1, T, 1], ["B", "T", "H"], contribution_wh, "Per-time shared wh contributions."),
tensor("contributionB", [1, T, 1], ["B", "T", "H"], contribution_b, "Per-time shared bias contributions."),
tensor("parameters", [5], ["Parameter"], parameters, "Old parameters in order wx,wh,b,v,c."),
tensor("gradients", [5], ["Parameter"], gradients,
"Old-snapshot original-loss gradients if full; otherwise fixed-boundary surrogate partials. Order wx,wh,b,v,c."),
tensor("updatedParameters", [5], ["Parameter"], updated_parameters, "Actual simultaneous updated parameters, order wx,wh,b,v,c."),
tensor("lossHistory", [2], ["Snapshot"], np.array([before["loss"], after["loss"]], dtype=np.float64),
"Initial and freshly recomputed complete sequence loss. No guaranteed decrease."),
]
summary = dict(initialLoss=before["loss"], finalLoss=after["loss"], usedHorizon=used, cut=cut,
loss=before["loss"], error=before["error"], prediction=before["prediction"], updatedPrediction=after["prediction"],
fullBPTT=full_bptt, boundaryAdjoint=boundary_adjoint, dWx=dwx, dWh=dwh, dB=db, dV=dv, dC=dc, dH0=dh0)
summary.update({f"dX{i}": dX[0, i, 0] for i in range(T)})
summary.update(updatedWx=updated["wx"], updatedWh=updated["wh"], updatedB=updated["b"], updatedV=updated["v"], updatedC=updated["c"])
return trace.result(summary, tensors)
if __name__ == "__main__":
run(derive_iv20, DEFAULT_IV20)
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.
"""Shared IV19–21 source: strict states, scalar arithmetic and NumPy storage.
Keep this helper beside the lesson files. Each CLI accepts defaults, a complete
JSON replacement, or '-' for stdin. Authored under the runtime hold; not executed.
"""
import argparse
from functools import wraps
import json
import math
import sys
import numpy as np
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, 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
def fixed_state(state, defaults, bounds, integers=()):
# Validate inactive fields too; no merging, string coercion or clipping.
if type(state) is not dict:
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 named scalar field and no extra fields, including inactive slots.")
result = {}
for key in defaults:
value = finite(state[key], key)
low, high = bounds[key]
if value < low or value > high:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
if key in integers and not value.is_integer():
raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
result[key] = int(value) if key in integers else value
return result
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)}
return call
def numbers(values):
return {key: finite(value, key) for key, value in values.items()}
class Trace:
def __init__(self):
self.outputs = {}
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, values):
inputs, values = numbers(inputs), numbers(values)
# Local names remain readable; aggregate keys cannot shadow the summary.
self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
self.steps.append({"id": identifier, "label": label, "equation": equation,
"explanation": explanation, "inputs": inputs, "outputs": values})
def result(self, summary, tensors):
return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
"steps": self.steps, "tensors": tensors}
def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
array = np.asarray(values, dtype=np.float64)
if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
flat = [finite(value, identifier) for value in array.reshape(-1)]
if dtype == "int32":
if any(not value.is_integer() for value in flat):
raise NumericalFault("INVALID_INPUT", "Source IDs must be integers.")
flat = [int(value) for value in flat]
return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": dtype,
"values": flat, "provenance": provenance, "precision": 8}
RECURRENT_DEFAULTS = dict(x0=1, x1=2, x2=-1, wx=0.5, wh=0.5, b=0, h0=0,
T=3, activation=0, order=0)
RECURRENT_BOUNDS = {"x0": (-4, 4), "x1": (-4, 4), "x2": (-4, 4),
"wx": (-2, 2), "wh": (-2, 2), "b": (-2, 2), "h0": (-2, 2),
"T": (1, 3), "activation": (0, 1), "order": (0, 5)}
PERMUTATIONS = ((0, 1, 2), (0, 2, 1), (1, 0, 2),
(1, 2, 0), (2, 0, 1), (2, 1, 0))
def activate(z, choice):
state = finite(z if choice == 0 else math.tanh(z), "activation")
square = finite(state * state, "stored activation square")
# Stored 1-h*h can round to zero although the finite real tanh slope is positive.
return state, 1.0 if choice == 0 else finite(1.0 - square, "stored tanh slope")
def forward(s, trace, prefix=""):
"""Permute source identities first, then evaluate only the active prefix."""
def name(key):
return f"{prefix}_{key}" if prefix else key
T = s["T"]
sources = np.array([s["x0"], s["x1"], s["x2"]], dtype=np.float64)
source_ids = np.array(PERMUTATIONS[s["order"]], dtype=np.int32)
ordered = np.empty(3, dtype=np.float64)
for position in range(3):
ordered[position] = sources[int(source_ids[position])]
X = np.empty((1, T, 1), dtype=np.float64)
states = np.empty((1, T + 1, 1), dtype=np.float64)
z = np.empty((1, T, 1), dtype=np.float64)
slopes = np.empty((1, T, 1), dtype=np.float64)
states[0, 0, 0] = s["h0"]
trace.add(name("sequence"), f"{prefix or 'Current'}: ordered active sequence",
"permute three source identities; take leading T; initialize h0",
"Inactive positions are skipped, not zero-padded. Every calculation starts from this explicit h0.",
s, dict(source0=source_ids[0], source1=source_ids[1], source2=source_ids[2], T=T, h0=s["h0"]))
for t in range(1, T + 1):
x, previous = float(ordered[t - 1]), float(states[0, t - 1, 0])
input_product = finite(s["wx"] * x, "wx*x")
recurrent_product = finite(s["wh"] * previous, "wh*previousState")
partial_sum = finite(input_product + recurrent_product, "input plus recurrent product")
preactivation = finite(partial_sum + s["b"], "z")
state, slope = activate(preactivation, s["activation"])
X[0, t - 1, 0], states[0, t, 0] = x, state
z[0, t - 1, 0], slopes[0, t - 1, 0] = preactivation, slope
trace.add(name(f"forward_{t}"), f"{prefix or 'Current'}: forward time {t}",
"inputProduct=wx*x; recurrentProduct=wh*previousState; z=(inputProduct+recurrentProduct)+b; state=a(z); slope=1 or 1-state²",
"The same wx, wh and b are reused at each time. A stored tanh slope can round to zero although the finite real derivative is positive.",
dict(t=t, sourceId=int(source_ids[t - 1]), x=x, wx=s["wx"], wh=s["wh"], b=s["b"],
previousState=previous, activation=s["activation"]),
dict(previousState=previous, inputProduct=input_product, recurrentProduct=recurrent_product,
partialSum=partial_sum, z=preactivation, state=state, slope=slope))
tensors = [
tensor(name("X"), [1, T, 1], ["B", "T", "D"], X, "Actual active ordered inputs; inactive positions omitted."),
tensor(name("states"), [1, T + 1, 1], ["B", "State", "H"], states, "Explicit h0 followed by every actual recurrent state."),
tensor(name("z"), [1, T, 1], ["B", "T", "H"], z, "Actual preactivations."),
tensor(name("slopes"), [1, T, 1], ["B", "T", "H"], slopes, "Stored linear or 1-state² slopes; saturation can produce zero."),
tensor(name("sourceIds"), [3], ["Position"], source_ids, "Source identity at each ordered position, even when values coincide.", "int32"),
tensor(name("orderedValues"), [3], ["Position"], ordered, "Full permutation before selecting the active prefix."),
tensor(name("sourceValues"), [3], ["Source"], sources, "Original source values indexed by identity."),
]
return dict(X=X, states=states, z=z, slopes=slopes, tensors=tensors)
def run(derive, defaults):
"""No argument uses defaults; a JSON object fully replaces them; '-' reads 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:
result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
else:
result = derive(state)
else:
state = dict(defaults)
result = derive(state)
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Keep both files together. The CLI accepts defaults, a complete JSON replacement, or - for standard input.
Full BPTT differentiates the final loss through all active times. Shared gradients add their time contributions before any update. Truncation differentiates a declared surrogate with a fixed saved boundary; a fresh full loss remains a separate calculation. Next, IV-21 — Long Dependencies and Recurrent Limitations studies why repeated local sensitivity factors can shrink, grow or change sign.