AI Research Library

Recurrence, Gating and the Vanishing Past

Rajesh Ranjan Mahapatra

A recurrent model remembers only when it carries useful state and useful learning signal across time; gates help by making that temporal path selective and adjustable.

© 2026 Rajesh Ranjan Mahapatra. 30 min read

Recurrence, Gating and the Vanishing Past

A recurrent model remembers only when it carries useful state and useful learning signal across time; gates help by making that temporal path selective and adjustable.

TLDR

  • A recurrent hidden state is not a vault. It is a value repeatedly transformed, so distant information can fade, explode or be overwritten before the model needs it.
  • Backpropagation through time multiplies local Jacobians. Repeated factors below one erase credit, factors above one destabilise it, and saturated activations can shrink it even when recurrent weights look well scaled.
  • LSTM and GRU gates create learnable carry paths. They can separate writing, retaining, revising and revealing state, giving each unit an adjustable temporal half-life.
  • Gating is neither necessary nor sufficient for long memory. Identity, orthogonal and carefully parameterised recurrence can preserve signal, while badly initialised or wrongly trained gates can still forget everything useful.
  • Choose a recurrent cell only after measuring the required horizon, distractor resistance, revision speed and causal influence. Architecture names are weaker evidence than a task-specific temporal memory test.

Opening case: the instruction at the start of the stream

At the first step of a monitoring sequence, a model receives one consequential fact: a pump is under scheduled maintenance. Sixty-four ordinary sensor readings follow. At the end, a vibration spike arrives. The correct interpretation depends on the old instruction. The same spike might mean “expected during maintenance” or “unexpected, inspect now”.

Nothing about the final input reveals which interpretation applies. The model must carry the earlier cue through a corridor of irrelevant events. That is the forward problem. Training creates a second problem in the opposite direction. When the final prediction is wrong, the error must travel back through those same sixty-four transitions and change how the first cue was encoded.

A sequence model needs two kinds of temporal continuity: the signal must survive forward, and responsibility for the outcome must survive backward. A system can fail either requirement. It may carry a trace that training cannot shape, or receive a usable gradient while repeatedly overwriting the state at inference time.

One cue, sixty-four chances to lose it

forward influencestate must still matter
early encoding must changebackward credit
Figure 1. The temporal double passage. The cue must affect the final state, and the final loss must affect the parameters that processed the cue. Illustrative sequence; no deployment result is implied.

Now change one feature only. Shorten the interval from sixty-four events to four. The business meaning, inputs, target and model width remain fixed. A plain recurrent network may learn the short version and fail the long one. The distant task is not merely “more data”. It composes the same state transition many more times, which changes both dynamics and optimisation.

The core answer is therefore precise. The past vanishes when the repeated state transition contracts the directions that carry useful information or useful gradient. Gates help because they introduce a controllable path whose local derivative can remain near one when retention is required, then move away from one when revision is required. They do not add an abstract faculty called memory. They alter the geometry of temporal transport.

Part one: the recurrent corridor

A feed-forward model sees an input and produces an output. A recurrent model also receives a summary of what it did one step earlier. Jeffrey Elman described this arrangement as a way to give a network a dynamic memory, representing time through its effect on ongoing processing rather than by allocating a separate input position to every moment.[1]

The basic update is compact:

ht = φ(Whht−1 + Wxxt + b)

xt is the current input, ht−1 is the previous hidden state, Wh and Wx are learned transformations, b is a bias, and φ is usually a nonlinear activation such as tanh.

The equation appears to put the entire past inside ht−1. That wording is dangerously generous. The hidden state is finite, continuously rewritten and useful only through the distinctions it preserves. A recurrent network has no independent archive of earlier states unless the surrounding system stores them. It carries one evolving compression.

Unroll the recurrence and the apparent loop becomes a deep computation with shared parameters. The hidden state at step 64 depends on the state at step 63, which depends on step 62, and so on. Backpropagation through time applies the chain rule to this unrolled graph. Werbos presented BPTT as an extension of backpropagation to dynamic systems; the central operation is the same derivative accounting used in ordinary networks, repeated along time.[2]

The loop becomes a corridor when training looks inside

Six recurrent states are connected forward from left to right. Inputs enter each state. A backward gradient path runs from the final loss towards the first state, crossing every local Jacobian. forward state transport backward credit transport h₀h₁h₂h₃h₄h₅ x₀x₁x₂x₃x₄x₅ J₅J₄J₃J₂J₁ final loss
Reading the diagramBlue circles: recurrent states from h₀ to h₅.Green arrows: forward state transport.Coral return path: backward credit from the final loss through J₅ to J₁.
Figure 2. An unrolled recurrent computation. Forward state and backward credit cross the same sequence of local transitions. The weights are shared, but the local Jacobian can differ at each step because inputs and activations differ. Conceptual figure.

A minimal scalar recurrence

Strip the system down to one number and remove new inputs after the first step:

ht = tanh(a ht−1)

Here a is the recurrent gain. The local sensitivity of the next state to the previous state is a(1 − tanh²(a ht−1)). Near zero, tanh is almost linear, so the multiplier is roughly a. Far from zero, tanh saturates and its derivative approaches zero. A weight of one does not therefore guarantee a derivative of one.

Suppose the effective local multiplier remains 0.9. One step retains 90 per cent of a small perturbation. After sixty-four steps, the retained fraction is 0.964, about 0.00118. The transition looked gentle locally. Composition made it severe.

This is the first durable intuition: temporal depth turns small local losses into large global amnesia. The same multiplication applies to the influence of an early state on a later state and to one important route by which gradient travels backwards.

Practitioner synthesis

Do not ask only whether the hidden state contains information under a probe. Ask whether changing the early cue changes the later decision, whether distractors can overwrite it, and whether the training loss can change the transition that first admitted it.

The argument in one passChart · flow
flowchart LR
  A["Opening case: the instruction<br/>at the start of the stream"] --> B["Part one, the recurrent corridor"]
  B --> C["Part two, why the past vanishes"]
  C --> D["Part three, what gates<br/>actually buy"]
  D -. "re-test" .-> A
  classDef first fill:#0a1424,stroke:#087A98,stroke-width:2px,color:#e6f3ff
  classDef step fill:#0a1424,stroke:#3f7da0,stroke-width:1px,color:#e6f3ff
  class A first
  class B,C,D step
A structural route through Recurrence, Gating and the Vanishing Past, from Opening case, the instruction at the… to Sources. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Part two: why the past vanishes

For a loss Lt at time t and an earlier hidden state hk, the chain rule gives a product of local Jacobians:

∂Lt/∂hk = (∂Lt/∂ht) · ∏j=k+1…t Jj

Jj = ∂hj/∂hj−1. In a tanh RNN it combines the recurrent matrix with the activation derivatives at step j.

A multidimensional Jacobian can contract some directions and expand others. The relevant question is not whether every matrix entry is small. It is how the product acts on the direction that carries the task-relevant perturbation. Repeated singular values below one shrink that direction. Repeated values above one expand it. Rotations can move a useful direction into a contracting one even when each individual step appears well behaved.

Bengio, Simard and Frasconi analysed why gradient-based learning becomes harder as temporal contingencies span longer intervals.[3] Pascanu, Mikolov and Bengio later described vanishing and exploding gradients from analytical, geometric and dynamical perspectives, and proposed gradient norm clipping as a practical response to explosion.[6] Clipping limits the size of an update after a gradient becomes large. It does not reconstruct a gradient that has already decayed towards zero.

Thought experiment 1: move the cue, change nothing else

Train two systems on the same binary decision. Both receive the same cue, the same distractor distribution, the same final query, the same labels and the same number of training examples. In system A, the cue arrives four steps before the query. In system B, it arrives sixty-four steps before. Only the gap changes.

If B fails while A succeeds, “the model lacks capacity” is incomplete. Both systems can represent a one-bit answer. The discriminating variable is the length and condition of the causal path. The experiment should therefore record sensitivity to the cue and gradient magnitude by lag, rather than reporting final accuracy alone.

Gradient half-life across time

Set an effective per-step carry factor for three paths. The chart displays qΔ, where Δ is lag. For LSTM and GRU this is the direct carry path under fixed gates, not the complete derivative of a learned cell.

A logarithmic chart of retained influence against time lag for plain recurrent, LSTM forget and GRU carry paths.
Chart key Horizontal axis: lag from zero to the selected maximum. Vertical axis: retained direct influence on a logarithmic scale from 1 to 10⁻⁶. Plain RNN, solid line LSTM direct path, dashed line GRU direct path, dotted line
RNN half-life6.58 steps
LSTM path half-life68.97 steps
GRU path half-life45.86 steps

A local multiplier is a temporal timescale

q = 0.90half-life 6.6
q = 0.95half-life 13.5
q = 0.98half-life 34.3
q = 0.99half-life 69.0
q = 0.999half-life 692.8
Figure 3. Gradient half-life. For a constant direct carry factor q between zero and one, the lag at which influence falls to one half is ln(0.5)/ln(q). Derived values; the full Jacobian of a learned recurrent unit can contain additional paths.

The half-life is useful, and incomplete

If a direct path multiplies by a constant q at every step, its half-life is:

H1/2 = ln(1/2) / ln(q)

As q approaches one from below, half-life grows sharply. Moving from 0.90 to 0.99 does not improve retention by eleven per cent. It changes the half-life from about 6.6 steps to about 69. This nonlinearity explains why a small gate-bias change can alter trainability over long delays.

The measure has boundaries. A real Jacobian varies by time, input and hidden direction. Several paths can add or cancel. A gate can depend on the state it is carrying. The full derivative may therefore differ from a simple product of displayed gate values. Half-life is an instrument for a declared path, not a certificate that the whole model remembers.

Three distinct ways to lose the past

Contraction reduces the magnitude of an old perturbation. Interference mixes later inputs into the same finite state, so an old distinction becomes unrecoverable even if norms remain large. Credit truncation stops the training graph before the relevant cause. Truncated BPTT can make a state observable at inference while preventing the distant loss from teaching the write decision that created it.

These failures require different remedies. Scaling or orthogonalising the recurrent transition addresses contraction. Gates can reduce interference by admitting some candidates and carrying old state around others. Longer unrolls, auxiliary losses or different supervision address missing credit. Calling all three “vanishing gradient” hides the design choice.

The failure surface has more than one axis

A contour map has retention on the horizontal axis and distractor admission on the vertical axis. A useful selective-memory region lies at high retention and low distractor admission. Other regions show forgetting, contamination and stale lock. selective memory carry old signal reject routine noise forgetting short carry path contamination distractors keep writing stale lock retains, cannot revise retention factor and temporal half-life → distractor admission → shortlong lowhigh
Reading the fieldLeft to right: shorter to longer retention.Bottom to top: lower to higher distractor admission.Regions: forgetting at lower left, contamination at upper left, stale lock at upper right, selective memory in the outlined right-hand pocket.
Figure 4. Retention alone is not useful memory. A model must preserve relevant state, block routine interference and still accept a superseding update. The regions are a design synthesis, not measured boundaries.

Negative control: when long memory is unnecessary

Consider a first-order temperature process whose next value depends on the current reading and current control input. Give a model the present state explicitly. A linear autoregression, a small feed-forward window or a plain RNN can be an adequate baseline. An LSTM may fit too, but success would not show that gating earned its cost.

This negative control matters because short tasks can make every recurrent architecture look like a memory system. If the target is Markov under the supplied state, long temporal credit is not the causal requirement. A memory claim needs a delay intervention that changes performance while holding the task semantics fixed.

Part three: what gates actually buy

Long short-term memory was introduced to address insufficient, decaying error flow in recurrent learning.[4] Its enduring idea is easier to see by ignoring the name and following the state path.

ct = ft ⊙ ct−1 + it ⊙ gt | ht = ot ⊙ tanh(ct)

The candidate gt proposes new content. The input gate it controls how much enters. The forget gate ft scales the old cell state. The output gate ot controls how much of the cell is exposed through the hidden state. Current PyTorch LSTM semantics implement this familiar four-part update.[15]

The cell update is additive. Old state has a direct route into new state instead of being forced through a complete nonlinear rewrite. Holding the gates fixed, the direct derivative from ct−1 to ct is ft. Across a delay, that route contains the product of forget gates. This is the adjustable near-identity path.

LSTM separates write, retain and reveal

An LSTM cell is drawn as a horizontal state rail. A forget gate controls the old state, an input gate controls candidate writing, and an output gate controls what is revealed as hidden state. cell-state rail c forgetfₜ inputiₜ × gₜ outputoₜ candidate write revealed hₜ old statenew state
Reading the cutawayTop teal rail: old cell state carried towards new cell state.Orange block: forget gate controlling carry.Indigo branch: input gate admitting a candidate write.Lavender branch: output gate revealing hidden state.
Figure 5. The LSTM cell-state cutaway. The drawing isolates the direct state path. In a learned LSTM the gates depend on input and hidden state, so total derivatives also include indirect routes. Architectural interpretation based on the standard equations.

The forget gate was not decorative complexity. Gers, Schmidhuber and Cummins introduced it to let continual LSTM systems reset internal state when sequence boundaries were not externally supplied.[5] A carry path without a revision mechanism can preserve obsolete information indefinitely. Forgetting is therefore part of useful memory, not its opposite.

Thought experiment 2: perfect retention, one superseding fact

Imagine a recurrent unit whose state transition is exactly the identity whenever no input arrives. It stores a maintenance flag for a thousand steps with no decay. Now insert a verified “maintenance complete” event at step 400. Keep every other property fixed.

If the unit has no selective update mechanism, perfect retention becomes stale lock. It either keeps the obsolete flag or must transform the entire state in a way that risks other stored distinctions. A gate can lower carry for the affected dimensions, admit the replacement and restore high carry afterwards. The causal benefit is not merely longer memory. It is conditional control over the timescale of each state component.

Gate values are time constants

A constant forget value near one produces a long direct half-life. A value near zero resets quickly. Tallec and Ollivier formalised a connection between learnable gates and robustness to time transformations, then proposed chrono initialisation to align gate biases with expected temporal dependencies.[13] The practical lesson is modest but consequential: gate bias is an architectural prior over duration.

A forget-gate bias of zero produces an initial sigmoid value of 0.5, whose direct half-life is one step. Learning can move it, but the distant signal needed to request that move may already be weak. Jozefowicz, Zaremba and Sutskever evaluated more than ten thousand recurrent architectures and reported that adding a bias of one to the LSTM forget gate closed a performance gap between their LSTM and GRU settings.[9] That result is task- and implementation-bounded, but it supports the mechanism: the initial timescale can change trainability.

GRU: carry and candidate in one state

The gated recurrent unit uses one exposed state rather than a separate cell and hidden state. In a common formulation:

ht = (1 − zt) ⊙ nt + zt ⊙ ht−1

The update gate zt interpolates between the old state and a new candidate nt. A reset gate controls how the previous state contributes while forming that candidate. Cho and colleagues introduced the GRU in an RNN encoder-decoder for statistical machine translation.[7] PyTorch’s documented GRU equations use the old-state coefficient zt, so the direct carry route again contains a product of gate values.[15]

A GRU update is a moving balance between old state and candidate

A balance beam interpolates between old hidden state and new candidate. Three marked gate values show rapid overwrite, balanced mixing and strong carry. candidate nₜ old state hₜ₋₁ z = 0.2rapid overwrite z = 0.5equal mixing z = 0.95strong carry hₜ = (1 − zₜ)nₜ + zₜhₜ₋₁
Reading the leverLeft: new candidate. Right: old state. Centre: update gate z.Small z favours rapid overwrite; large z favours strong carry; an intermediate value mixes both.
Figure 6. The GRU carry lever. Under fixed gates, the update is a component-wise interpolation. The reset gate shapes the candidate and can change how prior state participates in revision. Conceptual rendering of the standard equation.

It is tempting to turn LSTM and GRU into a universal ranking. The evidence does not support one. Chung and colleagues found gated units better than tanh units on their polyphonic music and speech tasks, with GRU comparable to LSTM.[8] Greff and colleagues compared eight LSTM variants across speech, handwriting and music, reporting that none significantly improved on the standard LSTM and that the forget gate and output activation were especially important in their study.[10] These are useful bounded results, not a law that one cell wins every sequence problem.

Published evidence

Architecture searches and matched task studies support three restrained claims. Gated cells often train more effectively than plain tanh recurrence on tasks with meaningful temporal dependencies. GRU can be competitive with LSTM. Initialisation plus a few critical components can matter as much as decorative variants.[8][9][10]

The strongest objection: gates are not the only path

A plain recurrent system can preserve long-range signal when its transition is designed around stable propagation. Le, Jaitly and Hinton showed that a ReLU RNN initialised with an identity or scaled identity recurrent matrix could be comparable to LSTM on their four benchmarks.[11] Arjovsky, Shah and Bengio constrained recurrence to a unitary transformation so eigenvalues had magnitude one, targeting vanishing and exploding gradients on long-memory tasks.[12]

More recently, Orvieto and colleagues showed that carefully designed linear, diagonal recurrent units with suitable parameterisation, initialisation and normalisation could match deep state-space models on the Long Range Arena benchmark while retaining recurrent inference.[14] This is a serious counterexample to any story in which gates uniquely “solve” recurrence.

Feng and colleagues pushed the same challenge in a different direction. By removing selected hidden-state dependencies from LSTM and GRU gates, they derived minimal cells whose associative updates can be parallelised during training and reported competitive results across their task suite.[16] The result does not establish a universal winner. It shows that useful gate semantics can survive substantial algebraic simplification.

The counterexample sharpens the thesis. Orthogonal or near-identity transitions preserve magnitude, but a system must also forget, select and revise. Gates offer one learnable way to vary timescale with content. Stable linear recurrence offers another design point, often paired with input-dependent selection elsewhere. The causal object is the controlled state-transition path, not the historical cell family.

Explicit failure boundary

Gating ceases to help under several conditions. The task may require random access to many separately addressable facts. Training may never supply credit across the required horizon, or gate saturation may block learning. The hidden state may be too small for the distinctions being compressed. Sequential training cost may also be the binding constraint. External state, attention, retrieval or modern state-space designs may then be the better mechanism.

Part four: a temporal memory acceptance test

Benchmark accuracy compresses several temporal behaviours into one number. A recurrent model can succeed by exploiting a short cue, fail only under distractors, retain obsolete state, or answer from the current input while ignoring the supposed memory. A useful test must intervene on the path.

The proposed acceptance test has four verbs. Write asks whether a relevant event changes the state. Retain asks whether its causal influence survives the required delay and routine interference. Revise asks whether a superseding event can replace it within an acceptable number of steps. Read asks whether the state changes the correct output only when the query requires it.

Retention curve R(Δ)
Intervene on an early cue and measure the change in a later output as lag Δ increases. Report the required P50, P95 and maximum horizon, not one convenient delay.
Interference susceptibility I
Hold the cue and lag fixed, then vary distractor count and amplitude. Measure how quickly causal margin or accuracy degrades.
Revision latency V
Insert a superseding event and count the steps until output reflects the new state. Excessive retention appears as a stale-state failure.
Read selectivity Q
Present matched queries that do and do not require the stored fact. A state that changes every output is entanglement, not selective use.

Controls that make the memory claim causal

A decoder probe can sometimes recover an old cue from hidden state even when the model’s own output ignores it. Decodability is therefore a weak pass condition. The decisive test keeps the current input fixed, changes only the earlier cue, and measures the late output. A stronger state-swap test takes two matched sequences with opposite cues, exchanges their recurrent states immediately before the query, and asks whether the answers exchange too. Stored information counts as functional memory only when intervening on its temporal carrier changes the decision.

Two shortcut controls should accompany that intervention. First, erase or permute the early cue across sequences. Performance should fall specifically on queries that require it. If performance survives, a later feature or label artefact may be carrying the answer. Second, train a current-window baseline that sees only the last few events. Matching performance means the declared long dependency was not necessary under the supplied representation, even if a recurrent probe can reconstruct the cue.

The learning path needs its own ablation. Train otherwise matched models with backward horizons shorter than, equal to and longer than the required delay. A sharp improvement when the horizon crosses the causal gap supports distant credit assignment as the mechanism. No change has several possible explanations: local supervision may already teach the write, a shortcut may bypass the old cue, or the optimiser may still fail to use the added path. Inspect cue intervention, state sensitivity and early-step gradient together before choosing among them.

These controls turn one benchmark score into a discriminating experiment. They can falsify the memory story while leaving accuracy unchanged, which is exactly why they belong in an acceptance test rather than an interpretability appendix.

Memory acceptance is a four-part envelope

Four curved petals labelled write, retain, revise and read surround a central acceptable-memory region. Failure examples sit outside each petal. acceptedtask-boundedtemporal memory write retain revise read cue ignoredpast fadesstale lockstate never used
Reading the envelopeTop: write. Right: retain. Bottom: revise. Left: read.The centre is accepted only when all four task-bounded tests pass.
Figure 7. The write-retain-revise-read test. Passing one petal is insufficient. The thresholds must come from the task’s temporal contract. New decision instrument developed for this article.

Run the RNN, LSTM and GRU challenge

The browser lab below isolates the direct retention mechanism. Each trial writes a cue of +1 or −1, passes it through a selected number of noisy steps, and asks for the cue’s sign at the end. The plain RNN uses a tanh recurrence. The LSTM-like and GRU-like paths use simplified fixed-gate carry equations. Freezing the gates makes the causal variable visible and keeps architecture search, parameter count and optimiser tuning out of the comparison.

This is a mechanism demonstration, not evidence that a trained LSTM or GRU will achieve the displayed score on a real task. The positive case uses a long carry factor and low distractor admission. The negative control shortens the dependency. The failure preset gives every path the wrong timescale.

Synthetic delayed-cue challenge

Bar chart showing delayed-cue accuracy and causal sensitivity for a plain RNN, an LSTM-like carry path and a GRU-like carry path.
Chart keyLeft, middle and right groups are plain RNN, LSTM-like and GRU-like. Filled bars show sign accuracy; dashed outlines show causal cue sensitivity.
Plain RNNaccuracy 0.503 · sensitivity 0.000
LSTM-likeaccuracy 1.000 · sensitivity 0.221
GRU-likeaccuracy 1.000 · sensitivity 0.221
Default result: over 5,000 deterministic synthetic trials, the plain path is near chance after 64 noisy steps while the two long-carry paths preserve the cue. Run the lab to recompute.
Reference run reproduced by the bundled Python script, seed 46, 5,000 trials
CasePathCarryHalf-life, stepsSign accuracyMedian cue sensitivity
64 noisy stepsPlain tanh RNN0.9006.580.4940.000072
LSTM-like direct path0.99068.971.0000.220737
GRU-like direct path0.99068.971.0000.220737
4 quiet stepsPlain tanh RNN0.9006.581.0000.097865
LSTM-like direct path0.99068.971.0000.403426
GRU-like direct path0.99068.971.0000.403426
64 steps, wrong timescalePlain tanh RNN0.9006.580.4940.000072
LSTM-like direct path0.9006.580.4950.000495
GRU-like direct path0.9006.580.4950.000495

The short case is the negative control. Every path recovers the cue, so gating has not earned a claim. The long noisy case isolates the value of a longer, cleaner carry path. The misgated case is equally important: adding gates while retaining a 0.90 timescale does not rescue the task.

The identical LSTM-like and GRU-like rows are deliberate. Once their gates are frozen and candidate details are removed, both reduce to the same scalar carry equation. At that level, the architecture label contains no extra causal information. Their learned behaviour differs because their gate networks, candidate construction and state exposure differ, which must be tested rather than assumed.

Runnable Python reference implementation

The script uses only the Python standard library. It includes the positive case, short negative control and misgated failure. Expected output matches the table above within exact deterministic arithmetic for the supplied seed.

#!/usr/bin/env python3
from __future__ import annotations
import argparse, math, random, statistics
from dataclasses import dataclass

@dataclass(frozen=True)
class Config:
    name: str
    carry: float
    noise_admission: float
    recurrence: str

def step(config: Config, state: float, x: float) -> float:
    if config.recurrence == "rnn":
        return math.tanh(config.carry * state + config.noise_admission * x)
    if config.recurrence in {"lstm", "gru"}:
        return config.carry * state + config.noise_admission * math.tanh(x)
    raise ValueError(config.recurrence)

def run(config: Config, delay: int, trials: int,
        noise_sd: float, seed: int) -> dict[str, float]:
    rng = random.Random(seed)
    correct, margins, sensitivities = 0, [], []
    eps = 1e-5
    for _ in range(trials):
        cue = 1.0 if rng.random() >= 0.5 else -1.0
        distractors = [rng.gauss(0.0, noise_sd) for _ in range(delay)]

        def final_state(cue_value: float) -> float:
            state = math.tanh(cue_value)
            for distractor in distractors:
                state = step(config, state, distractor)
            return state

        final = final_state(cue)
        correct += int((final >= 0) == (cue >= 0))
        margins.append(cue * final)
        derivative = (final_state(cue + eps) - final_state(cue - eps)) / (2 * eps)
        sensitivities.append(abs(derivative))

    return {
        "accuracy": correct / trials,
        "mean_margin": statistics.fmean(margins),
        "median_sensitivity": statistics.median(sensitivities),
    }

def half_life(q: float) -> float:
    return math.log(0.5) / math.log(q) if 0 < q < 1 else math.inf

def suite(delay: int, noise: float, trials: int,
          seed: int, misgated: bool):
    gated_carry = 0.90 if misgated else 0.99
    gated_noise = 0.10 if misgated else 0.02
    configs = [
        Config("plain RNN", 0.90, 0.12, "rnn"),
        Config("LSTM-like path", gated_carry, gated_noise, "lstm"),
        Config("GRU-like path", gated_carry, gated_noise, "gru"),
    ]
    return [(config, run(config, delay, trials, noise, seed))
            for config in configs]

def print_suite(title: str, results) -> None:
    print("\n" + title)
    print(f"{'model':18} {'carry':>7} {'half-life':>10} "
          f"{'accuracy':>10} {'margin':>10} {'sensitivity':>12}")
    for config, result in results:
        print(f"{config.name:18} {config.carry:7.3f} "
              f"{half_life(config.carry):10.2f} "
              f"{result['accuracy']:10.3f} "
              f"{result['mean_margin']:10.3f} "
              f"{result['median_sensitivity']:12.6f}")

def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--trials", type=int, default=5000)
    parser.add_argument("--seed", type=int, default=46)
    args = parser.parse_args()
    print_suite("Positive long-delay case: selective carry, 64 noisy steps",
                suite(64, 0.35, args.trials, args.seed, False))
    print_suite("Negative control: short dependency, four quiet steps",
                suite(4, 0.0, args.trials, args.seed, False))
    print_suite("Failure case: gates choose the wrong timescale",
                suite(64, 0.35, args.trials, args.seed, True))

if __name__ == "__main__":
    main()

A production-shaped worked scenario

Worked scenario

A synthetic equipment-monitoring service consumes a continuous event stream. A verified maintenance event should influence anomaly interpretation for thirty minutes, routine telemetry should not overwrite it, a maintenance-complete event should supersede it immediately, and the state should affect only decisions whose policy explicitly consults maintenance status.

The temporal contract exposes four different tests. The maintenance event must produce a measurable write. Across the observed event-rate distribution, its influence must remain above threshold for thirty minutes. A completion event must reduce the old influence and establish the new state within one event. Queries unrelated to maintenance should be invariant to the stored flag.

A useful recurrent state has an expiry and a revision path

A production event timeline shows maintenance start, routine telemetry, anomaly queries, a maintenance-complete supersession, and a verified external world-state record outside the recurrent hidden state. maintenance start routine telemetry anomaly query complete later query model state may carry maintenance context old state must no longer authorise interpretation authoritative event record and current world state remain external
Reading the timelineTop rail: model state may carry predictive maintenance context.Event line: start, routine telemetry, anomaly query, completion, later query.Coral rail: old state must stop influencing interpretation after completion.Bottom outline: authoritative event record and current world state remain external.
Figure 8. Model state versus authoritative state. Recurrence can support prediction, but a hidden vector is not an evidence ledger or world-state record. The scenario is synthetic and illustrates a production boundary.

This distinction prevents a category error. A recurrent hidden state is a model proposal about relevant history. It may be useful for classification or forecasting. It should not silently become the sole record that maintenance exists, has ended or may authorise an effect. The operational system still needs typed events, current world state, evidence and recovery outside the model.

Choose by temporal contract

Before selecting a recurrent cell, write the dependency as an engineering contract. State the distribution of required lags in domain time and event count. Name what writes state, what should be ignored, what supersedes it, when it is read, how training credit reaches the write, and whether the state is merely predictive or operationally authoritative.

Decision instrument: choose the cheapest mechanism that passes the temporal contract
Observed requirementBaseline to test firstEvidence that upgrades the mechanismLikely next choice
Current state is sufficient; short, smooth dynamicsLinear state model, fixed window or plain RNNDelay intervention stays inside measured half-life and revision is simpleKeep the simple baseline
Variable-duration state with selective writes and explicit revisionPlain or identity-initialised RNNDistractors overwrite state or long-lag gradient collapsesLSTM or GRU, selected by matched tests
Separate internal carry and controlled exposure matterGRURead timing or protected cell state improves the acceptance envelopeLSTM
Compact gated update is sufficient and latency mattersLSTMGRU matches retention, revision and quality under the same budgetGRU
Many discrete memories require content-addressed accessGated recurrenceState compression or query selectivity fails as item count growsAttention, retrieval or external state
Very long sequences require parallel trainingCanonical RNN, LSTM or GRUSequential dependency dominates cost despite acceptable qualityStructured state-space, convolutional or attention design

The architecture decision begins with how the past will be read

A two-dimensional decision map places mechanisms by temporal state complexity and read pattern. Plain recurrence occupies low complexity sequential reads, gated recurrence handles selective updates, and attention or retrieval handles content-addressed reads. plain recurrenceshort sequential state LSTM / GRUselective carry and revision attention / retrievalcontent-addressed read structured linear statevery long regular dynamics read pattern: sequential summary → content-addressed access state update complexity →
Reading the decision mapHorizontal: sequential summary towards content-addressed access.Vertical: increasing state-update complexity.Zones: plain recurrence at lower left, LSTM/GRU in the middle, structured linear state above left, attention/retrieval above right.
Figure 9. Temporal mechanism decision map. Boundaries are illustrative. The map changes the first question from “Which cell is best?” to “How must state be updated and later addressed?”

A fair RNN, LSTM and GRU comparison must also match more than hidden width. Under common implementations, LSTM computes four gate or candidate blocks per step, GRU computes three, and a plain RNN computes one. Equal width therefore means unequal parameter count and work. Equal parameter count means unequal state width. Report both, include tuning budget, and judge the temporal acceptance envelope against latency and memory cost.

Practical release rule

Do not release a recurrent component because its aggregate validation score is highest. Release it when the required lag distribution, distractor regime, supersession events and read conditions are represented in tests, and when the simpler temporal baseline fails under the same resource and tuning budget.

How the claim changes under pressureChart · state
stateDiagram-v2
  [*] --> Claim
  state "A minimal scalar recurrence" as Claim
  state "Thought experiment 1: move the<br/>cue, change nothing else" as Test
  state "Gradient half-life across time" as Revision
  Claim --> Test: expose mechanism
  Test --> Decision: evidence survives
  Test --> Revision: rival survives
  Revision --> Claim: narrow or rebuild
  Decision --> [*]
The revision loop begins with A minimal scalar recurrence and keeps counterexamples inside the reasoning path. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Compact glossary

Hidden state
The evolving finite vector passed between recurrent steps and exposed to later computation.
Cell state
The LSTM’s separate internal carry vector, updated additively through forget and input gates.
BPTT
Backpropagation through time, which differentiates an unrolled recurrent computation across a chosen horizon.
Jacobian
The local linear map from a small change in one state to the resulting change in the next.
Gate
A learned, usually sigmoid-valued control that scales carry, candidate admission, reset or exposure.
Gradient half-life
The lag at which a declared multiplicative gradient or influence path falls to half its initial magnitude.
Truncated BPTT
Training that stops the backward graph after a limited number of steps, reducing cost while excluding longer credit paths.
Derivation: why the direct LSTM path is only part of the derivative

From ct = ft⊙ct−1 + it⊙gt, treating the gates and candidate as fixed gives ∂ct/∂ct−1 = diag(ft). In a learned LSTM, the gates depend on ht−1, which depends on earlier cell state. The full derivative therefore includes terms through the gate networks and output path. The direct product of forget gates remains an interpretable route, but it is not the entire Jacobian.

Choose the path, then the cell

The phrase “an RNN remembers” hides the mechanism. A recurrent system repeatedly transforms a finite state. Every step can contract a useful direction, admit interference or cut the learning path that would have taught the model what to keep. The past survives only through a causal route that remains usable in both forward computation and backward credit.

LSTM and GRU made that route easier to control. Their gates can create long local time constants, block routine writes, revise selected dimensions and expose state when needed. This is why they often outperform plain tanh recurrence on meaningful sequence tasks. It is also why the forget or update bias, training horizon and distractor regime can matter more than the family name.

The strongest counterexamples improve the conclusion rather than weaken it. Identity, unitary and carefully parameterised linear recurrence show that magnitude-preserving transport does not require a classical gate. They also reveal what preservation alone omits: selective revision and content-dependent timescale. Attention and external state reveal a different boundary, where one compressed recurrent summary is the wrong addressing mechanism.

The architecture decision should therefore be made from a temporal contract and a failure injection, not from a diagram of cell internals. Measure write, retention, interference, revision and read selectivity at the lags the system will actually face. Keep a short-memory baseline. Match parameter, compute and tuning budgets. Withdraw the memory claim when the early cue does not causally change the late decision.

For the opening monitoring case, the changed design is concrete. The model may use gated recurrence to carry predictive context across routine events, but a superseding event must be able to revise it immediately, and authoritative maintenance state remains outside the hidden vector. The test suite varies the event gap, inserts distractors, forces a completion event and checks query-specific influence. That is a defensible reason to choose a recurrent mechanism. “LSTM remembers long sequences” is not.

The evidence conversationChart · sequence
sequenceDiagram
  participant Q as Question
  participant M as Mechanism
  participant E as Evidence
  participant D as Decision
  Q->>M: Opening case: the instruction at the start of the stream
  M->>E: A minimal scalar recurrence
  E-->>M: compare rival explanations
  E->>D: Sources
  D-->>Q: revise scope or act
Question, mechanism, evidence and decision exchange the burdens developed in Recurrence, Gating and the Vanishing Past. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Sources

  1. Jeffrey L. Elman, “Finding Structure in Time”, Cognitive Science, 1990.
  2. Paul J. Werbos, “Backpropagation Through Time: What It Does and How to Do It”, Proceedings of the IEEE, 1990.
  3. Yoshua Bengio, Patrice Simard and Paolo Frasconi, “Learning Long-Term Dependencies with Gradient Descent Is Difficult”, IEEE Transactions on Neural Networks, 1994.
  4. Sepp Hochreiter and Jürgen Schmidhuber, “Long Short-Term Memory”, Neural Computation, 1997.
  5. Felix A. Gers, Jürgen Schmidhuber and Fred Cummins, “Learning to Forget: Continual Prediction with LSTM”, Neural Computation, 2000.
  6. Razvan Pascanu, Tomas Mikolov and Yoshua Bengio, “On the Difficulty of Training Recurrent Neural Networks”, ICML, 2013.
  7. Kyunghyun Cho et al., “Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation”, EMNLP, 2014.
  8. Junyoung Chung et al., “Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling”, 2014.
  9. Rafal Jozefowicz, Wojciech Zaremba and Ilya Sutskever, “An Empirical Exploration of Recurrent Network Architectures”, ICML, 2015.
  10. Klaus Greff et al., “LSTM: A Search Space Odyssey”, IEEE Transactions on Neural Networks and Learning Systems, 2017.
  11. Quoc V. Le, Navdeep Jaitly and Geoffrey E. Hinton, “A Simple Way to Initialize Recurrent Networks of Rectified Linear Units”, 2015.
  12. Martin Arjovsky, Amar Shah and Yoshua Bengio, “Unitary Evolution Recurrent Neural Networks”, ICML, 2016.
  13. Corentin Tallec and Yann Ollivier, “Can Recurrent Neural Networks Warp Time?”, ICLR, 2018.
  14. Antonio Orvieto et al., “Resurrecting Recurrent Neural Networks for Long Sequences”, 2023.
  15. PyTorch documentation for RNN, LSTM and GRU.
  16. Leo Feng et al., “Were RNNs All We Needed?”, 2024.