Certainly! Using multiple parallel environments can significantly speed up training and provide more diverse experiences for your PPO agent. Below, I'll guide you through modifying your existing PPO implementation to employ 8 vectorized environments using Gym's vectorization utilities. This approach allows the agent to interact with multiple instances of the environment simultaneously, enhancing learning efficiency.
Overview of Steps
- Create Multiple Environments with Vectorization
- Adjust the Agent and Memory Classes for Vectorized Data
- Modify the Training Loop to Handle Multiple Environments
- Ensure Proper Handling of Observations and Actions
Let's dive into each step in detail.
1. Create Multiple Environments with Vectorization
Gym provides powerful utilities to create multiple environments that can run in parallel. We'll use gym.vector.SyncVectorEnv to create 8 synchronized environments. Each environment will be wrapped with your existing wrappers to ensure consistency.
a. Define an Environment Creation Function
First, create a function that initializes a single environment with all the necessary wrappers:
import gym
from gym.vector import SyncVectorEnv
def create_env(env_id, max_episode_steps=None, render=None):
def _init():
env = make_atari(env_id, max_episode_steps=max_episode_steps, render=render)
env = wrap_deepmind(env,
episode_life=True,
clip_rewards=True,
frame_stack=True,
scale=True)
return env
return _init
b. Initialize the Vectorized Environment
Now, create 8 instances of the Pong environment using the SyncVectorEnv wrapper:
num_envs = 8
env_id = "PongNoFrameskip-v4"
# Create a list of 8 environment creation functions
env_fns = [create_env(env_id, max_episode_steps=100000, render=None) for _ in range(num_envs)]
# Initialize the vectorized environment
vector_env = SyncVectorEnv(env_fns)
# Reset the environments to get initial observations
observations, info = vector_env.reset()
# Transpose observations to match your network's expected input (C, H, W)
observations = np.transpose(observations, [0, 3, 1, 2]) # Shape: (num_envs, C, H, W)
2. Adjust the Agent and Memory Classes for Vectorized Data
Your existing Agent and PPOMemory classes are designed for single environments. We'll need to modify them to handle batched data from multiple environments.
a. Modify the PPOMemory Class
Ensure that PPOMemory can store experiences from all environments:
class PPOMemory:
def __init__(self, batch_size):
self.states = []
self.probs = []
self.vals = []
self.actions = []
self.rewards = []
self.dones = []
self.batch_size = batch_size
def generate_batches(self):
n_states = len(self.states)
indices = np.arange(n_states, dtype=np.int64)
np.random.shuffle(indices)
batches = [indices[i:i + self.batch_size] for i in range(0, n_states, self.batch_size)]
return (np.array(self.states),
np.array(self.actions),
np.array(self.probs),
np.array(self.vals),
np.array(self.rewards),
np.array(self.dones),
batches)
def store_memory(self, state, action, probs, vals, reward, done):
self.states.append(state)
self.actions.append(action)
self.probs.append(probs)
self.vals.append(vals)
self.rewards.append(reward)
self.dones.append(done)
def clear_memory(self):
self.states = []
self.probs = []
self.actions = []
self.rewards = []
self.dones = []
self.vals = []
b. Update the Agent Class
Modify the Agent to handle batched observations and actions:
import torch as T
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np
class Agent:
def __init__(self, n_actions, input_dims, gamma=0.99, alpha=0.0003, gae_lambda=0.95,
policy_clip=0.2, batch_size=64, n_epochs=10, num_envs=8):
self.gamma = gamma
self.policy_clip = policy_clip
self.n_epochs = n_epochs
self.gae_lambda = gae_lambda
self.num_envs = num_envs
self.actor = ActorConvNetwork(n_actions, input_dims, alpha)
self.critic = CriticConvNetwork(input_dims, alpha)
self.memory = PPOMemory(batch_size)
def choose_action(self, observations):
state = T.tensor(observations, dtype=T.float).to(self.actor.device)
dist = self.actor(state)
value = self.critic(state)
actions = dist.sample()
probs = T.squeeze(dist.log_prob(actions)).cpu().detach().numpy()
actions = T.squeeze(actions).cpu().detach().numpy()
values = T.squeeze(value).cpu().detach().numpy()
return actions, probs, values
def remember(self, states, actions, probs, vals, rewards, dones):
# Store experiences from all environments
for i in range(self.num_envs):
self.memory.store_memory(states[i], actions[i], probs[i], vals[i], rewards[i], dones[i])
def learn(self):
if len(self.memory.states) < self.memory.batch_size:
return # Not enough samples to learn
for _ in range(self.n_epochs):
state_arr, action_arr, old_prob_arr, vals_arr, \
reward_arr, dones_arr, batches = self.memory.generate_batches()
# Compute advantages and returns using GAE
values = np.append(vals_arr, 0) # Append 0 for the last value
advantages = np.zeros_like(reward_arr)
gae = 0
for t in reversed(range(len(reward_arr))):
delta = reward_arr[t] + self.gamma * values[t + 1] * (1 - dones_arr[t]) - values[t]
gae = delta + self.gamma * self.gae_lambda * (1 - dones_arr[t]) * gae
advantages[t] = gae
returns = advantages + vals_arr
advantages = np.array(advantages)
returns = np.array(returns)
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
advantages = T.tensor(advantages, dtype=T.float).to(self.actor.device)
returns = T.tensor(returns, dtype=T.float).to(self.actor.device)
values = T.tensor(vals_arr, dtype=T.float).to(self.actor.device)
for batch in batches:
states = T.tensor(state_arr[batch], dtype=T.float).to(self.actor.device)
old_probs = T.tensor(old_prob_arr[batch], dtype=T.float).to(self.actor.device)
actions = T.tensor(action_arr[batch], dtype=T.long).to(self.actor.device)
adv = advantages[batch]
ret = returns[batch]
dist = self.actor(states)
critic_value = self.critic(states).squeeze()
new_probs = dist.log_prob(actions)
prob_ratio = (new_probs - old_probs).exp()
weighted_probs = adv * prob_ratio
weighted_clipped_probs = T.clamp(prob_ratio, 1 - self.policy_clip, 1 + self.policy_clip) * adv
actor_loss = -T.min(weighted_probs, weighted_clipped_probs).mean()
critic_loss = (ret - critic_value).pow(2).mean()
total_loss = actor_loss + 0.5 * critic_loss
self.actor.optimizer.zero_grad()
self.critic.optimizer.zero_grad()
total_loss.backward()
self.actor.optimizer.step()
self.critic.optimizer.step()
self.memory.clear_memory()
def save_models(self):
print('... saving models ...')
self.actor.save_checkpoint()
self.critic.save_checkpoint()
def load_models(self):
print('... loading models ...')
self.actor.load_checkpoint()
self.critic.load_checkpoint()
Notes:
- Advantage Calculation: The
learn method computes Generalized Advantage Estimation (GAE) for policy updates. It iterates backward through rewards to calculate advantages.
- Normalization: Advantages are normalized to have zero mean and unit variance, which can stabilize training.
- Batch Processing: The agent processes batches of experiences, aligning with PPO's training regime.
3. Modify the Training Loop to Handle Multiple Environments
Adjust your training loop to interact with all 8 environments simultaneously. This involves handling batched observations, actions, rewards, and done flags.
import numpy as np
import time
# Initialize the agent
agent = Agent(n_actions=vector_env.single_action_space.n,
input_dims=[4, 84, 84],
num_envs=num_envs)
num_episodes = 10000 # Total episodes to train
max_steps = 500000 # Max steps per episode
update_freq = 2048 # Number of steps before updating the policy
log_interval = 10 # Episodes between logging
episode_rewards = np.zeros(num_envs, dtype=float)
episode_lengths = np.zeros(num_envs, dtype=int)
total_steps = 0
episode_count = 0
start_time = time.time()
while episode_count < num_episodes:
observations, info = vector_env.reset()
observations = np.transpose(observations, [0, 3, 1, 2]) # Shape: (num_envs, C, H, W)
episode_rewards_env = np.zeros(num_envs, dtype=float)
episode_lengths_env = np.zeros(num_envs, dtype=int)
for step in range(max_steps):
actions, probs, vals = agent.choose_action(observations)
observations_, rewards, truncated, terminated, info = vector_env.step(actions)
observations_ = np.transpose(observations_, [0, 3, 1, 2])
done = np.logical_or(terminated, truncated)
agent.remember(observations, actions, probs, vals, rewards, done)
episode_rewards_env += rewards
episode_lengths_env += 1
total_steps += num_envs
# Update the agent every `update_freq` steps
if total_steps % update_freq == 0:
agent.learn()
# Logging
for i in range(num_envs):
if done[i]:
episode_rewards[i] += episode_rewards_env[i]
episode_lengths[i] += episode_lengths_env[i]
print(f"Episode: {episode_count + 1} | "
f"Reward: {episode_rewards_env[i]} | "
f"Length: {episode_lengths_env[i]}")
episode_count += 1
episode_rewards_env[i] = 0
episode_lengths_env[i] = 0
if episode_count >= num_episodes:
break
if episode_count >= num_episodes:
break
observations = observations_
# Save models periodically
if episode_count % 500 == 0 and episode_count > 0:
agent.save_models()
end_time = time.time()
print(f"Training completed in {end_time - start_time} seconds.")
vector_env.close()
Key Points:
-
Observation Transposition: Ensure that the observation dimensions match what your neural networks expect (channels first for ConvNets).
-
Agent Updates: The agent learns every update_freq steps, aggregating experiences from all environments.
-
Episode Tracking: Track rewards and lengths for each environment individually and log them upon episode termination.
-
Saving Models: Periodically save the model checkpoints to preserve training progress.
4. Ensure Proper Handling of Observations and Actions
Ensure that your ActorConvNetwork and CriticConvNetwork are compatible with batched inputs from multiple environments.
Example ActorConvNetwork:
import torch.nn as nn
import torch.optim as optim
import os
class ActorConvNetwork(nn.Module):
def __init__(self, n_actions, input_dims, alpha, fc1_dims=256, fc2_dims=256, chkpt_dir='tmp/ppo'):
super(ActorConvNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'actor_torch_ppo')
self.actor = nn.Sequential(
nn.Conv2d(input_dims[0], 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, stride=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(7 * 7 * 64, 512),
nn.ReLU(),
nn.Linear(512, n_actions),
nn.Softmax(dim=-1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
dist = self.actor(state)
return Categorical(dist)
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
Example CriticConvNetwork:
class CriticConvNetwork(nn.Module):
def __init__(self, input_dims, alpha, fc1_dims=256, fc2_dims=256, chkpt_dir='tmp/ppo'):
super(CriticConvNetwork, self).__init__()
self.checkpoint_file = os.path.join(chkpt_dir, 'critic_torch_ppo')
self.critic = nn.Sequential(
nn.Conv2d(input_dims[0], 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, stride=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(7 * 7 * 64, 512),
nn.ReLU(),
nn.Linear(512, 1)
)
self.optimizer = optim.Adam(self.parameters(), lr=alpha)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
value = self.critic(state)
return value
def save_checkpoint(self):
T.save(self.state_dict(), self.checkpoint_file)
def load_checkpoint(self):
self.load_state_dict(T.load(self.checkpoint_file))
Notes:
-
Input Dimensions: Ensure that the first dimension of your Conv2D layers matches the number of stacked frames (e.g., 4 for frame stacking).
-
Device Compatibility: Both networks are moved to the appropriate device (cpu or cuda).
Final Considerations
-
Batch Size and Memory: With 8 environments running in parallel, your effective batch size increases. Ensure that your memory buffers and model can handle the increased data volume.
-
Hyperparameter Tuning: You might need to adjust hyperparameters like learning rate, update frequency, and GAE lambda to accommodate the dynamics introduced by multiple environments.
-
Logging and Monitoring: When working with multiple environments, maintain clear logging to track performance across different instances. This helps in diagnosing issues and understanding agent behavior.
-
Resource Management: Running multiple environments, especially with rendering enabled, can be resource-intensive. Ensure your hardware can handle the increased computational load.
-
Alternative Libraries: While implementing parallel environments manually provides flexibility, consider using libraries like Stable Baselines3 which offer robust PPO implementations with built-in support for vectorized environments.
Complete Example Code Integration
Here's how the full integration might look with all the changes:
import gym
from gym.vector import SyncVectorEnv
import numpy as np
import torch as T
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
from collections import deque
import time
import os
# [Include all your existing wrappers: TimeLimit, NoopResetEnv, FireResetEnv, EpisodicLifeEnv, MaxAndSkipEnv, ClipRewardEnv, WarpFrame, FrameStack, ScaledFloatFrame, LazyFrames]
# [Include make_atari and wrap_deepmind functions]
def create_env(env_id, max_episode_steps=None, render=None):
def _init():
env = make_atari(env_id, max_episode_steps=max_episode_steps, render=render)
env = wrap_deepmind(env,
episode_life=True,
clip_rewards=True,
frame_stack=True,
scale=True)
return env
return _init
# Initialize 8 parallel environments
num_envs = 8
env_id = "PongNoFrameskip-v4"
env_fns = [create_env(env_id, max_episode_steps=100000, render=None) for _ in range(num_envs)]
vector_env = SyncVectorEnv(env_fns)
# [Include ActorConvNetwork and CriticConvNetwork classes]
# [Include Agent and PPOMemory classes]
# Initialize the agent
agent = Agent(n_actions=vector_env.single_action_space.n,
input_dims=[4, 84, 84],
num_envs=num_envs)
num_episodes = 10000
max_steps = 500000
update_freq = 2048
log_interval = 10
episode_rewards = []
total_steps = 0
episode_count = 0
start_time = time.time()
while episode_count < num_episodes:
observations, info = vector_env.reset()
observations = np.transpose(observations, [0, 3, 1, 2])
episode_rewards_env = np.zeros(num_envs, dtype=float)
episode_lengths_env = np.zeros(num_envs, dtype=int)
for step in range(max_steps):
actions, probs, vals = agent.choose_action(observations)
observations_, rewards, truncated, terminated, info = vector_env.step(actions)
observations_ = np.transpose(observations_, [0, 3, 1, 2])
done = np.logical_or(terminated, truncated)
agent.remember(observations, actions, probs, vals, rewards, done)
episode_rewards_env += rewards
episode_lengths_env += 1
total_steps += num_envs
if total_steps % update_freq == 0:
agent.learn()
for i in range(num_envs):
if done[i]:
episode_rewards.append(episode_rewards_env[i])
print(f"Episode: {episode_count + 1} | "
f"Reward: {episode_rewards_env[i]} | "
f"Length: {episode_lengths_env[i]}")
episode_count += 1
episode_rewards_env[i] = 0
episode_lengths_env[i] = 0
if episode_count >= num_episodes:
break
if episode_count >= num_episodes:
break
observations = observations_
if episode_count % 500 == 0 and episode_count > 0:
agent.save_models()
end_time = time.time()
print(f"Training completed in {end_time - start_time} seconds.")
vector_env.close()
Conclusion
By following the above steps, you can effectively employ 8 parallel environments in your PPO implementation for Atari Pong. This setup leverages parallelism to collect more diverse experiences, potentially leading to faster and more stable learning. Always monitor training closely to ensure that the agent is learning as expected and adjust hyperparameters as needed to optimize performance.
Feel free to ask if you have any further questions or need additional assistance!