Temporal State and Memory › Recurrent Memory

Michael BrenndoerferJune 16, 202612 min read
World Models HandbookAll chapters
Part 3 of 12Representing Agents and Worlds
Chapter 16Temporal State and Memory › Recurrent Memory
Reading section 4 of 12 · Recurrent Memory · 12 minSection 4 of 12 · 12 min

Book contents

Section 4 of 12 · 12 min read

Temporal State and Memory › Recurrent MemoryOne section · Sections in this chapter4 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Recurrent networks are a standard learned answer to the compression problem: a fixed-size state updated one step at a time. This section covers how recurrence works, why plain recurrence can struggle over long horizons, and how gated architectures provide a more direct retention path.

Recurrence as Learned Compression

The workhorse solution is a recurrent state: a fixed-size vector hth_t updated step by step,

ht=fθ(ht−1, ot, at−1),h_t = f_\theta(h_{t-1},\, o_t,\, a_{t-1}),

where:

  • hth_t: the recurrent state at time tt, a fixed-size vector summarizing the history
  • ht−1h_{t-1}: the previous recurrent state, carrying everything absorbed so far
  • oto_t: the current observation
  • at−1a_{t-1}: the action taken at the previous step
  • fθf_\theta: a neural network, with parameters θ\theta, that decides how to merge the new observation and the last action into the running summary

Everything the model "knows" about the past lives in hth_t; the history itself is discarded after being absorbed. This is the compression decision in its purest form: one fixed-size vector stands in for an arbitrarily long past, and the network fθf_\theta is the sole arbiter of what makes it into the summary. Prediction then proceeds from the recurrent state:

o^t+1=gϕ(ht,at),r^t+1=qϕ(ht,at),\hat{o}_{t+1} = g_\phi(h_t, a_t), \qquad \hat{r}_{t+1} = q_\phi(h_t, a_t),

where:

  • o^t+1\hat{o}_{t+1}: the predicted next observation (the hat marks a prediction, as opposed to the observed ot+1o_{t+1})
  • r^t+1\hat{r}_{t+1}: the predicted next reward
  • gϕg_\phi: the observation head, a network with parameters ϕ\phi mapping the recurrent state and a candidate action to the next-observation prediction
  • qϕq_\phi: the reward head, mapping the same inputs to the predicted reward
  • hth_t: the recurrent state defined above
  • ata_t: the action whose consequences are being predicted

Notice that the prediction heads condition on both the recurrent state and the proposed action. They therefore produce action-conditional predictions, and a planner can compare candidate actions by running the heads. Interpreting those predictions as causal consequences additionally requires the data and model to identify the effects of intervening on the action. A policy or planner can operate on the same hth_t. This is exactly the structure of the recurrent state-space models we will build in detail in Part V, Chapter 1; here we focus on the memory inside the recurrence, not the full world-model architecture.

Conceptually, a recurrent network is doing online compression: at every step it decides, implicitly, which parts of the new observation to merge into the running summary and which parts of the old summary to discard. The compression is shaped by the training objective and data. When trained for the role, hth_t can approximate a belief-like filter, a running integral, or a short-term buffer. The catch is that nothing in the architecture guarantees retention over the task horizon. Gated architectures provide a more direct retention path, but optimization must still learn when to use it.

The Long-Range Gradient Problem

To see why plain recurrence struggles, consider what training demands. If the correct action at step TT depends on a cue at step 00, then the loss at step TT must send gradients back through every intermediate hidden state. Learning to preserve the cue means learning weight values for which the cue's influence survives that chain, and whether such weights are discoverable by gradient descent depends on the geometry of the chain itself. For a simple recurrent update ht=tanh⁡(Wht−1+Uxt)h_t = \tanh(W h_{t-1} + U x_t), the derivative of the final state with respect to the initial state is a product of Jacobians:

Jt=∂ht∂ht−1,∂hT∂h0=JTJT−1⋯J1.J_t = \frac{\partial h_t}{\partial h_{t-1}}, \qquad \frac{\partial h_T}{\partial h_0} = J_T J_{T-1} \cdots J_1.

where:

  • h0h_0: the hidden state at the step where the cue arrives
  • hTh_T: the hidden state at the step where the loss is computed
  • Jt=∂ht/∂ht−1J_t = \partial h_t / \partial h_{t-1}: the Jacobian of recurrent step tt, the matrix of partial derivatives describing how each component of ht−1h_{t-1} influences each component of hth_t
  • JTJT−1⋯J1J_T J_{T-1} \cdots J_1: the ordered product of these TT matrices, with the latest step on the left, chaining the cue's influence from step 00 to step TT
  • xtx_t: the input at step tt (for a world model, typically the current observation together with the last action)
  • WW: the recurrent weight matrix, multiplying the previous hidden state ht−1h_{t-1}
  • UU: the input weight matrix, multiplying xtx_t

For matrix-valued, time-varying Jacobians, growth depends on the product's singular directions as well as the norm of each factor. A useful bound is

∥JTJT−1⋯J1∥≤∏t=1T∥Jt∥.\left\lVert J_T J_{T-1} \cdots J_1 \right\rVert \leq \prod_{t=1}^{T} \left\lVert J_t \right\rVert.

Thus uniformly contractive factors are sufficient for decay, while factors with norm above one make growth possible but do not force it: directions can rotate, contract, or cancel. The scalar constant-gain model below isolates the basic effect. If every step multiplies a scalar signal by ρ\rho, its magnitude after TT steps is ∣ρ∣T|\rho|^T: it decays when ∣ρ∣<1|\rho| < 1, stays constant when ∣ρ∣=1|\rho| = 1, and grows when ∣ρ∣>1|\rho| > 1. Over 50 steps, 0.950≈0.005150.9^{50} \approx 0.00515, about 0.515 percent of the initial magnitude.

We can make the scalar approximation concrete with a simple computation. The plot shows decay (ρ=0.9\rho = 0.9), constancy (ρ=1.0\rho = 1.0), and growth (ρ=1.1\rho = 1.1) over 50 steps. It illustrates repeated scalar gain, not the exact behavior of every recurrent Jacobian product.

In[3]:
Code
import numpy as np

horizons = np.arange(1, 51)
rho_values = [0.9, 1.0, 1.1]
grad_norms = {rho: rho ** horizons.astype(float) for rho in rho_values}
Out[4]:
Visualization
Log-scale line chart of gradient magnitude versus horizon for rho values 0.9, 1.0, and 1.1.
Illustrative scalar gradient magnitude rho^T across a recurrent chain. With rho = 0.9 the signal falls below one percent within fifty steps; rho = 1.0 remains constant; and rho = 1.1 grows. Matrix-valued recurrent Jacobians need not follow one fixed scalar gain.

In this scalar illustration, a ten-percent change around one produces orders-of-magnitude differences over a corridor-length span. Gated additive updates are a widely used way to give optimization a controllable near-identity path. They make long-range retention easier to learn, but they are not necessary: other recurrent parameterizations and explicit memory mechanisms can also preserve long dependencies.

Without such a path, the network may need to learn retention through the same long Jacobian chain that attenuates its training signal.

Gating: Additive Memory Channels

Long short-term memory (LSTM) networks and gated recurrent units (GRUs) attack the problem by changing the shape of the update. Instead of always overwriting the state through a squashing nonlinearity, they introduce an additive channel guarded by learned gates. The key insight is that an additive update, one that adds new content to old content rather than replacing it, provides a gradient path whose gain can be held near one, so information can flow across many steps without exponential decay. For an LSTM, the core equations are:

it=σ(Wixt+Uiht−1+bi)(input gate)ft=σ(Wfxt+Ufht−1+bf)(forget gate)c~t=tanh⁡(Wcxt+Ucht−1+bc)(candidate)ct=ft⊙ct−1+it⊙c~t(cell state)ωt=σ(Woxt+Uoht−1+bo)(output gate)ht=ωt⊙tanh⁡(ct)\begin{aligned} i_t &= \sigma(W_i x_t + U_i h_{t-1} + b_i) & &\text{(input gate)}\\ f_t &= \sigma(W_f x_t + U_f h_{t-1} + b_f) & &\text{(forget gate)}\\ \tilde{c}_t &= \tanh(W_c x_t + U_c h_{t-1} + b_c) & &\text{(candidate)}\\ c_t &= f_t \odot c_{t-1} + i_t \odot \tilde{c}_t & &\text{(cell state)}\\ \omega_t &= \sigma(W_o x_t + U_o h_{t-1} + b_o) & &\text{(output gate)}\\ h_t &= \omega_t \odot \tanh(c_t) & & \end{aligned}

where:

  • xtx_t: the input at step tt, for a world model typically the current observation together with the last action
  • ht−1h_{t-1}: the previous hidden state, the network's working output
  • ctc_t: the cell state, the protected long-term memory carried across steps
  • c~t\tilde{c}_t: the candidate value, a proposal for new information to write into the cell state
  • iti_t: the input gate, controlling how much of the candidate is written into the cell state
  • ftf_t: the forget gate, controlling how much of the previous cell state survives
  • ωt\omega_t: the output gate, controlling how much of the cell state is exposed as the hidden state (written ωt\omega_t rather than the conventional oto_t to avoid clashing with the observation symbol used elsewhere in this chapter)
  • hth_t: the new hidden state, the gated readout of the cell state
  • σ\sigma: the logistic sigmoid, which maps any real number to (0,1)(0, 1) so each gate acts as a soft switch
  • ⊙\odot: elementwise multiplication
  • Wi,Wf,Wc,WoW_i, W_f, W_c, W_o and Ui,Uf,Uc,UoU_i, U_f, U_c, U_o: weight matrices acting on the input and on the previous hidden state; bi,bf,bc,bob_i, b_f, b_c, b_o: their bias vectors

Look at the cell-state update ct=ft⊙ct−1+it⊙c~tc_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t. It is a residual update: when the forget gate ftf_t is near 11 and the input gate iti_t near 00, information flows through the direct cell-state branch nearly unchanged. Across several such steps, the direct gain is the product of the forget gates, so quantitative retention still depends on how close each gate remains to one. In the corridor, the desired behavior is to write the cue at step 0, preserve it during the featureless walk, and expose it at the decision point. Because the gates depend on the input and hidden state, gradient-based training can learn a write-and-retain policy, provided the objective supplies a useful signal.

The GRU is a streamlined variant with a single update gate ztz_t and a reset gate rtr_t:

zt=σ(Wzxt+Uzht−1)(update gate)rt=σ(Wrxt+Urht−1)(reset gate)h~t=tanh⁡(Wxt+U(rt⊙ht−1))(candidate)ht=(1−zt) ht−1+zt h~t(new state)\begin{aligned} z_t &= \sigma(W_z x_t + U_z h_{t-1}) & &\text{(update gate)}\\ r_t &= \sigma(W_r x_t + U_r h_{t-1}) & &\text{(reset gate)}\\ \tilde{h}_t &= \tanh(W x_t + U (r_t \odot h_{t-1})) & &\text{(candidate)}\\ h_t &= (1 - z_t)\, h_{t-1} + z_t\, \tilde{h}_t & &\text{(new state)} \end{aligned}

where:

  • ztz_t: the update gate, blending how much of the old state is kept versus replaced by the candidate
  • rtr_t: the reset gate, controlling how much of the old state the candidate can consult
  • h~t\tilde{h}_t: the candidate hidden state, the proposed new content
  • Wz,Wr,WW_z, W_r, W and Uz,Ur,UU_z, U_r, U: weight matrices acting on the input and on the previous state (biases omitted for brevity)
  • σ\sigma and ⊙\odot: the logistic sigmoid and elementwise multiplication, as in the LSTM equations

Notice that the GRU hidden state itself now has the residual form: the update ht=(1−zt)ht−1+zth~th_t = (1 - z_t) h_{t-1} + z_t \tilde{h}_t is an interpolation between keeping and replacing, so the direct "keep" branch has gain 1−zt1 - z_t. The GRU merges the LSTM's separate cell and hidden states into one, using three affine gate/candidate groups where the displayed LSTM uses four. Which architecture performs better is task-dependent. The LSTM's output gate controls how much cell content is exposed as hth_t, but it does not isolate the cell completely: hth_t feeds the next step's gates and candidate, so noisy exposed state can still influence ct+1c_{t+1} indirectly.

Fast and slow state

It is often useful to give the model two coupled recurrent states: a fast state updated every step (carrying recent context) and a slow state updated rarely or with strong damping (carrying cues and integrals). This is the architectural answer to the tension we identified in "What Must Survive the Compression": rather than forcing one vector to serve constancy, accumulation, and turnover simultaneously, give each dynamical role its own compartment and couple them. Hierarchical recurrent models make this split explicit, updating the slow state every kk steps or on event boundaries, which also shortens the gradient path each timescale must span. The same idea reappears in modern state-space models with multi-timescale dynamics, covered in Part V, Chapter 2.

Training Practicalities That Shape Memory

Two training choices quietly influence how good the learned memory is. They are easy to overlook because they do not appear in the architecture diagram:

  • Truncated backpropagation through time (TBPTT). Unrolled gradients are cut at a window of length KK, so a loss cannot assign credit directly through more than KK recurrent transitions. This is not a hard bound on forward memory: hidden state can be carried across windows, and shorter-range or auxiliary losses can teach a retention rule that generalizes farther. But a terminal-only 50-step dependency receives no direct cue-to-loss gradient when K=20K=20, which can make it difficult to learn. Treat KK as a credit-assignment limit and test retention at the horizon the task needs.
  • Scheduled or curriculum length. Training first on shorter episodes and then extending the horizon can help optimization. One plausible explanation is that shorter examples first establish useful update behavior, which longer examples then refine. That mechanism is a hypothesis unless an ablation separates it from data ordering, regularization, and other optimization effects.

A related trap: if observations occasionally contain the needed cue deterministically and observably, the model can learn memory. If the cue is buried in noise, or appears only under rare action sequences, the data distribution itself may never teach the gates to open. Memory learning is a joint property of architecture, gradient budget, and data distribution. When a memory model fails, before concluding that the architecture is inadequate, check whether the training signal demanded retention, and check whether the truncation window ever spanned the dependence in question.