CoolFace
Modelpublic

ericyoc/the_applied_ai_universe_adversarial_defenses

sourceHugging Facemitupdated 2mo agoView on Hugging Face
0likes
Model Card

The Applied AI Universe: Adversarial Defenses Coding Guide

Hardening Every Model in the AI Universe

![Open Classical Notebook in Colab](https://colab.research.google.com/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesClassical.ipynb) [![Open Hybrid & Quantum Notebook in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesHybrid_Quantum.ipynb) ![Python 3.10+](https://www.python.org/) ![TensorFlow](https://tensorflow.org/) ![PennyLane](https://pennylane.ai/) ![Hugging Face](https://huggingface.co/)


<p align="center"> <em>Book 1 builds the models. Book 2 breaks them. Book 3 hardens them — all within one shared model universe.</em> </p>



The Adaptive AI Codex Series

BookAmazonModels
1 — Build The Applied AI Universe Coding GuideAmazonHub
2 — Break Adversarial AttacksAmazonHub
3 — Defend Adversarial Defenses (this repo)AmazonHub

Book 3 — 601 pages, 37 chapters, ISBN 9798188703509. Series overview: ericyocam.com


Overview

This repository is Book 3 of The Applied AI Universe series. Book 2 attacks the models created in Book 1; Book 3 reconstructs those attacks and applies a corresponding defense to each victim.

The notebooks do not treat success against a static, original attack as sufficient evidence of robustness. Each experiment follows the same evaluation loop:

  1. 1.reconstruct the Book 2 victim and attack;
  2. 2.measure the undefended result;
  3. 3.apply the defense;
  4. 4.measure clean and post-defense performance;
  5. 5.re-attack the defended system with an adaptive adversary that knows the defense is present; and
  6. 6.save figures, metrics, and leaderboards to Google Drive.

The notebooks intentionally retain weak, partial, and failed defenses. Negative results are part of the defensive evaluation rather than being removed from the record.

The headline result

Across the 29 defenses for which both a naive and an adaptive figure were measured:

Mean gain
Naive — against the original Book 2 attack+0.271
Adaptive — against an attacker who knows the defense is deployed+0.191

71% of the apparent benefit survives contact with a knowledgeable adversary. 29% does not. Reporting only the naive figures, as much published work does, would have overstated this repository's aggregate robustness by a factor of 1.42.

The loss is not evenly distributed, and the pattern is the finding:

Defense familynNaiveAdaptiveRetained
Engineering (integrity/provenance)7+0.344+0.344100%
Gold standard (adversarial training)12+0.182+0.17898%
Established4+0.292+0.12242%
Heuristic4+0.469+0.11324%
Demonstrably weak (detection)2+0.116+0.03328%

Integrity checks lose nothing to an adaptive attacker — a digest either matches or it does not, so knowing the check exists confers no advantage. Detection defenses lose most of their measured benefit, because the attacker adds the detector's threshold as a constraint on their search. Defense family predicts failure mode.

Repository Notebooks

NotebookCoverage
`Adversarial_Defenses_Classical.ipynb`29 classical victims spanning symbolic AI, classical machine learning, neural networks, deep learning, reinforcement learning, generative AI, NLP, diffusion, PEFT/LoRA, and state-space models
`Adversarial_Defenses_Hybrid_Quantum.ipynb`6 hybrid and quantum victims covering QAOA, VQC, Hybrid QNN, VQE, Quantum-Kernel SVM, and QGAN on PennyLane simulators

Both notebooks end with a Book 2 Commitments module. Book 2 closed each attack chapter with a mitigation preview, and not every promise is the lead defense of a chapter. These cells implement the remainder — perplexity detection, the Unicode confusables table, training-data deduplication, adapter provenance, the reward-model ensemble, encoding-perturbed training, encoding-sensitivity comparison, and fidelity-bounded evaluation. Each states the promise it delivers and logs nothing to the leaderboard, since the chapter's own cell owns that row.

Every cell carries a session guard, so any cell runs on its own after a runtime restart. The leaderboard cell is the exception: it reads a list the victim cells build during the session, so run the victims you care about first.

A locally downloaded notebook may include a duplicate suffix such as (1) or (2). The canonical repository filenames used by the badges are shown above.

Defense-Level Classification

Every defense is assigned a level in the notebook. The level identifies the maturity and evidentiary status of the defense family, not a guarantee that every implementation or run will withstand all adaptive attacks.

BadgeLevelMeaning
🟢GOLD STANDARDPeer-reviewed, widely replicated defense family that is appropriate to cite and build upon
🟢ESTABLISHEDWell-supported and conventional method, but not necessarily a formal or state-of-the-art adversarial robustness guarantee
🔵ENGINEERINGCorrect security engineering practice such as integrity verification, provenance checking, validation, or checkpoint recovery
🟡HEURISTICPractical mitigation with narrow assumptions and no general robustness guarantee
🔴DEMONSTRABLY WEAKA defense class known to be bypassable; retained intentionally to document the failure mode

A Gold Standard label does not mean the evaluated model is invulnerable. For example, adversarial training is a gold-standard defense family, yet a particular training budget, threat model, or implementation may still fail under a stronger adaptive attack — and the tier table above shows that family retaining 98%, not 100%, precisely because one FGSM-trained model lost half its gain to a stronger evaluation.


Why Weak and Failed Defenses Matter

Weak defenses are not included as filler, shortcuts, or substitutes for stronger methods. They are included because understanding why a plausible defense fails is one of the most important lessons in adversarial machine learning.

A defense may appear effective when tested only against the original attack, yet collapse once the attacker knows how the defense works. Reporting only successful defenses would hide this distinction and could encourage readers to deploy controls that create false confidence.

The weak-defense experiments serve five specific purposes:

  1. 1.They expose false security signals. A higher score against a fixed attack does not necessarily mean the defended system is robust.
  2. 2.They demonstrate adaptive bypasses. Thresholds, detectors, rejection rules, and preprocessing steps can often be incorporated into the attacker's optimization strategy.
  3. 3.They establish comparative baselines. Readers can see why a stronger defense is needed and what improvement it must provide.
  4. 4.They teach evaluation discipline. A negative result shows why defenses must be tested against attacks designed specifically for the defended model.
  5. 5.They support honest and reproducible research. Retaining failures prevents selective reporting and makes the notebooks more useful for education, peer review, and future work.

A sixth lesson: verify what a defense is allowed to see

An earlier revision of the semi-supervised cell rebuilt its screened label vector from the clean seed labels rather than the poisoned ones the defender actually holds. Every seed the screen happened to trust was silently restored to its true value, including poisoned seeds the screen had failed to detect. The cell ran without error and reported a gain of +0.345. Rebuilt from the labels a defender really has, the same screen recovers +0.024.

The defect is worth recording because it is invisible to the checks most people run: the code executes, the numbers are internally consistent, and the figure looks convincing. It is caught only by asking a question that is not about code at all — could a real defender obtain every input this defense consumes? A defense that reads the answer key is measuring nothing, and no amount of adaptive testing will reveal that, because the leak inflates the defended score under every attack equally.

The corrected cell and the corrected figures are in this repository. The original number is recorded here rather than quietly replaced, because the failure mode is more instructive than the result.

A seventh: a defense that fails is still a result

Fine-Pruning is a published, peer-reviewed backdoor defense. Applied to the LoRA adapter at 30% pruning, it did not remove the backdoor — the trigger fired before and after, and the measured gain is 0.000. That single configuration is not evidence about the method, and the notebook says so. What it does establish is narrower and generalizable: a defense whose mechanism is search provides nothing when the search fails, and the defender cannot distinguish a clean adapter from a failed search.

The lead defense for that victim is therefore adapter provenance — hashing and signing the adapter so any modification is detected before loading. It is trigger-agnostic, catches a change of 10⁻⁶ in a single weight, and is what Book 2 actually promised.

A DEMONSTRABLY WEAK label therefore means:

This defense is realistic enough to be tempting, but the notebook shows the conditions under which an informed attacker can bypass it.

Readers should interpret these experiments as diagnostic case studies: the defense is implemented, its initial benefit is measured, its assumptions are identified, the attacker is adapted to those assumptions, and the remaining weakness is documented.


Disclaimer

This repository is intended solely for education, reproducible defensive research, and authorized security evaluation. The attacks and defenses are applied only to the author's own models and publicly available benchmark datasets.

Reported performance depends on random seeds, runtime environment, package versions, compute resources, training budget, and cached model state. The included quantum experiments run on classical simulators through PennyLane's default.qubit; no physical quantum computer is required.

A defense that improves performance against the original attack may still fail against an adaptive or stronger attack. The notebooks report those failures explicitly.


Interactive Notebooks

GitHub may time out while rendering large notebooks. Open them directly in Google Colab or use nbviewer.

Classical Adversarial Defenses

![Open in Colab](https://colab.research.google.com/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesClassical.ipynb) [![View with nbviewer](https://img.shields.io/badge/render-nbviewer-orange.svg)](https://nbviewer.org/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesClassical.ipynb)

Hybrid and Quantum Adversarial Defenses

![Open in Colab](https://colab.research.google.com/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesHybridQuantum.ipynb) ![View with nbviewer](https://nbviewer.org/github/ericyoc/theappliedaiuniverseadversarialdefenses/blob/main/AdversarialDefensesHybridQuantum.ipynb)


Cross-Book Model–Attack–Defense Map

The table below connects the complete three-book progression:

  • —Book 1: the model or AI system being built;
  • —Book 2: the adversarial attack applied to that model; and
  • —Book 3: the corresponding defense evaluated against the original and adaptive attacks.

Classical Models

ModuleBook 1 — ModelBook 2 — AttackBook 3 — DefenseDefense Level
Symbolic AIPath-planning systemObstacle injectionSHA-256 occupancy-map integrity + restoration🔵 ENGINEERING
Symbolic AIExpert systemKnowledge-base poisoning through rule injectionProvenance-verified and signed rule registry🔵 ENGINEERING
Symbolic AIFuzzy-logic controllerMembership-function shiftCalibration-bound clamping🔵 ENGINEERING
Classical MLBreast Cancer feature pipelineLabel-flip data poisoningNeighbour-consensus data sanitization🟢 GOLD STANDARD
Classical MLSupervised Iris classifierAdversarial evasionAdversarial training🟢 GOLD STANDARD
Classical MLK-Means clustering modelCentroid poisoningRobust covariance estimator (MCD)🟢 GOLD STANDARD
Classical MLSemi-supervised classifierPseudo-label poisoningNeighbour-consensus seed screening🟡 HEURISTIC
Classical MLEnsemble classifierBlack-box evasion and transferDisagreement-based rejection🔴 DEMONSTRABLY WEAK
Neural NetworksMLP on MNIST (activations)FGSM/PGD evasionPGD adversarial training + gradient-masking diagnosis🟢 GOLD STANDARD
Neural NetworksPerceptronDecision-boundary perturbationMaximum-margin retraining🟢 ESTABLISHED
Neural NetworksMLP on MNIST (backprop)PGD evasionPGD adversarial training🟢 GOLD STANDARD
Neural NetworksCNN on MNIST / LSTM forecasterFGSM/PGD; temporal perturbationPGD adversarial training; adversarial training through time🟢 GOLD STANDARD
Neural NetworksSelf-Organizing MapBMU displacementMap coarsening + input smoothing + QE flagging🟢 ESTABLISHED
Deep LearningDNN on CIFAR-10FGSM/PGD evasionPGD adversarial training🟢 GOLD STANDARD
Deep LearningMobileNetV2 transfer modelFGSM/PGDAdversarial training on the head + backbone provenance🟢 GOLD STANDARD
Deep LearningGAN discriminatorMembership inferenceDP-SGD🟢 GOLD STANDARD
Deep LearningAttention mechanismKey-matrix perturbationKey/query normalization + temperature control🟢 ESTABLISHED
Deep LearningDropout neural networkFGSM/PGDAdversarial training, with a randomized-smoothing certificate🟢 GOLD STANDARD
Reinforcement LearningQ-Learning agentReward poisoningMedian aggregation + clipping + reward-function provenance🟢 ESTABLISHED
Deep LearningCapsule NetworkFGSM through dynamic routingBatched adversarial training🟢 GOLD STANDARD
Deep LearningDeep Belief NetworkBlack-box evasionReconstruction-error anomaly detection🔴 DEMONSTRABLY WEAK
Generative AIN-Gram language modelOOV token injectionOOV sanitization + perplexity detection🟡 HEURISTIC
NLPMulti-head self-attentionToken substitutionUnicode canonicalization + confusables table🟡 HEURISTIC
NLPPretrained NLU modelHomoglyph substitutionUnicode canonicalization🟡 HEURISTIC
NLPRetrieval chatbotQuery perturbationQuery normalization🟡 HEURISTIC
Generative AIDiffusion model / DDPMMembership inferenceDP-SGD + training-data deduplication🟢 GOLD STANDARD
PEFTLoRA adapterRare-token backdoorAdapter provenance + signatures🔵 ENGINEERING
AlignmentRLHF reward modelReward hacking through response lengthReward clipping with a length penalty🟡 HEURISTIC
State-Space ModelsMamba / SSM modelLong-range token perturbationCurriculum adversarial training🟢 GOLD STANDARD

Hybrid and Quantum Models

ModuleBook 1 — ModelBook 2 — AttackBook 3 — DefenseDefense Level
Quantum ClassificationVariational Quantum ClassifierQuantum FGSMPGD adversarial training + fidelity-bounded evaluation🟢 GOLD STANDARD
Hybrid Quantum MLHybrid quantum-classical neural networkFGSMAdversarial training🟢 GOLD STANDARD
Quantum EncodingQuantum encoding pipelineEncoding corruptionEncoding-perturbed training + encoding choice🟢 GOLD STANDARD
Quantum KernelsQuantum-Kernel SVMKernel-boundary evasionDistance-based anomaly rejection🔴 DEMONSTRABLY WEAK
Quantum Generative AIQuantum GANGenerator-weight poisoningSHA-256 parameter integrity + checkpoint recovery🔵 ENGINEERING
Quantum OptimizationQAOAParameter poisoningSHA-256 parameter integrity + checkpoint recovery🔵 ENGINEERING
Quantum ChemistryVariational Quantum EigensolverParameter-noise injectionSHA-256 parameter integrity + independent energy cross-check🔵 ENGINEERING

Executed Results — Classical

Every figure below is the output of an executed cell. Nine defenses produced a gain of zero or below; those rows are reported as measured rather than reframed.

VictimUndefendedDefendedAdaptive finding
Planning0.0001.000Integrity restoration recovered the valid plan; a hash has no threshold to sit beneath
Expert system0.6671.000A per-rule check is blind to deletion; a canonical whole-set digest closes it
Fuzzy controller0.8660.960An attacker who stays inside the calibrated range keeps most of the damage; the measured gain falls to +0.000
Feature pipeline0.8650.912Clustered poisoning makes each record's neighbours agree with it; not measured on this victim
Supervised classifier0.7560.800Gain holds under PGD; HopSkipJump is unbounded and adversarial training barely helps
K-Means0.1060.792Centroid shift fell from 8.46 to 0.26; poisoning past the configured contamination is not measured
Semi-supervised0.6380.662Corrected. The earlier cell read the clean seed vector, which a defender does not have; the reported +0.345 was an artefact
Ensemble0.0670.300Threshold-aware search cuts the gain from +0.233 to +0.066 — 28% retained
MLP (MNIST)0.0000.029Real and negligible; the gradient-masking diagnostic confirms no inversion
Perceptron0.2500.750Margin is geometric, so disclosure confers no advantage; robustness ends at the margin
CNN (MNIST)0.0480.658+0.610 at a clean cost of 0.025 — roughly 24× the MLP's exchange rate
LSTM forecaster0.9890.990Measured against random jitter, not a gradient attack; says nothing about an adversary
Self-Organizing Map0.3290.315Gaussian augmentation gives −0.014; coarsening and QE flagging are what Book 2 asked for
DNN (CIFAR-10)0.0010.010A tenfold gain on a model that is still almost entirely vulnerable, and 0.303 clean
MobileNetV2 transfer0.1300.496Only the head was hardened; gradients still traverse the frozen backbone
GAN discriminator0.5000.488DP-SGD gain −0.012; membership inference was already at chance, so there was no headroom
Attention0.9590.961Randomized smoothing gives +0.00 — a family-selection error; key/query normalization cuts shift 15×
Dropout network0.0000.006The ℓ₂ certificate never contained the ℓ∞ threat; the guarantee is inapplicable, not violated
Q-Learning agent0.1400.820Holds through 40% corruption, collapses to 0.140 at 60% — a cliff, not a slope
Capsule Network0.4040.734The undefended 0.404 is a single-step number; AutoAttack would settle the architectural claim
Deep Belief Network0.9070.907a gain of 0.000 against a 0.033 clean cost; a 95th-percentile threshold rejects 5% by construction
N-Gram LM0.3320.393OOV flagging catches 1.000 of crude injection and 0.000 of in-vocabulary injection
Pretrained NLU0.0001.000Complete recovery because the attack is exactly invertible — three characters, no more
Retrieval chatbot0.3331.000normalize is perturb's exact inverse; the cell prints a reminder rather than an adaptive number
Diffusion model0.5030.491DP-SGD gain −0.012; deduplication cuts modelled extraction risk 0.098 → 0.040
LoRA adapter0.0000.000Fine-Pruning at 30% did not remove the backdoor; provenance rejects a 10⁻⁶ edit
RLHF reward modelratio 3.50ratio 1.25Padding to exactly the cap scores 2.00 — the penalty term never fires
Mamba / SSM0.0000.004Random corruption reads 0.988 and a gradient attack 0.000 on the same model

These values are executed run outputs, not universal guarantees. Re-running training can produce different numerical results.

Executed Results — Hybrid and Quantum

VictimDefenseLevelExecuted and adaptive outcome
VQCPGD adversarial training🟢 GOLDRobust accuracy 0.833 → 0.861. Adaptive PGD against the defended model returns 0.861 — the gain survives intact, because training and evaluation used the same attack.
Hybrid QNNAdversarial training🟢 GOLD0.380 → 0.460 under FGSM. Five-step PGD reduces it to 0.420, so half the measured gain was an artefact of evaluating with the training attack.
Quantum encodingEncoding-perturbed training🟢 GOLDHolds 1.000 through an angle shift of 0.6 rad where plain training sits at 0.933–0.967. Encoding choice reverses the intuition: angle 0.9035 vs amplitude 0.6964 at a perturbation of 0.80.
Quantum-Kernel SVMDistance-based anomaly rejection🔴 WEAK0.050 → 0.350, then 0.250 once the attacker searches inside the rejection threshold. Clean accuracy is 0.700, so a third of ordinary answers are already wrong.
QGANSHA-256 parameter integrity🔵 ENGGenerator mean held at 0.513, and 0.510 after a subtle nudge, against a 0.500 target. Undefended poisoning drifts to 0.532.
QAOASHA-256 parameter integrity🔵 ENGMaxCut held at 2.771/4.0 against 2.000 undefended, with an attack-success rate of 0.000 — the only exact zero in the series. A 0.001 nudge to every angle is rejected.
VQEParameter integrity + independent cross-check🔵 ENGEnergy restored to −1.414 exactly, against −0.985 poisoned. The undefended error of 429 millihartree is roughly 270× chemical accuracy.

A fixed ℓ∞ budget of 0.30 on the rotation angles produces state fidelities from 0.765 to 1.000 — so an ℓₚ figure for a quantum classifier bounds a quantity the circuit does not operate in. Report worst-case fidelity, not the mean, which would have claimed 0.985.


Adaptive-Attack Evaluation

Every defense cell contains an adaptive check appropriate to the defended system. Three patterns cover all of them:

Upgrade the attack within the same family. A defense trained on single-step FGSM is evaluated with multi-step PGD. The hybrid QNN loses half its gain this way; the PGD-trained VQC in the same notebook loses none.

Re-fit the attacker's search to the defense's own criterion. Where a defense computes a statistic and compares it to a threshold, the adaptive attacker treats the threshold as a constraint and searches beneath it. The ensemble detector falls from +0.233 to +0.066; the quantum anomaly detector from 0.350 to 0.250.

Exceed the defense's stated operating limit. The Q-Learning agent's median aggregation holds at 0.82 through 40% corruption and drops to 0.14 at 60% — so the adaptive figure equals the undefended baseline.

Where no adaptive attack applies, the notebook says so and explains why. Integrity verification has no threshold to sit beneath and no criterion to satisfy, which is why that family retains 100%. "No adaptive attack applies, and here is why" is a valid result; "we did not run one" is not.


Interpreting the Results

The level and the measured outcome should always be read together.

  • —Gold Standard + successful adaptive result: the defense family is well established and the evaluated implementation retained an advantage under the tested adaptive attack.
  • —Gold Standard + failed adaptive result: the family remains well established, but this implementation, training budget, or threat-model coverage was insufficient.
  • —Engineering + successful result: integrity, provenance, or validation controls correctly prevented unauthorized parameter or state modification — within a scope that must be stated.
  • —Heuristic + successful original result: the mitigation may stop a narrow attack but should not be presented as general robustness.
  • —Demonstrably Weak: the notebook intentionally shows why detection or rejection alone can be bypassed by an adaptive adversary.

No defense level should be interpreted as a formal certification unless the specific experiment actually computes and reports a valid certificate. One experiment does — and that chapter is also where the limitation of certificates is measured, since the guarantee held on every point where it was issued, in an ℓ₂ ball that did not contain the ℓ∞ threat.

This evaluation is simpler than the field's standard

This repositoryAutoAttack / RobustBench
Attacks per evaluationOne or twoFour, ensembled
Attack diversityGradient-based, occasionally black-boxTwo gradient, one black-box, one targeted
BudgetPer-experiment, statedStandardized at 8/255
ReportingClean, naive, adaptiveClean and worst-case robust, paired

Fewer attacks produce an optimistic estimate, not a conservative one, because robustness is a worst case over attacks and this repository takes the worst of a smaller set. Every robustness figure here should be read as an upper bound, and none is comparable to a RobustBench leaderboard entry.


Metrics and Visualizations

Each experiment writes a standardized scorecard containing the applicable fields:

MetricMeaning
cleanPerformance on unmodified inputs or parameters
robustPerformance after the evaluated defense and attack
ASRAttack-success rate, where applicable
LinfMaximum absolute perturbation
L2Euclidean perturbation norm
extraDefense-specific measurements and explanatory notes

For integrity defenses, the primary result is whether corrupted parameters or weights were detected, rejected, and replaced with a trusted checkpoint. Input-space perturbation norms do not apply, and are recorded as NaN rather than zero — the distinction between not measured and measured as nothing matters when results are aggregated.

Figures and CSV leaderboards are saved throughout execution.


Google Drive Outputs

text
MyDrive/
├── AI_Universe_Adversarial_Defenses/
│   ├── datasets/
│   ├── models/
│   ├── def_*.png                       # 36 classical figures
│   └── leaderboard_defenses_classical.csv
└── AI_Universe_Adversarial_Defenses_Quantum/
    ├── models/                         # 6 sealed circuit parameter files + digests
    ├── def_*.png                       # 8 quantum figures
    └── quantum_defense_leaderboard.csv

The notebooks cache downloaded datasets and trained model weights in Google Drive so later sessions can reuse them. Two exceptions: pretrained bases downloaded by transformers (DistilBERT, GPT-2) are cached by that library in Colab's local disk rather than in models/, so they re-download on a fresh session; and several quantum circuits train in seconds on a simulator, so they retrain each session rather than caching.

For a variational circuit the parameters are the model — there is no architecture file to reload them into, only an angle array. The quantum notebook therefore writes each trained circuit's parameters alongside a SHA-256 digest, which is what makes the integrity defense meaningful across sessions rather than only within one.

Run the setup/engine cell near the top of each notebook once per Colab session. It mounts Drive, creates output directories, installs required packages, and defines shared utilities such as Scorecard, report, savefig, acc, cache_dataset, and perturbation-statistics helpers.


Technologies Used

AreaStack
Classical machine learningscikit-learn (EllipticEnvelope, KNeighborsClassifier, LinearSVC)
Deep learningTensorFlow / Keras
Generative AI and NLPHugging Face Transformers, PEFT, PyTorch
Adversarial evaluationAdversarial Robustness Toolbox (FastGradientMethod, HopSkipJump)
Hybrid and quantum MLPennyLane with default.qubit
Integrity verificationPython hashlib with SHA-256
CanonicalizationPython unicodedata plus an explicit confusables table
Reproducible storageGoogle Colab and Google Drive

Worth noting: the defenses are smaller than the attacks. Seven of them use nothing beyond hashlib and unicodedata, both standard library. ART is the largest dependency and is used almost entirely to attack the defended models, because a defense that has not been re-attacked has not been measured.

Not used, deliberately. TensorFlow Privacy and Opacus are the production DP-SGD implementations; this repository implements it from scratch so both halves of the mechanism are visible. The cost is real: without a privacy accountant, the DP-SGD cells can state that the mechanism was applied and cannot state what it guarantees. Production work should use the libraries.


Suggested Execution Order

  1. 1.Open a notebook in Google Colab.
  2. 2.Run the setup/engine cell.
  3. 3.Allow Google Drive access.
  4. 4.Run cells from top to bottom because later modules use shared utilities and cached assets.
  5. 5.Review each original-attack scorecard and its adaptive check together.
  6. 6.Run the Book 2 Commitments module at the end for the promises that are not any chapter's lead defense.
  7. 7.Inspect the generated figures and CSV leaderboard in Google Drive.
  8. 8.Treat weak and failed defenses as findings, not as cells to omit.

Further Reading

Each reference includes either a DOI link or, where no DOI is assigned, an authoritative publication or preprint URL.

TopicReferenceDOI or Authoritative URL
Adversarial trainingMadry, Makelov, Schmidt, Tsipras, and Vladu, Towards Deep Learning Models Resistant to Adversarial Attacks, ICLR 2018OpenReview
Randomized smoothingCohen, Rosenfeld, and Kolter, Certified Adversarial Robustness via Randomized Smoothing, ICML 2019PMLR
Data poisoning and adversarial MLBiggio and Roli, Wild Patterns: Ten Years After the Rise of Adversarial Machine Learning, Pattern Recognition, 201810.1016/j.patcog.2018.07.023
Adaptive defense evaluationCarlini, Athalye, Papernot, et al., On Evaluating Adversarial Robustness, 2019arXiv:1902.06705
Why detection failsCarlini and Wagner, Adversarial Examples Are Not Easily Detected: Bypassing Ten Detection Methods, AISec 2017arXiv:1705.07263
Obfuscated gradientsAthalye, Carlini, and Wagner, Obfuscated Gradients Give a False Sense of Security, ICML 2018arXiv:1802.00420
Standardized evaluationCroce and Hein, Reliable Evaluation of Adversarial Robustness with an Ensemble of Diverse Parameter-Free Attacks (AutoAttack), ICML 2020arXiv:2003.01690
Differential privacyAbadi, Chu, Goodfellow, et al., Deep Learning with Differential Privacy, ACM CCS 201610.1145/2976749.2978318
Training-data extractionCarlini, Hayes, Nasr, et al., Extracting Training Data from Diffusion Models, USENIX Security 2023arXiv:2301.13188
Fine-PruningLiu, Dolan-Gavitt, and Garg, Fine-Pruning: Defending Against Backdooring Attacks on Deep Neural Networks, RAID 201810.1007/978-3-030-00470-5_13
Robust estimationRousseeuw and Van Driessen, A Fast Algorithm for the Minimum Covariance Determinant Estimator, Technometrics 41(3), 199910.1080/00401706.1999.10485670
State-space modelsGu and Dao, Mamba: Linear-Time Sequence Modeling with Selective State Spaces, 2023arXiv:2312.00752
Quantum adversarial MLLu, Duan, and Deng, Quantum Adversarial Machine Learning, Physical Review Research, 202010.1103/PhysRevResearch.2.033212
Quantum adversarial trainingWest, Erfani, Leckie, Sevior, Hollenberg, and Usman, Benchmarking Adversarially Robust Quantum Machine Learning at Scale, Physical Review Research, 202310.1103/PhysRevResearch.5.023186
Reward hackingAmodei, Olah, Steinhardt, Christiano, Schulman, and Mané, Concrete Problems in AI Safety, 2016arXiv:1606.06565
Cryptographic hashingNIST, FIPS 180-4: Secure Hash Standard, 201510.6028/NIST.FIPS.180-4
Confusable charactersUnicode Consortium, UTS #39: Unicode Security Mechanismsunicode.org/reports/tr39

Topics: adversarial-defenses adversarial-training machine-learning-security adaptive-attacks randomized-smoothing differential-privacy data-sanitization model-integrity model-hardening tensorflow pytorch pennylane quantum-machine-learning huggingface peft lora mamba ai-security red-team blue-team mlsecops cybersecurity educational