> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation.md). Agents can also search and read this documentation through its [MCP server](https://infinitode-docs.gitbook.io/documentation/~gitbook/mcp).

# DeepDefend Package Documentation

Package documentation for DeepDefend, our Python package.

**Version 0.2.0.** This documentation describes DeepDefend 0.2.0 only. If you are upgrading from 0.1.x, read [Migration from 0.1.x](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/migration-from-0.1.x.md) first — several attacks were numerically wrong before 0.2.0, and `gradient_masking` no longer exists.

DeepDefend is an open-source Python library for adversarial attacks and defenses in deep learning models, intended to help you measure and improve the robustness of models you are authorised to test.

{% hint style="warning" %}
**DeepDefend** is an experimental package, please be sure to report any issues, bugs, or errors you come across when using it.
{% endhint %}

{% hint style="info" %}
Updates to DeepDefend's attack module will be less frequent due to the potential misuse of adversarial attacks on AI models. Read [Responsible use](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/limitations-and-responsible-use.md#responsible-use) before running any attack.
{% endhint %}

## What's new in 0.2.0

0.2.0 is a correctness release. Functions that previously crashed on every call (`jsma`, `spsa`, `pixel_deflection`) or returned silently wrong results (`cw`, `deepfool`, `ead`, all preprocessing defenses) now do what their names claim, and the API changed accordingly.

* **Removed:** `gradient_masking()`. It never affected the gradients an attacker computes, so it was not a defense. See [Gradient masking is not a defense](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/limitations-and-responsible-use.md#gradient-masking-is-not-a-defense).
* **New:** `smooth_predict()` for Monte-Carlo certified-radius estimates, and the `FeatureDenoisingBlock` Keras layer.
* **Changed defaults:** `pgd` / `bim` / `mim` use `alpha = epsilon / 4`, `cw` uses `epsilon=None` (unconstrained) and `c=10.0`, `jsma` uses `theta=0.0, gamma=0.2`, `ead` uses `beta=0.001`, and `spsa` uses `num_steps=50, learning_rate=0.05, spsa_samples=32`.
* **Shared attack behaviour:** every attack accepts one-hot, sparse-integer and binary labels, auto-detects `from_logits`, clips to the valid data range, and returns a NumPy array with the same shape as the input, as `float32` (non-float32 inputs are cast internally).
* **Defense hardening:** every preprocessing defense returns a savable `tf.keras.Model`, rejects invalid parameters with `ValueError` instead of producing `NaN`, and keeps a usable gradient (straight-through where the operation is not differentiable), so you can still attack a defended model.

See [What's new in 0.2.0](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/whats-new-in-0.2.0.md) for the full list, or the [`CHANGELOG.md`](https://github.com/Infinitode/DeepDefend/blob/master/CHANGELOG.md) in the repository for the release notes.

## Installation

DeepDefend 0.2.0 is published on [PyPI](https://pypi.org/project/deepdefend/):

```bash
pip install deepdefend
```

To upgrade an existing install:

```bash
pip install --upgrade "deepdefend==0.2.0"
```

DeepDefend 0.2.0 requires **Python 3.9 – 3.12**, matching the versions supported by TensorFlow 2.x. Python 3.6 – 3.8 are no longer supported because TensorFlow does not publish wheels for them.

It depends on `tensorflow>=2.13,<3` and `numpy>=1.23,<3`; both are installed automatically. Verify the installed version:

```bash
python -c "import deepdefend; print(deepdefend.__version__)"  # 0.2.0
```

`import deepdefend` does not import TensorFlow — the submodules and functions are loaded lazily on first access.

For development (tests and linting):

```bash
git clone https://github.com/Infinitode/DeepDefend.git
cd DeepDefend
pip install -e ".[dev]"
pytest
```

## Quick start

### Adversarial attacks

```python
import numpy as np
import tensorflow as tf
from deepdefend.attacks import fgsm, pgd, bim, cw, deepfool, jsma, spsa, mim, ead

# Load a pre-trained TensorFlow model
model = ...

# Load example input and label data (replace this with your own data loading code)
x_example = ...  # shape (batch, ...), values in [0, 1]
y_example = ...  # one-hot (batch, classes), sparse indices (batch,) or binary (batch, 1)

# Single-step attack
adversarial_fgsm = fgsm(model, x_example, y_example, epsilon=0.01)

# Iterative attacks (alpha defaults to epsilon / 4)
adversarial_pgd = pgd(model, x_example, y_example, epsilon=0.01, num_steps=10)
adversarial_bim = bim(model, x_example, y_example, epsilon=0.01, num_steps=10)
adversarial_mim = mim(model, x_example, y_example, epsilon=0.01, num_steps=10)

# Optimisation-based attacks
adversarial_cw = cw(model, x_example, y_example, c=10.0, num_steps=100)
adversarial_ead = ead(model, x_example, y_example, epsilon=0.01, num_steps=50)
adversarial_deepfool = deepfool(model, x_example, y_example, num_steps=50)
adversarial_spsa = spsa(model, x_example, y_example, epsilon=0.01, num_steps=50)

# Saliency-map attack
adversarial_jsma = jsma(model, x_example, y_example, num_steps=10)

# Targeted attack: y_example is the class you want the model to predict
adversarial_targeted = pgd(model, x_example, target_labels, epsilon=0.03, targeted=True)
```

### Adversarial defenses

```python
import tensorflow as tf
from deepdefend.defenses import *

# Load a pre-trained TensorFlow model
model = ...
```

```python
# Training-time defenses
defended_model = adversarial_training(model, x_train, y_train, epsilon=0.01, epochs=10)
defended_model = defensive_distillation(model, teacher_model, temperature=2)
defended_model = adversarial_logit_pairing(model, epsilon=0.01)
```

```python
# Inference-time preprocessing defenses (these return a new Keras model)
defended_model = feature_squeezing(model, bit_depth=4)
defended_model = gaussian_blur(model, kernel_size=3, sigma=1.0)
defended_model = median_smoothing(model, kernel_size=3)
defended_model = spatial_smoothing(model, kernel_size=3, method="median")
defended_model = jpeg_compression(model, quality=75)
defended_model = pixel_deflection(model, deflection_count=100, window_size=10)
defended_model = total_variation_minimization(model, iterations=10)
defended_model = thermometer_encoding(model, num_bins=10)
defended_model = feature_denoising(model, method="median")
defended_model = input_transformation(model, tf.keras.layers.Rescaling(1.0 / 255))
defended_model = randomized_smoothing(model, noise_level=0.1)

# They can be saved and reloaded like any other Keras model
defended_model.save("defended.keras")
restored = tf.keras.models.load_model("defended.keras")

# Monte-Carlo prediction with a certified L2 radius (randomized smoothing).
# Use add_noise_at_inference=False: smooth_predict supplies the noise itself.
smoothed = randomized_smoothing(model, noise_level=0.1, add_noise_at_inference=False)
result = smooth_predict(smoothed, x_test, n_samples=100)
print(result["predictions"], result["certified_radius"])
```

```python
# Text
defended_text = word_masking("The movie was great", mask_prob=0.2)
```

## Supported model types

Legend: ✅ supported · ❌ unsupported (raises a clear error)

| Feature                | Image |      Text      | Numeric | Classification |
| ---------------------- | :---: | :------------: | :-----: | :------------: |
| **Attacks**            |       |                |         |                |
| FGSM                   |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| PGD                    |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| BIM                    |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| MIM                    |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| CW (L2)                |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| EAD                    |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| DeepFool               |   ✅   | ✅ (Embeddings) |    ✅    |        ✅       |
| JSMA                   |   ✅   |        ❌       |    ✅    |        ✅       |
| SPSA                   |   ✅   |        ❌       |    ✅    |        ✅       |
| Word Swap              |   ❌   |        ✅       |    ❌    |        —       |
| Char Swap              |   ❌   |        ✅       |    ❌    |        —       |
| **Defenses**           |       |                |         |                |
| Adversarial Training   |   ✅   |        ✅       |    ✅    |        ✅       |
| Feature Squeezing      |   ✅   |        ✅       |    ✅    |        ✅       |
| Input Transformation   |   ✅   |        ✅       |    ✅    |        ✅       |
| Defensive Distillation |   ✅   |        ✅       |    ✅    |        ✅       |
| Randomized Smoothing   |   ✅   |        ✅       |    ✅    |        ✅       |
| Thermometer Encoding   |   ✅   |        ✅       |    ✅    |        ✅       |
| ALP                    |   ✅   |        ✅       |    ✅    |        ✅       |
| Feature Denoising      |   ✅   |        ❌       |    ❌    |        ✅       |
| Spatial Smoothing      |   ✅   |        ❌       |    ❌    |        ✅       |
| Median Smoothing       |   ✅   |        ❌       |    ❌    |        ✅       |
| JPEG Compression       |   ✅   |        ❌       |    ❌    |        ✅       |
| Pixel Deflection       |   ✅   |        ❌       |    ❌    |        ✅       |
| Gaussian Blur          |   ✅   |        ❌       |    ❌    |        ✅       |
| TV Minimization        |   ✅   |        ❌       |    ❌    |        ✅       |
| Word Masking           |   ❌   |        ✅       |    ❌    |        —       |

{% hint style="info" %}
`gradient_masking` used to be listed here. It was removed in 0.2.0 — see [Gradient masking is not a defense](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/limitations-and-responsible-use.md#gradient-masking-is-not-a-defense).
{% endhint %}

## Documentation map

* [What's new in 0.2.0](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/whats-new-in-0.2.0.md) — everything that changed, with links to the changelog.
* [Migration from 0.1.x](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/migration-from-0.1.x.md) — breaking changes, invalidated results, saved-model incompatibility.
* [Limitations & responsible use](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/limitations-and-responsible-use.md) — what these defenses do **not** guarantee, and the rules for running attacks.
* [DeepDefend Reference](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/deepdefend-reference.md) — shared concepts (labels, logits, clipping, inputs, seeding) and per-function pages.
  * [Attacks](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/deepdefend-reference/attacks-functions.md)
  * [Defenses](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/deepdefend-reference/defenses-functions.md)

## Version history

* **0.2.0 (Latest)**: Correctness release. `gradient_masking` removed; `cw`, `deepfool`, `ead`, `spsa`, `jsma` fixed; label handling, logits detection and clipping unified across all attacks; preprocessing defenses made savable, gradient-preserving and validated; added `smooth_predict()` and `FeatureDenoisingBlock`; Python 3.9–3.12. See [What's new in 0.2.0](https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation/whats-new-in-0.2.0.md).
* **0.1.5**: Added MIM and EAD attacks, Word Swap and Character Swap attacks, Pixel Deflection, Gaussian Blur, Total Variation Minimization and Median Smoothing defenses, Word Masking, and a support table.
* **0.1.4**: Added SPSA and JPEG Compression, fixed flawed logic in some defense functions.
* **0.1.3**: Added Randomized Smoothing, Feature Denoising, Thermometer Encoding, Adversarial Logit Pairing (ALP) and Spatial Smoothing.
* **0.1.2**: Updated the PyPI project description.
* **0.1.1**: 6 new functions.
* **0.1.0**: Initial release.
