AI Logic

Adversarial Attacks and Defenses

TRADES

Updated:

Diagram of TRADES. Left: one training step (mini-batch, start right next to x, K repetitions of a gradient step that widens the output gap and projection onto the ε-ball, loss as the sum of two terms, weight update). Upper right: a 2D sketch with points and ε squares showing that robust error is the sum of natural error and boundary error. Lower right: a plot of Table 4 of the paper on CIFAR-10, where increasing 1/λ lowers accuracy on the original data and raises accuracy under PGD

What is TRADES

TRADES is an adversarial training method that tunes the trade-off between correctness on the original input (accuracy) and resistance to perturbations (robustness) with a single coefficient. Its loss is the sum of "the classification loss on the original input" and "how much the model's output differs between the original input and a nearby adversarial example." Zhang, Yu, Jiao, Xing, El Ghaoui, and Jordan proposed it in 2019, and it was presented at ICML 2019. The name stands for TRadeoff-inspired Adversarial DEfense via Surrogate-loss minimization.

Adversarial training with PGD was known to improve robustness at the cost of accuracy on the original data. The paper analyzes this "trade-off between robustness and accuracy" theoretically, starting from the following decomposition.

Rrob(f)=Rnat(f)+Rbdy(f)\mathcal{R}_{\mathrm{rob}}(f) = \mathcal{R}_{\mathrm{nat}}(f) + \mathcal{R}_{\mathrm{bdy}}(f)
  • Robust error Rrob\mathcal{R}_{\mathrm{rob}}: The fraction of inputs that have a misclassified point somewhere within ε\varepsilon of them.
  • Natural error Rnat\mathcal{R}_{\mathrm{nat}}: The fraction of original inputs that are themselves misclassified (the ordinary error rate).
  • Boundary error Rbdy\mathcal{R}_{\mathrm{bdy}}: The fraction of inputs that are classified correctly but have the decision boundary within ε\varepsilon.

The first term of the TRADES loss works to reduce the natural error, and the second term works to reduce the boundary error. The second term keeps the output from changing abruptly around the data, which pushes the decision boundary away from the data. The left side of the header figure shows one training step, the upper right sketches this decomposition, and the lower right shows how accuracy and robustness change with the coefficient (Table 4 in the paper).

This method is the basis of the entry that took first place among about 2,000 submissions in the defense track of the NeurIPS 2018 Adversarial Vision Challenge.

The TRADES loss and training procedure

The paper first gives, for binary classification, a differentiable upper bound on the gap between the robust error and the optimal natural error (Theorem 3.1). ϕ\phi is a surrogate loss used for classification (one satisfying a condition called classification-calibrated, such as the hinge loss), f(X)f(X) is the model's score, and Y∈{−1,+1}Y \in \{-1, +1\} is the label.

Rrob(f)−Rnat∗≤ψ−1(Rϕ(f)−Rϕ∗)+Emax⁡X′∈B(X,ε)ϕ(f(X′)f(X)/λ)\mathcal{R}_{\mathrm{rob}}(f) - \mathcal{R}^*_{\mathrm{nat}} \le \psi^{-1}\big(\mathcal{R}_\phi(f) - \mathcal{R}^*_\phi\big) + \mathbb{E} \max_{X' \in \mathbb{B}(X, \varepsilon)} \phi\big(f(X') f(X) / \lambda\big)

The first term on the right-hand side corresponds to the natural error, and the second to the boundary error. The paper also shows that, as a bound holding for every distribution, this bound cannot be made any tighter (Theorem 3.2).

Extending this bound to multiclass classification and replacing ϕ\phi with cross-entropy LL gives the TRADES loss.

min⁡f E{L(f(X),Y)+max⁡X′∈B(X,ε)L(f(X),f(X′))/λ}\min_{f} \ \mathbb{E} \Big\{ L\big(f(X), Y\big) + \max_{X' \in \mathbb{B}(X, \varepsilon)} L\big(f(X), f(X')\big) / \lambda \Big\}

f(X)f(X) is the output vector after softmax, YY is the vector representing the label, and B(X,ε)\mathbb{B}(X, \varepsilon) is the region within ε\varepsilon of XX. The larger 1/λ1/\lambda, the more weight on the robustness term.

The training procedure (Algorithm 1 in the paper) is as follows.

  1. Take a mini-batch {x1,…,xm}\{x_1, \dots, x_m\}.
  2. Add small Gaussian noise to each xix_i to make the starting point xi′=xi+0.001⋅N(0,I)x'_i = x_i + 0.001 \cdot \mathcal{N}(0, I).
  3. Take a step of size η1\eta_1 along the gradient's sign in the direction that increases L(f(xi),f(xi′))L(f(x_i), f(x'_i)), and project onto the ε\varepsilon-ball around xix_i. Repeat this KK times.
  4. Update the weights with learning rate η2\eta_2 using the average of the loss L(f(xi),yi)+L(f(xi),f(xi′))/λL(f(x_i), y_i) + L(f(x_i), f(x'_i)) / \lambda.
  5. Repeat steps 1–4 until training converges.

Step 2 adds small noise because at xi′=xix'_i = x_i the second term is at its minimum (the output gap is 0) and its gradient is also 0, so step 3 could not get started. Unlike PGD, which starts from uniform noise inside the ε\varepsilon-ball, TRADES starts very close to the input.

Since the second term does not use the label yy, it can be computed even for unlabeled data. The paper points out that the method extends directly to semi-supervised learning. The authors' public implementation uses the KL divergence KL(f(x) ∥ f(x′))\mathrm{KL}\big(f(x) \,\|\, f(x')\big) for the second term and writes the coefficient as β=1/λ\beta = 1/\lambda.

Why it balances accuracy and robustness more easily

Adversarial training with PGD (Madry et al.) solves the following problem.

min⁡f E{max⁡X′∈B(X,ε)ϕ(f(X′)Y)}\min_{f} \ \mathbb{E} \Big\{ \max_{X' \in \mathbb{B}(X, \varepsilon)} \phi\big(f(X') Y\big) \Big\}

This is an upper bound on the robust error, but the paper points out that for complex problems this bound may be loose and cannot express the trade-off between accuracy and robustness. TRADES differs in two ways.

  • It separates the terms: TRADES puts the loss on the original input (for accuracy) and the loss on output change (for robustness) in separate terms, weighted by 1/λ1/\lambda. Adversarial training with PGD has no such knob.
  • The second term is the gap to "the output on the original input," not to "the label": Instead of matching the adversarial example's output to the label, it pulls it toward the output on the original input. This directly smooths the model's output around the data and pushes the boundary away from it.

A small example in the paper shows that this trade-off is unavoidable. For inputs uniformly distributed on 0–1 whose class alternates every interval of width ε\varepsilon, the optimal (Bayes-optimal) classifier has natural error 0, but because every point has a boundary within ε\varepsilon, its robust error is 1. A classifier that always answers "positive" has both natural and robust error of 1/2. Optimizing accuracy alone gives the worst robustness, and vice versa. The TRADES loss approaches the former as λ→∞\lambda \to \infty and the latter as λ→0\lambda \to 0.

Another method that penalizes the gap between outputs on the original input and the adversarial example is Adversarial Logit Pairing (ALP). The paper notes the differences: ALP uses an ℓ2 loss on the output gap and builds adversarial examples with the label loss, whereas TRADES uses a loss derived from theory and also builds adversarial examples to maximize the output gap.

Experimental results

Effect of the coefficient 1/λ1/\lambda. Results of varying 1/λ1/\lambda on CIFAR-10 (ResNet-18, ε=0.031\varepsilon = 0.031) (Table 4 in the paper; robustness evaluated with 20-step PGD).

1/λ1/\lambdaAccuracy on original test dataAccuracy under PGD
0.191.31%26.53%
1.087.01%44.68%
2.085.22%48.22%
5.081.72%50.64%

Increasing 1/λ1/\lambda raises robustness and lowers accuracy. On MNIST, accuracy barely dropped (99.41% → 99.16%). The paper suggests that setting 1/λ1/\lambda between 1 and 10 trains models with both high accuracy and high robustness.

Comparison with other defenses. Below are some results comparing accuracy under white-box PGD attacks on CIFAR-10 (WRN-34-10, ℓ∞ with ε=0.031\varepsilon = 0.031) and MNIST (ε=0.3\varepsilon = 0.3) (Table 5 in the paper).

DataDefenseOriginal test dataPGD attack
CIFAR-10Adversarial training with PGD (Madry et al.)87.30%47.04%
CIFAR-10TRADES (1/λ=11/\lambda = 1)88.64%49.14%
CIFAR-10TRADES (1/λ=61/\lambda = 6)84.92%56.61%
MNISTAdversarial training with PGD (Madry et al.)99.36%96.01%
MNISTTRADES (1/λ=61/\lambda = 6)99.48%96.07%

On CIFAR-10, 1/λ=11/\lambda = 1 beat Madry et al. in both accuracy and robustness, and 1/λ=61/\lambda = 6 gave up a little accuracy to gain about 10 points of robustness. Even with PGD increased to 1,000 steps, 1/λ=61/\lambda = 6 held 56.43%. This contrasts with many gradient-masking defenses, which dropped to 0–9% under the attacks of Athalye et al. (2018) at the same ε\varepsilon.

Competition. In the defense track of the NeurIPS 2018 Adversarial Vision Challenge (Tiny ImageNet, 200 classes, black-box attacks), a ResNet trained with TRADES took first place with an average ℓ2 perturbation size of 2.256 needed for misclassification, 11.41% above second place (2.025).

Caveats

Computation is about as heavy as adversarial training with PGD. Every weight update builds adversarial examples with KK gradient computations (10 in the paper's CIFAR-10 setup). The paper also notes that adversarial training is often more than 10 times slower than standard training. In addition, the robustness applies within the ε\varepsilon and distance (such as ℓ∞) chosen for training; robustness to other perturbations is not guaranteed.

  • Choosing 1/λ1/\lambda: Make it small to favor accuracy and large to favor robustness. The paper's experiments use 1/λ=11/\lambda = 1 and 66. In the public implementation, the argument is named β\beta (=1/λ= 1/\lambda).
  • Direction of the second term: The second term is L(f(x),f(x′))L(f(x), f(x')), and the paper says f(x)f(x) and f(x′)f(x') may be swapped. The direction can differ between implementations, so check it when comparing results.
  • Handling BatchNorm: The public implementation uses model.eval() while building adversarial examples and model.train() when updating the weights. This way, the BatchNorm statistics are not updated with inputs from the middle of the attack.
  • Evaluate with strong attacks: The paper's evaluation also combines PGD with more steps, the C&W attack, DeepFool, transfer attacks, and others. Evaluating only with an attack configured the same as in training risks overestimating robustness.

Comparison with other methods and how to choose

The table below lines up training methods that improve resistance to adversarial examples along the same criteria.

MethodTraining lossHow adversarial examples are builtAccuracy/robustness tuningCost
Adversarial training with FGSMWeighted sum of the label losses on the original input and the adversarial exampleFGSM (1 step)A weight α\alpha sets the ratio of the two lossesLight
Adversarial training with PGDLabel loss on adversarial examplesPGD (maximize the label loss)No knobHeavy
ALPLosses on adversarial examples and original inputs + ℓ2 loss on the output gapIterative attack (maximize the label loss)Tuned by a coefficientHeavy
TRADESLoss on the original input + output gap between original input and adversarial examplePGD that maximizes the output gapTuned by 1/λ1/\lambdaHeavy

Rough guidelines for choosing:

  • To build a model robust to ℓ∞ perturbations while keeping accuracy: Use TRADES and try 1/λ1/\lambda around 1–6.
  • To use a simple reference method: Use adversarial training with PGD. It serves as the baseline in many studies.
  • To reduce computation: Combine adversarial training with FGSM with tricks such as random starts, and keep evaluating with PGD.
  • To also use unlabeled data: The second term of TRADES does not use labels, so it extends to unlabeled data. As related methods that improve robustness through regularization, the paper also mentions semi-supervised approaches such as VAT (virtual adversarial training).

PyTorch example

Show code
python
import torch
import torch.nn.functional as F

"""
TRADES loss (Algorithm 1 of Zhang et al., 2019)
  loss = L(f(x), y) + β · KL(f(x) ‖ f(x′)), β = 1/λ
  x′ starts from x + 0.001·N(0, I); K times, step η1 by sign in the direction that increases KL and project onto the ε-ball
(the second term uses the KL divergence, as in the authors' public implementation)
"""

def trades_loss(model, x, y, epsilon=0.031, step_size=0.007, steps=10, beta=6.0):
  # 1) build adversarial examples x′ (eval mode so BatchNorm statistics are not changed)
  model.eval()
  with torch.no_grad():
    p_nat = F.softmax(model(x), dim=1)                   # f(x) (fixed)
  x_adv = x.detach() + 0.001 * torch.randn_like(x)       # start right next to x
  for _ in range(steps):
    x_adv.requires_grad_(True)
    # KL(f(x) ‖ f(x′)): kl_div takes arguments in the order (log q, p)
    loss_kl = F.kl_div(F.log_softmax(model(x_adv), dim=1), p_nat, reduction='sum')
    grad = torch.autograd.grad(loss_kl, x_adv)[0]
    x_adv = x_adv.detach() + step_size * grad.sign()             # step η1 in the sign direction
    x_adv = torch.min(torch.max(x_adv, x - epsilon), x + epsilon)  # project onto the ε-ball (ℓ∞)
    x_adv = x_adv.clamp(0.0, 1.0)                                  # keep within the pixel value range
  # 2) loss = sum of the two terms (back to train mode since the weights are updated)
  model.train()
  logits_nat = model(x)
  loss_natural = F.cross_entropy(logits_nat, y)                     # L(f(x), y): term for accuracy
  loss_robust = F.kl_div(F.log_softmax(model(x_adv.detach()), dim=1),
                         F.softmax(logits_nat, dim=1), reduction='batchmean')  # term for robustness
  return loss_natural + beta * loss_robust


# Example training loop (CIFAR-10 setup: ε = 0.031, η1 = 0.007, K = 10, learning rate 0.1, batch 128)
# optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=2e-4)
# for x, y in train_loader:
#   optimizer.zero_grad()
#   loss = trades_loss(model, x, y, beta=6.0)  # β = 1/λ. e.g. 1 to favor accuracy, 6 to favor robustness
#   loss.backward()
#   optimizer.step()

FAQ

Q. How does TRADES differ from adversarial training with PGD?
A.

Adversarial training with PGD trains the model so that its output on adversarial examples matches the label. TRADES keeps the loss on the original input as is and adds a term that pulls the output on adversarial examples toward the output on the original input. Because the terms are separate, 1/λ1/\lambda tunes the trade-off between accuracy and robustness. In the paper's CIFAR-10 experiments, 1/λ=11/\lambda = 1 beat adversarial training with PGD in both accuracy and robustness.

Q. How should λ (β) be chosen?
A.

Make 1/λ1/\lambda small to favor accuracy and large to favor robustness. The paper states that 1/λ1/\lambda between 1 and 10 yields models with both high accuracy and high robustness, and uses 1 and 6 in its experiments. Decide how much accuracy loss the application can tolerate, and choose together with accuracy under attacks such as PGD on validation data.

Q. Can it be used with unlabeled data?
A.

The second term (the gap between outputs on the original input and the adversarial example) does not use labels, so it can be computed on unlabeled data. The paper notes that more unlabeled data approximates the second term better, and mentions extending the method to semi-supervised learning.

References

  1. H. Zhang, Y. Yu, J. Jiao, E. P. Xing, L. El Ghaoui, and M. I. Jordan, "Theoretically Principled Trade-off between Robustness and Accuracy," ICML, 2019.
  2. Official TRADES implementation (GitHub: yaodongyu/TRADES)
  3. A. Madry, A. Makelov, L. Schmidt, D. Tsipras, and A. Vladu, "Towards Deep Learning Models Resistant to Adversarial Attacks," ICLR, 2018.
  4. A. Athalye, N. Carlini, and D. Wagner, "Obfuscated Gradients Give a False Sense of Security: Circumventing Defenses to Adversarial Examples," ICML, 2018.