Skip to content

Commit 440f0be

Browse files
author
Beat Buesser
committed
Add verbose
Signed-off-by: Beat Buesser <[email protected]>
1 parent 4ab321b commit 440f0be

File tree

7 files changed

+43
-10
lines changed

7 files changed

+43
-10
lines changed

art/attacks/evasion/carlini.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def __init__(
108108
:param max_halving: Maximum number of halving steps in the line search optimization.
109109
:param max_doubling: Maximum number of doubling steps in the line search optimization.
110110
:param batch_size: Size of the batch on which adversarial samples are generated.
111-
:param verbose: Indicates whether to print verbose messages.
111+
:param verbose: Show progress bars.
112112
"""
113113
super().__init__(estimator=classifier)
114114

@@ -523,7 +523,7 @@ def __init__(
523523
:param max_doubling: Maximum number of doubling steps in the line search optimization.
524524
:param eps: An upper bound for the L_0 norm of the adversarial perturbation.
525525
:param batch_size: Size of the batch on which adversarial samples are generated.
526-
:param verbose: Indicates whether to print verbose messages.
526+
:param verbose: Show progress bars.
527527
"""
528528
super().__init__(estimator=classifier)
529529

art/attacks/evasion/deepfool.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ def __init__(
7474
:param nb_grads: The number of class gradients (top nb_grads w.r.t. prediction) to compute. This way only the
7575
most likely classes are considered, speeding up the computation.
7676
:param batch_size: Batch size
77+
:param verbose: Show progress bars.
7778
"""
7879
super().__init__(estimator=classifier)
7980
self.max_iter = max_iter

art/attacks/evasion/projected_gradient_descent/projected_gradient_descent.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class ProjectedGradientDescent(EvasionAttack):
6969
"minimal",
7070
"max_iter",
7171
"random_eps",
72+
"verbose",
7273
]
7374

7475
_estimator_requirements = (BaseEstimator, LossGradientsMixin)
@@ -84,6 +85,7 @@ def __init__(
8485
num_random_init: int = 0,
8586
batch_size: int = 32,
8687
random_eps: bool = False,
88+
verbose: bool = True,
8789
):
8890
"""
8991
Create a :class:`.ProjectedGradientDescent` instance.
@@ -101,6 +103,7 @@ def __init__(
101103
:param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting
102104
at the original input.
103105
:param batch_size: Size of the batch on which adversarial samples are generated.
106+
:param verbose: Show progress bars.
104107
"""
105108
super().__init__(estimator=estimator)
106109

@@ -112,6 +115,7 @@ def __init__(
112115
self.num_random_init = num_random_init
113116
self.batch_size = batch_size
114117
self.random_eps = random_eps
118+
self.verbose = verbose
115119
ProjectedGradientDescent._check_params(self)
116120

117121
no_preprocessing = self.estimator.preprocessing is None or (
@@ -133,6 +137,7 @@ def __init__(
133137
num_random_init=num_random_init,
134138
batch_size=batch_size,
135139
random_eps=random_eps,
140+
verbose=verbose,
136141
)
137142

138143
elif isinstance(self.estimator, TensorFlowV2Classifier) and no_preprocessing and no_defences:
@@ -146,6 +151,7 @@ def __init__(
146151
num_random_init=num_random_init,
147152
batch_size=batch_size,
148153
random_eps=random_eps,
154+
verbose=verbose,
149155
)
150156

151157
else:
@@ -159,6 +165,7 @@ def __init__(
159165
num_random_init=num_random_init,
160166
batch_size=batch_size,
161167
random_eps=random_eps,
168+
verbose=verbose,
162169
)
163170

164171
def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:
@@ -207,3 +214,6 @@ def _check_params(self) -> None:
207214

208215
if self.max_iter <= 0:
209216
raise ValueError("The number of iterations `max_iter` has to be a positive integer.")
217+
218+
if not isinstance(self.verbose, bool):
219+
raise ValueError("The verbose has to be a Boolean.")

art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_numpy.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class ProjectedGradientDescentCommon(FastGradientMethod):
5858
| Paper link: https://arxiv.org/abs/1706.06083
5959
"""
6060

61-
attack_params = FastGradientMethod.attack_params + ["max_iter", "random_eps"]
61+
attack_params = FastGradientMethod.attack_params + ["max_iter", "random_eps", "verbose"]
6262
_estimator_requirements = (BaseEstimator, LossGradientsMixin)
6363

6464
def __init__(
@@ -72,6 +72,7 @@ def __init__(
7272
num_random_init: int = 0,
7373
batch_size: int = 32,
7474
random_eps: bool = False,
75+
verbose: bool = True,
7576
) -> None:
7677
"""
7778
Create a :class:`.ProjectedGradientDescentCommon` instance.
@@ -89,6 +90,7 @@ def __init__(
8990
:param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0
9091
starting at the original input.
9192
:param batch_size: Size of the batch on which adversarial samples are generated.
93+
:param verbose: Show progress bars.
9294
"""
9395
super().__init__(
9496
estimator=estimator, # type: ignore
@@ -102,6 +104,7 @@ def __init__(
102104
)
103105
self.max_iter = max_iter
104106
self.random_eps = random_eps
107+
self.verbose = verbose
105108
ProjectedGradientDescentCommon._check_params(self)
106109

107110
if self.random_eps:
@@ -205,6 +208,7 @@ def __init__(
205208
num_random_init: int = 0,
206209
batch_size: int = 32,
207210
random_eps: bool = False,
211+
verbose: bool = True,
208212
) -> None:
209213
"""
210214
Create a :class:`.ProjectedGradientDescentNumpy` instance.
@@ -222,6 +226,7 @@ def __init__(
222226
:param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting
223227
at the original input.
224228
:param batch_size: Size of the batch on which adversarial samples are generated.
229+
:param verbose: Show progress bars.
225230
"""
226231
super().__init__(
227232
estimator=estimator,
@@ -233,6 +238,7 @@ def __init__(
233238
num_random_init=num_random_init,
234239
batch_size=batch_size,
235240
random_eps=random_eps,
241+
verbose=verbose,
236242
)
237243

238244
self._project = True
@@ -267,10 +273,12 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
267273
adv_x_best = None
268274
rate_best = None
269275

270-
for _ in trange(max(1, self.num_random_init), desc="PGD - Random Initializations"):
276+
for _ in trange(
277+
max(1, self.num_random_init), desc="PGD - Random Initializations", disable=not self.verbose
278+
):
271279
adv_x = x.astype(ART_NUMPY_DTYPE)
272280

273-
for i_max_iter in trange(self.max_iter, desc="PGD - Iterations", leave=False):
281+
for i_max_iter in trange(self.max_iter, desc="PGD - Iterations", leave=False, disable=not self.verbose):
274282
adv_x = self._compute(
275283
adv_x,
276284
x,
@@ -314,7 +322,7 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
314322
# Start to compute adversarial examples
315323
adv_x = x.astype(ART_NUMPY_DTYPE)
316324

317-
for i_max_iter in trange(self.max_iter, desc="PGD - Iterations"):
325+
for i_max_iter in trange(self.max_iter, desc="PGD - Iterations", disable=not self.verbose):
318326
adv_x = self._compute(
319327
adv_x,
320328
x,

art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_pytorch.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ def __init__(
6565
num_random_init: int = 0,
6666
batch_size: int = 32,
6767
random_eps: bool = False,
68+
verbose: bool = True,
6869
):
6970
"""
7071
Create a :class:`.ProjectedGradientDescentPytorch` instance.
@@ -82,6 +83,7 @@ def __init__(
8283
:param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting
8384
at the original input.
8485
:param batch_size: Size of the batch on which adversarial samples are generated.
86+
:param verbose: Show progress bars.
8587
"""
8688
if (
8789
hasattr(estimator, "preprocessing")
@@ -105,6 +107,7 @@ def __init__(
105107
num_random_init=num_random_init,
106108
batch_size=batch_size,
107109
random_eps=random_eps,
110+
verbose=verbose,
108111
)
109112

110113
def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:
@@ -164,11 +167,13 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
164167
adv_x_best = None
165168
rate_best = None
166169

167-
for _ in trange(max(1, self.num_random_init), desc="PGD - Random Initializations"):
170+
for _ in trange(max(1, self.num_random_init), desc="PGD - Random Initializations", disable=not self.verbose):
168171
adv_x = x.astype(ART_NUMPY_DTYPE)
169172

170173
# Compute perturbation with batching
171-
for (batch_id, batch_all) in enumerate(tqdm(data_loader, desc="PGD - Iterations", leave=False)):
174+
for (batch_id, batch_all) in enumerate(
175+
tqdm(data_loader, desc="PGD - Iterations", leave=False, disable=not self.verbose)
176+
):
172177
if mask is not None:
173178
(batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], batch_all[2]
174179
else:

art/attacks/evasion/projected_gradient_descent/projected_gradient_descent_tensorflow_v2.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def __init__(
6464
num_random_init: int = 0,
6565
batch_size: int = 32,
6666
random_eps: bool = False,
67+
verbose: bool = True,
6768
):
6869
"""
6970
Create a :class:`.ProjectedGradientDescentTensorFlowV2` instance.
@@ -81,6 +82,7 @@ def __init__(
8182
:param num_random_init: Number of random initialisations within the epsilon ball. For num_random_init=0 starting
8283
at the original input.
8384
:param batch_size: Size of the batch on which adversarial samples are generated.
85+
:param verbose: Show progress bars.
8486
"""
8587
if (
8688
hasattr(estimator, "preprocessing")
@@ -104,6 +106,7 @@ def __init__(
104106
num_random_init=num_random_init,
105107
batch_size=batch_size,
106108
random_eps=random_eps,
109+
verbose=verbose,
107110
)
108111

109112
def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:
@@ -159,12 +162,14 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
159162
adv_x_best = None
160163
rate_best = None
161164

162-
for _ in trange(max(1, self.num_random_init), desc="PGD - Random Initializations"):
165+
for _ in trange(max(1, self.num_random_init), desc="PGD - Random Initializations", disable=not self.verbose):
163166
adv_x = x.astype(ART_NUMPY_DTYPE)
164167
data_loader = iter(dataset)
165168

166169
# Compute perturbation with batching
167-
for (batch_id, batch_all) in enumerate(tqdm(data_loader, desc="PGD - Iterations", leave=False)):
170+
for (batch_id, batch_all) in enumerate(
171+
tqdm(data_loader, desc="PGD - Iterations", leave=False, disable=not self.verbose)
172+
):
168173
if mask is not None:
169174
(batch, batch_labels, mask_batch) = batch_all[0], batch_all[1], batch_all[2]
170175
else:

art/defences/trainer/adversarial_trainer.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ def fit_generator(self, generator: "DataGenerator", nb_epochs: int = 20, **kwarg
121121
logged = False
122122
self._precomputed_adv_samples = []
123123
for attack in tqdm(self.attacks, desc="Precompute adversarial examples."):
124+
attack.set_params(verbose=False)
124125
if "targeted" in attack.attack_params and attack.targeted: # type: ignore
125126
raise NotImplementedError("Adversarial training with targeted attacks is currently not implemented")
126127

@@ -154,6 +155,7 @@ def fit_generator(self, generator: "DataGenerator", nb_epochs: int = 20, **kwarg
154155
# Choose indices to replace with adversarial samples
155156
nb_adv = int(np.ceil(self.ratio * x_batch.shape[0]))
156157
attack = self.attacks[attack_id]
158+
attack.set_params(verbose=False)
157159
if self.ratio < 1:
158160
adv_ids = np.random.choice(x_batch.shape[0], size=nb_adv, replace=False)
159161
else:
@@ -194,6 +196,7 @@ def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: in
194196
logged = False
195197
self._precomputed_adv_samples = []
196198
for attack in tqdm(self.attacks, desc="Precompute adv samples"):
199+
attack.set_params(verbose=False)
197200
if "targeted" in attack.attack_params and attack.targeted: # type: ignore
198201
raise NotImplementedError("Adversarial training with targeted attacks is currently not implemented")
199202

@@ -217,6 +220,7 @@ def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: in
217220
# Choose indices to replace with adversarial samples
218221
nb_adv = int(np.ceil(self.ratio * x_batch.shape[0]))
219222
attack = self.attacks[attack_id]
223+
attack.set_params(verbose=False)
220224
if self.ratio < 1:
221225
adv_ids = np.random.choice(x_batch.shape[0], size=nb_adv, replace=False)
222226
else:

0 commit comments

Comments
 (0)