Sign in

ELBO

Evidence Lower Bound

The training loss of a variational autoencoder: a reconstruction error plus a KL term that keeps the encoder's code distribution close to a standard normal.

Overview

A variational autoencoder compresses each input into a small random code and then rebuilds the input from it. Two things are wanted at once. The rebuilt output should match the input, which is the reconstruction term. And the codes should fill the latent space in a regular way, so that sampling a code at random gives a sensible output, which is the KL term. The KL term measures how far the encoder's distribution for one input is from a standard normal. Their sum is the negative of the evidence lower bound, a quantity that is never above the log-probability the model gives the data.

A short history

The bound comes from variational inference, developed for graphical models in the 1990s by Michael Jordan and others as a way to approximate distributions that cannot be computed exactly. Diederik Kingma and Max Welling turned it into a loss for neural networks in the 2013 paper 'Auto-Encoding Variational Bayes', and Rezende, Mohamed and Wierstra published a similar method in 2014. Their reparameterisation trick let the bound be optimised by ordinary backpropagation.

How it works

  1. The encoder gives a mean μ\mu and a log-variance for each latent dimension. The decoder gives a reconstruction. Both come from your model.
  2. Compute the reconstruction negative log-likelihood per sample: Bernoulli from logits, or Gaussian with fixed sigma.
  3. Compute the KL divergence from the encoder distribution to the standard normal in closed form, summed over latent dimensions.
  4. Add them: reconstruction plus beta times KL, per sample.
  5. Average or sum over the batch with reduction.
  6. In backward, return the direct gradients for the reconstruction, μ\mu and the log-variance. The path through the sampled code is added by the model.

Watch out for

  • If the KL term dominates, the encoder outputs the prior for every input and the decoder ignores the code. This posterior collapse shows as a KL near zero.
  • The two terms must be summed over dimensions, not averaged, before they are added. Averaging one and not the other changes their balance by a large factor.
  • With beta different from 1 the loss is no longer a bound on the log-likelihood, so its value cannot be compared across settings of beta.
  • The template computes the loss terms only. Sampling the code with the reparameterisation trick and running the decoder are the model's job.
  • The Bernoulli option expects logits and data in [0,1][0, 1]. Passing probabilities gives a wrong reconstruction term with no error.

Use cases

When to use it

Training variational autoencoders and related latent-variable models. Set beta above 1 for more disentangled codes, or anneal it from 0 to avoid the KL term winning too early.

In industry

Image generation
Latent diffusion image generators first compress images with an autoencoder trained with a KL term, and run the diffusion process in that latent space.
Drug discovery
Variational autoencoders trained on molecule strings give a continuous space in which chemists search for new candidate structures.
Anomaly detection
A variational autoencoder trained on normal sensor or transaction data flags inputs that it reconstructs poorly or finds unlikely.

Choosing it: what must hold

  • A goal of learning a latent representation or generating new samples, not predicting a label.
  • A reconstruction likelihood that suits the data: Gaussian for real values, Bernoulli or categorical for discrete ones.
  • A plan for balancing the two terms, such as KL warm-up, so the model does not ignore its latent code.

When to choose something else

IfUse instead
You only need a compressed representation, not a generative modelA plain autoencoder with mean squared error
You want the sharpest possible generated imagesA diffusion model or a GAN
You want representations for retrieval or downstream classifiersInfoNCE on augmented pairs

Math foundations

  1. The bound

    ln⁡pθ(x)  ≥  Eqϕ(z∣x)[ln⁡pθ(x∣z)]−KL⁡(qϕ(z∣x) ∥ p(z))\ln p_\theta(x) \;\ge\; \mathbb{E}_{q_\phi(z \mid x)}\big[\ln p_\theta(x \mid z)\big] - \operatorname{KL}\big(q_\phi(z \mid x)\,\Vert\,p(z)\big)

    The right side is the evidence lower bound. The first term rewards codes from which the decoder can rebuild xx. The second penalises an encoder distribution far from the prior.

  2. The loss

    L=−ln⁡pθ(x∣z)⏟reconstruction  +  β KL⁡(qϕ(z∣x) ∥ p(z))\mathcal{L} = \underbrace{-\ln p_\theta(x \mid z)}_{\text{reconstruction}} \;+\; \beta\,\operatorname{KL}\big(q_\phi(z \mid x)\,\Vert\,p(z)\big)

    The negative bound, estimated with one sampled code zz. With β=1\beta = 1 minimising it maximises the bound.

  3. The KL term in closed form

    KL⁡=12∑j=1J(μj2+evj−vj−1)\operatorname{KL} = \frac{1}{2}\sum_{j=1}^{J}\big(\mu_j^{2} + e^{v_j} - v_j - 1\big)

    For a diagonal Gaussian encoder and a standard normal prior no sampling is needed. Each dimension contributes zero exactly when μj=0\mu_j = 0 and vj=0v_j = 0, which means unit variance.

  4. Bernoulli reconstruction from logits

    −ln⁡pθ(x∣z)=∑k[ln⁡ ⁣(1+erk)−xk rk]-\ln p_\theta(x \mid z) = \sum_{k}\Big[\ln\!\big(1 + e^{r_k}\big) - x_k\,r_k\Big]

    Binary cross-entropy between the data and σ(r)\sigma(r), written on the logits rr so it is stable. Used for data in [0,1][0, 1] such as pixel intensities.

  5. Gaussian reconstruction

    −ln⁡pθ(x∣z)=∑k[(xk−rk)22σ2+12ln⁡ ⁣(2πσ2)]-\ln p_\theta(x \mid z) = \sum_{k}\left[\frac{(x_k - r_k)^{2}}{2\sigma^{2}} + \frac{1}{2}\ln\!\big(2\pi\sigma^{2}\big)\right]

    Squared error scaled by a fixed variance, plus a constant. A smaller σ\sigma weights reconstruction more heavily against the KL term.

  6. Direct gradients of the KL term

    ∂ βKL⁡∂μj=β μj,∂ βKL⁡∂vj=β2(evj−1)\frac{\partial\,\beta\operatorname{KL}}{\partial \mu_j} = \beta\,\mu_j, \qquad \frac{\partial\,\beta\operatorname{KL}}{\partial v_j} = \frac{\beta}{2}\big(e^{v_j} - 1\big)

    The KL term pulls every mean toward 0 and every log-variance toward 0. The reconstruction term, through the decoder, pulls the other way.

Symbols

xx
one data sample, target
zz
the latent code sampled from the encoder distribution
qϕ(z∣x)q_\phi(z \mid x)
the encoder distribution, a diagonal Gaussian with mean mu and log-variance v
pθ(x∣z)p_\theta(x \mid z)
the decoder likelihood of the data given the code
p(z)p(z)
the prior over codes, a standard normal
μj,vj\mu_j, v_j
encoder mean and log-variance for latent dimension j; mu and logvar
rkr_k
decoder output for data element k, recon (logits or means)
β\beta
weight on the KL term, beta in the config, default 1
σ\sigma
fixed standard deviation of the Gaussian likelihood, sigma
JJ
the number of latent dimensions
KL⁡\operatorname{KL}
the Kullback-Leibler divergence
L\mathcal{L}
the loss for one sample, the negative ELBO

Worked by hand

One sample with a single latent dimension, μ=1\mu = 1 and v=−1v = -1, and a single data element x=1x = 1 with decoder logit r=2r = 2. Bernoulli likelihood, β=1\beta = 1. Use e−1=0.3679e^{-1} = 0.3679 and ln⁡(1+e2)=2.1269\ln(1 + e^{2}) = 2.1269.

KL⁡=12(12+0.3679−(−1)−1)=12×1.3679=0.6839\operatorname{KL} = \tfrac{1}{2}\big(1^{2} + 0.3679 - (-1) - 1\big) = \tfrac{1}{2} \times 1.3679 = 0.6839
−ln⁡p(x∣z)=2.1269−1×2=0.1269-\ln p(x \mid z) = 2.1269 - 1 \times 2 = 0.1269
L=0.1269+1×0.6839=0.8108\mathcal{L} = 0.1269 + 1 \times 0.6839 = 0.8108

The loss is 0.8108 nats, most of it KL. The encoder is paying 0.6839 to place this input away from the origin with a narrow variance.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import ELBO
from config import ELBOConfig

loss = ELBO(ELBOConfig(likelihood="bernoulli", beta=1.0))
rng = np.random.default_rng(0)
x = (rng.uniform(size=(4, 784)) > 0.5).astype(float)      # a batch of binary images, flattened
mu, logvar = rng.normal(size=(4, 16)), np.zeros((4, 16))  # encoder outputs
z = mu + np.exp(0.5 * logvar) * rng.normal(size=mu.shape) # the sampling step, in your model
recon_logits = rng.normal(size=(4, 784))                  # decoder output for z
print(loss.forward(recon_logits, x, mu, logvar))          # negative ELBO, nats per sample
recon_nll, kl = loss.components(recon_logits, x, mu, logvar)
g_recon, g_mu, g_logvar = loss.backward(recon_logits, x, mu, logvar)
Read the implementation (72 lines)
"""Negative ELBO of a VAE with a diagonal Gaussian encoder and a standard normal prior: reconstruction negative log-
likelihood plus beta times the closed-form KL term.

NumPy only. `forward` returns the loss, `components` its two parts, `backward` the gradients with respect to the
reconstruction, mu and logvar.
"""
from __future__ import annotations

import math

import numpy as np

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

class ELBO:
    """reconstruction NLL + beta * KL(N(mu, exp(logvar)) || N(0, I)), per sample, then reduced over the batch."""

    def __init__(self, config: ELBOConfig | None = None) -> None:
        self.config = config or ELBOConfig()

    @staticmethod
    def _check(recon, target, mu, logvar) -> tuple[np.ndarray, ...]:
        """All four as float arrays; recon and target share a shape (N, ...), mu and logvar a shape (N, ...)."""
        recon, target, mu, logvar = (np.asarray(x, dtype=float) for x in (recon, target, mu, logvar))
        if recon.shape != target.shape or mu.shape != logvar.shape or recon.ndim < 1 or mu.ndim < 1:
            raise ValueError("recon and target must share a shape, and mu and logvar must share a shape")
        if recon.shape[0] != mu.shape[0]:
            raise ValueError(f"batch sizes differ: {recon.shape[0]} and {mu.shape[0]}")
        return recon, target, mu, logvar

    def components(self, recon, target, mu, logvar) -> tuple[np.ndarray, np.ndarray]:
        """The two parts of the loss for every sample, before weighting and reduction.

        recon: (N, ...) decoder output (logits for "bernoulli", means for "gaussian"). target: same shape,
        the data. mu, logvar: (N, latent) encoder outputs. Returns (reconstruction NLL (N,), KL (N,)), in nats.
        """
        recon, target, mu, logvar = self._check(recon, target, mu, logvar)
        n = recon.shape[0]
        if self.config.likelihood == "bernoulli":
            nll = np.logaddexp(0.0, recon) - target * recon  # -[x log p + (1 - x) log(1 - p)], p = sigmoid(recon)
        else:
            var = self.config.sigma**2
            nll = 0.5 * (target - recon) ** 2 / var + 0.5 * math.log(2.0 * math.pi * var)
        kl = -0.5 * (1.0 + logvar - mu**2 - np.exp(logvar))
        return nll.reshape(n, -1).sum(axis=1), kl.reshape(n, -1).sum(axis=1)

    def forward(self, recon, target, mu, logvar) -> float:
        """Negative ELBO as a float: reconstruction + beta * KL, averaged (or summed) over the batch."""
        nll, kl = self.components(recon, target, mu, logvar)
        per_sample = nll + self.config.beta * kl
        return float(per_sample.mean() if self.config.reduction == "mean" else per_sample.sum())

    def backward(self, recon, target, mu, logvar) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Gradients of the loss with respect to recon, mu and logvar, each in the shape it was given.

        These are the direct gradients of the two terms. The gradient that flows from recon back through the
        decoder and the sampled code into mu and logvar is the model's job and adds to the ones returned here.
        """
        recon, target, mu, logvar = self._check(recon, target, mu, logvar)
        scale = 1.0 / recon.shape[0] if self.config.reduction == "mean" else 1.0
        if self.config.likelihood == "bernoulli":
            g_recon = np.exp(-np.logaddexp(0.0, -recon)) - target  # sigmoid(recon) - x
        else:
            g_recon = (recon - target) / self.config.sigma**2
        g_mu = self.config.beta * mu
        g_logvar = self.config.beta * 0.5 * (np.exp(logvar) - 1.0)
        return g_recon * scale, g_mu * scale, g_logvar * scale

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build ELBO(ELBOConfig(likelihood="bernoulli", beta=1.0)). With random recon and target of shape (4, 10), call components once with mu and logvar all zero and once with mu all 2. Confirm the KL is 0 in the first case, compute by hand what it should be in the second, then compare forward at beta of 1 and 4.

Check on learning

  1. After training, the KL term is nearly zero for every input and reconstructions all look like the dataset average. What happened, and what would you try?
    A way to think about it

    A zero KL means the code carries no information about the input. Think about ways to make using the code worthwhile early on: a smaller β\beta at first, or a weaker decoder.

  2. Why can the KL term be computed exactly while the reconstruction term needs a sampled code?
    A way to think about it

    The KL is between two Gaussians, which has a formula. The reconstruction passes the code through a neural network, and no closed form exists for an expectation through that.

  3. With the Gaussian likelihood, what happens to the balance between the two terms when sigma is halved?
    A way to think about it

    Look at the factor 1/(2σ2)1/(2\sigma^{2}). Compare the effect with changing β\beta, and ask whether the two settings are really independent.

  4. The KL term pulls every code toward the standard normal. Why is that useful for generating new samples?
    A way to think about it

    To generate, you draw a code from the prior and decode it. Consider what the decoder has seen during training if the encoder's codes lie nowhere near the prior.

  5. backward returns βμ\beta\mu as the gradient for the mean. Why is that not the full gradient the encoder needs?
    A way to think about it

    The mean also shifts the sampled code, which changes the reconstruction. Trace that second path through the decoder and decide who is responsible for it.