Module contents
Lesson 14 of 19Advanced 110 min

Rate-distortion theory

Study how many bits per symbol are needed to reconstruct a source at average distortion D. Define the rate–distortion function as a mutual-information minimum, derive it for binary and Gaussian sources, implement Blahut–Arimoto and interpret learned compression and β-VAE through an objective that trades rate against distortion.

After this lesson you can

  • Define R(D) and prove that it is nonincreasing and convex.
  • Compute R(D) for a Bernoulli source with Hamming distortion and a Gaussian source with squared error.
  • Solve reverse water filling for a Gaussian vector with components of different variances.
  • Implement Blahut–Arimoto for R(D) and trace its curve by varying the multiplier.
  • Interpret learned image compression and β-VAE as points on a rate–distortion curve.

Before you start

Motivation: how much can be lost, and at what price?

So far this module has considered lossless compression: the source coding theorem says a memoryless source cannot be described with fewer than H(X)H(X) bits per symbol if exact recovery is required. But most compression we use daily deliberately loses information:

  • JPEG, MP3, video codecs. A 12-megapixel photo occupies 36 MB raw and about 3 MB as JPEG. The original pixels are not recovered; what is recovered is visually indistinguishable to the eye.
  • Weight quantization. A language model with 16-bit weights is served with 4 bits per weight. Each weight changes slightly, and what matters is how much the model’s loss worsens.
  • Latent spaces. Latent diffusion compresses an image of 512×512×3512 \times 512 \times 3 into a tensor of 64×64×464 \times 64 \times 4, 48 times smaller, and generates in that space. The autoencoder producing it is a lossy codec.

For a continuous source, lossless compression does not even make sense in this setting: describing a real number exactly requires infinitely many bits. The right question is the one Shannon posed in 1959: if average distortion DD is tolerated, what is the minimum number of bits per symbol? The answer is a function, the rate-distortion function R(D)R(D). This lesson builds it, calculates it for important cases and connects it to learned compression.

Start with the simplest source: equally likely bits, Xi∼iidBern⁡(1/2)X_i \iid \Bern(1/2), and Hamming distortion, the fraction of bits incorrectly reconstructed. If we tolerate D=0.11D = 0.11, the obvious strategy is to send a fraction of bits unchanged and guess the rest by coin toss (failing half the time). To fail on 11 %11\,\% overall, we must guess 22 %22\,\% of the bits, giving rate 0.780.78 bits per symbol. Can we do better? The cell compares that strategy with two block quantizers: replace each block with the nearest word in a small codebook.

[ ]Concrete strategies versus Shannon's limitBrowser
from itertools import product
from math import log2

def h2(x):
    return 0.0 if x in (0, 1) else -x * log2(x) - (1 - x) * log2(1 - x)

def R_binaria(D):                       # el resultado que demostraremos: R(D) = 1 - h2(D) para Bern(1/2)
    return max(0.0, 1 - h2(D)) if D < 0.5 else 0.0

def ingenua(D):                         # enviar una fracción de los bits y adivinar el resto
    return max(0.0, 1 - 2 * D)

def cuantizador(diccionario, n):
    """Cada bloque de n bits se sustituye por la palabra más cercana. Devuelve (tasa, distorsión por bit)."""
    total = 0
    for w in product([0, 1], repeat=n):
        total += min(sum(a != b for a, b in zip(w, c)) for c in diccionario)
    return log2(len(diccionario)) / n, total / (n * 2**n)

G = [[1, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1, 1]]
hamming = [tuple(sum(m[i] * G[i][j] for i in range(4)) % 2 for j in range(7)) for m in product([0, 1], repeat=4)]

print("estrategia              tasa     D      ingenua(D)   R(D)")
for nombre, (R, D) in [("mayoría de 3", cuantizador([(0,) * 3, (1,) * 3], 3)),
                       ("mayoría de 5", cuantizador([(0,) * 5, (1,) * 5], 5)),
                       ("Hamming (7, 4)", cuantizador(hamming, 7))]:
    print(f"{nombre:20s}  {R:6.4f}  {D:6.4f}     {ingenua(D):6.4f}    {R_binaria(D):6.4f}")
print(f"\ncon D = 0.11: ingenua {ingenua(0.11):.4f} bits, límite R(0.11) = {R_binaria(0.11):.4f} bits")

Both quantizers clearly improve on the naive strategy. The (7,4)(7, 4) Hamming quantizer represents each 7-bit block by one of its 16 words (4 bits), and because every block lies within distance 1 of a word (the code is perfect), it misses 12.5 %12.5\,\% of the bits at 0.5710.571 bits per symbol, where the naive method would need 0.750.75. But the limit lies lower still: with D=0.11D = 0.11, half a bit per symbol suffices, R(0.11)=0.5001R(0.11) = 0.5001. The seemingly reasonable naive strategy wastes 36 %36\,\% of the rate. This lesson explains where 0.50.5 comes from, why it cannot be beaten and how it is achieved.

Unless stated otherwise, log⁡\log is the base-2 logarithm and rate is measured in bits per source symbol.

Distortion, lossy codes and the operational problem

A source XX takes values in an alphabet X\mathcal{X} and is reconstructed in a reproduction alphabet X^\hat{\mathcal{X}}, which may differ (for example, a color image is reproduced using a 256-color palette).

The encoder chooses one of 2nR2^{nR} indices, so uses nRnR bits per block, RR per symbol. The problem is to find, for each DD, the lowest rate at which arbitrarily long codes exist. Two values of DD bound the problem:

  • Dmin⁡=E[min⁡x^d(X,x^)]D_{\min} = \E\big[\min_{\hat x} d(X, \hat x)\big]: below this no code works (for Hamming and squared error, Dmin⁡=0D_{\min} = 0).
  • Dmax⁡=min⁡x^E[d(X,x^)]D_{\max} = \min_{\hat x} \E[d(X, \hat x)]: with D≥Dmax⁡D \ge D_{\max} it suffices always to reproduce the same symbol x^∗\hat x^*, which minimizes average distortion, without sending anything. For Hamming on a Bern⁡(p)\Bern(p), Dmax⁡=min⁡(p,1−p)D_{\max} = \min(p, 1-p); for squared error, Dmax⁡=Var⁡(X)D_{\max} = \Var(X), reproducing the mean.

As in lossless compression, the operational definition is intractable as written: an infimum over all codes of all lengths. Shannon replaced it with an optimization over a single symbol.

The rate-distortion function

The key idea is to view the (source, reproduction) pair as a channel: encoder and decoder together turn XX into X^\hat X through conditional distribution Q(x^∣x)Q(\hat x \mid x), the test channel. But here the channel is not given, as in lesson 9: we choose it, seeking the one that transmits the least information compatible with tolerated distortion.

For finite alphabets the minimum exists: the feasible-channel set is compact (the constraint is linear in QQ) and mutual information is continuous. It is dual to the capacity problem: there we maximize II over input with channel fixed; here we minimize II over channel with input fixed. Since I(p,Q)I(p, Q) is convex in QQ (proved in lesson 9), this is a convex optimization problem, which structures everything that follows.

Proof

(1) If D1≤D2D_1 \le D_2, every channel feasible for D1D_1 is feasible for D2D_2: the minimum over a larger set does not increase.

(2) Let Q1,Q2Q_1, Q_2 be optimal channels for D1,D2D_1, D_2, λ∈[0,1]\lambda \in [0, 1] and Qλ=λQ1+(1−λ)Q2Q_\lambda = \lambda Q_1 + (1 - \lambda) Q_2 (rowwise mixture). Distortion is linear in QQ, so EQλ[d]≤λD1+(1−λ)D2\E_{Q_\lambda}[d] \le \lambda D_1 + (1-\lambda) D_2: QλQ_\lambda is feasible for Dλ=λD1+(1−λ)D2D_\lambda = \lambda D_1 + (1-\lambda)D_2. By convexity of mutual information in the channel,

R(Dλ)≤I(p,Qλ)≤λI(p,Q1)+(1−λ)I(p,Q2)=λR(D1)+(1−λ)R(D2).R(D_\lambda) \le I(p, Q_\lambda) \le \lambda I(p, Q_1) + (1-\lambda) I(p, Q_2) = \lambda R(D_1) + (1-\lambda) R(D_2).

A finite convex function on an interval is continuous in its interior.

(3) If D≥Dmax⁡D \ge D_{\max}, the channel sending everything to x^∗\hat x^* is feasible and has I=0I = 0. If R(D)=0R(D) = 0, the optimal channel makes X^\hat X independent of XX and then E[d]=∑x^q(x^) E[d(X,x^)]≥Dmax⁡\E[d] = \sum_{\hat x} q(\hat x)\,\E[d(X, \hat x)] \ge D_{\max}, hence D≥Dmax⁡D \ge D_{\max}. A convex, nonincreasing function positive on [Dmin⁡,Dmax⁡)[D_{\min}, D_{\max}) and zero on Dmax⁡D_{\max} cannot have horizontal segments in that interval: if R(D1)=R(D2)>0R(D_1) = R(D_2) > 0 with D1<D2<Dmax⁡D_1 < D_2 < D_{\max}, convexity between D1D_1 and Dmax⁡D_{\max} would give R(D2)<R(D1)R(D_2) < R(D_1).

(4) I(X;X^)≤H(X)I(X; \hat X) \le H(X) always, and with Hamming the identity channel has distortion 0 and I=H(X)I = H(X); any channel with D=0D = 0 must be the identity, so R(0)=H(X)R(0) = H(X).

∎

Convexity has a direct operational interpretation, time sharing: if one codec achieves (R1,D1)(R_1, D_1) and another (R2,D2)(R_2, D_2), using the first for fraction λ\lambda of blocks and the second for the rest achieves intermediate point (λR1+(1−λ)R2, λD1+(1−λ)D2)(\lambda R_1 + (1-\lambda)R_2,\ \lambda D_1 + (1-\lambda)D_2). Thus the achievable region is convex and its boundary a convex curve. The motivation’s “naive” strategy is exactly time sharing between the lossless codec, with (R,D)=(H(X),0)(R, D) = (H(X), 0), and one sending nothing, with (R,D)=(0,Dmax⁡)(R, D) = (0, D_{\max}): a chord above the curve.

The rate-distortion theorem

The definition above minimizes mutual information for one symbol; the operational problem concerns arbitrarily long blocks. Their equality is the central theorem.

The converse has a short complete proof, worth seeing in full because each inequality has a role.

Proof

Converse. Let a code (2nR,n)(2^{nR}, n) and X^n=gn(fn(Xn))\hat X^n = g_n(f_n(X^n)) with E[d(Xn,X^n)]≤D\E[d(X^n, \hat X^n)] \le D. Since Xn→fn(Xn)→X^nX^n \to f_n(X^n) \to \hat X^n is a Markov chain, the data processing inequality and the entropy bound for an index give

nR  ≥  H(fn(Xn))  ≥  I(Xn;fn(Xn))  ≥  I(Xn;X^n).nR \;\ge\; H(f_n(X^n)) \;\ge\; I(X^n; f_n(X^n)) \;\ge\; I(X^n; \hat X^n).

Now use that the source is memoryless. By the chain rule, I(Xn;X^n)=H(Xn)−H(Xn∣X^n)=∑iH(Xi)−∑iH(Xi∣X^n,Xi−1)I(X^n; \hat X^n) = H(X^n) - H(X^n \mid \hat X^n) = \sum_i H(X_i) - \sum_i H(X_i \mid \hat X^n, X^{i-1}), and since conditioning reduces entropy, H(Xi∣X^n,Xi−1)≤H(Xi∣X^i)H(X_i \mid \hat X^n, X^{i-1}) \le H(X_i \mid \hat X_i). Thus

I(Xn;X^n)  ≥  ∑i=1nI(Xi;X^i)  ≥  ∑i=1nR(E[d(Xi,X^i)])  ≥  n R(1n∑i=1nE[d(Xi,X^i)])  ≥  nR(D).I(X^n; \hat X^n) \;\ge\; \sum_{i=1}^n I(X_i; \hat X_i) \;\ge\; \sum_{i=1}^n R\big(\E[d(X_i, \hat X_i)]\big) \;\ge\; n\,R\Big(\frac1n\sum_{i=1}^n \E[d(X_i, \hat X_i)]\Big) \;\ge\; n R(D).

The second inequality is the definition of RR (the pair (Xi,X^i)(X_i, \hat X_i) defines a test channel with distortion E[d(Xi,X^i)]\E[d(X_i, \hat X_i)]), the third is Jensen with convex RR and the last uses that RR is nonincreasing. Dividing by nn, R≥R(D)R \ge R(D). If distortion only satisfies lim sup⁡≤D\limsup \le D, the same argument gives R≥R(D+ε)R \ge R(D + \varepsilon) for every ε>0\varepsilon > 0, and continuity of RR closes the case D>Dmin⁡D > D_{\min}.

∎

Notice where assumptions enter: independence of XiX_i (for H(Xn)=∑H(Xi)H(X^n) = \sum H(X_i)) and convexity of RR, which prevents unevenly distributing distortion across positions from helping.

Achievability (sketch). Fix an optimal channel Q∗Q^* for DD and its marginal q∗q^*, and choose R>I(p,Q∗)=R(D)R > I(p, Q^*) = R(D). Draw a codebook of 2nR2^{nR} words x^n(1),…,x^n(2nR)\hat x^n(1), \dots, \hat x^n(2^{nR}) with symbols ∼iidq∗\iid q^*. To encode xnx^n, find a word jointly typical with it (in the sense of asymptotic equipartition applied to the pair) and send its index. For a typical xnx^n, a random word is jointly typical with probability of order 2−nI(X;X^)2^{-n I(X; \hat X)}: there are about 2nH(X^∣X)2^{nH(\hat X \mid X)} reproductions compatible with xnx^n among 2nH(X^)2^{nH(\hat X)} typical ones. The probability that none of the 2nR2^{nR} words is jointly typical is

(1−2−nI)2nR≤exp⁡ ⁣(−2n(R−I))→n→∞0si R>I.\big(1 - 2^{-nI}\big)^{2^{nR}} \le \exp\!\big(-2^{n(R - I)}\big) \xrightarrow[n \to \infty]{} 0 \quad\text{si } R > I.

When a jointly typical word exists, block distortion is approximately Ep×Q∗[d]≤D\E_{p \times Q^*}[d] \le D; otherwise it costs at most dmax⁡d_{\max} with vanishing probability. Averaging over random codebooks, mean distortion tends to something ≤D\le D, so at least one such codebook exists. The rigorous version quantifies joint typicality via strong typicality (Cover and Thomas, section 10.5).

The argument is existential and convergence in nn is slow. The cell draws codebooks of 2n/22^{n/2} words (rate 12\tfrac12) for equally likely bits and measures mean nearest-neighbor distortion. The limit is D(12)=0.110D(\tfrac12) = 0.110, the value with R(D)=12R(D) = \tfrac12.

[ ]Random coding: the limit is reached, but slowlyBrowser
import numpy as np

rng = np.random.default_rng(0)
cuenta = np.array([bin(i).count("1") for i in range(1 << 12)], dtype=np.uint8)
def popcount(a):                                 # bits a 1 de enteros de hasta 24 bits
    return cuenta[a & 0xFFF] + cuenta[(a >> 12) & 0xFFF]

print(" n    palabras   distorsión media   (límite D(1/2) = 0.110)")
for n in [4, 8, 12, 16, 20, 24]:
    diccionario = rng.integers(0, 1 << n, size=1 << (n // 2))     # tasa R = 1/2: 2^(n/2) palabras de n bits
    fuente = rng.integers(0, 1 << n, size=300)                     # 300 bloques de bits equiprobables
    D = np.mean([popcount(diccionario ^ x).min() for x in fuente]) / n
    print(f"{n:2d}  {1 << (n // 2):8d}       {D:.4f}")

With n=24n = 24, a randomly drawn codebook of 4096 words stays around 0.1470.147, still far from 0.1100.110 and worse than the Hamming code at a slightly higher rate. Random coding is a proof that the limit is achievable, not a practical algorithm; real codes (lattice, LDPC or polar-code quantization, and trellis coded quantization) approach it with structure.

Binary source: R(D) = h₂(p) − h₂(D)

Now we can calculate the number in the motivation. The tool is the same as for binary symmetric channel capacity, in reverse.

Proof

Assume p≤12p \le \tfrac12 (the other case is symmetric) and D≤pD \le p. Let ⊕\oplus be addition modulo 2.

Lower bound. For any test channel with P(X≠X^)=E[d]≤D\Pr(X \ne \hat X) = \E[d] \le D,

I(X;X^)=H(X)−H(X∣X^)=h2(p)−H(X⊕X^∣X^)≥h2(p)−H(X⊕X^)≥h2(p)−h2(D).I(X; \hat X) = H(X) - H(X \mid \hat X) = h_2(p) - H(X \oplus \hat X \mid \hat X) \ge h_2(p) - H(X \oplus \hat X) \ge h_2(p) - h_2(D).

The middle equality uses that, given X^\hat X, XX and X⊕X^X \oplus \hat X determine each other. The last inequality uses X⊕X^∼Bern⁡(E[d])X \oplus \hat X \sim \Bern(\E[d]) with E[d]≤D≤12\E[d] \le D \le \tfrac12, and that h2h_2 increases on [0,12][0, \tfrac12].

Achievability. Construct the channel backward: X^∼Bern⁡(r)\hat X \sim \Bern(r) and X=X^⊕ZX = \hat X \oplus Z with independent Z∼Bern⁡(D)Z \sim \Bern(D). For XX to have the correct distribution, r(1−D)+(1−r)D=pr(1-D) + (1-r)D = p, that is r=p−D1−2Dr = \frac{p - D}{1 - 2D}, which lies in [0,1][0, 1] exactly when D≤pD \le p. Then E[d]=P(Z=1)=D\E[d] = \Pr(Z = 1) = D and I(X;X^)=H(X)−H(Z)=h2(p)−h2(D)I(X; \hat X) = H(X) - H(Z) = h_2(p) - h_2(D): both inequalities are equalities.

∎

For the fair coin, R(0.11)=1−h2(0.11)=0.5001R(0.11) = 1 - h_2(0.11) = 0.5001: the half bit in the motivation. The optimal test channel is best read backward: the source is the reproduction plus independent noise Bern⁡(D)\Bern(D). It is the binary symmetric channel of lesson 9, and the coincidence is not accidental: 1−h2(ε)1 - h_2(\varepsilon) was the capacity of BSC(ε)\mathrm{BSC}(\varepsilon), and now 1−h2(D)1 - h_2(D) is the rate needed for distortion DD. Forward, the channel is Q(x^∣x)=P(X^=x^)P(X=x∣X^=x^)/p(x)Q(\hat x \mid x) = \Pr(\hat X = \hat x)\Pr(X = x \mid \hat X = \hat x)/p(x); for p≠12p \ne \tfrac12 it is not symmetric.

InteractiveA coin's R(D) curve
Optimal test channel Q(x^∣x)Q(\hat x \mid x)
X = 00.50X̂ = 00.50X = 10.50X̂ = 10.50opaque bands: errors, total mass 0.110backward: X = X̂ ⊕ Z, with Z ~ Bern(0.110)
  • R(D)R(D)
  • achievable region
  • send a fraction of bits
  • block quantizers (M3, M5, H7)
0.50
0.110
R(D)=h2(p)−h2(D)R(D) = h_2(p) - h_2(D)0.5001 bits
h2(p)h_2(p) (lossless)1.0000 bits
Naive: send a fraction0.7800 bits
Optimal P(X^=1)\Pr(\hat X = 1), rr0.500
Q(x^=1∣x=0)Q(\hat x = 1 \mid x = 0), Q(x^=1∣x=1)Q(\hat x = 1 \mid x = 1)0.110, 0.890
majority of 3: (D,R)(D, R)(0.250, 0.333)
majority of 5: (D,R)(D, R)(0.313, 0.200)
Hamming (7, 4): (D,R)(D, R)(0.125, 0.571)
At equal distortion the naive strategy needs 0.7800.780 bits and the limit is 0.5000.500: 36% less. The best block quantizer here is majority of 5, 0.0960.096 bits above the curve at its distortion.
Left: the (distortion, rate) plane. The shaded region above the curve is achievable; below it, nothing is. The dashed orange line is the naive strategy (send a fraction of bits losslessly and reproduce the most likely symbol for the rest), and red points are real block quantizers with their index compressed by ideal entropy coding. Right: the optimal test channel for the chosen distortion, with band widths p(x)Q(x^∣x)p(x)Q(\hat x \mid x). Start at p=0.5p = 0.5, D=0.11D = 0.11: how much does the limit save over the naive strategy? Lower pp to 0.20.2: where does the curve meet the horizontal axis now, and why? Set DD to zero and check that the curve ends at h2(p)h_2(p).

What to notice in the figure:

  1. The curve is convex and the naive strategy is a chord. It goes from (0,h2(p))(0, h_2(p)) to (min⁡(p,1−p),0)(\min(p, 1-p), 0) below the chord joining its endpoints. Halfway, with p=12p = \tfrac12 and D=0.25D = 0.25, the limit is 0.1890.189 bits versus 0.50.5.
  2. Block quantizers lie between the chord and curve. Majority of 3 achieves (0.25,0.333)(0.25, 0.333) and Hamming (7,4)(7, 4), (0.125,0.571)(0.125, 0.571). Longer, better-structured blocks approach the curve; none cross it.
  3. The test channel corrupts the rare symbol more. With p=0.2p = 0.2 and D=0.1D = 0.1, the reproduction has r=0.125r = 0.125 and the forward channel is Q(1^∣0)=0.016Q(\hat 1 \mid 0) = 0.016, Q(1^∣1)=0.563Q(\hat 1 \mid 1) = 0.563: it almost never invents ones but erases almost half of those present. Errors concentrate where they are cheapest in bits.
  4. The slope diverges near D=0D = 0. R′(D)=−log⁡1−DD→−∞R'(D) = -\log\frac{1-D}{D} \to -\infty: the last errors are most expensive to eliminate.

Gaussian sources: R(D) = ½ log(σ²/D)

For a continuous source with squared error, the definition of R(D)R(D) is the same with densities (and the coding theorem extends under appropriate assumptions; it holds for the Gaussian). The new tool is Gaussian maximum entropy: among variables with second moment E[W2]≤s\E[W^2] \le s, the one with greatest differential entropy is N(0,s)\Normal(0, s), with h=12log⁡(2πe s)h = \frac12\log(2\pi e\, s).

Proof

Lower bound. For any test channel with E[(X−X^)2]≤D\E[(X - \hat X)^2] \le D,

I(X;X^)=h(X)−h(X∣X^)=h(X)−h(X−X^∣X^)≥h(X)−h(X−X^)≥12log⁡(2πeσ2)−12log⁡(2πeD)=12log⁡σ2D.I(X; \hat X) = h(X) - h(X \mid \hat X) = h(X) - h(X - \hat X \mid \hat X) \ge h(X) - h(X - \hat X) \ge \tfrac12\log(2\pi e\sigma^2) - \tfrac12\log(2\pi e D) = \tfrac12\log\tfrac{\sigma^2}{D}.

The second equality is translation invariance of differential entropy (given X^\hat X, subtracting X^\hat X is a translation), the first inequality is that conditioning reduces entropy, and the second is maximum entropy applied to W=X−X^W = X - \hat X, with E[W2]≤D\E[W^2] \le D.

Achievability. Backward: X^∼N(0,σ2−D)\hat X \sim \Normal(0, \sigma^2 - D) and X=X^+ZX = \hat X + Z with independent Z∼N(0,D)Z \sim \Normal(0, D). Then X∼N(0,σ2)X \sim \Normal(0, \sigma^2), E[(X−X^)2]=D\E[(X - \hat X)^2] = D and I(X;X^)=h(X)−h(Z)=12log⁡σ2DI(X; \hat X) = h(X) - h(Z) = \frac12\log\frac{\sigma^2}{D}. For D>σ2D > \sigma^2, X^=0\hat X = 0 suffices.

∎

Three ways to read the formula:

  • Every bit divides distortion by 4. D(R)=σ22−2RD(R) = \sigma^2 2^{-2R} means signal-to-noise ratio improves by 10log⁡104=6.0210\log_{10} 4 = 6.02 dB per bit, the rule of thumb for analog-to-digital converters. With σ2=1\sigma^2 = 1 and D=0.25D = 0.25 exactly 1 bit is needed.
  • The optimal reproduction has less variance than the source. Forward, the channel is X^=aX+V\hat X = a X + V with a=1−D/σ2a = 1 - D/\sigma^2 and independent V∼N(0,aD)V \sim \Normal\big(0, a D\big): reconstruction shrinks the source toward its mean. Var⁡(X^)=σ2−D<σ2\Var(\hat X) = \sigma^2 - D < \sigma^2. This detail reappears as blur in learned codecs.
  • The Gaussian is the hardest source. For any source with variance σ2\sigma^2, the same linear channel X^=aX+V\hat X = aX + V has the same distortion (depending only on second moments) and I(X;aX+V)=h(aX+V)−h(V)≤12log⁡(2πe(a2σ2+Var⁡V))−h(V)=12log⁡σ2DI(X; aX + V) = h(aX + V) - h(V) \le \frac12\log(2\pi e(a^2\sigma^2 + \Var V)) - h(V) = \frac12\log\frac{\sigma^2}{D}. Thus R(D)≤12log⁡σ2DR(D) \le \frac12\log\frac{\sigma^2}{D} for every source of variance σ2\sigma^2: among sources with given variance, the Gaussian requires the most bits. Conversely, the lower-bound argument gives the Shannon lower bound R(D)≥h(X)−12log⁡(2πeD)R(D) \ge h(X) - \frac12\log(2\pi e D), used when studying quantizers.

Gaussian vectors and reverse water-filling

Now consider vector source X=(X1,…,Xk)\vb{X} = (X_1, \dots, X_k) with independent components Xi∼N(0,σi2)X_i \sim \Normal(0, \sigma_i^2) and total distortion E∥X−X^∥2=∑iE(Xi−X^i)2≤D\E\norm{\vb{X} - \hat{\vb{X}}}^2 = \sum_i \E(X_i - \hat X_i)^2 \le D. How is distortion allocated among components?

Proof

Reduction to components. Since components are independent, the same converse argument (chain rule and conditioning reduces entropy) gives I(X;X^)≥∑iI(Xi;X^i)≥∑iRi(Di′)I(\vb{X}; \hat{\vb{X}}) \ge \sum_i I(X_i; \hat X_i) \ge \sum_i R_i(D_i'), with Di′=E(Xi−X^i)2D_i' = \E(X_i - \hat X_i)^2 and Ri(t)=max⁡{0,12log⁡(σi2/t)}R_i(t) = \max\{0, \frac12\log(\sigma_i^2/t)\}. Thus R(D)≥min⁡{∑iRi(Di):∑iDi≤D, Di≥0}R(D) \ge \min\{\sum_i R_i(D_i) : \sum_i D_i \le D,\ D_i \ge 0\}, and equality is achieved with independent Gaussian test channels per component, each with its DiD_i.

Optimal allocation. It suffices to consider 0<Di≤σi20 < D_i \le \sigma_i^2 (giving a component more distortion than its variance saves nothing). Problem min⁡∑i12log⁡σi2Di\min \sum_i \frac12\log\frac{\sigma_i^2}{D_i} with ∑iDi=D\sum_i D_i = D and Di≤σi2D_i \le \sigma_i^2 is convex (the function is convex in each DiD_i and constraints are linear), so KKT conditions suffice. With multiplier ν\nu for the sum and μi≥0\mu_i \ge 0 for Di≤σi2D_i \le \sigma_i^2, stationarity is −log⁡e2Di+ν+μi=0-\frac{\log e}{2 D_i} + \nu + \mu_i = 0. If Di<σi2D_i < \sigma_i^2, complementary slackness gives μi=0\mu_i = 0 and Di=log⁡e2ν=:θD_i = \frac{\log e}{2\nu} =: \theta, the same value for all. If Di=σi2D_i = \sigma_i^2, μi≥0\mu_i \ge 0 requires σi2≤θ\sigma_i^2 \le \theta. This is exactly the stated rule, and θ\theta is fixed by ∑iDi=D\sum_i D_i = D (the sum is continuous and increasing in θ\theta).

∎

The name comes from the picture: variances are bars and distortion is water rising to level θ\theta. What remains submerged is each component’s distortion; what protrudes above the water, σi2−θ\sigma_i^2 - \theta, is reproduction variance X^i\hat X_i, what is actually encoded. It reverses power allocation (water-filling) for the Gaussian channel in lesson 11: there water (power) is poured over noise and channels with little noise are used; here components with little variance are discarded.

Correlated sources and PCA. If X∼N(0,Σ)\vb{X} \sim \Normal(\vb{0}, \mat{\Sigma}) with Σ=UΛU⊤\mat{\Sigma} = \mat{U}\mat{\Lambda}\mat{U}\T, coordinates Y=U⊤X\vb{Y} = \mat{U}\T\vb{X} are independent with variances λi\lambda_i, the eigenvalues. A rotation changes neither squared error (∥U⊤v∥=∥v∥\norm{\mat{U}\T\vb{v}} = \norm{\vb{v}}) nor mutual information (it is invertible), so R(D)R(D) is water-filling over the eigenvalues of Σ\mat{\Sigma}. The optimal codec rotates into the principal-component basis, discards directions with eigenvalue below θ\theta and encodes the rest with equal distortion θ\theta. PCA truncation, appearing in module 12 as the best low-rank linear approximation, is the “discard” part of this result; JPEG transform coding (the DCT approximates image-block eigenvectors) is the “rotate then quantize” part.

InteractiveReverse water-filling
Variances σi2\sigma_i^2, level θ\theta and bits per component
123404.0002.6001.7001.1000.7000.4500.2800.18θ =4.600above each bar: bits; below: σ²
Vector R(D)R(D) curve
The two largest components in original coordinates
  • encoded: variance of X^i\hat X_i, σi2−θ\sigma_i^2 - \theta
  • distortion Di=min⁡(θ,σi2)D_i = \min(\theta, \sigma_i^2)
  • optimal R(D)R(D)
  • same bits per component
  • source
  • reconstruction
θ = 4.600
Variances
4.600
Level θ\theta4.600
Total distortion D=∑imin⁡(θ,σi2)D = \sum_i \min(\theta, \sigma_i^2)11.010
Total rate R(D)R(D)0.000 bits
Encoded components0 of 8
Same bits equally: DD11.010
Total variance ∑iσi2\sum_i \sigma_i^211.01
Water covers every bar: nothing is sent, X^=0\hat{\vb{X}} = 0 and distortion is total variance.
Left: variances σi2\sigma_i^2 of eight independent components. Water rises to level θ\theta: each bar's submerged part is its distortion Di=min⁡(θ,σi2)D_i = \min(\theta, \sigma_i^2) and the blue part above water is encoded; above are each component's bits. Top right, the vector's R(D)R(D) curve compared with allocating the same total bits equally across components (orange). Below, the two largest components in rotated coordinates as correlated data: the gray cloud is the source and magenta is reconstruction by the optimal test channel. Press ▶ to lower the level. When does the last component start receiving bits? What happens to the magenta cloud when θ\theta exceeds the second variance? Try “Isotropic”: what is special about it?

Takeaways from the figure:

  • All encoded components lose the same amount. With the decaying spectrum and θ=0.303\theta = 0.303, six components receive bits and the two smallest (variances 0.280.28 and 0.180.18) are discarded. Counterintuitively, distortion is not allocated in proportion to variance, but equally while possible.
  • Allocating bits equally is costly. At that point (6.476.47 total bits, distortion 2.282.28), giving every component the same bits gives distortion 3.593.59, 57 %57\,\% higher: it spends bits on components worth less than the water level and skimps on large ones.
  • Reconstruction collapses onto principal axes. When θ\theta exceeds the second variance, the magenta cloud flattens onto a line, the first principal axis: its conditional mean E[X^∣X]\E[\hat{\vb{X}} \mid \vb{X}] is the PCA projection shrunk by 1−θ/σ121 - \theta/\sigma_1^2, and the channel adds noise along that axis.
  • Isotropic: nothing to discard. With all variances equal, either all or none are encoded, and the curve is R(D)=k2log⁡kσ2DR(D) = \frac{k}{2}\log\frac{k\sigma^2}{D}.

The Lagrangian and Blahut-Arimoto algorithm

Outside closed-form cases, R(D)R(D) is calculated numerically, using the same approach as capacity: duality and alternating minimization. Instead of imposing constraint E[d]≤D\E[d] \le D, penalize it.

Proof

(1) For any QQ, I(p,Q)+β EQ[d]≥F(β)=I(p,Qβ)+βDβI(p, Q) + \beta\,\E_Q[d] \ge F(\beta) = I(p, Q_\beta) + \beta D_\beta. If EQ[d]≤Dβ\E_Q[d] \le D_\beta, this gives I(p,Q)≥I(p,Qβ)+β(Dβ−EQ[d])≥I(p,Qβ)I(p, Q) \ge I(p, Q_\beta) + \beta(D_\beta - \E_Q[d]) \ge I(p, Q_\beta): QβQ_\beta is optimal for constraint DβD_\beta. For the supporting line, take QQ optimal for any DD: R(D)+βD≥I(p,Q)+β EQ[d]≥F(β)R(D) + \beta D \ge I(p, Q) + \beta\,\E_Q[d] \ge F(\beta).

(2) F(β)−βDF(\beta) - \beta D is the dual function of the problem defining R(D)R(D), so R(D)≥max⁡β[F(β)−βD]R(D) \ge \max_\beta [F(\beta) - \beta D] is weak duality. The problem is convex and, if D>Dmin⁡D > D_{\min}, the channel reproducing each xx by its nearest x^\hat x has distortion Dmin⁡<DD_{\min} < D: Slater’s condition holds and there is strong duality, with optimal multiplier β∗≥0\beta^* \ge 0. If D<Dmax⁡D < D_{\max}, the constraint is active (RR is strictly decreasing) and the minimizer of Lβ∗\mathcal{L}_{\beta^*} satisfying it with equality is optimal.

∎

Thus sweeping β\beta traces the curve, from endpoint (Dmax⁡,0)(D_{\max}, 0) at small β\beta to endpoint (Dmin⁡,R(Dmin⁡))(D_{\min}, R(D_{\min})) with β→∞\beta \to \infty, and β\beta is minus the slope: R′(Dβ)=−βR'(D_\beta) = -\beta where the curve is differentiable. For the fair coin, R′(D)=−log⁡1−DDR'(D) = -\log\frac{1-D}{D}, so point D=0.11D = 0.11 corresponds to β=log⁡0.890.11=3.02\beta = \log\frac{0.89}{0.11} = 3.02 bits per unit of distortion. For the Gaussian, R′(D)=−log⁡e2DR'(D) = -\frac{\log e}{2D} and Dβ=log⁡e2βD_\beta = \frac{\log e}{2\beta}.

The optimal test channel has Gibbs form

To minimize Lβ\mathcal{L}_\beta use the compensation identity from lesson 9: for any distribution q′q' over X^\hat{\mathcal{X}},

∑xp(x) KL⁡(Q(⋅∣x) ∥ q′)=I(p,Q)+KL⁡(pQ ∥ q′)≥I(p,Q),\sum_x p(x)\,\KL\big(Q(\cdot \mid x)\,\|\,q'\big) = I(p, Q) + \KL(pQ\,\|\,q') \ge I(p, Q),

with equality only if q′q' is marginal pQpQ. Therefore F(β)=min⁡Q, q′G(Q,q′)F(\beta) = \min_{Q,\, q'} G(Q, q') with

G(Q,q′)=∑xp(x)[KL⁡(Q(⋅∣x) ∥ q′)+β∑x^Q(x^∣x) d(x,x^)].G(Q, q') = \sum_x p(x)\Big[\KL\big(Q(\cdot \mid x)\,\|\,q'\big) + \beta \sum_{\hat x} Q(\hat x \mid x)\, d(x, \hat x)\Big].

For fixed q′q', the bracket for each xx is exactly the functional of the Gibbs variational principle from lesson 13, with energy d(x,⋅)d(x, \cdot) and reference measure q′q': it equals −log⁡Z(x)+KL⁡(Q(⋅∣x) ∥ Gx)-\log Z(x) + \KL\big(Q(\cdot \mid x)\,\|\,G_x\big), where GxG_x is the Gibbs distribution

Gx(x^)=q′(x^) 2−βd(x,x^)Z(x),Z(x)=∑x^q′(x^) 2−βd(x,x^).G_x(\hat x) = \frac{q'(\hat x)\, 2^{-\beta d(x, \hat x)}}{Z(x)}, \qquad Z(x) = \sum_{\hat x} q'(\hat x)\, 2^{-\beta d(x, \hat x)}.

Thus the best channel for fixed q′q' is Gibbs, and the best q′q' for fixed QQ is its marginal. At the optimum both conditions hold: the optimal test channel weights each reproduction by its frequency and penalizes it exponentially for its distortion, at temperature 1/β1/\beta. With small β\beta (high temperature) the channel ignores distortion and copies the marginal; with large β\beta it concentrates on the nearest reproduction.

Alternating the two exact minimizations gives Blahut’s algorithm (1972), a sibling of the capacity algorithm:

Qk(x^∣x)=qk(x^) 2−βd(x,x^)Zk(x),qk+1(x^)=∑xp(x) Qk(x^∣x)=qk(x^) ck(x^),ck(x^)=∑xp(x) 2−βd(x,x^)Zk(x).Q_k(\hat x \mid x) = \frac{q_k(\hat x)\,2^{-\beta d(x, \hat x)}}{Z_k(x)}, \qquad q_{k+1}(\hat x) = \sum_x p(x)\, Q_k(\hat x \mid x) = q_k(\hat x)\, c_k(\hat x), \qquad c_k(\hat x) = \sum_x \frac{p(x)\,2^{-\beta d(x, \hat x)}}{Z_k(x)}.

This is another multiplicative update: each reproduction multiplies its probability by ck(x^)c_k(\hat x), measuring how much nearby xx “claim” it. Each step lowers GG, which is bounded below, and the sequence converges to the minimum (Csiszár and Tusnády, 1984). As in capacity, there are bounds on both sides at each iteration. With Dk=EQk[d]D_k = \E_{Q_k}[d]:

Lk=−βDk−∑xp(x)log⁡Zk(x)−log⁡max⁡x^ck(x^)  ≤  R(Dk)  ≤  I(p,Qk).L_k = -\beta D_k - \sum_x p(x)\log Z_k(x) - \log\max_{\hat x} c_k(\hat x) \;\le\; R(D_k) \;\le\; I(p, Q_k).

The upper bound is immediate: QkQ_k is a channel with distortion DkD_k. The lower bound follows from duality. For any channel QQ with marginal qQq_Q and distortion ≤Dk\le D_k, with λ(x)=1/(Zk(x)max⁡ck)\lambda(x) = 1/\big(Z_k(x)\max c_k\big), Gibbs’ inequality applied to mass p(x)Q(x^∣x)p(x)Q(\hat x \mid x) against unnormalized weights p(x)qQ(x^)λ(x)2−βd(x,x^)p(x)q_Q(\hat x)\lambda(x)2^{-\beta d(x, \hat x)} gives I(p,Q)−∑xp(x)log⁡λ(x)+β EQ[d]≥−log⁡∑x^qQ(x^) ck(x^)max⁡ck≥0I(p, Q) - \sum_x p(x)\log\lambda(x) + \beta\,\E_Q[d] \ge -\log\sum_{\hat x} q_Q(\hat x)\,\frac{c_k(\hat x)}{\max c_k} \ge 0, which is I(p,Q)≥LkI(p, Q) \ge L_k. Substituting Gibbs form into I(p,Qk)I(p, Q_k) yields the exact gap:

I(p,Qk)−Lk=log⁡max⁡x^ck(x^)−∑x^qk+1(x^)log⁡ck(x^)  ≥  0,I(p, Q_k) - L_k = \log\max_{\hat x} c_k(\hat x) - \sum_{\hat x} q_{k+1}(\hat x)\log c_k(\hat x) \;\ge\; 0,

which vanishes exactly when ckc_k is constant on used reproductions and no greater on the others; since ∑x^qk(x^) ck(x^)=1\sum_{\hat x} q_k(\hat x)\, c_k(\hat x) = 1, that constant is 1. This is the KKT condition: at the optimum, each used reproduction is claimed exactly as much as it is used (c=1c = 1), and unused ones at most that much (c≤1c \le 1).

InteractiveBlahut-Arimoto sweeping β
The R(D)R(D) curve and supporting line of slope −β-\beta
Iterations to convergence versus β\beta
Test channel Q(x^∣x)Q(\hat x \mid x) and its marginal q(x^)q(\hat x)
x̂1x̂2x̂3x̂4x1p = 0.400.001.000.000.00x2p = 0.100.001.000.000.00x3p = 0.200.001.000.000.00x4p = 0.300.001.000.000.00
Marginal q(x^)q(\hat x) versus β\beta: splits
  • x̂1
  • x̂2
  • x̂3
  • x̂4
SOURCE p(x), NORMALIZED ON EDIT
DISTORTION d(x, x̂): ROW x, COLUMN x̂
  • R(D)R(D) traced by sweeping β\beta
  • line R+βD=R + \beta D = Lagrangian minimum
β = 0.020
0.020
β\beta0.020
Distortion Dβ=E[d(X,X^)]D_\beta = \E[d(X, \hat X)]1.8000
Rate R(Dβ)=I(X;X^)R(D_\beta) = I(X; \hat X)0.0000 bits
Blahut lower bound0.0000 bits
Iterations to gap <10−7< 10^{-7}4666
Reproduction symbols used1 of 4
H(X)H(X), Dmax⁡D_{\max}1.846 bits, 1.800
With β\beta this small distortion barely weighs: everything is reproduced by the symbol minimizing E[d]\E[d] and rate is 0 (D=Dmax⁡=1.800D = D_{\max} = 1.800).
A 4-symbol source with editable distortion matrix. For each β\beta, Blahut-Arimoto minimizes I+β E[d]I + \beta\,\E[d] from a uniform marginal and produces a point on the curve (left), where magenta line R+βD=F(β)R + \beta D = F(\beta) touches it from below. Below are the iterations needed to close the gap. Right: test channel Q(x^∣x)Q(\hat x \mid x) (rows: source; columns: reproduction; bars: marginal q(x^)q(\hat x)) and marginal versus β\beta. Press ▶: how many reproduction symbols are initially used, and which? What happens to iterations just as a symbol is born? With “Two groups”, why does distortion fall so much with a small change in β\beta?

What to look for:

  • From collapsing everything to identity. With small β\beta all channel rows are equal: everything is reproduced by the symbol minimizing mean distortion (in the first example x^2\hat x_2, closest to the source mean) and rate is zero. As β\beta increases, new reproductions appear until the channel is identity, with D→0D \to 0 and R→H(X)R \to H(X).
  • Reproduction symbols split. On the plot of q(x^)q(\hat x) against β\beta, each symbol is born at a critical β\beta when its c(x^)c(\hat x) reaches 1. In the line example one is even used, abandoned and returns: the solution rearranges reproductions like soft kk-means gaining centers as temperature drops. (The analogy is literal: module 12 will cover kk-means as vector quantization and deterministic annealing as this same algorithm.)
  • Convergence slows near a split. Iterations surge from tens to thousands at critical β\beta and small β\beta: the direction in which a symbol gains or loses mass is nearly flat. This parallels almost-abandoned inputs in capacity.
  • A sharp fall in DD is an almost straight section of the curve. In “Two groups”, distortion falls from 1.81.8 to 1.11.1 while β\beta barely moves from 0.290.29 to 0.350.35: x^1\hat x_1 is born and replaces x^2\hat x_2 as representative of the first group. Since the curve’s slope is −β-\beta, it is nearly straight there. The fall is continuous (with very fine tolerance D(β)D(\beta) does not jump), but illustrates the limit: if DD jumped at fixed β\beta, the supporting line would touch the curve along a whole segment (two solutions with the same β\beta and everything between them by time sharing), and sweeping β\beta would give only its endpoints.

Implementation from scratch

First, Blahut-Arimoto with its bounds, validated against the binary formula and relation β=−R′(D)\beta = -R'(D), and the sweep of the figure’s four-symbol source.

[ ]Blahut-Arimoto for R(D), with boundsBrowser
import numpy as np

def blahut_rd(p, d, beta, tol=1e-9, max_iter=20_000):
    """Minimiza I(X; Xh) + beta E[d]. p: fuente; d[x, xh]: distorsión. Devuelve R, D, cota inferior, canal y marginal."""
    p, d = np.asarray(p, float), np.asarray(d, float)
    A = 2.0 ** (-beta * d)
    q = np.full(d.shape[1], 1 / d.shape[1])            # marginal inicial con soporte completo
    for k in range(max_iter):
        Z = A @ q                                       # Z(x)
        Q = A * q / Z[:, None]                          # canal de Gibbs
        c = (p / Z) @ A                                 # c(xh): cuánto reclaman las x a cada reproducción
        q_nueva = q * c                                 # = p Q
        D = float(np.sum(p[:, None] * Q * d))
        with np.errstate(divide="ignore", invalid="ignore"):
            I = float(np.sum(np.where(Q > 0, p[:, None] * Q * np.log2(Q / q_nueva), 0.0)))
        L = -beta * D - float(p @ np.log2(Z)) - float(np.log2(c.max()))
        if I - L < tol:                                 # parada por la brecha certificada
            break
        q = q_nueva
    return {"R": I, "D": D, "L": L, "Q": Q, "q": q_nueva, "iter": k + 1}

h2 = lambda x: -x * np.log2(x) - (1 - x) * np.log2(1 - x)
hamming = np.array([[0, 1], [1, 0]])
for p1 in [0.5, 0.2]:
    for beta in [3.0, 5.0]:
        r = blahut_rd([1 - p1, p1], hamming, beta)
        print(f"Bern({p1}), beta = {beta}: D = {r['D']:.5f}  R = {r['R']:.6f}  h2(p) - h2(D) = {h2(p1) - h2(r['D']):.6f}  iteraciones = {r['iter']}")
print("pendiente: D = 1/(1 + 2^beta) da", [round(1 / (1 + 2**b), 5) for b in [3, 5]])

# la fuente de la figura: cuatro puntos en una recta, distorsión cuadrática
pos = np.array([0.0, 1, 2, 3]); p = np.array([0.4, 0.1, 0.2, 0.3])
d = (pos[:, None] - pos[None, :]) ** 2
print("\n beta     D        R       cota L    iteraciones   q(xh)")
for beta in [0.05, 0.3, 0.7, 1.5, 3, 6]:
    r = blahut_rd(p, d, beta, tol=1e-7)
    print(f"{beta:5.2f}  {r['D']:.4f}  {r['R']:.4f}   {r['L']:.4f}    {r['iter']:6d}      {np.round(r['q'], 3)}")

Both binary validations match h2(p)−h2(D)h_2(p) - h_2(D) to six digits; with p=12p = \tfrac12 the uniform marginal is already optimal and the algorithm ends on the first iteration, with D=1/(1+2β)D = 1/(1 + 2^\beta), the slope-multiplier relation. The four-symbol source shows everything in the figure: at β=0.05\beta = 0.05 one symbol and thousands of iterations, at β=0.7\beta = 0.7 another bottleneck as support reorganizes, and from β=3\beta = 3 all four symbols in use and convergence in a few dozen steps.

Now a continuous source: discretize N(0,1)\Normal(0, 1) on a fine grid, use the same grid as reproduction alphabet and compare with 12log⁡(1/D)\frac12\log(1/D). Here the optimal marginal is a discretized Gaussian with full support, so the gap closes slowly; we limit iterations and report the gap.

[ ]A discretized Gaussian versus the closed formulaBrowser
import numpy as np

def blahut_rd(p, d, beta, iteraciones):
    A = 2.0 ** (-beta * d)
    q = np.full(d.shape[1], 1 / d.shape[1])
    for _ in range(iteraciones):
        Z = A @ q
        c = (p / Z) @ A
        q = q * c
    Q = A * q / (A @ q)[:, None]
    qm = p @ Q
    D = float(np.sum(p[:, None] * Q * d))
    I = float(np.sum(p[:, None] * Q * np.log2(np.maximum(Q, 1e-300) / qm)))
    return D, I, float(np.log2(c.max()) - np.sum(qm * np.log2(c)))   # la última, la brecha I - L

x = np.linspace(-4.5, 4.5, 91)
p = np.exp(-x**2 / 2); p /= p.sum()
d = (x[:, None] - x[None, :]) ** 2
print(" beta      D       R (Blahut)   1/2 log2(1/D)   brecha")
for beta in [1.0, 3.0, 8.0]:
    D, R, brecha = blahut_rd(p, d, beta, 600)
    print(f"{beta:4.1f}   {D:.4f}    {R:.4f}        {0.5 * np.log2(1 / D):.4f}       {brecha:.1e}")
print("D teórica para cada beta: log2(e) / (2 beta) =", [round(np.log2(np.e) / (2 * b), 4) for b in [1.0, 3.0, 8.0]])

The calculated rate matches 12log⁡1D\frac12\log\frac1D to three or four digits, and distortion matches Dβ=log⁡e2βD_\beta = \frac{\log e}{2\beta}: the discretized Gaussian behaves like the continuous one while the grid is much finer than D\sqrt{D}. This is also a practical warning: with large continuous reproduction alphabets, Blahut-Arimoto converges slowly, so modern methods for continuous sources optimize a parameterized reproduction using gradients (last section).

Scalar quantization versus Shannon’s limit

The limit R(D)R(D) is achieved with long blocks. How much is lost with the simplest approach, a uniform scalar quantizer (rounding each sample to a multiple of Δ\Delta) followed by entropy coding of the index (Huffman or arithmetic, lesson 7)? At high resolution there is a clean answer. If density is smooth and Δ\Delta is small, quantization error is nearly uniform on [−Δ/2,Δ/2][-\Delta/2, \Delta/2], with

D≈Δ212,H(X^)≈h(X)−log⁡Δ,D \approx \frac{\Delta^2}{12}, \qquad H(\hat X) \approx h(X) - \log\Delta,

the second because each cell has probability ≈f(x)Δ\approx f(x)\Delta. Eliminating Δ\Delta, quantizer rate is h(X)−12log⁡(12D)h(X) - \frac12\log(12 D), while Shannon’s lower bound is h(X)−12log⁡(2πeD)h(X) - \frac12\log(2\pi e D) (exact for the Gaussian). The difference depends on neither source nor distortion:

Rescalar(D)−R(D)≈12log⁡2πe12=0.2546 bits,o, a igual tasa,10log⁡10πe6=1.53 dB de distorsioˊn.R_{\text{escalar}}(D) - R(D) \approx \frac12\log\frac{2\pi e}{12} = 0.2546 \text{ bits}, \qquad\text{o, a igual tasa,}\quad 10\log_{10}\frac{\pi e}{6} = 1.53 \text{ dB de distorsión}.

This is the price of quantizing one at a time: scalar quantizer cells, viewed in nn dimensions, are cubes, and a cube has more moment of inertia than a sphere of the same volume. Vector quantizers with rounder cells (high-dimensional lattices) gradually recover the difference. The cell calculates the exact Gaussian curve without simulation: cell probabilities from the distribution function and reproduction at each cell centroid.

[ ]Entropy-coded uniform quantizer versus R(D)Browser
import numpy as np
from scipy.stats import norm

print(" paso    H(índice)    D (centroide)   R(D) = 1/2 log2(1/D)   brecha (bits)   brecha (dB)")
for paso in [3.0, 2.0, 1.0, 0.5, 0.25, 0.1]:
    bordes = np.arange(-12 - paso / 2, 12 + paso, paso)            # celdas centradas en múltiplos del paso
    P = np.diff(norm.cdf(bordes))
    m1 = norm.pdf(bordes[:-1]) - norm.pdf(bordes[1:])              # integral de x f(x) en cada celda
    m2 = P + bordes[:-1] * norm.pdf(bordes[:-1]) - bordes[1:] * norm.pdf(bordes[1:])   # integral de x^2 f(x)
    usadas = P > 1e-300
    D = float(np.sum(m2[usadas] - m1[usadas] ** 2 / P[usadas]))   # reproducción en el centroide
    H = float(-np.sum(P[usadas] * np.log2(P[usadas])))
    R = 0.5 * np.log2(1 / D)
    print(f"{paso:5.2f}    {H:7.4f}      {D:9.5f}          {R:7.4f}             {H - R:.4f}         {10 * np.log10(D * 4**H):.3f}")
print(f"\nteoría a alta resolución: {0.5 * np.log2(2 * np.pi * np.e / 12):.4f} bits, {10 * np.log10(np.pi * np.e / 6):.3f} dB")

The gap stabilizes at 0.25460.2546 bits (1.5331.533 dB) once the step falls below 11 (about 2 bits per sample), and at lower rates it is somewhat smaller. The practical message is strong: a uniform scalar quantizer with good entropy coding is within a quarter bit of optimal at any reasonable rate. That is why real codecs, classic and learned, are mostly “transform + scalar quantization + entropy coding”: the transform handles correlation (water-filling), rounding is nearly free and entropy coding charges what the probability model says.

The library version: bit allocation for a correlated source

For a correlated Gaussian, numpy.linalg.eigh gives the principal-component basis and water-filling does the rest. We check against a generic optimizer, scipy.optimize.minimize, which allocates distortion knowing nothing about water levels, and against encoding in the original coordinates.

[ ]Water-filling on eigenvalues and SciPy checkBrowser
import numpy as np
from scipy.optimize import minimize

rng = np.random.default_rng(1)
k = 8
U, _ = np.linalg.qr(rng.normal(size=(k, k)))
Sigma = U @ np.diag([4, 2.6, 1.7, 1.1, 0.7, 0.45, 0.28, 0.18]) @ U.T       # covarianza correlacionada
lam = np.linalg.eigvalsh(Sigma)[::-1]

def llenado_inverso(var, D):
    lo, hi = 0.0, var.max()
    for _ in range(100):                                    # bisección en el nivel theta
        theta = (lo + hi) / 2
        lo, hi = (theta, hi) if np.minimum(theta, var).sum() < D else (lo, theta)
    Di = np.minimum(theta, var)
    return 0.5 * np.log2(var / Di).sum(), Di, theta

D = 2.0
R, Di, theta = llenado_inverso(lam, D)
print(f"autovalores: {np.round(lam, 3)}")
print(f"D = {D}: theta = {theta:.4f}, R(D) = {R:.4f} bits, componentes descartadas: {(lam <= theta).sum()}")

# scipy reparte la distorsión sin conocer la regla del nivel de agua
obj = lambda t: 0.5 * np.sum(np.log2(lam / np.minimum(np.exp(t), lam)))
res = minimize(obj, np.log(np.full(k, D / k)), method="SLSQP",
               constraints=[{"type": "eq", "fun": lambda t: np.minimum(np.exp(t), lam).sum() - D}])
print(f"scipy (SLSQP): R = {res.fun:.4f} bits, D_i = {np.round(np.minimum(np.exp(res.x), lam), 3)}")

# sin girar: llenado sobre las varianzas marginales (la diagonal de Sigma), lo que haría un códec que ignora la correlación
R_diag, _, _ = llenado_inverso(np.diag(Sigma), D)
print(f"codificando en las coordenadas originales: R = {R_diag:.4f} bits ({R_diag - R:+.4f})")

The generic optimizer finds the same allocation (each encoded component at distortion θ\theta, the rest discarded) and rate. Encoding in original coordinates one component at a time costs clearly more: it is a valid upper bound (coordinates are not independent, but encoding separately is still a possible scheme) and pays for correlation not removed. Rotating first saves that cost.

Learned compression and the rate-distortion plane

Everything above assumes the source distribution is known. For images or sound it is not, and learned compression replaces calculation with optimization of a parameterized codec on data, using the same objective: the Lagrangian.

Ballé, Laparra and Simoncelli (2017). An encoder y=ga(x)\vb{y} = g_a(\vb{x}) (the “analysis transform”), rounding y^=round(y)\hat{\vb{y}} = \mathrm{round}(\vb{y}), a decoder x^=gs(y^)\hat{\vb{x}} = g_s(\hat{\vb{y}}) and an entropy model P(y^)P(\hat{\vb{y}}), all learned. The loss is

E[−log⁡P(y^)]+λ E[d(x,x^)],\E\big[-\log P(\hat{\vb{y}})\big] + \lambda\,\E\big[d(\vb{x}, \hat{\vb{x}})\big],

the rate an arithmetic coder guided by PP would charge plus λ\lambda for distortion: this lesson’s Lagrangian with β=λ\beta = \lambda. The obstacle is that rounding has zero derivative almost everywhere. The solution is to train with noise: replace y^\hat{\vb{y}} by y~=y+u\tilde{\vb{y}} = \vb{y} + \vb{u}, with u∼Unif⁡[−12,12]k\vb{u} \sim \Unif[-\tfrac12, \tfrac12]^k, and the mass of y^\hat y by the density of y~\tilde y, the model density convolved with a box: P(y~)=F(y~+12)−F(y~−12)P(\tilde y) = F(\tilde y + \tfrac12) - F(\tilde y - \tfrac12), with FF the model distribution function. At integers it matches the mass of y^\hat y and between them interpolates differentiably. With this trick the codec trains with Adam and backpropagation like any network (in PyTorch, following the correspondence between mathematics and code), and is evaluated with actual rounding.

β-VAE and the rate-distortion plane (Alemi et al., 2018). A variational autoencoder has stochastic encoder q(z∣x)q(\vb{z} \mid \vb{x}), prior p(z)p(\vb{z}) and decoder p(x∣z)p(\vb{x} \mid \vb{z}). Its two terms are distortion and rate:

D=E[−log⁡p(x∣z)],R=Ex[KL⁡(q(z∣x) ∥ p(z))]  ≥  I(X;Z),D = \E\big[-\log p(\vb{x} \mid \vb{z})\big], \qquad R = \E_{\vb{x}}\Big[\KL\big(q(\vb{z} \mid \vb{x})\,\|\,p(\vb{z})\big)\Big] \;\ge\; I(\vb{X}; \vb{Z}),

and the inequality is the compensation identity again: mutual information is mean divergence from the latent marginal, and the prior is another arbitrary distribution. ELBO is −(D+R)-(D + R) and β-VAE minimizes D+βRD + \beta R. Beware notation: in β-VAE the coefficient multiplies rate, so it is the inverse of this lesson’s multiplier β\beta. Increasing the β-VAE’s β\beta makes distortion cheaper relative to rate and moves the model toward less rate and more distortion.

InteractiveAutoencoders in the rate-distortion plane
Above, originals; below, reconstructions with β=1.00\beta = 1.00
Each model: 784-256-16 MLP encoder and decoder, trained for 8 epochs on 20,000 binarized images; RR and DD measured on 2000 test images. Reconstruction shows P(xj=1∣z)\Pr(x_j = 1 \mid z).
  • trained β-VAEs
  • estimated frontier (convex envelope)
  • constant R+DR + D (same ELBO)
  • selected model line D+βRD + \beta R
1.00
Reconstruction
Lines
β\beta (loss D+βRD + \beta R)1.00
Rate R=E KL⁡(q(z∣x) ∥ p(z))R = \E\,\KL(q(z \mid x)\,\|\,p(z))33.8 bits
Distortion D=−Elog⁡2p(x∣z)D = -\E \log_2 p(x \mid z)119.5 bits
R+DR + D (negative ELBO)153.3 bits
Best R+DR + D overall153.3 bits (β = 1.0)
Zero rate: DD without latent287.9 bits
β=1\beta = 1 is the standard VAE: it minimizes R+D=153.3R + D = 153.3 bits, negative ELBO. Its neighbors have almost equal ELBO and allocate information very differently.
Eleven β-VAEs trained on binarized MNIST, each with a β\beta (in the β-VAE convention, multiplying rate), plotted in the (distortion, rate) plane, both in bits per image. The dashed gray line is the lower convex envelope of models and the zero-rate point: the estimated achievable frontier (by time sharing, everything above it can be achieved). The orange line joins models with the same ELBO as the best; magenta is the selected model's constant D+βRD + \beta R line. Start at β=1\beta = 1: which models have nearly the same ELBO? Lower to β=0.1\beta = 0.1 and raise to β=16\beta = 16: what is preserved of each digit? Compare “sample” and “mean” with β=8\beta = 8.

What the figure shows, with numbers from that experiment:

  • All models lie on a convex curve. Going down from β=16\beta = 16 to β=0.1\beta = 0.1, rate rises from 1.21.2 to 8484 bits per image and distortion falls from 265265 to 103103 bits. The curve’s slope at each model is that of its line D+βRD + \beta R: β\beta selects the support point, just as in Blahut-Arimoto.
  • ELBO does not distinguish points on the same line. The standard VAE (β=1\beta = 1) has the best R+DR + D, 153.3153.3 bits; those at β=0.7\beta = 0.7 and β=1.5\beta = 1.5 are 0.60.6 and 1.31.3 bits away, but their rates are 3939 and 2828 bits: one stores more than 40 %40\,\% more information about the image than the other with nearly identical likelihood. At the extreme, a very powerful (autoregressive) decoder can achieve a good ELBO with R≈0R \approx 0, ignoring the latent: posterior collapse. If representation matters, likelihood is insufficient: one must decide where to be on the curve, choosing β\beta.
  • At low rate the model keeps coarse shape and sometimes changes identity. With β=4\beta = 4 reconstructions are plausible digits, but some are no longer the original: 2 becomes 3 and 4 becomes 9. With β=8\beta = 8 almost all merge into generic shapes, and with β=16\beta = 16 (a little over one bit) reconstructions are almost identical blobs. Using the mean of q(z∣x)q(\vb{z} \mid \vb{x}) rather than a sample removes latent noise, and with β=8\beta = 8 several identities return (1 becomes 1 again): at low rate, much of the distortion is noise the encoder deliberately adds to avoid spending rate.

That last point has a name. Blau and Michaeli showed (in 2018, and in 2019 with rate) that distortion and perceptual quality (reconstruction having the distribution of real images) conflict: the minimum-squared-error reconstructor averages images compatible with the code and becomes blurry, like the optimal Gaussian reconstruction, which shrank variance from σ2\sigma^2 to σ2−D\sigma^2 - D. Also requiring X^\hat X to have the same distribution as XX costs rate or distortion, defining a rate-distortion-perception surface. In the Gaussian case, among jointly Gaussian schemes with correlation ρ\rho fixed by rate, requiring Var⁡(X^)=σ2\Var(\hat X) = \sigma^2 moves distortion from σ2(1−ρ2)\sigma^2(1 - \rho^2) to 2σ2(1−ρ)2\sigma^2(1 - \rho), a factor 21+ρ∈[1,2]\frac{2}{1 + \rho} \in [1, 2]; Blau and Michaeli show that with squared error, perfect perception never costs more than twice the minimum distortion at the same rate. Generative codecs (with GAN or diffusion in the decoder) deliberately choose that point: less faithful in squared error, more plausible.

The local cell trains the smallest possible Ballé codec on MNIST: an analysis MLP and synthesis MLP, 64-coordinate latent, rounding simulated with uniform noise and a factorized entropy model (one learned logistic per coordinate), at three values of λ\lambda; it then measures actual rate with the rounded latent and compares it with JPEG on a mosaic of 10×1010 \times 10 digits so file-header cost is shared. It runs on CPU in about a minute.

[ ]Minimal learned compression versus JPEGLocal GPU
import io, os, time
import numpy as np
import torch
from torch import nn
from torchvision import datasets
from PIL import Image

torch.set_num_threads(2)
torch.manual_seed(0)
t0 = time.time()
root = os.path.join(os.path.expanduser("~"), ".cache", "atlas-data")             # MNIST se descarga la primera vez (unos 11 MB)
tr = datasets.MNIST(root, train=True, download=True)
te = datasets.MNIST(root, train=False, download=True)
Xtr = (tr.data[:20000].float() / 255).view(-1, 784)                            # modelo diminuto: en CPU basta
Xte = (te.data[:1000].float() / 255).view(-1, 784)
LATENTE = 64

class Compresor(nn.Module):
    def __init__(self):
        super().__init__()
        self.g_a = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, LATENTE))                # análisis
        self.g_s = nn.Sequential(nn.Linear(LATENTE, 256), nn.ReLU(), nn.Linear(256, 784), nn.Sigmoid())   # síntesis
        self.loc = nn.Parameter(torch.zeros(LATENTE))                       # modelo de entropía factorizado:
        self.log_esc = nn.Parameter(torch.zeros(LATENTE))                   # una logística por coordenada

    def bits(self, y):
        """-log2 P(y), con P(k) = F(k + 1/2) - F(k - 1/2) y F la función de distribución logística."""
        s = self.log_esc.exp()
        sup = torch.sigmoid((y + 0.5 - self.loc) / s)
        inf = torch.sigmoid((y - 0.5 - self.loc) / s)
        return -torch.log2((sup - inf).clamp_min(1e-9)).sum(-1)

    def forward(self, x, entrenando):
        y = self.g_a(x)
        y_t = y + torch.rand_like(y) - 0.5 if entrenando else torch.round(y)   # ruido uniforme en lugar de redondear
        return self.g_s(y_t), self.bits(y_t)

def entrenar(lam, epocas=10):
    m = Compresor()
    opt = torch.optim.Adam(m.parameters(), 2e-3)
    for _ in range(epocas):
        perm = torch.randperm(len(Xtr))
        for i in range(0, len(Xtr), 128):
            x = Xtr[perm[i:i + 128]]
            x_r, R = m(x, entrenando=True)
            perdida = (R + lam * ((x_r - x) ** 2).sum(-1)).mean()          # tasa + lambda * distorsión
            opt.zero_grad(); perdida.backward(); opt.step()
    return m

psnr = lambda mse: 10 * np.log10(1 / mse)
print(" lambda   bits/imagen (redondeo)   bits (ruido)   PSNR (dB)")
aprendido = []
for lam in [8, 64, 1024]:
    m = entrenar(lam)
    with torch.no_grad():
        x_r, R = m(Xte, entrenando=False)                                   # rendimiento real: latente redondeado
        _, R_ruido = m(Xte, entrenando=True)
        mse = float(((x_r - Xte) ** 2).mean())
    aprendido.append((float(R.mean()), psnr(mse)))
    print(f" {lam:6d}       {float(R.mean()):7.1f}              {float(R_ruido.mean()):7.1f}       {psnr(mse):6.2f}")

mosaico = (Xte[:100].view(10, 10, 28, 28).permute(0, 2, 1, 3).reshape(280, 280).numpy() * 255).round().astype(np.uint8)
jpeg = []
for calidad in [5, 10, 20, 35, 50, 75, 90]:
    buf = io.BytesIO()
    Image.fromarray(mosaico).save(buf, format="JPEG", quality=calidad)
    rec = np.asarray(Image.open(io.BytesIO(buf.getvalue())), dtype=np.float64) / 255
    jpeg.append((8 * len(buf.getvalue()) / 100, psnr(np.mean((rec - mosaico / 255) ** 2))))
print("JPEG (bits/imagen, PSNR):", [(round(b), round(float(q), 1)) for b, q in jpeg])
for b, q in aprendido:
    suficientes = [jb for jb, jq in jpeg if jq >= q]
    print(f"aprendido: {b:5.0f} bits para {q:.1f} dB;  JPEG necesita {min(suficientes):.0f} bits para igualarlo" if suficientes else f"aprendido: {b:.0f} bits, {q:.1f} dB")
print(f"tiempo: {time.time() - t0:.0f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exact numbers vary somewhat across machines, but the pattern is stable. Rate measured with rounded latent matches noise-training rate within a couple of bits per image: the uniform-noise trick measures what it promises. JPEG does not go below about 380 bits per digit even at minimum quality (its 8×88 \times 8 blocks and tables have fixed cost), giving about 20.7 dB there; the learned codec exceeds that quality with about 170 bits, less than half, and still gives about 18.6 dB at 75 bits, a region JPEG cannot reach. At the other extreme the tiny model saturates near 21 dB due to limited capacity and training, and high-quality JPEG surpasses it. Serious learned codecs (with convolutional networks and a hierarchical prior adapting the entropy model per image) outperform JPEG and its successors across the rate range.

Common mistakes

Exercises

NumericR(D) of a fair coin
A source of equiprobable bits, X∼Bern⁡(1/2)X \sim \Bern(1/2), is compressed with Hamming distortion. What is the minimum bits per symbol required for mean distortion D=0.11D = 0.11?
NumericOne bit for a Gaussian
A source X∼N(0,1)X \sim \Normal(0, 1) is compressed with mean squared error D=0.25D = 0.25. What is R(D)R(D) in bits per sample?
NumericThe multiplier at a curve point
For a Bern⁡(1/2)\Bern(1/2) source with Hamming distortion, what β\beta (bits per unit distortion) makes the minimum of I(X;X^)+β E[d]I(X;\hat X) + \beta\,\E[d] occur at D=0.11D = 0.11?
NumericReverse water-filling with three components
A Gaussian source has three independent components with variances 44, 11 and 0.250.25. With total distortion (sum of mean squared errors) D=1.5D = 1.5, what is R(D)R(D) in bits?
NumericThe scalar quantizer's quarter bit
At high resolution, how many extra bits per sample does a uniform scalar quantizer with ideal entropy coding need relative to R(D)R(D) for a Gaussian source with squared error?
QuizChanging β in a β-VAE
A β-VAE minimizes D+βRD + \beta R, with D=E[−log⁡p(x∣z)]D = \E[-\log p(x \mid z)] and R=E KL⁡(q(z∣x) ∥ p(z))R = \E\,\KL(q(z \mid x)\,\|\,p(z)). What happens as β\beta increases, and why does ELBO not suffice to choose among models on the same curve?
QuizWhy can the curve have no concave section?
An engineer measures operational curves of several codecs and finds their points' lower boundary has a concave section between codecs A and B. What can they conclude?
QuizWhich is a valid rate measure?
A learned codec produces latent y∈R64\vb{y} \in \R^{64}. Which quantities validly measure rate in bits per image?

More than one answer may be correct.

ProofR(D) is convex
Prove: For a source pp over a finite alphabet and distortion dd, R(D)=min⁡Q: E[d]≤DI(p,Q)R(D) = \min_{Q:\,\E[d] \le D} I(p, Q) is convex in DD.
0
Let D1,D2≥Dmin⁡D_1, D_2 \ge D_{\min}, λ∈[0,1]\lambda \in [0, 1] and Q1,Q2Q_1, Q_2 be optimal test channels for D1D_1 and D2D_2.

Step 1 of 4. What channel bounds R(λD1+(1−λ)D2)R(\lambda D_1 + (1-\lambda)D_2)?

ProofGaussian rate-distortion
Prove: For X∼N(0,σ2)X \sim \Normal(0, \sigma^2) with squared error and 0<D≤σ20 < D \le \sigma^2, R(D)=12log⁡σ2DR(D) = \tfrac12\log\frac{\sigma^2}{D}.
0
Let X^\hat X be any reproduction with E[(X−X^)2]≤D\E[(X - \hat X)^2] \le D.

Step 1 of 3. How is I(X;X^)I(X; \hat X) rewritten to expose the error?

CodeImplement reverse water-filling
Implement reverse_water_filling(variances, D) for a Gaussian source with independent components of variances variances and total distortion D (sum of mean squared errors). Return (R, Di): total rate R(D)R(D) in bits and an array of each component's distortion, Di=min⁡(θ,σi2)D_i = \min(\theta, \sigma_i^2), with level θ\theta such that ∑iDi=D\sum_i D_i = D (tolerance 10−910^{-9}). If D≥∑iσi2D \ge \sum_i \sigma_i^2, rate is 0 and Di=σi2D_i = \sigma_i^2. Discarded components contribute zero rate.
import numpy as np

def reverse_water_filling(variances, D):
  """Llenado de agua inverso. Devuelve (R en bits, array D_i)."""
  var = np.asarray(variances, dtype=float)
  # tu código: busca el nivel theta (bisección o recorriendo las varianzas ordenadas)
  return 0.0, np.zeros_like(var)
Shift+Enter to run

Summary

Key idea
The rate-distortion function R(D)=min⁡I(X;X^)R(D) = \min I(X;\hat X) over test channels with mean distortion ≤D\le D is the lowest rate at which a memoryless source can be compressed with distortion DD: the converse follows from data processing and convexity, and achievability from covering typical sequences with a random codebook. It is convex and decreasing, equals h2(p)−h2(D)h_2(p) - h_2(D) for a coin and 12log⁡(σ2/D)\tfrac12\log(\sigma^2/D) for a Gaussian, and allocates distortion in Gaussian vectors by reverse water-filling. The Lagrangian I+β E[d]I + \beta\,\E[d] traces it point by point with Gibbs channels and is the same objective optimized by learned codecs and β-VAEs.
  • Operational problem. Codes (2nR,n)(2^{nR}, n) with mean distortion ≤D\le D; Dmax⁡=min⁡x^E[d(X,x^)]D_{\max} = \min_{\hat x}\E[d(X, \hat x)] is free.
  • Definition and properties. R(D)=min⁡Q: Ed≤DI(p,Q)R(D) = \min_{Q:\,\E d \le D} I(p, Q): nonincreasing, convex (time sharing; convexity of II in the channel), zero from Dmax⁡D_{\max}, R(0)=H(X)R(0) = H(X) with Hamming.
  • Theorem. Converse: nR≥I(Xn;X^n)≥∑iI(Xi;X^i)≥nR(D)nR \ge I(X^n; \hat X^n) \ge \sum_i I(X_i; \hat X_i) \ge nR(D). Achievability: 2nR2^{nR} random words cover the typical set if R>IR > I. This covering problem is dual to channel coding’s packing.
  • Closed formulas. Bernoulli: h2(p)−h2(D)h_2(p) - h_2(D), backward channel X=X^⊕ZX = \hat X \oplus Z. Gaussian: 12log⁡(σ2/D)\tfrac12\log(\sigma^2/D), D(R)=σ22−2RD(R) = \sigma^2 2^{-2R} (6.02 dB per bit), and it is the hardest source at given variance.
  • Reverse water-filling. Di=min⁡(θ,σi2)D_i = \min(\theta, \sigma_i^2): encoded components all lose θ\theta and those with smaller variance are discarded. With correlation, apply to eigenvalues: PCA plus quantization.
  • Lagrangian and Blahut-Arimoto. min⁡QI+β Ed\min_Q I + \beta\,\E d gives the point with slope −β-\beta; optimal channel Q(x^∣x)∝q(x^)2−βd(x,x^)Q(\hat x \mid x) \propto q(\hat x)2^{-\beta d(x, \hat x)}; update q←q cq \leftarrow q\,c with bounds Lk≤R(Dk)≤I(p,Qk)L_k \le R(D_k) \le I(p, Q_k). Slow with small β\beta and near splits.
  • Practical quantization. Uniform scalar plus entropy coding: 0.25460.2546 bits (1.531.53 dB) from the limit at high resolution.
  • Learned compression. Ballé: rate E[−log⁡P(y^)]\E[-\log P(\hat{\vb{y}})] with uniform noise in training and rounding in evaluation. β-VAE: D+βRD + \beta R, with β\beta on rate; ELBO does not distinguish points on the same line. Rate-distortion-perception: realism costs up to twice the distortion.