AI Logic

Adversarial Attacks and Defenses

C&W Attack

Updated:

Diagram of the C&W attack. Left: the flow of the L2 attack (input and target class, change of variables with tanh, objective function, optimizing w with Adam, binary search over the coefficient c, adversarial example). Upper right: the misclassification term f plotted as a function of the logit difference, flattening at −κ for κ = 0 and κ = 5. Lower right: the change of variables ½(tanh(w) + 1), showing that pixel values stay in 0–1 for any w

What is the C&W attack

The C&W attack (Carlini & Wagner attack) searches for the input closest to the original among those classified as a chosen target class, using optimization with a carefully designed objective. Carlini and Wagner proposed it in 2016, and it was presented at the IEEE Symposium on Security and Privacy 2017. Matching three ways of measuring distance, there are three attacks: L0 (number of pixels changed), L2 (square root of the sum of squared differences), and L∞ (maximum change of any pixel).

The paper's goal was to build a strong attack for evaluating defenses. At the time, a defense called defensive distillation had been reported to reduce the success rate of existing attacks from 95% to 0.5%. The C&W attack found adversarial examples with 100% probability even on networks trained with defensive distillation, showing that this defense barely improves robustness.

The idea has the same form as the L-BFGS attack of Szegedy et al.: "minimize perturbation size plus a misclassification term." On top of that, it revises three points:

  • Misclassification term: Instead of cross-entropy, it uses differences of the pre-softmax outputs (logits).
  • Handling the pixel range: A change of variables keeps pixel values within 0–1 no matter what.
  • Optimization method: Since no box constraint is needed anymore, the problem can be optimized with Adam.

The left side of the header figure shows the flow of the L2 attack; the right side plots the two design choices in its objective, drawn from the formulas.

How the C&W attack works

The paper writes the problem of finding an adversarial example as follows, where xx is the original input, tt is the target class, CC is the classifier's prediction, and D\mathcal{D} is a distance.

min⁡δ D(x,x+δ)subject toC(x+δ)=t,x+δ∈[0,1]n\min_{\delta} \ \mathcal{D}(x, x + \delta) \quad \text{subject to} \quad C(x + \delta) = t,\quad x + \delta \in [0, 1]^n

Because the condition C(x+δ)=tC(x + \delta) = t is hard to handle, the paper builds a function ff such that "the input is classified as tt if and only if f(x+δ)≤0f(x + \delta) \le 0," multiplies it by a coefficient c>0c > 0, and puts it into the objective.

min⁡δ ∥δ∥p+c⋅f(x+δ)subject tox+δ∈[0,1]n\min_{\delta} \ \|\delta\|_p + c \cdot f(x + \delta) \quad \text{subject to} \quad x + \delta \in [0, 1]^n

The paper compared seven candidates for ff and chose the best one, a difference of logits ZZ. κ≥0\kappa \ge 0 sets how large a margin the classification as tt should have.

f(x′)=max⁡(max⁡i≠tZ(x′)i−Z(x′)t, −κ)f(x') = \max\Big( \max_{i \ne t} Z(x')_i - Z(x')_t,\ -\kappa \Big)

The pixel range [0,1][0, 1] is satisfied through a change of variables x′=12(tanh⁡(w)+1)x' = \tfrac{1}{2}(\tanh(w) + 1) with a new variable ww. Since tanh⁡\tanh takes values between −1-1 and 11, x′x' stays in 0–1 however ww moves.

The L2 attack proceeds as follows.

  1. Choose the target class tt and an initial value for the coefficient cc.
  2. Minimize the following objective over ww with Adam (10,000 steps for each cc in the paper).
∥12(tanh⁡(w)+1)−x∥22+c⋅f(12(tanh⁡(w)+1))\Big\| \tfrac{1}{2}(\tanh(w) + 1) - x \Big\|_2^2 + c \cdot f\Big(\tfrac{1}{2}(\tanh(w) + 1)\Big)
  1. If the resulting x′x' is classified as tt, decrease cc; otherwise increase cc, and redo step 2 (a binary search; 20 rounds in the paper).
  2. Among the solutions classified as tt, take the one with the smallest L2 distance as the adversarial example.
  3. To save it as an image, round each pixel to an integer from 0 to 255.

The L0 and L∞ attacks are iterative procedures built on the L2 attack. The L0 attack takes the perturbation found by the L2 attack, marks pixels with little effect on the prediction as "fixed" one at a time, and stops when the L2 attack fails. For the L∞ attack, directly minimizing the L∞ norm makes gradient descent oscillate, so it uses a penalty ∑i(δi−τ)+\sum_i (\delta_i - \tau)^+ on the amount exceeding a threshold τ\tau, and lowers τ\tau by a factor of 0.9 each time every pixel falls below τ\tau.

On choosing cc, the paper recommends picking "the smallest cc for which f(x∗)≤0f(x^*) \le 0." If cc is too small, the input never reaches misclassification; if it is too large, the attack ignores the perturbation size and rushes toward misclassification, so the perturbation becomes large. On MNIST, c<0.1c < 0.1 almost never succeeded, while c>1c > 1 always succeeded but with large perturbations.

Why it is strong: choosing the objective

The paper compared every combination of the seven choices of ff and three ways of handling the box constraint (clipping to 0–1 at every step, clipping inside the function, and a change of variables) on MNIST. Below are some results with the change of variables and randomly chosen target classes.

Misclassification term ffMean L2 distanceSuccess rate
Cross-entropy (−lossF,t(x′)+1-\mathrm{loss}_{F,t}(x') + 1)4.35100%
Softmax output difference (max⁡i≠tF(x′)i−F(x′)t)+(\max_{i \ne t} F(x')_i - F(x')_t)^+3.2244%
(0.5−F(x′)t)+(0.5 - F(x')_t)^+4.0355%
Logit difference (max⁡i≠tZ(x′)i−Z(x′)t)+(\max_{i \ne t} Z(x')_i - Z(x')_t)^+ (adopted)3.47100%

For rows with a success rate below 100%, the mean is over successful cases only. The logit difference always succeeded while keeping perturbations small. Cross-entropy, the most common choice in earlier work, produced larger perturbations than the best ff.

The paper explains why as follows.

  • Softmax outputs have very small gradients around the original input: Terms that use softmax outputs, such as cross-entropy, have small gradients near the original input (on average 2−202^{-20} in the paper's measurements) and large gradients near adversarial examples (2−12^{-1}). Getting started requires a very large cc, and once the optimization starts moving, that large cc makes it rush toward misclassification and inflate the perturbation. A single cc cannot strike a good balance from start to finish.
  • Logits change almost linearly: The paper confirms that along the straight line from the original input to an adversarial example, the logit Z(⋅)tZ(\cdot)_t changes almost linearly (correlation coefficient above 0.9). With a logit difference, the gradient magnitude does not change drastically along the way, so a single cc can reduce both the perturbation term and the misclassification term.

For the same reason, the attack is also strong against defensive distillation. In networks trained with defensive distillation, the softmax outputs stick almost at 0 or 1 and the gradient vanishes, so the L-BFGS attack and DeepFool, which use softmax outputs, fail. The C&W attack uses logits and is unaffected.

Experimental results

Below are results of targeted attacks compared with earlier attacks (MNIST and CIFAR-10, first 1,000 test images). "Best" is the easiest class to attack after trying every class; "Average" is a randomly chosen target class. Values are mean distances, with success rates noted where they are below 100%.

AttackDistanceMNIST (best)MNIST (average)CIFAR-10 (best)CIFAR-10 (average)
C&W L0 attackL08.5165.913
JSMA-ZL020562058
C&W L2 attackL21.361.760.170.33
DeepFool (cannot choose the target class)L22.11―0.85―
C&W L∞ attackL∞0.130.160.00920.013
FGSML∞0.220.26 (42% success)0.015 (99% success)0.029 (51% success)
Iterative gradient sign attackL∞0.140.190.00780.014

The C&W attacks had a 100% success rate for every distance and dataset. The paper summarizes that the L0 and L2 attacks succeed with perturbations 2–10 times smaller than the best earlier attacks, and the L∞ attack has similar quality with a higher success rate. On Inception v3 for ImageNet, the untargeted L2 attack needed an average perturbation of 0.32, smaller than DeepFool's 0.91. With the L∞ attack, changing only the least significant bit of each pixel was enough to make the image classified as any desired class.

Attacking defensive distillation. Against networks trained with defensive distillation at temperature T=100T = 100, none of the earlier attacks found adversarial examples. All three C&W attacks succeeded 100% of the time, and the mean distance of the L2 attack on MNIST rose only slightly, from 1.76 without distillation to 2.2. Varying the distillation temperature from 1 to 100 barely changed the distance found by the L2 attack (correlation coefficient −0.05), showing that raising the temperature does not increase robustness.

Transfer attacks. Making κ\kappa larger to build "high-confidence" adversarial examples makes them transfer more easily to other models. On MNIST, between ordinary models, transfer reached almost 100% at κ≈20\kappa \approx 20, and to defensively distilled models it reached 100% at κ=40\kappa = 40. This shows that even defenses whose gradients are unusable can be broken by transfer.

Caveats

The attack is computationally heavy. In the paper's setup, each input requires 20 rounds of binary search over cc × 10,000 Adam steps (Adam is reported to reach 95% of the optimum within 1,000 steps in most cases). The paper states that the L2 and L∞ attacks are 10–100 times slower than earlier attacks (10 times slower than the iterative gradient sign attack). For uses that need many examples, such as material for adversarial training, PGD and similar methods are a better fit.

  • It is a targeted attack: The paper's attacks specify a target class tt. To cause misclassification without picking a class, either try every class and take the closest result, or rewrite ff to push the logit of the true class down. Madry et al. (2018) ran evaluations using the C&W loss, which directly optimizes the difference between correct and incorrect logits, as the loss for PGD.
  • Logits are required: Because ff uses the pre-softmax outputs, the logits must be accessible from the model. It cannot be used as is on a model that returns only probabilities.
  • It can get stuck in local optima: Being gradient descent, it can stop at a poor local optimum. The paper restarts from several starting points chosen inside a ball whose radius is the distance to the closest adversarial example found so far.
  • Use in evaluating defenses: The paper recommends that anyone proposing a defense at least (1) evaluate it directly with strong attacks (especially the L2 attack), and (2) check that high-confidence adversarial examples built on an undefended model do not transfer.

Comparison with other attacks and how to choose

The table below lines up the C&W attack and the attacks it is often compared with along the same criteria.

MethodHow the perturbation is foundPerturbation sizeCostMain use
L-BFGS attackMinimize perturbation size + cross-entropy with L-BFGSSearches for the minimum (L2)HeavyHistorical method
FGSMTake one step of size ε\varepsilon in the direction of the gradient's signFixed in advanceVery lightQuick checks, material for adversarial training
PGDRepeatedly take small steps in the sign direction and project back into the rangeFixed in advanceModerateEvaluation within a fixed range, adversarial training
DeepFoolRepeatedly step perpendicular to the linearized boundarySearches for the minimumFairly lightQuickly quantifying robustness
C&W attackMinimize perturbation size + logit difference with a change of variables and Adam, binary search over the coefficientSearches for the minimum (L0, L2, L∞)HeavyEvaluating defenses, targeted attacks

Rough guidelines for choosing:

  • To evaluate a new defense: Use the C&W attack. It is strong even against defenses that make gradients vanish, and it can test misclassification into a chosen class. Combine it with other attacks such as PGD.
  • To test robustness within a fixed ε\varepsilon on many inputs: Use PGD. Some evaluations use the C&W logit-difference loss inside PGD (Madry et al., 2018).
  • To quickly quantify robustness: Use DeepFool.
  • To train a robust model: Rather than an attack, use PGD-based adversarial training or TRADES, and use the C&W attack to evaluate the result.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
C&W L2 attack (Carlini and Wagner, 2017, Section 6A)
  x' = ½(tanh(w) + 1)                         … change of variables keeps pixels in [0, 1]
  minimize ‖x' − x‖2² + c·f(x')
  f(x') = max( max_{i≠t} Z(x')_i − Z(x')_t, −κ )  … Z is the pre-softmax logits
c is binary-searched to find the smallest c that gives classification as target class t
"""

def cw_l2_attack(model, x, target, kappa=0.0, c_init=1e-2, search_steps=9, max_iter=1000, lr=1e-2):
  # x: [B, C, H, W] (pixel values in 0-1), target: [B] target classes
  model.eval()  # put BatchNorm and Dropout in inference mode (weights are not changed)
  x = x.detach()
  B = x.size(0)
  lower = torch.zeros(B, device=x.device)
  upper = torch.full((B,), 1e10, device=x.device)
  c = torch.full((B,), c_init, device=x.device)
  best_l2 = torch.full((B,), float('inf'), device=x.device)
  best_adv = x.clone()
  onehot = nn.functional.one_hot(target, num_classes=model(x[:1]).size(1)).bool()

  def to_x(w):
    return 0.5 * (torch.tanh(w) + 1)

  # start from w with x = ½(tanh(w) + 1) (shrink slightly so the ends 0 and 1 do not diverge)
  w0 = torch.atanh((2 * x - 1).clamp(-1 + 1e-6, 1 - 1e-6))

  for _ in range(search_steps):  # binary search over c
    w = w0.clone().requires_grad_(True)
    optimizer = torch.optim.Adam([w], lr=lr)
    success = torch.zeros(B, dtype=torch.bool, device=x.device)
    for _ in range(max_iter):
      x_adv = to_x(w)
      Z = model(x_adv)                                    # logits
      z_t = Z[onehot]                                     # Z(x')_t
      z_other = Z.masked_fill(onehot, float('-inf')).amax(dim=1)  # max_{i≠t} Z(x')_i
      f = torch.clamp(z_other - z_t, min=-kappa)          # f(x')
      l2 = ((x_adv - x) ** 2).flatten(1).sum(dim=1)        # ‖x' − x‖2²
      loss = (l2 + c * f).sum()
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()
      with torch.no_grad():
        ok = (z_other - z_t) <= -kappa                     # classified as t (with margin κ)
        better = ok & (l2 < best_l2)
        best_l2 = torch.where(better, l2, best_l2)
        best_adv[better] = x_adv[better].detach()
        success |= ok
    # decrease c on success, increase c on failure
    upper = torch.where(success, torch.minimum(upper, c), upper)
    lower = torch.where(success, lower, torch.maximum(lower, c))
    c = torch.where(upper < 1e9, (lower + upper) / 2, c * 10)
  return best_adv, best_l2.sqrt()  # inputs with no solution stay as the original x (distance inf)


# Usage example (assumes a trained classifier model that returns logits, images x, and target classes target)
# x_adv, dist = cw_l2_attack(model, x, target, kappa=0.0)
# x_adv = (x_adv * 255).round() / 255  # to save as images, round to integers 0-255 and re-check the predictions

FAQ

Q. Should evaluation use the C&W attack or PGD?
A.

Choose by purpose. PGD checks "how often the model errs within a fixed ε\varepsilon" relatively cheaply across many inputs. The C&W attack searches, with heavy optimization, for "the minimum perturbation needed to cause an error." When evaluating a defense, the safe approach is to use both and confirm that the model holds up against each.

Q. What is κ (the confidence parameter) used for?
A.

Increasing κ\kappa keeps pushing until the logit of the target class exceeds those of other classes by at least κ\kappa, producing "high-confidence" adversarial examples. The perturbation grows, but the examples transfer more easily to other models. The paper uses κ=0\kappa = 0 for ordinary attacks and varies κ\kappa from 0 to 40 in the transfer experiments.

Q. Why use a logit difference instead of cross-entropy?
A.

Terms that use softmax outputs, such as cross-entropy, have very small gradients near the original input and become large abruptly near adversarial examples. A single coefficient cc therefore cannot balance them against the perturbation term, and the perturbation grows. With a logit difference, the gradient magnitude does not change drastically, and the attack is less affected by defenses that make gradients vanish, such as defensive distillation.

References

  1. N. Carlini and D. Wagner, "Towards Evaluating the Robustness of Neural Networks," IEEE Symposium on Security and Privacy, pp. 39–57, 2017.
  2. C. Szegedy, W. Zaremba, I. Sutskever, J. Bruna, D. Erhan, I. Goodfellow, and R. Fergus, "Intriguing properties of neural networks," ICLR, 2014.
  3. S.-M. Moosavi-Dezfooli, A. Fawzi, and P. Frossard, "DeepFool: a simple and accurate method to fool deep neural networks," CVPR, 2016.
  4. A. Madry, A. Makelov, L. Schmidt, D. Tsipras, and A. Vladu, "Towards Deep Learning Models Resistant to Adversarial Attacks," ICLR, 2018.