PPO + Envpool

Creado El diff nunca expira
52 eliminaciones
340 líneas
82 adiciones
366 líneas
import argparse
import argparse
import os
import os
import random
import random
import time
import time
from collections import deque
from distutils.util import strtobool
from distutils.util import strtobool


import envpool
import gym
import gym
import numpy as np
import numpy as np
import torch
import torch
import torch.nn as nn
import torch.nn as nn
import torch.optim as optim
import torch.optim as optim
from torch.distributions.categorical import Categorical
from torch.distributions.categorical import Categorical
from torch.utils.tensorboard import SummaryWriter
from torch.utils.tensorboard import SummaryWriter


from stable_baselines3.common.atari_wrappers import ( # isort:skip
ClipRewardEnv,
EpisodicLifeEnv,
FireResetEnv,
MaxAndSkipEnv,
NoopResetEnv,
)



def parse_args():
def parse_args():
# fmt: off
# fmt: off
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser()
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
help="the name of this experiment")
help="the name of this experiment")
parser.add_argument("--gym-id", type=str, default="BreakoutNoFrameskip-v4",
parser.add_argument("--gym-id", type=str, default="Pong-v5",
help="the id of the gym environment")
help="the id of the gym environment")
parser.add_argument("--learning-rate", type=float, default=2.5e-4,
parser.add_argument("--learning-rate", type=float, default=2.5e-4,
help="the learning rate of the optimizer")
help="the learning rate of the optimizer")
parser.add_argument("--seed", type=int, default=1,
parser.add_argument("--seed", type=int, default=1,
help="seed of the experiment")
help="seed of the experiment")
parser.add_argument("--total-timesteps", type=int, default=10000000,
parser.add_argument("--total-timesteps", type=int, default=10000000,
help="total timesteps of the experiments")
help="total timesteps of the experiments")
parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="if toggled, `torch.backends.cudnn.deterministic=False`")
help="if toggled, `torch.backends.cudnn.deterministic=False`")
parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="if toggled, cuda will be enabled by default")
help="if toggled, cuda will be enabled by default")
parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
help="if toggled, this experiment will be tracked with Weights and Biases")
help="if toggled, this experiment will be tracked with Weights and Biases")
parser.add_argument("--wandb-project-name", type=str, default="ppo-implementation-details",
parser.add_argument("--wandb-project-name", type=str, default="ppo-implementation-details",
help="the wandb's project name")
help="the wandb's project name")
parser.add_argument("--wandb-entity", type=str, default=None,
parser.add_argument("--wandb-entity", type=str, default=None,
help="the entity (team) of wandb's project")
help="the entity (team) of wandb's project")
parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
help="weather to capture videos of the agent performances (check out `videos` folder)")
help="weather to capture videos of the agent performances (check out `videos` folder)")


# Algorithm specific arguments
# Algorithm specific arguments
parser.add_argument("--num-envs", type=int, default=8,
parser.add_argument("--num-envs", type=int, default=8,
help="the number of parallel game environments")
help="the number of parallel game environments")
parser.add_argument("--num-steps", type=int, default=128,
parser.add_argument("--num-steps", type=int, default=128,
help="the number of steps to run in each environment per policy rollout")
help="the number of steps to run in each environment per policy rollout")
parser.add_argument("--anneal-lr", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--anneal-lr", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="Toggle learning rate annealing for policy and value networks")
help="Toggle learning rate annealing for policy and value networks")
parser.add_argument("--gae", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--gae", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="Use GAE for advantage computation")
help="Use GAE for advantage computation")
parser.add_argument("--gamma", type=float, default=0.99,
parser.add_argument("--gamma", type=float, default=0.99,
help="the discount factor gamma")
help="the discount factor gamma")
parser.add_argument("--gae-lambda", type=float, default=0.95,
parser.add_argument("--gae-lambda", type=float, default=0.95,
help="the lambda for the general advantage estimation")
help="the lambda for the general advantage estimation")
parser.add_argument("--num-minibatches", type=int, default=4,
parser.add_argument("--num-minibatches", type=int, default=4,
help="the number of mini-batches")
help="the number of mini-batches")
parser.add_argument("--update-epochs", type=int, default=4,
parser.add_argument("--update-epochs", type=int, default=4,
help="the K epochs to update the policy")
help="the K epochs to update the policy")
parser.add_argument("--norm-adv", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--norm-adv", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="Toggles advantages normalization")
help="Toggles advantages normalization")
parser.add_argument("--clip-coef", type=float, default=0.1,
parser.add_argument("--clip-coef", type=float, default=0.1,
help="the surrogate clipping coefficient")
help="the surrogate clipping coefficient")
parser.add_argument("--clip-vloss", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
parser.add_argument("--clip-vloss", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
help="Toggles whether or not to use a clipped loss for the value function, as per the paper.")
help="Toggles whether or not to use a clipped loss for the value function, as per the paper.")
parser.add_argument("--ent-coef", type=float, default=0.01,
parser.add_argument("--ent-coef", type=float, default=0.01,
help="coefficient of the entropy")
help="coefficient of the entropy")
parser.add_argument("--vf-coef", type=float, default=0.5,
parser.add_argument("--vf-coef", type=float, default=0.5,
help="coefficient of the value function")
help="coefficient of the value function")
parser.add_argument("--max-grad-norm", type=float, default=0.5,
parser.add_argument("--max-grad-norm", type=float, default=0.5,
help="the maximum norm for the gradient clipping")
help="the maximum norm for the gradient clipping")
parser.add_argument("--target-kl", type=float, default=None,
parser.add_argument("--target-kl", type=float, default=None,
help="the target KL divergence threshold")
help="the target KL divergence threshold")
args = parser.parse_args()
args = parser.parse_args()
args.batch_size = int(args.num_envs * args.num_steps)
args.batch_size = int(args.num_envs * args.num_steps)
args.minibatch_size = int(args.batch_size // args.num_minibatches)
args.minibatch_size = int(args.batch_size // args.num_minibatches)
# fmt: on
# fmt: on
return args
return args




def make_env(gym_id, seed, idx, capture_video, run_name):
class RecordEpisodeStatistics(gym.Wrapper):
def thunk():
def __init__(self, env, deque_size=100):
env = gym.make(gym_id)
super(RecordEpisodeStatistics, self).__init__(env)
env = gym.wrappers.RecordEpisodeStatistics(env)
self.num_envs = getattr(env, "num_envs", 1)
if capture_video:
self.episode_returns = None
if idx == 0:
self.episode_lengths = None
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
# get if the env has lives
env = NoopResetEnv(env, noop_max=30)
self.has_lives = False
env = MaxAndSkipEnv(env, skip=4)
env.reset()
env = EpisodicLifeEnv(env)
info = env.step(np.zeros(self.num_envs, dtype=int))[-1]
if "FIRE" in env.unwrapped.get_action_meanings():
if info["lives"].sum() > 0:
env = FireResetEnv(env)
self.has_lives = True
env = ClipRewardEnv(env)
print("env has lives")
env = gym.wrappers.ResizeObservation(env, (84, 84))
env = gym.wrappers.GrayScaleObservation(env)
env = gym.wrappers.FrameStack(env, 4)
env.seed(seed)
env.action_space.seed(seed)
env.observation_space.seed(seed)
return env


return thunk
def reset(self, **kwargs):
observations = super(RecordEpisodeStatistics, self).reset(**kwargs)
self.episode_returns = np.zeros(self.num_envs, dtype=np.float32)
self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
self.lives = np.zeros(self.num_envs, dtype=np.int32)
self.returned_episode_returns = np.zeros(self.num_envs, dtype=np.float32)
self.returned_episode_lengths = np.zeros(self.num_envs, dtype=np.int32)
return observations

def step(self, action):
observations, rewards, dones, infos = super(RecordEpisodeStatistics, self).step(action)
self.episode_returns += infos["reward"]
self.episode_lengths += 1
self.returned_episode_returns[:] = self.episode_returns
self.returned_episode_lengths[:] = self.episode_lengths
all_lives_exhausted = infos["lives"] == 0
if self.has_lives:
self.episode_returns *= 1 - all_lives_exhausted
self.episode_lengths *= 1 - all_lives_exhausted
else:
self.episode_returns *= 1 - dones
self.episode_lengths *= 1 - dones
infos["r"] = self.returned_episode_returns
infos["l"] = self.returned_episode_lengths
return (
observations,
rewards,
dones,
infos,
)




def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
def layer_init(layer, std=np.sqrt(2), bias_const=0.0):
torch.nn.init.orthogonal_(layer.weight, std)
torch.nn.init.orthogonal_(layer.weight, std)
torch.nn.init.constant_(layer.bias, bias_const)
torch.nn.init.constant_(layer.bias, bias_const)
return layer
return layer




class Agent(nn.Module):
class Agent(nn.Module):
def __init__(self, envs):
def __init__(self, envs):
super(Agent, self).__init__()
super(Agent, self).__init__()
self.network = nn.Sequential(
self.network = nn.Sequential(
layer_init(nn.Conv2d(4, 32, 8, stride=4)),
layer_init(nn.Conv2d(4, 32, 8, stride=4)),
nn.ReLU(),
nn.ReLU(),
layer_init(nn.Conv2d(32, 64, 4, stride=2)),
layer_init(nn.Conv2d(32, 64, 4, stride=2)),