Lossy compression: rate–distortion, the information bottleneck and the β-VAE
Before this lesson: lesson 05 (lossless coding, rates in bits per symbol), lesson 07 (mutual information, the data processing inequality), lesson 09 (the ELBO and the VAE). "Conditioning reduces entropy" is from lesson 02; the maximum entropy of the Gaussian is from lesson 06. Reverse water-filling uses PCA (linear algebra lesson 09). Time: about 75 minutes, plus the notebook. This lesson is dense; take a break after section 3.4.
Why this matters #
- Learned compression. Neural image and video codecs (Ballé et al.) are trained with the loss rate distortion. JPEG, MP3 and video codecs are hand-made points on the same plane.
- VAEs and latent diffusion. The two terms of the VAE loss are a distortion and a rate. The β-VAE moves along the curve, and posterior collapse is the point "rate = 0". The autoencoder of a latent diffusion model chooses a point with a high rate, so that details survive.
- Quantization of models. "How many bits per weight for a given error?" is a rate–distortion question. The rule "6 dB per bit" comes from the Gaussian .
- Representation learning. The information bottleneck and its variational form are used as regularizers, and as one (debated) theory of what deep networks learn.
- ML for science. Climate, weather and simulation archives are compressed with error bounds, and compressors are compared by bits per value against error.
As in the whole track, is the natural log (nats) and gives bits. Rates are in bits unless a formula says nats. is the binary entropy in bits.
1. Predict first #
2. The picture #
Encoder, bits, decoder #
An encoder sees a block of source symbols and sends one of messages, that is, bits. A decoder turns the message into a reconstruction . A distortion measure scores each symbol:
- Hamming distortion for symbols: the average is the error rate;
- squared error for real numbers: the average is the mean squared error (MSE).
The rate is in bits per symbol. The question: what is the smallest rate for an average distortion of at most ?
A fair coin: store or guess #
Take fair coin flips and Hamming distortion. A simple scheme: store a fraction of the flips exactly (1 bit each), and output a fixed guess for the rest. A fixed guess is wrong half of the time. So
This is a straight line from to . To allow 11% errors, it needs bits per flip.
Shannon's answer is the curve . At , , so only 0.50 bits per flip are needed. The curve lies below the line everywhere between the end points.
Move the slider and compare the limit (magenta) with the store-or-guess line (orange). The aqua bar is the gain of coding long blocks. Then change : the curve starts at the lossless limit and reaches 0 at , where you can always output the more likely symbol.
Why block coding wins (a counting picture). Code flips at once, for a large . Around each reconstruction sequence, the sequences within Hamming distance form a "ball". This ball contains about sequences (for ). There are possible source sequences, so you need at least
reconstruction sequences to come within distance of every one. That is bits, a rate of . Shannon showed that a random set of slightly more sequences is enough. Store-or-guess treats each flip alone and wastes this geometry. For and : about reconstruction sequences for source sequences.
The test channel #
Think of encoder and decoder together as one noisy channel from to , with a conditional distribution : the test channel. The message has bits, so can carry at most bits of information about . Rate–distortion asks for the channel that carries the least information about while it still meets the distortion budget.
Channel capacity (the other half of Shannon's theory) is the opposite problem: there the channel is fixed, and you maximize over the input distribution.
For a fair coin with Hamming distortion, what is ?
allows no errors, so and bit: lossy coding with zero distortion is lossless coding (lesson 05). by the convention , so .
3. Definitions and main results #
3.1 The rate–distortion function #
Notation. The source is i.i.d. The reconstruction takes values in a set . is the distortion and is a test channel.
Definition (rate–distortion function).
where the expectation and are under the joint distribution . Let : the distortion of the best constant output. For , a constant output meets the budget and carries no information, so .
Theorem (Shannon's rate–distortion theorem; stated without proof). For an i.i.d. source and a bounded distortion measure:
- for every rate and every , there are block codes of rate with expected distortion at most , for large enough;
- no code of rate has expected distortion at most .
(Cover and Thomas, Elements of Information Theory, ch. 10.) So the mathematical minimum in the definition is also the operational limit.
Properties.
- is non-increasing: a larger allows more channels, so the minimum can only go down.
- For a discrete source with Hamming distortion, : forces .
- is convex.
Proof of convexity.
- Let and be optimal channels for and , and . Mix them: .
- The expected distortion is linear in the channel, so has distortion at most .
- For a fixed , is a convex function of (Cover and Thomas, Theorem 2.7.4). So .
Convexity explains the coin picture: store-or-guess mixes the two end points and , so it is the straight line between them, and a convex curve lies below that line.
Rate–distortion theory looks for the test channel that
Fewer bits means less information about in the reconstruction. So we look for the least informative channel that still meets the distortion budget. Capacity is the opposite problem: it maximizes over input distributions for a fixed channel. Minimizing distortion with no constraint just gives .
3.2 A binary source with Hamming distortion #
Theorem. Let Bernoulli() with , and . Then
(For swap the roles of 0 and 1: the formula holds with in place of .)
Proof. First a lower bound, for any channel with .
- Let (XOR). exactly when the reconstruction is wrong, so .
- . Once is known, knowing is the same as knowing .
- . The first step is "conditioning reduces entropy" (lesson 02). The second holds because is increasing on .
- So .
Then a channel that reaches the bound.
- Build the joint distribution backwards: Bernoulli() and , with Bernoulli() independent of . Choose , so that .
- Then and , because given , the only uncertainty in is . The forward channel follows from Bayes' rule (section 4).
Example. , : bits per symbol. Lossless coding needs 0.881 bits; allowing 10% errors saves more than half.
3.3 A Gaussian source with squared error #
Theorem. Let and . Then
Equivalently, the smallest MSE at rate is .
Why this is true (intuition). The reconstruction must "explain" all of the variance except . The best reconstruction is itself Gaussian with variance , and the leftover error is Gaussian noise with variance . The information is the log of the ratio of the two "volumes", .
Proof. Lower bound, for any channel with . Here is the differential entropy in bits (lesson 06).
- . Given , subtracting it is a shift, which does not change ; then conditioning reduces entropy.
- Among all distributions with a given variance, the Gaussian has the largest differential entropy, and the variance is at most the second moment. So .
- With : .
Achievability:
- Backwards again: and with independent of . Then , , and .
Each extra bit divides by 4, that is, dB per bit (it halves the standard deviation of the error). The Gaussian is also the hardest source for squared error: every source with variance has .
Move the slider along the curve . The lower chart shows a sample signal and a reconstruction drawn from the optimal test channel with that mean squared error; the aqua bars are the errors. Halve the bits and watch the errors grow. Then show the quantizer points: a uniform scalar quantizer followed by an ideal entropy coder stays about 0.25 bits above the curve.
3.4 Many Gaussian components: reverse water-filling #
Now let have independent Gaussian components with variances (for example, the principal components of data), and let the distortion be the total squared error. How should you share the bits?
Theorem (reverse water-filling). Choose a "water level" . Component gets the distortion and the rate . Then
where is chosen so that the add up to . Components with get no bits at all.
Move the water level (yellow). Each blue bar is the variance of one component; the aqua part is its distortion , and the number above the bar is its rate in bits. Notice that every coded component ends with the same error , and that small components are dropped. Try the spectrum of the digits data set: its top principal components have similar variances.
Why water-filling is optimal (sketch)
- For independent components, (Cover and Thomas, §10.3.3), and each term is at least . So over . Coding each component with its own optimal channel reaches this sum, so equality holds.
- Minimize subject to and . With a Lagrange multiplier, the derivative must be the same for every component that gets bits: all such are equal, to .
- If , the best choice is (send nothing): reducing its error below would cost more than spending the bits elsewhere.
This is the theory behind transform coding: rotate the data to its principal components (PCA, the DCT in JPEG), then spend bits only on components with large variance. Dropping the small components is exactly what truncated PCA does.
3.5 The Blahut–Arimoto algorithm #
For a general discrete source there is no closed form. The Blahut–Arimoto (BA) algorithm computes points of the curve.
- Lagrangian. For , minimize over . The minimizer is the point of the curve where the slope is (with in nats). Large : low distortion and high rate. Small : low rate.
- A variational form of . For any distribution on ,
where is the output marginal. Equality holds if and only if . So BA minimizes, over both and ,
- Alternate two exact minimizations (see the box).
- Convergence. No step increases , and is jointly convex in , so the iteration converges to the minimum (Csiszár and Tusnády, 1984). At the end, report and . A sweep over traces the whole curve.
Press 1 step a few times, then 25 steps. The yellow point is the current channel; it moves onto the curve and stops where the dashed line of slope touches the curve. The table on the right is the test channel (darker orange = larger). Move and run again to land on another point. Try the 3-level source with squared error.
For the Bernoulli source, the slope of in nats is . Setting it to gives , which does not depend on (as long as ).
You run Blahut–Arimoto on a Bernoulli(0.3) source with Hamming distortion and . Where does it end?
The end point has slope , so , and . Then bits. is jointly convex, so the limit does not depend on the start (any start with ).
3.6 The information bottleneck #
Now the goal is not to reconstruct but to keep what matters for a target . Input , target , and a representation computed from alone, with a distribution . So is a Markov chain. The information bottleneck (IB; Tishby, Pereira and Bialek, 1999) is, for :
Compress (small ) while keeping the information about (large ). By the data processing inequality (lesson 07), : cannot know more about than does.
IB is a rate–distortion problem. Take the rate and the distortion : how much the prediction of gets worse when you use instead of . The Markov chain gives , so
does not depend on . So minimizing is the IB objective. Its solution has the BA form ; the iteration also updates , because here the distortion itself depends on the channel.
Variational IB (Alemi et al., 2017) makes this trainable with neural networks. For any , . For any decoder , . The resulting loss is
a β-VAE whose decoder predicts instead of .
3.7 The β-VAE as a rate–distortion trade-off #
A VAE has an encoder , a decoder and a prior (lesson 09). For one data point :
- Distortion is the expected reconstruction loss in nats. For a Gaussian decoder with fixed variance , : a scaled squared error.
- Rate is the KL term. Averaged over the data it bounds the information that carries about .
Theorem (the rate is an upper bound on ). Average over the data and let be the aggregate posterior. Then
where is the mutual information under .
Proof.
- Split the log: .
- Take the expectation over . The first term gives by the definition of mutual information.
- In the second term only appears, and its marginal is . So it gives .
The bound is tight when the aggregate posterior equals the prior. On the other side, , where is the entropy of the data, because (a cross-entropy is at least the entropy). So (Alemi et al., 2018).
The β-VAE (Higgins et al., 2017) minimizes .
- is the negative ELBO.
- buys a lower rate with more distortion: more compressed codes, often blurrier reconstructions.
- does the opposite: more information in , sharper reconstructions.
- Same ELBO, different models. , so every point on a line has the same ELBO. A model with ignores : this is posterior collapse. A powerful decoder can reach a good ELBO this way. So report and separately, not only the ELBO.
A linear-Gaussian example. Let , the encoder with , the prior , and the best decoder . With , all quantities have closed forms (in nats):
So : measured by mutual information, every such encoder sits exactly on the Gaussian curve. The rate equals only when , that is, when is the prior. With a decoder variance of the distortion is the MSE (plus a constant), and the β-VAE optimum is on the curve for , and the collapsed point , for .
Move the encoder sliders and . The orange point is (MSE, rate) and the violet point is (MSE, ); the aqua bar between them is . The violet point always lies on the curve. Then move : the yellow point is the β-VAE optimum, where the dashed line of equal loss touches the curve. Press Go to the β-optimum, and try to see posterior collapse.
Learned image compression (Ballé et al., 2017) minimizes , with the rate given by a learned entropy model of a quantized latent (coded with arithmetic coding, lesson 05). It is the β-VAE objective with .
You train a β-VAE and increase from 1 to 4. What do you expect?
The loss is . A larger makes each nat of rate more expensive, so the optimum moves along the curve to a lower rate and a higher distortion. You cannot lower both: the curve is the limit. The ELBO is only.
A VAE reports an average KL term of 12 nats. What do you know about under the encoder?
, and the last term is . Equality needs the aggregate posterior to equal the prior.
Answers to section 1. (1) bits per flip, not 0.78: coding long blocks beats store-or-guess. (2) By a factor of 4: , that is 6.02 dB per bit. (3) The KL term (rate) goes down and the reconstruction error goes up; for large enough the rate can reach 0 (posterior collapse).
4. Worked example #
A Bernoulli(0.3) source with Hamming distortion, at .
- Rate. and , so bits per symbol. (always output 0).
- Backward channel. : Bernoulli(0.25), and is flipped with probability 0.1. Check: ✓.
- Forward channel, by Bayes' rule. , and . The encoder keeps almost all 0s and turns a quarter of the 1s into 0s: it errs toward the more likely symbol. Distortion: ✓.
- Slope. nats per unit of distortion. So BA with ends here: .
- This is a fixed point of BA. The output marginal is (vectors list , then ), and . For : , which normalizes to . For : , which normalizes to . Both match step 3.
- Gaussian. and give bit per sample. A uniform scalar quantizer with ideal entropy coding needs about bits more per sample at high rate (1.53 dB). Coding long blocks closes this gap.
5. In code #
The code checks the Bernoulli formula by brute force over all binary test channels, runs Blahut–Arimoto at , and evaluates the linear-Gaussian VAE in closed form. SciPy computes as .
import numpy as np
from scipy.stats import entropy
# 1. R(D) of a Bernoulli(0.3) source by brute force over all binary test channels.
# a = q(x̂=1 | x=0), b = q(x̂=0 | x=1) on a grid; I(X; X̂) = KL(joint || product of marginals).
p1 = 0.3
a, b = np.meshgrid(np.linspace(0, 1, 1001), np.linspace(0, 1, 1001))
joint = np.stack([(1 - p1) * (1 - a), (1 - p1) * a, p1 * b, p1 * (1 - b)]) # (x, x̂) = 00, 01, 10, 11
out1 = joint[1] + joint[3] # P(x̂ = 1)
prod = np.stack([(1 - p1) * (1 - out1), (1 - p1) * out1, p1 * (1 - out1), p1 * out1])
info_bits = entropy(joint, prod, axis=0, base=2)
dist = joint[1] + joint[2] # P(x̂ != x)
Hb = lambda x: entropy([x, 1 - x], base=2)
for D in [0.05, 0.1, 0.2]:
print(D, info_bits[dist <= D].min().round(3), round(Hb(p1) - Hb(D), 3))
# 0.05 0.595 0.595
# 0.1 0.412 0.412
# 0.2 0.159 0.159
# 2. Blahut-Arimoto for the same source at beta = ln 9.
px, d = np.array([0.7, 0.3]), 1.0 - np.eye(2)
beta, q = np.log(9), np.full((2, 2), 0.5)
for _ in range(500):
r = px @ q # output marginal r(x̂)
q = r * np.exp(-beta * d) # Gibbs form, then normalize each row
q /= q.sum(axis=1, keepdims=True)
r = px @ q
I = np.sum(px[:, None] * q * np.log2(q / r))
print(q.round(4).tolist(), round(I, 4), round(np.sum(px[:, None] * q * d), 4))
# [[0.9643, 0.0357], [0.25, 0.75]] 0.4123 0.1
# 3. Linear-Gaussian "VAE" on X ~ N(0, 1): encoder z = a x + s eps, prior N(0, 1).
for a_, s_ in [(0.8, 0.6), (0.8, 0.3)]:
v = a_**2 + s_**2
rate = 0.5 * (v - 1 - np.log(s_**2)) # E_x KL(N(a x, s^2) || N(0, 1))
mi = 0.5 * np.log(v / s_**2) # I(X; Z) = h(Z) - h(Z | X)
mse = s_**2 / v # best linear decoder x̂ = (a / v) z
print(f"rate {rate:.3f} I {mi:.3f} 1/2 ln(1/MSE) {0.5 * np.log(1 / mse):.3f} nats")
# rate 0.511 I 0.511 1/2 ln(1/MSE) 0.511 nats (a^2 + s^2 = 1: on the curve)
# rate 1.069 I 1.047 1/2 ln(1/MSE) 1.047 nats (rate = I + KL(q(z) || p(z)))
Part 3: measured by , a linear-Gaussian encoder with the best decoder sits exactly on the Gaussian curve . The VAE rate adds , which is zero only when .
6. Where it shows up #
- Learned compression. End-to-end image codecs (Ballé et al., 2017; with a hyperprior, 2018) minimize , with the rate given by a learned entropy model and arithmetic coding. Neural codecs for video, audio (neural audio codecs with residual vector quantization) and scientific fields follow the same recipe.
- VAEs and latent diffusion. β-VAEs move along the curve; free bits set a floor on the rate per latent dimension to avoid collapse. The first-stage autoencoder of a latent diffusion model uses a very small KL weight: a high rate, so details survive, and the diffusion model then learns the distribution of the latents.
- Quantization. A uniform quantizer with step has MSE about at high resolution. Each extra bit halves (for a fixed range) and divides the error by 4. Going from 8 to 4 bits per weight at a fixed range multiplies the error by . Post-training quantization decides where to spend bits for the smallest output error: a rate–distortion problem, often solved layer by layer.
- Transform coding. JPEG uses the DCT, an approximation of PCA for images, then spends more bits on the large low-frequency coefficients: reverse water-filling in practice.
- ML for science. Lossy compressors for climate, weather and seismic archives (error-bounded SZ and ZFP, or neural codecs) are compared by bits per value against error. Reverse water-filling explains why coding in principal components (EOFs of a climate field) works.
- Representations. Variational IB is used as a regularizer for classifiers and for robustness. Rate and distortion curves are a useful way to compare representation learners.
7. Common mistakes #
- Mixing up and capacity. minimizes over channels for a fixed source. Capacity maximizes over inputs for a fixed channel.
- Using beyond . There ; the formula would give a wrong, often negative, value. The same holds for the Gaussian formula when .
- Units. BA's slope is in nats per unit of distortion when is in nats. Convert to bits at the end.
- Mixing up the β's. In BA and the IB, a large means a high rate; in the β-VAE, a large means a low rate.
- Reading the β-VAE rate as . It is an upper bound; the gap is .
- Comparing VAEs by the ELBO alone. Equal ELBOs can hide very different pairs, including .
- Expecting a scalar quantizer to reach . For a Gaussian at high rate, even with ideal entropy coding, it stays 0.254 bits per sample (1.53 dB) above the curve. The bound needs coding over long blocks (vector quantization).
- IB with a deterministic network. For a continuous and an injective deterministic , is infinite. A finite estimate comes from the estimator, not from the network.
8. Check yourself #
- A fair coin, Hamming distortion, 0.25 bits per flip. What is the smallest error rate? What does
store-or-guess reach?
Answer
Solve , so and . Store-or-guess: gives . - A Gaussian source with and squared error. What MSE can you reach with 3 bits per sample?
Answer
. - Why is convex?
Answer
Mix the optimal channels for and with weights and . The distortion is linear in the channel, so the mixture meets . is convex in the channel for a fixed source, so . - Three independent Gaussian components have variances . With the water level ,
give each , each rate and the totals.
Answer
. Rates , , and 0 bits. Total bits for . The third component is not sent. - Prove with .
Answer
Write and take the expectation over . The first term gives . In the second term has marginal , so it gives . - A β-VAE with and a powerful autoregressive decoder. What can happen, and why?
Answer
Posterior collapse: the decoder can model without , so the optimum can set , which gives with no loss in . The code then carries no information. , free bits or a weaker decoder push the rate up.
Define the rate–distortion function .
over test channels with : the fewest bits per symbol for average distortion .
What is for a Bernoulli() source with Hamming distortion?
for , and 0 above.
What is for a Gaussian source with squared error?
bits for , and 0 for .
By what factor does one extra bit per sample reduce the smallest MSE of a Gaussian source?
By 4 (about 6.02 dB), because .
Compute for a fair coin at .
bits per flip (store-or-guess needs 0.78).
How does reverse water-filling share bits among independent Gaussian components?
Each component gets distortion for a common level ; components with variance below get no bits.
What are the two steps of the Blahut–Arimoto algorithm?
(output marginal), then . Repeat; the limit is the point of slope .
Write the information bottleneck objective.
, with the Markov chain .
Why is the β-VAE rate an upper bound on ?
, and the last term is .
In a β-VAE, what does a larger do?
The loss pays more for rate, so the optimum has a lower rate (KL term) and a higher distortion.
9. Interview angle #
- "What is the rate–distortion function? How is it different from channel capacity?" The minimum of over channels that meet the distortion budget; capacity maximizes over inputs for a fixed channel.
- "How many bits per sample does a Gaussian signal need at an SNR of 30 dB?" , so bits.
- "Why does a β-VAE with give blurrier reconstructions?" It pays more for rate, so it moves to a point with lower rate and higher distortion.
- "What is posterior collapse in rate–distortion language?" The point : the code carries no information, and the decoder alone models the data.
- "What is the information bottleneck?" : rate–distortion with the distortion . Mention that the "compression phase" claim is disputed.
- "Why do codecs transform the data before quantizing?" In decorrelated components, reverse water-filling gives the bits to high-variance components and drops the rest.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- Brute-force of a Bernoulli source over binary test channels on a grid, compared with .
blahut_arimoto(p_x, distortion, beta), then trace the whole curve with a sweep over .- Gaussian and reverse water-filling on the PCA spectrum of the
load_digitsdata set. - A linear-Gaussian "VAE": rate, and MSE in closed form for several encoders, placed on the plane.
- Uniform scalar quantization of a Gaussian: entropy of the quantized values against MSE, compared with (the gap of about 0.25 bits at high rate).
11. Watch and read #
- Stanford EE274 notes: rate–distortion theory (the Bernoulli and Gaussian examples) and quantization.
- Kevin Murphy, Probabilistic Machine Learning: Advanced Topics (free PDF): §5.4.2 (lossy compression and the rate–distortion trade-off), §5.6 (the information bottleneck and variational IB), §21.3.1 (β-VAE).
- Yury Polyanskiy and Yihong Wu, Information Theory: From Coding to Learning (free draft): the chapters on rate–distortion theory.
- Tishby, Pereira and Bialek, The information bottleneck method (1999); Alemi et al., Deep Variational Information Bottleneck (ICLR 2017).
- Alemi et al., Fixing a Broken ELBO (ICML 2018), §2: rate, distortion and the β-VAE; Higgins et al., β-VAE (ICLR 2017).
- Ballé, Laparra and Simoncelli, End-to-end optimized image compression (ICLR 2017); Saxe et al., On the information bottleneck theory of deep learning (ICLR 2018).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.