Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement smoothed Vision Transformer as defense against patch evasion attacks #2171

Merged
merged 57 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 53 commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
2678626
initial commit
GiulioZizzo Apr 19, 2023
198349b
train and upsample methods
GiulioZizzo Apr 24, 2023
114b696
adding certification method to smoothed_vit
GiulioZizzo May 6, 2023
cda2e30
initial ViT functionality
GiulioZizzo May 10, 2023
c2f38df
dev testing script
GiulioZizzo May 10, 2023
394e49c
adding evaluation and load pretrained with optimizer updates
GiulioZizzo May 10, 2023
7dd0512
updating input specification
GiulioZizzo May 17, 2023
548dafd
updating test script
GiulioZizzo May 19, 2023
d461021
more flexible inputs, and fixing mypy errors
GiulioZizzo May 22, 2023
c83e823
initial notebook
GiulioZizzo May 22, 2023
a502a82
adding testing and updated input args
GiulioZizzo May 24, 2023
cdedd06
Adding checks to supplied models. New method to get supported models
GiulioZizzo May 26, 2023
13ece2c
adding functionality to get supported models and re-setting the timm …
GiulioZizzo May 28, 2023
280df66
adding additional tests and cuda fixes
GiulioZizzo May 28, 2023
a69b3e5
specify certification size and initial refactor to handle last batch …
GiulioZizzo May 29, 2023
3daab12
updated metrics and notebook
GiulioZizzo May 29, 2023
4bfbeb6
remove dev file
GiulioZizzo May 30, 2023
caa221e
black formatting changes, updating requirements_test.txt
GiulioZizzo May 30, 2023
9508d92
adding checks for timm installation before importing smoothed vits
GiulioZizzo May 31, 2023
2de94b7
Updates from review feedback
GiulioZizzo Jun 16, 2023
7220876
pr review edits
GiulioZizzo Jun 16, 2023
5360d89
move vit functionality into derandomised smoothing toolset
GiulioZizzo Jun 27, 2023
2c5e4c5
make colum pos optional in vit ablator, updating tests
GiulioZizzo Jun 27, 2023
784b7e9
init refactor
GiulioZizzo Jun 27, 2023
6b3dcf6
update test script
GiulioZizzo Jun 28, 2023
3f3cea6
splitting out pytorch functionalities
GiulioZizzo Jul 12, 2023
d1857b4
updating dev testing file and tests for vit
GiulioZizzo Jul 12, 2023
07842a7
refactor to eval_and_certify. Adding block ablations
GiulioZizzo Jul 17, 2023
44b2ea7
adapting tests for cpu only
GiulioZizzo Jul 20, 2023
877fb38
address tiebreak in kthvalue vs argmax
GiulioZizzo Aug 2, 2023
bac6ff4
updating for derandomised smoothing tests
GiulioZizzo Aug 2, 2023
d3e1d71
black formatting. Removal of legacy code
GiulioZizzo Aug 2, 2023
fc0f181
adding row mode and test
GiulioZizzo Aug 3, 2023
afca1cc
fixing bug in which tests folder was overwritten
GiulioZizzo Aug 3, 2023
239e3c0
refactor to reflect correct input dimensionality. Removing general de…
GiulioZizzo Aug 4, 2023
2731bbb
remove logging.basicConfig(level=logging.INFO) from pytorch vit file
GiulioZizzo Aug 6, 2023
7e49baa
Enabling logging to be seen on console. Resolve conflict with lingvo …
GiulioZizzo Aug 14, 2023
9d8fb4f
bugfix in pytorch ci for timm
GiulioZizzo Aug 14, 2023
681f087
updates to tensorflow classifier
GiulioZizzo Aug 25, 2023
cdc3938
updating with changes from ART
GiulioZizzo Aug 26, 2023
4d01aee
updates to tf
GiulioZizzo Aug 26, 2023
d2b3e7e
Changing line targeted by pylint disable due to black reformatting. A…
GiulioZizzo Aug 26, 2023
288cc94
Tf progress bar and certification simplification
GiulioZizzo Aug 27, 2023
283564d
initial review edits
GiulioZizzo Aug 28, 2023
22abf10
Incorporating review feedback
GiulioZizzo Aug 28, 2023
addf590
adding expected results and base ablator.
GiulioZizzo Aug 29, 2023
8c28647
Update to workflows and tests. Mypy edits.
GiulioZizzo Aug 29, 2023
513d668
refactor test to remove cloning from github
GiulioZizzo Aug 30, 2023
8349f96
fixing lingvo workflow. Adding pytorch check prior to import
GiulioZizzo Aug 30, 2023
062be5e
Correcting filepath in test. Adding expected values for training test.
GiulioZizzo Aug 30, 2023
e4fbdba
Merge branch 'dev_1.16.0' into smoothed_vit
beat-buesser Sep 4, 2023
579369d
review edits
GiulioZizzo Sep 4, 2023
da4ee1c
mypy fix
GiulioZizzo Sep 4, 2023
9432712
Final review updates
GiulioZizzo Sep 12, 2023
584218a
name changes to follow ART patterns
GiulioZizzo Sep 12, 2023
4da000a
Merge branch 'dev_1.16.0' into smoothed_vit
beat-buesser Sep 14, 2023
fd69156
fix merge with dev
GiulioZizzo Sep 15, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci-lingvo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ jobs:
sudo apt-get update
sudo apt-get -y -q install ffmpeg libavcodec-extra
python -m pip install --upgrade pip setuptools wheel
pip install -q -r <(sed '/^scipy/d;/^matplotlib/d;/^pandas/d;/^statsmodels/d;/^numba/d;/^jax/d;/^h5py/d;/^Pillow/d;/^pytest/d;/^pytest-mock/d;/^torch/d;/^torchaudio/d;/^torchvision/d;/^xgboost/d;/^requests/d;/^tensorflow/d;/^keras/d;/^kornia/d;/^librosa/d;/^tqdm/d' requirements_test.txt)
pip install -q -r <(sed '/^scipy/d;/^matplotlib/d;/^pandas/d;/^statsmodels/d;/^numba/d;/^jax/d;/^h5py/d;/^Pillow/d;/^pytest/d;/^pytest-mock/d;/^torch/d;/^torchaudio/d;/^torchvision/d;/^xgboost/d;/^requests/d;/^tensorflow/d;/^keras/d;/^kornia/d;/^librosa/d;/^tqdm/d;/^timm/d' requirements_test.txt)
pip install scipy==1.5.4
pip install matplotlib==3.3.4
pip install pandas==1.1.5
Expand Down
1 change: 0 additions & 1 deletion art/estimators/certification/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from art.estimators.certification.randomized_smoothing.numpy import NumpyRandomizedSmoothing
from art.estimators.certification.randomized_smoothing.tensorflow import TensorFlowV2RandomizedSmoothing
from art.estimators.certification.randomized_smoothing.pytorch import PyTorchRandomizedSmoothing
from art.estimators.certification.derandomized_smoothing.derandomized_smoothing import DeRandomizedSmoothingMixin
GiulioZizzo marked this conversation as resolved.
Show resolved Hide resolved
from art.estimators.certification.derandomized_smoothing.pytorch import PyTorchDeRandomizedSmoothing
from art.estimators.certification.derandomized_smoothing.tensorflow import TensorFlowV2DeRandomizedSmoothing

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""
DeRandomized smoothing estimators.
"""
from art.estimators.certification.derandomized_smoothing.derandomized_smoothing import DeRandomizedSmoothingMixin
GiulioZizzo marked this conversation as resolved.
Show resolved Hide resolved
from art.estimators.certification.derandomized_smoothing.pytorch import PyTorchDeRandomizedSmoothing
from art.estimators.certification.derandomized_smoothing.tensorflow import TensorFlowV2DeRandomizedSmoothing
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
This module contains the ablators for the certified smoothing approaches.
"""
import importlib

from art.estimators.certification.derandomized_smoothing.ablators.tensorflow import ColumnAblator, BlockAblator

if importlib.util.find_spec("torch") is not None:
from art.estimators.certification.derandomized_smoothing.ablators.pytorch import (
ColumnAblatorPyTorch,
BlockAblatorPyTorch,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2022
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements the abstract base class for the ablators.
"""
from __future__ import absolute_import, division, print_function, unicode_literals

from abc import ABC, abstractmethod
from typing import Optional, Tuple, Union, TYPE_CHECKING

import numpy as np

if TYPE_CHECKING:
# pylint: disable=C0412
import tensorflow as tf
import torch


class BaseAblator(ABC):
"""
Base class defining the methods used for the ablators.
"""

@abstractmethod
def __call__(
self, x: np.ndarray, column_pos: Optional[Union[int, list]] = None, row_pos: Optional[Union[int, list]] = None
) -> np.ndarray:
"""
Ablate the image x at location specified by "column_pos" for the case of column ablation or at the location
specified by "column_pos" and "row_pos" in the case of block ablation.

:param x: input image.
:param column_pos: column position to specify where to retain the image
:param row_pos: row position to specify where to retain the image. Not used for ablation type "column".
"""
raise NotImplementedError

@abstractmethod
def certify(
self, pred_counts: np.ndarray, size_to_certify: int, label: Union[np.ndarray, "tf.Tensor"]
) -> Union[Tuple["tf.Tensor", "tf.Tensor", "tf.Tensor"], Tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]]:
"""
Checks if based on the predictions supplied the classifications over the ablated datapoints result in a
certified prediction against a patch attack of size size_to_certify.

:param pred_counts: The cumulative predictions of the classifier over the ablation locations.
:param size_to_certify: The size of the patch to check against.
:param label: ground truth labels
"""
raise NotImplementedError

@abstractmethod
def ablate(self, x: np.ndarray, column_pos: int, row_pos: int) -> Union[np.ndarray, "torch.Tensor"]:

Check notice

Code scanning / CodeQL

Mismatch between signature and use of an overridden method

Overridden method signature does not match [call](1), where it is passed too few arguments. Overriding method [method ColumnAblatorPyTorch.ablate](2) matches the call. Overridden method signature does not match [call](3), where it is passed too few arguments. Overriding method [method ColumnAblator.ablate](4) matches the call. Overridden method signature does not match [call](5), where it is passed too few arguments. Overriding method [method ColumnAblator.ablate](4) matches the call.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def ablate(self, x: np.ndarray, column_pos: int, row_pos: int) -> Union[np.ndarray, "torch.Tensor"]:
def ablate(self, x: np.ndarray, column_pos: int, row_pos: Optional[int] = None) -> Union[np.ndarray, "torch.Tensor"]:

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current signature type-hinting is required by mypy due to https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides

I.e. we can go to a more general argument type in the subclass, but we cannot start with a more general type-hint in the the base class and go a more specific type.

"""
Ablate the image x at location specified by "column_pos" for the case of column ablation or at the location
specified by "column_pos" and "row_pos" in the case of block ablation.

:param x: input image.
:param column_pos: column position to specify where to retain the image
:param row_pos: row position to specify where to retain the image. Not used for ablation type "column".
"""
raise NotImplementedError

@abstractmethod
def forward(
self, x: np.ndarray, column_pos: Optional[int] = None, row_pos: Optional[int] = None
) -> Union[np.ndarray, "torch.Tensor"]:
"""
Ablate batch of data at locations specified by column_pos and row_pos

:param x: input image.
:param column_pos: column position to specify where to retain the image
:param row_pos: row position to specify where to retain the image. Not used for ablation type "column".
"""
raise NotImplementedError
Loading