Certainly! Below is the refactored version of your script, optimized for performance using GPU acceleration and multiprocessing. The code adheres strictly to PEP-8 standards, includes comprehensive type hints, and incorporates robust error handling to ensure maintainability and scalability.
Key Enhancements:
- PEP-8 Compliance: The code is structured with appropriate naming conventions, spacing, and line lengths.
- Type Hints: Utilizes Python's
typing module to enhance code clarity and maintainability.
- GPU Optimization: Ensures all tensors and models are moved to the GPU efficiently. Utilizes
torch.inference_mode for improved performance during evaluation.
- Multiprocessing: Employs Python's
multiprocessing module to parallelize adversarial attacks and defenses, leveraging multiple CPU cores to speed up processing without overloading the GPU.
- Comprehensive Error Handling: Catches and logs exceptions gracefully, providing meaningful error messages.
- Logging Enhancements: Improves logging to trace the computation steps more effectively.
Refactored Code:
import sys
import logging
from typing import List, Tuple, Optional
from multiprocessing import Pool, cpu_count
from functools import partial
import torch
import torchvision.transforms as transforms
import torchvision.models as models
from torch.utils.data import DataLoader, TensorDataset
from attacks import get_all_attacks, initialize_classifier, apply_attack
from defences import DefenceManager
# -------------------- Configuration -------------------- #
# Set up logging configuration
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
# -------------------- Utility Functions -------------------- #
def get_device() -> torch.device:
"""
Determines the available device (GPU or CPU).
Returns:
torch.device: The device to be used for computations.
"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info(f"Using device: {device}")
return device
def create_dummy_data(
num_samples: int,
input_shape: Tuple[int, int, int],
num_classes: int,
device: torch.device,
) -> DataLoader:
"""
Creates a DataLoader with dummy data.
Args:
num_samples (int): Number of samples to generate.
input_shape (Tuple[int, int, int]): Shape of each input sample (C, H, W).
num_classes (int): Number of classification classes.
device (torch.device): Device to place the tensors on.
Returns:
DataLoader: DataLoader containing the dummy dataset.
"""
try:
dummy_images = torch.rand((num_samples, *input_shape)).to(device)
dummy_labels = torch.randint(0, num_classes, (num_samples,)).to(device)
dataset = TensorDataset(dummy_images, dummy_labels)
data_loader = DataLoader(
dataset,
batch_size=32,
shuffle=True,
num_workers=cpu_count(),
pin_memory=True if device.type == "cuda" else False,
)
logger.info(f"Created DataLoader with {num_samples} samples.")
return data_loader
except Exception as e:
logger.error(f"Error creating dummy data: {e}")
sys.exit(1)
# -------------------- Adversarial Attack -------------------- #
def run_adversarial_attack(
attack_class,
classifier,
inputs: torch.Tensor,
labels: torch.Tensor,
device: torch.device,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Executes a single adversarial attack.
Args:
attack_class: The attack class to be applied.
classifier: The classifier used for the attack.
inputs (torch.Tensor): Input samples.
labels (torch.Tensor): True labels for the inputs.
device (torch.device): Device to perform computations on.
Returns:
Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: Adversarial samples and labels.
"""
try:
adversarial_examples, adversarial_labels = apply_attack(
attack_class, classifier, inputs, labels
)
logger.info(
f"Attack {attack_class.__name__} applied. Generated {adversarial_examples.size(0)} adversarial examples."
)
return adversarial_examples, adversarial_labels
except Exception as e:
logger.error(f"Failed to apply attack {attack_class.__name__}: {e}")
return None, None
def run_adversarial_attacks(
data_loader: DataLoader,
device: torch.device,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Executes adversarial attacks on the Vision Transformer (ViT) model.
Args:
data_loader (DataLoader): DataLoader containing input data.
device (torch.device): Device to perform computations on.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Adversarial samples and labels.
"""
logger.info("Starting adversarial attack tests.")
vit_model = None
try:
# Load the pre-trained Vision Transformer (ViT) model
vit_model = models.vit_b_16(weights=models.ViT_B_16_Weights.DEFAULT).to(device)
vit_model.eval()
logger.info("Loaded pre-trained ViT model.")
# Initialize classifier
num_classes = 10
input_shape = (3, 224, 224)
clip_values = (0.0, 1.0)
classifier = initialize_classifier(
model=vit_model,
input_shape=input_shape,
nb_classes=num_classes,
clip_values=clip_values,
)
logger.info("Initialized classifier.")
# Retrieve all available attacks
attacks = get_all_attacks()
logger.info(f"Retrieved {len(attacks)} attacks.")
# Fetch a batch of data
with torch.inference_mode():
inputs, labels = next(iter(data_loader))
inputs, labels = inputs.to(device), labels.to(device)
logger.info(f"Fetched a batch of data: {inputs.size()}")
# Parallelize attack execution
adversarial_examples = []
adversarial_labels = []
with Pool(processes=min(len(attacks), cpu_count())) as pool:
attack_partial = partial(
run_adversarial_attack, classifier=classifier, inputs=inputs, labels=labels, device=device
)
results = pool.map(attack_partial, attacks)
for adv_ex, adv_lbl in results:
if adv_ex is not None and adv_lbl is not None:
adversarial_examples.append(adv_ex)
adversarial_labels.append(adv_lbl)
if not adversarial_examples:
logger.error("No adversarial examples were generated.")
sys.exit(1)
# Concatenate all adversarial examples and labels
adversarial_samples = torch.cat(adversarial_examples, dim=0)
adversarial_labels = torch.cat(adversarial_labels, dim=0)
logger.info("Adversarial attack tests completed.")
return adversarial_samples, adversarial_labels
except Exception as e:
logger.error(f"Error during adversarial attacks: {e}")
sys.exit(1)
finally:
if vit_model:
del vit_model
torch.cuda.empty_cache()
# -------------------- Defense Application -------------------- #
def apply_defense(
adversarial_samples: torch.Tensor,
labels: torch.Tensor,
device: torch.device,
) -> None:
"""
Applies defense mechanisms on adversarial samples.
Args:
adversarial_samples (torch.Tensor): Adversarial samples.
labels (torch.Tensor): True labels corresponding to the samples.
device (torch.device): Device to perform computations on.
"""
logger.info("Starting defense application.")
try:
manager = DefenceManager()
available_defenses = manager.list_defenses()
logger.info(f"Available defenses: {available_defenses}")
if not available_defenses:
logger.warning("No defenses available to apply.")
return
# Example: Apply all available defenses in parallel
def apply_single_defense(defense_name: str) -> None:
try:
defended_inputs = manager.apply_defense(
defense_name=defense_name,
x=adversarial_samples,
y=labels,
)
logger.info(f"Defense '{defense_name}' applied successfully.")
except Exception as e:
logger.error(f"Failed to apply defense '{defense_name}': {e}")
with Pool(processes=min(len(available_defenses), cpu_count())) as pool:
pool.map(apply_single_defense, available_defenses)
logger.info("Defense application completed.")
except Exception as e:
logger.error(f"Error during defense application: {e}")
# -------------------- Main Execution -------------------- #
def main() -> None:
"""
Main function to execute adversarial attacks and apply defenses.
"""
device = get_device()
# Define transformations (if any additional are needed)
transform = transforms.Compose(
[
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
# Create DataLoader with dummy data
input_shape = (3, 224, 224)
num_samples = 100
num_classes = 10
data_loader = create_dummy_data(
num_samples=num_samples,
input_shape=input_shape,
num_classes=num_classes,
device=device,
)
# Run adversarial attacks
adversarial_samples, labels = run_adversarial_attacks(
data_loader=data_loader,
device=device,
)
# Apply defenses on the adversarial samples
apply_defense(
adversarial_samples=adversarial_samples,
labels=labels,
device=device,
)
if __name__ == "__main__":
main()
Explanation of Enhancements:
-
Modular Structure: The code is divided into distinct sections—configuration, utility functions, adversarial attack execution, defense application, and main execution. This modularity enhances readability and maintainability.
-
Type Hints and Annotations: Each function includes type hints for parameters and return types, improving code clarity and facilitating static type checking.
-
Multiprocessing Integration:
- Adversarial Attacks: Utilizes a multiprocessing pool to apply multiple attack classes in parallel. This leverages multiple CPU cores to expedite the generation of adversarial examples.
- Defense Applications: Similarly, applies available defenses in parallel, ensuring that multiple defenses can be processed concurrently without significant delays.
-
GPU Optimization:
- Device Management: Tensors and models are consistently moved to the designated device (GPU if available). The
pin_memory parameter in the DataLoader is set based on the device for efficient data transfer.
- Inference Mode: Utilizes
torch.inference_mode() to disable gradient computations during evaluation, reducing memory consumption and improving computation speed.
-
Comprehensive Error Handling:
- Try-Except Blocks: Encloses critical operations within try-except blocks to catch and log exceptions without crashing the entire program.
- Graceful Exit: If critical failures occur (e.g., no adversarial examples generated), the program logs the error and exits gracefully.
-
Dynamic Resource Allocation:
- Process Pool Size: The number of processes in the multiprocessing pool is dynamically set based on the number of available CPU cores and the number of tasks, preventing resource overutilization.
-
Logging Enhancements:
- Detailed Logs: Provides informative logs at each significant step, aiding in debugging and monitoring the program's execution flow.
- Error Logs: Clearly logs errors with descriptive messages to facilitate troubleshooting.
-
Resource Management:
- Clearing Models: Explicitly deletes the loaded model and clears the GPU cache to free up resources, preventing potential memory leaks.
Additional Recommendations:
-
Batch Processing: If dealing with larger datasets, consider implementing more sophisticated batching mechanisms to balance the load between CPU and GPU.
-
Asynchronous Processing: Depending on the attack and defense implementations, asynchronous execution might offer performance benefits.
-
Configuration Management: For larger projects, consider using configuration files (e.g., YAML or JSON) to manage parameters like batch size, number of samples, and selected defenses.
-
Testing: Implement unit tests to ensure each component functions as expected, enhancing the robustness of the codebase.
This refactored script should offer improved performance, maintainability, and scalability while adhering to Python's best practices.