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"))
Mirror descent (MD) is a powerful optimization framework that extends and generalizes classical methods such as gradient descent by taking advantage of a dual representation of the problem. The key component of MD is the use of mirror maps, which map the optimization iterates back and forth between the primal space (where the problem is defined) and the dual space (where computations are performed). These maps are typically associated with convex functions of Legendre-type, leading to updates that incorporate curvature information about the domain and objective function. Let's break down the concepts introduced in the provided text:
Bregman Divergence and Bregman Projection
The Bregman divergence is a fundamental concept in mirror descent, and it generalizes the concept of squared Euclidean distance in a way that is more adapted to the geometry of the problem at hand, especially in non-Euclidean spaces.
Given a convex function (\Phi) of Legendre type, the Bregman divergence between two points (x) and (y) (where (x \in \text{dom}(\Phi)), and (y \in \text{int(dom}(\Phi)))) is defined as:
[
D_\Phi(x, y) = \Phi(x) - \Phi(y) - \langle \nabla \Phi(y), x - y \rangle.
]
This measures the difference between (\Phi(x)) and the first-order approximation of (\Phi(x)) around (y), capturing how different the structure of (x) and (y) is with respect to (\Phi)'s curvature.
The Bregman projection projects a point (y) onto a convex set (C) under the Bregman divergence induced by (\Phi):
[
\text{proj}{\Phi, C}(y) = \arg \min{x \in C} D_\Phi(x, y).
]
This operation is crucial in the mirror descent update step when we need to ensure iterates remain within a feasible region (C).
Mirror Descent Algorithm
Given a convex function (f) and a closed convex set (C), MD proceeds in two main steps at each iteration (k):
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Dual variable update:
[
\nabla \Phi(y^{(k+1)}) = \nabla \Phi(x^{(k)}) - \eta_k g^{(k)},
]
where (\eta_k) is the step size and ( g^{(k)} ) is the gradient (or sub-gradient) of (f) at (x^{(k)}).
In this process, (\Phi) is the mirror map, and (\Phi^) is its conjugate function, defined as:
[
\Phi^(x^) = \sup_{x \in \text{dom}(\Phi)} { \langle x, x^ \rangle - \Phi(x) },
]
which enables the primal-dual mapping structure. Additionally, if (\Phi) is differentiable, the relations (\nabla \Phi^*(\nabla \Phi(x)) = x) hold, facilitating practical implementations of the MD algorithm.
Using Bregman divergence, the MD update can be rewritten as:
[
x^{(k+1)} = \arg \min_{x \in C} \left{ \eta_k \langle g^{(k)}, x \rangle + D_\Phi(x, x^{(k)}) \right}.
]
This highlights the two parts of the update: minimizing the linearized form of the objective function (\langle g^{(k)}, x \rangle) and regularizing the move by penalizing large changes in terms of the Bregman divergence.
Examples of Mirror Descent
The text gives three specific examples of MD algorithms applied to the problem of minimizing a convex function (f(x)) over the simplex (\Delta).
Example 2.1: Squared L2-norm
Here, the mirror map (\Phi(x) = \frac{1}{2} |x|2^2) corresponds to standard Euclidean projection, leading to the projected gradient descent algorithm:
[
x^{(k+1)} = \arg \min{x \in \Delta} |x - (x^{(k)} - \eta_k \nabla f(x^{(k)}))|_2^2,
]
which projects the new point (x^{(k)} - \eta_k \nabla f(x^{(k)})) back onto the simplex (\Delta).
Example 2.2: Negative Entropy on ( \mathbb{R}_+^n )
Using the negative entropy function (\Phi(x) = \sum_i (x_i \log x_i - x_i)) as the mirror map leads to an exponentiated gradient update:
[
x^{(k+1)} = \frac{x^{(k)} \exp(-\eta_k g^{(k)})}{|x^{(k)} \exp(-\eta_k g^{(k)})|_1},
]
where the update is performed in the dual space using a multiplicative adjustment, followed by normalization to ensure the result remains on the simplex.
Example 2.3: Negative Entropy on the Simplex
This example refines Example 2.2 by restricting (\Phi(x)) to the simplex (\Delta). The resulting update is similar to Example 2.2:
[
x^{(k+1)} = \frac{x^{(k)} \exp(-\eta_k g^{(k)})}{|x^{(k)} \exp(-\eta_k g^{(k)})|_1},
]
but no projection step is necessary because the mirror map naturally keeps the iterates within the simplex.
Remarks and Differences Between Examples
Example 2.1 corresponds to standard Euclidean geometry and results in classical projected gradient descent.
Examples 2.2 and 2.3 both lead to the same exponentiated gradient update rule, though they differ in terms of the underlying structure. Example 2.2 uses the negative entropy on ( \mathbb{R}_+^n ), while Example 2.3 focuses on the simplex itself. In Example 2.3, the mirror map is not differentiable, and the standard convex optimization machinery cannot be directly applied since (\Phi) in this case lacks a fully invertible gradient.
Conclusion
Mirror descent generalizes traditional optimization approaches by leveraging problem-specific geometric information encoded in the mirror map (\Phi). This allows MD to adapt to different structures, such as probability distributions (simplex constraints) or non-Euclidean geometries, making it a flexible and powerful tool for various optimization problems. The specific examples discussed here—squared L2-norm and negative entropy—illustrate different ways MD can be tailored to problems that involve constraints like non-negativity or membership in the simplex.
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 Q^(k) that approximates Q(k).
Policy Update:
Find θ(k+1) by (approximately) solving:
θ∈ΘminEs∼ν(k)[D
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 an end-to-end implementation of the Dual Approximation Policy Optimization (DAPO) algorithm using PyTorch, applied to the LunarLander-v3 environment from gymnasium. The code adheres strictly to the PEP-8 standards, includes comprehensive type hints, optimized for efficiency, and features robust error handling to ensure maintainability and scalability.
Overview
Environment Initialization: Sets up the LunarLander-v3 environment with rendering enabled.
Neural Network Architectures:
Policy Network: Determines the action probabilities.
Critic Network: Estimates the Q-values.
Function Approximator: Approximates the dual update.
DAPO-KL Algorithm Implementation:
Critic Update: Trains the critic network to approximate Q-values.
Policy Update: Updates the policy network using mirror descent with KL divergence as the Bregman divergence.
Training Loop: Orchestrates the interaction between the agent and the environment, performing updates iteratively.
Error Handling: Ensures graceful handling of unexpected issues during training.
Dependencies
Before running the code, ensure you have the following packages installed:
bash
pip install torch gymnasium[box2d] numpy
Implementation
python
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Categorical
from typing import Optional, Tuple
import logging
import sys
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
class PolicyNetwork(nn.Module):
"""
Policy Network to parameterize the policy π_θ.
"""
def __init__(self, state_dim: int, action_dim: int, hidden_dim: Tuple[int, ...] = (128, 128)) -> None:
super(PolicyNetwork, self).__init__()
layers = []
input_dim = state_dim
for hidden in hidden_dim:
layers.append(nn.Linear(input_dim, hidden))
layers.append(nn.ReLU())
input_dim = hidden
layers.append(nn.Linear(input_dim, action_dim))
self.network = nn.Sequential(*layers)
def forward(self, state: torch.Tensor) -> torch.Tensor:
logits = self.network(state)
action_probs = F.softmax(logits, dim=-1)
return action_probs
class CriticNetwork(nn.Module):
"""
Critic Network to approximate the Q-values Q(s, a).
"""
def __init__(self, state_dim: int, action_dim: int, hidden_dim: Tuple[int, ...] = (128, 128)) -> None:
super(CriticNetwork, self).__init__()
layers = []
input_dim = state_dim + action_dim
for hidden in hidden_dim:
layers.append(nn.Linear(input_dim, hidden))
layers.append(nn.ReLU())
input_dim = hidden
layers.append(nn.Linear(input_dim, 1))
self.network = nn.Sequential(*layers)
def forward(self, state: torch.Tensor, action: torch.Tensor) -> torch.Tensor:
x = torch.cat([state, action], dim=-1)
q_value = self.network(x)
return q_value
class FunctionApproximator(nn.Module):
"""
Function Approximator for dual updates f_θ(s).
"""
def __init__(self, state_dim: int, hidden_dim: Tuple[int, ...] = (128, 128)) -> None:
super(FunctionApproximator, self).__init__()
layers = []
input_dim = state_dim
for hidden in hidden_dim:
layers.append(nn.Linear(input_dim, hidden))
layers.append(nn.ReLU())
input_dim = hidden
layers.append(nn.Linear(input_dim, 1))
self.network = nn.Sequential(*layers)
def forward(self, state: torch.Tensor) -> torch.Tensor:
return self.network(state)
class ReplayBuffer:
"""
Replay Buffer for storing and sampling experiences.
"""
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.buffer = []
self.position = 0
def push(self, state: np.ndarray, action: int, reward: float,
next_state: np.ndarray, done: bool) -> None:
if len(self.buffer) < self.capacity:
self.buffer.append(None)
self.buffer[self.position] = (state, action, reward, next_state, done)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size: int) -> Tuple:
batch = np.random.choice(len(self.buffer), batch_size, replace=False)
states, actions, rewards, next_states, dones = zip(*(self.buffer[idx] for idx in batch))
return (np.array(states), np.array(actions),
np.array(rewards), np.array(next_states), np.array(dones))
def __len__(self) -> int:
return len(self.buffer)
class DAPOAgent:
"""
Dual Approximation Policy Optimization (DAPO) Agent.
"""
def __init__(self,
state_dim: int,
action_dim: int,
env: gym.Env,
gamma: float = 0.99,
lr_policy: float = 1e-3,
lr_critic: float = 1e-3,
lr_approximator: float = 1e-3,
buffer_capacity: int = 100000,
batch_size: int = 64,
eta: float = 0.1,
mirror_map: str = 'kl') -> None:
self.state_dim = state_dim
self.action_dim = action_dim
self.env = env
self.gamma = gamma
self.batch_size = batch_size
self.eta = eta
self.mirror_map = mirror_map
# Initialize networks
self.policy_net = PolicyNetwork(state_dim, action_dim)
self.critic_net = CriticNetwork(state_dim, action_dim)
self.approximator = FunctionApproximator(state_dim)
# Initialize optimizers
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.approximator_optimizer = optim.Adam(self.approximator.parameters(), lr=lr_approximator)
# Initialize replay buffer
self.replay_buffer = ReplayBuffer(capacity=buffer_capacity)
# Initialize 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)
self.approximator.to(self.device)
def select_action(self, state: np.ndarray) -> int:
"""
Select an action based on the current policy.
"""
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
action_probs = self.policy_net(state_tensor)
dist = Categorical(action_probs)
action = dist.sample().item()
return action
def update_critic(self, states: torch.Tensor, actions: torch.Tensor,
rewards: torch.Tensor, next_states: torch.Tensor,
dones: torch.Tensor) -> None:
"""
Update the critic network by minimizing the MSE loss.
"""
try:
actions_one_hot = F.one_hot(actions, num_classes=self.action_dim).float()
q_values = self.critic_net(states, actions_one_hot).squeeze(-1)
with torch.no_grad():
next_action_probs = self.policy_net(next_states)
next_actions = Categorical(next_action_probs).sample()
next_actions_one_hot = F.one_hot(next_actions, num_classes=self.action_dim).float()
target_q = rewards + self.gamma * self.critic_net(next_states, next_actions_one_hot).squeeze(-1) * (1 - dones)
loss = F.mse_loss(q_values, target_q)
self.critic_optimizer.zero_grad()
loss.backward()
self.critic_optimizer.step()
logger.debug(f"Critic Loss: {loss.item()}")
except Exception as e:
logger.error(f"Error in critic update: {e}")
def update_approximator(self, states: torch.Tensor,
dual_targets: torch.Tensor) -> None:
"""
Update the function approximator f_θ(s).
"""
try:
predictions = self.approximator(states).squeeze(-1)
loss = F.mse_loss(predictions, dual_targets)
self.approximator_optimizer.zero_grad()
loss.backward()
self.approximator_optimizer.step()
logger.debug(f"Approximator Loss: {loss.item()}")
except Exception as e:
logger.error(f"Error in approximator update: {e}")
def policy_update(self, states: torch.Tensor, q_values: torch.Tensor) -> None:
"""
Update the policy network using Mirror Descent with KL divergence.
"""
try:
# Compute dual variable
f_theta = self.approximator(states).squeeze(-1)
dual_variable = torch.clamp(torch.log_softmax(f_theta, dim=-1), min=-20, max=20)
# Compute mirror descent update
action_probs = self.policy_net(states)
loss = torch.sum(action_probs * (q_values.detach() * self.eta)) + F.kl_div(action_probs.log(), dual_variable, reduction='batchmean')
self.policy_optimizer.zero_grad()
loss.backward()
self.policy_optimizer.step()
logger.debug(f"Policy Loss: {loss.item()}")
except Exception as e:
logger.error(f"Error in policy update: {e}")
def train(self, num_episodes: int = 1000, max_steps: int = 1000) -> None:
"""
Train the DAPO agent.
"""
try:
for episode in range(1, num_episodes + 1):
state, _ = self.env.reset()
episode_reward = 0
for step in range(max_steps):
action = self.select_action(state)
next_state, reward, done, _, _ = self.env.step(action)
self.replay_buffer.push(state, action, reward, next_state, done)
state = next_state
episode_reward += reward
if len(self.replay_buffer) < self.batch_size:
continue
# Sample a batch
batch = self.replay_buffer.sample(self.batch_size)
states, actions, rewards, next_states, dones = batch
states = torch.FloatTensor(states).to(self.device)
actions = torch.LongTensor(actions).to(self.device)
rewards = torch.FloatTensor(rewards).to(self.device)
next_states = torch.FloatTensor(next_states).to(self.device)
dones = torch.FloatTensor(dones).to(self.device)
# Update Critic
self.update_critic(states, actions, rewards, next_states, dones)
# Update Approximator
q_vals = self.critic_net(states, F.one_hot(actions, num_classes=self.action_dim).float()).squeeze(-1)
dual_targets = self.nabla_phi_star(q_vals)
self.update_approximator(states, dual_targets)
# Update Policy
self.policy_update(states, q_vals)
if done:
break
logger.info(f"Episode {episode} Reward: {episode_reward}")
if episode % 50 == 0:
self.evaluate(num_episodes=5)
except KeyboardInterrupt:
logger.info("Training interrupted by user.")
except Exception as e:
logger.error(f"Error during training: {e}")
def nabla_phi_star(self, q_values: torch.Tensor) -> torch.Tensor:
"""
Compute the gradient of the conjugate mirror map Φ*.
For KL divergence, Φ(x) = �sum_i x_i log x_i - x_i,
so Φ*(y) = exp(y).
Hence, ∇Φ*(y) = exp(y).
"""
try:
return torch.exp(q_values)
except Exception as e:
logger.error(f"Error in nabla_phi_star: {e}")
return torch.zeros_like(q_values)
def evaluate(self, num_episodes: int = 5) -> None:
"""
Evaluate the current policy without exploration.
"""
try:
total_reward = 0.0
for _ in range(num_episodes):
state, _ = self.env.reset()
done = False
while not done:
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad():
action_probs = self.policy_net(state_tensor)
action = torch.argmax(action_probs, dim=-1).item()
state, reward, done, _, _ = self.env.step(action)
total_reward += reward
average_reward = total_reward / num_episodes
logger.info(f"Evaluation over {num_episodes} episodes: Average Reward: {average_reward}")
except Exception as e:
logger.error(f"Error during evaluation: {e}")
def main() -> None:
"""
Main function to initialize environment and start training.
"""
try:
env_name = "LunarLander-v3"
env = gym.make(env_name, render_mode="human")
state_dim = env.observation_space.shape[0]
action_dim = env.action_space.n
agent = DAPOAgent(
state_dim=state_dim,
action_dim=action_dim,
env=env,
gamma=0.99,
lr_policy=1e-3,
lr_critic=1e-3,
lr_approximator=1e-3,
buffer_capacity=100000,
batch_size=64,
eta=0.1,
mirror_map='kl' # Using KL divergence as Bregman divergence
)
agent.train(num_episodes=1000, max_steps=1000)
except Exception as e:
logger.error(f"Error in main: {e}")
finally:
env.close()
logger.info("Environment closed.")
if __name__ == "__main__":
main()
Explanation of Key Components
Logging Configuration:
Utilizes Python's built-in logging module to provide informative messages during training and debugging.
Logs are output to the console with timestamps and log levels.
Neural Networks:
PolicyNetwork: Determines action probabilities using a softmax layer.
CriticNetwork: Estimates Q-values for state-action pairs.
FunctionApproximator: Approximates the dual update function ( f_{\theta}(s) ).
ReplayBuffer:
Implements a simple experience replay mechanism to store and sample experiences, which helps in breaking correlations between sequential data and improves learning stability.
DAPOAgent:
Manages the policy and critic updates, incorporating mirror descent with KL divergence.
select_action: Chooses actions based on the current policy without exploration noise for simplicity.
update_critic: Trains the critic network using mean squared error loss between predicted Q-values and target Q-values.
update_approximator: Trains the function approximator to predict dual variables based on the current state.
policy_update: Updates the policy network by minimizing a combination of expected Q-values and KL divergence, ensuring updates stay within a trust region.
nabla_phi_star: Computes the gradient of the conjugate mirror map (Φ*) for the KL divergence, which is exp(y) in this case.
train: The main training loop that interacts with the environment, updates networks, and logs progress.
evaluate: Periodically evaluates the policy over several episodes to monitor performance.
Error Handling:
Each update method (update_critic, update_approximator, policy_update) includes try-except blocks to catch and log errors without crashing the training process.
The train and main functions also handle exceptions to ensure graceful termination and resource cleanup.
Main Function:
Initializes the environment and DAPOAgent.
Notes
Mirror Map (Φ): In this implementation, the KL divergence is used as the Bregman divergence. The mirror map Φ corresponds to the negative entropy function, making the dual map Φ* the exponential function.
Training Parameters: The learning rates, gamma, eta, and other hyperparameters are set to typical values but can be tuned based on performance.
Device Configuration: The code automatically utilizes GPU acceleration if available, falling back to CPU otherwise.
Rendering: The environment is set to render_mode="human", which will display the environment's graphical interface during training. This can be resource-intensive; consider setting it to None for faster training without visualization.
Scalability: The use of batch processing and efficient neural network architectures ensures that the agent can scale to more complex environments and larger datasets.
Extensibility: The modular design allows for easy extension or modification of components, such as experimenting with different mirror maps or network architectures.
Conclusion
This implementation provides a robust and maintainable foundation for experimenting with the Dual Approximation Policy Optimization algorithm in reinforcement learning settings. By adhering to best coding practices and ensuring comprehensive error handling, it facilitates both development and debugging, promoting scalability and efficiency.