Module contents
Lesson 26 of 39Advanced 110 min

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 L∞L_\infty box of radius ε each coordinate may vary by up to ε; an L2L_2 ball bounds total length. If pixels must remain in [0,1][0,1], 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 f(x)∈RKf(x)\in\mathbb R^K be the logit vector and aa its winning class. Its margin is m(x)=min⁡j≠a(fa(x)−fj(x))m(x)=\min_{j\ne a}(f_a(x)-f_j(x)). If ff is LL-Lipschitz from L2L_2 to L2L_2, then for any competitor

∣(fa−fj)(x+δ)−(fa−fj)(x)∣≤2 L∥δ∥2.|(f_a-f_j)(x+\delta)-(f_a-f_j)(x)|\le\sqrt{2}\,L\|\delta\|_2.

Apply Cauchy-Schwarz to vector ea−eje_a-e_j, whose norm is 2\sqrt2. Thus if m>0m>0, no competitor reaches aa for ∥δ∥2<m/(2L)\|\delta\|_2<m/(\sqrt2 L). 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 L=2L=2 is known, the guaranteed open radius is 0.6/(22)≈0.21210.6/(2\sqrt2)\approx0.2121 in L2L_2. 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 z=Wx+bz=Wx+b, define W+=max⁡(W,0)W^+=\max(W,0) and W−=min⁡(W,0)W^-=\min(W,0). If l≤x≤ul\le x\le u componentwise,

lz=W+l+W−u+b,uz=W+u+W−l+b.l_z=W^+l+W^-u+b,\qquad u_z=W^+u+W^-l+b.

After ReLU, bounds are max⁡(0,lz)\max(0,l_z) and max⁡(0,uz)\max(0,u_z). 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.

InteractiveInflating boxes

The orange box contains the outputs of the first two ReLUs. The blue dots sample an input grid mapped through the network, showing part of the reachable region.

ReLU 1ReLU 2

This fixed network has two inputs. Increasing its width adds two more neurons to the margin calculation. The linear bound uses back-substitution with slopes chosen for each neuron. It can be tighter or looser than IBP. A positive lower margin certifies the class throughout the box.

15
ε en L∞0.15
IBP margin bound0.353
Linear margin bound0.382
Compare reachable points with an IBP box and two margin bounds for an explicit network.

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 l<0<ul<0<u, the upper line joining (l,0)(l,0) to (u,u)(u,u) is

h≤uu−l(z−l).h\le \frac{u}{u-l}(z-l).

Below, one may use h≥0h\ge0 or h≥zh\ge z. If l≥0l\ge0 the ReLU is exactly h=zh=z; if u≤0u\le0 it is exactly zero. The figure uses lower slope 1 when u≥−lu\ge-l and 0 otherwise. This is a valid choice for the illustration, not necessarily the best for every objective.

InteractiveBounding a ReLU between lines
lu

Blue: ReLU. Orange: upper bound. Dashed: lower bound. When l < 0 < u, the chosen lower bound is y = z and the upper bound joins (l, 0) and (u, u). In the stable case, both lines coincide with the function.

The area measures the gap between the lines over this interval. Its units differ from those of a probability or a network-margin bound.

0
8
l−0.8
u0.8
Area between the lines0.640
StateUnstable
Adjust the interval and observe stable cases and relaxation of the unstable case.

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 ff and noise η∼N(0,σ2I)\eta\sim\mathcal N(0,\sigma^2I), define g(x)=argmax⁡cP(f(x+η)=c)g(x)=\operatorname{argmax}_c\Pr(f(x+\eta)=c). The guarantee belongs to the smoothed classifier gg, not necessarily base classifier ff. 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 xx and x+δx+\delta. For a given probability under the first, the set of lowest probability under the second is a half-space perpendicular to δ\delta. Thus probability of class AA after shifting the center is at least Φ(Φ−1(p‾A)−∥δ∥2/σ)\Phi(\Phi^{-1}(\underline p_A)-\|\delta\|_2/\sigma). If the norm is strictly smaller than the stated radius, this exceeds 1/21/2. All other classes together sum to less than 1/21/2, so AA remains the most probable class. Cohen, Rosenfeld and Kolter also prove a tighter version using an upper bound on the rival class.

∎
InteractiveSmoothing to certify
−22

The dashed unit circle shows the base boundary. Blue and orange estimate smoothed classes under Gaussian noise. The disk around the point uses a sample independent of class selection. The one-sided Clopper–Pearson bound uses α = 0.001. This numerical demonstration does not formally verify rounding.

3
160
Selected classInterior
Samples in that class137/160
Lower bound on p0.753
L2 radius0.205
Choose σ and the sample budget; the disk belongs to the smoothed classifier.

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 gg.

Independent selection and abstention

For CERTIFY, take n0n_0 samples to choose a candidate class and another nn independent samples to count kk votes for that class. The exact one-sided Clopper-Pearson lower bound is Beta⁡−1(α;k,n−k+1)\operatorname{Beta}^{-1}(\alpha;k,n-k+1) if k>0k>0, and zero if k=0k=0. 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 L2L_2. To ensure an L∞L_\infty box of radius ε in dimension dd, it suffices to require d ε<R2\sqrt d\,\varepsilon<R_2, 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 L∞L_\infty box; the Lipschitz bound calculated directly for the margin is L2L_2. 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.

[ ]IBP, linear relaxation and PGDBrowser
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<0

Local 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 n=512n=512 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.

[ ]Training with noise and statistical certificationLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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"
[ ]Independent comparison with auto_LiRPALocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
With σ = 0.5 and lower bound p = 0.9, calculate σ Φ⁻¹(p), in L2 units.
Proof
Prove: Justify why a lower bound p greater than 1/2 certifies the stated Gaussian radius.
0
The base classifier is deterministic and Gaussian noise is isotropic.

Step 1 of 2. Which event minimizes its shifted probability for a fixed probability under the original center?

Proof
Prove: Prove the bound m/(√2 L) for L-Lipschitz logits in L2.
0
Class a has positive margin m against every competitor.

Step 1 of 2. What is the norm of e_a − e_j?

Quiz
Which statement describes a valid bound relaxation without exhaustive branching?
Quiz
Consider a terminating exhaustive exact verifier, IBP, a 'safe' conclusion based only on a failed attack, and a Monte Carlo smoothing certificate. Which classification respects their assumptions?
Code
Implement ibp_bounds(layers, x, eps). Each layer is a pair (W,b) followed by ReLU; return a list of (lower, upper) pairs, one per layer. Reject negative eps.
import numpy as np
def ibp_bounds(layers, x, eps):
  pass
Shift+Enter to run
Key idea
A certificate is a claim about a model, a set and precise assumptions; an inconclusive result and a failed attack answer different questions.