Defenses: adversarial training and honest evaluation
Develop adversarial training as robust optimization, alongside TRADES, fast training, and robust and catastrophic overfitting. Study careful evaluation: gradient masking, BPDA and EOT, and adaptive attack protocols with AutoAttack and RobustBench.
After this lesson you can
- Formulate the adversarial training as a minimax problem and justify the gradient used with Danskin.
- Train with PGD-AT, fast training, and TRADES on the local GPU and compare their robustness-accuracy frontiers.
- Detect robust and catastrophic overfitting and apply early stopping.
- Recognize the signals of gradient masking and break defenses with BPDA and EOT.
- Evaluate the model with AutoAttack and communicate its robustness with your full threat model.
Before you start
- 30Projected gradient descent attackLp and semantic threat modelsAdversarial transferabilityQuery-based black-box attacks
- 06Min-max problems and saddle pointsStochastic gradient descent
- 13Generalization gapSample complexity
- 00PyTorch learning rate schedulers
- 15Batch normalization
- 07Kullback-Leibler divergence (relative entropy)
Training for the worst-case approximation
A defense should be evaluated against attacks that know how it works, as well as the attack used to design it. Adversarial training turns the training loss into a minimax problem: for each example, first search for an allowed perturbation, then update the model to reduce the loss on that input.
The set specifies the threat: norm, radius, pixel range, and other constraints. Changing this set changes the property being learned. For a non-convex network, the inner optimization is usually approximated with PGD rather than solved by an exact oracle. The resulting defense is empirical and depends on both the threat and training budget. Madry and colleagues studied this approach as robust optimization.
In the figure’s example, the clean loss is minimized at , while the maximum over is minimized at . This function was constructed to visualize the operation; it is not an estimated network loss surface. The inner maximum lies at an endpoint because the function is convex in ; a real network can have multiple local maxima.
Proof
As varies, evaluating the new maximum at the old maximizer gives a lower bound on the difference between envelopes; evaluating the old maximum at a new maximizer gives an upper bound. Continuity and uniqueness make both difference quotients converge to the same partial derivative. There is no need to differentiate through in this case. With several maximizers, the envelope may be non-differentiable and its directional derivatives depend on the active gradients.
∎With finite PGD, an approximate candidate is used and is treated as fixed during the outer update. The gradient calculated is that of the loss at that candidate, not necessarily the gradient of the true envelope. Differentiating through all attack iterations defines another operation and requires justifying it; simply forgetting that the maximum is approximate can lead to over-interpreting a training curve.
What guarantees the derivation and what does not
Danskin’s result answers a local question about the exact envelope. The inner set must remain fixed as the outer parameter varies; if the allowed set depended on θ, additional terms could appear. Continuity and uniqueness allow identifying a single active gradient. At a point where two perturbations reach the same maximum, as can occur in the figure with θ equal to zero, different directions can activate different extrema and the envelope can have a corner.
In actual training, PGD provides , without proving that . Treating as constant is a useful algorithmic choice, but replaces the exact objective with the loss the attack has found at that point. With a weak attack, the model can improve against that procedure while remaining vulnerable to another. Searching for stronger examples competes with the number of outer steps available, so the total budget is part of the comparison.
PGD-AT, fast training and failures
PGD-AT generates examples with several projected steps and trains on them. Fast training uses a single FGSM step with random initialization to reduce cost. Wong and colleagues studied this regime and catastrophic overfitting: the training attack can stop representing stronger attacks, while robustness measured with PGD drops abruptly. Low training loss does not rule this out; monitor a stronger validation attack, with different step and restart counts, throughout the run.
Robust generalization and robust overfitting can also deteriorate without the abrupt collapse associated with one-step training. Rice and colleagues observed declining test robustness during adversarial training in their experiments. Early stopping selects an epoch using independent validation and reserves the test set for the end. Repeatedly using the test set to choose the epoch makes it cease to be an independent evaluation.
The curves use a single seed, 512 training images, and a small model from scratch during four epochs. The training curve is calculated on 64 images and the validation curve on 128 others; both use a seven-step PGD with two starts. In one recipe, it is observed that the best validation appears before the end, but this small trial does not establish a law of overfitting nor does it necessarily show a catastrophic collapse. The high rate and low rate are two discrete executions, not an interpolation of hypothetical results.
Early stopping without looking at the test
In each epoch, a checkpoint can be saved and a robust measure evaluated on validation with a defined attack before observing the results. Selecting the best checkpoint uses validation information, so that figure is no longer an impartial final evaluation. The test is reserved for the selected model and reported along with the number of epochs evaluated and the tie-breaking rule. If several checkpoints tie, systematically choosing the first one avoids a later selection based on the test.
Robust overfitting refers to a gap between training and unseen data under a specific threat; the catastrophic drop associated with fast training describes a particular pathology of one-step attack. A noisy curve of four epochs over 128 images can rise or fall due to sample variation and does not identify the mechanism by itself. To investigate that mechanism, more epochs, seeds, sufficient validation attacks, and, if applicable, separate training and test curves are needed.
TRADES and the trade-off between objectives
TRADES separates natural loss from a penalty on prediction changes within the threat model:
The first KL argument is the clean distribution and the second is the perturbed distribution. The parameter controls this term’s weight, but its effect depends on architecture, data, optimizer, and inner attack. The clean distribution can be held fixed during the inner search; for the outer update, state whether gradients flow through both branches. In the lab, clean probabilities are fixed during the search, while both branches participate in the outer loss. Zhang and colleagues relate natural loss and boundary regularization through a theoretical trade-off under explicit assumptions.
The relationship between clean and robust accuracy does not imply a universal rule that every robustness gain reduces clean accuracy. Tsipras and colleagues construct a problem with such a tension; Schmidt and colleagues analyze the data requirements for robust generalization in specific models. Comparing training recipes requires controlling the budget, selection procedure, and dataset. Additional data can help in some settings, but its quality and possible overlap with the test set matter.
The outline identifies non-dominated points among those shown: a point dominates another if it matches or improves both metrics and strictly improves at least one. A sample of five recipes does not establish the true frontier across all models. The values use 128 test images, one seed, and four epochs, with the epoch chosen by robust validation. The evaluation attack uses seven steps and two restarts; its failures can underestimate actual vulnerability.
Comparisons with the same budget
To compare β values, specify the architecture, splits, optimizer, and computation spent generating adversarial examples. The KL term and cross-entropy are averaged over the batch; using a sum in one implementation and a mean in another changes the effective scale of β. It also matters whether the clean distribution is fixed during inner optimization and which branches receive gradients in the outer step.
The points in the graph use the best epoch according to robust validation, not necessarily the one with the highest clean accuracy. This favors a specific question and does not demonstrate that all points are equally well-fitted. With 128 examples, changing one prediction modifies the accuracy by approximately 0.78 percentage points. Differences of one or two images should be interpreted with caution and repeated on more data and seeds before drawing conclusions.
Detect misleading gradients
Gradient masking occurs when an attack using the available gradient fails because its signal is unusable, rather than because adversarial perturbations do not exist. Quantization has zero derivative almost everywhere; JPEG processing followed by integer conversion also offers no useful derivative; a random transformation can produce noisy gradients. Very small gradients or one-step attacks that appear stronger than iterative attacks are signals to investigate, rather than automatic proof of a broken defense.
The figure uses the two MLPs of digits from the previous lesson. Quantization, JPEG quality 15, and random resizing convert to integers and leave an exact zero gradient almost everywhere in this implementation. Distillation is a temperature 10 imitation of a standard teacher, not a full reproduction of all defensive distillation recipes. Adversarial training is an additional brief training with three-step PGD. 40 test images are measured, in and eight paired evaluation realizations. The score-based attack uses 40 queries during the search; the final evaluation uses additional realizations. The numbers are results of this trial, not universal properties of the defenses.
BPDA conserves the actual preprocessed input in the forward pass and replaces its derivative with a useful approximation backward, like the identity. It is a deliberate approximation: the resulting gradient is not the exact derivative of JPEG or rounding. In a random transformation, EOT approximates the gradient of the expected loss by averaging several realizations; more samples reduce Monte Carlo noise but increase cost. If both techniques are combined, gradients of substitutes for the sampled transformations are averaged. No number in this figure certifies that the worst case was found.
A practical warning arises when a black-box attack with a reasonable budget finds more failures than a supposedly better-informed white-box attack, or when increasing iterations inexplicably improves estimated robustness. Check the range, normalization, loss, derivatives, and whether the attack actually sees the full defense. For a randomized defense, decide whether to measure expected accuracy, majority vote, or a failure probability; these are different objectives. The figure’s eight paired realizations average the indicator that both the clean and attacked inputs are classified correctly under the same realization; they do not estimate every notion of failure for a randomized model.
What does a stochastic evaluation count?
A defense that samples a transformation has no single output for an image unless its seed is fixed. You may want the probability of a correct prediction in one run, the majority decision over several runs, or the probability that at least one run fails. Each objective requires a different loss and budget. Pairing random draws for clean and attacked inputs, as in the figure, estimates the chosen indicator under those draws; it does not establish behavior for every realization.
In BPDA, substituting the derivative by identity can help the attacker even when it is a poor approximation in some region. It is advisable to test other approximations and independent attacks, and verify the success with the actual preprocessing in the forward pass. In EOT, increasing the gradient samples improves the estimation at the cost of more evaluations; if there is a query limit, each sample counts. The absence of success after a single adaptive attack remains absence of evidence, not a proof of robustness.
Adaptive evaluation and reporting
Adaptive evaluation tailors the attack to each defense component and checks its assumptions. Tramèr and colleagues analyzed defenses whose adaptive evaluation remained incomplete. Compare losses, step counts, restarts, and gradient-free attacks; check the range and measure time and queries. Detecting gradient masking does not itself determine actual robustness: it shows that the initial attack is insufficient.
AutoAttack combines various attacks to reduce dependence on a single configuration, and RobustBench provides protocols and comparable models under concrete threats. Its results remain empirical and do not replace an adaptive evaluation for a defense that uses randomness, detection, or special preprocessing. When reporting, include dataset and partition, clean accuracy, norm and ε in pixel units, attack and version, steps, restarts, seeds, queries, epoch selection, and number of examples.
NumPy Laboratory: BPDA and EOT
An MLP is trained on synthetic augmentations of ten digit templates. The test uses different augmentations of those same templates, so it is not independent of the original images; four augmentations are selected per class. The defense rounds to four intervals and can add uniform noise. From a clean start, the exact rounding derivative is zero almost everywhere; BPDA uses the identity backward, and EOT averages several realizations. The lab includes transfer from another MLP and a score-based search. The result illustrates masking in this example, rather than breaking every possible defense.
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 predict(m,x):return forward(m,x)[1].argmax(axis=1)
def grad(m,x,y):
h,q=forward(m,x);q[np.arange(len(y)),y]-=1
return ((q@m[2].T)*(h>0))@m[0].T
def preprocess(x,noise,rng):
# Cuantización por cuatro intervalos, con ruido opcional antes de cuantizar.
return np.round(np.clip(x+rng.uniform(-noise,noise,x.shape),0,1)*4)/4
def eval_acc(x,y,noise,seed=999,draws=8):
r=np.random.default_rng(seed);return np.mean([np.mean(predict(p,preprocess(x,noise,r))==y) for _ in range(draws)])
def bpda_attack(x,y,eps,noise,samples,seed=71):
# BPDA: en el forward usa cuantización; en backward sustituye su derivada por identidad.
r=np.random.default_rng(seed);a=x.copy()
for _ in range(12):
g=np.zeros_like(a)
for _ in range(samples):g+=grad(p,preprocess(a,noise,r),y)/samples
a=np.clip(np.clip(a+(eps/4)*np.sign(g),x-eps,x+eps),0,1)
return a
def transfer(x,y,eps):
a=x.copy()
for _ in range(12):a=np.clip(np.clip(a+(eps/4)*np.sign(grad(q,a,y)),x-eps,x+eps),0,1)
return a
def score_attack(x,y,eps,noise,budget=40):
# Cada consulta devuelve una puntuación; cuatro consultas por candidato y diez candidatos.
r=np.random.default_rng(91);a=x.copy()
def score(v):
vals=[]
for _ in range(4):
_,prob=forward(p,preprocess(v,noise,r));vals.append(prob[np.arange(len(y)),y])
return np.mean(vals,axis=0)
best=score(a)
for _ in range(budget//4-1):
cand=a.copy()
for i in range(len(x)):
row=int(r.integers(0,7));col=int(r.integers(0,7));sgn=r.choice([-1.,1.]);patch=cand[i].reshape(8,8);orig=x[i].reshape(8,8)
patch[row:row+2,col:col+2]=orig[row:row+2,col:col+2]+sgn*eps
cand=np.clip(cand,0,1);v=score(cand);take=v<best;a[take]=cand[take];best[take]=v[take]
return a
idx=np.concatenate([np.arange(8*d,8*d+4) for d in range(10)])
x=Xt[idx];y=Yt[idx];eps=.15
print('ejemplos',len(y),'epsilon L∞',eps,'pasos',12,'sin reinicios')
for noise in (0.,.05):
clean=eval_acc(x,y,noise)
# La derivada exacta de round es cero casi en todas partes; con inicio limpio PGD no se mueve.
naive=x.copy();bpda=bpda_attack(x,y,eps,noise,1);eot=bpda_attack(x,y,eps,noise,8);trans=transfer(x,y,eps);black=score_attack(x,y,eps,noise)
for name,a in [('limpio',x),('PGD gradiente real',naive),('BPDA',bpda),('BPDA+EOT',eot),('transferencia',trans),('puntuaciones',black)]:
assert np.max(np.abs(a-x))<=eps+1e-9 and np.all((a>=0)&(a<=1))
print('ruido',noise,'método',name,'exactitud promedio',round(eval_acc(a,y,noise),4))Local Lab: Training and AutoAttack
The cell trains from scratch a small residual network with group normalization on CIFAR-10: standard, FGSM with random start, a high-learning-rate variant, PGD-AT, and TRADES with β equal to 1, 3, and 6. It uses 512 training images, 128 for validation, and 128 for test, a seed, and four epochs by default. All receive the same partitions and a learning rate drop at mid-training. The internal attack uses three steps in PGD-AT and TRADES; the fast uses one and keeps the best candidate against the clean input. To evaluate, PGD uses seven steps and two starts. The pixels are restricted in and the normalization occurs within the model.
The best epoch is chosen by robust validation and the test is evaluated once per recipe. This size and duration are a functional test, not a competitive comparison nor conclusive evidence of convergence, overfitting, or collapse. In the recorded execution, the PGD-AT selected model obtained 28 of 128 correct clean predictions and 26 of 128 against the evaluation PGD. The accuracy of the other recipes is shown in the figure; changing architecture, seeds, steps, or data can change the order.
Finally, the official standard version of AutoAttack runs on up to four test images that PGD-AT classified correctly. In one run, three of these four remained correct after the attack suite; this conditional selection does not represent 75% robustness on CIFAR-10. The output lists the attacks and surviving examples. The code uses BF16 for the outer update if supported by the GPU, but evaluates attacks in FP32. In a repeat of training and PGD evaluation with AutoAttack omitted, PyTorch recorded peak allocated memory of 0.100 GiB and reserved memory of 0.121 GiB on RTX 3060. This does not measure AutoAttack’s peak or necessarily include the driver context or other processes; it does not guarantee that the full workflow fits on any 8 GB GPU. Time and memory also depend on batch size and implementation.
The lab requires PyTorch, torchvision, and the official autoattack package; install the latter following its repository instructions and add its folder to the Python environment. Use CIFAR_ROOT and CIFAR_LOCAL_ONLY=1 to select local data when available. Standard AutoAttack evaluation can take several minutes even for four images. For a quick training-only check, set AT_SKIP_AUTOATTACK=1; in that case AutoAttack has not run and must not be reported as completed.
import os, json, copy, time, random
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader,Subset
from torchvision import datasets,transforms
from autoattack import AutoAttack
ROOT=os.environ.get('CIFAR_ROOT','./data/cifar10');LOCAL=os.environ.get('CIFAR_LOCAL_ONLY','0')=='1'
EPOCHS=int(os.environ.get('AT_EPOCHS','4'));DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
if DEVICE=='cuda':torch.cuda.reset_peak_memory_stats()
USE_BF16=DEVICE=='cuda' and torch.cuda.is_bf16_supported()
torch.set_num_threads(4);eps=8/255;alpha=2/255
class Residual(nn.Module):
def __init__(self,cin,cout,stride=1):
super().__init__();self.a=nn.Conv2d(cin,cout,3,stride,1,bias=False);self.na=nn.GroupNorm(4,cout);self.b=nn.Conv2d(cout,cout,3,1,1,bias=False);self.nb=nn.GroupNorm(4,cout)
self.skip=nn.Identity() if cin==cout and stride==1 else nn.Conv2d(cin,cout,1,stride,bias=False)
def forward(self,x):return F.relu(self.nb(self.b(F.relu(self.na(self.a(x)))))+self.skip(x))
class SmallResNet(nn.Module):
def __init__(self):
super().__init__();self.head=nn.Conv2d(3,16,3,padding=1,bias=False);self.blocks=nn.Sequential(Residual(16,16),Residual(16,32,2),Residual(32,64,2));self.fc=nn.Linear(64,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):
z=(x-self.mean)/self.std;z=self.blocks(self.head(z));return self.fc(z.mean(dim=(2,3)))
def attack(m,x,y,steps,alpha,random_start=True,restarts=1):
# Evalúa en FP32; el ataque devuelve el mejor candidato, priorizando errores.
best=x.detach().clone()
with torch.no_grad():
z=m(best);score=F.cross_entropy(z,y,reduction='none');bad=z.argmax(1)!=y
for r in range(restarts):
a=(x+torch.empty_like(x).uniform_(-eps,eps)).clamp(0,1) if random_start else x.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)
with torch.no_grad():
z=m(a);s=F.cross_entropy(z,y,reduction='none');is_bad=z.argmax(1)!=y
take=(is_bad & ~bad)|((is_bad==bad)&(s>score));best[take]=a[take];score[take]=s[take];bad[take]=is_bad[take]
return best.detach()
def trades_attack(m,x,steps=3):
with torch.no_grad():p=F.softmax(m(x),dim=1)
a=(x+torch.empty_like(x).uniform_(-eps,eps)).clamp(0,1)
for _ in range(steps):
a.requires_grad_(True);kl=F.kl_div(F.log_softmax(m(a),dim=1),p,reduction='batchmean');g=torch.autograd.grad(kl,a)[0]
a=(a.detach()+alpha*g.sign()).clamp(x-eps,x+eps).clamp(0,1)
return a.detach()
def evaluate(m,loader):
m.eval();correct=robust=total=0
for x,y in loader:
x,y=x.to(DEVICE),y.to(DEVICE)
with torch.no_grad():clean=m(x).argmax(1)==y
a=attack(m,x,y,steps=7,alpha=alpha,random_start=True,restarts=2)
with torch.no_grad():ok=m(a).argmax(1)==y
correct+=int(clean.sum());robust+=int((clean&ok).sum());total+=len(y)
return correct/total,robust/total
data_train=datasets.CIFAR10(ROOT,train=True,transform=transforms.ToTensor(),download=not LOCAL)
data_test=datasets.CIFAR10(ROOT,train=False,transform=transforms.ToTensor(),download=False)
training=Subset(data_train,range(512));val=Subset(data_train,range(512,640));test=Subset(data_test,range(128))
train_eval=DataLoader(Subset(data_train,range(64)),batch_size=64,shuffle=False)
val_loader=DataLoader(val,batch_size=64,shuffle=False);test_loader=DataLoader(test,batch_size=64,shuffle=False)
results={};models={}
for mode,beta,base_lr in [('standard',0,.05),('fast',0,.05),('fast_large',0,.2),('pgd',0,.05),('trades1',1,.05),('trades3',3,.05),('trades6',6,.05)]:
random.seed(24);np.random.seed(24);torch.manual_seed(24);torch.cuda.manual_seed_all(24)
m=SmallResNet().to(DEVICE);opt=torch.optim.SGD(m.parameters(),lr=base_lr,momentum=.9,weight_decay=5e-4)
gen=torch.Generator().manual_seed(24);loader=DataLoader(training,batch_size=64,shuffle=True,generator=gen,num_workers=0)
best_score=-1.;best_state=None;best_epoch=0;history=[];start=time.perf_counter()
for epoch in range(EPOCHS):
lr=base_lr*(.1 if epoch>=max(1,EPOCHS//2) else 1.)
for group in opt.param_groups:group['lr']=lr
m.train()
for x,y in loader:
x,y=x.to(DEVICE),y.to(DEVICE)
if mode=='standard':a=x
elif mode.startswith('fast'):a=attack(m,x,y,steps=1,alpha=1.25*eps,random_start=True,restarts=1)
elif mode=='pgd':a=attack(m,x,y,steps=3,alpha=alpha,random_start=True,restarts=1)
else:a=trades_attack(m,x)
opt.zero_grad()
with torch.autocast(device_type=DEVICE,dtype=torch.bfloat16,enabled=USE_BF16):
if beta:
clean_logits=m(x);adv_logits=m(a);loss=F.cross_entropy(clean_logits,y)+beta*F.kl_div(F.log_softmax(adv_logits.float(),dim=1),F.softmax(clean_logits.float(),dim=1),reduction='batchmean')
else:loss=F.cross_entropy(m(a),y)
loss.backward();opt.step()
train_clean,train_rob=evaluate(m,train_eval);val_clean,val_rob=evaluate(m,val_loader)
row={'epoch':epoch+1,'lr':lr,'train_clean':train_clean,'train_robust':train_rob,'val_clean':val_clean,'val_robust':val_rob};history.append(row)
if val_rob>best_score:best_score=val_rob;best_epoch=epoch+1;best_state=copy.deepcopy(m.state_dict())
print(mode,row,flush=True)
m.load_state_dict(best_state);tc,tr=evaluate(m,test_loader)
results[mode]={'history':history,'best_epoch':best_epoch,'test_clean':tc,'test_robust':tr,'seconds':round(time.perf_counter()-start,1)}
models[mode]=m.cpu();print('selected',mode,results[mode],flush=True)
# Suite estándar oficial en hasta cuatro imágenes del test correctamente clasificadas por PGD-AT.
m=models['pgd'].to(DEVICE).eval();tx,ty=next(iter(DataLoader(test,batch_size=128,shuffle=False)));tx,ty=tx.to(DEVICE),ty.to(DEVICE)
with torch.no_grad():correct=(m(tx).argmax(1)==ty).nonzero().flatten()
chosen=correct[:4]
if len(chosen) and os.environ.get('AT_SKIP_AUTOATTACK','0')!='1':
xa,ya=tx[chosen],ty[chosen];runner=AutoAttack(m,norm='Linf',eps=eps,version='standard',seed=24,device=DEVICE,verbose=True)
attacked=runner.run_standard_evaluation(xa,ya,bs=len(chosen))
assert (attacked-xa).abs().max().item()<=eps+1e-6
with torch.no_grad():aa=int((m(attacked).argmax(1)==ya).sum())
print('autoattack estándar condicional',aa,'/',len(chosen),'indices',chosen.tolist(),flush=True)
results['autoattack']={'correct':aa,'n':len(chosen),'indices':chosen.tolist(),'version':'standard','eps':eps}
elif os.environ.get('AT_SKIP_AUTOATTACK','0')=='1':
print('autoattack omitido por AT_SKIP_AUTOATTACK=1',flush=True);results['autoattack']={'skipped':True}
else:
print('autoattack: sin aciertos limpios para seleccionar',flush=True);results['autoattack']={'n':0}
print('RESULT_JSON',json.dumps(results),flush=True)
if DEVICE=='cuda':print('pico memoria asignada y reservada GiB',round(torch.cuda.max_memory_allocated()/2**30,3),round(torch.cuda.max_memory_reserved()/2**30,3),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. What happens when evaluating the new loss on the old maximizer?
import torch
def bpda_wrapper(preprocess):
passimport torch
import torch.nn.functional as F
def pgd_at_step(model,x,y,eps,alpha,steps,optimizer):
pass