Skip to content

Commit 70f1ada

Browse files
Arena Agentarena-agent
andcommitted
fix: correctness and security pass over attacks and defenses (0.2.0)
Several public functions either raised on every call or returned silently wrong results. This makes each function do what its name claims, and adds the guardrails (tests, lint, packaging, CI) that were missing. Attacks - jsma: was indexing a rank-4 Jacobian with 5 indices and mutating an eager tensor in place; rewritten as a real saliency-map attack for any input rank. - spsa: passed a tensor (not a tf.Variable) to the optimizer and hard-coded rank-4 inputs; now a correct finite-difference estimate with Adam. - ead: returned the input unchanged with default args (alpha == beta); now a proper ISTA/proximal step on the elastic-net objective. - cw: the L2 term and kappa were inert (x was already clipped); now a real tanh-space C&W with a fixed target class. - deepfool: ignored any budget and returned out-of-range values; now computes per-class boundaries and respects epsilon/clip range. - fgsm: output is clipped to the valid range. - all attacks: accept sparse/one-hot/binary labels, honour from_logits, call the model with training=False, support clip_min/clip_max, and no longer freeze targeted attacks at step 0. - deepfool/jsma/spsa no longer project against the whole batch. - word_swap/char_swap preserve whitespace, newlines and punctuation. Defenses - every preprocessing defense can now be saved/reloaded (layers were defined inside function bodies, so no defended model was serialisable). - jpeg_compression, feature_squeezing, total_variation_minimization: restore the gradient via straight-through so attacks against a defended model work. - median_smoothing is a real median filter (was avg_pool2d); gaussian_blur honours sigma (was avg_pool2d). - pixel_deflection no longer raises; deterministic when seeded. - adversarial_training batches attack generation and keeps the caller's optimizer/loss; defensive_distillation stops double-applying softmax and scales by T^2; ALP now generates adversarial examples; gradient_masking warns that it is not a security defense. - randomized_smoothing clips and is seedable, plus smooth_predict() with a certified-radius estimate. - invalid parameters raise instead of producing NaN; subclassed/multi-input models get a clear TypeError. Packaging / CI / docs - replace setup.py ({{VERSION_PLACEHOLDER}}) with pyproject.toml; pip install . works from a checkout again. - bound dependencies, require Python >= 3.9. - add 171 tests, ruff config and a CI workflow; rewrite the publish workflow with SHA-pinned actions, a tag/version check, a test gate and PyPI Trusted Publishing. - add SECURITY.md, CODE_OF_CONDUCT.md, CHANGELOG.md, CODE_REVIEW.md, Dependabot and pre-commit; correct the README support matrix. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
1 parent cda6c32 commit 70f1ada

22 files changed

Lines changed: 4011 additions & 923 deletions

‎.github/dependabot.yml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
version: 2
2+
updates:
3+
- package-ecosystem: "pip"
4+
directory: "/"
5+
schedule:
6+
interval: "weekly"
7+
open-pull-requests-limit: 5
8+
9+
- package-ecosystem: "github-actions"
10+
directory: "/"
11+
schedule:
12+
interval: "weekly"

‎.github/workflows/build_and_publish.yml‎

Lines changed: 56 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,63 @@ name: Publish Python 🐍 distributions 📦 to PyPI
33
on:
44
push:
55
tags:
6-
- '*'
6+
- "v*"
7+
8+
# Least privilege at the workflow level; the publish job widens `id-token` only.
9+
permissions:
10+
contents: read
711

812
jobs:
9-
build-n-publish:
10-
name: Build and publish Python 🐍 distributions 📦 to PyPI
13+
build:
14+
name: Build and verify distributions
15+
runs-on: ubuntu-latest
16+
steps:
17+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
18+
with:
19+
persist-credentials: false
20+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
21+
with:
22+
python-version: "3.12"
23+
- name: Install build tooling
24+
run: |
25+
python -m pip install --upgrade pip build twine
26+
- name: Verify the tag matches the packaged version
27+
run: |
28+
python - <<'PY'
29+
import os, sys, tomllib
30+
tag = os.environ["GITHUB_REF_NAME"].lstrip("v")
31+
with open("pyproject.toml", "rb") as fh:
32+
version = tomllib.load(fh)["project"]["version"]
33+
if tag != version:
34+
sys.exit(f"Tag {tag!r} does not match pyproject version {version!r}")
35+
print(f"Building {version}")
36+
PY
37+
- name: Run the test-suite before publishing
38+
run: |
39+
python -m pip install -e ".[dev]"
40+
python -m pytest -q
41+
- name: Build sdist and wheel
42+
run: |
43+
python -m build
44+
python -m twine check dist/*
45+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
46+
with:
47+
name: dist
48+
path: dist/
49+
50+
publish:
51+
name: Publish to PyPI
52+
needs: build
1153
runs-on: ubuntu-latest
54+
environment:
55+
name: pypi
56+
url: https://pypi.org/project/deepdefend/
57+
permissions:
58+
# Trusted Publishing (OIDC). No long-lived API token is stored.
59+
id-token: write
1260
steps:
13-
- uses: actions/checkout@master
14-
- name: Set up Python 3.12
15-
uses: actions/setup-python@v3
16-
with:
17-
python-version: '3.12'
18-
- name: Install pypa/setuptools
19-
run: >-
20-
python -m
21-
pip install setuptools wheel
22-
- name: Extract tag name
23-
id: tag
24-
run: echo ::set-output name=TAG_NAME::$(echo $GITHUB_REF | cut -d / -f 3)
25-
- name: Update version in setup.py
26-
run: >-
27-
sed -i "s/{{VERSION_PLACEHOLDER}}/${{ steps.tag.outputs.TAG_NAME }}/g" setup.py
28-
- name: Build a binary wheel
29-
run: >-
30-
python setup.py sdist bdist_wheel
31-
- name: Publish distribution 📦 to PyPI
32-
uses: pypa/gh-action-pypi-publish@master
33-
with:
34-
password: ${{ secrets.PYPI_API_TOKEN }}
61+
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
62+
with:
63+
name: dist
64+
path: dist/
65+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1

‎.github/workflows/ci.yml‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches: [master, main]
6+
pull_request:
7+
workflow_dispatch:
8+
9+
permissions:
10+
contents: read
11+
12+
concurrency:
13+
group: ci-${{ github.ref }}
14+
cancel-in-progress: true
15+
16+
jobs:
17+
lint:
18+
name: Lint
19+
runs-on: ubuntu-latest
20+
steps:
21+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
22+
with:
23+
persist-credentials: false
24+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
25+
with:
26+
python-version: "3.12"
27+
- name: Install ruff
28+
run: python -m pip install "ruff>=0.6"
29+
- name: Ruff
30+
run: ruff check .
31+
32+
test:
33+
name: Tests (Python ${{ matrix.python-version }})
34+
runs-on: ubuntu-latest
35+
strategy:
36+
fail-fast: false
37+
matrix:
38+
python-version: ["3.10", "3.11", "3.12"]
39+
steps:
40+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
41+
with:
42+
persist-credentials: false
43+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
44+
with:
45+
python-version: ${{ matrix.python-version }}
46+
cache: pip
47+
- name: Install package
48+
run: |
49+
python -m pip install --upgrade pip
50+
python -m pip install -e ".[dev]"
51+
- name: Run tests
52+
run: python -m pytest -q
53+
54+
build:
55+
name: Build distribution
56+
runs-on: ubuntu-latest
57+
needs: [lint, test]
58+
steps:
59+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
60+
with:
61+
persist-credentials: false
62+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
63+
with:
64+
python-version: "3.12"
65+
- name: Build sdist and wheel
66+
run: |
67+
python -m pip install --upgrade pip build twine
68+
python -m build
69+
python -m twine check dist/*
70+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
71+
with:
72+
name: dist
73+
path: dist/

‎.gitignore‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1-
__pycache__
2-
*.pyc
1+
__pycache__/
2+
*.py[cod]
3+
*.egg-info/
34
dist/
45
build/
5-
venv/
6+
venv/
7+
.venv/
8+
.pytest_cache/
9+
.ruff_cache/
10+
.coverage
11+
htmlcov/

‎.pre-commit-config.yaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
repos:
2+
- repo: https://github.com/astral-sh/ruff-pre-commit
3+
rev: 75b98813cfb7e663870a28c74366a1e99d7bfe79 # v0.6.9
4+
hooks:
5+
- id: ruff
6+
args: [--fix]

‎CHANGELOG.md‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# Changelog
2+
3+
All notable changes to DeepDefend are documented here. The format loosely
4+
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this
5+
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6+
7+
## [0.2.0]
8+
9+
This release is a correctness and security pass over the whole package. Many
10+
functions that previously returned *silently wrong* results (or crashed) now do
11+
what their name and documentation claim. Because the numerical output of several
12+
attacks and defenses changes, the minor version was bumped.
13+
14+
### Fixed — attacks
15+
16+
- **`jsma`** no longer raises on every call (it indexed a rank-4 Jacobian with
17+
five indices and mutated an eager tensor in place). It is now a real
18+
saliency-map attack that works on any input rank.
19+
- **`spsa`** no longer raises on every call (it passed a tensor, not a
20+
`tf.Variable`, to the optimizer and hard-coded rank-4 inputs). The gradient
21+
estimate now uses the correct finite difference
22+
`(L(x+δd) − L(x−δd)) / (2δ)`, the optimiser is Adam, and any number of
23+
samples and dimensions is accepted.
24+
- **`ead`** no longer returns the input unchanged with its default arguments.
25+
It now performs a proper ISTA/proximal step on the elastic-net objective.
26+
- **`cw`** is now the Carlini & Wagner L2 attack: the tanh-space optimisation
27+
actually minimises distortion and the `c` / `kappa` parameters change the
28+
result (previously they were inert). The untargeted target class is fixed at
29+
the runner-up class instead of being recomputed every step.
30+
- **`deepfool`** is now DeepFool: per-class decision boundaries, an optional
31+
L∞ budget, and output that stays inside the valid data range (it used to
32+
return values such as `-0.90` and `2.08` for `[0, 1]` inputs).
33+
- **`fgsm`** output is clipped to the valid data range instead of overshooting
34+
to `-0.01` / `1.007`.
35+
- **All attacks** now accept sparse integer labels, one-hot labels and binary
36+
targets; previously every attack rejected the sparse-label format used by most
37+
Keras examples.
38+
- **All attacks** now auto-detect `from_logits` (with an override), call the
39+
model with `training=False`, and support an explicit `clip_min` / `clip_max`
40+
for normalised inputs.
41+
- **Targeted attacks** no longer freeze at step 0 (the early-stop mask had the
42+
logic inverted for targeted mode).
43+
- **`pgd`** gained `random_start` and no longer duplicates `bim`.
44+
- **DeepFool / JSMA / SPSA** no longer project against the whole batch inside
45+
their per-sample loops.
46+
- **`word_swap` / `char_swap`** preserve whitespace, newlines and punctuation,
47+
accept a `seed`, and `word_swap` no longer silently returns the input when
48+
`swap_dict` is missing.
49+
50+
### Fixed — defenses
51+
52+
- **All preprocessing defenses** can now be saved and reloaded. Their layers
53+
were previously defined inside the function body, so every defended model
54+
failed at `model.save()` / `load_model()`.
55+
- **`jpeg_compression`**, **`feature_squeezing`** and
56+
**`total_variation_minimization`** no longer break the gradient: attacks
57+
against a defended model used to raise `ValueError` (JPEG) or silently return
58+
a zero perturbation (TV, quantisation). They now use a straight-through
59+
gradient.
60+
- **`median_smoothing`** is a real median filter again (it was calling
61+
`avg_pool2d`).
62+
- **`gaussian_blur`** builds an actual Gaussian kernel and honours `sigma`
63+
(the parameter was previously ignored).
64+
- **`pixel_deflection`** no longer raises on every call, works inside
65+
`tf.function`, and is reproducible when a `seed` is given.
66+
- **`adversarial_training`** generates adversarial examples in batches instead
67+
of one sample at a time (~500× fewer model calls), honours the caller's
68+
optimiser and loss instead of forcing Adam + categorical cross-entropy, and
69+
accepts `epochs`, `batch_size`, `verbose` and a custom `attack`.
70+
- **`defensive_distillation`** no longer applies softmax twice, scales the
71+
distillation term by `T²`, evaluates the teacher in inference mode, and works
72+
for both probability and logit outputs.
73+
- **`adversarial_logit_pairing`** generates adversarial examples inside the
74+
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.
78+
- **`randomized_smoothing`** clips the noisy input, is reproducible when
79+
seeded, and ships with `smooth_predict()` for Monte-Carlo prediction and a
80+
certified-radius estimate.
81+
- **`feature_denoising`** has an explicit `method` (`median` / `gaussian`) and a
82+
new `FeatureDenoisingBlock` layer for feature-level denoising.
83+
- **`input_transformation`** raises instead of silently returning an
84+
undefended model when no transformation is given.
85+
- **`word_masking`** preserves whitespace and accepts a `seed`.
86+
- **All defenses** raise a clear `TypeError` for subclassed or multi-input
87+
models instead of an obscure `AttributeError`, and reject invalid parameters
88+
(`bit_depth` outside 1-8, `num_bins < 2`, `quality` outside 1-100, even kernel
89+
sizes, negative noise levels, ...) instead of producing `NaN`.
90+
91+
### Added
92+
93+
- `deepdefend.__version__`, `deepdefend.__all__`, and lazy imports: every public
94+
function is reachable as `deepdefend.<name>`, and `import deepdefend` no
95+
longer imports TensorFlow.
96+
- `deepdefend/smooth_predict` for Monte-Carlo randomized smoothing.
97+
- 164 tests covering attacks, defenses, serialisation, gradients, label
98+
formats, input validation and the public API.
99+
- CI: lint + test matrix (3.10-3.12) + reproducible build on every push and PR.
100+
- `SECURITY.md`, `CODE_OF_CONDUCT.md`, Dependabot, pre-commit and
101+
`pyproject.toml`.
102+
103+
### Changed
104+
105+
- `setup.py` was replaced by `pyproject.toml`; the version is now static and
106+
`pip install .` works from a checkout (it previously failed because the
107+
version was a `{{VERSION_PLACEHOLDER}}`).
108+
- Dependencies are bounded (`numpy<3`, `tensorflow>=2.13,<3`) and
109+
`python_requires` is `>=3.9` (TensorFlow 2.x is not available on 3.6-3.8).
110+
- `pgd` / `bim` / `mim` default `alpha` is now `epsilon / 4` (previously
111+
`0.01`, which equals `epsilon` for the default settings).
112+
- `jsma` defaults are `theta=0.0`, `gamma=0.2`.
113+
- `cw` defaults are `epsilon=None` (unconstrained), `c=10.0`.
114+
- `spsa` defaults are `num_steps=50`, `learning_rate=0.05`, `spsa_samples=32`
115+
probe directions, `delta=epsilon/5`.
116+
- `median_smoothing` is documented as an alias of `spatial_smoothing`.
117+
- The publish workflow uses SHA-pinned actions, a tag/version consistency check,
118+
a test gate, `python -m build`, `twine check`, PyPI Trusted Publishing (OIDC)
119+
and a protected `pypi` environment.
120+
121+
### Removed
122+
123+
- The `setup.py`-based `{{VERSION_PLACEHOLDER}}` release mechanism.
124+
125+
## [0.1.5]
126+
127+
- Added MIM and EAD attacks, word/character swap attacks, pixel deflection,
128+
Gaussian blur, TV minimisation and median smoothing defenses, word masking,
129+
and a support table.
130+
131+
## [0.1.4]
132+
133+
- Added the SPSA attack and the JPEG compression defense.
134+
135+
## [0.1.3]
136+
137+
- Added randomized smoothing, feature denoising, thermometer encoding,
138+
adversarial logit pairing and spatial smoothing.
139+
140+
## [0.1.2]
141+
142+
- Three new attacks and three new defenses.

‎CODE_OF_CONDUCT.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Code of Conduct
2+
3+
## Our pledge
4+
5+
We as members, contributors, and maintainers pledge to make participation in the
6+
DeepDefend community a harassment-free experience for everyone, regardless of
7+
age, body size, visible or invisible disability, ethnicity, sex characteristics,
8+
gender identity and expression, level of experience, education, socio-economic
9+
status, nationality, personal appearance, race, religion, or sexual identity and
10+
orientation.
11+
12+
## Our standards
13+
14+
Examples of behaviour that contributes to a positive environment:
15+
16+
- Demonstrating empathy and kindness toward other people.
17+
- Being respectful of differing opinions, viewpoints, and experiences.
18+
- Giving and gracefully accepting constructive feedback.
19+
- Accepting responsibility and apologising to those affected by our mistakes.
20+
- Focusing on what is best for the community and the project.
21+
22+
Examples of unacceptable behaviour:
23+
24+
- The use of sexualised language or imagery, and sexual attention of any kind.
25+
- Trolling, insulting or derogatory comments, and personal or political attacks.
26+
- Public or private harassment.
27+
- Publishing others' private information without their explicit permission.
28+
- Submitting attack code intended to harm third-party systems, or requesting
29+
help to do so.
30+
- Other conduct which could reasonably be considered inappropriate in a
31+
professional setting.
32+
33+
## Enforcement
34+
35+
Instances of abusive, harassing, or otherwise unacceptable behaviour may be
36+
reported to the maintainers at **infinitode.ltd@gmail.com**. All complaints will
37+
be reviewed and investigated promptly and fairly, and the privacy and security
38+
of the reporter will be respected.
39+
40+
Maintainers may remove, edit or reject comments, commits, code, issues and other
41+
contributions that are not aligned with this Code of Conduct, and will
42+
communicate the reasons for moderation decisions when appropriate.
43+
44+
## Attribution
45+
46+
This Code of Conduct is adapted from the
47+
[Contributor Covenant](https://www.contributor-covenant.org), version 2.1.

0 commit comments

Comments
 (0)