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
- 07Mutual informationData processing inequalitySource coding theoremBlahut-Arimoto algorithmDifferential entropyMaximum entropy property of the GaussianWater-fillingGibbs distribution
- 06Lagrange dual functionDual problem and weak dualityStrong duality and Slater's conditionAdam
- 15Micro framework to PyTorch correspondenceBackpropagation
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 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 into a tensor of , 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 is tolerated, what is the minimum number of bits per symbol? The answer is a function, the rate-distortion function . This lesson builds it, calculates it for important cases and connects it to learned compression.
Start with the simplest source: equally likely bits, , and Hamming distortion, the fraction of bits incorrectly reconstructed. If we tolerate , 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 overall, we must guess of the bits, giving rate 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.
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 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 of the bits at bits per symbol, where the naive method would need . But the limit lies lower still: with , half a bit per symbol suffices, . The seemingly reasonable naive strategy wastes of the rate. This lesson explains where comes from, why it cannot be beaten and how it is achieved.
Unless stated otherwise, is the base-2 logarithm and rate is measured in bits per source symbol.
Distortion, lossy codes and the operational problem
A source takes values in an alphabet and is reconstructed in a reproduction alphabet , which may differ (for example, a color image is reproduced using a 256-color palette).
The encoder chooses one of indices, so uses bits per block, per symbol. The problem is to find, for each , the lowest rate at which arbitrarily long codes exist. Two values of bound the problem:
- : below this no code works (for Hamming and squared error, ).
- : with it suffices always to reproduce the same symbol , which minimizes average distortion, without sending anything. For Hamming on a , ; for squared error, , 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 into through conditional distribution , 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 ) and mutual information is continuous. It is dual to the capacity problem: there we maximize over input with channel fixed; here we minimize over channel with input fixed. Since is convex in (proved in lesson 9), this is a convex optimization problem, which structures everything that follows.
Proof
(1) If , every channel feasible for is feasible for : the minimum over a larger set does not increase.
(2) Let be optimal channels for , and (rowwise mixture). Distortion is linear in , so : is feasible for . By convexity of mutual information in the channel,
A finite convex function on an interval is continuous in its interior.
(3) If , the channel sending everything to is feasible and has . If , the optimal channel makes independent of and then , hence . A convex, nonincreasing function positive on and zero on cannot have horizontal segments in that interval: if with , convexity between and would give .
(4) always, and with Hamming the identity channel has distortion 0 and ; any channel with must be the identity, so .
∎Convexity has a direct operational interpretation, time sharing: if one codec achieves and another , using the first for fraction of blocks and the second for the rest achieves intermediate point . 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 , and one sending nothing, with : 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 and with . Since is a Markov chain, the data processing inequality and the entropy bound for an index give
Now use that the source is memoryless. By the chain rule, , and since conditioning reduces entropy, . Thus
The second inequality is the definition of (the pair defines a test channel with distortion ), the third is Jensen with convex and the last uses that is nonincreasing. Dividing by , . If distortion only satisfies , the same argument gives for every , and continuity of closes the case .
∎Notice where assumptions enter: independence of (for ) and convexity of , which prevents unevenly distributing distortion across positions from helping.
Achievability (sketch). Fix an optimal channel for and its marginal , and choose . Draw a codebook of words with symbols . To encode , find a word jointly typical with it (in the sense of asymptotic equipartition applied to the pair) and send its index. For a typical , a random word is jointly typical with probability of order : there are about reproductions compatible with among typical ones. The probability that none of the words is jointly typical is
When a jointly typical word exists, block distortion is approximately ; otherwise it costs at most with vanishing probability. Averaging over random codebooks, mean distortion tends to something , 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 is slow. The cell draws codebooks of words (rate ) for equally likely bits and measures mean nearest-neighbor distortion. The limit is , the value with .
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 , a randomly drawn codebook of 4096 words stays around , still far from 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 (the other case is symmetric) and . Let be addition modulo 2.
Lower bound. For any test channel with ,
The middle equality uses that, given , and determine each other. The last inequality uses with , and that increases on .
Achievability. Construct the channel backward: and with independent . For to have the correct distribution, , that is , which lies in exactly when . Then and : both inequalities are equalities.
∎For the fair coin, : the half bit in the motivation. The optimal test channel is best read backward: the source is the reproduction plus independent noise . It is the binary symmetric channel of lesson 9, and the coincidence is not accidental: was the capacity of , and now is the rate needed for distortion . Forward, the channel is ; for it is not symmetric.
What to notice in the figure:
- The curve is convex and the naive strategy is a chord. It goes from to below the chord joining its endpoints. Halfway, with and , the limit is bits versus .
- Block quantizers lie between the chord and curve. Majority of 3 achieves and Hamming , . Longer, better-structured blocks approach the curve; none cross it.
- The test channel corrupts the rare symbol more. With and , the reproduction has and the forward channel is , : it almost never invents ones but erases almost half of those present. Errors concentrate where they are cheapest in bits.
- The slope diverges near . : the last errors are most expensive to eliminate.
Gaussian sources: R(D) = ½ log(σ²/D)
For a continuous source with squared error, the definition of 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 , the one with greatest differential entropy is , with .
Proof
Lower bound. For any test channel with ,
The second equality is translation invariance of differential entropy (given , subtracting is a translation), the first inequality is that conditioning reduces entropy, and the second is maximum entropy applied to , with .
Achievability. Backward: and with independent . Then , and . For , suffices.
∎Three ways to read the formula:
- Every bit divides distortion by 4. means signal-to-noise ratio improves by dB per bit, the rule of thumb for analog-to-digital converters. With and exactly 1 bit is needed.
- The optimal reproduction has less variance than the source. Forward, the channel is with and independent : reconstruction shrinks the source toward its mean. . This detail reappears as blur in learned codecs.
- The Gaussian is the hardest source. For any source with variance , the same linear channel has the same distortion (depending only on second moments) and . Thus for every source of variance : among sources with given variance, the Gaussian requires the most bits. Conversely, the lower-bound argument gives the Shannon lower bound , used when studying quantizers.
Gaussian vectors and reverse water-filling
Now consider vector source with independent components and total distortion . 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 , with and . Thus , and equality is achieved with independent Gaussian test channels per component, each with its .
Optimal allocation. It suffices to consider (giving a component more distortion than its variance saves nothing). Problem with and is convex (the function is convex in each and constraints are linear), so KKT conditions suffice. With multiplier for the sum and for , stationarity is . If , complementary slackness gives and , the same value for all. If , requires . This is exactly the stated rule, and is fixed by (the sum is continuous and increasing in ).
∎The name comes from the picture: variances are bars and distortion is water rising to level . What remains submerged is each component’s distortion; what protrudes above the water, , is reproduction variance , 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 with , coordinates are independent with variances , the eigenvalues. A rotation changes neither squared error () nor mutual information (it is invertible), so is water-filling over the eigenvalues of . The optimal codec rotates into the principal-component basis, discards directions with eigenvalue below and encodes the rest with equal distortion . 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.
Takeaways from the figure:
- All encoded components lose the same amount. With the decaying spectrum and , six components receive bits and the two smallest (variances and ) are discarded. Counterintuitively, distortion is not allocated in proportion to variance, but equally while possible.
- Allocating bits equally is costly. At that point ( total bits, distortion ), giving every component the same bits gives distortion , higher: it spends bits on components worth less than the water level and skimps on large ones.
- Reconstruction collapses onto principal axes. When exceeds the second variance, the magenta cloud flattens onto a line, the first principal axis: its conditional mean is the PCA projection shrunk by , 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 .
The Lagrangian and Blahut-Arimoto algorithm
Outside closed-form cases, is calculated numerically, using the same approach as capacity: duality and alternating minimization. Instead of imposing constraint , penalize it.
Proof
(1) For any , . If , this gives : is optimal for constraint . For the supporting line, take optimal for any : .
(2) is the dual function of the problem defining , so is weak duality. The problem is convex and, if , the channel reproducing each by its nearest has distortion : Slater’s condition holds and there is strong duality, with optimal multiplier . If , the constraint is active ( is strictly decreasing) and the minimizer of satisfying it with equality is optimal.
∎Thus sweeping traces the curve, from endpoint at small to endpoint with , and is minus the slope: where the curve is differentiable. For the fair coin, , so point corresponds to bits per unit of distortion. For the Gaussian, and .
The optimal test channel has Gibbs form
To minimize use the compensation identity from lesson 9: for any distribution over ,
with equality only if is marginal . Therefore with
For fixed , the bracket for each is exactly the functional of the Gibbs variational principle from lesson 13, with energy and reference measure : it equals , where is the Gibbs distribution
Thus the best channel for fixed is Gibbs, and the best for fixed 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 . With small (high temperature) the channel ignores distortion and copies the marginal; with large it concentrates on the nearest reproduction.
Alternating the two exact minimizations gives Blahut’s algorithm (1972), a sibling of the capacity algorithm:
This is another multiplicative update: each reproduction multiplies its probability by , measuring how much nearby “claim” it. Each step lowers , 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 :
The upper bound is immediate: is a channel with distortion . The lower bound follows from duality. For any channel with marginal and distortion , with , Gibbs’ inequality applied to mass against unnormalized weights gives , which is . Substituting Gibbs form into yields the exact gap:
which vanishes exactly when is constant on used reproductions and no greater on the others; since , that constant is 1. This is the KKT condition: at the optimum, each used reproduction is claimed exactly as much as it is used (), and unused ones at most that much ().
What to look for:
- From collapsing everything to identity. With small all channel rows are equal: everything is reproduced by the symbol minimizing mean distortion (in the first example , closest to the source mean) and rate is zero. As increases, new reproductions appear until the channel is identity, with and .
- Reproduction symbols split. On the plot of against , each symbol is born at a critical when its reaches 1. In the line example one is even used, abandoned and returns: the solution rearranges reproductions like soft -means gaining centers as temperature drops. (The analogy is literal: module 12 will cover -means as vector quantization and deterministic annealing as this same algorithm.)
- Convergence slows near a split. Iterations surge from tens to thousands at critical and small : the direction in which a symbol gains or loses mass is nearly flat. This parallels almost-abandoned inputs in capacity.
- A sharp fall in is an almost straight section of the curve. In “Two groups”, distortion falls from to while barely moves from to : is born and replaces as representative of the first group. Since the curve’s slope is , it is nearly straight there. The fall is continuous (with very fine tolerance does not jump), but illustrates the limit: if jumped at fixed , the supporting line would touch the curve along a whole segment (two solutions with the same and everything between them by time sharing), and sweeping would give only its endpoints.
Implementation from scratch
First, Blahut-Arimoto with its bounds, validated against the binary formula and relation , and the sweep of the figure’s four-symbol source.
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 to six digits; with the uniform marginal is already optimal and the algorithm ends on the first iteration, with , the slope-multiplier relation. The four-symbol source shows everything in the figure: at one symbol and thousands of iterations, at another bottleneck as support reorganizes, and from all four symbols in use and convergence in a few dozen steps.
Now a continuous source: discretize on a fine grid, use the same grid as reproduction alphabet and compare with . Here the optimal marginal is a discretized Gaussian with full support, so the gap closes slowly; we limit iterations and report the gap.
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 to three or four digits, and distortion matches : the discretized Gaussian behaves like the continuous one while the grid is much finer than . 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 is achieved with long blocks. How much is lost with the simplest approach, a uniform scalar quantizer (rounding each sample to a multiple of ) 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 is small, quantization error is nearly uniform on , with
the second because each cell has probability . Eliminating , quantizer rate is , while Shannon’s lower bound is (exact for the Gaussian). The difference depends on neither source nor distortion:
This is the price of quantizing one at a time: scalar quantizer cells, viewed in 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.
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 bits ( dB) once the step falls below (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.
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 , 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 (the “analysis transform”), rounding , a decoder and an entropy model , all learned. The loss is
the rate an arithmetic coder guided by would charge plus for distortion: this lesson’s Lagrangian with . The obstacle is that rounding has zero derivative almost everywhere. The solution is to train with noise: replace by , with , and the mass of by the density of , the model density convolved with a box: , with the model distribution function. At integers it matches the mass of 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 , prior and decoder . Its two terms are distortion and rate:
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 and β-VAE minimizes . Beware notation: in β-VAE the coefficient multiplies rate, so it is the inverse of this lesson’s multiplier . Increasing the β-VAE’s makes distortion cheaper relative to rate and moves the model toward less rate and more distortion.
What the figure shows, with numbers from that experiment:
- All models lie on a convex curve. Going down from to , rate rises from to bits per image and distortion falls from to bits. The curve’s slope at each model is that of its line : selects the support point, just as in Blahut-Arimoto.
- ELBO does not distinguish points on the same line. The standard VAE () has the best , bits; those at and are and bits away, but their rates are and bits: one stores more than 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 , ignoring the latent: posterior collapse. If representation matters, likelihood is insufficient: one must decide where to be on the curve, choosing .
- At low rate the model keeps coarse shape and sometimes changes identity. With reconstructions are plausible digits, but some are no longer the original: 2 becomes 3 and 4 becomes 9. With almost all merge into generic shapes, and with (a little over one bit) reconstructions are almost identical blobs. Using the mean of rather than a sample removes latent noise, and with 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 to . Also requiring to have the same distribution as costs rate or distortion, defining a rate-distortion-perception surface. In the Gaussian case, among jointly Gaussian schemes with correlation fixed by rate, requiring moves distortion from to , a factor ; 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 ; it then measures actual rate with the rounded latent and compares it with JPEG on a mosaic of digits so file-header cost is shared. It runs on CPU in about a minute.
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")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 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
More than one answer may be correct.
Step 1 of 4. What channel bounds ?
Step 1 of 3. How is rewritten to expose the error?
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 in bits and an array of each component's distortion, , with level such that (tolerance ). If , rate is 0 and . 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)Summary
- Operational problem. Codes with mean distortion ; is free.
- Definition and properties. : nonincreasing, convex (time sharing; convexity of in the channel), zero from , with Hamming.
- Theorem. Converse: . Achievability: random words cover the typical set if . This covering problem is dual to channel coding’s packing.
- Closed formulas. Bernoulli: , backward channel . Gaussian: , (6.02 dB per bit), and it is the hardest source at given variance.
- Reverse water-filling. : encoded components all lose and those with smaller variance are discarded. With correlation, apply to eigenvalues: PCA plus quantization.
- Lagrangian and Blahut-Arimoto. gives the point with slope ; optimal channel ; update with bounds . Slow with small and near splits.
- Practical quantization. Uniform scalar plus entropy coding: bits ( dB) from the limit at high resolution.
- Learned compression. Ballé: rate with uniform noise in training and rounding in evaluation. β-VAE: , with on rate; ELBO does not distinguish points on the same line. Rate-distortion-perception: realism costs up to twice the distortion.