Recurrent State-Space Models › Learning the Model: Posterior Inference and the ELBO
World Models HandbookAll chapters Recurrent State-Space Models › Learning the Model: Posterior Inference and the ELBOOne section · Sections in this chapter4 / 10 ↓
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
You now know what the parts are. This section explains how they are trained, and why the training objective has the peculiar two-part structure it does.
The filtering ELBO
Consider a single training sequence of observations and actions . The generative story is:
- Start from an initial belief ( can be a learned vector or fixed zeros, with the initial latent prior conditioned on it).
- For each : draw from the prior , emit from , then update .
The action-conditioned likelihood integrates over latent trajectories. For a general nonlinear neural model, that sum or integral is intractable; linear-Gaussian models are an important tractable exception. We use the filtering variational factorization , where each depends on earlier sampled latents. Jensen's inequality gives an evidence lower bound on the log likelihood. Written with all expectations visible, it is
The outer expectation averages over the earlier posterior draws that determine ; at there are no earlier latents. The inner expectation averages the current reconstruction likelihood. We estimate these expectations with a sampled trajectory, drawing , where is parameter-independent noise and . This reparameterization exposes a differentiable map from the mean and scale to the sample, so ordinary backpropagation supplies a pathwise Monte Carlo gradient under the usual differentiability and integrability conditions. The expected objective is a lower bound; an individual Monte Carlo estimate is not guaranteed to lie below the log likelihood.
Filtering uses only past and current observations. If a smoothing variational family contains this filtering family, its optimal ELBO cannot be lower, because it can use future observations too. That is a statement about the families' optima, not a promise about two fitted networks. One posterior trajectory is also not a particle filter with importance weighting and resampling. Finally, the decoder log density at a given sample may be analytic while its expectation through a nonlinear decoder is not. The conditional diagonal-Gaussian KL does have the closed form below; its outer expectation over earlier latent history is still estimated by sampling.
where:
- : shorthand for the posterior Gaussian , with mean and standard deviation along latent dimension
- : shorthand for the prior Gaussian , with mean and standard deviation
- : an index over the latent dimensions, so the sum runs over the coordinates of
The three summands divide the work: the log-scale ratio and normalized variance compare their widths, the normalized squared mean gap penalizes mean disagreement, and subtracts the posterior's expected standardized quadratic contribution. The terms cancel jointly: when the two Gaussians coincide the log ratio is zero and the variance term plus the constant sum to zero, so the divergence vanishes exactly when the two Gaussians coincide. This closed form is what the code below implements directly. Notice also the asymmetry of the divergence: because it is the KL with first, the prior's standard deviation appears in the denominator, so a prior that is too confident (small ) pays a steep price when the posterior disagrees with it. For distinct prior-head parameters under this posterior-sampled objective, the denominator punishes prior overconfidence steeply, and the KL is the only term whose gradient reaches the prior distribution's parameters (the mean and scale head of ; the reconstruction gradient still reaches the deterministic transition through the sampled ). Its gradient pulls the posterior toward the prior too. That is the collapse route the stabilizers below are designed to suppress.
The asymmetry is worth seeing as a curve rather than a formula.
import numpy as np
## KL( N(mu_q, 1) || N(mu_p, sigma_p) ) for a unit-width posterior, as the
## posterior mean mu_q moves away from the prior mean mu_p = 0, for several
## prior standard deviations. Fixed seed is not needed: the grid is
## deterministic.
gap = np.linspace(0.0, 3.0, 300)
prior_stds = np.array([0.25, 0.5, 1.0, 2.0])
kl_curves = {}
for sp in prior_stds:
kl_curves[sp] = np.log(sp) + (1.0 + gap**2) / (2.0 * sp**2) - 0.5prior sigma=0.25: KL at gap 1 = 14.11 nats, KL at gap 3 = 78.11 nats prior sigma=0.50: KL at gap 1 = 2.81 nats, KL at gap 3 = 18.81 nats prior sigma=1.00: KL at gap 1 = 0.50 nats, KL at gap 3 = 4.50 nats prior sigma=2.00: KL at gap 1 = 0.44 nats, KL at gap 3 = 1.44 nats

Read the vertical gap between the curves: at a mean gap of one, the narrowest prior already pays about 13.7 nats more than the widest one (14.11 versus 0.44) for the identical posterior. The KL direction therefore punishes prior overconfidence, which is exactly the behavior a dynamics-learning signal should have.
What each term teaches
The two terms have distinct jobs. Their traces can suggest where to investigate a broken training run, but do not uniquely identify a failing component.
The reconstruction term trains the posterior, decoder, and recurrent transition to make observations predictable. It encourages the posterior to encode current information that helps the decoder, but does not force use of every latent dimension. The current reconstruction has no dependency on : it is later losses that reward retaining useful information there. In this observation-only example, reconstruction is the direct incentive to encode observations; an agent with reward or other auxiliary heads would have additional incentives.
The KL term trains the prior and regularizes the posterior. Either distribution can move to reduce it. Its initial value and subsequent trend depend on both networks, so neither a large starting KL nor a monotonic decline is guaranteed. Residual KL is not sensor-noise variance. In a scalar exact Gaussian update with prior variance and measurement variance , expected information gain is , while innovation variance is . Increasing sensor noise can therefore decrease expected information gain while increasing innovation variance. Nats and squared observation units describe different quantities.
Posterior collapse, free nats, and KL balancing
Posterior collapse means the posterior stops using observation information beyond what the prior already supplies. Exact equality gives zero conditional KL, but zero KL alone does not prove useless prediction: the history may already explain the relevant observation. Collapse is harmful when the latent drops information needed for the task. Check observation dependence and prediction quality, rather than treating a low scalar KL as a complete diagnosis.
Collapse happens when the KL cost of encoding information exceeds the reconstruction benefit of using it. The ELBO literature developed several remedies, and the RSSM line uses two that you should know by name.
Free nats replace the per-step KL by . PlaNet and the original Dreamer use 3 nats; the cited DreamerV3 paper uses 1 nat. Below the threshold, this term is constant and supplies no gradient through either KL argument. It removes marginal regularization pressure in that region; it does not measure irreducible surprise or guarantee that the posterior uses the available capacity. A collapsed posterior equal to its prior also has a clipped value at the floor. We use a 1-nat threshold below and log both raw and clipped KL to keep these cases distinguishable. Reconstruction and shared upstream parameters can still change the distributions while the clipped KL's own gradient is zero.
KL balancing (DreamerV2, kept in DreamerV3): split the KL gradient by stopping gradients through one argument at a time:
where:
- and : shorthand for the per-step posterior and prior
- : stop-gradient, meaning the bracketed distribution is held fixed, so that term's gradient can only reach the other argument
- and : the loss weights. DreamerV2 introduced the balance with the factor , weighting the dynamics term four times the representation term; the DreamerV3 paper v2 applies loss scales of and to the two terms
Both terms are minimized alongside the negative reconstruction objective. The first differentiates through the prior argument with the posterior argument stopped; the second reverses those roles. Shared upstream parameters, including the recurrent context, may influence both distributions after an update. Larger dynamics coefficients emphasize direct prior-fitting gradients, but coefficient ratios are not gradient-norm ratios and do not guarantee an optimizer's outcome. The aim is to reduce the incentive to discard useful observation information merely to make matching easier. DreamerV3 reports results across its evaluated domains with a shared configuration and several coordinated design choices; that empirical result should not be attributed to KL balancing alone.
Loss units matter for both images and low-dimensional observations. A sum over many pixels differs from a mean over pixels, and the observation likelihood's scale determines reconstruction strength. For a fixed scalar Gaussian decoder variance , negative log likelihood equals squared error divided by , plus a parameter-independent constant. Thus squared error plus is, up to positive scaling and an additive constant, a Gaussian negative-ELBO objective with . Here corresponds to variance before clipping. Free-nat clipping modifies that objective; a learned variance would also introduce scale-dependent terms. Scalar loss magnitudes alone do not establish gradient dominance, especially when a large clipped term is locally constant.
The posterior-prior gap
During filtering, the posterior uses the currently available observation; during imagination, future states come from the prior. At fixed recurrent context , averaging over a specified observation distribution gives two terms: the mutual information between and under that joint distribution, plus the KL between the observation-averaged posterior and the prior. Consequently, expected KL upper-bounds that observation information but is not equal to it in general. It mixes useful or irrelevant encoded information with prior mismatch; it is not a direct measure of forecast error.
Keep observation-conditioned filtering and open-loop prediction separate when evaluating a model. The experiment below measures both; it does not train a policy or measure closed-loop decision usefulness. A good posterior reconstruction can coexist with poor imagination because observations supply information that an open-loop forecast lacks. Approximation and training failures can widen that difference too. A high held-out KL is a reason to investigate, not proof of a failed prior: check predictions, interval quality, and which observations change the inferred state.