def __init__(
self,
classifier: 'PyTorchClassifier',
device: torch.device,
train_loader: torch.utils.data.DataLoader,
max_steps: int = 100,
robustness_threshold: float = 0.95,
seed: Optional[int] = 42,
) -> None:
"""
Initializes the DefenseSelectionEnv environment.
Args:
classifier: The PyTorch classifier to be defended.
device: The device (CPU/GPU) for computation.
train_loader: DataLoader for training data.
max_steps: Maximum number of steps per episode.
robustness_threshold: Threshold of robustness to terminate the episode.
seed: Random seed for reproducibility.
"""
super(DefenseSelectionEnv, self).__init__()
self.classifier = classifier
self.device = device
self.defense_manager = DefenseManager()
self.list_of_defenses = self.defense_manager.list_defenses()
self.current_step = 0
self.max_steps = max_steps
self.train_loader = train_loader
self.robustness_threshold = robustness_threshold
self.seed(seed)
# Define action and observation space
self.action_space = spaces.Discrete(len(self.list_of_defenses))
# Observation space components
metrics_keys = [
'Accuracy', 'Precision', 'Recall', 'F1 Score',
'ROC-AUC', 'PR-AUC', 'Log Loss', 'Cross Entropy Loss',
'Mean Squared Error', 'Kappa Statistic',
'Matthews Correlation Coefficient', 'Specificity',
'Jaccard Index', 'Balanced Accuracy',
'True Negative Rate', 'False Positive Rate',
'Dice Coefficient', 'Mean Average Precision'
]
self.metrics_keys = metrics_keys
self.observation_space = spaces.Dict({
'metrics': spaces.Box(
low=0.0, high=1.0, shape=(len(metrics_keys),), dtype=np.float32
),
'current_attack': spaces.Discrete(len(LIST_OF_ATTACKS)),
'attack_impact': spaces.Box(
low=0.0, high=1.0, shape=(1,), dtype=np.float32
),
'attack_strength': spaces.Box(
low=0.0, high=1.0, shape=(1,), dtype=np.float32
),
'previous_robustness': spaces.Box(
low=0.0, high=1.0, shape=(1,), dtype=np.float32
)
})
# Initialize internal state
self.current_attack: Optional[str] = None
self.attack_impact: float = 0.0
self.attack_strength: float = 0.0
self.previous_robustness: float = 0.0
self.history: List[int] = []
self.original_weights = copy.deepcopy(self.classifier.model.state_dict())
self.best_weights: Optional[Dict[str, torch.Tensor]] = None
def seed(self, seed: Optional[int] = None) -> List[int]:
"""
Sets the seed for reproducibility.
Args:
seed: The seed value.
Returns:
A list containing the seed.
"""
self.np_random, seed = seeding.np_random(seed)
return [seed]
def reset(self, seed: Optional[int] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Resets the environment to an initial state and returns the initial observation.
Args:
seed: The seed value for randomness.
Returns:
A tuple containing the initial observation and an empty info dictionary.
"""
try:
self.current_step = 0
self.previous_robustness = 0.0
self.current_attack = self.np_random.choice(LIST_OF_ATTACKS)
self.attack_impact = self.np_random.uniform(0.3, 0.7) # Ensuring meaningful impact
self.attack_strength = self.np_random.uniform(0.5, 1.0) # Attack strength between 0.5 and 1.0
self.history = []
self.classifier.model.load_state_dict(copy.deepcopy(self.original_weights)) # Resetting model weights
initial_observation = {
'metrics': np.zeros((len(self.metrics_keys),), dtype=np.float32),
'current_attack': LIST_OF_ATTACKS.index(self.current_attack),
'attack_impact': np.array([self.attack_impact], dtype=np.float32),
'attack_strength': np.array([self.attack_strength], dtype=np.float32),
'previous_robustness': np.array([self.previous_robustness], dtype=np.float32)
}
return initial_observation, {}
except Exception as e:
raise RuntimeError(f"Error during reset: {e}")
def step(self, action: int) -> Tuple[Dict[str, Any], float, bool, bool, Dict[str, Any]]:
"""
Executes the selected action (defense), applies attack, calculates metrics, and returns the outcome.
Args:
action: The action chosen by the agent.
Returns:
A tuple containing the next observation, reward, done flag, truncated flag, and an info dictionary.
"""
try:
self.current_step += 1
done = False
truncated = False
info = {}
# Validate action
if not self.action_space.contains(action):
raise ValueError(f"Invalid action: {action}")
selected_defense = self.list_of_defenses[action]
self.history.append(action)
# Apply attack with specified strength
images, labels = next(iter(self.train_loader))
images = images.to(self.device)
labels = labels.to(self.device)
attacked_images = apply_attack(
attack_name=self.current_attack,
classifier=self.classifier,
x=images,
y=labels,
strength=self.attack_strength # Assuming apply_attack can take strength parameter
)
# Apply defense
defended_output = self.defense_manager.apply_defense(
defense_name=selected_defense,
classifier=self.classifier,
x=attacked_images,
y=labels
)
# Compute metrics
metrics_calculator = MetricsCalculator(
preds=defended_output,
labels=labels,
num_classes=1000
)
metrics = metrics_calculator.get_all_metrics()
# Extract relevant metrics
metrics_values = np.array([
metrics.get(key, 0.0) for key in self.metrics_keys
], dtype=np.float32)
# Calculate robustness as the average of key metrics
current_robustness = np.mean(metrics_values[:5]) # Example: first five metrics
robustness_improvement = current_robustness - self.previous_robustness
self.previous_robustness = current_robustness
# Update model weights if robustness improves significantly
if self.best_weights is None or current_robustness > self.robustness_threshold:
self.best_weights = copy.deepcopy(self.classifier.model.state_dict())
# Define rewards
reward_defense = robustness_improvement * 10 # Reward for robustness improvement
reward_efficiency = -0.1 # Small penalty per step to encourage efficiency
reward = reward_defense + reward_efficiency
# Check if robustness threshold is achieved
if current_robustness >= self.robustness_threshold:
done = True
info['reason'] = 'Desired robustness achieved.'
if self.best_weights:
self.save_best_weights()
# Check if maximum steps are reached
if self.current_step >= self.max_steps:
done = True
truncated = True
info['reason'] = 'Maximum steps reached.'
if self.best_weights:
self.save_best_weights()
# Adapt attack for next step if not done
if not done:
self.current_attack = self.np_random.choice(LIST_OF_ATTACKS)
self.attack_impact = self.np_random.uniform(0.3, 0.7) # Update attack impact
self.attack_strength = self.np_random.uniform(0.5, 1.0) # Update attack strength
# Construct next observation
next_observation = {
'metrics': metrics_values,
'current_attack': LIST_OF_ATTACKS.index(self.current_attack),
'attack_impact': np.array([self.attack_impact], dtype=np.float32),
'attack_strength': np.array([self.attack_strength], dtype=np.float32),
'previous_robustness': np.array([self.previous_robustness], dtype=np.float32)
}
return next_observation, reward, done, truncated, info
except StopIteration:
# Handle the case where the data loader is exhausted
done = True
truncated = True
reward = 0.0
next_observation, _ = self.reset()
return next_observation, reward, done, truncated, {}
except Exception as e:
raise RuntimeError(f"Error during step: {e}")
def render(self, mode: str = 'human') -> None:
"""
Renders the environment. Displays current state metrics.
Args:
mode: The mode in which to render the environment.
"""
try:
metrics_str = ', '.join([f"{key}: {value:.2f}" for key, value in zip(
self.metrics_keys,
self.observation_space['metrics'].shape # This should be metrics_values, corrected below
)])
# Correcting the above line to display actual metrics
# To store and display actual metrics, we need to save them as part of the state
# For now, we'll just print placeholders
print(f"Step: {self.current_step}, Current Attack: {self.current_attack}, "
f"Attack Impact: {self.attack_impact:.2f}, Attack Strength: {self.attack_strength:.2f}, "
f"Previous Robustness: {self.previous_robustness:.2f}")
# If metrics_values are stored, they can be printed here
except Exception as e:
print(f"Error during render: {e}")
def close(self) -> None:
"""
Performs any necessary cleanup.
"""
# Implement any necessary cleanup here
pass
def save_best_weights(self, filepath: str = "best_model_weights.pth") -> None:
"""
Saves the best model weights to a file.
Args:
filepath: Path to save the best model weights.
"""
if self.best_weights:
try:
torch.save(self.best_weights, filepath)
print(f"Best model weights saved to {filepath}.")
except Exception as e:
print(f"Error saving best weights: {e}")