Certified robustness: verification, bounds and randomized smoothing
Study provable robustness guarantees: exact verification and its complexity, Lipschitz-margin certificates, interval propagation, CROWN-style linear relaxations and randomized smoothing with Monte Carlo estimation and its limits.
After this lesson you can
- Distinguish sound from complete certificates and empirical from certified robustness.
- Derive a certified radius from the margin and Lipschitz constant and calculate it using spectral norms.
- Implement IBP and a linear relaxation with backward substitution for an MLP.
- Prove the randomized-smoothing certified radius using the Neyman-Pearson lemma.
- Implement Monte Carlo certification with Clopper-Pearson and plot certified accuracy against radius.
Before you start
From searching for attacks to proving properties
An attack that finds no adversarial example offers only empirical evidence. A valid certificate proves that no perturbation within a declared set changes the prediction. Certified robustness depends on the input, norm, radius and exact classifier considered. A conservative bound may certify nothing even when the model is robust: absence of a certificate does not imply an attack exists.
A verifier is sound if every property it declares proved is true under its assumptions. It is complete if, for the assumed problem and resources, it decides both the property and its negation; completeness must not be confused with speed. An attack with a valid example refutes robustness at that point, but failure to find one does not prove it. A bounding method can be sound and incomplete; a relaxation that is too loose returns “inconclusive”.
ReLU networks can be represented by linear constraints and disjunctions over which neurons are active. An MILP or SMT solver explores these combinations and can produce a proof or counterexample. Reluplex studies verification using a specialized procedure; complexity grows quickly and NP-complete decision formulations exist. This does not mean every real instance is hard or that a time-limited run is complete: if computation is interrupted, return “unknown”.
The threat must be written down before verification. In an box of radius ε each coordinate may vary by up to ε; an ball bounds total length. If pixels must remain in , intersecting with that range reduces the set, while certifying the larger box remains conservative. Bounds calculated in ordinary arithmetic are mathematical proofs for the ideal algorithm, but an industrial verifier must also consider floating-point errors.
Margin and Lipschitz constants
Let be the logit vector and its winning class. Its margin is . If is -Lipschitz from to , then for any competitor
Apply Cauchy-Schwarz to vector , whose norm is . Thus if , no competitor reaches for . At the boundary there may be a tie; the tie-breaking rule determines what happens there. The vector’s Lipschitz bound can be obtained by multiplying spectral norms of matrices in an affine and ReLU network, since ReLU is 1-Lipschitz. The product can be much larger than the true constant and yield a small radius. A margin-specific bound can be tighter than one derived from the full vector.
For example, if the margin is 0.6 and is known, the guaranteed open radius is in . This requires a valid bound across the entire relevant region, not a norm estimated from few samples. Methods such as Lipschitz-Margin Training incorporate control of these bounds during training, in exchange for architecture-dependent constraints and cost.
Propagating boxes: IBP
Interval bound propagation maintains lower and upper bounds for each neuron. For , define and . If componentwise,
After ReLU, bounds are and . Each box contains the reachable region but treats correlated coordinates as independent. That loss of dependence accumulates across layers. To certify a class, bound each logit difference directly: if its lower bound is positive for all competitors, the class does not change in the box.
Points depict a finite input grid; they do not prove the box is tight. Changing width adds neurons to the margin, but the plane always represents the first two. The network and weights are defined in the NumPy laboratory. For four neurons and ε = 0.15, its IBP margin bound is 0.353 and the linear bound used is 0.3825; both are positive. In other boxes a simply chosen linear relaxation can be looser than IBP.
A network trained only on clean data can produce enormous intervals. Gowal and colleagues incorporate IBP bounds into training loss and adapt the threat schedule: the network learns to produce useful bounds. The result depends on training; it does not guarantee every arbitrary model will have good certified accuracy.
Linear relaxations and backward substitution
Linear relaxation retains information about how activations change with input. For a ReLU with , the upper line joining to is
Below, one may use or . If the ReLU is exactly ; if it is exactly zero. The figure uses lower slope 1 when and 0 otherwise. This is a valid choice for the illustration, not necessarily the best for every objective.
To lower-bound a combination of activations, a positive coefficient multiplies a lower bound and a negative coefficient an upper bound. Substituting these lines backward yields an affine function of input; its minimum on a box is obtained by choosing an endpoint per coordinate. CROWN develops this approach for different activations. Slopes and intermediate bounds affect looseness and cost.
Splitting the domain by a ReLU’s state and rebounding each branch reduces looseness. β-CROWN incorporates branching constraints into bound propagation. An implementation exhaustively exploring relevant branches and terminating can be complete under its assumptions; one bound pass or an interrupted search remains incomplete.
Randomized smoothing
For base classifier and noise , define . The guarantee belongs to the smoothed classifier , not necessarily base classifier . Noise is added to all coordinates; clipping it or changing preprocessing changes the distribution and must form part of the analyzed base function.
Proof
The Neyman-Pearson lemma compares probabilities of the same set under Gaussians centered at and . For a given probability under the first, the set of lowest probability under the second is a half-space perpendicular to . Thus probability of class after shifting the center is at least . If the norm is strictly smaller than the stated radius, this exceeds . All other classes together sum to less than , so remains the most probable class. Cohen, Rosenfeld and Kolter also prove a tighter version using an upper bound on the rival class.
∎The figure uses a two-dimensional base classifier distinguishing the interior of a circle. One independent sample chooses the point’s class and another estimates its probability; the colored map is also a Monte Carlo approximation. The drawn boundary is not a certificate for all pixels. Increasing σ can enlarge a radius at some points and change the smoothed class or degrade accuracy at others. Sample count affects uncertainty, not the mathematical definition of .
Independent selection and abstention
For CERTIFY, take samples to choose a candidate class and another independent samples to count votes for that class. The exact one-sided Clopper-Pearson lower bound is if , and zero if . If the bound does not exceed 1/2, the procedure abstains. Conditional on independent selection, the probability that the bound exceeds the true probability is at most α. Reusing the same samples to choose class and calculate this bound without correction breaks that argument.
PREDICT asks a different question: it compares counts for the two most-voted classes with a two-sided binomial test and abstains if it does not pass the threshold. A non-abstaining prediction does not itself determine a radius. Each certificate has a statistical confidence level; a collection of many certificates does not automatically have the same simultaneous guarantee without a multiplicity adjustment. Test-sample uncertainty also affects a certified-accuracy curve.
The previous radius uses . To ensure an box of radius ε in dimension , it suffices to require , but conversion can be very conservative on large images. Smoothing scales to large models using sampled inferences, although many samples per example take time. IBP, relaxations and branching can offer other tradeoffs for other architectures and threats; none removes the need to state model, domain and properties.
NumPy laboratory: bounds and attack
The scalar margin of this fixed network represents the difference between two logits. Bounds use an box; the Lipschitz bound calculated directly for the margin is . PGD search supplies a found adversarial example and therefore an upper bound on minimum distance in its norm; it does not establish the optimal distance. Sampling checks particular cases and does not replace proof of the formulas.
import numpy as np
# MLP de dos entradas y una capa oculta; el margen es logit_0-logit_1.
W=np.array([[1.,.7],[-.8,1.1],[1.2,-.9],[-.7,-.5]])
b=np.array([-.15,.12,-.2,.3]); v=np.array([.9,-.6,.55,-.4]); c=.35
x=np.array([.45,.35])
def margin(z): return np.maximum(z@W.T+b,0)@v+c
def bounds(eps):
lo=W@x+b-np.abs(W).sum(1)*eps
hi=W@x+b+np.abs(W).sum(1)*eps
# Cota inferior de intervalo, usando el signo del peso de salida.
ibp=np.maximum(lo,0)@np.maximum(v,0)+np.maximum(hi,0)@np.minimum(v,0)+c
# Retrosustitución: cota inferior para v>=0 y superior para v<0.
a=np.zeros_like(lo); d=np.zeros_like(lo)
for j,(l,u) in enumerate(zip(lo,hi)):
if l>=0: a[j]=1
elif u<=0: a[j]=0
elif v[j]>=0: a[j]=float(u>=-l)
else: a[j]=u/(u-l); d[j]=-l*u/(u-l)
coef=(v*a)@W; intercept=(v*a)@b+v@d+c
crown=coef@x+intercept-eps*np.abs(coef).sum()
return float(ibp),float(crown)
def radius_bound(which):
lo,hi=0.,2.
for _ in range(50):
mid=(lo+hi)/2
if bounds(mid)[which]>0:lo=mid
else:hi=mid
return lo
def pgd(eps,rng):
best=x.copy(); mb=float(margin(best))
for _ in range(12):
a=x+rng.uniform(-eps,eps,2)
for __ in range(80):
grad=(v*((W@a+b)>0))@W
a=np.clip(a-eps/20*np.sign(grad),x-eps,x+eps)
score=float(margin(a))
if score<mb:best=a.copy();mb=score
return best,mb
rng=np.random.default_rng(26)
print('margen limpio',margin(x))
for eps in (.05,.15,.30,.50):
ibp,crown=bounds(eps); z=x+rng.uniform(-eps,eps,(20000,2)); observed=margin(z).min()
assert ibp<=observed+1e-12 and crown<=observed+1e-12
print('epsilon',eps,'IBP',round(ibp,6),'CROWN',round(crown,6),'mínimo muestreado',round(observed,6))
lip=np.linalg.norm(v)*np.linalg.norm(W,2)
print('Lipschitz margen L2',round(lip,6),'radio L2',round(float(margin(x)/lip),6))
print('radios L∞ IBP y CROWN',radius_bound(0),radius_bound(1))
adv,am=pgd(.7,rng);print('PGD L∞ distancia',round(float(np.max(np.abs(adv-x))),6),'margen',round(am,6),'adversario',adv.round(6))
assert am<0Local laboratory: smoothing on CIFAR-10
Three small CNNs are trained from scratch on 4096 training images with Gaussian noise σ = 0.12, 0.25 and 0.50, four epochs and seed 26. PREDICT and CERTIFY are calculated on the first 64 test images with 100 samples for selection and 512 independent samples for certification, α = 0.001 per point. The graph counts success only as a certificate of the correct label with at least the indicated radius. These figures are from a short run, not competitive results or a conclusive model comparison.
Normalization is inside the network and noise is not clipped; the threat space is expressed in pixel units before normalization. With the lower bound never reaches 1, even with 512 identical votes, so radius is finite. PREDICT and CERTIFY calls use separate samples and may disagree. The code requires PyTorch, torchvision, SciPy and Matplotlib; CIFAR_LOCAL_ONLY=1 reuses downloaded data. A GPU accelerates inference, but CPU also works with more time.
import os, json, math, random, time
import numpy as np
import torch
import matplotlib.pyplot as plt
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
from scipy.stats import beta, binomtest, norm
torch.set_num_threads(4)
device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('CIFAR_ROOT','./data/cifar10')
local=os.environ.get('CIFAR_LOCAL_ONLY','0')=='1'
train=datasets.CIFAR10(root,train=True,transform=transforms.ToTensor(),download=not local)
test=datasets.CIFAR10(root,train=False,transform=transforms.ToTensor(),download=False)
loader=DataLoader(Subset(train,range(4096)),batch_size=128,shuffle=True,num_workers=0,generator=torch.Generator().manual_seed(26))
class SmallCNN(nn.Module):
def __init__(self):
super().__init__();self.net=nn.Sequential(nn.Conv2d(3,32,3,padding=1),nn.ReLU(),nn.AvgPool2d(2),nn.Conv2d(32,64,3,padding=1),nn.ReLU(),nn.AvgPool2d(2),nn.Flatten(),nn.Linear(64*8*8,128),nn.ReLU(),nn.Linear(128,10))
self.register_buffer('mean',torch.tensor([.4914,.4822,.4465])[None,:,None,None]);self.register_buffer('std',torch.tensor([.2023,.1994,.2010])[None,:,None,None])
def forward(self,x):return self.net((x-self.mean)/self.std)
def sample_counts(model,x,sigma,n,batch=128):
counts=np.zeros(10,dtype=int)
with torch.no_grad():
for start in range(0,n,batch):
k=min(batch,n-start);noise=torch.randn((k,*x.shape),device=device)*sigma
# No recortar: la garantía corresponde al ruido gaussiano completo.
pred=model(x.unsqueeze(0)+noise).argmax(1)
counts+=torch.bincount(pred,minlength=10).cpu().numpy()
return counts
def predict(model,x,sigma,n=100,alpha=.001):
counts=sample_counts(model,x,sigma,n);order=np.argsort(counts)[::-1];a,b=order[:2]
p=binomtest(int(counts[a]),int(counts[a]+counts[b]),.5,alternative='two-sided').pvalue
return (int(a) if p<=alpha else None),counts,p
def certify(model,x,sigma,n0=100,n=512,alpha=.001):
selected=int(sample_counts(model,x,sigma,n0).argmax()) # muestra independiente
k=int(sample_counts(model,x,sigma,n)[selected])
lower=0. if k==0 else float(beta.ppf(alpha,k,n-k+1))
return (selected if lower>.5 else None),float(sigma*norm.ppf(lower) if lower>.5 else 0.),k,lower
results={}
for sigma in (.12,.25,.50):
random.seed(26);np.random.seed(26);torch.manual_seed(26);torch.cuda.manual_seed_all(26)
model=SmallCNN().to(device);opt=torch.optim.Adam(model.parameters(),lr=.001)
start=time.perf_counter()
for epoch in range(4):
model.train();loss_sum=0
for x,y in loader:
x,y=x.to(device),y.to(device);opt.zero_grad();loss=F.cross_entropy(model(x+sigma*torch.randn_like(x)),y);loss.backward();opt.step();loss_sum+=loss.item()*len(y)
print('sigma',sigma,'época',epoch+1,'pérdida',round(loss_sum/len(loader.dataset),4),flush=True)
model.eval(); rows=[]
for i in range(64):
x,y=test[i];x=x.to(device)
guess,counts,p=predict(model,x,sigma)
pred,r,k,lb=certify(model,x,sigma)
rows.append({'index':i,'label':y,'predict':guess,'predict_p':p,'certified_class':pred,'radius':r,'count':k,'lower':lb})
radii=[0.,.05,.10,.20,.30,.50]
curve=[sum(row['certified_class']==row['label'] and row['radius']>=r for row in rows)/len(rows) for r in radii]
results[str(sigma)]={'epochs':4,'training':4096,'n0':100,'n':512,'alpha':.001,'test':len(rows),'radii':radii,'accuracy':curve,'rows':rows,'seconds':round(time.perf_counter()-start,1)}
print('RESULTADO',sigma,'exactitud certificada',list(zip(radii,curve)),flush=True)
print('RESULT_JSON',json.dumps(results),flush=True)
for label,result in results.items():
plt.plot(result['radii'],result['accuracy'],marker='o',label='σ = '+label)
plt.xlabel('Radio L2');plt.ylabel('Exactitud certificada');plt.ylim(0,1);plt.legend();plt.grid(alpha=.3);plt.show()npm run lab and open the connection link.Comparison with auto_LiRPA
The same scalar network is checked with auto_LiRPA, pinning code to commit e3930353a3589f7d10879f1e71223d1eefb57196. In double precision, IBP and CROWN bounds agree with the previous implementation for all four radii, differing by less than 1e-10. Agreement checks this network and these relaxation choices, not correctness of every implementation. At ε = 0.5, the chosen CROWN bound is lower than IBP: the particular relaxation need not dominate it. The network is the logit difference, so positive output certifies that margin.
The test ran in an isolated environment with auto_LiRPA 0.8.0 and PyTorch 2.11.0 on CPU and Python 3.12; the repository version declares Python 3.11 support, so this combination is a specific test outside its stated range, not a general compatibility guarantee. To reproduce in a supported environment use Python 3.11 and dependencies from the pinned repository. The cell requires that local environment.
With a Python 3.11 virtual environment active, install the exact revision and its dependencies from the project source archive:
python -m pip install "https://github.com/Verified-Intelligence/auto_LiRPA/archive/e3930353a3589f7d10879f1e71223d1eefb57196.zip"
import numpy as np
import torch
from torch import nn
from auto_LiRPA import BoundedModule, BoundedTensor, PerturbationLpNorm
W=np.array([[1.,.7],[-.8,1.1],[1.2,-.9],[-.7,-.5]])
b=np.array([-.15,.12,-.2,.3]);v=np.array([.9,-.6,.55,-.4]);x=np.array([.45,.35])
def own_bounds(eps):
lo=W@x+b-np.abs(W).sum(1)*eps;hi=W@x+b+np.abs(W).sum(1)*eps
ibp=np.maximum(lo,0)@np.maximum(v,0)+np.maximum(hi,0)@np.minimum(v,0)+.35
a=np.zeros(4);d=np.zeros(4)
for j,(l,u) in enumerate(zip(lo,hi)):
if l>=0:a[j]=1
elif u<=0:a[j]=0
elif v[j]>=0:a[j]=float(u>=-l)
else:a[j]=u/(u-l);d[j]=-l*u/(u-l)
coef=(v*a)@W; intercept=(v*a)@b+v@d+.35
return ibp,coef@x+intercept-eps*np.abs(coef).sum()
net=nn.Sequential(nn.Linear(2,4),nn.ReLU(),nn.Linear(4,1)).double().eval()
with torch.no_grad():
net[0].weight.copy_(torch.tensor(W));net[0].bias.copy_(torch.tensor(b))
net[2].weight.copy_(torch.tensor([v]));net[2].bias.fill_(.35)
tx=torch.tensor([x]);bounded=BoundedModule(net,tx,device='cpu')
for eps in (.05,.15,.30,.50):
bx=BoundedTensor(tx,PerturbationLpNorm(norm=np.inf,eps=eps))
lb_i,_=bounded.compute_bounds(x=(bx,),method='IBP')
lb_c,_=bounded.compute_bounds(x=(bx,),method='backward')
expected=own_bounds(eps);measured=(lb_i.item(),lb_c.item())
print('epsilon',eps,'NumPy',np.round(expected,6),'auto_LiRPA',np.round(measured,6))
assert np.allclose(expected,measured,rtol=0,atol=1e-10)npm run lab and open the connection link.Exercises
Step 1 of 2. Which event minimizes its shifted probability for a fixed probability under the original center?
Step 1 of 2. What is the norm of e_a − e_j?
import numpy as np
def ibp_bounds(layers, x, eps):
pass