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
- 13Occam's razor boundTest set boundStructural risk minimizationUniform and on-average algorithmic stability
- 07Kullback-Leibler divergence (relative entropy)Mutual information
- 04Chernoff boundMoment generating function
- 05Prior, likelihood and posterior
- 15Multilayer perceptron
- 00Canonical training and evaluation loop
- 06Stochastic gradient descentSharpness and flat minimaHessian spectrum of neural networks
A prior for a randomized predictor
Occam assigns weight to discrete hypotheses. PAC-Bayes permits a prior over continuous parameters and a posterior chosen after observing the sample. The Gibbs predictor draws and predicts with that hypothesis; its risks and average over the draw. The guarantee concerns that randomized predictor, not automatically the model with mean parameters.
For i.i.d. losses in , a prior independent of , and , a PAC-Bayes kl bound states that with probability at least , simultaneously for every ,
Here is Bernoulli divergence and divergence between hypothesis distributions. Simultaneity allows to depend on . 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 among candidates.
Change of measure and proof
For and measurable with integrable exponential, the Donsker-Varadhan inequality is
Indeed, define . The identity gives the result. Equality holds at when it exists.
For fixed , an exponential inequality of Maurer controls for . Integrate over the independent prior and apply Markov: with failure at most , the exponential integral is at most . Apply change of measure with and joint convexity of kl to bring the expectation inside. This gives the preceding inequality for all posteriors on the same event. Pinsker gives the square-root form , with equal to the right side; other McAllester versions use different constants.
Inversion finds the largest satisfying . If , obtain . For the upper bound is 1. Bisection preserves the interval and avoids nonexistent roots.
Gibbs and temperature
For a finite class and , minimizing gives the Gibbs posterior
It follows directly from equality in change of measure with . As grows it concentrates on empirical minimizers with positive prior mass; at it equals . A linear bound for fixed is , by Hoeffding and change of measure. Selecting with data requires paying for that selection, for example with a grid and union bound.
A Catoni version for fixed gives
Its numerator increases in , so the optimal posterior is Gibbs with . 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.
Width, compression and parameterization
For and ,
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.
Flatness and generalization depend on parameterization. In a ReLU network, multiplying one layer by and the next by 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 selected examples and a -bit message to reconstruct a predictor correct on the remaining . For fixed in advance, a union over descriptions gives with confidence
Choosing 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
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: 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')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 , KL , Monte Carlo empirical error , Monte Carlo upper limit and kl bound ; Monte Carlo test error was . 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.
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 is fixed before observing data; trying many temperatures requires allocating confidence.
Mutual information
For a randomized algorithm with output , if each hypothesis has -sub-Gaussian loss under the distribution, Xu and Raginsky give the mutual-information bound
This bounds the expected gap, not high-probability risk or low risk. For losses in one may take . If is a continuous deterministic function of , can be infinite and the bound vacuous. Conditional mutual information uses a supersample of independent pairs and selection bits ; for bounded loss, one form is . Conditioning on the supersample measures information about which member of each pair was used, and can be finite where is not.
Exercises
Step 1 of 2. What identity results for KL(Q||P_f)?
Step 1 of 2. Why does Markov apply after integrating over P?
def kl_inverse_upper(q, c):
pass