Skip to content

Commit 3359f4c

Browse files
Arena Agentarena-agent
andcommitted
refactor: remove gradient_masking, fold review into README, add docs brief
- Remove gradient_masking()/GradientMaskingModel entirely. It only masked training gradients and had no effect on an attacker's gradients (attacks against a wrapped model were bit-identical to the base model), so it is a false defense. Removed from the package namespace, __all__, the module docstring, the README support matrix and the tests; a regression test now asserts it stays gone. - Delete CODE_REVIEW.md and move its findings into the README as a 'What was wrong before 0.2.0' section (attacks, defenses, packaging/CI tables) and a Limitations section. - Add a 'Documentation update brief' code cell to the README describing every 0.2.0 API change for the docs agent. - CHANGELOG: gradient_masking moves from Fixed to Removed with the rationale; test count updated to 170. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
1 parent 70f1ada commit 3359f4c

8 files changed

Lines changed: 311 additions & 478 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,6 @@ attacks and defenses changes, the minor version was bumped.
7272
for both probability and logit outputs.
7373
- **`adversarial_logit_pairing`** generates adversarial examples inside the
7474
training step; the previous implementation paired two models on clean inputs.
75-
- **`gradient_masking`** no longer crashes on `None` gradients and now emits a
76-
`RuntimeWarning` explaining that it is a training regulariser, not an
77-
inference-time defense.
7875
- **`randomized_smoothing`** clips the noisy input, is reproducible when
7976
seeded, and ships with `smooth_predict()` for Monte-Carlo prediction and a
8077
certified-radius estimate.
@@ -94,7 +91,7 @@ attacks and defenses changes, the minor version was bumped.
9491
function is reachable as `deepdefend.<name>`, and `import deepdefend` no
9592
longer imports TensorFlow.
9693
- `deepdefend/smooth_predict` for Monte-Carlo randomized smoothing.
97-
- 164 tests covering attacks, defenses, serialisation, gradients, label
94+
- 170 tests covering attacks, defenses, serialisation, gradients, label
9895
formats, input validation and the public API.
9996
- CI: lint + test matrix (3.10-3.12) + reproducible build on every push and PR.
10097
- `SECURITY.md`, `CODE_OF_CONDUCT.md`, Dependabot, pre-commit and
@@ -120,6 +117,14 @@ attacks and defenses changes, the minor version was bumped.
120117

121118
### Removed
122119

120+
- **`gradient_masking`** (and the `GradientMaskingModel` wrapper) has been
121+
deleted. It only masked *training* gradients and had no effect on the
122+
gradients an attacker computes at inference time — attacks against a wrapped
123+
model were bit-identical to attacks against the base model. Gradient masking
124+
is a documented false defense (Athalye et al., 2018) that makes a model look
125+
robust while leaving it vulnerable, so it does not belong in a robustness
126+
library. Mask gradients in your own `train_step` if you want the training
127+
regulariser, and never report it as a security measure.
123128
- The `setup.py`-based `{{VERSION_PLACEHOLDER}}` release mechanism.
124129

125130
## [0.1.5]

‎CODE_REVIEW.md‎

Lines changed: 0 additions & 371 deletions
This file was deleted.

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Thank you for considering contributing to **DeepDefend**! Contributions, whether
1818
Before and after making changes, run the test-suite and the linter:
1919

2020
```bash
21-
pytest # 171 tests covering attacks, defenses and the public API
21+
pytest # 170 tests covering attacks, defenses and the public API
2222
ruff check . # lint
2323
```
2424

‎deepdefend/__init__.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747
"feature_denoising",
4848
"feature_squeezing",
4949
"gaussian_blur",
50-
"gradient_masking",
5150
"input_transformation",
5251
"jpeg_compression",
5352
"median_smoothing",

‎deepdefend/defenses.py‎

Lines changed: 0 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
Available functions:
1515
- `adversarial_training(model, x, y, epsilon=0.01)`: Adversarial Training.
1616
- `feature_squeezing(model, bit_depth=4)`: Feature Squeezing.
17-
- `gradient_masking(model, mask_threshold=0.1)`: Gradient Masking (training regulariser, *not* a defense).
1817
- `input_transformation(model, transformation_function)`: Input Transformation.
1918
- `defensive_distillation(model, teacher_model, temperature=2)`: Defensive Distillation.
2019
- `randomized_smoothing(model, noise_level=0.1)`: Randomized Smoothing (inference-time noise).
@@ -34,7 +33,6 @@
3433
from __future__ import annotations
3534

3635
import math
37-
import warnings
3836

3937
import numpy as np
4038
import tensorflow as tf
@@ -56,7 +54,6 @@
5654
"feature_denoising",
5755
"feature_squeezing",
5856
"gaussian_blur",
59-
"gradient_masking",
6057
"input_transformation",
6158
"jpeg_compression",
6259
"median_smoothing",
@@ -582,85 +579,6 @@ def adversarial_training(model, x, y, epsilon=0.01, epochs=10, batch_size=32,
582579
return defended_model
583580

584581

585-
@tf.keras.utils.register_keras_serializable(package="deepdefend")
586-
class GradientMaskingModel(tf.keras.Model):
587-
"""Training wrapper that drops gradients below ``threshold``.
588-
589-
.. warning::
590-
This is a *training regulariser*, not an adversarial defense. It does
591-
not alter the gradients an attacker computes at inference time.
592-
"""
593-
594-
def __init__(self, base_model=None, mask_threshold=0.1, **kwargs):
595-
super().__init__(**kwargs)
596-
self.base_model = base_model
597-
self.mask_threshold = mask_threshold
598-
599-
def call(self, inputs, training=None):
600-
return self.base_model(inputs, training=training)
601-
602-
def train_step(self, data):
603-
x, y = data[0], data[1]
604-
with tf.GradientTape() as tape:
605-
predictions = self.base_model(x, training=True)
606-
loss = self.compiled_loss(y, predictions)
607-
608-
trainable = self.base_model.trainable_variables
609-
gradients = tape.gradient(loss, trainable)
610-
pairs = [
611-
(tf.where(tf.abs(g) > self.mask_threshold, g, tf.zeros_like(g)), v)
612-
for g, v in zip(gradients, trainable) if g is not None
613-
]
614-
self.optimizer.apply_gradients(pairs)
615-
self.compiled_metrics.update_state(y, predictions)
616-
return {m.name: m.result() for m in self.metrics}
617-
618-
def get_config(self):
619-
config = super().get_config()
620-
config.update(
621-
base_model=tf.keras.utils.serialize_keras_object(self.base_model),
622-
mask_threshold=self.mask_threshold,
623-
)
624-
return config
625-
626-
@classmethod
627-
def from_config(cls, config):
628-
config = dict(config)
629-
config["base_model"] = tf.keras.utils.deserialize_keras_object(config["base_model"])
630-
return cls(**config)
631-
632-
633-
def gradient_masking(model, mask_threshold=0.1):
634-
"""
635-
Gradient Masking "defense".
636-
637-
Zeroes training gradients smaller than ``mask_threshold``.
638-
639-
.. warning::
640-
Gradient masking is a well documented **false** defense (Athalye et al.,
641-
"Obfuscated Gradients Give a False Sense of Security", 2018). It has no
642-
effect on the gradients an attacker sees, and it can make a model look
643-
robust while remaining vulnerable. Use it only as a training
644-
regulariser, never as evidence of robustness.
645-
646-
Parameters:
647-
model (tensorflow.keras.Model): The model to wrap.
648-
mask_threshold (float): Threshold below which gradients are zeroed.
649-
650-
Returns:
651-
defended_model (tensorflow.keras.Model): The wrapped model.
652-
"""
653-
mask_threshold = check_float("mask_threshold", mask_threshold, minimum=0.0)
654-
warnings.warn(
655-
"gradient_masking() does not defend against inference-time attacks; "
656-
"it only modifies training gradients. Do not treat it as a robustness "
657-
"measure.",
658-
RuntimeWarning,
659-
stacklevel=2,
660-
)
661-
return GradientMaskingModel(base_model=model, mask_threshold=mask_threshold)
662-
663-
664582
def _temperature_softmax(outputs, temperature, from_logits):
665583
"""Temperature-scaled softmax that works for logits and probabilities."""
666584
if from_logits:

0 commit comments

Comments
 (0)