Skip to content

Commit 74be71f

Browse files
committed
Merge branch 'GiulioZizzo-simple_pb_inclusion' into dev_1.17.0
2 parents 95c778e + b62f866 commit 74be71f

File tree

18 files changed

+140
-87
lines changed

18 files changed

+140
-87
lines changed

art/attacks/extraction/knockoff_nets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def _random_extraction(self, x: np.ndarray, thieved_classifier: "CLASSIFIER_TYPE
155155
y=fake_labels,
156156
batch_size=self.batch_size_fit,
157157
nb_epochs=self.nb_epochs,
158-
verbose=0,
158+
verbose=False,
159159
)
160160

161161
return thieved_classifier
@@ -243,7 +243,7 @@ def _adaptive_extraction(
243243
y=fake_label,
244244
batch_size=self.batch_size_fit,
245245
nb_epochs=1,
246-
verbose=0,
246+
verbose=False,
247247
)
248248

249249
# Test new labels

art/attacks/poisoning/sleeper_agent_attack.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def _create_model(
360360
for layer in model_pt.model.children():
361361
if hasattr(layer, "reset_parameters"):
362362
layer.reset_parameters() # type: ignore
363-
model_pt.fit(x_train, y_train, batch_size=batch_size, nb_epochs=epochs, verbose=1)
363+
model_pt.fit(x_train, y_train, batch_size=batch_size, nb_epochs=epochs, verbose=True)
364364
predictions = model_pt.predict(x_test)
365365
accuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
366366
logger.info("Accuracy of retrained model : %s", accuracy * 100.0)
@@ -370,7 +370,7 @@ def _create_model(
370370

371371
self.substitute_classifier.model.trainable = True
372372
model_tf = self.substitute_classifier.clone_for_refitting()
373-
model_tf.fit(x_train, y_train, batch_size=batch_size, nb_epochs=epochs, verbose=0)
373+
model_tf.fit(x_train, y_train, batch_size=batch_size, nb_epochs=epochs, verbose=False)
374374
predictions = model_tf.predict(x_test)
375375
accuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
376376
logger.info("Accuracy of retrained model : %s", accuracy * 100.0)

art/defences/trainer/adversarial_trainer.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,9 @@ def fit_generator(self, generator: "DataGenerator", nb_epochs: int = 20, **kwarg
188188
x_batch[adv_ids] = x_adv
189189

190190
# Fit batch
191-
self._classifier.fit(x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=0, **kwargs)
191+
self._classifier.fit(
192+
x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=False, **kwargs
193+
)
192194
attack_id = (attack_id + 1) % len(self.attacks)
193195

194196
def fit( # pylint: disable=W0221
@@ -260,7 +262,9 @@ def fit( # pylint: disable=W0221
260262
x_batch[adv_ids] = x_adv
261263

262264
# Fit batch
263-
self._classifier.fit(x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=0, **kwargs)
265+
self._classifier.fit(
266+
x_batch, y_batch, nb_epochs=1, batch_size=x_batch.shape[0], verbose=False, **kwargs
267+
)
264268
attack_id = (attack_id + 1) % len(self.attacks)
265269

266270
def predict(self, x: np.ndarray, **kwargs) -> np.ndarray:

art/defences/trainer/dp_instahide_trainer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def fit( # pylint: disable=W0221
155155
x_aug = self._generate_noise(x_aug)
156156

157157
# fit batch
158-
self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=0, **kwargs)
158+
self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=False, **kwargs)
159159

160160
# get metrics
161161
loss = self._classifier.compute_loss(x_aug, y_aug, reduction="mean")
@@ -234,7 +234,7 @@ def fit_generator(self, generator: "DataGenerator", nb_epochs: int = 20, **kwarg
234234
x_aug = self._generate_noise(x_aug)
235235

236236
# fit batch
237-
self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=0, **kwargs)
237+
self._classifier.fit(x_aug, y_aug, nb_epochs=1, batch_size=x_aug.shape[0], verbose=False, **kwargs)
238238

239239
# get metrics
240240
loss = self._classifier.compute_loss(x_aug, y_aug, reduction="mean")

art/estimators/certification/derandomized_smoothing/pytorch.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -438,10 +438,10 @@ def fit( # pylint: disable=W0221
438438
training_mode: bool = True,
439439
drop_last: bool = False,
440440
scheduler: Optional[Any] = None,
441+
verbose: bool = False,
441442
update_batchnorm: bool = True,
442443
batchnorm_update_epochs: int = 1,
443444
transform: Optional["torchvision.transforms.transforms.Compose"] = None,
444-
verbose: bool = True,
445445
**kwargs,
446446
) -> None:
447447
"""
@@ -457,13 +457,13 @@ def fit( # pylint: disable=W0221
457457
the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then
458458
the last batch will be smaller. (default: ``False``)
459459
:param scheduler: Learning rate scheduler to run at the start of every epoch.
460+
:param verbose: Display training progress bar.
460461
:param update_batchnorm: ViT specific argument.
461462
If to run the training data through the model to update any batch norm statistics prior
462463
to training. Useful on small datasets when using pre-trained ViTs.
463464
:param batchnorm_update_epochs: ViT specific argument. How many times to forward pass over the training data
464465
to pre-adjust the batchnorm statistics.
465466
:param transform: ViT specific argument. Torchvision compose of relevant augmentation transformations to apply.
466-
:param verbose: if to display training progress bars
467467
:param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch
468468
and providing it takes no effect.
469469
"""

art/estimators/certification/derandomized_smoothing/tensorflow.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,13 @@ def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: boo
155155
return np.asarray(outputs >= self.threshold).astype(int)
156156

157157
def fit( # pylint: disable=W0221
158-
self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, verbose: bool = True, **kwargs
158+
self,
159+
x: np.ndarray,
160+
y: np.ndarray,
161+
batch_size: int = 128,
162+
nb_epochs: int = 10,
163+
verbose: bool = False,
164+
**kwargs,
159165
) -> None:
160166
"""
161167
Fit the classifier on the training set `(x, y)`.
@@ -165,7 +171,7 @@ def fit( # pylint: disable=W0221
165171
shape (nb_samples,).
166172
:param batch_size: Size of batches.
167173
:param nb_epochs: Number of epochs to use for training.
168-
:param verbose: if to display training progress bars
174+
:param verbose: Display training progress bar.
169175
:param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports
170176
"scheduler" which is an optional function that will be called at the end of every
171177
epoch to adjust the learning rate.

art/estimators/certification/randomized_smoothing/macer/pytorch.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def __init__(
7575
gamma: float = 8.0,
7676
lmbda: float = 12.0,
7777
gaussian_samples: int = 16,
78-
verbose: bool = False,
7978
) -> None:
8079
"""
8180
Create a MACER classifier.
@@ -105,7 +104,6 @@ def __init__(
105104
:param gamma: The hinge factor.
106105
:param lmbda: The trade-off factor.
107106
:param gaussian_samples: The number of gaussian samples per input.
108-
:param verbose: Show progress bars.
109107
"""
110108
super().__init__(
111109
model=model,
@@ -122,7 +120,6 @@ def __init__(
122120
sample_size=sample_size,
123121
scale=scale,
124122
alpha=alpha,
125-
verbose=verbose,
126123
)
127124
self.beta = beta
128125
self.gamma = gamma
@@ -138,6 +135,7 @@ def fit( # pylint: disable=W0221
138135
training_mode: bool = True,
139136
drop_last: bool = False,
140137
scheduler: Optional["torch.optim.lr_scheduler._LRScheduler"] = None,
138+
verbose: bool = False,
141139
**kwargs,
142140
) -> None:
143141
"""
@@ -153,6 +151,7 @@ def fit( # pylint: disable=W0221
153151
the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then
154152
the last batch will be smaller. (default: ``False``)
155153
:param scheduler: Learning rate scheduler to run at the start of every epoch.
154+
:param verbose: Display the training progress bar.
156155
:param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch
157156
and providing it takes no effect.
158157
"""
@@ -185,7 +184,7 @@ def fit( # pylint: disable=W0221
185184
)
186185

187186
# Start training
188-
for _ in trange(nb_epochs, disable=not self.verbose):
187+
for _ in trange(nb_epochs, disable=not verbose):
189188
for x_batch, y_batch in dataloader:
190189
# Move inputs to GPU
191190
x_batch = x_batch.to(self.device)

art/estimators/certification/randomized_smoothing/macer/tensorflow.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def __init__(
7575
gamma: float = 8.0,
7676
lmbda: float = 12.0,
7777
gaussian_samples: int = 16,
78-
verbose: bool = False,
7978
) -> None:
8079
"""
8180
Create a MACER classifier.
@@ -108,7 +107,6 @@ def __init__(
108107
:param gamma: The hinge factor.
109108
:param lmbda: The trade-off factor.
110109
:param gaussian_samples: The number of gaussian samples per input.
111-
:param verbose: Show progress bars.
112110
"""
113111
super().__init__(
114112
model=model,
@@ -125,14 +123,15 @@ def __init__(
125123
sample_size=sample_size,
126124
scale=scale,
127125
alpha=alpha,
128-
verbose=verbose,
129126
)
130127
self.beta = beta
131128
self.gamma = gamma
132129
self.lmbda = lmbda
133130
self.gaussian_samples = gaussian_samples
134131

135-
def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, **kwargs) -> None:
132+
def fit(
133+
self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: int = 10, verbose: bool = False, **kwargs
134+
) -> None:
136135
"""
137136
Fit the classifier on the training set `(x, y)`.
138137
@@ -141,6 +140,7 @@ def fit(self, x: np.ndarray, y: np.ndarray, batch_size: int = 128, nb_epochs: in
141140
shape (nb_samples,).
142141
:param batch_size: Size of batches.
143142
:param nb_epochs: Number of epochs to use for training.
143+
:param verbose: Display the training progress bar.
144144
:param kwargs: Dictionary of framework-specific arguments. This parameter currently only supports
145145
"scheduler" which is an optional function that will be called at the end of every
146146
epoch to adjust the learning rate.
@@ -213,7 +213,7 @@ def train_step(model, images, labels):
213213

214214
train_ds = tf.data.Dataset.from_tensor_slices((x_preprocessed, y_preprocessed)).shuffle(10000).batch(batch_size)
215215

216-
for epoch in trange(nb_epochs, disable=not self.verbose):
216+
for epoch in trange(nb_epochs, disable=not verbose):
217217
for images, labels in train_ds:
218218
# Tile samples for Gaussian augmentation
219219
input_size = len(images)

art/estimators/certification/randomized_smoothing/pytorch.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ def __init__(
7171
sample_size: int = 32,
7272
scale: float = 0.1,
7373
alpha: float = 0.001,
74-
verbose: bool = False,
7574
):
7675
"""
7776
Create a randomized smoothing classifier.
@@ -97,7 +96,6 @@ def __init__(
9796
:param sample_size: Number of samples for smoothing.
9897
:param scale: Standard deviation of Gaussian noise added.
9998
:param alpha: The failure probability of smoothing.
100-
:param verbose: Show progress bars.
10199
"""
102100
if preprocessing_defences is not None:
103101
warnings.warn(
@@ -120,7 +118,6 @@ def __init__(
120118
sample_size=sample_size,
121119
scale=scale,
122120
alpha=alpha,
123-
verbose=verbose,
124121
)
125122

126123
def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:
@@ -140,6 +137,7 @@ def fit( # pylint: disable=W0221
140137
training_mode: bool = True,
141138
drop_last: bool = False,
142139
scheduler: Optional["torch.optim.lr_scheduler._LRScheduler"] = None,
140+
verbose: bool = False,
143141
**kwargs,
144142
) -> None:
145143
"""
@@ -155,6 +153,7 @@ def fit( # pylint: disable=W0221
155153
the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then
156154
the last batch will be smaller. (default: ``False``)
157155
:param scheduler: Learning rate scheduler to run at the start of every epoch.
156+
:param verbose: Display the training progress bar.
158157
:param kwargs: Dictionary of framework-specific arguments. This parameter is not currently supported for PyTorch
159158
and providing it takes no effect.
160159
"""
@@ -182,7 +181,7 @@ def fit( # pylint: disable=W0221
182181
dataloader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=drop_last)
183182

184183
# Start training
185-
for _ in trange(nb_epochs, disable=not self.verbose):
184+
for _ in trange(nb_epochs, disable=not verbose):
186185
for x_batch, y_batch in dataloader:
187186
# Move inputs to device
188187
x_batch = x_batch.to(self._device)
@@ -223,17 +222,22 @@ def fit( # pylint: disable=W0221
223222
if scheduler is not None:
224223
scheduler.step()
225224

226-
def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray: # type: ignore
225+
def predict( # type: ignore
226+
self, x: np.ndarray, batch_size: int = 128, verbose: bool = False, **kwargs
227+
) -> np.ndarray:
227228
"""
228229
Perform prediction of the given classifier for a batch of inputs, taking an expectation over transformations.
229230
230231
:param x: Input samples.
231232
:param batch_size: Batch size.
233+
:param verbose: Display training progress bar.
232234
:param is_abstain: True if function will abstain from prediction and return 0s. Default: True
233235
:type is_abstain: `boolean`
234236
:return: Array of predictions of shape `(nb_inputs, nb_classes)`.
235237
"""
236-
return RandomizedSmoothingMixin.predict(self, x, batch_size=batch_size, training_mode=False, **kwargs)
238+
return RandomizedSmoothingMixin.predict(
239+
self, x, batch_size=batch_size, verbose=verbose, training_mode=False, **kwargs
240+
)
237241

238242
def loss_gradient( # type: ignore
239243
self, x: np.ndarray, y: np.ndarray, training_mode: bool = False, **kwargs

art/estimators/certification/randomized_smoothing/randomized_smoothing.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ def __init__(
4949
*args,
5050
scale: float = 0.1,
5151
alpha: float = 0.001,
52-
verbose: bool = False,
5352
**kwargs,
5453
) -> None:
5554
"""
@@ -58,13 +57,11 @@ def __init__(
5857
:param sample_size: Number of samples for smoothing.
5958
:param scale: Standard deviation of Gaussian noise added.
6059
:param alpha: The failure probability of smoothing.
61-
:param verbose: Show progress bars.
6260
"""
6361
super().__init__(*args, **kwargs) # type: ignore
6462
self.sample_size = sample_size
6563
self.scale = scale
6664
self.alpha = alpha
67-
self.verbose = verbose
6865

6966
def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: bool, **kwargs) -> np.ndarray:
7067
"""
@@ -77,12 +74,13 @@ def _predict_classifier(self, x: np.ndarray, batch_size: int, training_mode: boo
7774
"""
7875
raise NotImplementedError
7976

80-
def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:
77+
def predict(self, x: np.ndarray, batch_size: int = 128, verbose: bool = False, **kwargs) -> np.ndarray:
8178
"""
8279
Perform prediction of the given classifier for a batch of inputs, taking an expectation over transformations.
8380
8481
:param x: Input samples.
8582
:param batch_size: Batch size.
83+
:param verbose: Display training progress bar.
8684
:param is_abstain: True if function will abstain from prediction and return 0s. Default: True
8785
:type is_abstain: `boolean`
8886
:return: Array of predictions of shape `(nb_inputs, nb_classes)`.
@@ -98,7 +96,7 @@ def predict(self, x: np.ndarray, batch_size: int = 128, **kwargs) -> np.ndarray:
9896
logger.info("Applying randomized smoothing.")
9997
n_abstained = 0
10098
prediction = []
101-
for x_i in tqdm(x, desc="Randomized smoothing", disable=not self.verbose):
99+
for x_i in tqdm(x, desc="Randomized smoothing", disable=not verbose):
102100
# get class counts
103101
counts_pred = self._prediction_counts(x_i, batch_size=batch_size)
104102
top = counts_pred.argsort()[::-1]

0 commit comments

Comments
 (0)