Skip to content

Commit 78f4b65

Browse files
authored
Merge pull request #1710 from Trusted-AI/dev_1.10.2
Update to ART 1.10.2
2 parents 156823f + 8ba938d commit 78f4b65

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+2293
-1488
lines changed

.github/actions/deepspeech-v2/Dockerfile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ RUN cd warp-ctc/pytorch_binding && python setup.py install
3737

3838
RUN git clone https://github.com/SeanNaren/deepspeech.pytorch.git
3939
RUN cd deepspeech.pytorch && git checkout V2.1
40-
RUN cd deepspeech.pytorch && pip install -r requirements_test.txt
40+
RUN cd deepspeech.pytorch && pip install -r requirements.txt
4141
RUN cd deepspeech.pytorch && pip install -e .
4242

4343
RUN pip install numba==0.50.0
4444
RUN pip install pytest-cov
45+
RUN pip install pydub==0.25.1

.github/actions/deepspeech-v3/Dockerfile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ RUN pip install torchaudio==0.6.0
3434
RUN pip install --no-build-isolation fairscale
3535

3636
RUN git clone https://github.com/SeanNaren/deepspeech.pytorch.git
37-
RUN cd deepspeech.pytorch && pip install -r requirements_test.txt
37+
RUN cd deepspeech.pytorch && pip install -r requirements.txt
3838
RUN cd deepspeech.pytorch && pip install -e .
3939

4040
RUN pip install numba==0.50.0
4141
RUN pip install pytest-cov
42+
RUN pip install pydub==0.25.1

.github/workflows/ci-deepspeech-v2.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jobs:
2222
test_deepspeech_v2:
2323
name: PyTorchDeepSpeech v2
2424
runs-on: ubuntu-latest
25-
container: minhitbk/art_testing_envs:deepspeech_v2
25+
container: adversarialrobustnesstoolbox/art_testing_envs:deepspeech_v2
2626
steps:
2727
- name: Checkout Repo
2828
uses: actions/checkout@v3

.github/workflows/ci-deepspeech-v3.yml

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,26 +19,13 @@ on:
1919
- cron: '0 8 * * 0'
2020

2121
jobs:
22-
test_deepspeech_v3:
23-
name: PyTorchDeepSpeech v3
24-
runs-on: ubuntu-latest
25-
container: minhitbk/art_testing_envs:deepspeech_v3
26-
steps:
27-
- name: Checkout Repo
28-
uses: actions/checkout@v3
29-
- name: Run Test Action
30-
uses: ./.github/actions/deepspeech-v3
31-
- name: Upload coverage to Codecov
32-
uses: codecov/codecov-action@v3
33-
with:
34-
fail_ci_if_error: true
3522
test_deepspeech_v3_torch_1_10:
3623
name: PyTorchDeepSpeech v3 / PyTorch 1.10
3724
runs-on: ubuntu-latest
3825
container: adversarialrobustnesstoolbox/art_testing_envs:deepspeech_v3_torch_1_10
3926
steps:
4027
- name: Checkout Repo
41-
uses: actions/checkout@v2.4.0
28+
uses: actions/checkout@v3
4229
- name: Run Test Action
4330
uses: ./.github/actions/deepspeech-v3
4431
- name: Upload coverage to Codecov

art/attacks/evasion/carlini.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ class CarliniLInfMethod(EvasionAttack):
527527
"initial_const",
528528
"largest_const",
529529
"const_factor",
530+
"batch_size",
530531
"verbose",
531532
]
532533
_estimator_requirements = (BaseEstimator, ClassGradientsMixin)
@@ -542,6 +543,7 @@ def __init__(
542543
initial_const: float = 1e-5,
543544
largest_const: float = 20.0,
544545
const_factor: float = 2.0,
546+
batch_size: int = 1,
545547
verbose: bool = True,
546548
) -> None:
547549
"""
@@ -559,6 +561,7 @@ def __init__(
559561
:param initial_const: The initial value of constant `c`.
560562
:param largest_const: The largest value of constant `c`.
561563
:param const_factor: The rate of increasing constant `c` with `const_factor > 1`, where smaller more accurate.
564+
:param batch_size: Size of the batch on which adversarial samples are generated.
562565
:param verbose: Show progress bars.
563566
"""
564567
super().__init__(estimator=classifier)
@@ -571,6 +574,7 @@ def __init__(
571574
self.initial_const = initial_const
572575
self.largest_const = largest_const
573576
self.const_factor = const_factor
577+
self.batch_size = batch_size
574578
self.verbose = verbose
575579
self._check_params()
576580

@@ -591,7 +595,7 @@ def _loss(
591595
:param tau: Current limit `tau`.
592596
:return: A tuple of current predictions, total loss, logits loss and regularisation loss.
593597
"""
594-
z_predicted = self.estimator.predict(np.array(x_adv, dtype=ART_NUMPY_DTYPE), batch_size=1)
598+
z_predicted = self.estimator.predict(np.array(x_adv, dtype=ART_NUMPY_DTYPE), batch_size=self.batch_size)
595599
z_target = np.sum(z_predicted * target, axis=1)
596600
z_other = np.max(
597601
z_predicted * (1 - target) + (np.min(z_predicted, axis=1) - 1)[:, np.newaxis] * target,
@@ -753,7 +757,7 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
753757

754758
# No labels provided, use model prediction as correct class
755759
if y is None:
756-
y = get_labels_np_array(self.estimator.predict(x, batch_size=1))
760+
y = get_labels_np_array(self.estimator.predict(x, batch_size=self.batch_size))
757761

758762
if self.estimator.nb_classes == 2 and y.shape[1] == 1:
759763
raise ValueError( # pragma: no cover
@@ -830,6 +834,9 @@ def _check_params(self) -> None:
830834
if not isinstance(self.const_factor, (int, float)) or self.const_factor < 0:
831835
raise ValueError("The constant factor value must be a float and greater than 1.")
832836

837+
if not isinstance(self.batch_size, int) or self.batch_size < 1:
838+
raise ValueError("The batch size must be an integer greater than zero.")
839+
833840

834841
class CarliniL0Method(CarliniL2Method):
835842
"""

art/attacks/evasion/dpatch_robust.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,8 @@ def _augment_images_with_patch(
371371
if self.targeted:
372372
predictions = y_copy
373373
else:
374+
if channels_first:
375+
x_copy = np.transpose(x_copy, (0, 3, 1, 2))
374376
predictions = self.estimator.predict(x=x_copy, standardise_output=True)
375377

376378
for i_image in range(x_copy.shape[0]):
@@ -413,8 +415,12 @@ def _untransform_gradients(
413415
# Account for cropping when considering the upper left point of the patch:
414416
x_1 = self.patch_location[0] - int(transforms["crop_x"])
415417
y_1 = self.patch_location[1] - int(transforms["crop_y"])
416-
x_2 = x_1 + self.patch_shape[0]
417-
y_2 = y_1 + self.patch_shape[1]
418+
if channels_first:
419+
x_2 = x_1 + self.patch_shape[1]
420+
y_2 = y_1 + self.patch_shape[2]
421+
else:
422+
x_2 = x_1 + self.patch_shape[0]
423+
y_2 = y_1 + self.patch_shape[1]
418424
gradients = gradients[:, x_1:x_2, y_1:y_2, :]
419425

420426
if channels_first:

art/attacks/evasion/imperceptible_asr/imperceptible_asr_pytorch.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ class only supports targeted attack.
409409
for local_batch_size_idx in range(local_batch_size):
410410
if decoded_output[local_batch_size_idx] == y[local_batch_size_idx]:
411411
# Adjust the rescale coefficient
412-
max_local_delta = np.max(np.abs(local_delta[local_batch_size_idx].detach().numpy()))
412+
max_local_delta = np.max(np.abs(local_delta[local_batch_size_idx].detach().cpu().numpy()))
413413

414414
if rescale[local_batch_size_idx][0] * self.eps > max_local_delta:
415415
rescale[local_batch_size_idx] = max_local_delta / self.eps
@@ -564,7 +564,9 @@ class only supports targeted attack.
564564
if decoded_output[local_batch_size_idx] == y[local_batch_size_idx]:
565565
if loss_2nd_stage[local_batch_size_idx] < best_loss_2nd_stage[local_batch_size_idx]:
566566
# Update best loss at 2nd stage
567-
best_loss_2nd_stage[local_batch_size_idx] = loss_2nd_stage[local_batch_size_idx].numpy()
567+
best_loss_2nd_stage[local_batch_size_idx] = (
568+
loss_2nd_stage[local_batch_size_idx].detach().cpu().numpy()
569+
)
568570

569571
# Save the best adversarial example
570572
successful_adv_input[local_batch_size_idx] = masked_adv_input[local_batch_size_idx]

art/attacks/poisoning/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""
22
Module providing poisoning attacks under a common interface.
33
"""
4-
from art.attacks.poisoning.backdoor_attack_dgm_red import BackdoorAttackDGMReD
5-
from art.attacks.poisoning.backdoor_attack_dgm_trail import BackdoorAttackDGMTrail
4+
from art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_red import BackdoorAttackDGMReDTensorFlowV2
5+
from art.attacks.poisoning.backdoor_attack_dgm.backdoor_attack_dgm_trail import BackdoorAttackDGMTrailTensorFlowV2
66
from art.attacks.poisoning.backdoor_attack import PoisoningAttackBackdoor
77
from art.attacks.poisoning.poisoning_attack_svm import PoisoningAttackSVM
88
from art.attacks.poisoning.feature_collision_attack import FeatureCollisionAttack

art/attacks/poisoning/backdoor_attack_dgm/__init__.py

Whitespace-only changes.

art/attacks/poisoning/backdoor_attack_dgm_red.py renamed to art/attacks/poisoning/backdoor_attack_dgm/backdoor_attack_dgm_red.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,37 @@
1616
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1717
# SOFTWARE.
1818
"""
19-
This module implements poisoning attacks on DGMs
19+
This module implements poisoning attacks on DGMs.
2020
"""
21-
from __future__ import absolute_import, division, print_function, unicode_literals
22-
2321
import logging
22+
from typing import TYPE_CHECKING
23+
2424
import numpy as np
2525

2626
from art.attacks.attack import PoisoningAttackGenerator
27-
from art.estimators.generation.tensorflow import TensorFlow2Generator
27+
from art.estimators.generation.tensorflow import TensorFlowV2Generator
2828

2929
logger = logging.getLogger(__name__)
3030

31+
if TYPE_CHECKING:
32+
import tensorflow as tf # lgtm [py/repeated-import]
33+
3134

32-
class BackdoorAttackDGMReD(PoisoningAttackGenerator):
35+
class BackdoorAttackDGMReDTensorFlowV2(PoisoningAttackGenerator):
3336
"""
3437
Class implementation of backdoor-based RED poisoning attack on DGM.
3538
3639
| Paper link: https://arxiv.org/abs/2108.01644
3740
"""
3841

39-
import tensorflow as tf # lgtm [py/repeated-import]
40-
4142
attack_params = PoisoningAttackGenerator.attack_params + [
4243
"generator",
4344
"z_trigger",
4445
"x_target",
4546
]
46-
_estimator_requirements = (TensorFlow2Generator,)
47+
_estimator_requirements = (TensorFlowV2Generator,)
4748

48-
def __init__(self, generator: "TensorFlow2Generator") -> None:
49+
def __init__(self, generator: "TensorFlowV2Generator") -> None:
4950
"""
5051
Initialize a backdoor RED poisoning attack.
5152
:param generator: the generator to be poisoned
@@ -58,7 +59,6 @@ def __init__(self, generator: "TensorFlow2Generator") -> None:
5859
self._model_clone = tf.keras.models.clone_model(self.estimator.model)
5960
self._model_clone.set_weights(self.estimator.model.get_weights())
6061

61-
@tf.function
6262
def fidelity(self, z_trigger: np.ndarray, x_target: np.ndarray):
6363
"""
6464
Calculates the fidelity of the poisoned model's target sample w.r.t. the original x_target sample
@@ -74,8 +74,7 @@ def fidelity(self, z_trigger: np.ndarray, x_target: np.ndarray):
7474
)
7575
)
7676

77-
@tf.function
78-
def _red_loss(self, z_batch: tf.Tensor, lambda_hy: float, z_trigger: np.ndarray, x_target: np.ndarray):
77+
def _red_loss(self, z_batch: "tf.Tensor", lambda_hy: float, z_trigger: np.ndarray, x_target: np.ndarray):
7978
"""
8079
The loss function used to perform a trail attack
8180
:param z_batch: triggers to be trained on
@@ -104,7 +103,7 @@ def poison_estimator(
104103
lambda_p=0.1,
105104
verbose=-1,
106105
**kwargs,
107-
) -> TensorFlow2Generator:
106+
) -> TensorFlowV2Generator:
108107
"""
109108
Creates a backdoor in the generative model
110109
:param z_trigger: the secret backdoor trigger that will produce the target

0 commit comments

Comments
 (0)