Certainly! Implementing Proximal Policy Optimization (PPO) to train an agent on the Pong environment with parallel environments is a great way to improve sample efficiency and training speed. Below, I'll provide a step-by-step guide along with code snippets to create such an implementation without using Stable Baselines.
We'll use:
- OpenAI Gym: For the Pong environment.
- NumPy and PyTorch: For numerical computations and neural networks.
- Multiprocessing: To run multiple environments in parallel.
Note: Ensure you have the necessary packages installed:
pip install gymnasium torch
Overview
- Create Multiple Environments: Use multiprocessing to run several instances of the Pong environment in parallel.
- Define the PPO Agent: Implement the actor-critic neural network architecture.
- Collect Experience: Gather batches of data from all parallel environments.
- Compute Advantages: Calculate the advantage estimates for the collected experiences.
- Perform PPO Update: Update the policy and value networks using the PPO objective.
Implementation
1. Import Necessary Libraries
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
from multiprocessing import Process, Pipe
2. Parallel Environment Setup
We create worker processes that run the environments independently and communicate with the main process via pipes.
Worker Function:
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
while True:
cmd, data = remote.recv()
if cmd == 'step':
ob, rew, done, info = env.step(data)
if done:
ob = env.reset()
remote.send((ob, rew, done, info))
elif cmd == 'reset':
ob = env.reset()
remote.send(ob)
elif cmd == 'close':
remote.close()
break
else:
raise NotImplementedError
Environment Wrapper:
class CloudpickleWrapper(object):
def __init__(self, x):
self.x = x
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x)
def __setstate__(self, ob):
import pickle
self.x = pickle.loads(ob)
SubprocVecEnv Class:
class SubprocVecEnv(object):
def __init__(self, env_fns):
self.waiting = False
self.closed = False
n_envs = len(env_fns)
self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(n_envs)])
self.ps = [Process(target=worker, args=(work_remote, remote, CloudpickleWrapper(env_fn)))
for (work_remote, remote, env_fn) in zip(self.work_remotes, self.remotes, env_fns)]
for p in self.ps:
p.start()
for remote in self.work_remotes:
remote.close()
def step_async(self, actions):
for remote, action in zip(self.remotes, actions):
remote.send(('step', action))
self.waiting = True
def step_wait(self):
results = [remote.recv() for remote in self.remotes]
self.waiting = False
obs, rews, dones, infos = zip(*results)
return np.stack(obs), np.array(rews), np.array(dones), infos
def reset(self):
for remote in self.remotes:
remote.send(('reset', None))
return np.stack([remote.recv() for remote in self.remotes])
def close(self):
if self.closed:
return
if self.waiting:
for remote in self.remotes:
remote.recv()
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
self.closed = True
Create the Vectorized Environments:
def make_env():
def _thunk():
env = gym.make('PongNoFrameskip-v4')
env = gym.wrappers.AtariPreprocessing(env, grayscale_obs=True, frame_skip=4, scale_obs=True)
env = gym.wrappers.FrameStack(env, 4)
return env
return _thunk
num_envs = 8
envs = SubprocVecEnv([make_env() for _ in range(num_envs)])
3. Define the PPO Agent
Actor-Critic Network:
class ActorCritic(nn.Module):
def __init__(self, in_channels, num_actions):
super(ActorCritic, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels, 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()
)
self.fc = nn.Linear(64 * 7 * 7, 512)
self.pi = nn.Linear(512, num_actions)
self.v = nn.Linear(512, 1)
def forward(self, x):
x = x / 255.0 # Normalize pixel values
x = self.conv(x)
x = x.view(x.size(0), -1)
x = torch.relu(self.fc(x))
logits = self.pi(x)
values = self.v(x)
return logits, values
4. Collect Experience
We collect experiences in batches from all parallel environments.
def collect_trajectories(envs, model, batch_size, gamma, device):
obs = envs.reset()
obs = np.asarray(obs)
observations = []
actions = []
rewards = []
dones = []
log_probs = []
values = []
for _ in range(batch_size):
obs_tensor = torch.tensor(obs, dtype=torch.float32).to(device)
logits, value = model(obs_tensor)
m = Categorical(logits=logits)
action = m.sample()
obs_next, reward, done, info = envs.step(action.cpu().numpy())
observations.append(obs)
actions.append(action.cpu().numpy())
rewards.append(reward)
dones.append(done)
log_probs.append(m.log_prob(action).detach().cpu().numpy())
values.append(value.detach().cpu().numpy())
obs = obs_next
return {
'observations': np.array(observations),
'actions': np.array(actions),
'rewards': np.array(rewards),
'dones': np.array(dones),
'log_probs': np.array(log_probs),
'values': np.array(values)
}
5. Compute Advantages
We calculate the Generalized Advantage Estimate (GAE) for more stable training.
def compute_gae(rewards, values, dones, gamma=0.99, lam=0.95):
advantages = np.zeros_like(rewards)
last_adv = 0
for t in reversed(range(len(rewards))):
mask = 1.0 - dones[t]
delta = rewards[t] + gamma * values[t + 1] * mask - values[t]
advantages[t] = last_adv = delta + gamma * lam * mask * last_adv
returns = advantages + values[:-1]
return advantages, returns
6. PPO Update Function
def ppo_update(model, optimizer, batch, epsilon=0.2, epochs=4, mini_batch_size=64, device='cpu'):
observations = torch.tensor(batch['observations'], dtype=torch.float32).to(device)
actions = torch.tensor(batch['actions'], dtype=torch.int64).to(device)
old_log_probs = torch.tensor(batch['log_probs'], dtype=torch.float32).to(device)
advantages = torch.tensor(batch['advantages'], dtype=torch.float32).to(device)
returns = torch.tensor(batch['returns'], dtype=torch.float32).to(device)
dataset = torch.utils.data.TensorDataset(observations, actions, old_log_probs, advantages, returns)
loader = torch.utils.data.DataLoader(dataset, batch_size=mini_batch_size, shuffle=True)
for _ in range(epochs):
for obs_batch, action_batch, old_log_prob_batch, adv_batch, return_batch in loader:
logits, values = model(obs_batch)
m = Categorical(logits=logits)
entropy = m.entropy().mean()
new_log_probs = m.log_prob(action_batch)
ratio = torch.exp(new_log_probs - old_log_prob_batch)
surr1 = ratio * adv_batch
surr2 = torch.clamp(ratio, 1.0 - epsilon, 1.0 + epsilon) * adv_batch
actor_loss = -torch.min(surr1, surr2).mean()
critic_loss = (return_batch - values.squeeze(-1)).pow(2).mean()
loss = actor_loss + 0.5 * critic_loss - 0.01 * entropy
optimizer.zero_grad()
loss.backward()
optimizer.step()
7. Training Loop
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ActorCritic(in_channels=4, num_actions=envs.remotes[0].recv().action_space.n).to(device)
optimizer = optim.Adam(model.parameters(), lr=2.5e-4)
num_steps = 128
num_updates = 1000
gamma = 0.99
lam = 0.95
for update in range(num_updates):
batch = collect_trajectories(envs, model, num_steps, gamma, device)
next_value = model(torch.tensor(batch['observations'][-1], dtype=torch.float32).to(device))[1].detach().cpu().numpy()
batch['values'] = np.append(batch['values'], next_value[None, :], axis=0)
advantages, returns = compute_gae(batch['rewards'], batch['values'], batch['dones'], gamma, lam)
batch['advantages'] = advantages.flatten()
batch['returns'] = returns.flatten()
ppo_update(model, optimizer, batch, device=device)
if update % 10 == 0:
print(f"Update {update} completed.")
8. Closing Environments
After training, ensure that all environments are properly closed.
envs.close()
Explanation
- Parallel Environments: The
SubprocVecEnv class manages multiple environments running in separate processes, allowing for parallel data collection.
- Actor-Critic Model: The neural network outputs both action logits (for the policy) and value estimates (for the critic).
- Advantage Calculation: Using GAE helps reduce variance and improve learning stability.
- PPO Update: The update function implements the PPO clipped objective, performing multiple epochs over mini-batches of data to improve sample efficiency.
Notes
- Observation Preprocessing: Pong's observations are preprocessed to grayscale, scaled, and stacked (FrameStack) to capture temporal information.
- Pong Action Space: Pong has an action space of 6 discrete actions.
- Hyperparameters: Adjust learning rates, batch sizes, and other hyperparameters as needed.
- Performance Monitoring: Include logging of rewards and other metrics to monitor training progress.
- Seed Setting: For reproducibility, set seeds for NumPy, PyTorch, and Gym environments.
Conclusion
This implementation allows you to train a PPO agent on the Pong environment using parallel environments without relying on external libraries like Stable Baselines. It's a powerful approach that can be adapted to other environments and tasks. Remember to experiment with hyperparameters and consider implementing additional features like learning rate schedules or gradient clipping to further enhance training.