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
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
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
| Time | Plain state | Fixed-gate state | Plain local Jacobian | Gate local Jacobian | Plain sensitivity to h0 | Gate sensitivity to h0 |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | Initial point | Initial point | 1 | 1 |
| 1 | 0.5 | 0.875 | 0.5 | 0.875 | 0.5 | 0.875 |
| 2 | 0.25 | 0.765625 | 0.5 | 0.875 | 0.25 | 0.765625 |
| 3 | 0.125 | 0.669921875 | 0.5 | 0.875 | 0.125 | 0.669921875 |
| 4 | 0.0625 | 0.586181640625 | 0.5 | 0.875 | 0.0625 | 0.586181640625 |
| 5 | 0.03125 | 0.512908935546875 | 0.5 | 0.875 | 0.03125 | 0.512908935546875 |
| 6 | 0.015625 | 0.4487953186035156 | 0.5 | 0.875 | 0.015625 | 0.4487953186035156 |
| 7 | 0.0078125 | 0.39269590377807617 | 0.5 | 0.875 | 0.0078125 | 0.39269590377807617 |
| 8 | 0.00390625 | 0.34360891580581665 | 0.5 | 0.875 | 0.00390625 | 0.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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.25 |
| 3 | 0.125 |
| 4 | 0.0625 |
| 5 | 0.03125 |
| 6 | 0.015625 |
| 7 | 0.0078125 |
| 8 | 0.00390625 |
gateStates
State=9 · float64 · display precision 8 · Actual independent fixed-gate chain states, starting at time zero.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.875 |
| 2 | 0.765625 |
| 3 | 0.669921875 |
| 4 | 0.586181640625 |
| 5 | 0.512908935546875 |
| 6 | 0.4487953186035156 |
| 7 | 0.39269590377807617 |
| 8 | 0.34360891580581665 |
plainSensitivity
State=9 · float64 · display precision 8 · Signed products of actual plain local Jacobians; initial value 1.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.5 |
| 2 | 0.25 |
| 3 | 0.125 |
| 4 | 0.0625 |
| 5 | 0.03125 |
| 6 | 0.015625 |
| 7 | 0.0078125 |
| 8 | 0.00390625 |
gateSensitivity
State=9 · float64 · display precision 8 · Signed products of actual fixed-gate local Jacobians; initial value 1.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.875 |
| 2 | 0.765625 |
| 3 | 0.669921875 |
| 4 | 0.586181640625 |
| 5 | 0.512908935546875 |
| 6 | 0.4487953186035156 |
| 7 | 0.39269590377807617 |
| 8 | 0.34360891580581665 |
plainLocalJacobian
T=8 × OutputH=1 × InputH=1 · float64 · display precision 8 · Each scalar local Jacobian is logically [1,1]; signed, unclamped.
| Storage index | Value |
|---|---|
| 0 | 0.5 |
| 1 | 0.5 |
| 2 | 0.5 |
| 3 | 0.5 |
| 4 | 0.5 |
| 5 | 0.5 |
| 6 | 0.5 |
| 7 | 0.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 index | Value |
|---|---|
| 0 | 0.875 |
| 1 | 0.875 |
| 2 | 0.875 |
| 3 | 0.875 |
| 4 | 0.875 |
| 5 | 0.875 |
| 6 | 0.875 |
| 7 | 0.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.
Reset starts both chains at , with recurrent multiplier , fixed gate , 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 , 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 , alpha in , and f in . 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:
Here t is integer time, the preactivation, and the candidate after activation. The superscript h labels the plain branch; it is not an exponent. Linear activation means ; tanh means .
The fixed-gate chain starts at and follows
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 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 and 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
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 . A zero state is not automatically a zero sensitivity.
Let and 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 :
The gated Jacobian adds two paths: direct retention has derivative f; the candidate path has derivative . No derivative of f appears because this experiment keeps it fixed.
Across time the chain rule instead multiplies:
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 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 . Linear activation leaves the scaled products unchanged:
The sensitivities are , and .
The gate’s effective linear factor is
Here g abbreviates the complete local factor, not a new control. Work through both products at every time:
Each local gated factor is , so the corresponding sensitivities are , and . These candidates clearly differ from the plain branch’s after the first time.
For any permitted positive integer T under linear activation,
A superscript T here means a power, not the transpose notation from earlier matrix chapters. At default T=8,
The equality of state and sensitivity holds here because and activation is linear. With the states double and the linear sensitivities stay the same. With , 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 , reaching 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=, the plain sensitivities alternate . 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, , so gated products also grow. With alpha= and f=3/4, the linear factor is : two nonzero paths cancel exactly.
What tanh changes, and what storage can erase
For tanh, each slope is . 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 is zero. Then the stored plain local factor is , while the gated factor at reset f is .
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
- Meaning. What is the plotted sensitivity? The signed derivative of that branch state with respect to common . It starts at one and multiplies actual local factors; no loss, accuracy or combined gradient norm is present.
- Plain three-step arithmetic. With linear activation and alpha=, what is the plain sensitivity at T=3? . Summing the factors to get would misuse the chain rule.
- Gated local factor. With linear activation, alpha= and f=, what is the fixed-gate local factor? . At T=3 its product is ; the factor and its three-step product are different quantities.
- Current product. Read the current table at the last time. What is the signed plain sensitivity? Use its current stored product; Reset gives . Preserve a negative sign or actual zero, and include tanh’s actual slope factors when selected.
- 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, 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.