The Carlini & Wagner (C&W) attack is an iterative, white-box adversarial attack that constructs minimally perturbed inputs by solving an optimization problem. Unlike earlier attacks like Fast Gradient Sign Method (FGSM), the C&W attack directly optimizes the L0, L2, or L∞ distance metric between the original and adversarial sample while using a margin-based loss function that ensures the target class logit exceeds the original class logit by a specified confidence margin κ. This formulation allows the attack to find adversarial examples with significantly smaller distortions than prior methods, making it a gold standard for evaluating adversarial robustness.
Glossary
Carlini & Wagner (C&W) Attack

What is Carlini & Wagner (C&W) Attack?
The Carlini & Wagner (C&W) attack is a powerful optimization-based adversarial attack that formulates the generation of adversarial examples as a constrained optimization problem, using a margin-based loss function to find minimally distorted perturbations that cause misclassification, often defeating defensive distillation.
The attack's key innovation is its objective function, which avoids the saturation problems of cross-entropy loss by using a hinge-like margin loss: max(max{Z(x')_i : i ≠ t} - Z(x')_t, -κ), where Z represents logits and t is the target class. By reformulating the constrained optimization using change-of-variables—such as the tanh transformation to enforce box constraints on pixel values—the C&W attack becomes solvable via standard optimizers like Adam. It was notably the first attack to reliably break defensive distillation, a previously promising defense that masked gradients, by demonstrating that gradient masking provides a false sense of security against a sufficiently sophisticated optimization-based adversary.
Key Characteristics of the C&W Attack
The Carlini & Wagner attack is a powerful optimization-based method that formulates adversarial example generation as a constrained minimization problem, using a margin-based loss function to find minimally distorted perturbations that reliably defeat defensive distillation.
Margin-Based Loss Function
Unlike earlier attacks that use cross-entropy loss, C&W employs a margin-based loss that directly optimizes the difference between the logit of the target class and the logit of the next most likely class. The attack succeeds when this margin exceeds zero, meaning the model assigns higher confidence to the target class. This formulation avoids the gradient saturation problems that make defensive distillation resistant to standard attacks, as the loss continues to provide useful gradients even when the model is highly confident in its incorrect prediction.
Optimization Formulation
The C&W attack frames adversarial generation as solving:
- Minimize: ||δ||_p + c · f(x + δ)
- Subject to: x + δ ∈ [0,1]^n
Where δ is the perturbation, ||·||_p is the Lp norm (typically L2), f is the objective function, and c is a constant balancing distortion against attack success. The constraint that the perturbed input remains in valid pixel space is enforced through a change-of-variables using the tanh function, transforming the box-constrained optimization into an unconstrained problem solvable with standard optimizers like Adam.
Lp Norm Variants
The C&W framework supports three distinct distance metrics, each producing different perturbation characteristics:
- L2 attack: Minimizes Euclidean distance, producing small, distributed perturbations across many pixels—the most commonly used variant
- L∞ attack: Minimizes the maximum per-pixel change, ensuring no single pixel is altered beyond a threshold
- L0 attack: Minimizes the number of altered pixels, producing sparse perturbations through an iterative pixel-selection procedure
This flexibility allows security researchers to evaluate model robustness against different threat models and perceptual constraints.
Defeating Defensive Distillation
Defensive distillation was considered a promising defense at the time of C&W's introduction, training a second model on the softened probability outputs of a first model to smooth decision boundaries. The C&W attack systematically breaks defensive distillation because:
- The margin-based loss avoids the gradient vanishing problem that occurs with softmax-saturated distilled models
- The optimization directly targets logits rather than probabilities, bypassing the temperature-scaled softmax that distillation relies on
- The attack achieves 100% success against distilled models with distortions comparable to those needed for undefended models
Binary Search for Constant c
The attack uses an outer optimization loop with binary search to find the smallest constant c that produces a successful adversarial example. Starting with a small initial value, the algorithm:
- Solves the inner minimization for the current c
- If the attack fails, increases c to penalize misclassification more heavily
- If the attack succeeds, decreases c to prioritize minimizing distortion
- Repeats until finding the boundary value where attack just succeeds
This ensures the final perturbation is near-optimal in terms of the distortion-attack success trade-off.
Benchmark Standard Status
The C&W attack has become the de facto standard for evaluating adversarial robustness in academic research. Its widespread adoption stems from:
- Near-optimal perturbation magnitudes that establish strong upper bounds on model vulnerability
- Consistent performance across diverse architectures including convolutional networks, residual networks, and transformers
- Availability in major adversarial robustness libraries such as Foolbox, CleverHans, and Adversarial Robustness Toolbox
- Use as the primary evaluation metric in hundreds of defense papers, making it the benchmark against which new defenses must demonstrate resilience
C&W Attack vs. Other Adversarial Attacks
A feature-level comparison of the Carlini & Wagner attack against other prominent adversarial example generation methods, highlighting differences in optimization objectives, perturbation norms, and defensive evasion capabilities.
| Feature | C&W Attack | Projected Gradient Descent | DeepFool |
|---|---|---|---|
Optimization Objective | Margin-based loss (L2, L∞, L0) | Cross-entropy loss maximization | Linearized distance to decision boundary |
Perturbation Minimization | Directly minimizes distortion | Constrained by epsilon-ball projection | Iteratively estimates minimal perturbation |
Defensive Distillation Evasion | |||
Gradient Masking Robustness | |||
Lp-Norm Flexibility | L0, L2, L∞ supported | L∞ (standard); L2 variant exists | L2 primarily |
Attack Strength (L2, MNIST) | 0.3% median distortion | 0.5% median distortion | 0.1% median distortion |
Computational Cost | High (per-sample optimization) | Medium (iterative gradient steps) | Low (fast linear approximation) |
Transferability (Black-Box) | Moderate | High | Low |
Frequently Asked Questions
Authoritative answers to the most common technical questions regarding the formulation, implementation, and defensive implications of the Carlini & Wagner optimization-based adversarial attack.
The Carlini & Wagner (C&W) attack is an optimization-based adversarial attack that generates minimally distorted perturbations by solving a constrained optimization problem using a margin-based loss function. Unlike earlier attacks that rely on simple gradient steps, the C&W attack formulates the adversarial generation as finding the smallest perturbation ( \delta ) that causes misclassification. It does this by minimizing a combined objective: the distance of the perturbation (measured in ( L_0 ), ( L_2 ), or ( L_\infty ) norms) plus a penalty term that drives the model's logit for the target class above the logit for the original class by a margin. The attack uses the Adam optimizer and often employs a change-of-variables technique (using the ( \tanh ) function) to ensure the perturbed input remains within valid pixel bounds, making it exceptionally effective at defeating defensive distillation.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
The Carlini & Wagner attack is a cornerstone of adversarial robustness evaluation. These related concepts define the broader ecosystem of attacks, defenses, and formal guarantees that security researchers use to harden neural networks.
Projected Gradient Descent (PGD)
A foundational iterative white-box attack that maximizes loss by taking gradient steps and projecting the perturbation back onto an Lp-norm epsilon-ball. PGD is the standard benchmark for empirical robustness. C&W often succeeds where PGD fails, particularly against defensive distillation, because C&W's margin-based loss directly optimizes for minimal distortion rather than just maximizing cross-entropy.
Adversarial Training
The primary empirical defense where the training set is augmented with on-the-fly adversarial examples. The model learns to map perturbed inputs back to the ground-truth class. C&W attacks are critical for evaluating adversarially trained models because weaker attacks like FGSM produce gradient masking artifacts—the model appears robust but remains vulnerable to stronger optimization-based attacks.
Certified Robustness
Unlike empirical defenses, certified robustness provides a formal mathematical guarantee that no perturbation within a specified Lp-radius can change the prediction. Techniques include randomized smoothing and interval bound propagation. C&W attacks serve as an upper-bound sanity check: if a C&W attack finds a perturbation smaller than the certified radius, the certificate is tight.
Gradient Masking
A false sense of security phenomenon where a defense obfuscates or saturates gradients, causing gradient-based attacks to fail during evaluation. C&W attacks are specifically designed to bypass gradient masking by using an unconstrained optimization variable (the 'w' variable in the L2 formulation) and a margin-based loss that doesn't saturate when logits are pushed to extremes.
Black-Box Attack
An attack executed without access to model internals, relying on query access or transferability from a surrogate model. C&W attacks generate high-quality adversarial examples that transfer effectively between models. Researchers use C&W on a white-box surrogate, then test the perturbation against the black-box target to evaluate transfer-based black-box attack success rates.
Defensive Distillation
A defense technique where a model is trained on the softmax probability vectors of a previously trained model, using a high temperature parameter. This was designed to smooth decision boundaries and reduce gradient magnitude. C&W attacks were the first to completely break defensive distillation by circumventing the near-zero gradients and directly optimizing the logit margin.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us