Module contents
Lesson 11 of 19Core 110 min

Differential entropy, Gaussians and the Gaussian channel

Extend information theory to continuous variables. Differential entropy may be negative and depends on scale, while KL divergence and mutual information retain their meaning. Derive the Gaussian maximum-entropy property, the Gaussian KL used by VAEs, Gaussian channel capacity, and water filling.

After this lesson you can

  • Calculate differential entropy for uniform, exponential, Gaussian, and multivariate Gaussian distributions.
  • Derive the effect of affine transformations on differential entropy and the invariance of KL divergence and mutual information.
  • Prove that a Gaussian maximizes differential entropy at fixed covariance.
  • Derive the KL divergence between multivariate Gaussians and its diagonal standard-normal case, and implement it with Cholesky factorization.
  • Derive Gaussian channel capacity and allocate power across parallel channels by water filling.

Before you start

Motivation: when variables are real numbers

So far every random variable had a finite alphabet and its information fit in a probability table. But almost everything measured, transmitted, and modeled is continuous: a cable’s voltage, the amplitude of a radio wave, a normalized pixel, the latent vector z∈Rd\vb{z} \in \R^{d} of a variational autoencoder. Two concrete questions require us to extend the theory.

  • The VAE divergence. A variational autoencoder’s regularization term is the divergence KL⁡(N(μ,diag⁡σ2) ∥ N(0,I))\KL\big(\Normal(\vb{\mu}, \diag\vb{\sigma}^2) \,\|\, \Normal(\vb{0}, \mat{I})\big) between two Gaussian densities. It is evaluated at every training step, thousands of times per second, and has a closed form that you should know how to derive and, above all, implement without numerical blow-ups in high dimensions.
  • The physical channel. A signal XX with average power bounded by PP arrives contaminated by thermal noise of power NN: Y=X+ZY = X + Z. How many bits per use can it carry reliably? The answer, 12log⁡2(1+P/N)\tfrac12\log_2(1 + P/N), governs the design of modems, mobile networks, and satellite links.

An exact real number contains infinite information (infinitely many decimal places), so the entropy HH from previous lessons cannot be applied as it stands. Noise nevertheless limits what can be distinguished. For intuition, if the signal varies over [−P,P][-\sqrt{P}, \sqrt{P}] and noise has standard deviation N\sqrt{N}, two levels closer than N\sqrt{N} are confused, and roughly P/N\sqrt{P/N} distinguishable levels fit. That is 12log⁡2(P/N)\tfrac12\log_2(P/N) bits, apart from a constant. This lesson turns that level count into an exact theorem, using three ingredients: entropy for densities, the fact that a Gaussian has the greatest entropy at equal variance, and the way divergence and mutual information survive the transition to the continuous case.

Unless stated otherwise, log⁡\log is the base-2 logarithm (bits) in channel formulas and ln⁡\ln the natural logarithm (nats) in Gaussian formulas; 11 nat =log⁡2e≈1.4427= \log_2 e \approx 1.4427 bits.

Differential entropy

The definition is the obvious one: replace the sum with an integral.

This is the same expected surprise as in Shannon entropy, but surprise −log⁡f(x)-\log f(x) is no longer the logarithm of a probability: f(x)f(x) is a density and can exceed 1. That is where the peculiarities arise. First consider the standard examples.

Densityh(X)h(X) in natsComment
Uniform Unif⁡(a,b)\Unif(a, b)ln⁡(b−a)\ln(b - a)maximum among densities supported on [a,b][a, b]
Exponential Exp(λ)\mathrm{Exp}(\lambda)1−ln⁡λ1 - \ln\lambdaλ\lambda is the rate; mean 1/λ1/\lambda
Gaussian N(μ,σ2)\Normal(\mu, \sigma^2)12ln⁡(2πe σ2)\tfrac12\ln(2\pi e\,\sigma^2)does not depend on μ\mu
Laplace with scale bb1+ln⁡(2b)1 + \ln(2b)variance 2b22b^2
Gaussian N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) in Rn\R^n12ln⁡((2πe)ndet⁡Σ)\tfrac12\ln\big((2\pi e)^n\det\mat{\Sigma}\big)proved below

The first three follow in one line. For the uniform density, −ln⁡f=ln⁡(b−a)-\ln f = \ln(b-a) is constant. For the exponential, −ln⁡f(x)=−ln⁡λ+λx-\ln f(x) = -\ln\lambda + \lambda x and E[X]=1/λ\E[X] = 1/\lambda gives 1−ln⁡λ1 - \ln\lambda. For the Gaussian, −ln⁡f(x)=12ln⁡(2πσ2)+(x−μ)22σ2-\ln f(x) = \tfrac12\ln(2\pi\sigma^2) + \frac{(x-\mu)^2}{2\sigma^2} and the second term has expectation 12\tfrac12.

Differential entropy can be negative, which can be surprising at first. For U∼Unif⁡(0,18)U \sim \Unif(0, \tfrac18), h(U)=log⁡218=−3h(U) = \log_2\tfrac18 = -3 bits. For a Gaussian, h<0h < 0 whenever σ2<1/(2πe)≈0.0585\sigma^2 < 1/(2\pi e) \approx 0.0585, that is, σ<0.242\sigma < 0.242. A highly concentrated density reaches values above 1 and its surprise −log⁡f-\log f is negative on average.

The effective volume interpretation makes sense of this: 2h(X)2^{h(X)} (with hh in bits) is the length of the uniform interval with the same entropy. For a uniform distribution it is exactly b−ab - a; for a Gaussian, 2h=2πe σ≈4.13 σ2^{h} = \sqrt{2\pi e}\,\sigma \approx 4.13\,\sigma. Negative entropy means an effective volume smaller than the unit of measurement. In Rn\R^n it is an nn-dimensional volume, and the channel section will show that this idea is literal: the number of elements in a typical set of nn samples is 2nH2^{nH} in the discrete case, and its volume is 2nh2^{nh} in the continuous case.

What is lost from the discrete case

  • It can be negative, as just seen, and tends to −∞-\infty when the distribution concentrates at a point (h(N(0,σ2))→−∞h(\Normal(0, \sigma^2)) \to -\infty if σ→0\sigma \to 0).
  • It depends on units. If XX is in meters and X′=100XX' = 100X in centimeters, h(X′)=h(X)+log⁡2100=h(X)+6.64h(X') = h(X) + \log_2 100 = h(X) + 6.64 bits. A quantity that changes when measured in different units cannot be “the information bits of XX.” This is proved in general below.
  • It is not the limit of HH. If XX is quantized with increasingly fine cells, HH grows without bound; the next section gives the exact relationship.

What survives: the chain rule, the fact that conditioning does not increase entropy (because I≥0I \ge 0), and, as we will see, divergence and mutual information unchanged, with their units and meaning.

From discrete to differential entropy

Quantizing XX into cells of width Δ\Delta gives a discrete variable XΔX_\Delta, whose entropy H(XΔ)H(X_\Delta) is indeed the entropy of lesson 1. How is it related to h(X)h(X)?

Proof

By the mean value theorem there is xi∈[iΔ,(i+1)Δ)x_i \in [i\Delta, (i+1)\Delta) with P(XΔ=i)=∫iΔ(i+1)Δf=f(xi)Δ\Pr(X_\Delta = i) = \int_{i\Delta}^{(i+1)\Delta} f = f(x_i)\Delta. Then

H(XΔ)=−∑if(xi)Δ log⁡(f(xi)Δ)=−∑iΔ f(xi)log⁡f(xi)  −  log⁡Δ∑if(xi)Δ.H(X_\Delta) = -\sum_i f(x_i)\Delta\,\log\big(f(x_i)\Delta\big) = -\sum_i \Delta\, f(x_i)\log f(x_i) \;-\; \log\Delta\sum_i f(x_i)\Delta .

The second sum is ∑iP(XΔ=i)=1\sum_i \Pr(X_\Delta = i) = 1. The first is a Riemann sum of −flog⁡f-f\log f, which tends to h(X)h(X). Thus H(XΔ)=h(X)−log⁡Δ+o(1)H(X_\Delta) = h(X) - \log\Delta + o(1).

∎

This result says that hh is entropy relative to the unit of measurement. Asking for nn bits of precision (Δ=2−n\Delta = 2^{-n}) costs H≈h+nH \approx h + n bits: h(X)h(X) is the cost of describing XX to precision 1, and each extra bit of precision costs exactly one bit. An infinitely precise real number costs infinitely many bits because n→∞n \to \infty, not because hh does. The figure shows all this together and adds what motivates the next section: a second variable Y=X+NY = X + N, with Gaussian noise of standard deviation 0.50.5.

InteractiveFrom discrete to differential entropy
  • density ff
  • bins, height pi/Δp_i/\Delta
  • H(XΔ)H(X_\Delta)
  • H(XΔ)+log⁡2ΔH(X_\Delta) + \log_2\Delta
  • I(XΔ′;YΔ)I(X'_\Delta;Y_\Delta)
  • limit
Density of X
−1.00
0.00
Bin Δ\Delta and stretching aa0.500 and 1.00
H(XΔ)H(X_\Delta)3.062 bits
−log⁡2Δ-\log_2\Delta (precision bits)1.00 bits
H(XΔ)+log⁡2ΔH(X_\Delta) + \log_2\Delta2.062 bits
h(aX)h(aX) (limit)2.047 bits
h(aX)−h(X)h(aX) - h(X), equal to log⁡2a\log_2 a0.000 bits
I(XΔ′;YΔ)I(X'_\Delta;Y_\Delta) with Y=X+NY = X + N1.070 bits
I(X;Y)I(X;Y) (limit)1.161 bits
H(XΔ)+log⁡2ΔH(X_\Delta) + \log_2\Delta differs from h(X′)h(X') by 0.01490.0149 bits, although H(XΔ)H(X_\Delta) is already 3.063.06.
At top left, the density of X′=aXX' = aX and its cells of width Δ\Delta (each bar's area is pip_i). At right (below on narrow screens), H(XΔ)H(X_\Delta) and H(XΔ)+log⁡2ΔH(X_\Delta) + \log_2\Delta against log⁡2Δ\log_2\Delta; below, mutual information I(XΔ′;YΔ)I(X'_\Delta; Y_\Delta) with Y=X+NY = X + N, quantizing both variables with the same Δ\Delta. Start with the Gaussian and lower log⁡2Δ\log_2\Delta: how much does H(XΔ)H(X_\Delta) grow per bit of precision? What about H+log⁡ΔH + \log\Delta? Then stretch the variable with aa: the magenta curve rises by log⁡2a\log_2 a bits, but what happens to the orange one? Switch to uniform and stretch with a=1/4a = 1/4: hh becomes negative. Does mutual information also become negative?

What to take away:

  • Each bit of precision costs one bit. Halving Δ\Delta increases H(XΔ)H(X_\Delta) by almost exactly 1 bit (a line with slope −1-1 in log⁡2Δ\log_2\Delta), while H(XΔ)+log⁡2ΔH(X_\Delta) + \log_2\Delta flattens at hh. For the standard Gaussian and Δ=1/16\Delta = 1/16, H=6.0473H = 6.0473 and H+log⁡2Δ=2.0473H + \log_2\Delta = 2.0473, within 0.00020.0002 bits of h=2.0471h = 2.0471.
  • Stretching shifts hh but not information. With a=4a = 4 the magenta curve moves to h=4.047h = 4.047: h(aX)=h(X)+log⁡2ah(aX) = h(X) + \log_2 a. Mutual information I(XΔ′;YΔ)I(X'_\Delta; Y_\Delta) converges to the same value, 12log⁡25=1.161\tfrac12\log_2 5 = 1.161 bits for the Gaussian, whatever aa. With coarse cells the curves differ (with a=4a = 4 the variable X′X' is resolved more finely relative to its scale), but the limit is the same. For the bimodal mixture it is 1.3771.377 and for the uniform distribution 1.1221.122.
  • hh can be negative; II never can. For the uniform distribution and a=1/4a = 1/4 the interval has length 0.870.87 and h=−0.21h = -0.21 bits, and the magenta curve falls below zero with fine cells; meanwhile, quantized mutual information is discrete mutual information and never falls below 00.
  • The mixture has no closed form: its hh is computed numerically (the figure’s tool uses an integral). This is a case of “no formula exists” that recurs in common mistakes.

What is invariant: transformations, divergence, and mutual information

The second point in the figure follows from a change of variables. If Y=g(X)\vb{Y} = \vb{g}(\vb{X}) with g\vb{g} a diffeomorphism, the density is fY(y)=fX(g−1(y)) ∣det⁡Jg−1(y)∣f_Y(\vb{y}) = f_X(\vb{g}^{-1}(\vb{y}))\,\abs{\det \mat{J}_{\vb{g}^{-1}}(\vb{y})}, with J\mat{J} the Jacobian (this is the change-of-variables formula).

Proof

We prove the fourth, which includes the others. Since fY(g(x))=fX(x)/∣det⁡Jg(x)∣f_Y(\vb{g}(\vb{x})) = f_X(\vb{x})/\abs{\det\mat{J}_{\vb{g}}(\vb{x})},

h(Y)=−E[log⁡fY(g(X))]=−E[log⁡fX(X)]+E[log⁡∣det⁡Jg(X)∣].h(\vb{Y}) = -\E\big[\log f_Y(\vb{g}(\vb{X}))\big] = -\E\big[\log f_X(\vb{X})\big] + \E\big[\log\abs{\det\mat{J}_{\vb{g}}(\vb{X})}\big].

For g(x)=Ax+c\vb{g}(\vb{x}) = \mat{A}\vb{x} + \vb{c} the Jacobian is constant, det⁡A\det\mat{A}.

∎

The interpretation is in terms of volume: applying A\mat{A} multiplies volumes by ∣det⁡A∣\abs{\det\mat{A}} and adds log⁡∣det⁡A∣\log\abs{\det\mat{A}} to entropy. In case 4, the term is the mean logarithm of the local expansion factor (not the logarithm of its mean), and is what a normalizing flow computes to give the likelihood of its samples.

What matters is what does not change. The two quantities defined by a ratio of densities inherit their properties without loss.

Proof

Let SS be the support of ff. Since log⁡\log is concave, Jensen’s inequality gives −KL⁡(f ∥ g)=Ef[log⁡gf]≤log⁡Ef[gf]=log⁡∫Sg≤log⁡1=0-\KL(f\,\|\,g) = \E_f\big[\log\tfrac{g}{f}\big] \le \log\E_f\big[\tfrac{g}{f}\big] = \log\int_S g \le \log 1 = 0. Equality requires g/fg/f to be constant on SS (strict Jensen) and ∫Sg=1\int_S g = 1, hence f=gf = g. For mutual information, I=KL⁡(fXY∥fXfY)≥0I = \KL(f_{XY}\|f_Xf_Y) \ge 0, and I=h(X)−h(X∣Y)I = h(X) - h(X \mid Y).

∎
Proof

The densities of T(X)T(\vb{X}) under ff and under gg carry the same Jacobian factor, which cancels in the ratio: fT(T(x))gT(T(x))=f(x)g(x)\frac{f_T(T(\vb{x}))}{g_T(T(\vb{x}))} = \frac{f(\vb{x})}{g(\vb{x})}. Divergence is the expectation under ff of the logarithm of that ratio, and the expectation under fTf_T of the function y↦ln⁡fT(y)gT(y)\vb{y} \mapsto \ln\frac{f_T(\vb{y})}{g_T(\vb{y})} is the expectation under ff of the same function evaluated at T(X)T(\vb{X}), so it does not change. For mutual information, apply the argument to the pair (X,Y)↦(T(X),S(Y))(X, Y) \mapsto (T(X), S(Y)): the joint density and product of marginals gain the same factor ∣det⁡JT∣∣det⁡JS∣\abs{\det\mat{J}_T}\abs{\det\mat{J}_S}.

∎

That is why divergence and mutual information are the “real” objects of continuous theory. They are also limits of their discrete versions: quantizing with increasingly fine partitions, each a refinement of the previous one, gives discrete divergences and mutual informations that increase (by data processing, mutual information does not increase on grouping) toward the continuous value, which is the supremum over all partitions (Gelfand–Yaglom–Perez; see Polyanskiy and Wu). This is what the figure’s orange curve shows. In summary, hh measures a volume, whose units are arbitrary; KL⁡\KL and II compare two volumes in the same units, which cancel.

The Gaussian maximizes entropy

Before the result, we need the entropy of a multivariate Gaussian. Let X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) with positive definite Σ\mat{\Sigma} (see the multivariate Gaussian and positive definite matrices). With the Cholesky factorization Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T (Cholesky), X=μ+LZ\vb{X} = \vb{\mu} + \mat{L}\vb{Z} with Z∼N(0,I)\vb{Z} \sim \Normal(\vb{0}, \mat{I}). The two preceding properties give

h(X)=h(Z)+ln⁡∣det⁡L∣=n2ln⁡(2πe)+12ln⁡det⁡Σ=12ln⁡((2πe)ndet⁡Σ),h(\vb{X}) = h(\vb{Z}) + \ln\abs{\det\mat{L}} = \frac{n}{2}\ln(2\pi e) + \frac12\ln\det\mat{\Sigma} = \frac12\ln\big((2\pi e)^n\det\mat{\Sigma}\big),

because h(Z)=n⋅12ln⁡(2πe)h(\vb{Z}) = n\cdot\tfrac12\ln(2\pi e) (independent coordinates) and det⁡Σ=(det⁡L)2\det\mat{\Sigma} = (\det\mat{L})^2. Entropy depends only on det⁡Σ\det\mat{\Sigma}: the volume of the covariance ellipsoid. The mean does not enter (translation).

Now the Gaussian maximum-entropy property: among all densities with a given covariance, the Gaussian is the most “spread out.”

Proof

Let φ\varphi be the density of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}). By the continuous Gibbs lemma, 0≤KL⁡(f ∥ φ)=−h(X)−Ef[ln⁡φ(X)]0 \le \KL(f\,\|\,\varphi) = -h(\vb{X}) - \E_f[\ln\varphi(\vb{X})]. Since −ln⁡φ(x)=12ln⁡((2π)ndet⁡Σ)+12(x−μ)⊤Σ−1(x−μ)-\ln\varphi(\vb{x}) = \tfrac12\ln\big((2\pi)^n\det\mat{\Sigma}\big) + \tfrac12(\vb{x}-\vb{\mu})\T\mat{\Sigma}\inv(\vb{x}-\vb{\mu}) is a degree-2 polynomial in x\vb{x}, its expectation under ff depends only on second-order moments, which match those of φ\varphi:

Ef[(X−μ)⊤Σ−1(X−μ)]=tr⁡(Σ−1 E[(X−μ)(X−μ)⊤])=tr⁡(Σ−1Σ)=n.\E_f\big[(\vb{X}-\vb{\mu})\T\mat{\Sigma}\inv(\vb{X}-\vb{\mu})\big] = \tr\big(\mat{\Sigma}\inv\,\E[(\vb{X}-\vb{\mu})(\vb{X}-\vb{\mu})\T]\big) = \tr(\mat{\Sigma}\inv\mat{\Sigma}) = n .

Therefore −Ef[ln⁡φ]=12ln⁡((2πe)ndet⁡Σ)-\E_f[\ln\varphi] = \tfrac12\ln\big((2\pi e)^n\det\mat{\Sigma}\big), equal to the entropy of φ\varphi, and 0≤KL⁡(f∥φ)=h(φ)−h(f)0 \le \KL(f\|\varphi) = h(\varphi) - h(f). Equality occurs only if KL⁡=0\KL = 0, that is, f=φf = \varphi.

∎

We have proved more: h(φ)−h(f)=KL⁡(f ∥ φ)h(\varphi) - h(f) = \KL(f\,\|\,\varphi). The entropy gap from the Gaussian is exactly the KL divergence to it. At the same scale (variance 1), the Gaussian has h=1.419h = 1.419 nats, the Laplace distribution 1.3471.347, and the uniform distribution ln⁡(23)=1.242\ln(2\sqrt3) = 1.242. No other density with variance 1 exceeds it.

Two variants used later have the same proof. If only the second moment is fixed, E[X2]≤P\E[X^2] \le P, we obtain h(X)≤12ln⁡(2πeP)h(X) \le \tfrac12\ln(2\pi e P) (the variance is at most PP, and hh increases with Gaussian variance). Among densities supported on [a,b][a, b] the maximum is uniform, while among those supported on [0,∞)[0, \infty) with mean mm it is exponential. All are cases of the maximum-entropy principle in lesson 13, proved there with a single variational argument.

KL divergence between Gaussians

This is the formula evaluated most often in the lesson. KL divergence between multivariate Gaussians has a closed form, derived by computing the expectation of a degree-2 polynomial.

Proof

KL⁡(p∥q)=Ep[ln⁡p(X)−ln⁡q(X)]\KL(p\|q) = \E_p[\ln p(\vb{X}) - \ln q(\vb{X})]. The first logarithm averages to −h(p)=−12ln⁡((2πe)ndet⁡Σ0)-h(p) = -\tfrac12\ln\big((2\pi e)^n\det\mat{\Sigma}_0\big). For the second, −ln⁡q(x)=12ln⁡((2π)ndet⁡Σ1)+12(x−μ1)⊤Σ1−1(x−μ1)-\ln q(\vb{x}) = \tfrac12\ln\big((2\pi)^n\det\mat{\Sigma}_1\big) + \tfrac12(\vb{x}-\vb{\mu}_1)\T\mat{\Sigma}_1\inv(\vb{x}-\vb{\mu}_1), and writing x−μ1=(x−μ0)+(μ0−μ1)\vb{x} - \vb{\mu}_1 = (\vb{x} - \vb{\mu}_0) + (\vb{\mu}_0 - \vb{\mu}_1), the cross term has zero expectation under pp, leaving

Ep[(X−μ1)⊤Σ1−1(X−μ1)]=tr⁡(Σ1−1Σ0)+(μ0−μ1)⊤Σ1−1(μ0−μ1).\E_p\big[(\vb{X}-\vb{\mu}_1)\T\mat{\Sigma}_1\inv(\vb{X}-\vb{\mu}_1)\big] = \tr(\mat{\Sigma}_1\inv\mat{\Sigma}_0) + (\vb{\mu}_0-\vb{\mu}_1)\T\mat{\Sigma}_1\inv(\vb{\mu}_0-\vb{\mu}_1).

Adding: KL⁡=−n2−12ln⁡det⁡Σ0+12ln⁡det⁡Σ1+12[ traza+n+medias ]\KL = -\tfrac n2 - \tfrac12\ln\det\mat{\Sigma}_0 + \tfrac12\ln\det\mat{\Sigma}_1 + \tfrac12[\,\text{traza} + n + \text{medias}\,], which is the formula.

∎

Two cases you will use constantly. In one dimension, with N(μ0,σ02)\Normal(\mu_0, \sigma_0^2) against N(μ1,σ12)\Normal(\mu_1, \sigma_1^2),

KL⁡=ln⁡σ1σ0+σ02+(μ0−μ1)22σ12−12,\KL = \ln\frac{\sigma_1}{\sigma_0} + \frac{\sigma_0^2 + (\mu_0 - \mu_1)^2}{2\sigma_1^2} - \frac12 ,

and with equal variance this becomes (μ0−μ1)2/(2σ2)(\mu_0-\mu_1)^2/(2\sigma^2): N(1,1)\Normal(1, 1) against N(0,1)\Normal(0, 1) gives exactly 12\tfrac12 nats. And the case that makes VAEs work: a diagonal encoder against the standard prior, p=N(μ,diag⁡σ2)p = \Normal(\vb{\mu}, \diag\vb{\sigma}^2), q=N(0,I)q = \Normal(\vb{0}, \mat{I}),

KL⁡(N(μ,diag⁡σ2) ∥ N(0,I))=12∑i=1d(σi2+μi2−1−ln⁡σi2).\KL\big(\Normal(\vb{\mu}, \diag\vb{\sigma}^2)\,\|\,\Normal(\vb{0}, \mat{I})\big) = \frac12\sum_{i=1}^{d}\big(\sigma_i^2 + \mu_i^2 - 1 - \ln\sigma_i^2\big).

Each coordinate contributes 12μi2\tfrac12\mu_i^2, pulling the mean toward 00, and 12(σi2−1−ln⁡σi2)≥0\tfrac12(\sigma_i^2 - 1 - \ln\sigma_i^2) \ge 0, pulling the variance toward 11 and vanishing only there (the function v−1−ln⁡vv - 1 - \ln v is convex with minimum 00 at v=1v = 1). This term pushes each individual encoding toward the prior, while reconstruction pulls in the opposite direction (favoring small σi\sigma_i and well-separated means); the balance makes the set of encodings resemble a standard Gaussian without each one being standard Gaussian. This is the KL regularization of lesson 15, which recurs in the VAEs of module 19.

Asymmetry

The figure lets you manipulate the formula. Each Gaussian is controlled by three handles (the mean and the two semiaxes of the one-standard-deviation ellipse), and the trace, log-determinant, and mean terms are shown separately.

InteractiveKL between two Gaussians in the plane
D(p ‖ q), natstrace−0.90log-det2.33means0.01total1.44D(q ‖ p), natstrace10.01log-det−2.33means0.05total7.72
  • pp
  • qq
  • trace: 12(tr(Σq−1Σp)−2)\tfrac12(\mathrm{tr}(\mat{\Sigma}_q^{-1}\mat{\Sigma}_p) - 2)
  • log-det: 12ln⁡(det⁡Σq/det⁡Σp)\tfrac12\ln(\det\mat{\Sigma}_q/\det\mat{\Sigma}_p)
  • means (Mahalanobis)
120
D(p ∥ q)D(p\,\|\,q)1.443 nats
D(q ∥ p)D(q\,\|\,p)7.721 nats
In bits, D(p ∥ q)D(p\,\|\,q)2.082 bits
Mean of ln⁡p/q\ln p/q (120 samples)1.394 nats
D(q∥p)D(q\|p) is 5.4 times D(p∥q)D(p\|q). A concentrated pp fits within a broad qq cheaply, but a broad qq inside narrow pp puts mass where pp has almost none.
Two Gaussians pp (blue) and qq (orange) with their 1- and 2-standard-deviation ellipses. Below or at right, the two divergences are decomposed into trace, log-determinant, and mean terms. Samples from pp are filled if ln⁡p/q>0\ln p/q > 0 and hollow if negative; their mean is the Monte Carlo estimator of D(p∥q)D(p\|q). Start with ‘narrow p inside q’: which divergence is greater, and which term dominates? Select ‘wide p, narrow q’ and observe the change. With ‘Separated means’ (both ellipses have the same shape), what is the asymmetry? With ‘Crossed ellipses’, which term is zero and which is not? Finally, fix q=N(0,I)q = \mathcal{N}(0, I) and move pp as if it were an encoder: what ellipse shape minimizes KL?

What to look for:

  • A narrow ellipse inside a wide one is cheap in one direction and costly in the other. With pp narrow and qq wide, KL⁡(p∥q)\KL(p\|q) is moderate: pp puts mass only where qq also has plenty. In reverse, qq puts mass in regions where pp has almost none, and the surprise −ln⁡p-\ln p there is enormous. In one dimension, with r=σp2/σq2r = \sigma_p^2/\sigma_q^2 and equal means, KL⁡(p∥q)=12(r−1−ln⁡r)\KL(p\|q) = \tfrac12(r - 1 - \ln r): with r=0.01r = 0.01 it equals 1.811.81 nats, with r=100r = 100 it equals 47.247.2. The cost grows linearly in rr when pp is wider, and only logarithmically when it is narrower.
  • Trace and log-determinant partly offset one another. Each can be negative, but their sum, decomposed into the eigenvalues λi\lambda_i of Σ1−1Σ0\mat{\Sigma}_1\inv\mat{\Sigma}_0, is 12∑i(λi−1−ln⁡λi)≥0\tfrac12\sum_i(\lambda_i - 1 - \ln\lambda_i) \ge 0. The “crossed ellipses” have the same determinant (zero log-determinant) and still have a large trace: volume agrees, orientation does not.
  • The mean term uses the covariance of the second argument. 12Δμ⊤Σ1−1Δμ\tfrac12\Delta\vb{\mu}\T\mat{\Sigma}_1\inv\Delta\vb{\mu} measures the distance between means using the Mahalanobis metric of qq; in KL⁡(q∥p)\KL(q\|p) it uses that of pp. Only with the same covariance do the terms agree, and then KL⁡(p∥q)=KL⁡(q∥p)\KL(p\|q) = \KL(q\|p).
  • The Monte Carlo estimator, the mean of ln⁡p/q\ln p/q over the mm samples from pp, converges to the formula (the lower readout) with error of order 1/m1/\sqrt{m}. Having a closed form is a luxury of Gaussians.

Implementation from scratch

First check numerically the claims about differential entropy: closed forms against numerical integration, the mixture with no formula, convergence under quantization, and the effect of rescaling.

[ ]Differential entropy: closed form, numerical integration, and quantizationBrowser
import numpy as np
from scipy import integrate, stats

def h_numerica(pdf, cortes):
    """h(X) = -∫ f ln f dx en nats, por cuadratura adaptativa entre los puntos de corte."""
    def integrando(x):
        f = pdf(x)
        return -f * np.log(f) if f > 0 else 0.0
    return sum(integrate.quad(integrando, a, b, limit=200)[0] for a, b in zip(cortes[:-1], cortes[1:]))

casos = {
    "N(0, 1)":      (stats.norm(0, 1).pdf,       [-12, 0, 12],  0.5 * np.log(2 * np.pi * np.e)),
    "N(0, 0.1^2)":  (stats.norm(0, 0.1).pdf,     [-1.2, 0, 1.2], 0.5 * np.log(2 * np.pi * np.e * 0.1**2)),
    "Exp(1)":       (stats.expon().pdf,          [0, 5, 60],    1.0),
    "Exp(2)":       (stats.expon(scale=0.5).pdf, [0, 3, 30],    1 - np.log(2)),
    "Laplace(b=1)": (stats.laplace().pdf,        [-60, 0, 60],  1 + np.log(2)),
    "U(0, 1/8)":    (lambda x: 8.0,              [0, 1 / 8],    np.log(1 / 8)),
}
print("densidad          numérica   cerrada (nats)   cerrada (bits)")
for nombre, (pdf, cortes, cerrada) in casos.items():
    print(f"{nombre:13s}  {h_numerica(pdf, cortes):9.5f}  {cerrada:9.5f}        {cerrada / np.log(2):9.5f}")

# una mezcla de dos gaussianas no tiene forma cerrada: integración numérica frente a Monte Carlo
mezcla = lambda x: 0.5 * stats.norm(-1.2, 0.55).pdf(x) + 0.5 * stats.norm(1.2, 0.55).pdf(x)
h_mezcla = h_numerica(mezcla, [-8, 0, 8])
rng = np.random.default_rng(0)
x = np.where(rng.random(200_000) < 0.5, rng.normal(-1.2, 0.55, 200_000), rng.normal(1.2, 0.55, 200_000))
mc = -np.mean(np.log(mezcla(x)))
var = 1.2**2 + 0.55**2
print(f"\nmezcla: h numérica = {h_mezcla:.4f}, Monte Carlo = {mc:.4f} nats; cota de la gaussiana con su varianza = {0.5 * np.log(2 * np.pi * np.e * var):.4f}")

# cuantización de N(0, 1): H(X_Δ) + log2 Δ converge a h(X) en bits
h_bits = 0.5 * np.log2(2 * np.pi * np.e)
print(f"\nh(N(0,1)) = {h_bits:.5f} bits")
for D in [1, 0.5, 0.25, 0.125, 0.0625]:
    k = np.arange(-int(8 / D) - 1, int(8 / D) + 2)
    p = np.diff(stats.norm.cdf(k * D))
    p = p[p > 0]
    H = -np.sum(p * np.log2(p))
    print(f"  Δ = {D:6.4f}:  H(X_Δ) = {H:7.4f}   H + log2 Δ = {H + np.log2(D):.5f}")

# cambio de escala: h(aX) = h(X) + ln a
for a in [0.1, 3.0]:
    h_a = 0.5 * np.log(2 * np.pi * np.e * a**2)
    print(f"h(N(0,{a}^2)) - h(N(0,1)) = {h_a - 0.5 * np.log(2 * np.pi * np.e):.5f}   ln a = {np.log(a):.5f}")

Integration reproduces the closed forms to five digits. The two negative values are expected: h(N(0,0.12))=−0.884h(\Normal(0, 0.1^2)) = -0.884 nats and h(Unif⁡(0,18))=−3h(\Unif(0, \tfrac18)) = -3 bits. The bimodal mixture has no formula, but numerical integration (1.47491.4749 nats) and the Monte Carlo estimate −1n∑ln⁡f(xi)-\frac1n\sum\ln f(x_i) (1.47591.4759) agree, and both lie below the Gaussian bound with the same variance (1.69661.6966), as the theorem requires. In quantization, each time Δ\Delta is halved, HH rises 11 bit (from 2.1052.105 to 6.0476.047) and H+log⁡2ΔH + \log_2\Delta converges to h=2.0471h = 2.0471. Scaling confirms h(aX)−h(X)=ln⁡ah(aX) - h(X) = \ln a (with a=0.1a = 0.1, −2.30259-2.30259).

Now KL between Gaussians. The naive formula with np.linalg.inv and np.linalg.det is correct in low dimensions, but a good implementation forms neither the inverse nor the determinant. With Σi=LiLi⊤\mat{\Sigma}_i = \mat{L}_i\mat{L}_i\T (Cholesky):

tr⁡(Σ1−1Σ0)=∥L1−1L0∥F2,(μ1−μ0)⊤Σ1−1(μ1−μ0)=∥L1−1(μ1−μ0)∥2,ln⁡det⁡Σi=2∑jln⁡(Li)jj.\tr(\mat{\Sigma}_1\inv\mat{\Sigma}_0) = \norm{\mat{L}_1\inv\mat{L}_0}_F^2, \qquad (\vb{\mu}_1-\vb{\mu}_0)\T\mat{\Sigma}_1\inv(\vb{\mu}_1-\vb{\mu}_0) = \norm{\mat{L}_1\inv(\vb{\mu}_1-\vb{\mu}_0)}^2, \qquad \ln\det\mat{\Sigma}_i = 2\sum_j\ln(\mat{L}_i)_{jj}.

The first two follow from Σ1−1=L1−TL1−1\mat{\Sigma}_1\inv = \mat{L}_1^{-\mathsf{T}}\mat{L}_1\inv and the cyclic property of trace; the third follows because det⁡Li\det\mat{L}_i is the product of its diagonal. Instead of inversion, solve triangular systems.

[ ]Gaussian KL: Cholesky versus naive formula and Monte CarloBrowser
import numpy as np
from scipy.linalg import cholesky, solve_triangular
from scipy import stats

def kl_gauss(mu0, S0, mu1, S1):
    """D( N(mu0, S0) || N(mu1, S1) ) en nats, con Cholesky: sin inversas ni determinantes explícitos."""
    mu0, mu1 = np.asarray(mu0, float), np.asarray(mu1, float)
    n = mu0.size
    L0 = cholesky(S0, lower=True)
    L1 = cholesky(S1, lower=True)
    M = solve_triangular(L1, L0, lower=True)            # L1^{-1} L0
    traza = np.sum(M ** 2)                              # tr(S1^{-1} S0) = ||L1^{-1} L0||_F^2
    z = solve_triangular(L1, mu1 - mu0, lower=True)
    maha = z @ z                                        # (mu1-mu0)^T S1^{-1} (mu1-mu0)
    logdet = 2 * (np.sum(np.log(np.diag(L1))) - np.sum(np.log(np.diag(L0))))
    return 0.5 * (traza + maha - n + logdet)

print("D(N(1,1) || N(0,1)) =", kl_gauss([1], [[1]], [0], [[1]]), "(esperado 0.5)")

rng = np.random.default_rng(0)
n = 5
def spd():
    A = rng.normal(size=(n, n))
    return A @ A.T + 0.5 * np.eye(n)
mu0, mu1, S0, S1 = rng.normal(size=n), rng.normal(size=n), spd(), spd()

# 1) contra la fórmula ingenua (inversa y determinante explícitos)
S1i, d = np.linalg.inv(S1), mu1 - mu0
ingenua = 0.5 * (np.trace(S1i @ S0) + d @ S1i @ d - n + np.log(np.linalg.det(S1) / np.linalg.det(S0)))
# 2) contra Monte Carlo: media de ln p(x) - ln q(x) con x ~ p
x = rng.multivariate_normal(mu0, S0, size=200_000)
lr = stats.multivariate_normal(mu0, S0).logpdf(x) - stats.multivariate_normal(mu1, S1).logpdf(x)
print(f"Cholesky = {kl_gauss(mu0, S0, mu1, S1):.5f}   ingenua = {ingenua:.5f}   Monte Carlo = {lr.mean():.5f} ± {lr.std() / np.sqrt(lr.size):.5f}")
print(f"asimetría: D(p||q) = {kl_gauss(mu0, S0, mu1, S1):.4f},  D(q||p) = {kl_gauss(mu1, S1, mu0, S0):.4f}")

# 3) el caso del VAE: codificador diagonal frente a N(0, I)
mu, sigma = np.array([0.5, -1.0]), np.array([0.8, 1.5])
vae = 0.5 * np.sum(sigma ** 2 + mu ** 2 - 1 - np.log(sigma ** 2))
print(f"VAE: fórmula diagonal = {vae:.5f},  Cholesky = {kl_gauss(mu, np.diag(sigma ** 2), np.zeros(2), np.eye(2)):.5f}")

# 4) alta dimensión: el determinante explícito se desborda, el log-determinante por Cholesky no
d = 200
S, I = 0.01 * np.eye(d), np.eye(d)
with np.errstate(divide="ignore"):
    ingenua = 0.5 * (np.trace(I @ S) - d + np.log(np.linalg.det(I) / np.linalg.det(S)))
exacta = d * 0.5 * (0.01 - 1 - np.log(0.01))
print(f"d = {d}: det(0.01 I) = {np.linalg.det(S)},  KL ingenua = {ingenua},  KL Cholesky = {kl_gauss(np.zeros(d), S, np.zeros(d), I):.3f}  (exacta {exacta:.3f})")

# 5) varianza del estimador Monte Carlo con p = N(0, 0.25 I), q = N(0, I) al crecer la dimensión
n_mc = 1000
print("   d    KL exacta   desv. del estimador   error relativo")
for d in [1, 10, 100, 1000]:
    xs = rng.normal(0.0, 0.5, size=(n_mc, d))
    lp = -0.5 * np.sum(xs ** 2 / 0.25 + np.log(2 * np.pi * 0.25), axis=1)
    lq = -0.5 * np.sum(xs ** 2 + np.log(2 * np.pi), axis=1)
    r = lp - lq
    kl = d * 0.5 * (0.25 - 1 - np.log(0.25))
    print(f"{d:4d}  {kl:10.3f}  {r.std() / np.sqrt(n_mc):17.4f}  {r.std() / np.sqrt(n_mc) / kl:14.4f}")

The three evaluations agree: 4.585274.58527 with Cholesky and the naive formula, and 4.601±0.0144.601 \pm 0.014 with 200 000 Monte Carlo samples (within two standard errors). Asymmetry is real even in this random example: KL⁡(p∥q)=4.585\KL(p\|q) = 4.585 and KL⁡(q∥p)=7.697\KL(q\|p) = 7.697. The VAE case gives 0.887680.88768 with both the diagonal formula and Cholesky. In dimension d=200d = 200 with Σ0=0.01 I\mat{\Sigma}_0 = 0.01\,\mat{I}, the determinant is 0.01200=10−4000.01^{200} = 10^{-400}, below the smallest representable value: np.linalg.det returns exactly 0.0 and the naive formula gives inf, while Cholesky sums logarithms and yields 361.517361.517, the exact value. This is the number-one mistake in this topic (see common mistakes).

The last block contains a useful observation. The absolute Monte Carlo estimator error grows as d\sqrt{d} (0.0180.018 in d=1d = 1 to 0.5350.535 in d=1000d = 1000), because the log ratio is a sum of dd independent terms, but relative error falls as 1/d1/\sqrt{d} (5.6%5.6\% to 0.17%0.17\%), because KL grows as dd. For high-dimensional Gaussians the estimator is not what fails: the naive formula is. Monte Carlo is used when there is no formula (mixtures, flows), in which case estimator variance depends on the shape of the density ratio; with Gaussians, the closed form is always better.

The Gaussian channel

Return to the physical problem. The channel of lesson 9 had finite alphabets; here input and output are real, and input must be limited, because without a power constraint enormous amplitudes could separate levels arbitrarily far, giving infinite capacity.

Proof

With Y=X+ZY = X + Z and ZZ independent of XX, h(Y∣X)=h(X+Z∣X)=h(Z)h(Y \mid X) = h(X + Z \mid X) = h(Z), because given XX, YY is a translation of ZZ. Therefore I(X;Y)=h(Y)−h(Z)I(X;Y) = h(Y) - h(Z), and h(Z)=12log⁡2(2πeN)h(Z) = \tfrac12\log_2(2\pi e N) is fixed. It remains to bound h(Y)h(Y). Since X⊥ ⁣ ⁣ ⁣⊥ZX \indep Z, E[Y2]=E[X2]+N≤P+N\E[Y^2] = \E[X^2] + N \le P + N, and by the maximum-entropy theorem (second-moment variant), h(Y)≤12log⁡2(2πe(P+N))h(Y) \le \tfrac12\log_2\big(2\pi e(P + N)\big). Subtracting,

I(X;Y)≤12log⁡2(2πe(P+N))−12log⁡2(2πeN)=12log⁡2(1+PN).I(X;Y) \le \frac12\log_2\big(2\pi e(P+N)\big) - \frac12\log_2(2\pi e N) = \frac12\log_2\Big(1 + \frac PN\Big).

With X∼N(0,P)X \sim \Normal(0, P), Y=X+Z∼N(0,P+N)Y = X + Z \sim \Normal(0, P + N) is Gaussian with the maximum allowed variance, and the bound is attained.

∎

The proof has a clear skeleton: I=h(Y)−h(Z)I = h(Y) - h(Z), noise sets a fixed floor and power limits a ceiling, attained if and only if the output is Gaussian. Since a sum of independent variables is Gaussian only if both are Gaussian, Gaussian input is the unique optimum. The figure compares Gaussian input with others of the same power.

InteractiveChoosing an input for the Gaussian channel
  • capacity (Gaussian input)
  • uniform
  • 8 points
  • 4 points
  • 2 points
  • output YY
  • Gaussian of equal variance
Input X distribution
12.0 dB
Power ratio P/NP/N15.85
I(X;Y)I(X;Y) for this input1.790 bits
Capacity 12log⁡2(1+P/N)\frac12\log_2(1 + P/N)2.037 bits
Gap C−IC - I0.248 bits
Power a Gaussian would save1.60 dB
The output YY has the same variance as the Gaussian (dashed) but lower entropy, causing the loss: I=h(Y)−h(Z)I = h(Y) - h(Z) and h(Z)h(Z) does not change.
Channel Y=X+ZY = X + Z with N=1N = 1 and fixed input power PP. At left, the input (curve or points), output YY (orange), and Gaussian with the same variance (dashed). At right, I(X;Y)I(X;Y) against SNR in decibels for each input, compared with capacity (thick line in the text color). With Gaussian input, the output is exactly the dashed curve. Choose ‘2 points’ and raise SNR: at how many bits does it saturate? With ‘Uniform’, raise it to 30 dB: what gap remains? How many decibels of power would a Gaussian input save?

Three things to read in the figure:

  • An input with MM points saturates at log⁡2M\log_2 M bits, however high the SNR. With 2 points (binary modulation), information at 10 dB is 0.9970.997 bits, and capacity 1.7301.730. With 4 and 8 points it rises further, but the limit log⁡2M\log_2 M remains. Capacity keeps growing without bound, and no finite constellation attains it at high SNR.
  • At high SNR, a uniform input (bounded support) loses 12log⁡2πe6=0.2546\tfrac12\log_2\frac{\pi e}{6} = 0.2546 bits. This is the limiting gap, which is 0.1870.187 at 20 dB and 0.2320.232 at 30 dB. It is 10log⁡10πe6=1.53310\log_{10}\frac{\pi e}{6} = 1.533 dB of power: the “shaping gain” and the reason modern modulation designs use probabilistic constellations that mimic a Gaussian.
  • With Gaussian input, the output is the dashed curve. With any other input, output entropy is less than that of a Gaussian with the same variance (by maximum entropy), and since h(Z)h(Z) is unchanged, information falls by exactly that difference.

Geometric interpretation: counting spheres

The theorem gives information capacity; that it is also the largest rate for communication with arbitrarily small error is the Gaussian channel coding theorem (Cover and Thomas, theorem 9.1.1), obtained using the same techniques as lesson 10: random Gaussian codebooks and joint-typicality decoding. We do not reproduce it, but the geometric argument explains the formula, and is the level count from the motivation carried out in Rn\R^n.

In nn uses, a codeword x∈Rn\vb{x} \in \R^n has ∥x∥2≤nP\norm{\vb{x}}^2 \le nP, and noise z\vb{z} has ∥z∥2≈nN\norm{\vb{z}}^2 \approx nN by the law of large numbers. The output y=x+z\vb{y} = \vb{x} + \vb{z} falls, with z\vb{z} nearly orthogonal to x\vb{x} in high dimension, inside the ball of radius n(P+N)\sqrt{n(P + N)}. For error-free decoding, noise balls of radius nN\sqrt{nN} around codewords cannot overlap. Since the volume of a ball of radius rr in Rn\R^n is proportional to rnr^n, the number of words satisfies

M≤(n(P+N)nN)n=(1+PN)n/2,R=1nlog⁡2M≤12log⁡2(1+PN).M \le \Big(\frac{\sqrt{n(P+N)}}{\sqrt{nN}}\Big)^n = \Big(1 + \frac PN\Big)^{n/2}, \qquad R = \frac1n\log_2 M \le \frac12\log_2\Big(1 + \frac PN\Big).

This is no coincidence with the previous proof: it is the same proof. A typical set of nn samples with density ff has volume ≈2nh\approx 2^{nh} (the continuous version of asymptotic equipartition, with the same proof and the law of large numbers applied to −log⁡f(Xi)-\log f(X_i)). Typical output occupies volume 2nh(Y)2^{n h(Y)} and each noise ball 2nh(Z)2^{nh(Z)}; their ratio is 2n(h(Y)−h(Z))=2nI(X;Y)2^{n(h(Y)-h(Z))} = 2^{nI(X;Y)}. Mutual information is the logarithm (per sample) of the number of noise balls that fit in the output.

Regimes and robustness

  • High SNR. C≈12log⁡2PNC \approx \tfrac12\log_2\frac PN: each 6.02 dB (four times the power) gains one bit, and each 3.01 dB half a bit. From 00 to 1010, 2020 and 3030 dB, capacity is 0.50.5, 1.731.73, 3.333.33, and 4.984.98 bits per use: it grows as the logarithm of power.
  • Low SNR. C≈P2Nln⁡2C \approx \frac{P}{2N\ln 2}, linear in power. With P/N=0.01P/N = 0.01, C=0.00718C = 0.00718 bits and the approximation gives 0.007210.00721. Here power buys bits at a constant rate; this is the deep-space-link regime.
  • The Shannon limit. If EbE_b is energy per bit and noise has spectral density N0N_0 (so N=N0/2N = N_0/2 per real sample), a rate RR bits per sample requires P=R EbP = R\,E_b and R≤12log⁡2(1+2R Eb/N0)R \le \tfrac12\log_2(1 + 2R\,E_b/N_0), that is Eb/N0≥(22R−1)/(2R)E_b/N_0 \ge (2^{2R}-1)/(2R). As R→0R \to 0 the ratio tends to ln⁡2\ln 2: reliable communication below Eb/N0=ln⁡2=−1.59E_b/N_0 = \ln 2 = -1.59 dB is impossible, however little is sent. With R=1R = 1 it requires 1.761.76 dB.
Proof

Let Y=X+ZY = X + Z and α=P/(P+N)\alpha = P/(P+N). Conditioning reduces entropy and hh is translation-invariant, so h(X∣Y)=h(X−αY∣Y)≤h(X−αY)h(X \mid Y) = h(X - \alpha Y \mid Y) \le h(X - \alpha Y). By maximum entropy, h(X−αY)≤12log⁡2(2πe E[(X−αY)2])h(X - \alpha Y) \le \tfrac12\log_2\big(2\pi e\,\E[(X-\alpha Y)^2]\big), and E[(X−αY)2]=(1−α)2P+α2N=PNP+N\E[(X-\alpha Y)^2] = (1-\alpha)^2P + \alpha^2N = \frac{PN}{P+N} whatever the distribution of ZZ. Therefore I=h(X)−h(X∣Y)≥12log⁡2(2πeP)−12log⁡22πe PNP+N=12log⁡2(1+P/N)I = h(X) - h(X \mid Y) \ge \tfrac12\log_2(2\pi e P) - \tfrac12\log_2\frac{2\pi e\,PN}{P+N} = \tfrac12\log_2(1 + P/N).

∎

This is a design guarantee: with Gaussian input, the information crossing the channel does not decrease if the actual noise has another distribution with the same variance. The operational version also holds: a random Gaussian codebook decoded by minimum Euclidean distance, the decoder designed for Gaussian noise, achieves any rate below 12log⁡2(1+P/N)\tfrac12\log_2(1 + P/N) with any i.i.d. noise of variance NN independent of the input (Lapidoth, 1996). That is why noise is modeled as Gaussian when nothing else is known: it is the pessimistic assumption.

Parallel channels and water filling

A real channel often decomposes into independent channels with different noise levels: the subcarriers of an OFDM signal (each frequency is attenuated differently), antennas of a MIMO system after singular-value decomposition, or principal components of colored noise. We have kk channels Yi=Xi+ZiY_i = X_i + Z_i, with independent Zi∼N(0,Ni)Z_i \sim \Normal(0, N_i), and total power ∑iE[Xi2]≤P\sum_i \E[X_i^2] \le P to allocate. How much power should each receive?

Intuition says power should go to clean channels, but not just one: returns diminish (the logarithm is concave). The exact answer comes from convex optimization.

Proof

Reduction. Since the noises are independent, h(Y∣X)=∑ih(Zi)h(\vb{Y} \mid \vb{X}) = \sum_i h(Z_i) and h(Y)≤∑ih(Yi)h(\vb{Y}) \le \sum_i h(Y_i), hence I(X;Y)≤∑i(h(Yi)−h(Zi))≤∑i12log⁡2(1+Pi/Ni)I(\vb{X};\vb{Y}) \le \sum_i\big(h(Y_i) - h(Z_i)\big) \le \sum_i\tfrac12\log_2(1 + P_i/N_i), with Pi=E[Xi2]P_i = \E[X_i^2] and the scalar channel inequality for each ii. Equality is attained with independent Gaussian inputs of powers PiP_i. What remains is an allocation problem.

Optimization. The objective is concave in (P1,…,Pk)(P_1, \dots, P_k) and the constraints are linear, so the KKT conditions are necessary and sufficient. With the Lagrangian (in nats, which does not change the optimum)

L=∑i12ln⁡(1+PiNi)−λ(∑iPi−P)+∑iμiPi,μi≥0, μiPi=0,\mathcal{L} = \sum_i\frac12\ln\Big(1 + \frac{P_i}{N_i}\Big) - \lambda\Big(\sum_i P_i - P\Big) + \sum_i\mu_i P_i, \qquad \mu_i \ge 0,\ \mu_iP_i = 0,

stationarity gives 12(Ni+Pi)=λ−μi\dfrac{1}{2(N_i + P_i)} = \lambda - \mu_i. If Pi>0P_i > 0, μi=0\mu_i = 0 and Ni+Pi=12λ=:νN_i + P_i = \frac{1}{2\lambda} =: \nu (the same for all active channels). If Pi=0P_i = 0, μi≥0\mu_i \ge 0 gives 12Ni≤λ\frac{1}{2N_i} \le \lambda, that is Ni≥νN_i \ge \nu. Both cases are Pi=(ν−Ni)+P_i = (\nu - N_i)^+. The function ν↦∑i(ν−Ni)+\nu \mapsto \sum_i(\nu - N_i)^+ is continuous, increasing, and piecewise linear, equals 00 at ν=min⁡iNi\nu = \min_i N_i, and tends to ∞\infty, so ν\nu exists and is unique. Since capacity grows with power, constraint ∑iPi≤P\sum_i P_i \le P is active.

∎

The image explains the name: the bottom of a vessel has height NiN_i in channel ii and an amount PP of water is poured in; the water rises to a common level ν\nu, and its depth in each channel is PiP_i. Channels with Ni≥νN_i \ge \nu stay dry. There is an economic interpretation: the marginal benefit of an extra watt in channel ii is 12ln⁡2 (Ni+Pi)\frac{1}{2\ln 2\,(N_i + P_i)} bits, and the optimum equalizes it across active channels at 12ln⁡2 ν\frac{1}{2\ln2\,\nu}; a dry channel would yield less even for its first watt. That number is the multiplier of the constraint and also the slope of the capacity curve: dC/dP=12ln⁡2 ν\mathrm{d}C/\mathrm{d}P = \frac{1}{2\ln2\,\nu}.

InteractiveWater filling
bits per use, ½ log₂(1 + Pᵢ/Nᵢ)channel 1P = 2.671.33channel 2P = 2.170.83channel 3P = 1.170.33channel 4P = 0.00drychannel 5P = 0.00dry
  • floor: noise NiN_i
  • water: power Pi=(ν−Ni)+P_i = (\nu - N_i)^+
  • uniform allocation P/KP/K
6.00
Water level ν\nu3.167
Active channels3 of 5
Capacity with water filling2.494 bits
Capacity with uniform allocation2.081 bits
Uniform allocation's loss0.414 bits
Value of an extra watt, 12ln⁡2 ν\frac{1}{2\ln 2\,\nu}0.228 bits
Only 3 of 5 channels receive power. The others have noise Ni≥ν=3.17N_i \ge \nu = 3.17: a watt there yields less than in any active channel, so they stay dry.
Five parallel Gaussian channels. The bottom of each vessel (gray) is its noise NiN_i and can be dragged using the point on its top edge. Pouring power PP (slider, or ‘Pour water’ to animate) raises the water to common level ν\nu. At right, or below on narrow screens, are the bits contributed by each channel with water filling (bars) and uniform allocation (dashed outlines). Select ‘Pour water’, which starts at P=0P = 0: in what order do channels activate? With ‘One very noisy channel’, how much power is needed before it receives any? With ‘Equal noises’, what is the optimal allocation? Drag a bottom down until water reaches it and watch everything redistribute.

With noise levels (1,3,6)(1, 3, 6) and P=4P = 4: first try one active channel (ν=5\nu = 5, which exceeds N2=3N_2 = 3, so it is insufficient), then two (ν=(4+1+3)/2=4≤N3=6\nu = (4 + 1 + 3)/2 = 4 \le N_3 = 6, valid). The allocation is P=(3,1,0)P = (3, 1, 0) and capacity 12log⁡24+12log⁡243=1.2075\tfrac12\log_2 4 + \tfrac12\log_2\tfrac43 = 1.2075 bits, versus 1.02121.0212 with uniform allocation. A common mistake is to assume all three are active: this gives ν=14/3\nu = 14/3 and P3=−4/3P_3 = -4/3, a negative power exposing the error.

What to look for in the figure:

  • Activation follows increasing noise levels, and each new channel activates just as the level reaches its bottom. With the initial configuration (N=0.5,1,2,4,8N = 0.5, 1, 2, 4, 8), the second channel activates at P=0.5P = 0.5, the third at P=2.5P = 2.5, the fourth at P=8.5P = 8.5, and the fifth at P=24.5P = 24.5 (in each case, P=∑i(Nk−Ni)+P = \sum_i(N_k - N_i)^+ with NkN_k the noise of the activating channel).
  • Uniform allocation is worse, especially at low power: with P=6P = 6 it loses 0.4140.414 bits out of 2.4942.494 (17%17\%). With very large PP the level ν\nu exceeds all bottoms and the optimum approaches uniform allocation (with P=32P = 32, 5.625.62 versus 5.495.49).
  • Marginal value is the same in active channels. This makes the KKT equation visible: water has a single level.

In practice the same result governs power allocation among OFDM subcarriers; in MIMO, with singular-value decomposition H=UΣV⊤\mat{H} = \mat{U}\mat{\Sigma}\mat{V}\T, the parallel channels have effective noise Ni=σ2/si2N_i = \sigma^2/s_i^2 (sis_i are the singular values); and with colored noise of covariance K\mat{K} water filling is performed over the eigenvalues of K\mat{K}. The last case connects with module 12: under Gaussian noise, maximizing the information of a linear projection leads to principal components.

The algorithm uses bisection on ν\nu and is verified with a generic optimizer and the KKT conditions:

[ ]Water filling by bisection, verified with SLSQP and KKTBrowser
import numpy as np
from scipy.optimize import minimize

def water_filling(ruido, P, tol=1e-13):
    """Potencias óptimas, nivel de agua nu y capacidad (bits por uso) de canales gaussianos paralelos."""
    N = np.asarray(ruido, float)
    lo, hi = N.min(), N.max() + P            # en lo no hay agua; en hi sobra: la suma supera P
    while hi - lo > tol * hi:
        nu = 0.5 * (lo + hi)
        if np.maximum(nu - N, 0).sum() > P:
            hi = nu
        else:
            lo = nu
    nu = 0.5 * (lo + hi)
    p = np.maximum(nu - N, 0)
    return p, nu, 0.5 * np.sum(np.log2(1 + p / N))

ruido, P = np.array([0.5, 1, 2, 4, 8]), 6.0
p, nu, C = water_filling(ruido, P)
uniforme = np.full(5, P / 5)
C_unif = 0.5 * np.sum(np.log2(1 + uniforme / ruido))
print(f"nivel nu = {nu:.4f}   potencias = {np.round(p, 4)}   suma = {p.sum():.4f}")
print(f"capacidad: agua = {C:.4f} bits,  uniforme = {C_unif:.4f} bits  (pierde {C - C_unif:.4f})")

# verificación con un optimizador genérico (SLSQP) sobre el simplex de potencias
neg_cap = lambda q: -0.5 * np.sum(np.log2(1 + np.maximum(q, 0) / ruido))
res = minimize(neg_cap, uniforme, method="SLSQP", bounds=[(0, None)] * 5, constraints=[{"type": "eq", "fun": lambda q: q.sum() - P}])
print(f"SLSQP:  potencias = {np.round(res.x, 4)}   capacidad = {-res.fun:.4f}")

# condiciones KKT: el valor marginal 1/(2 ln2 (N_i + P_i)) es el mismo en los canales activos y menor en los secos
marginal = 1 / (2 * np.log(2) * (ruido + p))
print("valor marginal por canal:", np.round(marginal, 4), "  1/(2 ln2 nu) =", round(1 / (2 * np.log(2) * nu), 4))

# la pendiente de C(P) es el valor marginal: derivada numérica
dP = 1e-4
print(f"dC/dP numérica = {(water_filling(ruido, P + dP)[2] - water_filling(ruido, P - dP)[2]) / (2 * dP):.5f}")

# capacidad frente a la potencia: canales que se van activando
print("\n   P    activos    agua   uniforme")
for P_ in [0.25, 0.5, 1, 2, 4, 8, 16, 32]:
    q, v, c = water_filling(ruido, P_)
    cu = 0.5 * np.sum(np.log2(1 + P_ / 5 / ruido))
    print(f"{P_:5.2f}  {int(np.sum(q > 0)):6d}  {c:8.4f}  {cu:8.4f}")

With P=6P = 6 the level is ν=3.1667\nu = 3.1667 and the powers (2.667,2.167,1.167,0,0)(2.667, 2.167, 1.167, 0, 0): three channels active and the two noisiest dry, with capacity 2.4942.494 bits versus 2.0812.081 for uniform allocation. SLSQP, which does not know the structure, reaches the same value 2.49442.4944 with powers agreeing to two decimals. The marginal value is 0.22780.2278 in the three active channels (equal to 1/(2ln⁡2 ν)1/(2\ln 2\,\nu) and the numerical derivative dC/dP=0.22779\mathrm{d}C/\mathrm{d}P = 0.22779), and 0.1800.180 and 0.0900.090 in the dry ones, smaller values: the KKT inequality condition. The final table shows channels activating as PP increases.

The library version

scipy.stats.multivariate_normal already computes Gaussian entropy, and in PyTorch KL divergence between distributions is one call. In VAEs, the diagonal formula is evaluated by hand on the log-variance output by the network, because parameterizing with λ=ln⁡σ2\lambda = \ln\sigma^2 prevents negative variance:

import torch
from torch.distributions import Normal, MultivariateNormal, kl_divergence

mu, logvar = torch.tensor([0.5, -1.0]), torch.log(torch.tensor([0.8, 1.5]) ** 2)

# a mano, sobre la log-varianza (la forma habitual en un VAE): 1/2 sum(mu^2 + exp(lv) - 1 - lv)
kl_manual = 0.5 * torch.sum(mu**2 + logvar.exp() - 1 - logvar)

# con torch.distributions (gaussiana diagonal: un lote de Normal univariantes, una por coordenada)
q = Normal(mu, (0.5 * logvar).exp())
p = Normal(torch.zeros(2), torch.ones(2))
kl_torch = kl_divergence(q, p).sum()

# gaussianas completas: usa Cholesky por dentro (scale_tril)
Sigma = torch.diag(logvar.exp())
kl_full = kl_divergence(MultivariateNormal(mu, covariance_matrix=Sigma), MultivariateNormal(torch.zeros(2), torch.eye(2)))
print(kl_manual.item(), kl_torch.item(), kl_full.item())  # 0.88768 las tres

All three forms give the same value, 0.887680.88768. Two practical details. kl_divergence(Normal, Normal) returns a tensor per coordinate, and you must sum over the latent dimension (and average over the batch): confusing this scales regularization by dd. Parameterizing by log-variance makes the gradient with respect to λ\lambda equal to 12(eλ−1)\tfrac12(e^{\lambda} - 1), stable and without singularities at σ→0\sigma \to 0, while parameterizing by σ\sigma gives σ−1/σ\sigma - 1/\sigma, which blows up.

Common mistakes

Exercises

NumericA negative differential entropy
Calculate, in bits, the differential entropy of a uniform variable on [0,1/8][0, 1/8].
NumericKL between Gaussians with equal variance
Calculate, in nats, D(N(1,1) ∥ N(0,1))D\big(\Normal(1, 1)\,\|\,\Normal(0, 1)\big).
NumericCapacity at 20 dB SNR
A Gaussian channel has a signal-to-noise ratio of 20 dB. What is its capacity in bits per use?
NumericWater filling with three channels
Three parallel Gaussian channels have noises N=(1,3,6)N = (1, 3, 6) and total power P=4P = 4. What is their joint capacity in bits per use under optimal allocation?
NumericEntropy after a linear transformation
Let X∼N(0,I2)\vb{X} \sim \Normal(\vb{0}, \mat{I}_2) and A=[2103]\mat{A} = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix}. Calculate the differential entropy of AX\mat{A}\vb{X} in nats.
QuizMultiply by 2
Define X′=2XX' = 2X and keep YY fixed. How do h(X)h(X) and I(X;Y)I(X;Y) change?
QuizWhich statements are true?
Select the correct statements about differential entropy.

More than one answer may be correct.

QuizA narrow Gaussian inside a wide one
Let p=N(0,0.01)p = \Normal(0, 0.01) and q=N(0,1)q = \Normal(0, 1). Which divergence is larger?
QuizOne more bit per use
In a Gaussian channel at high SNR, how much extra power (in dB) is needed to gain one bit per use of capacity?
ProofThe Gaussian maximizes entropy
Prove: Let X\vb{X} have density ff on Rn\R^n, mean μ\vb{\mu} and covariance Σ≻0\mat{\Sigma} \succ 0. Then h(X)≤12ln⁡((2πe)ndet⁡Σ)h(\vb{X}) \le \tfrac12\ln\big((2\pi e)^n\det\mat{\Sigma}\big), with equality if and only if X\vb{X} is Gaussian.
0
Let φ\varphi be the density of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}). Work in nats.

Step 1 of 4. Which inequality is used, and with which two densities?

ProofThe KL of a VAE encoder
Prove: With p=N(μ,diag⁡σ2)p = \Normal(\vb{\mu}, \diag\vb{\sigma}^2) and q=N(0,Id)q = \Normal(\vb{0}, \mat{I}_d), KL⁡(p ∥ q)=12∑i=1d(σi2+μi2−1−ln⁡σi2)\KL(p\,\|\,q) = \frac12\sum_{i=1}^d\big(\sigma_i^2 + \mu_i^2 - 1 - \ln\sigma_i^2\big).
0
Work in nats. The coordinates of pp and those of qq are independent.

Step 1 of 4. How does the problem reduce to one dimension?

CodeImplement water filling
Implement water_filling(noise, P), which takes noises noise (a vector of kk positive numbers) and total power P ≥0\ge 0 and returns (p, C): the optimal allocation p (a vector of length kk) and capacity C in bits per use, ∑i12log⁡2(1+pi/Ni)\sum_i \frac12\log_2(1 + p_i/N_i). The allocation must satisfy pi=(ν−Ni)+p_i = (\nu - N_i)^+ with ∑pi=P\sum p_i = P. It must work with P = 0, repeated noise levels, one channel, and noises in any order.
import numpy as np

def water_filling(noise, P):
  """Reparto óptimo de potencia entre canales gaussianos paralelos. Devuelve (p, C) con C en bits."""
  N = np.asarray(noise, dtype=float)
  # tu código: busca el nivel nu (bisección o ordenando los ruidos) y reparte p = max(nu - N, 0)
  return np.zeros_like(N), 0.0
Shift+Enter to run

Summary

Key idea
Differential entropy h(X)=−∫flog⁡fh(X) = -\int f\log f is the entropy of XX measured relative to the unit of measurement, the logarithm of an effective volume: it can be negative and changes with scale, h(aX)=h(X)+log⁡∣a∣h(aX) = h(X) + \log\abs{a}. Divergence KL⁡\KL and mutual information II instead compare volumes in the same units and are invariant, nonnegative, and limits of their discrete versions. A Gaussian maximizes hh at fixed covariance, yielding the closed-form KL between Gaussians, Gaussian channel capacity 12log⁡2(1+P/N)\tfrac12\log_2(1 + P/N), and water filling for parallel channels.
  • Differential entropy. h(X)=E[−log⁡f(X)]h(X) = \E[-\log f(X)]. Unif⁡(a,b)\Unif(a,b): ln⁡(b−a)\ln(b-a). Exp(λ)\mathrm{Exp}(\lambda): 1−ln⁡λ1 - \ln\lambda. N(μ,σ2)\Normal(\mu,\sigma^2): 12ln⁡(2πeσ2)\tfrac12\ln(2\pi e\sigma^2). N(μ,Σ)\Normal(\vb{\mu},\mat{\Sigma}): 12ln⁡((2πe)ndet⁡Σ)\tfrac12\ln((2\pi e)^n\det\mat{\Sigma}). It can be negative (Unif⁡(0,18)\Unif(0,\tfrac18): −3-3 bits).
  • Quantization. H(XΔ)+log⁡Δ→h(X)H(X_\Delta) + \log\Delta \to h(X): each bit of precision costs one bit. hh is entropy at precision 1.
  • Transformations. h(AX+c)=h(X)+log⁡∣det⁡A∣h(\mat{A}\vb{X} + \vb{c}) = h(\vb{X}) + \log\abs{\det\mat{A}}; in general, add the expected log-Jacobian. KL⁡\KL and II are invariant under diffeomorphisms, and KL⁡(f∥g)≥0\KL(f\|g) \ge 0, I≥0I \ge 0.
  • Maximum entropy. With covariance Σ\mat{\Sigma}, h≤12ln⁡((2πe)ndet⁡Σ)h \le \tfrac12\ln((2\pi e)^n\det\mat{\Sigma}) with equality only for the Gaussian; the gap is KL⁡(f∥φ)\KL(f\|\varphi). With EX2≤P\E X^2 \le P: h≤12ln⁡(2πeP)h \le \tfrac12\ln(2\pi e P).
  • KL between Gaussians. 12[tr⁡(Σ1−1Σ0)−n+ln⁡det⁡Σ1det⁡Σ0+Δμ⊤Σ1−1Δμ]\tfrac12[\tr(\mat{\Sigma}_1\inv\mat{\Sigma}_0) - n + \ln\frac{\det\mat{\Sigma}_1}{\det\mat{\Sigma}_0} + \Delta\vb{\mu}\T\mat{\Sigma}_1\inv\Delta\vb{\mu}]; VAE: 12∑(σi2+μi2−1−ln⁡σi2)\tfrac12\sum(\sigma_i^2 + \mu_i^2 - 1 - \ln\sigma_i^2). Asymmetric: a narrow ellipse inside a wide one costs little in one direction and much in the other. Compute with Cholesky, not inv or det.
  • Gaussian channel. Y=X+ZY = X + Z, EX2≤P\E X^2 \le P: C=12log⁡2(1+P/N)C = \tfrac12\log_2(1 + P/N) bits per use, with X∼N(0,P)X \sim \Normal(0,P) uniquely optimal, because I=h(Y)−h(Z)I = h(Y) - h(Z) with maximum h(Y)h(Y). One extra bit costs 6 dB; the Shannon limit is Eb/N0≥ln⁡2=−1.59E_b/N_0 \ge \ln 2 = -1.59 dB; Gaussian noise is the worst. Geometrically, II is the logarithm of the number of noise balls that fit in the output.
  • Parallel channels. C=max⁡∑12log⁡2(1+Pi/Ni)C = \max\sum\tfrac12\log_2(1 + P_i/N_i) gives Pi=(ν−Ni)+P_i = (\nu - N_i)^+ with ∑Pi=P\sum P_i = P (water filling, by KKT): channels with Ni≥νN_i \ge \nu stay dry and marginal value 12ln⁡2 ν\frac{1}{2\ln 2\,\nu} is common.
  • Practice. hh is not bits; units (nats or bits); solve_triangular and log-determinants, not inv or det; sum over the latent dimension in the KL term; parameterize by log-variance; colored noise and MIMO reduce to parallel channels.