@@ -315,210 +315,7 @@ Keras model, not inferred from reading it.
315315
316316How the fixes are guarded today: 170 tests (` pytest ` ), ` ruff check . ` , a CI
317317workflow on Python 3.10 – 3.12, and a release workflow that refuses to publish
318- when the tag and ` pyproject.toml ` version disagree or the tests fail.
319-
320- ## Documentation update brief (for the docs agent)
321-
322- The block below is a self-contained brief. It is a code cell so it renders as
323- plain text: paste it into the docs agent as-is after any API change.
324-
325- ``` text
326- DOCS AGENT BRIEF — DeepDefend 0.2.0
327- ===================================
328-
329- CONTEXT
330- -------
331- Repository: Infinitode/DeepDefend (PyPI package: deepdefend)
332- Branch merged: arena/b52ef87b-deepdefend, released as version 0.2.0.
333- Published docs live at:
334- https://infinitode-docs.gitbook.io/documentation/package-documentation/deepdefend-package-documentation
335-
336- 0.2.0 is a correctness release. Several public functions were broken or silently
337- wrong before it; the API changed accordingly. The docs must describe the 0.2.0
338- behaviour only. Do not keep pages that document 0.1.x behaviour, except in the
339- "Migration from 0.1.x" page described below.
340-
341- TASKS
342- -----
343- 1. Add a "What's new in 0.2.0" page, linking to CHANGELOG.md in the repo.
344- 2. Create a "Migration from 0.1.x" page (breaking changes; see section below).
345- 3. Update every per-function page for the attacks and defenses listed.
346- 4. Remove the gradient_masking page entirely and redirect it to the new
347- "Gradient masking is not a defense" note under Limitations.
348- 5. Update the supported-model-types table so it matches the README exactly.
349- 6. Update the Python version support statement to 3.9-3.12.
350- 7. Add the "Limitations" and "Responsible use" sections verbatim from the README.
351- 8. Add code samples for every function, using 0.2.0 signatures (see below).
352-
353- REMOVED IN 0.2.0
354- ----------------
355- gradient_masking(model, mask_threshold=0.1)
356- - Deleted from the package. hasattr(deepdefend, "gradient_masking") is False.
357- - Reason: it only masked training gradients, never the gradients an attacker
358- computes at inference, so it provided no protection (verified: attacks
359- against a wrapped model were bit-identical to attacks against the base
360- model). Gradient masking is a documented false defense (Athalye et al.,
361- 2018, "Obfuscated Gradients Give a False Sense of Security").
362- - Docs action: delete the page; state clearly that the technique creates a
363- false sense of security and that gradient regularisation belongs in the
364- user's own train_step, never in a robustness claim.
365-
366- CHANGED SIGNATURES AND DEFAULTS (attacks)
367- -----------------------------------------
368- All attacks additionally accept: from_logits=None, clip_min=None, clip_max=None
369- and return a NumPy array with the same shape and dtype as the input.
370-
371- fgsm(model, x, y, epsilon=0.01, *, targeted=False, from_logits=None,
372- clip_min=None, clip_max=None)
373- - Output is clipped to the valid data range (used to be unclipped).
374- - New: targeted.
375-
376- pgd(model, x, y, epsilon=0.01, alpha=None, num_steps=10, *, random_start=True,
377- seed=None, targeted=False, from_logits=None, clip_min=None, clip_max=None)
378- - alpha now defaults to epsilon / 4 (used to be a fixed 0.01).
379- - New: random_start, seed, targeted.
380-
381- bim(model, x, y, epsilon=0.01, alpha=None, num_steps=10, *, seed=None,
382- targeted=False, from_logits=None, clip_min=None, clip_max=None)
383- - Now documented as PGD without a random start (they used to be identical).
384-
385- mim(model, x, y, epsilon=0.01, alpha=None, num_steps=10, decay_factor=1.0, *,
386- seed=None, targeted=False, from_logits=None, clip_min=None, clip_max=None)
387- - Momentum is now normalised per sample, not across the batch.
388-
389- cw(model, x, y, epsilon=None, c=10.0, kappa=0.0, num_steps=100, alpha=0.01, *,
390- targeted=False, from_logits=None, clip_min=None, clip_max=None)
391- - This is now the real Carlini & Wagner L2 attack (tanh-space optimisation of
392- ||delta||^2 + c * margin).
393- - epsilon defaults to None (unconstrained). If set, it is an L2 budget
394- expressed as an L-infinity equivalent: radius = epsilon * sqrt(num_features).
395- - c and kappa now genuinely change the result; document that c trades
396- distortion against the margin and should be swept to minimise distortion.
397- - The untargeted target class is the runner-up class of the original input.
398-
399- deepfool(model, x, y, num_steps=50, epsilon=None, overshoot=0.02, *,
400- from_logits=None, clip_min=None, clip_max=None)
401- - Now computes per-class decision boundaries and respects epsilon / clip range
402- (used to return out-of-range images and ignore any budget).
403-
404- jsma(model, x, y, theta=0.0, gamma=0.2, num_steps=10, *, targeted=False,
405- from_logits=None, clip_min=None, clip_max=None)
406- - theta defaults to 0.0 (always pick the most salient feature); raw saliency
407- values are products of two gradients and therefore tiny.
408-
409- spsa(model, x, y, epsilon=0.01, num_steps=50, learning_rate=0.05, delta=None,
410- spsa_samples=32, *, seed=None, targeted=False, from_logits=None,
411- clip_min=None, clip_max=None)
412- - Accepts any batch size and any input rank.
413- - delta defaults to epsilon / 5.
414-
415- ead(model, x, y, epsilon=0.01, beta=0.001, num_steps=50, alpha=0.01, *, c=0.1,
416- kappa=0.0, targeted=False, from_logits=None, clip_min=None, clip_max=None)
417- - beta defaults to 0.001 (0.01 made the default attack a no-op).
418-
419- word_swap(text, swap_dict=None, max_swaps=None, seed=None)
420- - swap_dict is now required (ValueError when missing).
421- - Whitespace, newlines and punctuation are preserved.
422-
423- char_swap(text, swap_prob=0.1, seed=None)
424- - Whitespace/punctuation preserved; adds seed.
425-
426- LABEL HANDLING (document as a shared concept)
427- ---------------------------------------------
428- Every attack accepts one-hot (batch, classes), sparse integer (batch,) and
429- binary (batch, 1) targets. from_logits is auto-detected from the last layer and
430- can be overridden. clip_min/clip_max are inferred: [0, 1] when the batch already
431- lies in that range, otherwise no clipping (so normalised inputs are not
432- destroyed). Iterative attacks stop working on a sample once it reaches the goal,
433- so already-misclassified samples are returned unchanged.
434-
435- NEW FUNCTIONS (defenses)
436- ------------------------
437- smooth_predict(model, x, n_samples=100, noise_level=None, seed=None)
438- - Monte-Carlo prediction for randomized_smoothing models.
439- - Returns dict with keys: predictions, probabilities, certified_radius.
440- - certified_radius = sigma * Phi^-1(p_hat) for the majority class, or 0.
441- - Document that it requires a noise-trained base model.
442-
443- FeatureDenoisingBlock(kernel_size=3)
444- - Keras layer to insert inside a network for feature-level denoising
445- (learned residual box filter, starts as an identity).
446-
447- defenses.FeatureDenoisingBlock is importable as
448- `from deepdefend.defenses import FeatureDenoisingBlock`.
449-
450- CHANGED DEFENSE SIGNATURES
451- --------------------------
452- adversarial_training(model, x, y, epsilon=0.01, epochs=10, batch_size=32,
453- attack=None, optimizer=None, loss=None, verbose=1,
454- shuffle=True)
455- - Generates adversarial examples in batches, keeps the caller's optimiser and
456- loss, returns a NEW model (a clone).
457-
458- defensive_distillation(model, teacher_model, temperature=2)
459- - Distillation loss is scaled by T^2; the teacher runs in inference mode.
460-
461- adversarial_logit_pairing(model, paired_model=None, epsilon=0.01, num_steps=1,
462- alpha=None)
463- - Generates adversarial examples inside the training step.
464-
465- feature_denoising(model, method="median", kernel_size=3, sigma=1.0)
466- spatial_smoothing(model, kernel_size=3, method="median", sigma=1.0)
467- median_smoothing(model, kernel_size=3) # alias of spatial_smoothing(median)
468- gaussian_blur(model, kernel_size=3, sigma=1.0) # sigma is now used
469- randomized_smoothing(model, noise_level=0.1, seed=None,
470- add_noise_at_inference=True)
471- pixel_deflection(model, deflection_count=100, window_size=10, seed=None)
472- thermometer_encoding(model, num_bins=10)
473- word_masking(text, mask_token="[MASK]", mask_prob=0.1, seed=None)
474- input_transformation(model, transformation_function) # now REQUIRED
475-
476- BEHAVIOUR THE DOCS MUST STATE
477- -----------------------------
478- 1. All preprocessing defenses return a tf.keras.Model that can be saved with
479- model.save() and reloaded with tf.keras.models.load_model() without
480- custom_objects.
481- 2. Image-only defenses (gaussian_blur, median_smoothing, spatial_smoothing,
482- jpeg_compression, pixel_deflection, total_variation_minimization,
483- feature_denoising) raise ValueError on non-4-D inputs instead of silently
484- returning the input. JPEG requires 1 or 3 channels.
485- 3. Subclassed or multi-input models raise TypeError: these defenses need a
486- Functional/Sequential model with a known input_shape.
487- 4. Invalid parameters raise ValueError instead of producing NaN:
488- bit_depth must be 1-8, num_bins >= 2, quality 1-100, kernel sizes odd,
489- noise levels >= 0, epsilon >= 0, num_steps >= 1.
490- 5. feature_squeezing, jpeg_compression and total_variation_minimization use a
491- straight-through gradient so gradient-based attacks against a defended model
492- still work.
493- 6. word_masking, word_swap and char_swap preserve whitespace, newlines and
494- punctuation exactly.
495- 7. All randomized helpers accept seed= and are reproducible when it is set.
496-
497- MIGRATION FROM 0.1.x (new page)
498- -------------------------------
499- - gradient_masking() no longer exists; remove it from user code.
500- - Results produced with cw, deepfool, ead, spsa or jsma under 0.1.x are invalid
501- and should be re-run.
502- - cw: the first positional argument after `y` is still epsilon, but its default
503- is now None and its meaning is an optional L2 budget.
504- - jsma: theta now defaults to 0.0.
505- - pgd/bim/mim: alpha now defaults to epsilon / 4; pass alpha explicitly to keep
506- the old step size.
507- - spsa: no longer restricted to batch size 1 or rank-4 inputs.
508- - Attacks now accept sparse labels, so `y.argmax(-1)` no longer needs
509- converting to one-hot.
510- - Defended models saved with 0.1.x cannot be loaded; retrain or re-wrap them.
511- - Python 3.9+ is required.
512-
513- TONE / FORMAT
514- -------------
515- - Each function page: one-line description, signature block, parameters table,
516- returns, a runnable example, and a "Caveats" note.
517- - Be explicit that preprocessing defenses are not robustness guarantees; link to
518- the Limitations page.
519- - Never present an attack's success rate as a defense's guarantee.
520- - Code samples must be copy-pasteable and use only public API.
521- ```
318+ when the tag and ` pyproject.toml ` version disagree, or the tests fail.
522319
523320## Responsible use
524321
0 commit comments