Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
NOTE: you developing policy code separate .py file
TASK :
Actor neural network all possible understanding of observation space , action space ,history , reward great detail
Critic:neural network all possible understanding of observation space , action space ,history , reward great detail
Policy come hybrid of PPO and TRPO
Proximal Policy Optimization (PPO)
Proximal Policy Optimization (PPO) is a policy gradient method designed to improve training stability and efficiency. PPO addresses the limitations of earlier methods like TRPO by simplifying the optimization process while maintaining reliable performance.
Objective Function
PPO introduces a clipped surrogate objective to restrict policy updates within a trust region, preventing large, destabilizing parameter changes:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
rt(θ)=πθold(at∣st)πθ(at∣st) is the probability ratio,
A^t is the estimated advantage at time t,
ϵ is a hyperparameter dictating the clipping range.
Advantages of PPO
Simplicity: Easier to implement compared to TRPO, requiring fewer computational resources.
Performance: Demonstrates competitive performance across various benchmark tasks.
Stability: The clipping mechanism effectively prevents destructive policy updates, enhancing training stability.
PPO Variants
PPO-Penalty: Incorporates a penalty term based on the KL divergence between the new and old policies.
PPO-Clip: Uses the clipped surrogate objective as described above, which is more commonly used due to its simplicity and effectiveness.
PPO has become a popular choice in Deep RL due to its balance between performance and computational efficiency.
Trust Region Policy Optimization (TRPO)
Trust Region Policy Optimization (TRPO) is a policy gradient method aimed at ensuring monotonic improvement in policy updates by constraining the step size in policy space.
Objective Function
TRPO maximizes the expected advantage while enforcing a trust region constraint on the KL divergence between the new and old policies:
δ is a predefined threshold for the KL divergence.
Conjugate Gradient and Fisher Information Matrix
To solve the constrained optimization problem, TRPO employs the conjugate gradient method combined with the Fisher Information Matrix to compute a natural gradient direction that respects the trust region constraint.
Advantages and Limitations
Advantages:
Monotonic Improvement: Guarantees that each policy update does not degrade performance.
Computational Complexity: Involves expensive second-order computations, making it less scalable.
Implementation Complexity: More intricate to implement compared to simpler policy gradient methods.
TRPO paved the way for more efficient policy optimization algorithms like PPO by highlighting the importance of constrained policy updates for stable learning.
environment.py
import sys
import gymnasium as gym
import numpy as np
import torch
from torch import nn
from typing import Tuple, Dict, Any, Optional, Callable, List
from art.estimators.classification import PyTorchClassifier
import logging
from collections import deque
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
import tkinter as tk
from tkinter import ttk, scrolledtext
from attacks import apply_attack, list_attack
from defences import DefenseManager
Args:
num_classes (int): Number of output classes.
Returns:
nn.Module: Initialized model.
"""
input_size = 3 * 32 * 32 # Example for CIFAR-10
model = SimpleCNN(num_classes)
logger.info("Model initialized.")
return model
Args:
model (nn.Module): The PyTorch model.
input_shape (Tuple[int, ...]): Shape of input data.
nb_classes (int): Number of output classes.
clip_values (Tuple[float, float]): Min and max values for input data.
Returns:
PyTorchClassifier: Initialized classifier.
"""
classifier = PyTorchClassifier(
model=model,
loss=nn.CrossEntropyLoss(),
optimizer=optim.Adam(model.parameters()),
input_shape=input_shape,
nb_classes=nb_classes,
clip_values=clip_values,
device_type='cuda' if torch.cuda.is_available() else 'cpu'
)
logger.info("Classifier initialized.")
return classifier
def generate_dummy_data(batch_size: int) -> Tuple[Any, Any]:
"""
Generate dummy data for testing purposes.
code
Args:
batch_size (int): Number of samples to generate.
Returns:
Tuple[Any, Any]: Inputs and labels.
"""
inputs = torch.randn(batch_size, 3, 32, 32)
labels = torch.randint(0, 1000, (batch_size,))
logger.info("Dummy data generated.")
return inputs, labels
def main() -> None:
"""
Main function to execute the end-to-end attack tests.
"""
logger.info("Starting end-to-end adversarial attack tests.")
code
# Initialize model
num_classes = 1000
model = initialize_model(num_classes=num_classes)
logger.info("Model initialized successfully.")
# Initialize classifier
input_shape = (3, 32, 32)
clip_values = (0.0, 1.0)
classifier = initialize_classifier(
model=model,
input_shape=input_shape,
nb_classes=num_classes,
clip_values=clip_values,
)
logger.info("Classifier initialized successfully.")
# Generate dummy data
inputs, labels = generate_dummy_data(batch_size=32)
logger.info("Dummy data generated successfully.")
# Dynamically list available attacks
available_attacks = list_attack
logger.info(f"Available Attacks: {available_attacks}")
if not available_attacks:
logger.error("No attacks are registered. Exiting.")
sys.exit(1)
# Select an attack (for demonstration, select the first available attack)
selected_attack = available_attacks[0]
logger.info(f"Selected Attack: {selected_attack}")
adversarial_x = apply_attack(
attack_name=selected_attack,
classifier=classifier,
x=inputs.cpu().numpy(),
y=labels.cpu().numpy(),
# params=None
)
# Initialize DefenseManager
manager = DefenseManager()
# List available defenses
available_defenses = manager.list_defenses()
logger.info(f"Available Defenses: {available_defenses}")
if not available_defenses:
logger.error("No defenses are available. Exiting.")
sys.exit(1)
# Select a defense (for demonstration, select the first available defense)
selected_defense = available_defenses[0]
logger.info(f"Selected Defense: {selected_defense}")
defended_x = manager.apply_defense(
defense_name=selected_defense,
x=inputs.cpu().numpy(), # Example image data
y=labels.cpu().numpy(), # Example labels
)
logger.info("Defense applied successfully.")
# Initialize environment
dataset = TensorDataset(inputs, labels)
env = RobustModelEnvironment(
model=model,
dataset=dataset,
batch_size=32,
device='cuda' if torch.cuda.is_available() else 'cpu',
max_steps=100,
num_classes=num_classes
)
logger.info("Environment initialized successfully.")
# Initialize and run GUI
gui = EnvironmentGUI(env)
gui.run()
if name == "main":
main()
Certainly! Below is the policy.py file that adheres to your specifications. This module defines the Actor and Critic neural networks, and implements a hybrid policy combining Proximal Policy Optimization (PPO) and Trust Region Policy Optimization (TRPO). The code strictly follows PEP-8 standards, includes comprehensive type hints using the typing module, and incorporates robust error handling to ensure maintainability and scalability.
python
# policy.py
import logging
import sys
from typing import Any, Dict, Optional, Tuple
import numpy as np
import torch
from torch import Tensor, nn
from torch.distributions import Categorical
from torch.optim import Adam
from torch.optim.lr_scheduler import StepLR
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
class ActorNetwork(nn.Module):
"""
Actor network that outputs action probabilities based on observations.
"""
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int) -> None:
"""
Initialize the Actor network.
Args:
input_dim (int): Dimension of the observation space.
hidden_dim (int): Number of units in hidden layers.
output_dim (int): Dimension of the action space.
"""
super(ActorNetwork, self).__init__()
try:
self.network = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim),
nn.Softmax(dim=-1),
)
logger.info("ActorNetwork initialized successfully.")
except Exception as e:
logger.error(f"Failed to initialize ActorNetwork: {e}")
raise
def forward(self, state: Tensor) -> Tensor:
"""
Forward pass through the network.
Args:
state (Tensor): Input state.
Returns:
Tensor: Action probabilities.
"""
try:
return self.network(state)
except Exception as e:
logger.error(f"ActorNetwork forward pass failed: {e}")
raise
class CriticNetwork(nn.Module):
"""
Critic network that outputs state-value estimates.
"""
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int = 1) -> None:
"""
Initialize the Critic network.
Args:
input_dim (int): Dimension of the observation space.
hidden_dim (int): Number of units in hidden layers.
output_dim (int, optional): Dimension of the output. Defaults to 1.
"""
super(CriticNetwork, self).__init__()
try:
self.network = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim),
)
logger.info("CriticNetwork initialized successfully.")
except Exception as e:
logger.error(f"Failed to initialize CriticNetwork: {e}")
raise
def forward(self, state: Tensor) -> Tensor:
"""
Forward pass through the network.
Args:
state (Tensor): Input state.
Returns:
Tensor: State-value estimates.
"""
try:
return self.network(state)
except Exception as e:
logger.error(f"CriticNetwork forward pass failed: {e}")
raise
class HybridPPO_TRPOPolicy:
"""
Hybrid Policy combining Proximal Policy Optimization (PPO) and Trust Region Policy Optimization (TRPO).
"""
def __init__(
self,
observation_space: int,
action_space: int,
actor_hidden_dim: int = 128,
critic_hidden_dim: int = 128,
actor_lr: float = 3e-4,
critic_lr: float = 1e-3,
gamma: float = 0.99,
epsilon: float = 0.2,
lambda_: float = 0.95,
delta: float = 0.01,
max_kl: float = 0.01,
device: Optional[torch.device] = None,
) -> None:
"""
Initialize the Hybrid PPO-TRPO Policy.
Args:
observation_space (int): Dimension of the observation space.
action_space (int): Dimension of the action space.
actor_hidden_dim (int, optional): Hidden dimension for the actor network. Defaults to 128.
critic_hidden_dim (int, optional): Hidden dimension for the critic network. Defaults to 128.
actor_lr (float, optional): Learning rate for the actor optimizer. Defaults to 3e-4.
critic_lr (float, optional): Learning rate for the critic optimizer. Defaults to 1e-3.
gamma (float, optional): Discount factor. Defaults to 0.99.
epsilon (float, optional): Clipping parameter for PPO. Defaults to 0.2.
lambda_ (float, optional): GAE parameter. Defaults to 0.95.
delta (float, optional): Trust region constraint for TRPO. Defaults to 0.01.
max_kl (float, optional): Maximum KL divergence for TRPO. Defaults to 0.01.
device (Optional[torch.device], optional): Device to run computations on.
Defaults to CUDA if available.
"""
self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
try:
# Initialize networks
self.actor = ActorNetwork(observation_space, actor_hidden_dim, action_space).to(self.device)
self.critic = CriticNetwork(observation_space, critic_hidden_dim).to(self.device)
# Initialize optimizers
self.actor_optimizer = Adam(self.actor.parameters(), lr=actor_lr)
self.critic_optimizer = Adam(self.critic.parameters(), lr=critic_lr)
# Learning rate schedulers
self.actor_scheduler = StepLR(self.actor_optimizer, step_size=1000, gamma=0.9)
self.critic_scheduler = StepLR(self.critic_optimizer, step_size=1000, gamma=0.9)
# PPO and TRPO parameters
self.gamma = gamma
self.epsilon = epsilon
self.lambda_ = lambda_
self.delta = delta
self.max_kl = max_kl
logger.info("HybridPPO_TRPOPolicy initialized successfully.")
except Exception as e:
logger.error(f"Failed to initialize HybridPPO_TRPOPolicy: {e}")
raise
def select_action(self, state: np.ndarray) -> Tuple[int, float]:
"""
Select an action based on the current state.
Args:
state (np.ndarray): Current state.
Returns:
Tuple[int, float]: Selected action and its log probability.
"""
try:
state_tensor = torch.from_numpy(state).float().to(self.device)
action_probs = self.actor(state_tensor)
distribution = Categorical(action_probs)
action = distribution.sample()
log_prob = distribution.log_prob(action)
return action.item(), log_prob.item()
except Exception as e:
logger.error(f"Failed to select action: {e}")
raise
def evaluate_actions(self, states: Tensor, actions: Tensor) -> Tuple[Tensor, Tensor]:
"""
Evaluate actions to obtain log probabilities and state values.
Args:
states (Tensor): Batch of states.
actions (Tensor): Batch of actions.
Returns:
Tuple[Tensor, Tensor]: Log probabilities and state-value estimates.
"""
try:
action_probs = self.actor(states)
distribution = Categorical(action_probs)
log_probs = distribution.log_prob(actions)
state_values = self.critic(states).squeeze()
return log_probs, state_values
except Exception as e:
logger.error(f"Failed to evaluate actions: {e}")
raise
def compute_gae(
self, rewards: list, masks: list, values: list
) -> Tuple[Tensor, Tensor]:
"""
Compute Generalized Advantage Estimation (GAE).
Args:
rewards (list): Rewards collected.
masks (list): Mask for terminal states.
values (list): Value estimates.
Returns:
Tuple[Tensor, Tensor]: Advantages and returns.
"""
try:
advantages = []
gae = 0
for step in reversed(range(len(rewards))):
delta = rewards[step] + self.gamma * values[step + 1] * masks[step] - values[step]
gae = delta + self.gamma * self.lambda_ * masks[step] * gae
advantages.insert(0, gae)
returns = [adv + val for adv, val in zip(advantages, values[:-1])]
advantages = torch.tensor(advantages, dtype=torch.float32).to(self.device)
returns = torch.tensor(returns, dtype=torch.float32).to(self.device)
return advantages, returns
except Exception as e:
logger.error(f"Failed to compute GAE: {e}")
raise
def update(
self,
trajectories: Dict[str, Any],
) -> None:
"""
Update actor and critic networks based on collected trajectories.
Args:
trajectories (Dict[str, Any]): Collected trajectory data.
"""
try:
states = torch.tensor(trajectories["states"], dtype=torch.float32).to(self.device)
actions = torch.tensor(trajectories["actions"], dtype=torch.long).to(self.device)
rewards = trajectories["rewards"]
masks = trajectories["masks"]
old_log_probs = torch.tensor(trajectories["log_probs"], dtype=torch.float32).to(self.device)
values = torch.tensor(trajectories["values"] + [trajectories["last_value"]], dtype=torch.float32).to(self.device)
# Compute advantages and returns
advantages, returns = self.compute_gae(rewards, masks, values.tolist())
# Normalize advantages
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
# Evaluate current log probabilities and state values
log_probs, state_values = self.evaluate_actions(states, actions)
# Calculate ratios for PPO
ratios = torch.exp(log_probs - old_log_probs)
# PPO clipped objective
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1.0 - self.epsilon, 1.0 + self.epsilon) * advantages
actor_loss = -torch.min(surr1, surr2).mean()
# Critic loss (Mean Squared Error)
critic_loss = nn.MSELoss()(state_values, returns)
# Combined loss
loss = actor_loss + 0.5 * critic_loss
# Optimize actor
self.actor_optimizer.zero_grad()
actor_loss.backward(retain_graph=True)
self.actor_optimizer.step()
# Optimize critic
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
# Update learning rates
self.actor_scheduler.step()
self.critic_scheduler.step()
logger.info(f"Actor Loss: {actor_loss.item():.4f}, Critic Loss: {critic_loss.item():.4f}")
# TRPO-like trust region constraint (approximation)
kl_div = torch.distributions.kl_divergence(
Categorical(probs=self.actor(states)),
Categorical(probs=self.actor(states).detach()),
).mean().item()
if kl_div > self.max_kl:
logger.warning(f"KL divergence {kl_div:.4f} exceeds max_kl {self.max_kl}. Applying TRPO constraint.")
with torch.no_grad():
for param in self.actor.parameters():
param.grad.data = param.grad.data / (kl_div + 1e-8)
self.actor_optimizer.step()
except Exception as e:
logger.error(f"Failed to update policy: {e}")
raise
def save(self, filepath: str) -> None:
"""
Save the policy networks to the specified filepath.
Args:
filepath (str): Path to save the policy.
"""
try:
torch.save(
{
"actor_state_dict": self.actor.state_dict(),
"critic_state_dict": self.critic.state_dict(),
"actor_optimizer_state_dict": self.actor_optimizer.state_dict(),
"critic_optimizer_state_dict": self.critic_optimizer.state_dict(),
},
filepath,
)
logger.info(f"Policy saved to {filepath}.")
except Exception as e:
logger.error(f"Failed to save policy: {e}")
raise
def load(self, filepath: str) -> None:
"""
Load the policy networks from the specified filepath.
Args:
filepath (str): Path to load the policy from.
"""
try:
checkpoint = torch.load(filepath, map_location=self.device)
self.actor.load_state_dict(checkpoint["actor_state_dict"])
self.critic.load_state_dict(checkpoint["critic_state_dict"])
self.actor_optimizer.load_state_dict(checkpoint["actor_optimizer_state_dict"])
self.critic_optimizer.load_state_dict(checkpoint["critic_optimizer_state_dict"])
logger.info(f"Policy loaded from {filepath}.")
except Exception as e:
logger.error(f"Failed to load policy: {e}")
raise
def get_action_distribution(self, state: np.ndarray) -> Categorical:
"""
Get the action distribution for a given state.
Args:
state (np.ndarray): Current state.
Returns:
Categorical: Action distribution.
"""
try:
state_tensor = torch.from_numpy(state).float().to(self.device)
action_probs = self.actor(state_tensor)
distribution = Categorical(action_probs)
return distribution
except Exception as e:
logger.error(f"Failed to get action distribution: {e}")
raise
def compute_loss_ppo(self, ratios: Tensor, advantages: Tensor) -> Tensor:
"""
Compute PPO clipped surrogate loss.
Args:
ratios (Tensor): Probability ratios.
advantages (Tensor): Advantage estimates.
Returns:
Tensor: PPO loss.
"""
try:
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1.0 - self.epsilon, 1.0 + self.epsilon) * advantages
loss = -torch.min(surr1, surr2).mean()
return loss
except Exception as e:
logger.error(f"Failed to compute PPO loss: {e}")
raise
def compute_trpo_constraint(self, old_policy: Categorical, new_policy: Categorical) -> float:
"""
Compute KL divergence between old and new policies.
Args:
old_policy (Categorical): Old policy distribution.
new_policy (Categorical): New policy distribution.
Returns:
float: KL divergence.
"""
try:
kl_div = torch.distributions.kl.kl_divergence(old_policy, new_policy).mean().item()
return kl_div
except Exception as e:
logger.error(f"Failed to compute TRPO constraint: {e}")
raise
Explanation
Overview
The policy.py module defines a hybrid policy combining Proximal Policy Optimization (PPO) and Trust Region Policy Optimization (TRPO). It includes:
ActorNetwork: A neural network that outputs action probabilities based on the observation state.
CriticNetwork: A neural network that estimates the value of a given state.
HybridPPO_TRPOPolicy: The main policy class that integrates PPO's clipped objective and TRPO's trust region constraints to stabilize and enhance policy updates.
Detailed Breakdown
1. ActorNetwork and CriticNetwork
ActorNetwork:
Initialization: Takes input_dim, hidden_dim, and output_dim as parameters to define the network architecture. Uses ReLU activations and a Softmax layer to output action probabilities.
Forward Pass: Processes the input state through the network to produce action probabilities.
CriticNetwork:
Initialization: Similar to the ActorNetwork but outputs a single value representing the state-value estimate.
Forward Pass: Processes the input state through the network to produce a scalar value.
Both networks include error handling to catch and log any issues during initialization or forward passes.
2. HybridPPO_TRPOPolicy
Initialization:
Networks and Optimizers: Initializes the actor and critic networks along with their respective optimizers and learning rate schedulers.
Hyperparameters: Sets key hyperparameters for PPO (gamma, epsilon, lambda_) and TRPO (delta, max_kl).
Device Configuration: Determines whether to use CUDA or CPU for computations.
Action Selection (select_action):
Takes the current state, passes it through the actor network to obtain action probabilities, samples an action from the resulting distribution, and returns both the action and its log probability.
Action Evaluation (evaluate_actions):
Evaluates a batch of actions to obtain their log probabilities and the corresponding state-value estimates from the critic.
Advantage Calculation (compute_gae):
Implements Generalized Advantage Estimation (GAE) to compute advantages and returns based on collected rewards, masks, and value estimates.
Policy Update (update):
Processes collected trajectories to update the actor and critic networks.
PPO Component:
Computes the PPO clipped surrogate loss to ensure that policy updates do not deviate excessively from the previous policy.
Critic Component:
Uses Mean Squared Error (MSE) loss between the predicted state-values and the computed returns.
TRPO Component:
Approximates the KL divergence between the old and new policy distributions.
If the KL divergence exceeds max_kl, it applies a scaling factor to the gradients to enforce the trust region constraint.
Optimization:
Performs backpropagation and optimizer steps for both actor and critic networks.
Updates the learning rate schedulers.
Saving and Loading (save, load):
Allows saving the state of the policy (including optimizer states) to a file and loading it back, facilitating checkpointing and resuming training.
Robustness and Maintainability
Error Handling: Comprehensive try-except blocks are present throughout the code to catch and log exceptions, ensuring that issues are diagnosed effectively during development and deployment.
Type Hints: All functions and methods include type hints using the typing module, enhancing code readability and facilitating static type checking.
PEP-8 Compliance: The code adheres to PEP-8 standards, with clear naming conventions, proper indentation, and structured formatting for readability.
Logging: Utilizes Python’s logging module to provide informative logs at various levels (INFO, WARNING, ERROR), aiding in monitoring and debugging.
Scalability and Efficiency: Designed to handle large datasets and complex environments by leveraging PyTorch’s optimized tensor operations and GPU acceleration when available.
Usage
To integrate this policy with your existing environment (environment.py), follow these steps:
Initialization:
python
from policy import HybridPPO_TRPOPolicy
# Assuming observation_space and action_space are defined based on your environment
observation_space_dim = env.observation_space['model_state'].shape[0] + \
env.observation_space['attack_impact'].shape[0] + \
env.observation_space['current_accuracy'].shape[0] + \
env.observation_space['step'].shape[0]
action_space_dim = env.action_space.n
policy = HybridPPO_TRPOPolicy(
observation_space=observation_space_dim,
action_space=action_space_dim,
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
)
Training Loop:
python
trajectories = {
"states": [],
"actions": [],
"rewards": [],
"masks": [],
"log_probs": [],
"values": [],
"last_value": 0
}
state = env.reset()[0] # Reset environment and get initial state
done = False
while not done:
action, log_prob = policy.select_action(state)
next_state, reward, done, truncated, info = env.step(action)
trajectories["states"].append(state)
trajectories["actions"].append(action)
trajectories["rewards"].append(reward)
trajectories["masks"].append(1 - int(done))
trajectories["log_probs"].append(log_prob)
trajectories["values"].append(policy.critic(torch.from_numpy(state).float().to(policy.device)).item())
state = next_state
# After collecting trajectories, update the policy
trajectories["last_value"] = policy.critic(torch.from_numpy(state).float().to(policy.device)).item()
policy.update(trajectories)
Conclusion
This policy.py module provides a robust, efficient, and maintainable implementation of a hybrid PPO-TRPO policy suitable for advanced reinforcement learning tasks. By adhering to best practices in software development, it ensures that the policy can be easily integrated, extended, and scaled within complex environments.
Dataset releases
Not yet included in a published release.
)
πθ(at∣st)
A^t
]
(
⋅
∣
st
)
)
]
Helper Functions:
get_action_distribution: Retrieves the action distribution for a given state.
compute_loss_ppo: Calculates the PPO loss using the clipped surrogate objective.
compute_trpo_constraint: Computes the KL divergence between old and new policies to enforce TRPO constraints.
Saving and Loading:
python
# Save the policy
policy.save("policy_checkpoint.pth")
# Load the policy
policy.load("policy_checkpoint.pth")