Variational Autoencoders in NumPy: Three Digits, No KL Term

Build a variational autoencoder from scratch in NumPy with hand-derived gradients. Measure what the KL term buys: without it the model can only generate 3 of 10 digits.

Cover Image for Variational Autoencoders in NumPy: Three Digits, No KL Term

You've trained an autoencoder on handwritten digits, and it can reconstruct the images you give it. It is tempting to try making a new digit by choosing a few numbers for its compressed representation and passing them through the decoder. Those numbers may land in a region the encoder never used during training, though, and the result can look like noise. Good reconstruction alone gives you little assurance that sampling new representations will work.

Adding the prior-matching term changes whether new latent samples decode as digits. On scikit-learn's 8x8 data, generated samples reach all ten classes. Removing the KL term leaves roughly three. We build the NumPy variational autoencoder with hand-derived gradients and vary that weight. Too much collapses the encoder. The standard setting from Kingma and Welling (2014) is slightly beyond the best point here.

Let's Build It

Open this in Google Colab and run it top to bottom. It builds an encoder, a decoder, the reparameterised sampling step and Adam, then trains four models at different KL weights and counts how many digit classes each one can produce. About ninety seconds on a CPU.

Open In Colab

import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression

sigmoid = lambda x: 1 / (1 + np.exp(-np.clip(x, -60, 60)))


class Dense:
    def __init__(self, n_in, n_out, rng, gain=None):
        self.W = rng.normal(0, gain or np.sqrt(2 / n_in), (n_in, n_out))
        self.b = np.zeros(n_out)

    def forward(self, x):
        self.x = x
        return x @ self.W + self.b

    def backward(self, g):
        self.gW, self.gb = self.x.T @ g, g.sum(0)
        return g @ self.W.T


class Stack:                                  # Dense -> ReLU -> ... -> Dense
    def __init__(self, widths, rng):
        self.L = [Dense(a, b, rng) for a, b in zip(widths[:-1], widths[1:])]

    def forward(self, x):
        self.m = []
        for i, l in enumerate(self.L):
            x = l.forward(x)
            if i < len(self.L) - 1:
                self.m.append(x > 0)
                x = x * self.m[-1]
        return x

    def backward(self, g):
        for i in reversed(range(len(self.L))):
            if i < len(self.L) - 1:
                g = g * self.m[i]
            g = self.L[i].backward(g)
        return g

    def pg(self):
        return [(l.W, l.gW) for l in self.L] + [(l.b, l.gb) for l in self.L]

    def p(self):
        return [l.W for l in self.L] + [l.b for l in self.L]


class VAE:
    def __init__(self, n_in, hidden=32, latent=2, seed=0):
        rng = np.random.default_rng(seed)
        self.latent = latent
        self.enc = Stack([n_in, hidden, hidden], rng)
        self.mu_head = Dense(hidden, latent, rng, gain=0.05)
        self.lv_head = Dense(hidden, latent, rng, gain=0.05)
        self.dec = Stack([latent, hidden, hidden, n_in], rng)

    def forward(self, x, rng, sample=True):
        h = self.enc.forward(x)
        self.mu, self.lv = self.mu_head.forward(h), self.lv_head.forward(h)
        self.sd = np.exp(0.5 * np.clip(self.lv, -20, 20))
        # The reparameterisation trick: the noise is an input, so dz/dmu = 1 and
        # gradient reaches the encoder. Sampling inside the graph would cut it.
        self.eps = rng.standard_normal(self.mu.shape) if sample else 0.0
        self.z = self.mu + self.sd * self.eps
        return self.dec.forward(self.z)

    def loss(self, x, beta):
        self.p_out, self.x = sigmoid(self.dec.forward(self.z)), x
        recon = -(x * np.log(self.p_out + 1e-7)
                  + (1 - x) * np.log(1 - self.p_out + 1e-7)).sum(1)
        kl = -0.5 * (1 + self.lv - self.mu**2 - np.exp(np.clip(self.lv, -20, 20))).sum(1)
        return recon.mean(), kl.mean()

    def backward(self, beta):
        n = len(self.x)
        g_z = self.dec.backward((self.p_out - self.x) / n)     # d(recon)/d(out) = p - x
        g_mu = g_z + beta * self.mu / n                        # + d(KL)/d(mu)
        g_lv = (g_z * self.eps * 0.5 * self.sd
                + beta * 0.5 * (np.exp(np.clip(self.lv, -20, 20)) - 1) / n)
        self.enc.backward(self.mu_head.backward(g_mu) + self.lv_head.backward(g_lv))

    def pg(self):
        return (self.enc.pg() + [(self.mu_head.W, self.mu_head.gW), (self.mu_head.b, self.mu_head.gb),
                                 (self.lv_head.W, self.lv_head.gW), (self.lv_head.b, self.lv_head.gb)]
                + self.dec.pg())

    def p(self):
        return (self.enc.p() + [self.mu_head.W, self.mu_head.b, self.lv_head.W, self.lv_head.b]
                + self.dec.p())

    def decode(self, z):
        return sigmoid(self.dec.forward(z))

    def fit(self, X, beta=0.25, steps=4000, lr=2e-3, batch=128, seed=0):
        rng = np.random.default_rng(seed)
        st = [(np.zeros_like(p), np.zeros_like(p)) for p in self.p()]
        for t in range(1, steps + 1):
            xb = X[rng.choice(len(X), batch, replace=False)]
            self.forward(xb, rng)
            self.loss(xb, beta)
            self.backward(beta)
            for (p, g), (m, v) in zip(self.pg(), st):
                m *= 0.9; m += 0.1 * g
                v *= 0.999; v += 0.001 * g**2
                p -= lr * (m / (1 - 0.9**t)) / (np.sqrt(v / (1 - 0.999**t)) + 1e-8)
        return self


# --- How much of the data can you actually reach by sampling the prior? ---
X, y = load_digits(return_X_y=True)
X = X / 16.0                                   # Bernoulli likelihood wants [0, 1]
judge = LogisticRegression(max_iter=2000).fit(X, y)

def digits_reachable(model, n=2000, seed=1):
    """Decode n draws from the prior, classify them, and count the digits that
    turn up as more than 1% of the samples. A class that appears twice in two
    thousand is not something the model can generate."""
    z = np.random.default_rng(seed).standard_normal((n, model.latent))
    hist = np.bincount(judge.predict(model.decode(z)), minlength=10) / n
    return int((hist > 0.01).sum())


print(f"{'beta':>6}{'recon':>9}{'code spread':>14}{'digits reachable':>19}")
for beta in (0.0, 0.25, 1.0, 4.0):
    m = VAE(64, seed=0).fit(X, beta=beta)
    m.forward(X, np.random.default_rng(0), sample=False)
    recon, _ = m.loss(X, beta)
    print(f"{beta:>6.2f}{recon:>9.2f}{m.mu.std():>14.2f}"
          f"{digits_reachable(m):>13} of 10")
  beta    recon   code spread   digits reachable
  0.00    20.94          2.90            4 of 10
  0.25    20.17          1.08           10 of 10
  1.00    20.95          0.98           10 of 10
  4.00    27.12          0.00            1 of 10

Four models, near-identical reconstruction loss for the first three, and wildly different answers to "can you generate with this". That table is one seed, and every figure below reports three, which matters more than it usually does: β=0\beta = 0 is by far the least stable setting in the sweep, averaging 3.3 of 10 classes with a spread of 0.9, while β=1\beta = 1 averages 9.3 rather than the 10 this run happened to reach. An unregularised latent space is not merely worse, it is unpredictable.

What Just Happened?

The ELBO, term by term

A VAE maximises a lower bound on the log-likelihood of the data. Written as a loss to minimise, with the KL weight β\beta made explicit:

L=Eq(z∣x)[−log⁡p(x∣z)]⏟reconstruction+βDKL ⁣(q(z∣x) ∥ p(z))⏟stay near the prior\mathcal{L} = \underbrace{\mathbb{E}_{q(z \mid x)}\left[-\log p(x \mid z)\right]}_{\text{reconstruction}} + \beta \underbrace{D_{\mathrm{KL}}\!\left(q(z \mid x)\,\|\,p(z)\right)}_{\text{stay near the prior}}

The first term is the autoencoder you already know: encode, decode, penalise the difference. The second is the whole difference. It measures how far the Gaussian the encoder produced for this input sits from N(0,I)N(0, I), the distribution you will later sample from when you want to generate.

Maximising a bound rather than the thing itself sounds like a compromise, and it is the honest move: the quantity you want, log⁡p(x)=log⁡∫p(x∣z)p(z) dz\log p(x) = \log \int p(x \mid z) p(z)\, dz, is an integral over every possible code and cannot be computed. The bound is tractable, and it is tight exactly when the approximate posterior matches the true one. The approximate inference post derives the same bound from the variational-inference side, without a neural network in sight.

Setting β=0\beta = 0 deletes the second term and leaves a plain autoencoder. That is the control the table above runs.

The reparameterisation trick

There is a sampling step between encoder and decoder, and gradients do not flow through sampling. Draw z∼N(μ,σ2)z \sim N(\mu, \sigma^2) as an operation in your graph and the encoder receives nothing: the derivative of "a sample" with respect to μ\mu is not defined in any form backpropagation can use.

The fix is to move the randomness out of the path. Draw ϵ∼N(0,I)\epsilon \sim N(0, I) first, treat it as an input, and compute z=μ+σϵz = \mu + \sigma \epsilon. The forward value has exactly the same distribution. The backward pass now has ∂z/∂μ=1\partial z / \partial \mu = 1 and ∂z/∂σ=ϵ\partial z / \partial \sigma = \epsilon, both perfectly ordinary.

The reparameterisation trick, and what it is worth

The right panel is the ablation. Cutting the gradient path (keeping the identical forward pass, so only the backward differs) leaves reconstruction stuck at 27.1 against 20.9, with zero active latent units. That is not a degraded model, it is a decoder learning to emit the average digit while the encoder never learns anything at all.

The gradients, by hand

Two pieces make the backward pass short enough to write out. The Bernoulli likelihood's derivative collapses, because the sigmoid and the cross-entropy cancel:

∂ recon∂ decoder output=p−x\frac{\partial\, \text{recon}}{\partial\, \text{decoder output}} = p - x

And the KL against a unit Gaussian has a closed form, so it differentiates directly:

DKL=−12∑j(1+log⁡σj2−μj2−σj2)∂DKL∂μj=μjD_{\mathrm{KL}} = -\tfrac{1}{2}\sum_j \left(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\right) \qquad \frac{\partial D_{\mathrm{KL}}}{\partial \mu_j} = \mu_j

Those are the g_mu and g_lv lines. No autodiff anywhere, and the same backpropagation machinery as every other network on this blog.

The KL Term, Measured

Here is the mechanism, drawn. Each panel is the same model at a different KL weight, showing where it placed the training set in its two-dimensional latent space. The circles mark one and two standard deviations of the prior, which is the entire region generation draws from.

Latent spaces at four KL weights

At β=0\beta = 0 the encoder has no reason to keep the codes anywhere in particular, so it spreads them across a range of roughly ±13\pm 13. The prior is the small circle near the origin. Sampling it lands in a crowded patch where a few classes overlap, and most digits are simply somewhere else. Reconstruction is fine, because the decoder is never asked to visit the empty regions. Generation is not, because that is all generation does.

Turn the term on and the codes are pulled onto the prior. The spread falls from 4.94 to 1.07 and the classes arrange themselves around the origin, filling the region that sampling reaches. Turn it up too far and everything collapses to a single point.

Watching it happen shows the two forces separately:

The latent space organising during training

The reconstruction term pushes the classes apart, because separated codes are easier to decode correctly. The KL term pulls the whole cloud back towards the origin. The arrangement you end up with is where those two settle, and β\beta sets the exchange rate between them.

Coverage and cost against the KL weight

Reading the two panels together gives the whole trade-off. The left shows what you can generate: 3.3 classes at β=0\beta = 0, all ten from 0.1 through 0.5, then a fall to one. The right shows the price and the mechanism: reconstruction is a shallow U with its floor around 0.1 to 0.25, and the spread of the codes slides monotonically from 4.94 to zero, crossing the target value of 1.0 at about β=0.5\beta = 0.5.

Going Deeper

The best setting is not the standard one

β=1\beta = 1 is the plain ELBO, and it is the default in most implementations. On this data it is already past the optimum on both axes: reconstruction 20.94 against 20.09 at β=0.25\beta = 0.25, and 9.3 of 10 classes against 10 of 10. Neither gap is large, and neither is noise, since the seed spreads are 0.06 and 0.47.

This is the observation Higgins and colleagues (2017) built beta-VAE on, approaching from the other direction: they turn β\beta up to buy disentangled representations at the cost of reconstruction. The same knob turned the other way buys reconstruction at the cost of prior match. There is no reason the correct weight should happen to be exactly 1, and it depends on the data, the architecture and, as the last section shows, the likelihood.

Posterior collapse

At β=4\beta = 4 the model reaches a solution that looks like a bug and is the optimum of the loss you wrote. The encoder outputs μ=0\mu = 0 and σ=1\sigma = 1 for every input, which drives the KL term to exactly zero. The decoder, receiving pure noise, learns to emit the average digit. Reconstruction sits at 27.12 with a standard deviation across seeds of 0.00, because every seed finds the same degenerate answer.

The diagnostic to watch is active units: count the latent dimensions whose per-dimension KL is above a small threshold. Two at β≤1\beta \le 1, zero at β=4\beta = 4. When that number falls, the model has stopped using its latent space, and no amount of further training brings it back. Bowman and colleagues (2016) hit this on text and introduced KL annealing, ramping β\beta from 0 upward during training, which remains the standard remedy.

Notice that the collapsed numbers are identical to the broken-gradient numbers from the ablation: 27.12, zero active units. The two failures have different causes and the same destination, which is worth remembering when you are debugging one.

The manifold the decoder learned

Because the latent space is two-dimensional, the decoder can be inspected exhaustively. Walk a grid across the prior's quantiles and decode every point.

The decoder over a grid of latent coordinates

Nothing in this picture is a training image. Every square is the decoder's output at a coordinate, and the digits change smoothly into one another as you move: 6 into 0 into 9 into 3, 4 into 7 into 5 into 2. That continuity is what the KL term bought. In the β=0\beta = 0 latent space the same walk would spend most of its length in regions the encoder never used, and decode to nothing in particular.

Bernoulli or Gaussian

The reconstruction term needs a likelihood, and the choice is a statement about the data rather than a loss-function detail. Bernoulli treats each pixel as a probability and gives cross-entropy. A unit-variance Gaussian gives half squared error. Both differentiate to the same tidy p−xp - x, so swapping them is a one-line change.

Bernoulli against Gaussian at two KL weights

The consequence is larger than it looks. The two reconstruction terms carry different magnitudes, so the same β\beta weighs the KL differently against each. At β=0.25\beta = 0.25 both work, with Bernoulli slightly ahead (pixel RMSE 0.177 against 0.205, ten classes against 8.7). At β=1\beta = 1 the Bernoulli model is healthy and the Gaussian model has collapsed completely: code spread 0.01, one class, pixel RMSE 0.271.

So "use β=1\beta = 1, it is the ELBO" is advice that silently depends on a modelling choice made elsewhere in the file. If you switch likelihood and your VAE stops working, this is the first thing to check.

Where This Comes From

Kingma and Welling published "Auto-Encoding Variational Bayes" in December 2013, and Rezende, Mohamed and Wierstra derived the same estimator independently within weeks. Variational inference was decades old by then, and the obstacle was never the bound. It was that fitting an approximate posterior meant a separate optimisation for every data point, which does not scale to a dataset.

Two ideas together removed the obstacle. Amortisation: instead of solving for q(z∣x)q(z \mid x) per example, train one network to output its parameters, so the cost of inference on a new point is a forward pass. The reparameterisation trick: rewrite the sampling step so that a low-variance gradient estimate exists at all. Neither is a statement about neural networks specifically. Together they turned variational Bayes from a technique applied to small models by specialists into something you can run on a million images.

The architecture also has a clean ancestor on this blog. Probabilistic PCA is a latent-variable model with a Gaussian prior, a linear decoder and a Gaussian likelihood, fitted by EM. Replace the linear decoder with a neural network, fit by gradient descent instead of EM, and amortise the posterior, and you have a VAE. The generative story is identical: draw zz from a simple prior, push it through a decoder, observe noisy output.

What the VAE gave up in that trade is the exact posterior. PPCA has one in closed form; a VAE has a Gaussian approximation produced by a network, and the gap between that approximation and the truth is the slack in the bound. Most of the decade of follow-up work, richer posteriors, normalising flows, discrete latents, has been about closing it.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions