The neural notebook
← All chapters

IV-21 / Part IV · Sequence Models

Long Dependencies and Recurrent Limitations

Derive signed initial-state sensitivities along two actual recurrent chains, compare a fixed gate, and inspect shrinking, growing and rounded-zero Jacobian products.

Review the ideas this chapter uses

A small change near the start of a sequence can become almost invisible later. It can also grow until tiny starting differences produce large final differences. To understand this, we need to follow the multiplications that transmit sensitivity through time. A longer state history by itself does not guarantee that useful information, or a useful backward signal, survives.

Learning objective: Compute Jacobian products to expose vanishing and exploding gradients.

The prerequisite is IV-20 — Recurrent Networks and Backpropagation Through Time, where each reverse step multiplied by a local activation slope and recurrent weight. Here we isolate that mechanism without a prediction, target, loss or optimizer. For the meaning of a Jacobian, see III.9 — Jacobian; numerical interpretation connects to III-39 — Reproducibility and Numerical Reliability.

Compare two actual chains

Compute it yourself

Inspect actual states and signed Jacobian products

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
h0
1
alpha
0.5
T
8
f
0.75
activation
0
finalPlain0.00390625
finalGate0.34360891580581665
sensitivityPlain0.00390625
sensitivityGate0.34360891580581665

finalPlain 0.00390625. finalGate 0.34360891580581665. sensitivityPlain 0.00390625. sensitivityGate 0.34360891580581665. Both autonomous chains start from the same explicit h0. Sensitivity is the signed derivative with respect to the initial state. There is no hidden loss, norm, training or measured accuracy.. plainState 1. gateState 1. plainSensitivity 1. gateSensitivity 1

Both autonomous chains start from the same explicit h0

h_0=s_0=h0; dh_0/dh0=ds_0/dh0=1

Sensitivity is the signed derivative with respect to the initial state. There is no hidden loss, norm, training or measured accuracy.

Inputs

h0
1
alpha
0.5
T
8
f
0.75
activation
0

Outputs

plainState
1
gateState
1
plainSensitivity
1
gateSensitivity
1
State versus actual timeSigned linear vertical scale, including zero. Horizontal axis is integer time from zero through 8. Plain uses a solid line and circles; fixed gate uses a dashed line and squares. Each marker is an actual stored record. Tables provide the same full values; line segments join discrete steps.State (signed linear scale)01.000008Time tPlain; t=0; State=1Plain; t=1; State=0.5Plain; t=2; State=0.25Plain; t=3; State=0.125Plain; t=4; State=0.0625Plain; t=5; State=0.03125Plain; t=6; State=0.015625Plain; t=7; State=0.0078125Plain; t=8; State=0.00390625Fixed gate; t=0; State=1Fixed gate; t=1; State=0.875Fixed gate; t=2; State=0.765625Fixed gate; t=3; State=0.669921875Fixed gate; t=4; State=0.586181640625Fixed gate; t=5; State=0.512908935546875Fixed gate; t=6; State=0.4487953186035156Fixed gate; t=7; State=0.39269590377807617Fixed gate; t=8; State=0.34360891580581665Plain: solid / circles; fixed gate: dashed / squares
State from actual numerical histories, including t=0. Negative and zero values stay on the signed linear scale. Scaling changes only the presentation; no model value is clamped. The segments are guides between discrete times, not additional samples.
Derivative with respect to h0 versus actual timeSigned linear vertical scale, including zero. Horizontal axis is integer time from zero through 8. Plain uses a solid line and circles; fixed gate uses a dashed line and squares. Each marker is an actual stored record. Tables provide the same full values; line segments join discrete steps.Derivative with respect to h0 (signed linear scale)01.000008Time tPlain; t=0; Derivative with respect to h0=1Plain; t=1; Derivative with respect to h0=0.5Plain; t=2; Derivative with respect to h0=0.25Plain; t=3; Derivative with respect to h0=0.125Plain; t=4; Derivative with respect to h0=0.0625Plain; t=5; Derivative with respect to h0=0.03125Plain; t=6; Derivative with respect to h0=0.015625Plain; t=7; Derivative with respect to h0=0.0078125Plain; t=8; Derivative with respect to h0=0.00390625Fixed gate; t=0; Derivative with respect to h0=1Fixed gate; t=1; Derivative with respect to h0=0.875Fixed gate; t=2; Derivative with respect to h0=0.765625Fixed gate; t=3; Derivative with respect to h0=0.669921875Fixed gate; t=4; Derivative with respect to h0=0.586181640625Fixed gate; t=5; Derivative with respect to h0=0.512908935546875Fixed gate; t=6; Derivative with respect to h0=0.4487953186035156Fixed gate; t=7; Derivative with respect to h0=0.39269590377807617Fixed gate; t=8; Derivative with respect to h0=0.34360891580581665Plain: solid / circles; fixed gate: dashed / squares
Derivative with respect to h0 from actual numerical histories, including t=0. Negative and zero values stay on the signed linear scale. Scaling changes only the presentation; no model value is clamped. The segments are guides between discrete times, not additional samples.
Both independent chains, including the initial point; local scalar Jacobians have shape [1,1]
TimePlain stateFixed-gate statePlain local JacobianGate local JacobianPlain sensitivity to h0Gate sensitivity to h0
011Initial pointInitial point11
10.50.8750.50.8750.50.875
20.250.7656250.50.8750.250.765625
30.1250.6699218750.50.8750.1250.669921875
40.06250.5861816406250.50.8750.06250.586181640625
50.031250.5129089355468750.50.8750.031250.512908935546875
60.0156250.44879531860351560.50.8750.0156250.4487953186035156
70.00781250.392695903778076170.50.8750.00781250.39269590377807617
80.003906250.343608915805816650.50.8750.003906250.34360891580581665

Sensitivity is a signed derivative of state with respect to the common h0, not a gradient norm, loss or accuracy. The gate branch computes its own candidate from its own previous state. f is fixed; this is not a learned LSTM or GRU.

Inspect tensor shapes and full precision

All computed outputs

finalPlain
0.00390625
finalGate
0.34360891580581665
sensitivityPlain
0.00390625
sensitivityGate
0.34360891580581665
T
8
alpha
0.5
f
0.75
activation
0
initial_plainState
1
initial_gateState
1
initial_plainSensitivity
1
initial_gateSensitivity
1
plain_1_previousState
1
plain_1_product
0.5
plain_1_candidate
0.5
plain_1_activationSlope
1
plain_1_localJacobian
0.5
plain_1_sensitivity
0.5
plain_1_state
0.5
gate_1_previousState
1
gate_1_product
0.5
gate_1_candidate
0.5
gate_1_activationSlope
1
gate_1_candidateWeight
0.25
gate_1_retained
0.75
gate_1_weightedCandidate
0.125
gate_1_candidateJacobian
0.5
gate_1_weightedJacobian
0.125
gate_1_localJacobian
0.875
gate_1_sensitivity
0.875
gate_1_state
0.875
plain_2_previousState
0.5
plain_2_product
0.25
plain_2_candidate
0.25
plain_2_activationSlope
1
plain_2_localJacobian
0.5
plain_2_sensitivity
0.25
plain_2_state
0.25
gate_2_previousState
0.875
gate_2_product
0.4375
gate_2_candidate
0.4375
gate_2_activationSlope
1
gate_2_candidateWeight
0.25
gate_2_retained
0.65625
gate_2_weightedCandidate
0.109375
gate_2_candidateJacobian
0.5
gate_2_weightedJacobian
0.125
gate_2_localJacobian
0.875
gate_2_sensitivity
0.765625
gate_2_state
0.765625
plain_3_previousState
0.25
plain_3_product
0.125
plain_3_candidate
0.125
plain_3_activationSlope
1
plain_3_localJacobian
0.5
plain_3_sensitivity
0.125
plain_3_state
0.125
gate_3_previousState
0.765625
gate_3_product
0.3828125
gate_3_candidate
0.3828125
gate_3_activationSlope
1
gate_3_candidateWeight
0.25
gate_3_retained
0.57421875
gate_3_weightedCandidate
0.095703125
gate_3_candidateJacobian
0.5
gate_3_weightedJacobian
0.125
gate_3_localJacobian
0.875
gate_3_sensitivity
0.669921875
gate_3_state
0.669921875
plain_4_previousState
0.125
plain_4_product
0.0625
plain_4_candidate
0.0625
plain_4_activationSlope
1
plain_4_localJacobian
0.5
plain_4_sensitivity
0.0625
plain_4_state
0.0625
gate_4_previousState
0.669921875
gate_4_product
0.3349609375
gate_4_candidate
0.3349609375
gate_4_activationSlope
1
gate_4_candidateWeight
0.25
gate_4_retained
0.50244140625
gate_4_weightedCandidate
0.083740234375
gate_4_candidateJacobian
0.5
gate_4_weightedJacobian
0.125
gate_4_localJacobian
0.875
gate_4_sensitivity
0.586181640625
gate_4_state
0.586181640625
plain_5_previousState
0.0625
plain_5_product
0.03125
plain_5_candidate
0.03125
plain_5_activationSlope
1
plain_5_localJacobian
0.5
plain_5_sensitivity
0.03125
plain_5_state
0.03125
gate_5_previousState
0.586181640625
gate_5_product
0.2930908203125
gate_5_candidate
0.2930908203125
gate_5_activationSlope
1
gate_5_candidateWeight
0.25
gate_5_retained
0.43963623046875
gate_5_weightedCandidate
0.073272705078125
gate_5_candidateJacobian
0.5
gate_5_weightedJacobian
0.125
gate_5_localJacobian
0.875
gate_5_sensitivity
0.512908935546875
gate_5_state
0.512908935546875
plain_6_previousState
0.03125
plain_6_product
0.015625
plain_6_candidate
0.015625
plain_6_activationSlope
1
plain_6_localJacobian
0.5
plain_6_sensitivity
0.015625
plain_6_state
0.015625
gate_6_previousState
0.512908935546875
gate_6_product
0.2564544677734375
gate_6_candidate
0.2564544677734375
gate_6_activationSlope
1
gate_6_candidateWeight
0.25
gate_6_retained
0.38468170166015625
gate_6_weightedCandidate
0.06411361694335938
gate_6_candidateJacobian
0.5
gate_6_weightedJacobian
0.125
gate_6_localJacobian
0.875
gate_6_sensitivity
0.4487953186035156
gate_6_state
0.4487953186035156
plain_7_previousState
0.015625
plain_7_product
0.0078125
plain_7_candidate
0.0078125
plain_7_activationSlope
1
plain_7_localJacobian
0.5
plain_7_sensitivity
0.0078125
plain_7_state
0.0078125
gate_7_previousState
0.4487953186035156
gate_7_product
0.2243976593017578
gate_7_candidate
0.2243976593017578
gate_7_activationSlope
1
gate_7_candidateWeight
0.25
gate_7_retained
0.3365964889526367
gate_7_weightedCandidate
0.05609941482543945
gate_7_candidateJacobian
0.5
gate_7_weightedJacobian
0.125
gate_7_localJacobian
0.875
gate_7_sensitivity
0.39269590377807617
gate_7_state
0.39269590377807617
plain_8_previousState
0.0078125
plain_8_product
0.00390625
plain_8_candidate
0.00390625
plain_8_activationSlope
1
plain_8_localJacobian
0.5
plain_8_sensitivity
0.00390625
plain_8_state
0.00390625
gate_8_previousState
0.39269590377807617
gate_8_product
0.19634795188903809
gate_8_candidate
0.19634795188903809
gate_8_activationSlope
1
gate_8_candidateWeight
0.25
gate_8_retained
0.29452192783355713
gate_8_weightedCandidate
0.04908698797225952
gate_8_candidateJacobian
0.5
gate_8_weightedJacobian
0.125
gate_8_localJacobian
0.875
gate_8_sensitivity
0.34360891580581665
gate_8_state
0.34360891580581665

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

plainStates

State=9 · float64 · display precision 8 · Actual plain chain states, starting at time zero.

Storage indexValue
01
10.5
20.25
30.125
40.0625
50.03125
60.015625
70.0078125
80.00390625

gateStates

State=9 · float64 · display precision 8 · Actual independent fixed-gate chain states, starting at time zero.

Storage indexValue
01
10.875
20.765625
30.669921875
40.586181640625
50.512908935546875
60.4487953186035156
70.39269590377807617
80.34360891580581665

plainSensitivity

State=9 · float64 · display precision 8 · Signed products of actual plain local Jacobians; initial value 1.

Storage indexValue
01
10.5
20.25
30.125
40.0625
50.03125
60.015625
70.0078125
80.00390625

gateSensitivity

State=9 · float64 · display precision 8 · Signed products of actual fixed-gate local Jacobians; initial value 1.

Storage indexValue
01
10.875
20.765625
30.669921875
40.586181640625
50.512908935546875
60.4487953186035156
70.39269590377807617
80.34360891580581665

plainLocalJacobian

T=8 × OutputH=1 × InputH=1 · float64 · display precision 8 · Each scalar local Jacobian is logically [1,1]; signed, unclamped.

Storage indexValue
00.5
10.5
20.5
30.5
40.5
50.5
60.5
70.5

gateLocalJacobian

T=8 × OutputH=1 × InputH=1 · float64 · display precision 8 · Each fixed-gate scalar local Jacobian is logically [1,1]; evaluated on its own branch.

Storage indexValue
00.875
10.875
20.875
30.875
40.875
50.875
60.875
70.875

Compare alpha=0, 1/2, 2 and a negative value. Set f=0 and f=1, then try tanh with h0=10, alpha=4 to inspect a stored zero first slope at z=40. Reset restores the default eight-step example. Both plots and tables use actual stored records, not a training curve.

Check your understanding

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

1. What is the plotted sensitivity?
2. Use linear activation and alpha=1/2. What is the plain sensitivity at T=3?
3. Use linear activation, alpha=1/2, f=3/4. What is the fixed-gate local factor?
4. Read the current table at the last time. What is the signed plain sensitivity?
5. Which fixed-gate statement is correct?

Reset starts both chains at h0=1h_0=1, with recurrent multiplier α=1/2\alpha=1/2, fixed gate f=3/4f=3/4, linear activation and T=8 actual steps. One plot shows states; the other shows signed sensitivity to the initial state. Read the numerical table alongside them. Equal default values on those two plots will turn out to have different meanings.

First shorten T to three. Then reset and try α=2\alpha=2, followed by a negative multiplier. Finally compare f=0 with f=1. Each edit recomputes both histories from the explicit initial value. Trace and Reset refer to this calculation; there is no hidden training run.

The five required fields are h0,alpha,T,f,activation. The initial state is finite in [−10,10][-10,10], alpha in [−4,4][-4,4], and f in [0,1][0,1]. T is integer 1 through 16; activation is integer 0 for linear or 1 for tanh. Invalid or incomplete states are rejected. Actual finite results are retained without clipping, and nonfinite intermediate arithmetic is unavailable.

Write down the two recurrence rules

The plain chain repeatedly scales its own previous state and applies activation:

zth=αht−1,qt=a(zth),ht=qt.z^h_t=\alpha h_{t-1},\qquad q_t=a(z^h_t),\qquad h_t=q_t.

Here t is integer time, zthz^h_t the preactivation, and qtq_t the candidate after activation. The superscript h labels the plain branch; it is not an exponent. Linear activation means a(z)=za(z)=z; tanh means a(z)=tanh⁡za(z)=\tanh z.

The fixed-gate chain starts at s0=h0s_0=h_0 and follows

zts=αst−1,rt=a(zts),st=fst−1+(1−f)rt.z^s_t=\alpha s_{t-1},\qquad r_t=a(z^s_t),\qquad s_t=fs_{t-1}+(1-f)r_t.

The symbol s names its state, and r its own activated candidate. The gate f retains a fraction of the old state and gives the remaining weight 1−f1-f to its candidate. These weights add to one. The candidate can still lie outside the old state’s magnitude when activation is linear.

The gate branch must compute r from its own previous state, not reuse the plain candidate q. Once ht−1h_{t-1} and st−1s_{t-1} differ, their preactivations and candidates generally differ. Mixing branches would produce another model.

These are autonomous chains: after initialization, no new external input enters at each time. Their purpose is to isolate state transmission. f is a constant across time, independent of state for this derivative. It is neither learned nor a complete long short-term memory network (LSTM) or gated recurrent unit (GRU).

Sensitivity is a derivative, not a score

Define the signed sensitivities

Sth=∂ht∂h0,Sts=∂st∂h0.S^h_t=\frac{\partial h_t}{\partial h_0},\qquad S^s_t=\frac{\partial s_t}{\partial h_0}.

A partial derivative here measures how a branch state locally changes when the common initial value changes, with alpha, f, activation and T fixed. A positive derivative preserves a small change’s direction; a negative derivative reverses it. Magnitude describes amplification or attenuation. It is not measured accuracy, loss, or a norm combining every training gradient.

At time zero, both sensitivities are one: changing a supplied initial value changes itself one-for-one. This remains true even if h0=0h_0=0. A zero state is not automatically a zero sensitivity.

Let σth=a′(zth)\sigma^h_t=a'(z^h_t) and σts=a′(zts)\sigma^s_t=a'(z^s_t) be the two actual activation slopes. A local Jacobian describes one step’s output derivative with respect to its own previous state. Since there is one input and one output coordinate, its logical matrix shape is [1,1][1,1]:

Jth=ασth,Jts=f+(1−f)ασts.J^h_t=\alpha\sigma^h_t,\qquad J^s_t=f+(1-f)\alpha\sigma^s_t.

The gated Jacobian adds two paths: direct retention has derivative f; the candidate path has derivative (1−f)ασts(1-f)\alpha\sigma^s_t. No derivative of f appears because this experiment keeps it fixed.

Across time the chain rule instead multiplies:

Sth=JthSt−1h=∏j=1tJjh,Sts=JtsSt−1s=∏j=1tJjs.S^h_t=J^h_tS^h_{t-1}=\prod_{j=1}^{t}J^h_j,\qquad S^s_t=J^s_tS^s_{t-1}=\prod_{j=1}^{t}J^s_j.

The product sign means multiply the local factors indexed by j from one through t. Adding the time factors would answer a different question. This is the forward sensitivity counterpart of IV-20’s reverse propagation.

Know which axes the histories use

The tensor inspector names plainStates, gateStates, plainSensitivity and gateSensitivity. Each is a scalar history with shape [T+1] and axis State, covering times zero through T. There is no batch or feature axis hidden in this storage.

The tensors plainLocalJacobian and gateLocalJacobian have shape [T,1,1], with axes T,OutputH,InputH. They store T actual 1×11\times1 matrices, one per update. Time zero has an initial sensitivity but no locally computed transition Jacobian.

Each trace record gives its branch’s previous state, scaled product, activated candidate, activation slope, local Jacobian and running sensitivity. The gate record also separates the retained-state product from the weighted-candidate product. Keeping these operands visible explains a curve from arithmetic rather than treating a curve as evidence by itself.

Work through three linear steps

For reset alpha, every plain local factor is 1/21/2. Linear activation leaves the scaled products unchanged:

h1=(1/2)(1)=1/2,h2=(1/2)(1/2)=1/4,h3=(1/2)(1/4)=1/8.h_1=(1/2)(1)=1/2,\quad h_2=(1/2)(1/2)=1/4,\quad h_3=(1/2)(1/4)=1/8.

The sensitivities are 1/21/2, (1/2)(1/2)=1/4(1/2)(1/2)=1/4 and (1/2)3=1/8(1/2)^3=1/8.

The gate’s effective linear factor is

g=f+(1−f)α=3/4+(1/4)(1/2)=3/4+1/8=7/8.g=f+(1-f)\alpha=3/4+(1/4)(1/2)=3/4+1/8=7/8.

Here g abbreviates the complete local factor, not a new control. Work through both products at every time:

r1=(1/2)(1)=1/2,s1=(3/4)(1)+(1/4)(1/2)=3/4+1/8=7/8,r_1=(1/2)(1)=1/2,\qquad s_1=(3/4)(1)+(1/4)(1/2)=3/4+1/8=7/8, r2=(1/2)(7/8)=7/16,s2=(3/4)(7/8)+(1/4)(7/16)=21/32+7/64=49/64,r_2=(1/2)(7/8)=7/16,\qquad s_2=(3/4)(7/8)+(1/4)(7/16) =21/32+7/64=49/64, r3=(1/2)(49/64)=49/128,s3=(3/4)(49/64)+(1/4)(49/128)=147/256+49/512=343/512.r_3=(1/2)(49/64)=49/128,\qquad s_3=(3/4)(49/64)+(1/4)(49/128) =147/256+49/512=343/512.

Each local gated factor is 7/87/8, so the corresponding sensitivities are 7/87/8, 49/6449/64 and 343/512343/512. These candidates clearly differ from the plain branch’s 1/2,1/4,1/81/2,1/4,1/8 after the first time.

For any permitted positive integer T under linear activation,

hT=αTh0,STh=αT,sT=gTh0,STs=gT.h_T=\alpha^Th_0,\quad S^h_T=\alpha^T,\qquad s_T=g^Th_0,\quad S^s_T=g^T.

A superscript T here means a power, not the transpose notation from earlier matrix chapters. At default T=8,

h8=S8h=(1/2)8=1/256,s8=S8s=(7/8)8=576480116777216.h_8=S^h_8=(1/2)^8=1/256,\qquad s_8=S^s_8=(7/8)^8=\frac{5764801}{16777216}.

The equality of state and sensitivity holds here because h0=1h_0=1 and activation is linear. With h0=2h_0=2 the states double and the linear sensitivities stay the same. With h0=0h_0=0, both linear states stay zero while these derivatives remain nonzero.

Shrinking, growth and sign changes

A product of eight halves is much smaller than one half. With this positive linear multiplier, increasing T attenuates initial-state influence. Vanishing gradients names the related difficulty when many local factors make backward signals very small. There is no universal time threshold; the factors and numerical scale matter.

Set alpha=2 with linear activation. The plain sensitivity is 2T2^T, reaching 216=655362^{16}=65536 at T=16. Exploding gradients refers to the corresponding amplification of backward signals. The reported derivative here is still initial-state sensitivity, not an entire training-gradient norm.

A negative multiplier preserves sign information that a norm would discard. At alpha=−1/2-1/2, the plain sensitivities alternate −1/2,1/4,−1/8,…-1/2,1/4,-1/8,\ldots. Their magnitudes shrink while their signs alternate. At alpha=0, each plain local factor is exactly zero, making every later sensitivity zero. Negative and zero results belong in the record.

A gate changes the factors rather than supplying a universal cure. For linear alpha=2 and f=3/4, g=3/4+(1/4)(2)=5/4>1g=3/4+(1/4)(2)=5/4>1, so gated products also grow. With alpha=−3-3 and f=3/4, the linear factor is 3/4−3/4=03/4-3/4=0: two nonzero paths cancel exactly.

What tanh changes, and what storage can erase

For tanh, each slope is 1−tanh⁡2z1-\tanh^2z. In real arithmetic it is positive and at most one at any finite z. The plain factor is now alpha times a state-dependent slope. The gate uses the slope at its own candidate preactivation. Thus neither branch generally has a constant factor or a simple linear-power state formula.

Large-magnitude preactivations push tanh close to −1 or 1, a condition called saturation. A small slope can strongly attenuate a signal even when the recurrent multiplier has large magnitude. Subsequent slopes depend on the states actually reached, so inspect the entire product.

Try h0=10, alpha=4 and tanh. Both first preactivations are 40. The real tanh slope is tiny but positive. A stored binary64 tanh can round to exactly 1, so the recorded expression 1−121-1^2 is zero. Then the stored plain local factor is 4(0)=04(0)=0, while the gated factor at reset f is 3/4+(1/4)(4)(0)=3/43/4+(1/4)(4)(0)=3/4.

This distinguishes the real derivative from its finite-precision evaluation. It is not proof that the real tanh is constant at finite inputs. The two branches then follow different states, so their later candidates must be recomputed separately. Stored zero factors remain zero in the displayed product; no artificial small positive floor is substituted.

Read both plots without changing the model

Both responsive plots use signed linear vertical axes with zero included, and integer time horizontally. The initial point at t=0 is part of each history. Circles and a solid line identify the plain chain; squares and a dashed line identify the fixed gate. Connecting segments guide the eye between discrete records; they are not extra simulated times.

The state plot and sensitivity plot have different meanings and their own numerical ranges. Axis scaling changes presentation only. It never clamps a model value, takes an undisclosed absolute value, or replaces a stored zero with a logarithmic surrogate. A small product can appear close to zero beside a much larger one; read its full stored value in the table.

Five exercises matched to the lab

  1. Meaning. What is the plotted sensitivity? The signed derivative of that branch state with respect to common h0h_0. It starts at one and multiplies actual local factors; no loss, accuracy or combined gradient norm is present.
  2. Plain three-step arithmetic. With linear activation and alpha=1/21/2, what is the plain sensitivity at T=3? (1/2)(1/2)(1/2)=1/8(1/2)(1/2)(1/2)=1/8. Summing the factors to get 3/23/2 would misuse the chain rule.
  3. Gated local factor. With linear activation, alpha=1/21/2 and f=3/43/4, what is the fixed-gate local factor? 3/4+(1/4)(1/2)=7/83/4+(1/4)(1/2)=7/8. At T=3 its product is 343/512343/512; the factor and its three-step product are different quantities.
  4. Current product. Read the current table at the last time. What is the signed plain sensitivity? Use its current stored product; Reset gives 1/2561/256. Preserve a negative sign or actual zero, and include tanh’s actual slope factors when selected.
  5. Gate limits. Which statement is correct? f=1 is exact identity with sensitivity one, but incorporates none of the new candidate. For f below one and linear alpha above one, products can still grow. f=0 gives the plain chain. Neither case turns this fixed mixture into an LSTM or GRU.

At f=1 the candidate is still computed and disclosed, despite receiving zero mixture weight. Retaining the initial state perfectly in this narrow derivative sense trades away incorporation of the new candidate. Even at the reset gate, (7/8)T(7/8)^T keeps shrinking as T grows in the ideal linear formula; a slower decline is not a guarantee of arbitrary long-range memory.

Read the canonical sources and bridge onward

The actual chapter program and shared recurrent helper expose each branch’s own arithmetic, stored slopes, local Jacobians and signed products.

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.

"""IV21: actual autonomous states and signed initial-state sensitivities.

The fixed gate is independent of state and time. It is neither a learned LSTM
nor a guarantee against vanishing or exploding products of local Jacobians.
"""
import numpy as np
from recurrent_reference import Trace, activate, finite, fixed_state, guarded, run, tensor

DEFAULT_IV21 = dict(h0=1, alpha=0.5, T=8, f=0.75, activation=0)


@guarded
def derive_iv21(state):
    """Compare two independent scalar chains, including the actual initial point."""
    bounds = dict(h0=(-10, 10), alpha=(-4, 4), T=(1, 16), f=(0, 1), activation=(0, 1))
    s = fixed_state(state, DEFAULT_IV21, bounds, ("T", "activation"))
    T, trace = s["T"], Trace()
    plain_states = np.empty(T + 1, dtype=np.float64)
    gate_states = np.empty(T + 1, dtype=np.float64)
    plain_sensitivity = np.empty(T + 1, dtype=np.float64)
    gate_sensitivity = np.empty(T + 1, dtype=np.float64)
    plain_jacobian = np.empty((T, 1, 1), dtype=np.float64)
    gate_jacobian = np.empty((T, 1, 1), dtype=np.float64)
    plain_states[0], gate_states[0] = s["h0"], s["h0"]
    plain_sensitivity[0], gate_sensitivity[0] = 1.0, 1.0
    trace.add("initial", "Both autonomous chains start from the same explicit h0",
              "h_0=s_0=h0; dh_0/dh0=ds_0/dh0=1",
              "Sensitivity is the signed derivative with respect to the initial state. There is no hidden loss, norm, training or measured accuracy.",
              s, dict(plainState=s["h0"], gateState=s["h0"], plainSensitivity=1, gateSensitivity=1))

    for t in range(1, T + 1):
        previous_plain = float(plain_states[t - 1])
        plain_product = finite(s["alpha"] * previous_plain, "plain alpha*previous")
        plain, plain_slope = activate(plain_product, s["activation"])
        local_plain = finite(s["alpha"] * plain_slope, "plain local Jacobian")
        sensitivity_plain = finite(float(plain_sensitivity[t - 1]) * local_plain, "plain running sensitivity")
        plain_states[t], plain_sensitivity[t], plain_jacobian[t - 1, 0, 0] = plain, sensitivity_plain, local_plain
        trace.add(f"plain_{t}", f"Plain chain time {t}",
                  "product=alpha*previousState; candidate=a(product); localJacobian=alpha*aSlope; sensitivity=previousSensitivity*localJacobian",
                  "This chain uses its own previous plain state. The running signed product is the derivative with respect to h0.",
                  dict(t=t, previousState=previous_plain, alpha=s["alpha"], activation=s["activation"], previousSensitivity=plain_sensitivity[t - 1]),
                  dict(previousState=previous_plain, product=plain_product, candidate=plain, activationSlope=plain_slope,
                       localJacobian=local_plain, sensitivity=sensitivity_plain, state=plain))

        # The gated candidate always uses its OWN branch, including when f=1.
        previous_gate = float(gate_states[t - 1])
        gate_product = finite(s["alpha"] * previous_gate, "gate alpha*previous")
        candidate, candidate_slope = activate(gate_product, s["activation"])
        candidate_weight = finite(1.0 - s["f"], "1-f")
        retained = finite(s["f"] * previous_gate, "retained old state")
        weighted_candidate = finite(candidate_weight * candidate, "weighted own candidate")
        gate_state = finite(retained + weighted_candidate, "gate state")
        candidate_jacobian = finite(s["alpha"] * candidate_slope, "gate candidate local Jacobian")
        weighted_jacobian = finite(candidate_weight * candidate_jacobian, "weighted candidate Jacobian")
        local_gate = finite(s["f"] + weighted_jacobian, "gate local Jacobian")
        sensitivity_gate = finite(float(gate_sensitivity[t - 1]) * local_gate, "gate running sensitivity")
        gate_states[t], gate_sensitivity[t], gate_jacobian[t - 1, 0, 0] = gate_state, sensitivity_gate, local_gate
        trace.add(f"gate_{t}", f"Fixed-gate chain time {t}",
                  "candidate=a(alpha*previousState); state=f*previousState+(1-f)*candidate; localJacobian=f+(1-f)*(alpha*aSlope); sensitivity=previousSensitivity*localJacobian",
                  "Compute the candidate from this branch’s own previous gated state, even at f=1. f is constant, independent of state for this derivative; this is not a learned LSTM/GRU gate.",
                  dict(t=t, previousState=previous_gate, alpha=s["alpha"], f=s["f"], activation=s["activation"], previousSensitivity=gate_sensitivity[t - 1]),
                  dict(previousState=previous_gate, product=gate_product, candidate=candidate, activationSlope=candidate_slope,
                       candidateWeight=candidate_weight, retained=retained, weightedCandidate=weighted_candidate,
                       candidateJacobian=candidate_jacobian, weightedJacobian=weighted_jacobian,
                       localJacobian=local_gate, sensitivity=sensitivity_gate, state=gate_state))

    tensors = [
        tensor("plainStates", [T + 1], ["State"], plain_states, "Actual plain chain states, starting at time zero."),
        tensor("gateStates", [T + 1], ["State"], gate_states, "Actual independent fixed-gate chain states, starting at time zero."),
        tensor("plainSensitivity", [T + 1], ["State"], plain_sensitivity, "Signed products of actual plain local Jacobians; initial value 1."),
        tensor("gateSensitivity", [T + 1], ["State"], gate_sensitivity, "Signed products of actual fixed-gate local Jacobians; initial value 1."),
        tensor("plainLocalJacobian", [T, 1, 1], ["T", "OutputH", "InputH"], plain_jacobian,
               "Each scalar local Jacobian is logically [1,1]; signed, unclamped."),
        tensor("gateLocalJacobian", [T, 1, 1], ["T", "OutputH", "InputH"], gate_jacobian,
               "Each fixed-gate scalar local Jacobian is logically [1,1]; evaluated on its own branch."),
    ]
    return trace.result(dict(finalPlain=plain_states[T], finalGate=gate_states[T],
                             sensitivityPlain=plain_sensitivity[T], sensitivityGate=gate_sensitivity[T],
                             T=T, alpha=s["alpha"], f=s["f"], activation=s["activation"]), tensors)


if __name__ == "__main__":
    run(derive_iv21, DEFAULT_IV21)
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. Defaults, a complete replacement JSON object, or - for standard input select the CLI input.

Local Jacobians add paths within a gated step; the chain rule multiplies factors across time. States and sensitivities measure different things. Nonlinearity and finite precision can change the observed products, while a fixed gate changes rather than eliminates recurrent limitations.

Part V begins with IV-22 — Queries, Keys and Values as Projections and introduces attention projections. Attention offers another route for combining information across positions; it does not establish that every long dependency is easy or remove all numerical and learning limitations.