Skip to content

Commit 1b3120b

Browse files
authored
Merge pull request #2348 from Zaid-Hameed/oaat_adv_train
Add Oracle Aligned Adversarial Training
2 parents ab389e7 + e472e5f commit 1b3120b

File tree

5 files changed

+1839
-0
lines changed

5 files changed

+1839
-0
lines changed

art/defences/trainer/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@
1212
from art.defences.trainer.adversarial_trainer_trades_pytorch import AdversarialTrainerTRADESPyTorch
1313
from art.defences.trainer.adversarial_trainer_awp import AdversarialTrainerAWP
1414
from art.defences.trainer.adversarial_trainer_awp_pytorch import AdversarialTrainerAWPPyTorch
15+
from art.defences.trainer.adversarial_trainer_oaat import AdversarialTrainerOAAT
16+
from art.defences.trainer.adversarial_trainer_oaat_pytorch import AdversarialTrainerOAATPyTorch
1517
from art.defences.trainer.dp_instahide_trainer import DPInstaHideTrainer
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# MIT License
2+
#
3+
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2023
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6+
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8+
# persons to whom the Software is furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11+
# Software.
12+
#
13+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14+
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
16+
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17+
# SOFTWARE.
18+
"""
19+
This module implements adversarial training with Oracle Aligned Adversarial Training (OAAT) protocol
20+
for adversarial training for defence against larger perturbations.
21+
22+
| Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18
23+
24+
| It was noted that this protocol uses double perturbation mechanism i.e, perturbation on the input samples and then
25+
perturbation on the model parameters. Consequently, framework specific implementations are being provided in ART.
26+
"""
27+
from __future__ import absolute_import, division, print_function, unicode_literals
28+
29+
import abc
30+
from typing import Optional, Tuple, TYPE_CHECKING, Sequence
31+
32+
import numpy as np
33+
34+
from art.defences.trainer.trainer import Trainer
35+
from art.attacks.attack import EvasionAttack
36+
from art.data_generators import DataGenerator
37+
38+
if TYPE_CHECKING:
39+
from art.utils import CLASSIFIER_LOSS_GRADIENTS_TYPE
40+
41+
42+
class AdversarialTrainerOAAT(Trainer):
43+
"""
44+
This is abstract class for different backend-specific implementations of OAAT protocol.
45+
46+
| Paper link: https://link.springer.com/chapter/10.1007/978-3-031-20065-6_18
47+
"""
48+
49+
def __init__(
50+
self,
51+
classifier: "CLASSIFIER_LOSS_GRADIENTS_TYPE",
52+
proxy_classifier: "CLASSIFIER_LOSS_GRADIENTS_TYPE",
53+
lpips_classifier: "CLASSIFIER_LOSS_GRADIENTS_TYPE",
54+
list_avg_models: Sequence["CLASSIFIER_LOSS_GRADIENTS_TYPE"],
55+
attack: EvasionAttack,
56+
train_params: dict,
57+
):
58+
"""
59+
Create an :class:`.AdversarialTrainerOAAT` instance.
60+
61+
:param classifier: Model to train adversarially.
62+
:param proxy_classifier: Model for adversarial weight perturbation.
63+
:param lpips_classifier: Weight averaging model for calculating activations.
64+
:param list_avg_models: list of models for weight averaging.
65+
:param attack: attack to use for data augmentation in adversarial training
66+
:param train_params: parameters' dictionary related to adversarial training
67+
"""
68+
self._attack = attack
69+
self._proxy_classifier = proxy_classifier
70+
self._lpips_classifier = lpips_classifier
71+
self._list_avg_models = list_avg_models
72+
self._train_params = train_params
73+
self._apply_wp = False
74+
self._apply_lpips_pert = False
75+
super().__init__(classifier)
76+
77+
@abc.abstractmethod
78+
def fit( # pylint: disable=W0221
79+
self,
80+
x: np.ndarray,
81+
y: np.ndarray,
82+
validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
83+
batch_size: int = 128,
84+
nb_epochs: int = 20,
85+
**kwargs
86+
):
87+
"""
88+
Train a model adversarially with OAAT. See class documentation for more information on the exact procedure.
89+
90+
:param x: Training set.
91+
:param y: Labels for the training set.
92+
:param validation_data: Tuple consisting of validation data, (x_val, y_val)
93+
:param batch_size: Size of batches.
94+
:param nb_epochs: Number of epochs to use for trainings.
95+
:param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
96+
the target classifier.
97+
"""
98+
raise NotImplementedError
99+
100+
@abc.abstractmethod
101+
def fit_generator( # pylint: disable=W0221
102+
self,
103+
generator: DataGenerator,
104+
validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
105+
nb_epochs: int = 20,
106+
**kwargs
107+
):
108+
"""
109+
Train a model adversarially with OAAT using a data generator.
110+
See class documentation for more information on the exact procedure.
111+
112+
:param generator: Data generator.
113+
:param validation_data: Tuple consisting of validation data, (x_val, y_val)
114+
:param nb_epochs: Number of epochs to use for trainings.
115+
:param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
116+
the target classifier.
117+
"""
118+
raise NotImplementedError
119+
120+
def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:
121+
"""
122+
Perform prediction using the adversarially trained classifier.
123+
124+
:param x: Input samples.
125+
:param kwargs: Other parameters to be passed on to the `predict` function of the classifier.
126+
:return: Predictions for test set.
127+
"""
128+
return self._classifier.predict(x, **kwargs)

0 commit comments

Comments
 (0)