The information bottleneck
Extract from X only what is relevant to Y by minimizing I(X;T) − β I(T;Y). Derive self-consistent equations and iterative annealing, connect rate–distortion and minimal sufficiency, study neural VIB and critically evaluate the information plane and compression hypothesis in deep learning.
After this lesson you can
- Formulate the information bottleneck Lagrangian and derive its self-consistent equations.
- Implement the iterative algorithm with β annealing and plot information curves and phase transitions.
- Derive the VIB bounds and train a VIB in PyTorch.
- Critically analyze why deterministic-network mutual information is infinite or trivial and how binning creates artifacts.
- Place the information bottleneck in self-supervision, generalization and minimal sufficient representations.
Before you start
- 07Mutual informationData processing inequalityGibbs distributionRate-distortion functionRate-distortion LagrangianVariational rate boundPlug-in entropy estimationVariational bounds on mutual information
- 15Micro framework to PyTorch correspondenceBackpropagation
- 06Adam
- 14Reparameterization gradient
- 04Affine transformations of Gaussians
Motivation: representations that forget what is irrelevant
A good representation does not preserve the most; it preserves what matters. A digit classifier need not know stroke thickness or tilt; a system grouping words by topic need not distinguish “goal” from “goalkeeper”; a chess agent need not know the screen colors of pieces. In each case an observed variable (image, word, pixel) and a variable defining relevance (class, topic, position value) lead us to seek a representation of that is small yet informative about .
Classical statistics names the exact version. A statistic is sufficient for if adds nothing about once is known: is a Markov chain. By the data processing inequality, this is equivalent to : not one bit of mutual information is lost. It is minimal sufficient if it is also a function of every other sufficient statistic: it compresses most without loss.
The problem is that exact minimal sufficient statistics are almost never small. For independent samples from a parametric family, the Pitman–Koopman–Darmois theorem says that, if support does not depend on the parameter, only exponential families admit fixed-dimensional sufficient statistics as sample size grows. Outside these, the minimal sufficient representation grows with data. The natural way out is to relax the requirement: accept losing a little in exchange for substantial compression. That is Tishby, Pereira and Bialek’s (1999) information bottleneck: an approximately minimal sufficient statistic, with a parameter setting how many compression bits each relevance bit is worth.
The idea has had three lives. As a clustering method (words by topic, documents, genes, neurons), with an elegant iterative algorithm and phase transitions. As a trainable objective for neural networks, the variational information bottleneck, a close relative of the VAE. And as a deep learning theory, the hypothesis that networks first fit and then compress, which sparked an instructive debate about how (not) to measure information. This lesson covers all three with appropriate rigor and critical distance.
Throughout, is base 2 in figures and natural in derivatives. This makes no difference: changing base multiplies both informations in the Lagrangian by the same constant, leaving the optimum and (compression bits per relevance bit) unchanged.
The bottleneck problem
Start with a known joint distribution , initially with discrete and . A representation is a stochastic encoder : for each , a distribution over representation alphabet . Since is built only from , the Markov chain holds, and everything else follows from the joint and encoder:
The structure is that of rate–distortion theory: is the encoder rate, and what was a hand-chosen distortion there is information lost about here. Basic curve properties follow readily.
Proof
(1) Data processing applied to gives , and applied to (the same chain reversed), . (2) With , is independent of and, by (1), . With (possible if ), is attained, the maximum by (1). (3) Monotonicity follows from constrained maximization. For concavity, take encoders with and , an independent coin with , and the encoder emitting . Since is independent of and , the chain rule gives , and similarly for . The achievable set is convex and its upper boundary concave. (4) By (1), , while the trivial encoder gives .
∎As in rate–distortion, the multiplier has a geometric interpretation: the optimum for given is where a line of slope touches the concave curve from above (the rate–distortion Lagrangian reads similarly). At small the line is steep and touches the origin; as grows it flattens and the contact point moves right. Point (1) and concavity say the curve never has slope above 1, so for contact is always at the origin: point (4) in the plane. The actual threshold is above 1 and has an exact expression.
Before deriving anything, see what the algorithm built next does. With , each is a point in a triangle, and the bottleneck solution appears as a few centroids attracting points.
Three observations the rest of the lesson turns into theorems. In the initial example, nothing happens until , well above trivial limit ; this number comes from a singular-value decomposition of the joint. Splits are abrupt: the cluster count jumps and the curve has elbows, like a phase transition. And the solution at large is no longer soft: each goes with probability nearly 1 to a cluster, that of its nearest centroid in a specific sense, KL divergence.
Self-consistent equations
Everything rests on an identity rewriting lost relevance as mean distortion.
Proof
By the chain rule applied to in two ways, . The Markov chain gives , so , a conditional mutual information. By definition, , and again by the Markov chain, .
∎Using this identity, the Lagrangian becomes
The last term is constant. What remains is exactly the rate–distortion Lagrangian, with distortion measuring how wrong centroid is as a substitute for , in nats. One difference changes everything: in rate–distortion the distortion is fixed, while here depends on the encoder itself. The reproduction alphabet is not given; it is chosen alongside assignment. Thus the problem ceases to be convex and local optima appear.
The derivation uses Lagrange multipliers with one normalization constraint per , worked through in the first proof exercise. The important part is the shape: a Gibbs distribution over clusters with prior , energy and inverse temperature . Both limits follow directly:
- : the exponential is 1 and . The representation ignores .
- : mass concentrates on minimizing . The encoder is a hard partition of assigning each to its nearest centroid in KL; this is k-means on the simplex with KL as distance and weights . With at least as many clusters as distinct distributions, lost relevance can vanish, and for large finite the compression term breaks ties by merging with identical : the optimum approaches the motivational minimal sufficient statistic . With fewer clusters the optimum is the best partition that fits. This underlies hard clustering methods such as Slonim and Tishby’s agglomerative method for words and documents.
The equations are implicit: the right side depends on and , which themselves depend on . This suggests iteration.
Iterative algorithm and annealing
This has the structure of Blahut–Arimoto with one extra step (centroids). Convergence is proved likewise: viewing each step as exact minimization of a functional over a block of variables.
Proof
(1) , verified by adding and subtracting ; the second term is and vanishes at by Gibbs’ inequality. (2) For each , , the same identity with in place of . (3) For each , the part of depending on is , minimized by the indicated Gibbs distribution by the Gibbs variational principle. (4) Substitute: the first term is by (1) and the second by the lost relevance identity. An iteration applies (2) and (1) (the first two steps), then (3); none increases , and after the first two steps equals . The sequence is monotone and bounded below by .
∎The guarantee is descent, not a global optimum: is convex in each block separately but not all three jointly, like k-means. In practice use deterministic annealing (Rose 1998): start with small , where only the trivial solution exists, and raise gradually, each time starting from the previous solution with a tiny perturbation. While stable, the perturbation disappears; once unstable, it grows and the cluster splits. This follows the solution branch continuously and reveals bifurcations, as in the first interactive.
When does the first cluster split?
Proof
(1) By definition of , . (2) Perturb the trivial solution: , with (normalization) and (so does not change). With and the first condition, the linear term cancels and
Also , so . The Lagrangian falls below 0 for some iff for some centered . The supremum of this ratio is the squared norm of the conditional-expectation operator on centered functions, (the optimal in the definition is ). In the discrete case, writing in the basis makes that operator restricted to the complement of , and its norm the second singular value of (singular value decomposition). Finally, because the limit of these perturbations is a family of with ratio .
∎In the initial interactive example, and, estimating numerically, : a narrow window exists where the global optimum is already nontrivial but the trivial solution remains stable, so annealing arrives “late.” For some joints, such as doubly symmetric binary (uniform through a binary symmetric channel) or Gaussian, and the thresholds coincide. Above the first threshold, each cluster has its own, tied to correlation of the joint restricted to its values, resulting in cascading bifurcations (general analysis with symmetric bifurcation theory appears in Gedeon, Parker and Dimitrov, 2012).
Deterministic information bottleneck
Strouse and Schwab (2017) observed that is not always the right cost. If is transmitted or stored using a code, the cost is its entropy , not its mutual information with . Since , the general objective is
with for the information bottleneck and for the deterministic information bottleneck, minimizing . Repeating the derivation, the optimum satisfies , and as the encoder is hard:
The term rewards large clusters: the deterministic method produces fewer and more unequal clusters, and the algorithm is k-means with KL and a size bonus. If the representation is a code, this version makes sense.
The Gaussian case: canonical correlations
For continuous variables the problem rarely has a closed form. The exception, as usual, is the Gaussian. Chechik, Globerson, Tishby and Weiss (2005) solved the case where and are centered jointly Gaussian with covariances , , and .
The interpretation is clear. Solution directions are those of canonical correlation analysis (CCA) and activate one at a time: component enters when exceeds . The first threshold, , is from the previous theorem, since for Gaussians maximal correlation is the first canonical correlation. Directions with never enter. Information bottleneck adds to CCA how many bits to allocate to each direction, a rule resembling reverse water filling in Gaussian rate–distortion.
In one dimension everything is calculated by hand. With correlation and , covariance of a Gaussian affine transformation gives and . Eliminating ,
a concave curve leaving the origin with slope and approaching . With active components, the curve is, also in nats,
made of pieces joining continuously at the . A cell below checks this in a three-dimensional example.
Variational information bottleneck
For real data (images, text) those formulas do not work: lives in a huge space, is known only through samples, and the encoder is a network. Both informations require intractable marginals: needs and needs . Alemi, Fischer, Dillon and Murphy (2017) resolved this with two variational bounds, one per term. Write for the latent, as in VAEs.
The first is the Barber–Agakov bound seen among variational mutual information bounds, and the second the VAE’s variational rate bound; you prove them in the second proof exercise. Together they upper-bound the Lagrangian, . Divide by and remove the constant, with :
With a Gaussian encoder, the rate has the closed form of KL between Gaussians,
and cross-entropy is estimated with one sample , : the reparameterization gradient lets gradients flow through sampling. The rest is ordinary training with backpropagation and Adam.
The VAE connection is structural. A β-VAE minimizes reconstruction distortion of plus a rate; VIB minimizes prediction distortion of plus the same rate. VIB is a supervised VAE: same encoder, prior and KL, with a decoder predicting labels instead of reconstructing input. A VAE is the case where the relevant variable is itself.
The numbers tell the Lagrangian’s story. With rate is nearly free: the encoder separates means by tens of units and shrinks ; measured rate is 614 bits and accuracy 90.3 %. With clusters approach prior scale and noise becomes visible but does not mix them: 30 bits and 91.8 %. With , 5.4 bits and 89.6 %; with , 2.2 bits and 81.8 %. With the model collapses to the prior: 0.06 bits and 21 % accuracy. The last is point (4) of the curve properties: with no representation pays off.
Two subtleties. First, rate is a bound and can be very loose. If is uniform over the 2000 test images, bits, so almost all of the 614 bits measured with are the gap between aggregated latent distribution and prior. At moderate , KL forces the aggregate toward the prior and tightens the bound. Second, robustness improves, but only slightly. With pixel noise of standard deviation 0.3, the best VIB achieves 71.4 % and the deterministic model 65.8 %. Alemi et al. found greater gains against adversarial examples with 256-dimensional latents; with a 2-dimensional latent and eight epochs, the advantage is modest. It is a regularizer, not a vaccine.
Information bottleneck in deep learning
In 2015, Tishby and Zaslavsky proposed viewing a deep network as the Markov chain , where is layer ‘s activation, and evaluating each layer as a representation using the bottleneck’s two informations.
Shwartz-Ziv and Tishby (2017) trained hyperbolic-tangent networks on a synthetic 12-bit task, estimated both informations by binning each neuron into 30 intervals, and described two phases: a short fitting phase where layers gain information about and , and a long compression phase where decreases. They attributed compression to stochastic gradient noise dominating the mean gradient in the second phase, linked it to generalization and conjectured that layers converge to the information bottleneck curve. The proposal was influential and heavily criticized; the criticisms teach more than the hypothesis.
Saxe et al. (2018). Their reproduction showed three things. Compression depends on nonlinearity: it appears with saturating tanh, but not ReLU, which does not saturate above, using their added-noise estimator, and both networks generalize. It also appears with full-batch gradient descent without stochastic noise, so diffusion does not cause it. And in deep linear networks, where everything is exactly calculable, good generalization occurs without compression.
Kolchinsky, Tracey and Van Kuyk (2019). In classification, is often a deterministic function of . Then the information curve is trivial: , a line and a horizontal segment. The Lagrangian cannot traverse it (at every point ties; for the optimum is a function of with ), and optimal representations are trivial transformations of the label. They proposed changing the functional to recover curve exploration.
Goldfeld et al. (2019). The underlying issue is definition. If is continuous and the network deterministic with strictly monotone nonlinearities such as tanh or sigmoid, retains all information about and . If is uniform over a finite set of examples and is injective on them (typical with generic weights), at all layers and epochs. Both planes are trivial; binning drew activation geometry, how many fall in the same bin. Goldfeld et al. proposed networks with injected Gaussian noise, where is finite and estimable, showing that compression, when present, coincides with clustering same-class representations.
With tanh and 30 bins, the fifth layer rises to 5.55 bits at epoch 64 and falls to 1.19 bits at the end, while stabilizes at 0.89 bits: the classic picture. With 100 bins the same layer starts higher and compression changes scale; with ReLU and added noise, never falls. Exact ReLU values pin all five layers at throughout training (apart from hundredths of a bit in early epochs from a few collisions): with 4096 equiprobable inputs and an injective network, bits always. With tanh, even exact counting “compresses” deep layers, because in float32 the hyperbolic tangent of a large number is exactly and many inputs end up at the same vector: floating-point arithmetic discretizes. None of these compressions is a property of the learning problem; all belong to the network–measurement instrument pair.
Where does the debate stand? There is broad agreement on three points. A deterministic network’s information plane, estimated with binning or noise added after training, measures not network mutual information but an estimator-dependent geometric quantity. Compression as clustering of each class’s representations occurs in many networks but is not necessary for generalization. And information bottleneck remains useful as an objective (VIB and descendants) and as language for thinking about representations, its current use.
Frontier: self-supervision, generalization and usable information
Self-supervised learning. Multi-view methods (SimCLR, CPC, VICReg) have no labels: two versions , of the same datum are obtained through augmentations. The bottleneck interpretation takes as relevant for : a good representation is sufficient for () and minimal (discarding what views do not share). Contrastive losses maximize a lower bound on , the InfoNCE bound, while augmentations supply compression: what changes between views cannot be shared. Shwartz-Ziv and LeCun’s (2023) review organizes this literature and concludes with nuance: under the redundancy assumption (task information is shared between views), a minimal sufficient representation is optimal; when a task needs something augmentation destroys, compression hurts.
Generalization bounds. Kawaguchi, Deng, Ji and Huang (2023) proved generalization error bounds depending on a layer’s conditional information , input information retained beyond the label, rather than parameter count; the bound grows as the square root of that quantity divided by sample count, up to logarithmic factors, with trained on those same examples. The authors state this precisely: controlling the bottleneck is one way to control generalization, neither the only nor a necessary one. In their experiments, generalization error correlates with that information across many architectures.
Usable information. A fundamental limitation of Shannon theory for representations is that it ignores computation: by data processing no layer can have more information about than the input, yet deep layers make information easier to use. Xu, Zhao, Song, Stewart and Ermon (2020) defined -information, information extractable by a restricted predictor family (for example linear predictors). Processing can create usable information, making “what does a layer do?” nontrivial. In a sense this bridges information bottleneck and the previous lesson’s minimum description length: both measure information relative to a model class.
How to read a paper measuring information inside a network
The lesson condenses into six questions to ask any paper measuring or with activation .
- What random variable is ? The data distribution (continuous), uniform over training data (finite), or something in between? This determines whether the quantity is , , or meaningful.
- Is the network deterministic? If it is and is continuous, is infinite. Something else is measured, and the paper should say what.
- Which estimator, with which hyperparameters, and how much do conclusions change with them? Binning, neighbors and added noise have known biases (plug-in bias); a figure with one bin size is not evidence.
- Is it an estimate or a bound, and which way can it err? InfoNCE cannot exceed ; VIB rate is an upper bound that can be extremely loose.
- Is the quantity invariant where it should be? Mutual information does not change under invertible transformations. If an invertible layer “compresses,” the estimator does it.
- Does the causal claim have an intervention behind it? Compression and generalization occurring together does not imply one causes the other; Saxe et al. separated them by changing only the nonlinearity.
Implementation from scratch
The first cell implements iterative annealing on a joint of words and topics: 32 words, 4 topics; 24 words specific to one topic, 4 shared by two and 4 neutral. It plots the information curve, compares the first threshold with , detects transitions as peaks in (the specific-heat analogue), and compares with k-means on rows, using Euclidean distance without weighting by .
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
K, n = 4, 32 # temas (Y) y palabras (X)
# 6 palabras propias de cada tema, 4 compartidas por parejas de temas y 4 neutras
perfiles = []
for k in range(K):
for _ in range(6):
a = np.full(K, 0.3); a[k] = 6.0
perfiles.append(a)
for k in range(K):
a = np.full(K, 0.3); a[k] = a[(k + 1) % K] = 3.0
perfiles.append(a)
perfiles += [np.full(K, 4.0)] * 4
py_x = np.array([rng.dirichlet(a) for a in perfiles]) # p(y | x), una fila por palabra
px = rng.dirichlet(np.full(n, 2.0)) # p(x)
def info_mutua(pab):
pa, pb = pab.sum(1, keepdims=True), pab.sum(0, keepdims=True)
m = pab > 0
return float((pab[m] * np.log2(pab[m] / (pa @ pb)[m])).sum())
def kl_filas(P, Q):
"""KL(P_i || Q_j) en nats para todas las parejas de filas."""
return (P * np.log(np.where(P > 0, P, 1))).sum(1)[:, None] - P @ np.log(np.maximum(Q, 1e-300)).T
def centroides(pt_x):
pt = px @ pt_x # p(t)
py_t = (px[:, None] * pt_x).T @ py_x / np.maximum(pt, 1e-300)[:, None] # p(y | t), por Bayes
return pt, py_t
def paso_ib(pt_x, beta):
pt, py_t = centroides(pt_x)
logits = np.log(np.maximum(pt, 1e-300)) - beta * kl_filas(py_x, py_t)
logits -= logits.max(1, keepdims=True) # estabilidad numérica
nuevo = np.exp(logits)
return nuevo / nuevo.sum(1, keepdims=True)
def curva(pt_x):
pxt = px[:, None] * pt_x
return info_mutua(pxt), info_mutua(pxt.T @ py_x)
# recocido: beta creciente, cada beta parte de la solución anterior con una perturbación pequeña
M, betas = 8, np.geomspace(0.8, 40, 80)
pt_x = np.full((n, M), 1 / M) * (1 + 1e-2 * rng.standard_normal((n, M)))
pt_x /= pt_x.sum(1, keepdims=True)
traza = []
for b in betas:
pt_x = np.abs(pt_x * (1 + 1e-3 * rng.standard_normal(pt_x.shape)))
pt_x /= pt_x.sum(1, keepdims=True)
for _ in range(60):
pt_x = paso_ib(pt_x, b)
traza.append(curva(pt_x))
ix, iy = np.array(traza).T
Q = px[:, None] * py_x / np.sqrt(np.outer(px, px @ py_x))
rho2 = np.linalg.svd(Q, compute_uv=False)[1] ** 2
sus = np.gradient(ix, np.log(betas)) # dI(X;T)/dlog(beta): picos en las transiciones
picos = [i for i in range(1, len(betas) - 1) if sus[i] > max(sus[i - 1], sus[i + 1]) and sus[i] > 0.3]
print(f"I(X;Y) = {info_mutua(px[:, None] * py_x):.3f} bits, H(X) = {-(px * np.log2(px)).sum():.3f} bits")
print(f"umbral previsto 1/rho_m^2 = {1 / rho2:.3f}; primer beta con I(X;T) > 0.001: {betas[np.argmax(ix > 1e-3)]:.3f}")
print("transiciones (picos de dI(X;T)/dlog beta) en beta =", np.round(betas[picos], 2))
# k-means de Lloyd sobre las filas p(y|x): euclídeo y sin pesos p(x)
def kmeans(P, k, reps=10):
mejor, coste_min = None, np.inf
for _ in range(reps):
C = P[rng.choice(len(P), k, replace=False)]
for _ in range(50):
et = ((P[:, None] - C[None]) ** 2).sum(-1).argmin(1)
C = np.array([P[et == j].mean(0) if np.any(et == j) else C[j] for j in range(k)])
coste = ((P - C[et]) ** 2).sum()
if coste < coste_min:
mejor, coste_min = et, coste
return mejor
puntos_km = [curva(np.eye(k)[kmeans(py_x, k)]) for k in range(2, 7)]
for k, (a, b) in zip(range(2, 7), puntos_km):
print(f"k-means k = {k}: I(X;T) = {a:.3f}, I(T;Y) = {b:.3f}; curva IB en ese I(X;T): {np.interp(a, ix, iy):.3f}")
fig, ax = plt.subplots(1, 2, figsize=(10, 3.8))
ax[0].plot(ix, iy, "-", label="IB con recocido")
ax[0].plot(*np.array(puntos_km).T, "s", label="k-means sobre p(y|x)")
ax[0].axhline(info_mutua(px[:, None] * py_x), ls="--", c="gray", label="I(X;Y)")
ax[0].set_xlabel("I(X;T) (bits)"); ax[0].set_ylabel("I(T;Y) (bits)"); ax[0].legend()
ax[1].semilogx(betas, ix, label="I(X;T)")
ax[1].semilogx(betas, iy, label="I(T;Y)")
ax[1].axvline(1 / rho2, ls="--", c="gray", label="1/ρ²")
for i in picos:
ax[1].axvline(betas[i], ls=":", c="k", lw=0.8)
ax[1].set_xlabel("β"); ax[1].legend(); plt.tight_layout(); plt.show()The predicted first threshold is and information begins growing at , slightly later because of critical slowing and grid spacing. Transitions appear as susceptibility peaks at , , , and : the first exits the trivial solution and the rest separate finer subgroups, with diminishing relevance gains as expected for a concave curve. K-means remains below the curve: with two clusters, 0.41 relevance bits versus 0.48 on the curve for equal compression; with three, 0.71 versus 0.78. The difference has two sources: distance (KL penalizes grouping a word almost certain of its topic with an ambiguous one much more) and weights , ignored by k-means.
The second cell checks the Gaussian solution: construct the theorem’s encoder for several , compute both informations using determinants and compare with the curve formula; then perturb the encoder randomly and check that the Lagrangian does not fall.
import numpy as np
rng = np.random.default_rng(3)
dx, dy = 3, 2
B = rng.standard_normal((dx + dy, dx + dy))
S = B @ B.T + 0.5 * np.eye(dx + dy) # covarianza conjunta de (X, Y)
Sx, Sy, Sxy = S[:dx, :dx], S[dx:, dx:], S[:dx, dx:]
Sx_y = Sx - Sxy @ np.linalg.solve(Sy, Sxy.T) # covarianza de X dado Y
# autovectores por la izquierda de Sx_y Sx^-1 (autovectores de su traspuesta)
lam, V = np.linalg.eig((Sx_y @ np.linalg.inv(Sx)).T)
orden = np.argsort(lam.real)
lam, V = lam.real[orden], V.real[:, orden]
# correlaciones canónicas, por la SVD de Sx^-1/2 Sxy Sy^-1/2 (con Cholesky)
Lx, Ly = np.linalg.cholesky(Sx), np.linalg.cholesky(Sy)
rho = np.linalg.svd(np.linalg.solve(Lx, Sxy) @ np.linalg.inv(Ly).T, compute_uv=False)
print("lambda_i :", np.round(lam, 4))
print("1 - rho_i^2 :", np.round(np.sort(np.r_[1 - rho**2, np.ones(dx - dy)]), 4))
print("beta crítico_i :", np.round(1 / (1 - lam[:dy]), 3), "(el tercero es infinito: esa dirección no dice nada de Y)")
def informacion(A):
"""I(X;T) e I(T;Y) en nats para T = A X + ruido N(0, I)."""
St, St_y = A @ Sx @ A.T + np.eye(len(A)), A @ Sx_y @ A.T + np.eye(len(A))
return 0.5 * np.log(np.linalg.det(St)), 0.5 * np.log(np.linalg.det(St) / np.linalg.det(St_y))
def codificador_optimo(beta):
filas = []
for i in range(dx):
v = V[:, i]
a2 = (beta * (1 - lam[i]) - 1) / (lam[i] * (v @ Sx @ v))
filas.append(np.sqrt(max(a2, 0.0)) * v)
return np.array(filas)
for beta in (1.5, 6, 100):
A = codificador_optimo(beta)
Ix, Iy = informacion(A)
n_act = int(np.sum(beta > 1 / (1 - lam)))
l = lam[:n_act]
formula = Ix - n_act / 2 * np.log(np.prod(1 - l) ** (1 / n_act) + np.exp(2 * Ix / n_act) * np.prod(l) ** (1 / n_act))
L = Ix - beta * Iy
L_pert = min(np.subtract(*np.array(informacion(A + 0.05 * rng.standard_normal(A.shape))) * [1, beta]) for _ in range(200))
print(f"beta = {beta:5}: componentes activas {n_act}, I(X;T) = {Ix:.4f}, I(T;Y) = {Iy:.4f}, "
f"fórmula de la curva {formula:.4f}; L = {L:.4f} <= mín. de 200 perturbaciones {L_pert:.4f}")The agree with to four digits, thresholds are and (the third direction, uncorrelated with , never enters), the curve formula reproduces , and none of 200 perturbations improves the Lagrangian. With two components are already active.
VIB in PyTorch
The local cell implements Alemi et al.’s VIB on a laptop scale: a 784-256-256 MLP encoder giving mean and standard deviation of a 16-dimensional latent, linear softmax decoder, prior , three values, and the same deterministic MLP as reference. It measures rate, the bound, and accuracy under input noise, and verifies closed-form KL with torch.distributions. Translating formulas to tensors is direct (from equations to PyTorch). It runs on CPU in seconds.
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # experimento pequeño: CPU
import math, time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal, kl_divergence
from torchvision import datasets
torch.manual_seed(0)
torch.set_num_threads(2)
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, ytr = tr.data[:20000].reshape(-1, 784).float() / 255, tr.targets[:20000]
Xte, yte = te.data[:2000].reshape(-1, 784).float() / 255, te.targets[:2000]
K, LN2 = 16, math.log(2)
class VIB(nn.Module):
"""Codificador gaussiano p(z|x) = N(mu(x), diag sigma(x)^2), decodificador softmax q(y|z), prior N(0, I)."""
def __init__(self, estocastico=True):
super().__init__()
self.enc = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 2 * K))
self.dec = nn.Linear(K, 10)
self.estocastico = estocastico
def codificar(self, x):
h = self.enc(x)
return h[:, :K], F.softplus(h[:, K:] - 5.0) # sigma empieza pequeña
def forward(self, x):
mu, sigma = self.codificar(x)
z = mu + sigma * torch.randn_like(mu) if self.estocastico else mu # reparametrización
return self.dec(z), mu, sigma
def kl_normal_estandar(mu, sigma):
"""KL(N(mu, diag sigma^2) || N(0, I)) por ejemplo, en nats (forma cerrada)."""
return 0.5 * (mu**2 + sigma**2 - 1 - 2 * torch.log(sigma)).sum(1)
def entrenar(gamma, estocastico=True, epocas=5):
torch.manual_seed(0)
m = VIB(estocastico)
opt = torch.optim.Adam(m.parameters(), lr=1e-3)
for _ in range(epocas):
perm = torch.randperm(len(Xtr))
for i in range(0, len(Xtr), 128):
idx = perm[i:i + 128]
logits, mu, sigma = m(Xtr[idx])
perdida = F.cross_entropy(logits, ytr[idx])
if estocastico:
perdida = perdida + gamma * kl_normal_estandar(mu, sigma).mean()
opt.zero_grad(); perdida.backward(); opt.step()
return m
@torch.no_grad()
def evaluar(m):
mu, sigma = m.codificar(Xte)
tasa = kl_normal_estandar(mu, sigma).mean().item() / LN2 if m.estocastico else float("inf")
z = mu + sigma * torch.randn_like(mu) if m.estocastico else mu
ce = F.cross_entropy(m.dec(z), yte).item() / LN2
exact = []
g = torch.Generator().manual_seed(1)
for s in (0.0, 0.2, 0.4):
mu_r, _ = m.codificar(Xte + s * torch.randn(Xte.shape, generator=g))
exact.append((m.dec(mu_r).argmax(1) == yte).float().mean().item())
return tasa, ce, exact
# comprobación de la forma cerrada de la KL con torch.distributions
mu, sigma = torch.randn(4, K), torch.rand(4, K) + 0.1
ref = kl_divergence(Normal(mu, sigma), Normal(0.0, 1.0)).sum(1)
print("KL cerrada frente a torch.distributions:", torch.allclose(kl_normal_estandar(mu, sigma), ref, atol=1e-5))
H_Y = -sum(p * math.log2(p) for p in (torch.bincount(yte, minlength=10) / len(yte)).tolist())
print(f"H(Y) = {H_Y:.3f} bits\n")
print("modelo R (bits) H(Y)-CE exactitud con ruido σ = 0 / 0.2 / 0.4")
t0 = time.time()
for gamma in (1e-3, 1e-2, 1e-1):
R, ce, ex = evaluar(entrenar(gamma))
print(f"VIB γ = {gamma:<6g} {R:8.1f} {H_Y - ce:7.3f} " + " / ".join(f"{100 * a:.1f} %" for a in ex))
R, ce, ex = evaluar(entrenar(0.0, estocastico=False))
print(f"determinista ∞ {H_Y - ce:7.3f} " + " / ".join(f"{100 * a:.1f} %" for a in ex))
print(f"\n({time.time() - t0:.0f} s en CPU)")npm run lab and open the connection link.At 16 dimensions the latent is no longer the interactive’s extremely narrow bottleneck, so the pattern changes scale but not shape. With VIB uses 21.5 rate bits, reaches 96.4 % accuracy, and 81.0 % with pixel noise of standard deviation 0.4; the same-size deterministic MLP reaches 94.6 % and 76.0 %. With rate rises to 64 bits without gains, and with falls to 7.9 bits and accuracy to 93.8 %. With five epochs on 20 000 images, differences of one or two points depend on the seed: treat them as a trend, not a measurement. Alemi et al.’s experiment uses a 256-dimensional latent, all 60 000 images and long training; its main result is the whole accuracy-versus- curve with an interior maximum.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What is , with ?
Step 1 of 4. How do you start the first bound?
paso_ib(px, py_x, pt_x, beta), taking marginal px (shape (n,)), matrix py_x with rows (shape (n, m), all entries positive), current encoder pt_x (shape (n, M)), and , and returning the next encoder: compute and from pt_x, then in nats. Ensure numerical stability (for large exponentials overflow unless the maximum is subtracted) and handle empty clusters.import numpy as np
def paso_ib(px, py_x, pt_x, beta):
"""Una iteración de las ecuaciones autoconsistentes. Devuelve p(t|x) con forma (n, M)."""
px, py_x, pt_x = np.asarray(px, float), np.asarray(py_x, float), np.asarray(pt_x, float)
# tu código: p(t), p(y|t), la matriz de KL(p(y|x) || p(y|t)) y la Gibbs normalizada por filas
return pt_xSummary
- Information curve is concave, lies below , and its supporting line has slope . With the solution is trivial; the trivial solution loses stability at , where is maximal correlation.
- Optima satisfy self-consistent equations: a Gibbs distribution with KL energy over centroids . Iteration decreases the Lagrangian each step; annealing in follows solution branches and reveals phase transitions where clusters split.
- In the Gaussian case the solution is noisy CCA: canonical direction activates at .
- VIB replaces both informations by bounds, a lower bound on using a decoder and upper bound on using a prior, trained as a supervised VAE: cross-entropy plus times KL, with reparameterization.
- A deterministic network’s information plane measures the estimator rather than the network: is infinite or constant. Compression depends on nonlinearity and estimator, and is unnecessary for generalization.
- Frontier work uses the bottleneck as objective and language: minimal sufficient representations in self-supervision, generalization bounds with and information usable by restricted models.