Sign in

Vision

World Models vision (V model): Variational Autoencoder (VAE)

The V model of World Models: a variational autoencoder that compresses each frame into a short latent vector the rest of the agent works with.

Overview

A frame has thousands of numbers, but what matters in it can often be said in a few: where things are and how they are arranged. The vision model learns that short description by itself. An encoder squeezes the frame into a small vector, a decoder tries to redraw the frame from the vector, and both are trained so the redrawing is close. A plain autoencoder could scatter its codes anywhere. The variational version adds noise to each code and a penalty that keeps codes near the origin, so nearby codes decode to similar frames. The memory and controller models never see pixels, only this code. This template uses small dense networks where the paper uses convolutions on 64 by 64 colour frames.

A short history

Diederik Kingma and Max Welling introduced the variational autoencoder in 2013, and Danilo Rezende and colleagues developed a closely related method at the same time. It trains an encoder and a decoder together so that data is compressed into a smooth latent space. In 2018 David Ha and Jürgen Schmidhuber used a convolutional VAE as the vision part of World Models, compressing each game frame into a short vector so that the memory model and controller never handle pixels.

How it works

  1. VAE.encode flattens a frame and maps it through one tanh hidden layer to two vectors: a mean and a log variance for the latent code.
  2. During training a code is sampled as the mean plus noise scaled by the standard deviation. Writing it this way lets gradients reach the encoder.
  3. decode maps the code through one tanh hidden layer and a sigmoid to a reconstructed frame with values between 0 and 1.
  4. loss_and_grads adds the squared reconstruction error to the KL term, which measures how far the code's distribution is from a standard normal.
  5. The KL of a frame is not pushed below kl_tolerance * latent_size. Under that floor its gradient is switched off, so the code keeps some room to carry information.
  6. fit takes Adam steps on random minibatches. Afterwards, use the mean from encode as the code zz for the memory and controller models.

Watch out for

  • The model is trained to reconstruct everything in the frame, not what matters for reward. A small object that decides the task can be lost while a large irrelevant background is kept.
  • With the KL weight too high, or the free-bits floor set to zero, the encoder can ignore the frame and output the prior for every input, so all codes look alike and the reconstructions are one blurry average.
  • A model trained only on frames from a random policy has never seen the states a good policy reaches, and it encodes those poorly.
  • Squared error averages over uncertainty, so reconstructions are blurry. Sharp fine detail is the first thing lost.
  • The dense layers here suit small frames such as 8 by 8. On larger images they need far more weights and data than a convolutional encoder.

Use cases

When to use it

Use it as the first stage of a World Models agent, or wherever a compact, smooth code of small images is needed. Train it on frames from random rollouts, then pass the mean from encode to the later stages.

In industry

Games and simulation
Compressing game frames into a few dozen numbers so that a small policy can be trained on them.
Robotics
Turning camera images into compact state vectors that a control policy or a dynamics model can use.
Image generation
Variational autoencoders supply the compressed latent space in which latent diffusion image generators operate.

Choosing it: what must hold

  • A set of frames that covers what the agent will see, since the encoder cannot represent scenes it never trained on.
  • Details that matter for the task are large enough to survive compression, because small objects can vanish in the reconstruction.
  • Image observations: for low-dimensional state vectors the compression step is unnecessary.

When to choose something else

IfUse instead
Observations are already short state vectorsAn MLP encoder from the shared networks lesson
Small, task-critical details are lost in reconstructionA model trained on reward and value instead of pixels, as in MuZero
You want an end-to-end agent from pixels without a separate vision stageDQN or PPO with a convolutional encoder

Math foundations

  1. The encoder's output

    qϕ(z∣x)=N ⁣(μϕ(x),  diag⁡ σϕ2(x)),σϕ2=exp⁡(ℓ)q_\phi(z \mid x) = \mathcal{N}\!\big(\mu_\phi(x),\; \operatorname{diag}\,\sigma_\phi^{2}(x)\big), \qquad \sigma_\phi^{2} = \exp(\ell)

    For each frame the encoder gives a small cloud of possible codes, not a single point. The network outputs the log variance ℓ\ell, which may be any real number, and the variance is its exponential.

  2. The reparameterized sample

    z=μ+exp⁡ ⁣(12ℓ)⊙ε,ε∼N(0,I)z = \mu + \exp\!\big(\tfrac{1}{2}\ell\big) \odot \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I)

    The randomness is moved into ε\varepsilon, which does not depend on the weights. zz is then an ordinary function of μ\mu and ℓ\ell, and backpropagation can pass through it.

  3. KL divergence from the prior

    KL⁡(qϕ(z∣x) ∥ N(0,I))=12∑j=1Z(eℓj+μj2−1−ℓj)\operatorname{KL}\big(q_\phi(z \mid x) \,\Vert\, \mathcal{N}(0, I)\big) = \frac{1}{2} \sum_{j=1}^{Z} \left( e^{\ell_j} + \mu_j^{2} - 1 - \ell_j \right)

    How far the code's cloud is from a standard normal, in nats. It is zero only when the mean is 0 and the variance is 1 in every dimension, which is when the code says nothing about the frame.

  4. The loss for one frame

    L(x)=∑i(xi−x^i)2+β max⁡ ⁣(KL⁡,  κZ)L(x) = \sum_{i} (x_i - \hat{x}_i)^{2} + \beta \, \max\!\big(\operatorname{KL},\; \kappa Z\big)

    Reconstruction error plus the weighted KL, with the KL floored at κZ\kappa Z nats (free bits). The first term wants the code to carry information. The second wants codes to stay close to the prior so the latent space is smooth.

  5. Gradients of the KL term

    ∂KL⁡∂μj=μj,∂KL⁡∂ℓj=12(eℓj−1)\frac{\partial \operatorname{KL}}{\partial \mu_j} = \mu_j, \qquad \frac{\partial \operatorname{KL}}{\partial \ell_j} = \frac{1}{2}\big(e^{\ell_j} - 1\big)

    The KL pulls every mean toward 0 and every variance toward 1. These are added to the gradients coming back from the reconstruction, but only for frames whose KL is above the floor.

Symbols

x,  x^x,\; \hat{x}
a flattened frame and its reconstruction, values between 0 and 1
zz
the latent code of a frame
ZZ
length of the latent code (latent_size)
qϕ(z∣x)q_\phi(z \mid x)
the encoder's distribution over codes for frame x
μ,  ℓ\mu,\; \ell
the encoder's outputs: mean and log variance of the code
ε\varepsilon
standard normal noise used to sample the code
β\beta
weight of the KL term (kl_weight)
κ\kappa
free-bits tolerance per latent dimension (kl_tolerance)

Worked by hand

A model with a 2-dimensional code and the default tolerance κ=0.5\kappa = 0.5 encodes a frame as μ=(1,0)\mu = (1, 0) and ℓ=(0,−1)\ell = (0, -1). Compute the KL and compare it with the floor.

j=1:e0+12−1−0=1j = 1: \quad e^{0} + 1^{2} - 1 - 0 = 1
j=2:e−1+02−1−(−1)=0.368j = 2: \quad e^{-1} + 0^{2} - 1 - (-1) = 0.368
KL⁡=12(1+0.368)=0.684\operatorname{KL} = \tfrac{1}{2}(1 + 0.368) = 0.684
κZ=0.5×2=1.0,max⁡(0.684,  1.0)=1.0\kappa Z = 0.5 \times 2 = 1.0, \qquad \max(0.684,\; 1.0) = 1.0

The KL of 0.684 nats is under the floor of 1.0, so the loss uses the floor and the KL gradient for this frame is zero. Only the reconstruction error shapes this code until its KL rises above 1.0.

Visual example

Loading the example.

Try this

  • Slide the dot along the strip and watch its code move along a curve in the latent plane.
  • Set κ to 0 and raise the KL weight β to 4: the codes collapse onto the centre and every reconstruction is the same blur. Then put κ back to 0.5.
  • Switch to decode a code I choose and drag z₁ and z₂ to draw frames that were never in the data.
  • Press Untrained, then Train, and watch the scattered codes line up.

Code sample

import numpy as np
from impl import VAE, blob_frames
from config import VisionConfig

frames, centers = blob_frames(500, size=8, rng=np.random.default_rng(0))   # (500, 8, 8) with values in [0, 1]
vae = VAE(VisionConfig())
losses = vae.fit(frames, n_steps=1500)
mu, logvar = vae.encode(frames[:5])        # (5, 4) each
recon = vae.decode(mu)                     # (5, 64)
print(losses[0], losses[-1])
Read the implementation (137 lines)
"""V of World Models: a variational autoencoder, frame -> latent z -> reconstructed frame.

NumPy only, manual backpropagation. Dense encoder and decoder with one hidden layer each, sized for small frames.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import VisionConfig
except ImportError:  # run from the template's own folder
    from config import VisionConfig


def blob_frames(n: int, size: int, rng: np.random.Generator, width: float = 1.0) -> tuple[np.ndarray, np.ndarray]:
    """Toy frames: one Gaussian blob per frame at a random place.

    Returns (frames (n, size, size) with values in [0, 1], centers (n, 2) as (row, col) in pixel units).
    """
    centers = rng.uniform(1.0, size - 2.0, size=(n, 2))
    grid = np.arange(size)
    rows = np.exp(-0.5 * ((grid[None, :] - centers[:, :1]) / width) ** 2)
    cols = np.exp(-0.5 * ((grid[None, :] - centers[:, 1:]) / width) ** 2)
    return rows[:, :, None] * cols[:, None, :], centers


def kl_divergence(mu: np.ndarray, logvar: np.ndarray) -> np.ndarray:
    """KL(N(mu, exp(logvar)) || N(0, I)) per row, in nats. mu, logvar: (B, latent_size) -> (B,)."""
    return 0.5 * (np.exp(logvar) + mu**2 - 1.0 - logvar).sum(axis=1)


def _sigmoid(x: np.ndarray) -> np.ndarray:
    return 0.5 * (1.0 + np.tanh(0.5 * x))


class VAE:
    """Variational autoencoder over flattened frames with values in [0, 1]."""

    def __init__(self, config: VisionConfig | None = None) -> None:
        self.config = c = config or VisionConfig()
        self.rng = np.random.default_rng(c.seed)
        d, h, z = c.input_dim, c.hidden_size, c.latent_size

        def init(n_in, n_out):
            return self.rng.normal(0.0, 1.0 / np.sqrt(n_in), size=(n_in, n_out))

        self.params = {
            "enc_w": init(d, h), "enc_b": np.zeros(h),
            "mu_w": init(h, z), "mu_b": np.zeros(z),
            "lv_w": init(h, z) * 0.1, "lv_b": np.zeros(z),
            "dec_w1": init(z, h), "dec_b1": np.zeros(h),
            "dec_w2": init(h, d), "dec_b2": np.zeros(d),
        }
        self._m = {k: np.zeros_like(v) for k, v in self.params.items()}
        self._v = {k: np.zeros_like(v) for k, v in self.params.items()}
        self._t = 0

    def _flat(self, frames: np.ndarray) -> np.ndarray:
        frames = np.asarray(frames, dtype=float)
        return frames.reshape(len(frames), -1)

    def encode(self, frames: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """frames (B, H, W) or (B, input_dim) -> (mu, logvar), each (B, latent_size). Use mu as the code z."""
        p = self.params
        hidden = np.tanh(self._flat(frames) @ p["enc_w"] + p["enc_b"])
        return hidden @ p["mu_w"] + p["mu_b"], hidden @ p["lv_w"] + p["lv_b"]

    def sample_z(self, frames: np.ndarray) -> np.ndarray:
        """Draw z ~ N(mu, exp(logvar)) for each frame, shape (B, latent_size)."""
        mu, logvar = self.encode(frames)
        return mu + np.exp(0.5 * logvar) * self.rng.standard_normal(mu.shape)

    def decode(self, z: np.ndarray) -> np.ndarray:
        """z (B, latent_size) -> reconstructed frames (B, input_dim) with values in (0, 1)."""
        p = self.params
        return _sigmoid(np.tanh(z @ p["dec_w1"] + p["dec_b1"]) @ p["dec_w2"] + p["dec_b2"])

    def loss_and_grads(self, frames: np.ndarray, eps: np.ndarray) -> tuple[float, dict, dict]:
        """VAE loss for a batch with the latent noise `eps` (B, latent_size) given.

        loss = mean_b [ sum_pixels (x - x_hat)^2 + kl_weight * max(KL_b, kl_tolerance * latent_size) ].
        Returns (loss, gradients keyed like params, parts) where parts holds the mean `reconstruction` and `kl`.
        """
        c, p = self.config, self.params
        x = self._flat(frames)
        b = len(x)
        enc_h = np.tanh(x @ p["enc_w"] + p["enc_b"])
        mu = enc_h @ p["mu_w"] + p["mu_b"]
        logvar = enc_h @ p["lv_w"] + p["lv_b"]
        std = np.exp(0.5 * logvar)
        z = mu + std * eps
        dec_h = np.tanh(z @ p["dec_w1"] + p["dec_b1"])
        x_hat = _sigmoid(dec_h @ p["dec_w2"] + p["dec_b2"])
        recon = ((x - x_hat) ** 2).sum(axis=1)
        kl = kl_divergence(mu, logvar)
        floor = c.kl_tolerance * c.latent_size
        active = (kl > floor).astype(float)[:, None]  # frames whose KL is above the free-bits floor
        loss = float((recon + c.kl_weight * np.maximum(kl, floor)).mean())

        d_out = 2.0 * (x_hat - x) * x_hat * (1.0 - x_hat) / b
        d_dec_h = (d_out @ p["dec_w2"].T) * (1.0 - dec_h**2)
        d_z = d_dec_h @ p["dec_w1"].T
        d_mu = d_z + c.kl_weight * active * mu / b
        d_logvar = d_z * eps * 0.5 * std + c.kl_weight * active * 0.5 * (np.exp(logvar) - 1.0) / b
        d_enc_h = (d_mu @ p["mu_w"].T + d_logvar @ p["lv_w"].T) * (1.0 - enc_h**2)
        grads = {
            "dec_w2": dec_h.T @ d_out, "dec_b2": d_out.sum(axis=0),
            "dec_w1": z.T @ d_dec_h, "dec_b1": d_dec_h.sum(axis=0),
            "mu_w": enc_h.T @ d_mu, "mu_b": d_mu.sum(axis=0),
            "lv_w": enc_h.T @ d_logvar, "lv_b": d_logvar.sum(axis=0),
            "enc_w": x.T @ d_enc_h, "enc_b": d_enc_h.sum(axis=0),
        }
        return loss, grads, {"reconstruction": float(recon.mean()), "kl": float(kl.mean())}

    def train_step(self, frames: np.ndarray) -> float:
        """One Adam step on a batch of frames. Returns the loss before the step."""
        eps = self.rng.standard_normal((len(frames), self.config.latent_size))
        loss, grads, _ = self.loss_and_grads(frames, eps)
        self._t += 1
        for name, p in self.params.items():
            m, v, g = self._m[name], self._v[name], grads[name]
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.config.learning_rate * (m / (1 - 0.9**self._t)) / (np.sqrt(v / (1 - 0.999**self._t)) + 1e-8)
        return loss

    def fit(self, frames: np.ndarray, n_steps: int) -> list[float]:
        """Train on random minibatches of `frames` for `n_steps` steps. Returns the loss of each step."""
        frames = self._flat(frames)
        batch = min(self.config.batch_size, len(frames))
        return [self.train_step(frames[self.rng.integers(0, len(frames), size=batch)]) for _ in range(n_steps)]

    def reconstruct(self, frames: np.ndarray) -> np.ndarray:
        """Encode to the mean code and decode again. Returns (B, input_dim)."""
        return self.decode(self.encode(frames)[0])
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Make frames with frames, centers = blob_frames(500, 8, np.random.default_rng(0)), create vae = VAE(VisionConfig()) and call vae.fit(frames, 1500). Compare a few rows of vae.reconstruct(frames) with the originals. Then take mu, logvar = vae.encode(frames), plot two components of mu against the blob centres, and repeat the training with kl_tolerance=0.0, comparing the mean of kl_divergence(mu, logvar) and the reconstructions with the first run.

Check on learning

  1. The blob frames have 64 pixels but are fully described by two numbers, the row and column of the blob. What do you expect a 4-dimensional code to do with its extra two dimensions?
    A way to think about it

    Think about which uses of a dimension lower the reconstruction error and which only cost KL. Then check the per-dimension variance of the means.

  2. Why does training sample zz with noise, when at use time only the mean is taken?
    A way to think about it

    Ask what the decoder must do well if neighbouring codes are fed to it during training, and what that implies for two frames that look alike.

  3. With the free-bits floor removed (kl_tolerance=0.0), the reconstructions of the blob frames all become the same blurry image. Explain the chain of cause and effect.
    A way to think about it

    Find the encoder output that makes the KL exactly zero, then ask how much the decoder can learn about the frame from such a code.

  4. The agent's reward depends on a single-pixel object. The VAE reconstructs frames well on average but drops that pixel. Why did the loss allow this, and what could you change?
    A way to think about it

    Compare how much one pixel contributes to the summed squared error against the cost of spending code capacity on it.

  5. The KL gradient with respect to the log variance is zero at ℓ=0\ell = 0. Which way does it push when the encoder is very confident, with ℓ\ell far below zero, and what balances it?
    A way to think about it

    Evaluate 12(eℓ−1)\tfrac{1}{2}(e^{\ell} - 1) for a negative ℓ\ell, then look at the term exp⁡(ℓ/2) ε\exp(\ell / 2)\,\varepsilon in the sample and what it does to the reconstruction.