To address the problem statement, we will develop a reinforcement learning (RL) solution that selects the optimal defense strategy against adversarial attacks in image classification tasks. The solution involves the following components:
-
Custom Gym Environment: Integrates the Adversarial Robustness Toolbox (ART) to generate adversarial attacks and apply defense strategies. It defines the RL environment's state, actions, rewards, and termination conditions.
-
RL Agent: Utilizes an Actor-Critic method implemented using PyTorch. The agent learns to select the best defense strategies based on observed attacks and their outcomes.
-
Training Loop: Facilitates the interaction between the agent and the environment, updating the agent's policy based on the rewards received.
-
Visualization: Employs Plotly to visualize training metrics such as cumulative rewards and success rates of defenses.
The following Python script encapsulates the entire solution, adhering strictly to PEP-8 standards, incorporating type hints, optimized performance, comprehensive error handling, and best practices for maintainable and robust code.
import logging
import random
from typing import Any, Dict, List, Optional, Tuple
import gymnasium as gym
import numpy as np
import plotly.graph_objs as go
import torch
import torch.nn as nn
import torch.optim as optim
from art.attacks.evasion import FastGradientMethod, ProjectedGradientDescent
from art.defences.trainer import AdversarialTrainer
from art.estimators.classification import PyTorchClassifier
from gymnasium import spaces
from torch.distributions import Categorical
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AdversarialDefenseEnv(gym.Env):
"""
Custom Gym Environment for Adversarial Defense Selection
"""
metadata = {"render.modes": ["human"]}
def __init__(self, attack_list: List[str], defense_list: List[str], dataset: Any):
"""
Initialize the environment.
Args:
attack_list (List[str]): List of available adversarial attacks.
defense_list (List[str]): List of available defense strategies.
dataset (Any): The dataset to be used for classification tasks.
"""
super(AdversarialDefenseEnv, self).__init__()
self.attack_list = attack_list
self.defense_list = defense_list
self.dataset = dataset
self.current_attack: Optional[str] = None
self.current_defense_idx: int = -1
self.max_steps: int = len(defense_list)
self.current_step: int = 0
# Define action and observation space
self.action_space = spaces.Discrete(len(defense_list))
# Observation: [attack_type one-hot, classification outcome]
self.observation_space = spaces.Box(
low=0,
high=1,
shape=(len(attack_list) + 1,),
dtype=np.float32,
)
# Initialize model (for simplicity, using a random model)
self.model = self._initialize_model()
# Wrap the model with ART's PyTorchClassifier
self.classifier = PyTorchClassifier(
model=self.model,
loss=nn.CrossEntropyLoss(),
optimizer=optim.SGD(self.model.parameters(), lr=0.01),
input_shape=(1, 28, 28),
nb_classes=10,
)
def _initialize_model(self) -> nn.Module:
"""
Initialize a simple PyTorch model.
Returns:
nn.Module: The initialized PyTorch model.
"""
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.flatten = nn.Flatten()
self.fc = nn.Linear(28 * 28, 10)
def forward(self, x):
x = self.flatten(x)
logits = self.fc(x)
return logits
model = SimpleModel()
return model
def reset(self, seed: Optional[int] = None) -> np.ndarray:
"""
Reset the environment for a new episode.
Args:
seed (Optional[int]): Seed for reproducibility.
Returns:
np.ndarray: Initial observation.
"""
if seed is not None:
np.random.seed(seed)
random.seed(seed)
self.current_attack = random.choice(self.attack_list)
self.current_defense_idx = -1
self.current_step = 0
attack_one_hot = self._get_attack_one_hot(self.current_attack)
classification_outcome = self._get_classification_outcome()
observation = np.concatenate([attack_one_hot, [classification_outcome]]).astype(
np.float32
)
logger.debug(f"Environment reset with attack: {self.current_attack}")
return observation
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]:
"""
Execute one step in the environment.
Args:
action (int): The action taken by the agent.
Returns:
Tuple[np.ndarray, float, bool, Dict[str, Any]]: Observation, reward, done, info
"""
try:
defense_strategy = self.defense_list[action]
logger.debug(f"Selected defense strategy: {defense_strategy}")
# Apply defense and evaluate
success = self._apply_defense_and_evaluate(
self.current_attack, defense_strategy
)
reward = 1.0 if success else -1.0
self.current_step += 1
done = self.current_step >= self.max_steps
# Prepare next observation
attack_one_hot = self._get_attack_one_hot(self.current_attack)
classification_outcome = 1.0 if success else 0.0
observation = np.concatenate([attack_one_hot, [classification_outcome]]).astype(
np.float32
)
info = {"defense": defense_strategy, "success": success}
logger.debug(
f"Step: {self.current_step}, Reward: {reward}, Done: {done}"
)
return observation, reward, done, info
except Exception as e:
logger.error(f"Error during step execution: {e}")
return np.zeros(self.observation_space.shape, dtype=np.float32), -1.0, True, {}
def render(self, mode: str = "human") -> None:
"""
Render the environment.
Args:
mode (str): The mode to render with.
"""
if self.current_attack:
logger.info(f"Current Attack: {self.current_attack}")
else:
logger.info("Environment not yet initialized.")
def _get_attack_one_hot(self, attack: str) -> np.ndarray:
"""
Convert attack type to one-hot encoding.
Args:
attack (str): The attack type.
Returns:
np.ndarray: One-hot encoded vector.
"""
one_hot = np.zeros(len(self.attack_list), dtype=np.float32)
try:
index = self.attack_list.index(attack)
one_hot[index] = 1.0
except ValueError:
logger.error(f"Attack {attack} not found in attack list.")
return one_hot
def _get_classification_outcome(self) -> float:
"""
Simulate a classification outcome.
Returns:
float: 1.0 for correct classification, 0.0 otherwise.
"""
return random.choice([0.0, 1.0])
def _apply_defense_and_evaluate(self, attack: str, defense: str) -> bool:
"""
Apply the defense strategy against the attack and evaluate success.
Args:
attack (str): The attack type.
defense (str): The defense strategy.
Returns:
bool: True if defense is successful, False otherwise.
"""
try:
# Placeholder implementation
# In practice, apply attack and defense using ART and evaluate
success = random.choice([True, False])
logger.debug(
f"Defense {defense} against attack {attack} {'succeeded' if success else 'failed'}."
)
return success
except Exception as e:
logger.error(f"Error applying defense {defense}: {e}")
return False
class ActorCritic(nn.Module):
"""
Actor-Critic Network for Reinforcement Learning
"""
def __init__(self, state_dim: int, action_dim: int, hidden_dim: int = 128):
"""
Initialize the Actor-Critic network.
Args:
state_dim (int): Dimension of the state space.
action_dim (int): Dimension of the action space.
hidden_dim (int): Number of hidden units.
"""
super(ActorCritic, self).__init__()
self.actor = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, action_dim),
nn.Softmax(dim=-1),
)
self.critic = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1),
)
def forward(self, state: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Forward pass through the network.
Args:
state (torch.Tensor): The input state.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Action probabilities and state value.
"""
action_probs = self.actor(state)
state_value = self.critic(state)
return action_probs, state_value
class RLAgent:
"""
Reinforcement Learning Agent using Actor-Critic Method
"""
def __init__(
self,
state_dim: int,
action_dim: int,
hidden_dim: int = 128,
lr: float = 1e-3,
gamma: float = 0.99,
):
"""
Initialize the RL agent.
Args:
state_dim (int): Dimension of the state space.
action_dim (int): Dimension of the action space.
hidden_dim (int): Number of hidden units.
lr (float): Learning rate.
gamma (float): Discount factor.
"""
self.gamma = gamma
self.model = ActorCritic(state_dim, action_dim, hidden_dim)
self.optimizer = optim.Adam(self.model.parameters(), lr=lr)
self.log_probs: List[torch.Tensor] = []
self.values: List[torch.Tensor] = []
self.rewards: List[float] = []
def select_action(self, state: np.ndarray) -> int:
"""
Select an action based on the current state.
Args:
state (np.ndarray): The current state.
Returns:
int: The selected action.
"""
state_tensor = torch.from_numpy(state).float()
action_probs, state_value = self.model(state_tensor)
dist = Categorical(action_probs)
action = dist.sample()
self.log_probs.append(dist.log_prob(action))
self.values.append(state_value)
logger.debug(f"Action selected: {action.item()} with prob {action_probs[action]}")
return action.item()
def store_reward(self, reward: float) -> None:
"""
Store the reward received.
Args:
reward (float): The reward received.
"""
self.rewards.append(reward)
def update(self) -> None:
"""
Update the policy and value networks.
"""
R = 0
returns: List[float] = []
for r in reversed(self.rewards):
R = r + self.gamma * R
returns.insert(0, R)
returns_tensor = torch.tensor(returns)
returns_tensor = (returns_tensor - returns_tensor.mean()) / (
returns_tensor.std() + 1e-5
)
policy_loss = []
value_loss = []
for log_prob, value, R in zip(self.log_probs, self.values, returns_tensor):
advantage = R - value.item()
policy_loss.append(-log_prob * advantage)
value_loss.append(nn.functional.mse_loss(value.squeeze(), torch.tensor(R)))
loss = torch.stack(policy_loss).sum() + torch.stack(value_loss).sum()
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
# Clear memory
self.log_probs.clear()
self.values.clear()
self.rewards.clear()
logger.debug(f"Agent updated with loss: {loss.item()}")
def train_agent(
episodes: int = 1000,
attack_list: Optional[List[str]] = None,
defense_list: Optional[List[str]] = None,
) -> Tuple[RLAgent, List[float]]:
"""
Train the RL agent in the Adversarial Defense Environment.
Args:
episodes (int): Number of training episodes.
attack_list (Optional[List[str]]): List of attacks.
defense_list (Optional[List[str]]): List of defenses.
Returns:
Tuple[RLAgent, List[float]]: The trained agent and the list of cumulative rewards.
"""
if attack_list is None:
attack_list = ["FGSM", "PGD"]
if defense_list is None:
defense_list = ["DefenseA", "DefenseB", "DefenseC"]
# Dummy dataset placeholder
dataset = None
env = AdversarialDefenseEnv(attack_list, defense_list, dataset)
state_dim = env.observation_space.shape[0]
action_dim = env.action_space.n
agent = RLAgent(state_dim, action_dim)
rewards_history: List[float] = []
for episode in range(1, episodes + 1):
state = env.reset()
done = False
cumulative_reward = 0.0
while not done:
action = agent.select_action(state)
next_state, reward, done, info = env.step(action)
agent.store_reward(reward)
cumulative_reward += reward
state = next_state
agent.update()
rewards_history.append(cumulative_reward)
if episode % 100 == 0:
avg_reward = np.mean(rewards_history[-100:])
logger.info(
f"Episode {episode}\tAverage Reward (last 100): {avg_reward:.2f}"
)
return agent, rewards_history
def visualize_training(rewards_history: List[float]) -> None:
"""
Visualize the training progress using Plotly.
Args:
rewards_history (List[float]): List of cumulative rewards per episode.
"""
try:
cumulative_rewards = np.cumsum(rewards_history)
episodes = list(range(1, len(rewards_history) + 1))
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=episodes,
y=cumulative_rewards,
mode="lines",
name="Cumulative Rewards",
)
)
fig.update_layout(
title="Training Progress",
xaxis_title="Episode",
yaxis_title="Cumulative Reward",
template="plotly_dark",
)
fig.show()
except Exception as e:
logger.error(f"Error during visualization: {e}")
def main() -> None:
"""
Main function to train the RL agent and visualize the results.
"""
try:
episodes = 1000
agent, rewards_history = train_agent(episodes=episodes)
visualize_training(rewards_history)
except Exception as e:
logger.error(f"An error occurred in the main execution: {e}")
if __name__ == "__main__":
main()
Explanation of the Code
-
AdversarialDefenseEnv:
- Initialization: Sets up the environment with specified adversarial attacks and defense strategies. It defines the action and observation spaces and initializes a simple PyTorch model wrapped by ART's
PyTorchClassifier.
- Reset: Randomly selects an adversarial attack and initializes the classification outcome.
- Step: Executes the selected defense strategy against the chosen attack, determines the reward based on the success of the defense, and updates the environment's state.
- Render: Outputs the current attack for visualization purposes.
- Helper Methods: Include methods for one-hot encoding attack types, simulating classification outcomes, and applying defense strategies (currently placeholders that randomly determine success).
-
ActorCritic:
- Implements the Actor-Critic network architecture with separate networks for policy (actor) and value (critic).
- The actor outputs action probabilities, and the critic estimates the value of the current state.
-
RLAgent:
- Utilizes the
ActorCritic network to select actions and update its policy based on the observed rewards.
- Stores log probabilities of actions, state values, and rewards to compute the loss during updates.
- The
update method calculates the policy and value losses, performs backpropagation, and updates the neural network weights.
-
train_agent:
- Trains the RL agent over a specified number of episodes.
- In each episode, the agent interacts with the environment, selects actions, receives rewards, and updates its policy accordingly.
- Logs the average reward every 100 episodes for monitoring progress.
-
visualize_training:
- Uses Plotly to plot the cumulative rewards over episodes, providing a visual representation of the training progress.
-
main:
- Executes the training process and triggers the visualization of results.
- Encapsulates the entire workflow and handles any exceptions that may arise during execution.
Notes
-
Error Handling: Comprehensive error handling is incorporated throughout the code to catch and log exceptions gracefully, ensuring robustness under unexpected conditions.
-
Type Hints: All functions and methods include type hints to enhance code clarity and maintainability.
-
PEP-8 Compliance: The code adheres to PEP-8 standards, ensuring readability and consistency.
-
Placeholder Implementations: Certain components, such as the actual application of adversarial attacks and defenses, are currently implemented as placeholders. These should be replaced with actual logic using ART's functionalities for a production-ready solution.
-
Logging: The script utilizes Python’s built-in logging module to provide informative messages during execution, aiding in debugging and monitoring.
-
Dependencies: Ensure that the following Python packages are installed:
pip install gymnasium torch torchvision adversarial-robustness-toolbox plotly
Running the Script
Execute the script using Python 3. Ensure that all dependencies are installed. The script will train the RL agent and display a Plotly graph visualizing the training progress.
python adversarial_defense_rl.py
Replace adversarial_defense_rl.py with the filename you save the script as.