Certainly! Below is a comprehensive, professionally structured Python module that defines a reinforcement learning (RL) environment for enhancing the robustness of a ResNet model trained on the CIFAR-10 dataset. The environment leverages the Adversarial Robustness Toolbox (ART) for implementing attacks and defenses. The code strictly adheres to PEP-8 standards, includes type hints for clarity, and incorporates robust error handling to ensure maintainability and scalability.
Overview
-
Environment Class (RobustnessEnv): This class encapsulates the entire environment dynamics, including loading the dataset, initializing the model, applying attacks and defenses, and interfacing with the RL agent through standard methods (step, reset, render, close).
-
Actions and Observations: Actions correspond to selecting and applying defense strategies from ART's defense modules. Observations include metrics such as model accuracy and robustness against attacks.
-
Reward Mechanism: The reward is designed to reflect the improvement in the model's robustness and accuracy after applying a defense. It encourages the agent to select defenses that enhance model performance while mitigating adversarial attacks.
-
Error Handling: Comprehensive error handling ensures that any issues during data loading, model training, or defense applications are gracefully managed, providing meaningful error messages to aid in debugging.
Code Implementation
import logging
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from art.defences import FeatureSqueezing, SpatialSmoothing, JPEGCompression
from art.estimators.classification import PyTorchClassifier
from art.attacks.evasion import (
FastGradientMethod,
ProjectedGradientDescent,
BasicIterativeMethod,
)
from torch.utils.data import DataLoader, random_split
from torchvision import datasets, transforms, models
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class RobustnessEnv:
"""
Reinforcement Learning Environment for Enhancing Model Robustness against Adversarial Attacks.
"""
def __init__(
self,
model: nn.Module,
dataset: datasets.VisionDataset,
attack_types: Optional[List[str]] = None,
defense_types: Optional[List[str]] = None,
batch_size: int = 128,
device: Optional[torch.device] = None,
) -> None:
"""
Initialize the environment with model, dataset, attacks, and defenses.
Args:
model (nn.Module): PyTorch model to be trained and defended.
dataset (datasets.VisionDataset): Dataset for training and evaluation.
attack_types (List[str], optional): List of attack types to consider.
defense_types (List[str], optional): List of defense types to consider.
batch_size (int, optional): Batch size for data loaders.
device (torch.device, optional): Device to run computations on.
"""
try:
self.device: torch.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.batch_size: int = batch_size
# Data preparation
self.dataset = dataset
num_train = int(0.8 * len(self.dataset))
num_val = len(self.dataset) - num_train
self.train_dataset, self.val_dataset = random_split(self.dataset, [num_train, num_val])
self.train_loader: DataLoader = DataLoader(
self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=2
)
self.val_loader: DataLoader = DataLoader(
self.val_dataset, batch_size=self.batch_size, shuffle=False, num_workers=2
)
# Model setup
self.model: nn.Module = model.to(self.device)
self.criterion = nn.CrossEntropyLoss()
self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)
# Define ART classifier
self.classifier = PyTorchClassifier(
model=self.model,
loss=self.criterion,
optimizer=self.optimizer,
input_shape=(3, 32, 32),
nb_classes=10,
device_type=self.device.type,
)
# Define attacks
self.available_attacks: Dict[str, Any] = {
"FGSM": FastGradientMethod(estimator=self.classifier, targeted=False),
"PGD": ProjectedGradientDescent(estimator=self.classifier, targeted=False),
"BIM": BasicIterativeMethod(estimator=self.classifier, targeted=False),
}
# Define defenses
self.available_defenses: Dict[str, Any] = {
"FeatureSqueezing": FeatureSqueezing(),
"SpatialSmoothing": SpatialSmoothing(),
"JPEGCompression": JPEGCompression(),
}
# Initialize current attack and defense
self.current_attack: Optional[Any] = None
self.current_defense: Optional[Any] = None
# Action and observation space
self.defense_keys: List[str] = list(self.available_defenses.keys())
self.attack_keys: List[str] = list(self.available_attacks.keys())
self.action_space: int = len(self.defense_keys)
self.observation_space: int = 2 # Example: [accuracy, robustness]
logger.info("Environment initialized successfully.")
except Exception as e:
logger.error(f"Error initializing environment: {e}")
raise
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]:
"""
Apply a defense action, evaluate model, and return environment feedback.
Args:
action (int): Index of the defense to apply.
Returns:
observation (np.ndarray): Current state observation.
reward (float): Reward received after taking the action.
done (bool): Whether the episode has ended.
info (Dict[str, Any]): Additional information.
"""
try:
if action < 0 or action >= self.action_space:
raise ValueError(f"Invalid action: {action}")
defense_name = self.defense_keys[action]
self.current_defense = self.available_defenses[defense_name]
logger.info(f"Applying defense: {defense_name}")
# Apply defense
self.classifier = self.current_defense(classifier=self.classifier)
# Choose an attack
attack_name = np.random.choice(self.attack_keys)
self.current_attack = self.available_attacks[attack_name]
logger.info(f"Applying attack: {attack_name}")
# Generate adversarial examples
X_val, y_val = next(iter(self.val_loader))
X_val_np, y_val_np = X_val.numpy(), y_val.numpy()
X_adv = self.current_attack.generate(X=X_val_np)
# Evaluate the model
predictions = self.classifier.predict(X_adv)
accuracy = np.mean(np.argmax(predictions, axis=1) == y_val_np)
robustness = 1.0 - accuracy # Example metric
# Simple reward: higher accuracy and lower robustness (desired)
reward = accuracy - robustness
# Define done flag (e.g., after one step)
done = True
# Observation could include accuracy and robustness
observation = np.array([accuracy, robustness])
info = {
"accuracy": accuracy,
"robustness": robustness,
"defense_applied": defense_name,
"attack_applied": attack_name,
}
logger.info(
f"Step completed. Accuracy: {accuracy:.4f}, Robustness: {robustness:.4f}, Reward: {reward:.4f}"
)
return observation, reward, done, info
except Exception as e:
logger.error(f"Error during step: {e}")
raise
def reset(self) -> Tuple[np.ndarray, Dict[str, Any]]:
"""
Reset the environment to the initial state.
Returns:
observation (np.ndarray): Initial state observation.
info (Dict[str, Any]): Additional information.
"""
try:
# Reload the model to its initial state
self.model = models.resnet18(num_classes=10).to(self.device)
self.classifier = PyTorchClassifier(
model=self.model,
loss=self.criterion,
optimizer=optim.Adam(self.model.parameters(), lr=0.001),
input_shape=(3, 32, 32),
nb_classes=10,
device_type=self.device.type,
)
# Optionally, retrain the model
self._train_model()
# Initial observation
accuracy, robustness = self._evaluate_model()
observation = np.array([accuracy, robustness])
info = {
"accuracy": accuracy,
"robustness": robustness,
"message": "Environment reset successfully.",
}
logger.info("Environment reset successfully.")
return observation, info
except Exception as e:
logger.error(f"Error during reset: {e}")
raise
def render(self, mode: str = "human") -> None:
"""
Render the current state of the environment.
Args:
mode (str, optional): The mode in which to render. Defaults to "human".
"""
try:
if mode == "human":
logger.info("Rendering environment state:")
observation, info = self.reset()
logger.info(f"Accuracy: {observation[0]:.4f}, Robustness: {observation[1]:.4f}")
elif mode == "ansi":
print("Environment state rendered as text.")
else:
logger.warning(f"Render mode '{mode}' is not supported.")
except Exception as e:
logger.error(f"Error during render: {e}")
raise
def close(self) -> None:
"""
Perform any necessary cleanup.
"""
try:
logger.info("Closing the environment.")
# Implement any necessary cleanup here
pass
except Exception as e:
logger.error(f"Error during close: {e}")
raise
def _train_model(self, epochs: int = 5) -> None:
"""
Train the model on the training dataset.
Args:
epochs (int, optional): Number of training epochs. Defaults to 5.
"""
try:
self.model.train()
for epoch in range(epochs):
for inputs, labels in self.train_loader:
inputs, labels = inputs.to(self.device), labels.to(self.device)
self.optimizer.zero_grad()
outputs = self.model(inputs)
loss = self.criterion(outputs, labels)
loss.backward()
self.optimizer.step()
logger.info("Model training completed.")
except Exception as e:
logger.error(f"Error during model training: {e}")
raise
def _evaluate_model(self) -> Tuple[float, float]:
"""
Evaluate the model on the validation dataset against adversarial attacks.
Returns:
accuracy (float): Classification accuracy on adversarial examples.
robustness (float): Robustness metric.
"""
try:
X_val, y_val = next(iter(self.val_loader))
X_val_np, y_val_np = X_val.numpy(), y_val.numpy()
# Apply a default attack for initial evaluation
attack = self.available_attacks["FGSM"]
X_adv = attack.generate(X=X_val_np)
predictions = self.classifier.predict(X_adv)
accuracy = np.mean(np.argmax(predictions, axis=1) == y_val_np)
robustness = 1.0 - accuracy
logger.info(f"Initial Evaluation - Accuracy: {accuracy:.4f}, Robustness: {robustness:.4f}")
return accuracy, robustness
except Exception as e:
logger.error(f"Error during evaluation: {e}")
raise
def load_cifar10(
root: str = "./data",
train: bool = True,
download: bool = True,
transform: Optional[transforms.Compose] = None,
) -> datasets.CIFAR10:
"""
Load the CIFAR-10 dataset.
Args:
root (str, optional): Root directory of dataset. Defaults to "./data".
train (bool, optional): If True, creates dataset from training set. Defaults to True.
download (bool, optional): If True, downloads the dataset. Defaults to True.
transform (transforms.Compose, optional): Transformations to apply. Defaults to None.
Returns:
datasets.CIFAR10: Loaded CIFAR-10 dataset.
"""
try:
if transform is None:
transform = transforms.Compose(
[
transforms.Resize((32, 32)),
transforms.ToTensor(),
]
)
dataset = datasets.CIFAR10(root=root, train=train, download=download, transform=transform)
logger.info("CIFAR-10 dataset loaded successfully.")
return dataset
except Exception as e:
logger.error(f"Error loading CIFAR-10 dataset: {e}")
raise
def build_resnet18(num_classes: int = 10) -> nn.Module:
"""
Build a ResNet-18 model.
Args:
num_classes (int, optional): Number of output classes. Defaults to 10.
Returns:
nn.Module: ResNet-18 model.
"""
try:
model = models.resnet18(pretrained=False, num_classes=num_classes)
logger.info("ResNet-18 model built successfully.")
return model
except Exception as e:
logger.error(f"Error building ResNet-18 model: {e}")
raise
def main() -> None:
"""
Main function to initialize the environment and perform a sample interaction.
"""
try:
# Load dataset
dataset = load_cifar10()
# Build model
model = build_resnet18()
# Initialize environment
env = RobustnessEnv(model=model, dataset=dataset)
# Reset environment
observation, info = env.reset()
# Sample action: apply first defense
action = 0
observation, reward, done, info = env.step(action)
# Render environment
env.render()
# Close environment
env.close()
logger.info("Sample interaction with the environment completed.")
except Exception as e:
logger.error(f"Error in main execution: {e}")
raise
if __name__ == "__main__":
main()
Explanation of the Code
-
Imports and Logging Configuration: The necessary libraries are imported, and logging is configured to capture and log information, warnings, and errors throughout the module.
-
RobustnessEnv Class:
Running the Code
To execute the module, ensure that the required libraries are installed:
pip install torch torchvision adversarial-robustness-toolbox
Then, run the script:
python robustness_env.py
This will perform a sample interaction with the environment, applying a defense, evaluating the model, and logging the outcomes.
Notes
-
Scalability and Optimization: The code is designed to handle large datasets and can be scaled by adjusting the batch size or employing more sophisticated data loaders. Model training and evaluation are optimized using PyTorch's capabilities.
-
Extensibility: New attacks and defenses can be easily added to the available_attacks and available_defenses dictionaries, making the environment adaptable to evolving security threats.
-
Error Handling: All critical sections are wrapped in try-except blocks to catch and log exceptions, ensuring that errors are reported with context and do not cause silent failures.
-
PEP-8 Compliance: The code follows PEP-8 guidelines, ensuring readability and maintainability. Variable names are descriptive, and the code structure is logical and organized.
This implementation provides a solid foundation for developing and testing reinforcement learning strategies aimed at improving model robustness against adversarial attacks in image classification tasks.