Search

Search papers and lessons

Recurrent State Space Model

Level 4 · 12 min read

The recurrent state space model splits a latent state into a deterministic memory and a stochastic part, so a model can predict many possible futures in latent space and remember information over long horizons.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Architectures
  • Sign in to see your progress

TL;DR

A recurrent state space model (RSSM) is a sequence model for hidden dynamics. It keeps two kinds of state at each time step: a deterministic vector that a recurrent network carries forward, and a random vector that represents what is uncertain right now. Because the randomness is sampled from a distribution, the model can imagine several different futures, and because the deterministic part carries memory, it does not forget what happened several steps back.

Where you'll see it: the world model inside PlaNet, where an agent learns to plan from pixels by imagining action sequences in a compact latent space.

Intuition

Think of a video of a ball bouncing behind a curtain. You only see the ball when it is in view. To predict where it is, you need two things. You need a memory: "it was moving left and rising a moment ago." You also need an honest sense of doubt: "it could have bounced off the wall or kept going, and I cannot tell which yet." A plain recurrent network has the memory but gives one answer. A plain state space model has the doubt but tends to lose the memory, because each step only looks at the last hidden value.

The RSSM does both. It holds a deterministic memory h_t that a recurrent network updates from the previous step. It holds a random state s_t that is drawn from a distribution whose parameters depend on h_t. The random part can represent alternative futures. The deterministic part keeps the history that the random part does not have to store.

The model is built for planning. An agent that wants to choose actions must evaluate thousands of candidate action sequences at every step. Rendering a picture for each imagined step is too slow, so the RSSM predicts forward entirely in a small latent space. Images are only decoded when the model is trained, to give it a learning signal.

flowchart LR
  hPrev["h(t-1), s(t-1)"] -->|"RNN f"| h["h(t): deterministic memory"]
  a["a(t-1): action"] --> h
  h -->|"prior p(s(t) given h(t))"| s["s(t): stochastic state"]
  h --> r["reward r(t)"]
  s --> r
  s --> o["observation o(t)"]
  h --> o

The plot below shows why a single Gaussian is a natural choice for the stochastic part. A narrow posterior (the belief after seeing the current image) sits inside a wide prior (the belief before seeing it). The gap between the two is what the training loss measures.

−3−2−1012300.20.40.60.81sdensity
  • prior, sigma = 1
  • posterior, mean 1, sigma = 0.5
The posterior after seeing the observation is narrower and shifted. The training loss pulls the prior toward it.

The math

Write oto_t for the image at step tt, ata_t for the action, and rtr_t for the reward. The model has a hidden state sts_t and a deterministic memory hth_t. Its generative process is

ht=f(ht−1,st−1,at−1)st∼p(st∣ht)ot∼p(ot∣ht,st)rt∼p(rt∣ht,st)\begin{aligned} h_t &= f(h_{t-1}, s_{t-1}, a_{t-1}) \\ s_t &\sim p(s_t \mid h_t) \\ o_t &\sim p(o_t \mid h_t, s_t) \\ r_t &\sim p(r_t \mid h_t, s_t) \end{aligned}

Here ff is a recurrent neural network, so hth_t is a deterministic function of the whole history of states and actions. The stochastic state sts_t depends only on the memory, which is the prior or transition distribution. The observation and reward models are Gaussians whose means come from neural networks. In PlaNet the observation model has identity covariance, so its log-likelihood is a squared error up to a constant.

Why two parts instead of one

A purely stochastic model, the classic linear state space model in the form st∼p(st∣st−1,at−1)s_t \sim p(s_t \mid s_{t-1}, a_{t-1}), has one state that must carry all memory. Each step passes through a random draw, so information can be lost, and the optimiser has no easy way to set the variance to zero for the parts that should be remembered. A purely deterministic recurrent network has the opposite problem: it gives one answer and cannot represent several futures. Splitting the state gives the deterministic path the job of memory and the stochastic path the job of uncertainty. Recall that a recurrent network is good at carrying a summary forward, and that a latent variable model represents what is unknown with a distribution.

Inference: the encoder

The true posterior over sts_t given the images is intractable, because the transition is non-linear. So the model learns an encoder qq that approximates it. PlaNet uses the filtering posterior, which conditions only on the past and present:

q(st∣ht,ot)q(s_t \mid h_t, o_t)

The encoder is a diagonal Gaussian whose mean and variance come from a convolutional network applied to oto_t, combined with hth_t, followed by a feed-forward network. The paper stresses one design rule: all information from the observation must pass through the sampling step of the encoder. If oto_t could reach the decoder through a deterministic path, the model would learn to ignore the latent state and would not learn dynamics at all.

The training objective

The model is trained by maximising a variational lower bound on the log-likelihood of the observations, the same bound that appears in the variational autoencoder. Writing the reward terms out by analogy, the bound over a sequence of length TT is

ln⁡p(o1:T∣a1:T)≥∑t=1T(Eq(st∣ht,ot)[ln⁡p(ot∣ht,st)]−Eq(st−1∣ht−1,ot−1)[KL[q(st∣ht,ot) ∥ p(st∣ht)]])\ln p(o_{1:T} \mid a_{1:T}) \geq \sum_{t=1}^{T} \Big( \mathbb{E}_{q(s_t \mid h_t, o_t)}\big[\ln p(o_t \mid h_t, s_t)\big] - \mathbb{E}_{q(s_{t-1} \mid h_{t-1}, o_{t-1})}\Big[ \mathrm{KL}\big[ q(s_t \mid h_t, o_t) \,\|\, p(s_t \mid h_t) \big] \Big] \Big)

Read the two terms as follows. The first is a reconstruction term: how well the state explains the observation, measured by the observation likelihood. The second is a complexity term: how far the encoder's posterior moves away from the transition prior, measured by a KL divergence. The bound is the same ELBO that any latent variable model uses. The expectations are estimated with a single sample, and the sample is drawn with the Reparameterization Trick so that gradients can flow through it.

The KL term in one dimension

For two univariate Gaussians q=N(μ1,σ12)q = \mathcal{N}(\mu_1, \sigma_1^2) and p=N(μ2,σ22)p = \mathcal{N}(\mu_2, \sigma_2^2), the KL divergence has a closed form:

KL(q ∥ p)=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12\mathrm{KL}(q \,\|\, p) = \ln\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}

This is what the RSSM computes at every step, with vectors instead of scalars and diagonal covariances.

Latent overshooting

The paper points out a limitation of the bound above. The prior p(st∣ht)p(s_t \mid h_t) receives gradient only through one-step KL terms, so its multi-step predictions are not trained directly. PlaNet therefore proposes latent overshooting: a generalised bound that adds KL terms for predictions dd steps ahead, computed in latent space, with no decoding. The overshooting variant is compatible with any latent sequence model, but the authors report that the final RSSM agent does not need it. Treat it as an optional regulariser, not part of the core model.

Worked examples

Example
Two Gaussians, by hand

Let the posterior be q=N(1,0.52)q = \mathcal{N}(1, 0.5^2) and the prior be p=N(0,1)p = \mathcal{N}(0, 1). So μ1=1\mu_1 = 1, σ1=0.5\sigma_1 = 0.5, μ2=0\mu_2 = 0, σ2=1\sigma_2 = 1.

  1. Log-ratio of standard deviations: ln⁡(σ2/σ1)=ln⁡(1/0.5)=ln⁡2≈0.6931\ln(\sigma_2 / \sigma_1) = \ln(1 / 0.5) = \ln 2 \approx 0.6931.
  2. Numerator of the quadratic term: σ12+(μ1−μ2)2=0.25+1=1.25\sigma_1^2 + (\mu_1 - \mu_2)^2 = 0.25 + 1 = 1.25.
  3. Divide by 2σ22=22 \sigma_2^2 = 2: 1.25/2=0.6251.25 / 2 = 0.625.
  4. Subtract one half: 0.6931+0.625−0.5=0.81810.6931 + 0.625 - 0.5 = 0.8181.

So KL(q ∥ p)≈0.818\mathrm{KL}(q \,\|\, p) \approx 0.818 nats. Interpretation: the posterior is both narrower and shifted, and the penalty in the training loss is about 0.82 nats for this one step. If the posterior equalled the prior, the same formula gives exactly 0, which matches the fact that KL is zero only when the two distributions are equal.

Example
One step of a toy RSSM, scalar version

Take a model with a scalar memory and a scalar stochastic state. Suppose the memory is ht=0.8h_t = 0.8, the encoder sees an observation with which it infers a posterior q(st)=N(1.0,0.25)q(s_t) = \mathcal{N}(1.0, 0.25) (variance 0.25), and the prior from the transition model is p(st∣ht)=N(0.6,1.0)p(s_t \mid h_t) = \mathcal{N}(0.6, 1.0). These numbers are illustrative, chosen to be hand-computable; they are not taken from a trained model.

  1. KL term: means differ by 1.0−0.6=0.41.0 - 0.6 = 0.4, so (μ1−μ2)2=0.16(\mu_1 - \mu_2)^2 = 0.16. Variances: σ12=0.25\sigma_1^2 = 0.25, σ22=1\sigma_2^2 = 1. The formula with σ1=0.5\sigma_1 = 0.5 and σ2=1\sigma_2 = 1 gives ln⁡2+(0.25+0.16)/2−0.5=0.6931+0.205−0.5=0.3981\ln 2 + (0.25 + 0.16) / 2 - 0.5 = 0.6931 + 0.205 - 0.5 = 0.3981 nats.
  2. Reconstruction term: suppose the decoder predicts the observation to be μ=0.8\mu = 0.8 with unit variance, and the observed value is o=1.0o = 1.0. The log-likelihood of a unit-variance Gaussian is −12(o−μ)2−12ln⁡(2π)-\tfrac{1}{2}(o - \mu)^2 - \tfrac{1}{2} \ln(2\pi). So −12(0.04)−12(1.8379)=−0.02−0.9189=−0.9389-\tfrac{1}{2}(0.04) - \tfrac{1}{2}(1.8379) = -0.02 - 0.9189 = -0.9389 nats.
  3. Per-step contribution to the bound: reconstruction minus KL, −0.9389−0.3981=−1.3370-0.9389 - 0.3981 = -1.3370 nats.

Interpretation: the bound is a sum of these per-step numbers over the sequence. Training pushes the sum up, which means better reconstructions with a posterior that does not stray far from what the memory predicts. The unit-variance reconstruction term is the squared error 0.040.04 in disguise, which is why the paper can say the observation loss is "mean squared error up to a constant".

Tradeoffs and failure modes

The RSSM is useful when you need to plan or imagine many steps ahead and cannot afford to decode images at each step. It is not free of problems.

SituationProblemBetter choice
Observations are low-dimensional and fully observedThe latent machinery is more than the task needsA plain feedforward dynamics model, or [[recurrent-neural-network
The future is essentially deterministicThe stochastic path adds variance that the data does not justifyA deterministic recurrent model
Very long horizons with a fixed encoderThe prior drifts, and the agent plans against its own errorsLatent overshooting, or a model trained with multi-step losses
Need precise pixel predictionsLatent states do not preserve every detailObservation decoding at every step, paid for in compute
Data is scarceThe KL term can collapse the posterior onto the prior, so the latent carries little informationStronger reconstruction weight, free-bits style constraints, or a simpler state

The most common failure is the planner exploiting model errors. If the model is wrong about some action sequence, a planner that searches thousands of sequences will find that sequence, because it looks good under the model. The stochastic part reduces this by representing alternatives, but it does not remove it. The deterministic memory also means that errors accumulate along the recurrence, so the model should be checked on predictions many steps ahead, not only one step.

Compared with a structured state space model such as those used in modern long-sequence architectures, the RSSM has a non-linear transition and a learned encoder. That makes it more expressive, and makes exact inference impossible. The structured models keep the transition linear so that sequences can be processed in parallel. You trade expressiveness for speed.

History

Classical state space models and the latent variable view of dynamics date back to filtering theory, where the Kalman filter is the linear-Gaussian case. In the mid-2010s, researchers combined the same structure with neural networks. Chung and colleagues (2015) added a deterministic recurrent path to a variational sequence model, which the PlaNet authors cite for the same idea of a deterministic path alongside stochastic latents. Karl and colleagues (2016) and Buesing and colleagues (2018) built related latent dynamics models that were trained with variational methods.

Hafner and colleagues applied the RSSM to planning from pixels in PlaNet, in 2018. Their central observation was that a purely stochastic transition forgets too much and a purely deterministic one cannot express uncertainty, so both parts are needed. In PlaNet the agent plans with the cross entropy method, evaluating candidate action sequences by rolling them forward in the RSSM.

Check yourself

QuestionRecall: what is the job of the deterministic state hth_t in the RSSM, and what is the job of the stochastic state sts_t?Show answer

The deterministic state hth_t is updated by a recurrent network from ht−1h_{t-1}, st−1s_{t-1} and at−1a_{t-1}, so it carries memory of the whole history. The stochastic state sts_t is sampled from a distribution that depends on hth_t, so it represents uncertainty about what is true now and lets the model hold several possible futures. Memory and uncertainty are split between the two parts, which is the design choice that PlaNet reports as crucial.

QuestionComputation: the posterior is q=N(0,0.52)q = \mathcal{N}(0, 0.5^2) and the prior is p=N(0,1)p = \mathcal{N}(0, 1). What is KL(q ∥ p)\mathrm{KL}(q \,\|\, p)?Show answer

Here the means are equal, so μ1−μ2=0\mu_1 - \mu_2 = 0. The standard deviations are σ1=0.5\sigma_1 = 0.5 and σ2=1\sigma_2 = 1. Then ln⁡(σ2/σ1)=ln⁡2≈0.6931\ln(\sigma_2 / \sigma_1) = \ln 2 \approx 0.6931. The quadratic term is (σ12+0)/(2σ22)=0.25/2=0.125(\sigma_1^2 + 0) / (2 \sigma_2^2) = 0.25 / 2 = 0.125. Sum: 0.6931+0.125−0.5=0.31810.6931 + 0.125 - 0.5 = 0.3181 nats. The answer is about 0.318 nats.

QuestionWhy does the RSSM route all observation information through the sampling step of the encoder?Show answer

If the observation could reach the reconstruction through a deterministic path from the encoder, the decoder could be fed the answer directly, and the latent state would not need to represent the dynamics. The model would then learn a shortcut that does not generalise to prediction, where no observation is available. Forcing the information through a sample keeps the stochastic state responsible for explaining what is seen.

QuestionApplied: you train an RSSM world model and the planner picks action sequences that look excellent in imagination but perform poorly in the real environment. Name two causes you would check first and what you would change for each.Show answer

First, the model may be inaccurate for the action sequences the planner favours, which the planner exploits by searching many candidates. Check the model's multi-step prediction error on held-out data, and collect more experience with those kinds of actions. Second, errors may accumulate over a long planning horizon. Check the prediction error at increasing horizons, and consider a shorter planning horizon with replanning at each step, which is what PlaNet does with model predictive control. Either fix targets the mismatch between imagination and reality, not the planner itself.

QuestionWhy might the KL term collapse, and what does it look like in the numbers?Show answer

If the decoder is powerful enough to reconstruct the observation from the deterministic state alone, the encoder has no incentive to put information in sts_t, so the posterior matches the prior and the KL term goes to zero. In the numbers, the reconstruction term stops improving while the KL stays near zero, which means the latent carries little information. The usual remedies are to limit the information the KL term can leave unpenalised, or to adjust the weight of the reconstruction term.

Sources