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.
TASK : we develop using torch module end to end , DAPO , from scratch user input is env (import gymnasium as gym env = gym.make("LunarLander-v3", render_mode="human"))
End-to-End Pseudo Algorithm Development for DAPO
The sources present DAPO (Dual Approximation Policy Optimization), a reinforcement learning framework that extends policy mirror descent methods to incorporate general function approximation. The algorithm leverages the concept of a Bregman projected policy class and utilizes the dual Bregman divergence for measuring the accuracy of function approximation. This response outlines the end-to-end pseudo-algorithm for DAPO, focusing on the DAPO-KL variant, along with its mathematical equations.
Initial state distribution ρ ∈ Δ(S) (optional, for online training)
Reply buffer distribution ν(k) ∈ Δ(S) (optional, for off-policy training)
Procedure:
Initialization: Set k = 0.
Loop: Repeat until convergence or a predefined number of iterations:
Critic Update: Find that approximates Q(k).
Assistant
Q^(k)
Policy Update:
Find θ(k+1) by (approximately) solving:
θ∈ΘminEs∼ν(k)[DΦ∗(∇Φ(πs(k))−η,
where:
ν(k) can be replaced by d(k)ρ for online training.
fθs is a parameterized function used for approximating the dual update.
Assign π(k+1)s using the Bregman projection:
πs(k+1)=
Increment k: k ← k + 1.
Output:
Learned policy π(K) after K iterations
Certainly! Below is a comprehensive implementation of the Dual Approximation Policy Optimization (DAPO) algorithm using PyTorch, designed to work with the LunarLander-v3 environment from Gymnasium. This implementation strictly adheres to PEP-8 standards, includes type hints for clarity, emphasizes performance and scalability, and incorporates robust error handling to ensure reliability.
Overview
The implementation is structured into several key components:
Policy Network (PolicyNetwork): A neural network representing the policy π(k), parameterized by θ(k).
Critic Network (CriticNetwork): A neural network approximating the Q-function Q(k).
DAPO Agent (DAPOAgent): Encapsulates the DAPO algorithm, handling policy updates, critic updates, and interactions with the environment.
Replay Buffer (ReplayBuffer): Stores experience tuples for off-policy training.
Main Function (main): Sets up the environment, initializes the DAPO agent, and orchestrates the training loop.
Each component is designed with maintainability and performance in mind, utilizing efficient data structures and leveraging PyTorch's capabilities for parallel computation. Comprehensive error handling ensures that unexpected issues are gracefully managed, providing meaningful feedback to developers.
Complete Implementation
python
import gymnasium as gym
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from typing import Any, Callable, Dict, Optional, Tuple, List
import numpy as np
import random
import collections
import math
import sys
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
# Type aliases for clarity
Tensor = torch.Tensor
State = np.ndarray
Action = int
Experience = Tuple[State, Action, float, State, bool]
class ReplayBuffer:
"""Replay Buffer for storing and sampling experiences."""
def __init__(self, capacity: int) -> None:
self.buffer: Deque[Experience] = collections.deque(maxlen=capacity)
def add(self, experience: Experience) -> None:
self.buffer.append(experience)
def sample(self, batch_size: int) -> List[Experience]:
if len(self.buffer) < batch_size:
raise ValueError("Not enough samples in buffer to sample.")
return random.sample(self.buffer, batch_size)
def __len__(self) -> int:
return len(self.buffer)
class PolicyNetwork(nn.Module):
"""Neural network representing the policy π."""
def __init__(self, state_dim: int, action_dim: int, hidden_dim: int = 128) -> None:
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.action_head = nn.Linear(hidden_dim, action_dim)
def forward(self, state: Tensor) -> Tensor:
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
action_logits = self.action_head(x)
return F.softmax(action_logits, dim=-1)
class CriticNetwork(nn.Module):
"""Neural network approximating the Q-function."""
def __init__(self, state_dim: int, action_dim: int, hidden_dim: int = 128) -> None:
super(CriticNetwork, self).__init__()
self.fc1 = nn.Linear(state_dim + action_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.q_head = nn.Linear(hidden_dim, 1)
def forward(self, state: Tensor, action: Tensor) -> Tensor:
x = torch.cat([state, action], dim=-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
q_value = self.q_head(x)
return q_value
class DAPOAgent:
"""Dual Approximation Policy Optimization Agent."""
def __init__(
self,
env: gym.Env,
buffer_capacity: int = 10000,
batch_size: int = 64,
gamma: float = 0.99,
lr_policy: float = 1e-3,
lr_critic: float = 1e-3,
eta_schedule: Callable[[int], float] = lambda k: 1.0 / math.sqrt(k + 1),
max_iterations: int = 1000
) -> None:
self.env = env
self.state_dim = env.observation_space.shape[0]
self.action_dim = env.action_space.n
self.policy_net = PolicyNetwork(self.state_dim, self.action_dim)
self.critic_net = CriticNetwork(self.state_dim, self.action_dim)
self.policy_optimizer = optim.Adam(self.policy_net.parameters(), lr=lr_policy)
self.critic_optimizer = optim.Adam(self.critic_net.parameters(), lr=lr_critic)
self.buffer = ReplayBuffer(capacity=buffer_capacity)
self.batch_size = batch_size
self.gamma = gamma
self.eta_schedule = eta_schedule
self.max_iterations = max_iterations
self.iteration = 0
# Set device
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.policy_net.to(self.device)
self.critic_net.to(self.device)
def select_action(self, state: State) -> Action:
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
action_probs = self.policy_net(state_tensor)
action = torch.multinomial(action_probs, num_samples=1).item()
return action
def store_experience(self, experience: Experience) -> None:
self.buffer.add(experience)
def critic_update(self, batch: List[Experience]) -> None:
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.FloatTensor(states).to(self.device)
actions = torch.LongTensor(actions).to(self.device).unsqueeze(1)
rewards = torch.FloatTensor(rewards).to(self.device).unsqueeze(1)
next_states = torch.FloatTensor(next_states).to(self.device)
dones = torch.FloatTensor(dones).to(self.device).unsqueeze(1)
# Current Q values
q_values = self.critic_net(states, F.one_hot(actions.squeeze(), num_classes=self.action_dim).float())
# Compute target Q values
with torch.no_grad():
next_action_probs = self.policy_net(next_states)
next_actions = torch.multinomial(next_action_probs, 1)
next_q_values = self.critic_net(next_states, F.one_hot(next_actions.squeeze(), num_classes=self.action_dim).float())
target_q_values = rewards + self.gamma * next_q_values * (1 - dones)
# Critic loss (Mean Squared Error)
critic_loss = F.mse_loss(q_values, target_q_values)
# Optimize critic
self.critic_optimizer.zero_grad()
critic_loss.backward()
self.critic_optimizer.step()
def policy_update(self, batch: List[Experience], eta: float) -> None:
states, actions, rewards, next_states, dones = zip(*batch)
states = torch.FloatTensor(states).to(self.device)
# Compute Q estimates
with torch.no_grad():
q_values = self.critic_net(states, F.one_hot(torch.LongTensor(actions), num_classes=self.action_dim).float())
# Policy loss using KL divergence as Bregman divergence
action_probs = self.policy_net(states)
log_probs = torch.log(action_probs + 1e-10)
policy_loss = (action_probs * (self.eta_schedule(self.iteration) * q_values - log_probs)).sum(dim=1).mean()
# Optimize policy
self.policy_optimizer.zero_grad()
policy_loss.backward()
self.policy_optimizer.step()
def train(self) -> None:
try:
for k in range(self.max_iterations):
self.iteration = k
state, _ = self.env.reset()
done = False
total_reward = 0
while not done:
action = self.select_action(state)
next_state, reward, done, truncated, _ = self.env.step(action)
self.store_experience((state, action, reward, next_state, done or truncated))
state = next_state
total_reward += reward
logging.info(f"Iteration {k}: Total Reward: {total_reward}")
if len(self.buffer) >= self.batch_size:
batch = self.buffer.sample(self.batch_size)
self.critic_update(batch)
eta = self.eta_schedule(k)
self.policy_update(batch, eta)
except KeyboardInterrupt:
logging.info("Training interrupted by user.")
except Exception as e:
logging.error(f"An error occurred during training: {e}")
def main() -> None:
"""Main function to train the DAPO agent."""
try:
env = gym.make("LunarLander-v3", render_mode="human")
except gym.error.Error as e:
logging.error(f"Failed to create environment: {e}")
return
agent = DAPOAgent(env=env, max_iterations=500)
agent.train()
env.close()
if __name__ == "__main__":
main()
Detailed Explanation
Imports and Configuration:
Packages: The implementation utilizes standard libraries (typing, math, logging, etc.) and essential external libraries (gymnasium, torch, numpy).
Logging: Configured to provide informative messages about the training progress and any potential errors.
Type Aliases:
Improves code readability by defining aliases like Tensor, State, Action, and Experience.
Replay Buffer:
Implements a fixed-size buffer using collections.deque to store experiences (state, action, reward, next_state, done).
Provides methods to add experiences and sample random batches for training.
Neural Networks:
PolicyNetwork: Outputs action probabilities using a softmax layer. It consists of two hidden layers with ReLU activations.
CriticNetwork: Estimates Q-values by taking concatenated state and one-hot encoded action vectors as input.
DAPOAgent:
Initialization:
Sets up policy and critic networks, optimizers, replay buffer, and relevant hyperparameters.
Determines the device (CPU or GPU) for computation.
Action Selection (select_action):
Given a state, computes action probabilities and samples an action accordingly.
Experience Storage (store_experience):
Adds experiences to the replay buffer.
Critic Update (critic_update):
Samples a batch from the replay buffer.
Computes current Q-values and target Q-values using the Bellman equation.
Calculates the Mean Squared Error (MSE) loss and updates the critic network.
Policy Update (policy_update):
Computes the policy loss based on the Kullback-Leibler (KL) divergence between the current policy and the updated policy influenced by the Q-values.
Error Handling and Robustness
Environment Creation: Catches and logs errors if the Gymnasium environment fails to initialize.
Replay Buffer Sampling: Raises a ValueError if there aren't enough samples to form a batch, preventing runtime errors.
Training Loop: Captures keyboard interruptions and unexpected exceptions, logging appropriate error messages without crashing the program.
Performance and Scalability
Neural Networks on GPU: Automatically utilizes GPU acceleration if available, enhancing computation speed, especially beneficial for large-scale training.
Efficient Sampling: Uses random.sample for experience replay, ensuring unbiased and diverse samples.
Optimized Data Structures: Leverages PyTorch tensors and vectorized operations for swift computations.
Maintainability and Readability
PEP-8 Compliance: Adheres to Python’s style guide, ensuring consistent indentation, naming conventions, and code structure.
Type Hints: Provides clear type annotations for functions and classes, aiding in code clarity and reducing potential bugs.
Modular Design: Separates concerns into distinct classes (ReplayBuffer, PolicyNetwork, CriticNetwork, DAPOAgent), facilitating easier updates and testing.
Dependencies
Ensure the following packages are installed in your Python environment:
bash
pip install gymnasium torch numpy
Execution
To run the DAPO agent, execute the script in a Python environment:
bash
python dapo_agent.py
This will start the training process, with the agent interacting with the LunarLander-v3 environment and logging progress to the console.