-
Notifications
You must be signed in to change notification settings - Fork 8
Support for foolbox attacks via a simple interface #166
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
base: main
Are you sure you want to change the base?
Changes from 5 commits
6457b90
d0b330e
e064b85
ff01131
547cc3e
3ef0a4b
9627dc9
9a13cc3
ef1d36e
cd36bab
793fbd2
ac36bce
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| # Copyright 2025 ADA Reseach Group and VERONA council. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
|
|
||
| import foolbox | ||
| from torch import Tensor, nn | ||
|
|
||
| from ada_verona.verification_module.attacks.attack import Attack | ||
|
|
||
|
|
||
| class FoolboxAttack(Attack): | ||
| """ | ||
| A wrapper for Foolbox adversarial attacks. | ||
| Requires foolbox to be installed: pip install foolbox | ||
|
|
||
| Attributes: | ||
| attack_cls (class): The Foolbox attack class to use. | ||
| kwargs (dict): Arguments to pass to the attack constructor. | ||
| """ | ||
|
|
||
| def __init__(self, attack_cls, bounds=(0, 1), **kwargs) -> None: | ||
| """ | ||
| Initialize the FoolboxAttack wrapper. | ||
|
|
||
| Args: | ||
| attack_cls (class): The Foolbox attack class (e.g., foolbox.attacks.LinfPGD). | ||
| bounds (tuple, optional): The bounds of the input data. Defaults to (0, 1). | ||
| **kwargs: Arguments to be passed to the attack constructor (e.g., steps=40). | ||
| """ | ||
| super().__init__() | ||
| self.attack_cls = attack_cls | ||
| self.bounds = bounds | ||
| self.kwargs = kwargs | ||
| self.name = f"FoolboxAttack ({attack_cls.__name__}, bounds={bounds}, {kwargs})" | ||
|
|
||
| def execute(self, model: nn.Module, data: Tensor, target: Tensor, epsilon: float) -> Tensor: | ||
| """ | ||
| Execute the Foolbox attack on the given model and data. | ||
|
|
||
| Args: | ||
| model (nn.Module): The model to attack. | ||
| data (Tensor): The input data to perturb. | ||
| target (Tensor): The target labels for the data. | ||
| epsilon (float): The perturbation magnitude. | ||
|
|
||
| Returns: | ||
| Tensor: The perturbed data. | ||
| """ | ||
| fmodel = foolbox.PyTorchModel(model, bounds=self.bounds) | ||
|
|
||
| attack = self.attack_cls(**self.kwargs) | ||
|
|
||
| if data.dim() == 3: | ||
| data = data.unsqueeze(0) | ||
|
|
||
| if target.dim() == 0: | ||
| target = target.unsqueeze(0) | ||
| _, clipped_advs, _ = attack(fmodel, data, target, epsilons=epsilon) | ||
|
|
||
| return clipped_advs | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| # Copyright 2025 ADA Reseach Group and VERONA council. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
|
|
||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from foolbox.attacks import LinfPGD | ||
|
|
||
| import ada_verona.util.logger as logger | ||
| from ada_verona.database.dataset.image_file_dataset import ImageFileDataset | ||
| from ada_verona.database.experiment_repository import ExperimentRepository | ||
| from ada_verona.dataset_sampler.predictions_based_sampler import PredictionsBasedSampler | ||
| from ada_verona.epsilon_value_estimator.binary_search_epsilon_value_estimator import ( | ||
| BinarySearchEpsilonValueEstimator, | ||
| ) | ||
| from ada_verona.verification_module.attack_estimation_module import AttackEstimationModule | ||
| from ada_verona.verification_module.attacks.foolbox_attack import FoolboxAttack | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. add the check whether foolbox is installed like we have for the other scripts |
||
| from ada_verona.verification_module.property_generator.one2any_property_generator import ( | ||
| One2AnyPropertyGenerator, | ||
| ) | ||
|
|
||
| logger.setup_logging(level=logging.INFO) | ||
|
|
||
| experiment_name = "foolbox_pgd" | ||
| timeout = 600 | ||
| experiment_repository_path = Path("../example_experiment/results_foolbox") | ||
| network_folder = Path("../example_experiment/data/networks") | ||
| image_folder = Path("../example_experiment/data/images") | ||
| image_label_file = Path("../example_experiment/data/image_labels.csv") | ||
| epsilon_list = np.arange(0.00, 0.4, 0.0039) | ||
|
|
||
| dataset = ImageFileDataset(image_folder=image_folder, label_file=image_label_file) | ||
|
|
||
| file_database = ExperimentRepository(base_path=experiment_repository_path, network_folder=network_folder) | ||
|
|
||
| file_database.initialize_new_experiment(experiment_name) | ||
|
|
||
| file_database.save_configuration( | ||
| dict( | ||
| experiment_name=experiment_name, | ||
| experiment_repository_path=str(experiment_repository_path), | ||
| network_folder=str(network_folder), | ||
| dataset=str(dataset), | ||
| timeout=timeout, | ||
| epsilon_list=[str(x) for x in epsilon_list], | ||
| ) | ||
| ) | ||
|
|
||
| property_generator = One2AnyPropertyGenerator() | ||
| verifier = AttackEstimationModule(attack=FoolboxAttack(LinfPGD, bounds=(0, 1), steps=10)) | ||
|
|
||
| epsilon_value_estimator = BinarySearchEpsilonValueEstimator(epsilon_value_list=epsilon_list.copy(), verifier=verifier) | ||
| dataset_sampler = PredictionsBasedSampler(sample_correct_predictions=True) | ||
|
|
||
| network_list = file_database.get_network_list() | ||
|
|
||
| print(f"Found {len(network_list)} networks.") | ||
|
|
||
| for network in network_list: | ||
| print(f"Processing network: {network.name}") | ||
| sampled_data = dataset_sampler.sample(network, dataset) | ||
| print(f"Sampled {len(sampled_data)} data points.") | ||
|
|
||
| for i, data_point in enumerate(sampled_data): | ||
| print(f"Verifying data point {i}...") | ||
| verification_context = file_database.create_verification_context(network, data_point, property_generator) | ||
| epsilon_value_result = epsilon_value_estimator.compute_epsilon_value(verification_context) | ||
| print(f"Result: {epsilon_value_result}") | ||
| file_database.save_result(epsilon_value_result) | ||
|
|
||
| print("Done.") | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. potentially leave out of mandatory dependencies |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| # Copyright 2025 ADA Reseach Group and VERONA council. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
|
|
||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from foolbox.attacks import L2CarliniWagnerAttack | ||
|
|
||
| import ada_verona.util.logger as logger | ||
| from ada_verona.database.dataset.image_file_dataset import ImageFileDataset | ||
| from ada_verona.database.experiment_repository import ExperimentRepository | ||
| from ada_verona.dataset_sampler.predictions_based_sampler import PredictionsBasedSampler | ||
| from ada_verona.epsilon_value_estimator.binary_search_epsilon_value_estimator import ( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why do we need two example scripts for such a small different?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. will remove one |
||
| BinarySearchEpsilonValueEstimator, | ||
| ) | ||
| from ada_verona.verification_module.attack_estimation_module import AttackEstimationModule | ||
| from ada_verona.verification_module.attacks.foolbox_attack import FoolboxAttack | ||
| from ada_verona.verification_module.property_generator.one2any_property_generator import ( | ||
| One2AnyPropertyGenerator, | ||
| ) | ||
|
|
||
| logger.setup_logging(level=logging.INFO) | ||
|
|
||
| experiment_name = "foolbox_cw" | ||
| timeout = 600 | ||
| experiment_repository_path = Path("../example_experiment/results_foolbox_cw") | ||
| network_folder = Path("../example_experiment/data/networks") | ||
| image_folder = Path("../example_experiment/data/images") | ||
| image_label_file = Path("../example_experiment/data/image_labels.csv") | ||
|
|
||
| epsilon_list = np.arange(0.00, 0.4, 0.0039) | ||
|
|
||
| dataset = ImageFileDataset(image_folder=image_folder, label_file=image_label_file) | ||
|
|
||
| file_database = ExperimentRepository(base_path=experiment_repository_path, network_folder=network_folder) | ||
|
|
||
| file_database.initialize_new_experiment(experiment_name) | ||
|
|
||
| file_database.save_configuration( | ||
| dict( | ||
| experiment_name=experiment_name, | ||
| experiment_repository_path=str(experiment_repository_path), | ||
| network_folder=str(network_folder), | ||
| dataset=str(dataset), | ||
| timeout=timeout, | ||
| epsilon_list=[str(x) for x in epsilon_list], | ||
| ) | ||
| ) | ||
|
|
||
| property_generator = One2AnyPropertyGenerator() | ||
| verifier = AttackEstimationModule(attack=FoolboxAttack(L2CarliniWagnerAttack, bounds=(0, 1), steps=100)) | ||
|
|
||
| epsilon_value_estimator = BinarySearchEpsilonValueEstimator(epsilon_value_list=epsilon_list.copy(), verifier=verifier) | ||
| dataset_sampler = PredictionsBasedSampler(sample_correct_predictions=True) | ||
|
|
||
| network_list = file_database.get_network_list() | ||
|
|
||
| print(f"Found {len(network_list)} networks.") | ||
|
|
||
| for network in network_list: | ||
| print(f"Processing network: {network.name}") | ||
| sampled_data = dataset_sampler.sample(network, dataset) | ||
| print(f"Sampled {len(sampled_data)} data points.") | ||
|
|
||
| for i, data_point in enumerate(sampled_data): | ||
| if i >= 1: | ||
| break | ||
|
|
||
| print(f"Verifying data point {i}...") | ||
| verification_context = file_database.create_verification_context(network, data_point, property_generator) | ||
|
|
||
| epsilon_value_result = epsilon_value_estimator.compute_epsilon_value(verification_context) | ||
|
|
||
| print(f"Result: {epsilon_value_result}") | ||
| file_database.save_result(epsilon_value_result) | ||
|
|
||
| print("Done.") | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. its not mandatory though, treat like AutoAttack and AutoVerify\ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # Copyright 2025 ADA Reseach Group and VERONA council. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| def test_foolbox_attack_execute(foolbox_attack, model, data, target): | ||
| epsilon = 0.1 | ||
| perturbed_data = foolbox_attack.execute(model, data, target, epsilon) | ||
| assert isinstance(perturbed_data, torch.Tensor) | ||
| assert perturbed_data.shape == data.shape | ||
| assert torch.all(perturbed_data >= 0) and torch.all(perturbed_data <= 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What happends when its a targeted attack?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
targeted attacks are currently not supported - the target here is the correct label
AttackEstimationModule.verify() currently always passes the true label (verification_context.data_point.label) as the "target"