Module contents
Lesson 12 of 20Advanced 110 min

PAC-Bayes, compression and information-theoretic bounds

Derive PAC-Bayes bounds through change of measure and KL divergence, obtain the Gibbs posterior, study nonvacuous network bounds, and connect compression and mutual information.

After this lesson you can

  • Prove a PAC-Bayes bound from the Donsker-Varadhan variational formula and a Chernoff bound.
  • State the Seeger-Maurer kl bound and numerically invert binary kl divergence.
  • Derive the Gibbs posterior as the minimizer of Catoni’s linear bound and relate it to Bayesian inference.
  • Optimize a nonvacuous PAC-Bayes bound for a small network with a diagonal Gaussian posterior.
  • Explain the relationship between flatness of minima, compression and PAC-Bayes, including the reparameterization objection.
  • State the Xu-Raginsky mutual-information bound and its conditional variant.

Before you start

A prior for a randomized predictor

Occam assigns weight to discrete hypotheses. PAC-Bayes permits a prior PP over continuous parameters and a posterior QQ chosen after observing the sample. The Gibbs predictor draws h∼Qh\sim Q and predicts with that hypothesis; its risks R(Q)=EQR(h)R(Q)=\mathbb E_Q R(h) and R^S(Q)=EQR^S(h)\widehat R_S(Q)=\mathbb E_Q\widehat R_S(h) average over the draw. The guarantee concerns that randomized predictor, not automatically the model with mean parameters.

For i.i.d. losses in [0,1][0,1], a prior independent of SS, n≥8n\ge8 and δ∈(0,1)\delta\in(0,1), a PAC-Bayes kl bound states that with probability at least 1−δ1-\delta, simultaneously for every Q≪PQ\ll P,

kl⁡(R^S(Q)∥R(Q))≤KL⁡(Q∥P)+ln⁡(2n/δ)n.\operatorname{kl}(\widehat R_S(Q)\|R(Q))\le \frac{\operatorname{KL}(Q\|P)+\ln(2\sqrt n/\delta)}n.

Here kl⁡\operatorname{kl} is Bernoulli divergence and KL⁡\operatorname{KL} divergence between hypothesis distributions. Simultaneity allows QQ to depend on SS. A prior trained on the same data is not independent; it can be trained on a separate split and certified on the remainder. If choosing a prior from a fixed grid after seeing certification data, allocate δ\delta among candidates.

Change of measure and proof

For Q≪PQ\ll P and measurable ff with integrable exponential, the Donsker-Varadhan inequality is

EQf≤KL⁡(Q∥P)+ln⁡EPef.\mathbb E_Q f\le\operatorname{KL}(Q\|P)+\ln\mathbb E_Pe^f.

Indeed, define dPf=efdP/EPefdP_f=e^f dP/\mathbb E_Pe^f. The identity KL⁡(Q∥Pf)=KL⁡(Q∥P)−EQf+ln⁡EPef≥0\operatorname{KL}(Q\|P_f)=\operatorname{KL}(Q\|P)-\mathbb E_Qf+\ln\mathbb E_Pe^f\ge0 gives the result. Equality holds at Q=PfQ=P_f when it exists.

For fixed hh, an exponential inequality of Maurer controls ESexp⁡(nkl⁡(R^S(h)∥R(h)))≤2n\mathbb E_S\exp(n\operatorname{kl}(\widehat R_S(h)\|R(h)))\le2\sqrt n for n≥8n\ge8. Integrate over the independent prior and apply Markov: with failure at most δ\delta, the exponential integral is at most 2n/δ2\sqrt n/\delta. Apply change of measure with f(h)=nkl⁡(R^S(h)∥R(h))f(h)=n\operatorname{kl}(\widehat R_S(h)\|R(h)) and joint convexity of kl to bring the QQ expectation inside. This gives the preceding inequality for all posteriors on the same event. Pinsker gives the square-root form R(Q)≤R^S(Q)+c/2R(Q)\le\widehat R_S(Q)+\sqrt{c/2}, with cc equal to the right side; other McAllester versions use different constants.

Inversion finds the largest p≥qp\ge q satisfying kl⁡(q∥p)≤c\operatorname{kl}(q\|p)\le c. If q=0q=0, obtain p≤1−e−cp\le1-e^{-c}. For q=1q=1 the upper bound is 1. Bisection preserves the interval and avoids nonexistent roots.

InteractiveInvert binary kl
  • kl(q||p)
  • radius
0.02
100
n
Inverted kl bound0.0479
Square-root bound0.0936
kl radius0.0108
Change q, KL and n; the intersection with the radius gives the kl bound and Pinsker’s square root provides a comparison.

Gibbs and temperature

For a finite class and β>0\beta>0, minimizing βEQR^+KL⁡(Q∥P)\beta\mathbb E_Q\widehat R+\operatorname{KL}(Q\|P) gives the Gibbs posterior

Qβ(h)=P(h)e−βR^(h)∑gP(g)e−βR^(g).Q_\beta(h)=\frac{P(h)e^{-\beta\widehat R(h)}}{\sum_gP(g)e^{-\beta\widehat R(g)}}.

It follows directly from equality in change of measure with f=−βR^f=-\beta\widehat R. As β\beta grows it concentrates on empirical minimizers with positive prior mass; at β=0\beta=0 it equals PP. A linear bound for fixed β\beta is R(Q)≤R^(Q)+(KL⁡+ln⁡(1/δ))/β+β/(8n)R(Q)\le\widehat R(Q)+(\operatorname{KL}+\ln(1/\delta))/\beta+\beta/(8n), by Hoeffding and change of measure. Selecting β\beta with data requires paying for that selection, for example with a grid and union bound.

A Catoni version for fixed c>0c>0 gives

R(Q)≤1−exp⁡[−cR^(Q)−(KL⁡(Q∥P)+ln⁡(1/δ))/n]1−e−c.R(Q)\le\frac{1-\exp[-c\widehat R(Q)-(\operatorname{KL}(Q\|P)+\ln(1/\delta))/n]}{1-e^{-c}}.

Its numerator increases in cR^+KL⁡/nc\widehat R+\operatorname{KL}/n, so the optimal posterior is Gibbs with β=nc\beta=nc. With log-loss the Gibbs posterior relates to the Bayesian posterior and the variational objective to the ELBO; because log-loss is unbounded, a bound needs additional assumptions such as those studied by Germain and colleagues.

InteractiveFrom prior to ERM with a temperature
  • linear bound
  • empirical risk
h10.092
h20.284
h30.310
h40.203
h50.111
20
Empirical risk of randomized vote0.113
KL0.270
Linear bound0.279
Grid minimum, excluding selection cost190
The five empirical errors and prior are an explicit model. The curve uses a fixed temperature; choosing its minimum requires another selection cost.

Width, compression and parameterization

For P=N(μP,diag⁡σP2)P=\mathcal N(\mu_P,\operatorname{diag}\sigma_P^2) and Q=N(μQ,diag⁡σQ2)Q=\mathcal N(\mu_Q,\operatorname{diag}\sigma_Q^2),

KL⁡(Q∥P)=∑j[ln⁡σPjσQj+σQj2+(μQj−μPj)22σPj2−12].\operatorname{KL}(Q\|P)=\sum_j\left[\ln\frac{\sigma_{Pj}}{\sigma_{Qj}}+\frac{\sigma_{Qj}^2+(\mu_{Qj}-\mu_{Pj})^2}{2\sigma_{Pj}^2}-\frac12\right].

If a region tolerates perturbations, a wider posterior can reduce KL relative to a wide prior without greatly increasing expected loss. The figure numerically integrates a synthetic landscape: it does not certify a real network or prove every flat solution generalizes.

InteractiveWide posteriors in flat minima
  • loss landscape
  • posterior mean
  • prior
  • posterior
−1.0
0.30
Gaussian KL1.352
Approximate expected loss0.175
Illustrative bound0.228
Move mean and deviation; expected loss uses approximate quadrature and the bound is illustrative.

Flatness and generalization depend on parameterization. In a ReLU network, multiplying one layer by a>0a>0 and the next by 1/a1/a preserves the function but can change curvature and width metrics. Dinh et al. show naive sharpness alone is not an invariant explanation. Prior and perturbations must be specified in the parameterization used.

In consistent compression, a fixed reconstructor uses k<nk<n selected examples and a bb-bit message to reconstruct a predictor correct on the remaining n−kn-k. For k,bk,b fixed in advance, a union over (nk)2b\binom nk2^b descriptions gives with confidence 1−δ1-\delta

R(h)≤1−(δ(nk)2b)1/(n−k).R(h)\le1-\left(\frac{\delta}{\binom nk2^b}\right)^{1/(n-k)}.

Choosing kk or the scheme after seeing data requires paying for that choice. Compression bounds do not mean any small file guarantees generalization: a specific scheme and proof are required. Lotfi et al. construct nonvacuous LLM bounds using compression and special treatment of unbounded log-loss; their result does not follow from the 0-1 formula above.

A small network and a nonvacuous bound

InteractiveSearch for a posterior on spirals
  • kl bound
  • upper empirical error
  • MC test error
Candidate deviation 1 of 7
Standard deviation σ0.005
KL82.40
Upper empirical error0.242
Monte Carlo test error0.115
Bound for this candidate0.447
Best on grid0.300
A tanh MLP is trained on data separate from certification. Explore seven deviations and observe KL, error and bound calculated in the browser.

The simulation trains an eight-unit MLP on 300 synthetic points to fix the prior mean; it uses another 1000 for certification and 1000 for test. It explores seven fixed diagonal Gaussian deviations, calculates KL and estimates each error with 100 networks. Hoeffding and a union over seven candidates correct Monte Carlo error; the PAC-Bayes bound pays its own confidence. A deterministic pseudorandom generator is used: the curve illustrates calculation under the i.i.d. model and is not a guarantee for another distribution. The best candidate minimizes the grid, not necessarily along a monotone descent.

The local lab below runs an MLP on MNIST 0/1, with a prior trained on 3000 separate examples and a diagonal posterior optimized on the certification split. The goal is to obtain nonvacuous bounds, i.e. below the trivial bound 1. The grid of two prior deviations is fixed in advance and selection pays a union bound. For each posterior, 256 independent complete networks estimate empirical Gibbs error; Hoeffding adds their uncertainty with another confidence allocation. Test uses 32 additional draws. Training minimizes a smooth surrogate, but the final bound evaluates actual 0-1 loss. The guarantee requires the i.i.d. model and concerns the stochastic predictor.

[ ]MNIST 0/1 MLP and PAC-Bayes certificateLocal GPU
"""MNIST 0/1: prior independiente, posterior diagonal y certificado Monte Carlo.

Ejecuta con torch y torchvision instalados. ORYON_MNIST_ROOT permite reutilizar
una descarga; ORYON_PAC_RESULT guarda resultados JSON si se indica.
"""
import json, math, os, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.func import functional_call
from torchvision.datasets import MNIST

torch.set_num_threads(1)
torch.manual_seed(1312); np.random.seed(1312)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
root=os.environ.get('ORYON_MNIST_ROOT','./data')
train=MNIST(root,train=True,download=True); test=MNIST(root,train=False,download=True)
def binary(ds):
    idx=(ds.targets==0)|(ds.targets==1)
    x=ds.data[idx].float().reshape(-1,784)/255
    y=ds.targets[idx].float()*2-1
    return x.to(device),y.to(device)
X,Y=binary(train); Xt,Yt=binary(test)
perm=torch.randperm(len(Y),device=device); n_prior=3000
Xp,Yp=X[perm[:n_prior]],Y[perm[:n_prior]]; Xc,Yc=X[perm[n_prior:]],Y[perm[n_prior:]]; n=len(Yc)
model=nn.Sequential(nn.Linear(784,8),nn.ReLU(),nn.Linear(8,1)).to(device)
opt=torch.optim.Adam(model.parameters(),lr=.005)
for epoch in range(5):
    order=torch.randperm(len(Yp),device=device)
    for ids in order.split(256):
        opt.zero_grad(); logits=model(Xp[ids]).squeeze(-1)
        loss=torch.nn.functional.softplus(-Yp[ids]*logits).mean(); loss.backward(); opt.step()
prior={name:p.detach().clone() for name,p in model.named_parameters()}
grid=[.005,.02]; delta_pb=.025; delta_mc=.025; draws=256
def kl_div(mu,log_sigma,sigma_prior):
    return sum((math.log(sigma_prior)-log_sigma[k]+(torch.exp(2*log_sigma[k])+(mu[k]-prior[k])**2)/(2*sigma_prior**2)-.5).sum() for k in mu)
def binary_kl(q,p):
    if q<=0:return -math.log1p(-p) if p<1 else math.inf
    if q>=1:return -math.log(p) if p>0 else math.inf
    if p<=0 or p>=1:return math.inf
    return q*math.log(q/p)+(1-q)*math.log((1-q)/(1-p))
def upper(q,c):
    if q>=1:return 1.
    lo,hi=q,1.
    for _ in range(70):
        mid=(lo+hi)/2
        if binary_kl(q,mid)<=c:lo=mid
        else:hi=mid
    return lo
def rates(mu,logs,x,y,count):
    values=[]
    with torch.no_grad():
        for _ in range(count):
            params={k:mu[k]+torch.exp(logs[k])*torch.randn_like(mu[k]) for k in mu}
            err=[]
            for ids in torch.arange(len(y),device=device).split(2048):
                logits=functional_call(model,params,(x[ids],)).squeeze(-1)
                err.append((y[ids]*logits<=0).float())
            values.append(float(torch.cat(err).mean()))
    return np.array(values)
results=[]; start=time.time()
for sigma_prior in grid:
    mu={k:nn.Parameter(v.clone()) for k,v in prior.items()}
    logs={k:nn.Parameter(torch.full_like(v,math.log(sigma_prior))) for k,v in prior.items()}
    optimizer=torch.optim.Adam([{'params':list(mu.values()),'lr':.00002},{'params':list(logs.values()),'lr':.01}])
    for epoch in range(2):
        order=torch.randperm(n,device=device)
        for ids in order.split(256):
            optimizer.zero_grad(); params={k:mu[k]+torch.exp(logs[k])*torch.randn_like(mu[k]) for k in mu}
            margin=Yc[ids]*functional_call(model,params,(Xc[ids],)).squeeze(-1)
            surrogate=torch.sigmoid(-4*margin).mean()
            cost=kl_div(mu,logs,sigma_prior)
            objective=surrogate+torch.sqrt((cost+math.log(2*math.sqrt(n)*len(grid)/delta_pb))/(2*n))
            objective.backward();optimizer.step()
    cost=float(kl_div(mu,logs,sigma_prior).detach()); empirical=rates(mu,logs,Xc,Yc,draws)
    q=float(empirical.mean()); q_upper=min(1.,q+math.sqrt(math.log(len(grid)/delta_mc)/(2*draws)))
    radius=(cost+math.log(2*math.sqrt(n)*len(grid)/delta_pb))/n
    bound=upper(q_upper,radius); test_risk=float(rates(mu,logs,Xt,Yt,32).mean())
    result={'prior_sigma':sigma_prior,'kl':cost,'q_mc':q,'q_upper':q_upper,'bound':bound,'test_mc':test_risk,'draws_cert':draws,'draws_test':32}
    results.append(result);print('prior',sigma_prior,'KL',round(cost,2),'q_MC',round(q,4),'q_sup',round(q_upper,4),'cota',round(bound,4),'test_MC',round(test_risk,4),flush=True)
best=min(results,key=lambda x:x['bound']);out={'seed':1312,'device':str(device),'n_prior':n_prior,'n_cert':n,'n_test':len(Yt),'parameters':sum(v.numel() for v in prior.values()),'prior_epochs':5,'posterior_epochs':2,'delta_pb':delta_pb,'delta_mc':delta_mc,'prior_grid':grid,'results':results,'best':best,'seconds':time.time()-start}
print('mejor cota',round(best['bound'],4),'con',n,'ejemplos de certificación; dispositivo',device,flush=True)
if os.environ.get('ORYON_PAC_RESULT'):
    Path(os.environ['ORYON_PAC_RESULT']).write_text(json.dumps(out,indent=2),encoding='utf-8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a run with RTX 3060, 3000 prior examples, 9665 for certification and 2115 for test, the best grid prior had σP=.02\sigma_P=.02, KL 0.00880.0088, Monte Carlo empirical error 0.002550.00255, Monte Carlo upper limit 0.095060.09506 and kl bound 0.108730.10873; Monte Carlo test error was 0.000780.00078. These are measurements from that run, not guaranteed values for a new seed. Monte Carlo uncertainty explains much of the gap between estimated error and the bound. Dziugaite and Roy obtained nonvacuous bounds for much larger networks through PAC-Bayes optimization; this small experiment does not reproduce their figures.

[ ]Finite class and Gibbs posteriorBrowser
import numpy as np
rng=np.random.default_rng(1312); n=400; x=rng.uniform(-1,1,n); y=np.where(x+rng.normal(scale=.25,size=n)>0,1,-1)
xt=rng.uniform(-1,1,3000); yt=np.where(xt+rng.normal(scale=.25,size=len(xt))>0,1,-1)
thresholds=np.linspace(-1,1,101); H=np.where(x[:,None]>=thresholds,1,-1); Ht=np.where(xt[:,None]>=thresholds,1,-1)
emp=(H!=y[:,None]).mean(axis=0); test=(Ht!=yt[:,None]).mean(axis=0); prior=np.ones(len(emp))/len(emp)
c=.1; logits=-n*c*emp; weights=prior*np.exp(logits-logits.max()); Q=weights/weights.sum()
KL=np.sum(Q*np.log(Q/prior)); q=Q@emp; testq=Q@test; delta=.05
def kl(q,p):
    if q==0:return -np.log1p(-p) if p<1 else np.inf
    if q==1:return -np.log(p) if p>0 else np.inf
    if p<=0 or p>=1:return np.inf
    return q*np.log(q/p)+(1-q)*np.log((1-q)/(1-p))
def kl_inverse_upper(q,radius):
    if q>=1:return 1.
    lo,hi=q,1.
    for _ in range(70):
        mid=(lo+hi)/2
        if kl(q,mid)<=radius:lo=mid
        else:hi=mid
    return lo
radius=(KL+np.log(2*np.sqrt(n)/delta))/n
seeger=kl_inverse_upper(q,radius); root=min(1,q+np.sqrt(radius/2))
catoni=(1-np.exp(-c*q-(KL+np.log(1/delta))/n))/(1-np.exp(-c))
print('q:',round(q,4),'test Gibbs:',round(testq,4),'KL:',round(KL,4))
print('kl:',round(seeger,4),'raíz:',round(root,4),'Catoni:',round(catoni,4))

The class of 101 thresholds and the prior are fixed before the sample. Mean test error averages exactly the 101 classifiers in this finite class, but remains an estimate on a test sample. Temperature c=.1c=.1 is fixed before observing data; trying many temperatures requires allocating confidence.

Mutual information

For a randomized algorithm with output W=A(S)W=A(S), if each hypothesis has σ\sigma-sub-Gaussian loss under the distribution, Xu and Raginsky give the mutual-information bound

∣E[R(W)−R^S(W)]∣≤2σ2I(W;S)n.|\mathbb E[R(W)-\widehat R_S(W)]|\le\sqrt{\frac{2\sigma^2 I(W;S)}n}.

This bounds the expected gap, not high-probability risk or low risk. For losses in [0,1][0,1] one may take σ=1/2\sigma=1/2. If WW is a continuous deterministic function of SS, I(W;S)I(W;S) can be infinite and the bound vacuous. Conditional mutual information uses a supersample of independent pairs S~\widetilde S and selection bits UU; for bounded loss, one form is ∣E gen∣≤2I(W;U∣S~)/n|\mathbb E\,\mathrm{gen}|\le\sqrt{2I(W;U\mid\widetilde S)/n}. Conditioning on the supersample measures information about which member of each pair was used, and can be finite where I(W;S)I(W;S) is not.

Exercises

Proof
Prove: Prove Donsker-Varadhan.
0
Define P_f with density proportional to exp(f) relative to P.

Step 1 of 2. What identity results for KL(Q||P_f)?

Proof
Prove: Derive the PAC-Bayes kl bound.
0
Use Maurer’s exponential moment, Markov and Donsker-Varadhan.

Step 1 of 2. Why does Markov apply after integrating over P?

Numeric
For q=0, KL=5000, n=60000 and δ=0.05, calculate 1−exp(−(KL+ln(2√n/δ))/n).
Quiz
Which symmetry lets Dinh et al. change sharpness without changing a ReLU network’s function?
CodeUpper kl inversion
Implement kl_inverse_upper(q, c), for 0≤q≤1 and c≥0, returning the largest p∈[q,1] with kl(q||p)≤c by bisection. Handle endpoints q=0 and q=1.
def kl_inverse_upper(q, c):
  pass
Shift+Enter to run

Summary

Key idea
PAC-Bayes controls a randomized predictor through KL relative to an independent prior. kl inversion, prior selection and Monte Carlo uncertainty must be included in the certificate; flatness depends on parameterization and mutual information controls an expected gap.