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 x is the original input, t is the target class, C is the classifier's prediction, and D is a distance.
δminD(x,x+δ)subject toC(x+δ)=t,x+δ∈[0,1]n
Because the condition C(x+δ)=t is hard to handle, the paper builds a function f such that "the input is classified as t if and only if f(x+δ)≤0," multiplies it by a coefficient c>0, and puts it into the objective.
δmin∥δ∥p+c⋅f(x+δ)subject tox+δ∈[0,1]n
The paper compared seven candidates for f and chose the best one, a difference of logits Z. κ≥0 sets how large a margin the classification as t should have.
f(x′)=max(i=tmaxZ(x′)i−Z(x′)t,−κ)
The pixel range [0,1] is satisfied through a change of variables x′=21(tanh(w)+1) with a new variable w. Since tanh takes values between −1 and 1, x′ stays in 0–1 however w moves.
The L2 attack proceeds as follows.
Choose the target class t and an initial value for the coefficient c.
Minimize the following objective over w with Adam (10,000 steps for each c in the paper).
21(tanh(w)+1)−x22+c⋅f(21(tanh(w)+1))
If the resulting x′ is classified as t, decrease c; otherwise increase c, and redo step 2 (a binary search; 20 rounds in the paper).
Among the solutions classified as t, take the one with the smallest L2 distance as the adversarial example.
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−τ)+ on the amount exceeding a threshold τ, and lowers τ by a factor of 0.9 each time every pixel falls below τ.
On choosing c, the paper recommends picking "the smallest c for which f(x∗)≤0." If c 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.1 almost never succeeded, while c>1 always succeeded but with large perturbations.
Why it is strong: choosing the objective
The paper compared every combination of the seven choices of f 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.
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 f.
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−20 in the paper's measurements) and large gradients near adversarial examples (2−1). Getting started requires a very large c, and once the optimization starts moving, that large c makes it rush toward misclassification and inflate the perturbation. A single c 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(⋅)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 c 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%.
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=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 κ 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, and to defensively distilled models it reached 100% at κ=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 c × 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 t. To cause misclassification without picking a class, either try every class and take the closest result, or rewrite f 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 f 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.
Repeatedly step perpendicular to the linearized boundary
Searches for the minimum
Fairly light
Quickly quantifying robustness
C&W attack
Minimize perturbation size + logit difference with a change of variables and Adam, binary search over the coefficient
Searches for the minimum (L0, L2, L∞)
Heavy
Evaluating 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 ε on many inputs: Use PGD. Some evaluations use the C&W logit-difference loss inside PGD (Madry et al., 2018).
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 ε" 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 κ keeps pushing until the logit of the target class exceeds those of other classes by at least κ, producing "high-confidence" adversarial examples. The perturbation grows, but the examples transfer more easily to other models. The paper uses κ=0 for ordinary attacks and varies κ 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 c 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.