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
VAE.encodeflattens a frame and maps it through one tanh hidden layer to two vectors: a mean and a log variance for the latent code.- 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.
decodemaps the code through one tanh hidden layer and a sigmoid to a reconstructed frame with values between 0 and 1.loss_and_gradsadds the squared reconstruction error to the KL term, which measures how far the code's distribution is from a standard normal.- 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. fittakes Adam steps on random minibatches. Afterwards, use the mean fromencodeas the code 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
| If | Use instead |
|---|---|
| Observations are already short state vectors | An MLP encoder from the shared networks lesson |
| Small, task-critical details are lost in reconstruction | A 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 stage | DQN or PPO with a convolutional encoder |
Math foundations
The encoder's output
For each frame the encoder gives a small cloud of possible codes, not a single point. The network outputs the log variance , which may be any real number, and the variance is its exponential.
The reparameterized sample
The randomness is moved into , which does not depend on the weights. is then an ordinary function of and , and backpropagation can pass through it.
KL divergence from the prior
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.
The loss for one frame
Reconstruction error plus the weighted KL, with the KL floored at 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.
Gradients of the KL term
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
- a flattened frame and its reconstruction, values between 0 and 1
- the latent code of a frame
- length of the latent code (latent_size)
- the encoder's distribution over codes for frame x
- the encoder's outputs: mean and log variance of the code
- standard normal noise used to sample the code
- weight of the KL term (kl_weight)
- free-bits tolerance per latent dimension (kl_tolerance)
Worked by hand
A model with a 2-dimensional code and the default tolerance encodes a frame as and . Compute the KL and compare it with the floor.
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
- 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.
- Why does training sample 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.
- 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.
- 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.
- The KL gradient with respect to the log variance is zero at . Which way does it push when the encoder is very confident, with far below zero, and what balances it?
A way to think about it
Evaluate for a negative , then look at the term in the sample and what it does to the reconstruction.