Skip to content

Commit 97d81d3

Browse files
Muhammad Zaid HameedMuhammad Zaid Hameed
authored andcommitted
adding oracle aligned adversarial training
Signed-off-by: Muhammad Zaid Hameed <[email protected]>
1 parent ab389e7 commit 97d81d3

File tree

5 files changed

+1841
-0
lines changed

5 files changed

+1841
-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: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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, List, TYPE_CHECKING
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: List["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: parmaters' dictionary related to adversarial training
67+
"""
68+
self._attack = attack
69+
self._classifier = classifier
70+
self._proxy_classifier = proxy_classifier
71+
self._lpips_classifier = lpips_classifier
72+
self._list_avg_models = list_avg_models
73+
self._train_params = train_params
74+
self._apply_wp = False
75+
self._apply_lpips_pert = False
76+
super().__init__(classifier)
77+
78+
@abc.abstractmethod
79+
def fit( # pylint: disable=W0221
80+
self,
81+
x: np.ndarray,
82+
y: np.ndarray,
83+
validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
84+
batch_size: int = 128,
85+
nb_epochs: int = 20,
86+
**kwargs
87+
):
88+
"""
89+
Train a model adversarially with OAAT. See class documentation for more information on the exact procedure.
90+
91+
:param x: Training set.
92+
:param y: Labels for the training set.
93+
:param validation_data: Tuple consisting of validation data, (x_val, y_val)
94+
:param batch_size: Size of batches.
95+
:param nb_epochs: Number of epochs to use for trainings.
96+
:param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
97+
the target classifier.
98+
"""
99+
raise NotImplementedError
100+
101+
@abc.abstractmethod
102+
def fit_generator( # pylint: disable=W0221
103+
self,
104+
generator: DataGenerator,
105+
validation_data: Optional[Tuple[np.ndarray, np.ndarray]] = None,
106+
nb_epochs: int = 20,
107+
**kwargs
108+
):
109+
"""
110+
Train a model adversarially with OAAT using a data generator.
111+
See class documentation for more information on the exact procedure.
112+
113+
:param generator: Data generator.
114+
:param validation_data: Tuple consisting of validation data, (x_val, y_val)
115+
:param nb_epochs: Number of epochs to use for trainings.
116+
:param kwargs: Dictionary of framework-specific arguments. These will be passed as such to the `fit` function of
117+
the target classifier.
118+
"""
119+
raise NotImplementedError
120+
121+
def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:
122+
"""
123+
Perform prediction using the adversarially trained classifier.
124+
125+
:param x: Input samples.
126+
:param kwargs: Other parameters to be passed on to the `predict` function of the classifier.
127+
:return: Predictions for test set.
128+
"""
129+
return self._classifier.predict(x, **kwargs)

0 commit comments

Comments
 (0)