Adversarial examples: evasion attacks
Introduce adversarial robustness through inference-time attacks. Formalize Lp and problem-space threat models, derive FGSM using norm duality, implement PGD and Carlini-Wagner, and study transferability and score-based and decision-based black-box attacks. Conclude with the explanations of why they exist (linearity in high dimension, non-robust features) and with domain constraints like malware and code.
After this lesson you can
- Formulate an evasion attack as optimization with constraints under an explicit threat model.
- Derive FGSM as the optimal solution of the linearized problem under L∞ and its analog in L2.
- Implement PGD with random restarts, Carlini-Wagner and a black-box attack by scores.
- Measure transferability between models and explain its use in attacks without queries.
- Adapt the threat model to domains with semantic constraints like malware or source code.
Before you start
A chosen error, not just noise
An adversarial example is an input modified to provoke an unwanted model output under an explicit set of permitted changes. In an evasion attack, the model is already deployed: the inference input is changed, rather than the training parameters. A valid change to an image may be infeasible for a program or message; a small norm alone does not establish that the true label or functionality has been preserved.
The threat model specifies what the attacker knows, what they can modify, whether they observe scores or only labels, their query budget, and what counts as success. For an image , label , fixed parameters , and loss , an untargeted formulation is
A targeted attack seeks a specific class , for example by minimizing its cross-entropy, and is evaluated by how often it reaches . High loss is a search signal; it is not always equivalent to misclassification. Every success figure should be accompanied by the feasible set, representation, scale, and budget.
Lp threat models constrain a norm of . The ball limits each coordinate; limits total energy; favors concentrated changes. For images, in original pixel values is different from applied to inputs already normalized per channel. If the model receives , a change in pixel space becomes ; attacking the normalized input without adjusting the bounds changes the problem.
What is known and what can be changed
A white-box evaluation grants access to the model and its gradients. A score-based black-box interface exposes only output values, while a decision-based interface returns only a label. Knowing the architecture or training set does not necessarily give access to gradients. Likewise, a budget of one hundred queries per image differs from one hundred queries shared across the dataset. Record whether queries can adapt to each response and whether the attacker knows the true label.
The objective also matters. In an untargeted attack, any class different from the reference is sufficient; in a targeted attack, only the chosen class counts. If an input was already misclassified before the attack, it is not a new evasion success in a success rate conditioned on correct clean predictions. Empirical robust accuracy over the full dataset counts these initial errors as non-robust. Reporting both quantities and their denominators avoids confusing a conditional success rate with overall accuracy.
An L∞ ball of radius ε contains points that change many coordinates at once; a ball L2 of the same number has a different geometry and does not represent the same budget. Nor is it enough to indicate ‘small’: units, range, and pre-processing are needed. Additional constraints may include pixels that cannot be modified, channels with different scales, or physical transformations. A result in a specific feasible set does not automatically extend to others.
FGSM and dual norms
FGSM linearizes the loss around : , with . Under , each coordinate can take the extreme value matching the sign of :
Proof
For each coordinate, . Summing gives the bound, attained by choosing ; if , any feasible value of that coordinate gives the same contribution. Hölder’s inequality generalizes the result to , where , including the limiting cases of and infinity.
∎For and , the optimum of the approximation is ; if , any feasible direction has the same linear value. Under , the budget can be concentrated on a coordinate where has maximum magnitude. These solutions are exact for the linearized objective without additional constraints. Clipping the image to preserves feasibility but can change the optimum, especially at the range boundaries.
Goodfellow and colleagues proposed FGSM and an explanation based on linear accumulation in many dimensions. The attack requires a single gradient evaluation, but its speed does not make a failed attack a guarantee of robustness. A nonlinear function can have high-loss regions that the first step misses.
PGD, projection and restarts
The PGD attack alternates ascent steps with a return to the permitted set. For , an untargeted version is
Projection onto this intersection is coordinatewise clipping. A targeted attack reverses the sign to minimize target-class loss. In , the direction is normalized and a radial projection is used; subsequent clipping to preserves feasibility when the original input is valid, although this composition is not always the exact Euclidean projection onto the intersection. The code states this choice instead of claiming unproven properties.
Restarts explore different feasible starting points. More steps and restarts can find examples missed by a single start, but do not prove that the global maximum has been found. To calculate empirical robust accuracy, retain any adversarial candidate already found and include the clean input: an initially misclassified example must not count as robust. Madry and colleagues formulated adversarial robustness as an inner and outer optimization problem; the attack used for evaluation remains an approximation.
How to compare iterative attacks
A step size that is too small may fail to explore the region; one that is too large may bounce between faces of the ball or miss details of the surface. Restarts cover other starting points, but a fixed restart count does not replace convergence analysis. A careful evaluation compares several step budgets, retains the best candidates, and examines attacks with different losses. Each step must preserve valid input values and constrain the distance from the original image, rather than from the previous iterate.
The optimization objective and the success criterion should be separated. The true label cross-entropy may rise without changing the argmax; it can also happen that a wrongly classified candidate has lower loss than another that remains correct. For this reason, the laboratory prioritizes conserving a found failure and only uses the loss to tie-break between candidates of the same condition. In targeted evaluation, the criterion is inverted: the candidate that reaches the target class is saved.
The radial projection and subsequent clipping are a simple way to construct a feasible point for L2, because clipping towards a box that contains the original input does not increase the distance to it. To obtain the exact Euclidean projection at the intersection, in general, one has to solve the joint problem. That distinction matters if convergence properties are analyzed, although both options produce valid images for a heuristic attack.
C&W and margins
The targeted Carlini-Wagner attack seeks to reduce distance while enforcing a margin between logits. One form of its L2 objective is
The change of variables preserves the pixel range. The constant balances distance and margin; searching over it and running multiple iterations are parts of the procedure, not guarantees of finding the global minimum distance. A positive margin requires additional separation. Implementations may use a penalty equivalent up to a constant; record the loss, success criterion, budget, and selection policy. Carlini and Wagner emphasized evaluating defenses with sufficiently strong attacks.
The interactive model was trained on sklearn.datasets.load_digits, intensities divided by 16 and stratified split 70/30 with seed 24. It has 32 hidden neurons; it achieved 96.5% on the 540 test examples. The curve uses the first 200 test examples: FGSM and PGD L∞ with 12 steps, step ε/4, and three starts (one clean and two random), without certifying the maximum. The example images are from the test and can be edited; for a custom drawing, the chosen label is a user reference, not a verified annotation. The panel uses 20 steps and two starts for PGD. Its targeted C&W test uses four constants and 100 steps per constant; it does not claim to find the optimal solution nor apply the ε of FGSM/PGD.
Transfer and black-box attacks
Transferability occurs when a perturbation crafted against a substitute also changes another model’s prediction. Report success on the substitute and the second model’s clean and attacked accuracy; conditioning only on images that already failed on one model can inflate the percentage. The lab’s two MLPs share training data but use different initialization seeds, so this is not a comparison between architectures. Papernot and colleagues studied transfer between models as a route to black-box attacks.
Black-box attacks depend on the information available. Scores permit gradient estimates using finite differences or random perturbations, or direct searches for changes that improve a loss. Square Attack uses a randomized patch search; the lab implements an educational L∞ version with boundary initialization, patches, and decreasing patch sizes. Its budget is short and it does not reproduce all options of the official implementation. With only decisions, neither probabilities nor loss gradients are available. HopSkipJumpAttack estimates information about the boundary from labels. The query count includes initial evaluations and rejected candidates; exhausting the budget without success does not establish the absence of an adversarial example.
Queries, transfer and coverage
In a score-based attack, a central finite difference queries the model on both sides of a point to approximate a directional derivative. In high dimensions, estimating each coordinate separately can require many queries; randomized estimates trade off cost and variance. A patch method can seek score improvements directly without reconstructing a gradient. Each approach must respect the input range at every query, count initialization costs, and state whether the budget is per image.
With just labels, a basic strategy first seeks a point that already produces another decision and then reduces the distance toward the original. If it does not find an initial point within the budget, the procedure may end without an example; the lab records that possibility. Bisection of a segment finds a transition along that line, not necessarily the nearest boundary in all directions. HopSkipJump and other methods add estimates and additional decisions; their guarantees or results should not be attributed to simple bisection.
To evaluate transfer, prepare the examples without using the gradient of the target model and keep fixed the input pairs. A different architecture and a different initialization are sources of different variations; two networks of the same architecture trained with other seeds do not measure the entire space of possible models. If an attack uses a set of substitutes, report how their losses are combined and account for their cost. The fact that an attack transfers on some examples does not guarantee that it transfers to any model or domain.
Dimension and meaning
If each weight has constant magnitude, grows with dimension, as does the maximum change . Normalizing the weights as dimension increases can change this growth rate; the figure does not estimate the weight distribution of a real network. Ilyas and colleagues study predictive but non-robust features as another perspective. Neither explanation alone establishes that every perturbation within a ball is imperceptible or label-preserving.
In discrete domains such as email, executables, or source code, the model input is usually a representation derived from the actual object. Changing an arbitrary coordinate may be infeasible or may alter functionality. A problem-space threat model must define permitted transformations and check their invariants; Pierazzi and colleagues analyze the difference between manipulating features and constructing valid objects. Medical images also require appropriate clinical constraints and evaluation, rather than an assumption that the norm captures meaning.
NumPy Laboratory
The lab trains two MLPs from scratch on synthetic augmentations of ten templates from sklearn (one per digit). Test examples are new augmentations of those same ten templates, rather than independent original images. It implements FGSM, PGD L∞ and L2, a targeted variant, C&W L2 with a search over constants, and a score-based patch search. The results check the operations and transfer between initializations; they do not estimate general robustness.
import numpy as np
# Diez plantillas reales de sklearn digits, una por clase. Los aumentos sintéticos no son un test independiente del original.
templates=np.array([[0.0, 0.0, 0.25, 0.75, 0.875, 0.3125, 0.0, 0.0, 0.0, 0.0, 0.6875, 1.0, 1.0, 1.0, 0.1875, 0.0, 0.0, 0.1875, 1.0, 0.875, 0.125, 1.0, 0.4375, 0.0, 0.0, 0.5, 1.0, 0.4375, 0.0, 1.0, 0.375, 0.0, 0.0, 0.25, 1.0, 0.25, 0.1875, 1.0, 0.25, 0.0, 0.0, 0.25, 1.0, 0.3125, 0.625, 0.875, 0.0, 0.0, 0.0, 0.0, 0.875, 1.0, 1.0, 0.625, 0.0, 0.0, 0.0, 0.0, 0.25, 0.875, 0.875, 0.125, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.625, 0.6875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.8125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4375, 1.0, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.8125, 1.0, 0.1875, 0.0, 0.0, 0.0, 0.0, 0.625, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.9375, 1.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.1875, 0.75, 0.375, 1.0, 0.375, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.625, 0.8125, 0.4375, 0.0], [0.0, 0.0, 0.375, 1.0, 1.0, 0.4375, 0.0, 0.0, 0.0, 0.5, 1.0, 0.8125, 0.625, 1.0, 0.0, 0.0, 0.0, 0.375, 0.5625, 0.0, 0.375, 0.9375, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.8125, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.375, 1.0, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.9375, 0.5, 0.1875, 0.3125, 0.0, 0.0, 0.0, 0.5, 1.0, 0.6875, 1.0, 0.5625, 0.0, 0.0, 0.0, 0.3125, 1.0, 1.0, 0.4375, 0.0, 0.0], [0.0, 0.0, 0.3125, 0.6875, 1.0, 1.0, 0.5, 0.0, 0.0, 0.0, 0.9375, 0.875, 0.5, 0.75, 0.9375, 0.0, 0.0, 0.0, 0.0, 0.0, 0.125, 0.875, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.6875, 0.75, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.0625, 1.0, 0.3125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.875, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.25, 0.9375, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.4375, 1.0, 0.6875, 0.125, 0.0, 0.0], [0.0, 0.0, 0.0, 0.4375, 1.0, 0.125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.9375, 0.6875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.6875, 0.875, 0.375, 0.3125, 0.0, 0.0, 0.0, 0.25, 1.0, 0.4375, 0.875, 0.8125, 0.125, 0.0, 0.0, 0.625, 1.0, 0.8125, 1.0, 1.0, 0.625, 0.0, 0.0, 0.5, 0.9375, 0.875, 1.0, 0.625, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.5625, 1.0, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5625, 0.9375, 0.0625, 0.0, 0.0], [0.0, 0.0, 0.0625, 0.625, 0.875, 0.8125, 0.0625, 0.0, 0.0, 0.0, 0.5, 0.75, 0.375, 0.25, 0.0, 0.0, 0.0, 0.0, 0.875, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3125, 1.0, 0.75, 0.8125, 0.75, 0.0, 0.0, 0.0, 0.125, 0.6875, 0.6875, 0.5, 0.875, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.375, 0.9375, 0.125, 0.0, 0.0, 0.0, 0.0, 0.75, 0.875, 0.25, 0.0, 0.0], [0.0, 0.0, 0.0, 0.4375, 0.8125, 0.125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.875, 0.875, 0.125, 0.0, 0.0, 0.0, 0.0, 0.3125, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.6875, 1.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.3125, 1.0, 1.0, 0.9375, 0.75, 0.0, 0.0, 0.0, 0.0, 0.5625, 1.0, 0.0625, 0.8125, 0.4375, 0.0, 0.0, 0.0, 0.25, 1.0, 0.375, 0.9375, 0.3125, 0.0, 0.0, 0.0, 0.0, 0.375, 0.875, 0.875, 0.0625, 0.0], [0.0, 0.0, 0.4375, 0.875, 1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.875, 0.875, 1.0, 0.875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.625, 0.75, 0.0, 0.0, 0.0, 0.0, 0.25, 0.25, 0.875, 0.5625, 0.125, 0.0, 0.0, 0.4375, 1.0, 1.0, 1.0, 1.0, 0.4375, 0.0, 0.0, 0.375, 0.75, 1.0, 0.6875, 0.0625, 0.0, 0.0, 0.0, 0.0, 0.125, 1.0, 0.1875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.375, 0.8125, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.3125, 0.25, 0.5625, 0.625, 0.0, 0.0, 0.0, 0.0, 0.625, 0.5, 0.6875, 1.0, 0.125, 0.0, 0.0, 0.0, 0.5, 0.75, 0.875, 0.875, 0.0625, 0.0, 0.0, 0.0, 0.3125, 0.9375, 0.4375, 0.0, 0.0, 0.0, 0.0, 0.0, 0.875, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.875, 0.8125, 0.1875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75, 0.8125, 0.3125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4375, 1.0, 0.3125, 0.0, 0.0, 0.0], [0.0, 0.0, 0.5625, 0.9375, 0.8125, 0.1875, 0.0, 0.0, 0.0, 0.125, 0.875, 0.125, 0.375, 0.3125, 0.0, 0.0, 0.0, 0.25, 0.5625, 0.0, 0.0, 0.9375, 0.25, 0.0, 0.0, 0.0625, 0.8125, 0.3125, 0.4375, 1.0, 0.375, 0.0, 0.0, 0.0, 0.125, 0.4375, 0.4375, 0.875, 0.1875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0625, 0.875, 0.0625, 0.0, 0.0, 0.0, 0.1875, 0.0625, 0.625, 0.5625, 0.0, 0.0, 0.0, 0.0, 0.6875, 0.9375, 0.5625, 0.0625, 0.0, 0.0]]).reshape(10,8,8)
rng=np.random.default_rng(24)
def make_data(n):
xs=[];ys=[]
for digit,img in enumerate(templates):
for _ in range(n):
shifted=np.roll(img,(rng.integers(-1,2),rng.integers(-1,2)),axis=(0,1))
xs.append(np.clip(shifted+rng.normal(0,.04,img.shape),0,1).ravel());ys.append(digit)
return np.array(xs),np.array(ys)
X,Y=make_data(24);Xt,Yt=make_data(8)
def init(seed):
r=np.random.default_rng(seed)
return [r.normal(0,.18,(64,32)),np.zeros(32),r.normal(0,.18,(32,10)),np.zeros(10)]
def forward(p,x):
h=np.maximum(0,x@p[0]+p[1]);z=h@p[2]+p[3];z=z-z.max(axis=1,keepdims=True);q=np.exp(z);return h,q/q.sum(axis=1,keepdims=True)
def loss(p,x,y):
_,q=forward(p,x);return -np.log(np.maximum(q[np.arange(len(y)),y],1e-12))
def grad_input(p,x,y,targeted=False):
h,q=forward(p,x);q[np.arange(len(y)),y]-=1
if targeted:q=-q
return ((q@p[2].T)*(h>0))@p[0].T
def train(seed):
p=init(seed);r=np.random.default_rng(seed+100)
for step in range(600):
idx=r.integers(0,len(Y),64);x=X[idx];y=Y[idx];h,q=forward(p,x);q[np.arange(len(y)),y]-=1;q/=len(y)
g2=h.T@q;gb2=q.sum(axis=0);gh=(q@p[2].T)*(h>0);g1=x.T@gh;gb1=gh.sum(axis=0)
for v,g in zip(p,(g1,gb1,g2,gb2)):v-=.25*g
return p
p=train(1);q=train(2)
def acc(m,x,y):return np.mean(forward(m,x)[1].argmax(axis=1)==y)
def feasible(x,x0,eps,norm):
d=x-x0
if norm=='linf':d=np.clip(d,-eps,eps)
else:
n=np.linalg.norm(d,axis=1,keepdims=True);d*=np.minimum(1,eps/np.maximum(n,1e-12))
return np.clip(x0+d,0,1)
def direction(g,norm):
if norm=='linf':return np.sign(g)
return g/np.maximum(np.linalg.norm(g,axis=1,keepdims=True),1e-12)
def pgd(m,x,y,eps,norm='linf',steps=12,restarts=2,targeted=False):
r=np.random.default_rng(77);best=x.copy();best_loss=loss(m,x,y);best_bad=forward(m,x)[1].argmax(axis=1)!=y
# En ataque dirigido, y contiene la clase objetivo y se minimiza su CE.
if targeted:best_bad=forward(m,x)[1].argmax(axis=1)==y;best_loss=-best_loss
for k in range(restarts):
a=x.copy() if k==0 else feasible(x+r.uniform(-eps,eps,x.shape),x,eps,norm)
for _ in range(steps):
a=feasible(a+(eps/4)*direction(grad_input(m,a,y,targeted),norm),x,eps,norm)
score=loss(m,a,y)*(-1 if targeted else 1);pred=forward(m,a)[1].argmax(axis=1);bad=pred==y if targeted else pred!=y
take=(bad & ~best_bad)|((bad==best_bad)&(score>best_loss));best[take]=a[take];best_loss[take]=score[take];best_bad[take]=bad[take]
return best
# C&W dirigido L2: variable tanh, margen de logits, búsqueda binaria de c y Adam.
def cw(m,x,target,outer=4,steps=100):
low=0.;high=100.;best=x.copy();bestd=np.inf;success=False
for _ in range(outer):
c=(low+high)/2;w=np.arctanh(np.clip(2*x-1,-.999999,.999999));mom=np.zeros_like(w);vel=np.zeros_like(w);found=False
for t in range(1,steps+1):
a=(np.tanh(w)+1)/2;h=np.maximum(a@m[0]+m[1],0);z=h@m[2]+m[3];other=int(np.argmax(np.where(np.arange(10)==target,-np.inf,z[0])));margin=z[0,other]-z[0,target]
if int(z.argmax())==target:
found=True;d=float(np.sum((a-x)**2))
if d<bestd:bestd=d;best=a.copy();success=True
dz=np.zeros((1,10))
if margin>0:dz[0,other]=1;dz[0,target]=-1
ga=2*(a-x)+c*((dz@m[2].T)*(h>0))@m[0].T;g=ga*.5*(1-np.tanh(w)**2)
mom=.9*mom+.1*g;vel=.999*vel+.001*g*g;w-=.05*(mom/(1-.9**t))/(np.sqrt(vel/(1-.999**t))+1e-8)
if found:high=c
else:low=c
return best,success
# Square Attack L∞ educativo: inicio en frontera, parches y reducción del tamaño con el presupuesto.
def square(m,x,y,eps,queries=40):
if queries<2:raise ValueError('se necesitan al menos dos consultas')
r=np.random.default_rng(41)
def observe(a):
_,probs=forward(m,a);pred=probs.argmax(axis=1);logits=np.log(np.maximum(probs,1e-12));true=logits[np.arange(len(y)),y]
logits[np.arange(len(y)),y]=-np.inf
return true-np.max(logits,axis=1),pred
# Se consultan el original y una inicialización de bandas con desplazamiento ±eps.
a=x.copy();score,pred=observe(a);best_bad=pred!=y
stripes=r.choice([-1.,1.],size=(len(x),1,8));init=np.clip(x+eps*np.repeat(stripes,8,axis=1).reshape(x.shape),0,1)
val,pred=observe(init);bad=pred!=y;take=(bad & ~best_bad)|((bad==best_bad)&(val<score))
a[take]=init[take];score[take]=val[take];best_bad[take]=bad[take]
thresholds=[10,50,200,500,1000,2000,4000,6000,8000]
for step in range(max(0,queries-2)):
scaled=step/max(1,queries-2)*10000
fraction=.8/(2**sum(scaled>=t for t in thresholds))
side=max(1,min(8,int(round(np.sqrt(fraction*64)))))
cand=a.copy()
for i in range(len(x)):
row=int(r.integers(0,9-side));col=int(r.integers(0,9-side));sign=r.choice([-1.,1.]);patch=cand[i].reshape(8,8);orig=x[i].reshape(8,8)
patch[row:row+side,col:col+side]=orig[row:row+side,col:col+side]+sign*eps
cand=np.clip(cand,0,1);new,pred=observe(cand);bad=pred!=y
take=(bad & ~best_bad)|((bad==best_bad)&(new<score));a[take]=cand[take];score[take]=new[take];best_bad[take]=bad[take]
return a,best_bad
print('accuracy limpio, dos MLP:',round(acc(p,Xt,Yt),3),round(acc(q,Xt,Yt),3))
clean=forward(p,Xt)[1].argmax(axis=1)==Yt
for eps in (0.,.05,.1,.2):
fg=feasible(Xt+eps*np.sign(grad_input(p,Xt,Yt)),Xt,eps,'linf');adv=pgd(p,Xt,Yt,eps)
print('eps',eps,'robusta FGSM',round(np.mean(clean&(forward(p,fg)[1].argmax(axis=1)==Yt)),3),
'robusta PGD',round(np.mean(clean&(forward(p,adv)[1].argmax(axis=1)==Yt)),3),
'transferencia: accuracy segundo',round(np.mean((forward(q,Xt)[1].argmax(axis=1)==Yt)&(forward(q,adv)[1].argmax(axis=1)==Yt)),3))
fg2=feasible(Xt[:8]+.8*direction(grad_input(p,Xt[:8],Yt[:8]),'l2'),Xt[:8],.8,'l2')
adv2=pgd(p,Xt[:8],Yt[:8],.8,norm='l2')
assert np.max(np.linalg.norm(fg2-Xt[:8],axis=1))<=.800001 and np.max(np.linalg.norm(adv2-Xt[:8],axis=1))<=.800001
sq,sq_bad=square(p,Xt[:20],Yt[:20],.2);assert np.max(np.abs(sq-Xt[:20]))<=.200001
print('square 40 consultas accuracy',round(np.mean(~sq_bad),3),'norma máxima FGSM y PGD L2',round(np.max(np.linalg.norm(fg2-Xt[:8],axis=1)),3),round(np.max(np.linalg.norm(adv2-Xt[:8],axis=1)),3))
target=(int(Yt[0])+1)%10;direct=pgd(p,Xt[:1],np.array([target]),.5,norm='l2',targeted=True);example,ok=cw(p,Xt[:1],target)
print('ataque dirigido PGD pred/objetivo',int(forward(p,direct)[1].argmax()),target,'C&W éxito',ok,'L2',round(float(np.linalg.norm(example-Xt[:1])),4) if ok else None)Local laboratory CIFAR-10
The cell uses the published weights of ResNet20 and VGG11 with batch normalization for CIFAR-10 from the repository pytorch-cifar-models, and torchattacks 3.5.1. You need PyTorch, torchvision, and torchattacks; download the official test and weights if they are not in cache. The measured SHA-256 are 4118986f0df73003d572b0e397f0ac7b3f60af1f31aff3d2da164536e36f6ec8 for ResNet and eaeebf42370c92fdfbb5dbe8eba7c27d4eb7366a1dca0b5be435364ccdf54378 for VGG. CIFAR_ROOT, RESNET_PATH and VGG_PATH allow the use of local copies; CIFAR_LOCAL_ONLY=1 prevents data downloads.
The attack receives pixels in and the normalization stays inside the model. It compares the custom PGD implementation with torchattacks.PGD from the same clean start, step, and number of iterations. Numerical agreement is required after one step and divergence is measured after ten, as small rounding differences can change signs of gradients in later steps. Then it measures PGD with three starts and transfer to VGG on 64 test images; it keeps any failure found. The label-only method looks for an image of another class and bisects the segment until exhausting a maximum of 40 queries: it is a demonstration of decision-based access, not HopSkipJump nor an optimal search. The resulting norm and budget are reported for each case. The sample is small and empirical accuracies are not certified. In an execution on RTX 3060, the two networks correctly classified 60 of 64 clean images. With , 10 steps and three starts on ResNet, none of the 64 remained correct against all the candidates tested; VGG kept 48 of 64 under those transferred perturbations. The comparison with torchattacks coincided exactly at the first step and differed at most after ten steps in that execution. In a previous attempt, the maximum difference was approximately 0.047: the iterative trajectories should not be assumed identical just because they have the same formula; the cause of that difference between executions was not determined. The decision attack found L2 distances of 10.682, 12.626, 8.375, and 1.026 for four images, with 40 queries in each case; it does not impose an L2 radius and those distances are not certified minimums.
import os, math, torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader,Subset
from torchvision import datasets,transforms
import torchattacks
torch.manual_seed(24);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'
RPATH=os.environ.get('RESNET_PATH');VPATH=os.environ.get('VGG_PATH')
RURL='https://github.com/chenyaofo/pytorch-cifar-models/releases/download/resnet/cifar10_resnet20-4118986f.pt'
VURL='https://github.com/chenyaofo/pytorch-cifar-models/releases/download/vgg/cifar10_vgg11_bn-eaeebf42.pt'
class Block(nn.Module):
def __init__(self,inp,out,stride=1):
super().__init__();self.conv1=nn.Conv2d(inp,out,3,stride,1,bias=False);self.bn1=nn.BatchNorm2d(out);self.relu=nn.ReLU(inplace=True);self.conv2=nn.Conv2d(out,out,3,1,1,bias=False);self.bn2=nn.BatchNorm2d(out)
self.downsample=nn.Sequential(nn.Conv2d(inp,out,1,stride,bias=False),nn.BatchNorm2d(out)) if stride!=1 or inp!=out else None
def forward(self,x):
skip=x if self.downsample is None else self.downsample(x)
return self.relu(self.bn2(self.conv2(self.relu(self.bn1(self.conv1(x)))))+skip)
class ResNet20(nn.Module):
def __init__(self):
super().__init__();self.conv1=nn.Conv2d(3,16,3,padding=1,bias=False);self.bn1=nn.BatchNorm2d(16);self.relu=nn.ReLU(inplace=True)
self.layer1=nn.Sequential(Block(16,16),Block(16,16),Block(16,16));self.layer2=nn.Sequential(Block(16,32,2),Block(32,32),Block(32,32));self.layer3=nn.Sequential(Block(32,64,2),Block(64,64),Block(64,64));self.avgpool=nn.AdaptiveAvgPool2d((1,1));self.fc=nn.Linear(64,10)
def forward(self,x):
x=self.relu(self.bn1(self.conv1(x)));x=self.layer3(self.layer2(self.layer1(x)));return self.fc(self.avgpool(x).flatten(1))
class VGG11(nn.Module):
def __init__(self):
super().__init__();layers=[];channels=3
for n in [64,'M',128,'M',256,256,'M',512,512,'M',512,512,'M']:
if n=='M':layers.append(nn.MaxPool2d(2))
else:layers.extend([nn.Conv2d(channels,n,3,padding=1),nn.BatchNorm2d(n),nn.ReLU(inplace=True)]);channels=n
self.features=nn.Sequential(*layers);self.classifier=nn.Sequential(nn.Linear(512,512),nn.ReLU(True),nn.Dropout(),nn.Linear(512,512),nn.ReLU(True),nn.Dropout(),nn.Linear(512,10))
def forward(self,x):return self.classifier(self.features(x).flatten(1))
class Pixels(nn.Module):
def __init__(self,base):
super().__init__();self.base=base
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.base((x-self.mean)/self.std)
def state(path,url):
return torch.load(path,map_location='cpu',weights_only=True) if path else torch.hub.load_state_dict_from_url(url,map_location='cpu',check_hash=True)
r=ResNet20();v=VGG11();r.load_state_dict(state(RPATH,RURL),strict=True);v.load_state_dict(state(VPATH,VURL),strict=True)
model=Pixels(r).to(DEVICE).eval();other=Pixels(v).to(DEVICE).eval()
dataset=datasets.CIFAR10(ROOT,train=False,transform=transforms.ToTensor(),download=not LOCAL)
loader=DataLoader(Subset(dataset,range(64)),batch_size=16,shuffle=False)
x,y=next(iter(DataLoader(Subset(dataset,range(64)),batch_size=64)));x=x.to(DEVICE);y=y.to(DEVICE)
@torch.no_grad()
def predict(m,x):return m(x).argmax(1)
def pgd_final(m,x,y,eps,alpha,steps):
a=x.detach().clone()
for _ in range(steps):
a.requires_grad_(True);loss=F.cross_entropy(m(a),y);g=torch.autograd.grad(loss,a)[0]
a=(a.detach()+alpha*g.sign()).clamp(x-eps,x+eps).clamp(0,1)
return a.detach()
def pgd_best(m,x,y,eps,alpha,steps,restarts):
best=x.detach().clone()
with torch.no_grad():best_loss=F.cross_entropy(m(best),y,reduction='none');best_bad=predict(m,best)!=y
for r in range(restarts):
a=x.clone() if r==0 else (x+torch.empty_like(x).uniform_(-eps,eps)).clamp(0,1)
for _ in range(steps):
a.requires_grad_(True);loss=F.cross_entropy(m(a),y);g=torch.autograd.grad(loss,a)[0]
a=(a.detach()+alpha*g.sign()).clamp(x-eps,x+eps).clamp(0,1)
with torch.no_grad():
logits=m(a);values=F.cross_entropy(logits,y,reduction='none');bad=logits.argmax(1)!=y
take=(bad & ~best_bad)|((bad==best_bad)&(values>best_loss))
best[take]=a[take];best_loss[take]=values[take];best_bad[take]=bad[take]
return best.detach()
eps=8/255;alpha=2/255;steps=10
own_one=pgd_final(model,x[:16],y[:16],eps,alpha,1)
ref_one=torchattacks.PGD(model,eps=eps,alpha=alpha,steps=1,random_start=False)(x[:16],y[:16])
diff_one=(own_one-ref_one).abs().max().item();assert diff_one<1e-6
own=pgd_final(model,x[:16],y[:16],eps,alpha,steps)
reference=torchattacks.PGD(model,eps=eps,alpha=alpha,steps=steps,random_start=False)(x[:16],y[:16])
diff=(own-reference).abs().max().item()
assert (reference-x[:16]).abs().max().item()<=eps+1e-6
print('torchattacks',torchattacks.__version__,'max diff un paso',diff_one,'max diff diez pasos',diff,
'acuerdos etiquetas',int((predict(model,own)==predict(model,reference)).sum()),'/16',flush=True)
with torch.no_grad():clean=predict(model,x);clean2=predict(other,x)
torch.manual_seed(24);adv=pgd_best(model,x,y,eps,alpha,steps,3)
assert (adv-x).abs().max().item()<=eps+1e-6 and adv.min().item()>=0 and adv.max().item()<=1
with torch.no_grad():p1=predict(model,adv);p2=predict(other,adv)
print('ResNet limpia',float((clean==y).float().mean()),'robusta PGD',float(((clean==y)&(p1==y)).float().mean()),
'VGG limpia',float((clean2==y).float().mean()),'VGG frente a transferencia',float(((clean2==y)&(p2==y)).float().mean()),'n',len(y),flush=True)
# Solo etiquetas: busca un punto de otra clase y biseca el segmento; no es HopSkipJump.
def decision_boundary(m,original,label,pool,budget=40):
queries=1
if int(predict(m,original).item())!=int(label):return None,queries
high=None
for candidate in pool:
if queries>=budget:break
z=candidate[None];queries+=1
if int(predict(m,z).item())!=int(label):high=z.clone();break
if high is None:return None,queries
low=original.clone()
while queries<budget:
middle=(low+high)/2;queries+=1
if int(predict(m,middle).item())!=int(label):high=middle
else:low=middle
return float(torch.linalg.vector_norm(high-original).item()),queries
for index in range(4):
distance,queries=decision_boundary(model,x[index:index+1],y[index],x,budget=40)
print('solo etiqueta',index,'L2',distance,'consultas',queries,flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. What bound does each term gᵢδᵢ have with |δᵢ| ≤ ε?
import numpy as np
def project_linf(x, x0, eps):
pass
def project_l2(x, x0, eps):
passimport numpy as np
def pgd_attack(model_grad, x, y, eps, alpha, steps, restarts, norm):
pass