diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index b57af7d8..2da3e755 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -206,3 +206,31 @@ jobs: run: poetry run pip install setuptools==59.5.0 - name: Run atari tests run: poetry run pytest tests/test_atari_multigpu.py + + test-pettingzoo-envs: + strategy: + fail-fast: false + matrix: + python-version: [3.8] + poetry-version: [1.1.11] + os: [ubuntu-18.04, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Run image + uses: abatilo/actions-poetry@v2.0.0 + with: + poetry-version: ${{ matrix.poetry-version }} + + # pettingzoo tests + - name: Install pettingzoo dependencies + run: poetry install -E "pytest pettingzoo atari" + - name: Downgrade setuptools + run: poetry run pip install setuptools==59.5.0 + - name: Install ROMs + run: poetry run AutoROM --accept-license + - name: Run pettingzoo tests + run: poetry run pytest tests/test_pettingzoo_ma_atari.py \ No newline at end of file diff --git a/.gitpod.yml b/.gitpod.yml index cf0fceab..85bd09cd 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -19,7 +19,7 @@ github: # enable for pull requests coming from forks (defaults to false) pullRequestsFromForks: true # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) - addComment: true + addComment: false # add a "Review in Gitpod" button to pull requests (defaults to false) addBadge: false # add a label once the prebuild is ready to pull requests (defaults to false) diff --git a/benchmark/ppo.sh b/benchmark/ppo.sh index 08a096f1..4458237c 100644 --- a/benchmark/ppo.sh +++ b/benchmark/ppo.sh @@ -49,3 +49,11 @@ xvfb-run -a python -m cleanrl_utils.benchmark \ --command "poetry run torchrun --standalone --nnodes=1 --nproc_per_node=2 cleanrl/ppo_atari_multigpu.py --track --capture-video" \ --num-seeds 3 \ --workers 1 + +poetry install -E "pettingzoo atari" +poetry run AutoROM --accept-license +xvfb-run -a python -m cleanrl_utils.benchmark \ + --env-ids pong_v3 surround_v2 tennis_v3 \ + --command "poetry run python cleanrl/ppo_pettingzoo_ma_atari.py --track --capture-video" \ + --num-seeds 3 \ + --workers 3 diff --git a/cleanrl/ppo_pettingzoo_ma_atari.py b/cleanrl/ppo_pettingzoo_ma_atari.py new file mode 100644 index 00000000..62295025 --- /dev/null +++ b/cleanrl/ppo_pettingzoo_ma_atari.py @@ -0,0 +1,326 @@ +import argparse +import importlib +import os +import random +import time +from distutils.util import strtobool + +import gym +import numpy as np +import supersuit as ss +import torch +import torch.nn as nn +import torch.optim as optim +from torch.distributions.categorical import Categorical +from torch.utils.tensorboard import SummaryWriter + + +def parse_args(): + # fmt: off + parser = argparse.ArgumentParser() + parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"), + help="the name of this experiment") + parser.add_argument("--seed", type=int, default=1, + help="seed of the experiment") + parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True, + help="if toggled, `torch.backends.cudnn.deterministic=False`") + parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True, + help="if toggled, cuda will be enabled by default") + 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") + parser.add_argument("--wandb-project-name", type=str, default="cleanRL", + help="the wandb's project name") + parser.add_argument("--wandb-entity", type=str, default=None, + help="the entity (team) of wandb's project") + 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)") + + # Algorithm specific arguments + parser.add_argument("--env-id", type=str, default="pong_v3", + help="the id of the environment") + parser.add_argument("--total-timesteps", type=int, default=20000000, + help="total timesteps of the experiments") + parser.add_argument("--learning-rate", type=float, default=2.5e-4, + help="the learning rate of the optimizer") + parser.add_argument("--num-envs", type=int, default=16, + help="the number of parallel game environments") + parser.add_argument("--num-steps", type=int, default=128, + 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, + 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, + help="Use GAE for advantage computation") + parser.add_argument("--gamma", type=float, default=0.99, + help="the discount factor gamma") + parser.add_argument("--gae-lambda", type=float, default=0.95, + help="the lambda for the general advantage estimation") + parser.add_argument("--num-minibatches", type=int, default=4, + help="the number of mini-batches") + parser.add_argument("--update-epochs", type=int, default=4, + help="the K epochs to update the policy") + parser.add_argument("--norm-adv", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True, + help="Toggles advantages normalization") + parser.add_argument("--clip-coef", type=float, default=0.1, + help="the surrogate clipping coefficient") + 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.") + parser.add_argument("--ent-coef", type=float, default=0.01, + help="coefficient of the entropy") + parser.add_argument("--vf-coef", type=float, default=0.5, + help="coefficient of the value function") + parser.add_argument("--max-grad-norm", type=float, default=0.5, + help="the maximum norm for the gradient clipping") + parser.add_argument("--target-kl", type=float, default=None, + help="the target KL divergence threshold") + args = parser.parse_args() + args.batch_size = int(args.num_envs * args.num_steps) + args.minibatch_size = int(args.batch_size // args.num_minibatches) + # fmt: on + return args + + +def layer_init(layer, std=np.sqrt(2), bias_const=0.0): + torch.nn.init.orthogonal_(layer.weight, std) + torch.nn.init.constant_(layer.bias, bias_const) + return layer + + +class Agent(nn.Module): + def __init__(self, envs): + super().__init__() + self.network = nn.Sequential( + layer_init(nn.Conv2d(6, 32, 8, stride=4)), + nn.ReLU(), + layer_init(nn.Conv2d(32, 64, 4, stride=2)), + nn.ReLU(), + layer_init(nn.Conv2d(64, 64, 3, stride=1)), + nn.ReLU(), + nn.Flatten(), + layer_init(nn.Linear(64 * 7 * 7, 512)), + nn.ReLU(), + ) + self.actor = layer_init(nn.Linear(512, envs.single_action_space.n), std=0.01) + self.critic = layer_init(nn.Linear(512, 1), std=1) + + def get_value(self, x): + x = x.clone() + x[:, :, :, [0, 1, 2, 3]] /= 255.0 + return self.critic(self.network(x.permute((0, 3, 1, 2)))) + + def get_action_and_value(self, x, action=None): + x = x.clone() + x[:, :, :, [0, 1, 2, 3]] /= 255.0 + hidden = self.network(x.permute((0, 3, 1, 2))) + logits = self.actor(hidden) + probs = Categorical(logits=logits) + if action is None: + action = probs.sample() + return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) + + +if __name__ == "__main__": + args = parse_args() + run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}" + if args.track: + import wandb + + wandb.init( + project=args.wandb_project_name, + entity=args.wandb_entity, + sync_tensorboard=True, + config=vars(args), + name=run_name, + monitor_gym=True, + save_code=True, + ) + writer = SummaryWriter(f"runs/{run_name}") + writer.add_text( + "hyperparameters", + "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])), + ) + + # TRY NOT TO MODIFY: seeding + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.backends.cudnn.deterministic = args.torch_deterministic + + device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu") + + # env setup + env = importlib.import_module(f"pettingzoo.atari.{args.env_id}").parallel_env() + env = ss.max_observation_v0(env, 2) + env = ss.frame_skip_v0(env, 4) + env = ss.clip_reward_v0(env, lower_bound=-1, upper_bound=1) + env = ss.color_reduction_v0(env, mode="B") + env = ss.resize_v1(env, x_size=84, y_size=84) + env = ss.frame_stack_v1(env, 4) + env = ss.agent_indicator_v0(env, type_only=False) + env = ss.pettingzoo_env_to_vec_env_v1(env) + envs = ss.concat_vec_envs_v1(env, args.num_envs // 2, num_cpus=0, base_class="gym") + envs.single_observation_space = envs.observation_space + envs.single_action_space = envs.action_space + envs.is_vector_env = True + envs = gym.wrappers.RecordEpisodeStatistics(envs) + if args.capture_video: + envs = gym.wrappers.RecordVideo(envs, f"videos/{run_name}") + assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported" + + agent = Agent(envs).to(device) + optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5) + + # ALGO Logic: Storage setup + obs = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space.shape).to(device) + actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape).to(device) + logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device) + rewards = torch.zeros((args.num_steps, args.num_envs)).to(device) + dones = torch.zeros((args.num_steps, args.num_envs)).to(device) + values = torch.zeros((args.num_steps, args.num_envs)).to(device) + + # TRY NOT TO MODIFY: start the game + global_step = 0 + start_time = time.time() + next_obs = torch.Tensor(envs.reset()).to(device) + next_done = torch.zeros(args.num_envs).to(device) + num_updates = args.total_timesteps // args.batch_size + + for update in range(1, num_updates + 1): + # Annealing the rate if instructed to do so. + if args.anneal_lr: + frac = 1.0 - (update - 1.0) / num_updates + lrnow = frac * args.learning_rate + optimizer.param_groups[0]["lr"] = lrnow + + for step in range(0, args.num_steps): + global_step += 1 * args.num_envs + obs[step] = next_obs + dones[step] = next_done + + # ALGO LOGIC: action logic + with torch.no_grad(): + action, logprob, _, value = agent.get_action_and_value(next_obs) + values[step] = value.flatten() + actions[step] = action + logprobs[step] = logprob + + # TRY NOT TO MODIFY: execute the game and log data. + next_obs, reward, done, info = envs.step(action.cpu().numpy()) + rewards[step] = torch.tensor(reward).to(device).view(-1) + next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor(done).to(device) + + for idx, item in enumerate(info): + player_idx = idx % 2 + if "episode" in item.keys(): + print(f"global_step={global_step}, {player_idx}-episodic_return={item['episode']['r']}") + writer.add_scalar(f"charts/episodic_return-player{player_idx}", item["episode"]["r"], global_step) + writer.add_scalar(f"charts/episodic_length-player{player_idx}", item["episode"]["l"], global_step) + + # bootstrap value if not done + with torch.no_grad(): + next_value = agent.get_value(next_obs).reshape(1, -1) + if args.gae: + advantages = torch.zeros_like(rewards).to(device) + lastgaelam = 0 + for t in reversed(range(args.num_steps)): + if t == args.num_steps - 1: + nextnonterminal = 1.0 - next_done + nextvalues = next_value + else: + nextnonterminal = 1.0 - dones[t + 1] + nextvalues = values[t + 1] + delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t] + advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam + returns = advantages + values + else: + returns = torch.zeros_like(rewards).to(device) + for t in reversed(range(args.num_steps)): + if t == args.num_steps - 1: + nextnonterminal = 1.0 - next_done + next_return = next_value + else: + nextnonterminal = 1.0 - dones[t + 1] + next_return = returns[t + 1] + returns[t] = rewards[t] + args.gamma * nextnonterminal * next_return + advantages = returns - values + + # flatten the batch + b_obs = obs.reshape((-1,) + envs.single_observation_space.shape) + b_logprobs = logprobs.reshape(-1) + b_actions = actions.reshape((-1,) + envs.single_action_space.shape) + b_advantages = advantages.reshape(-1) + b_returns = returns.reshape(-1) + b_values = values.reshape(-1) + + # Optimizing the policy and value network + b_inds = np.arange(args.batch_size) + clipfracs = [] + for epoch in range(args.update_epochs): + np.random.shuffle(b_inds) + for start in range(0, args.batch_size, args.minibatch_size): + end = start + args.minibatch_size + mb_inds = b_inds[start:end] + + _, newlogprob, entropy, newvalue = agent.get_action_and_value(b_obs[mb_inds], b_actions.long()[mb_inds]) + logratio = newlogprob - b_logprobs[mb_inds] + ratio = logratio.exp() + + with torch.no_grad(): + # calculate approx_kl http://joschu.net/blog/kl-approx.html + old_approx_kl = (-logratio).mean() + approx_kl = ((ratio - 1) - logratio).mean() + clipfracs += [((ratio - 1.0).abs() > args.clip_coef).float().mean().item()] + + mb_advantages = b_advantages[mb_inds] + if args.norm_adv: + mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8) + + # Policy loss + pg_loss1 = -mb_advantages * ratio + pg_loss2 = -mb_advantages * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef) + pg_loss = torch.max(pg_loss1, pg_loss2).mean() + + # Value loss + newvalue = newvalue.view(-1) + if args.clip_vloss: + v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2 + v_clipped = b_values[mb_inds] + torch.clamp( + newvalue - b_values[mb_inds], + -args.clip_coef, + args.clip_coef, + ) + v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2 + v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped) + v_loss = 0.5 * v_loss_max.mean() + else: + v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean() + + entropy_loss = entropy.mean() + loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef + + optimizer.zero_grad() + loss.backward() + nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm) + optimizer.step() + + if args.target_kl is not None: + if approx_kl > args.target_kl: + break + + y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy() + var_y = np.var(y_true) + explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y + + # TRY NOT TO MODIFY: record rewards for plotting purposes + writer.add_scalar("charts/learning_rate", optimizer.param_groups[0]["lr"], global_step) + writer.add_scalar("losses/value_loss", v_loss.item(), global_step) + writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step) + writer.add_scalar("losses/entropy", entropy_loss.item(), global_step) + writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step) + writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step) + writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step) + writer.add_scalar("losses/explained_variance", explained_var, global_step) + print("SPS:", int(global_step / (time.time() - start_time))) + writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step) + + envs.close() + writer.close() diff --git a/docs/rl-algorithms/ppo.md b/docs/rl-algorithms/ppo.md index 5f7655f8..9dba01b1 100644 --- a/docs/rl-algorithms/ppo.md +++ b/docs/rl-algorithms/ppo.md @@ -739,4 +739,139 @@ Tracked experiments and game play videos: + + +## `ppo_pettingzoo_ma_atari.py` + +`ppo_pettingzoo_ma_atari.py` trains an agent to learn playing Atari games via selfplay. The selfplay environment is implemented as a vectorized environment from [PettingZoo.ml](https://www.pettingzoo.ml/atari). The basic idea is to create vectorized environment $E$ with `num_envs = N`, where $N$ is the number of players in the game. Say $N = 2$, then the 0-th sub environment of $E$ will return the observation for player 0 and 1-th sub environment will return the observation of player 1. Then the two environments takes a batch of 2 actions and execute them for player 0 and player 1, respectively. See "Vectorized architecture" in [The 37 Implementation Details of Proximal Policy Optimization](https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/) for more detail. + +`ppo_pettingzoo_ma_atari.py` has the following features: + +* For playing the pettingzoo's multi-agent Atari game. +* Works with the pixel-based observation space +* Works with the `Box` action space + +???+ warning + + Note that `ppo_pettingzoo_ma_atari.py` does not work in Windows :fontawesome-brands-windows:. See [https://pypi.org/project/multi-agent-ale-py/#files](https://pypi.org/project/multi-agent-ale-py/#files) + +### Usage + +```bash +poetry install -E "pettingzoo atari" +poetry run AutoROM --accept-license +python cleanrl/ppo_pettingzoo_ma_atari.py --help +python cleanrl/ppo_pettingzoo_ma_atari.py --env-id pong_v3 +python cleanrl/ppo_pettingzoo_ma_atari.py --env-id surround_v2 +``` + +See [https://www.pettingzoo.ml/atari](https://www.pettingzoo.ml/atari) for a full-list of supported environments such as `basketball_pong_v3`. Notice pettingzoo sometimes introduces breaking changes, so make sure to install the pinned dependencies via `poetry`. + +### Explanation of the logged metrics + +Additionally, it logs the following metrics + +* `charts/episodic_return-player0`: episodic return of the game for player 0 +* `charts/episodic_return-player1`: episodic return of the game for player 1 +* `charts/episodic_length-player0`: episodic length of the game for player 0 +* `charts/episodic_length-player1`: episodic length of the game for player 1 + +See other logged metrics in the [related docs](/rl-algorithms/ppo/#explanation-of-the-logged-metrics) for `ppo.py`. + +### Implementation details + +[ppo_pettingzoo_ma_atari.py](https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/ppo_pettingzoo_ma_atari.py) is based on `ppo_atari.py` (see its [related docs](/rl-algorithms/ppo/#implementation-details_1)). + +`ppo_pettingzoo_ma_atari.py` additionally has the following implementation details: + +1. **`supersuit` wrappers**: uses preprocessing wrappers from `supersuit` instead of from `stable_baselines3`, which looks like the following. In particular note that the `supersuit` does not offer a wrapper similar to `NoopResetEnv`, and that it uses the `agent_indicator_v0` to add two channels indicating the which player the agent controls. + + ```diff + -env = gym.make(env_id) + -env = NoopResetEnv(env, noop_max=30) + -env = MaxAndSkipEnv(env, skip=4) + -env = EpisodicLifeEnv(env) + -if "FIRE" in env.unwrapped.get_action_meanings(): + - env = FireResetEnv(env) + -env = ClipRewardEnv(env) + -env = gym.wrappers.ResizeObservation(env, (84, 84)) + -env = gym.wrappers.GrayScaleObservation(env) + -env = gym.wrappers.FrameStack(env, 4) + +env = importlib.import_module(f"pettingzoo.atari.{args.env_id}").parallel_env() + +env = ss.max_observation_v0(env, 2) + +env = ss.frame_skip_v0(env, 4) + +env = ss.clip_reward_v0(env, lower_bound=-1, upper_bound=1) + +env = ss.color_reduction_v0(env, mode="B") + +env = ss.resize_v1(env, x_size=84, y_size=84) + +env = ss.frame_stack_v1(env, 4) + +env = ss.agent_indicator_v0(env, type_only=False) + +env = ss.pettingzoo_env_to_vec_env_v1(env) + +envs = ss.concat_vec_envs_v1(env, args.num_envs // 2, num_cpus=0, base_class="gym") + ``` +1. **A more detailed note on the `agent_indicator_v0` wrapper**: let's dig deeper into how `agent_indicator_v0` works. We do `print(envs.reset(), envs.reset().shape)` + ```python + [ 0., 0., 0., 236., 1, 0.]], + + [[ 0., 0., 0., 236., 0., 1.], + [ 0., 0., 0., 236., 0., 1.], + [ 0., 0., 0., 236., 0., 1.], + ..., + [ 0., 0., 0., 236., 0., 1.], + [ 0., 0., 0., 236., 0., 1.], + [ 0., 0., 0., 236., 0., 1.]]]]) torch.Size([16, 84, 84, 6]) + ``` + + So the `agent_indicator_v0` adds the last two columns, where `[ 0., 0., 0., 236., 1, 0.]]` means this observation is for player 0, and `[ 0., 0., 0., 236., 0., 1.]` is for player 1. Notice the observation still has the range of $[0, 255]$ but the agent indicator channel has the range of $[0,1]$, so we need to be careful when dividing the observation by 255. In particular, we would only divide the first four channels by 255 and leave the agent indicator channels untouched as follows: + + ```py + def get_action_and_value(self, x, action=None): + x = x.clone() + x[:, :, :, [0, 1, 2, 3]] /= 255.0 + hidden = self.network(x.permute((0, 3, 1, 2))) + ``` + + +### Experiment results + + + +To run benchmark experiments, see :material-github: [benchmark/ppo.sh](https://github.com/vwxyzjn/cleanrl/blob/master/benchmark/ppo.sh). Specifically, execute the following command: + + + +???+ info + + Note that evaluation is usually tricker in in selfplay environments. The usual episodic return is not a good indicator of the agent's performance in zero-sum games because the episodic return converges to zero. To evaluate the agent's ability, an intuitive approach is to take a look at the videos of the agents playing the game (included below), visually inspect the agent's behavior. The best scheme, however, is rating systems like [Trueskill](https://www.microsoft.com/en-us/research/project/trueskill-ranking-system/) or [ELO scores](https://en.wikipedia.org/wiki/Elo_rating_system). However, they are more difficult to implement and are outside the scode of `ppo_pettingzoo_ma_atari.py`. + + + For simplicity, we measure the **episodic length** instead, which in a sense measures how many "back and forth" the agent can create. In other words, the longer the agent can play the game, the better the agent can play. Empirically, we have found episodic length to be a good indicator of the agent's skill, especially in `pong_v3` and `surround_v2`. However, it is not the case for `tennis_v3` and we'd need to visually inspect the agents' game play videos. + + +Below are the average **episodic length** for `ppo_pettingzoo_ma_atari.py`. To ensure no loss of sample efficiency, we compared the results against `ppo_atari.py`. + +| Environment | `ppo_pettingzoo_ma_atari.py` | +| ----------- | ----------- | +| pong_v3 | 4153.60 ± 190.80 | +| surround_v2 | 3055.33 ± 223.68 | +| tennis_v3 | 14538.02 ± 7005.54 | + + +Learning curves: + +
+ + + + + +
+ + + +Tracked experiments and game play videos: + + + + + [^1]: Huang, Shengyi; Dossa, Rousslan Fernand Julien; Raffin, Antonin; Kanervisto, Anssi; Wang, Weixun (2022). The 37 Implementation Details of Proximal Policy Optimization. ICLR 2022 Blog Track https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/ \ No newline at end of file diff --git a/docs/rl-algorithms/ppo/pong_v3.png b/docs/rl-algorithms/ppo/pong_v3.png new file mode 100644 index 00000000..0b2498f3 Binary files /dev/null and b/docs/rl-algorithms/ppo/pong_v3.png differ diff --git a/docs/rl-algorithms/ppo/surround_v2.png b/docs/rl-algorithms/ppo/surround_v2.png new file mode 100644 index 00000000..797b648b Binary files /dev/null and b/docs/rl-algorithms/ppo/surround_v2.png differ diff --git a/docs/rl-algorithms/ppo/tennis_v3.png b/docs/rl-algorithms/ppo/tennis_v3.png new file mode 100644 index 00000000..f051abc3 Binary files /dev/null and b/docs/rl-algorithms/ppo/tennis_v3.png differ diff --git a/poetry.lock b/poetry.lock index 6797d20b..a374bd24 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1240,6 +1240,17 @@ category = "main" optional = true python-versions = "*" +[[package]] +name = "multi-agent-ale-py" +version = "0.1.11" +description = "Multi-Agent Arcade Learning Environment Python Interface" +category = "main" +optional = true +python-versions = "*" + +[package.dependencies] +numpy = "*" + [[package]] name = "mypy-extensions" version = "0.4.3" @@ -1470,7 +1481,7 @@ python-versions = "*" [[package]] name = "pettingzoo" -version = "1.16.0" +version = "1.18.1" description = "Gym for multi-agent reinforcement learning" category = "main" optional = true @@ -1481,15 +1492,15 @@ gym = ">=0.21.0" numpy = ">=1.18.0" [package.extras] -all = ["multi_agent_ale_py (==0.1.11)", "pygame (==2.1.0)", "chess (==1.7.0)", "rlcard (==1.0.4)", "pygame (==2.1.0)", "hanabi_learning_environment (==0.0.1)", "pygame (==2.1.0)", "pymunk (==6.2.0)", "magent (==0.2.0)", "pyglet (>=1.4.0)", "pygame (==2.1.0)", "box2d-py (==2.3.5)", "scipy (>=1.4.1)", "pillow (>=8.0.1)"] -atari = ["multi_agent_ale_py (==0.1.11)", "pygame (==2.1.0)"] +all = ["multi-agent-ale-py (==0.1.11)", "pygame (==2.1.0)", "chess (==1.7.0)", "rlcard (==1.0.4)", "hanabi-learning-environment (==0.0.1)", "pymunk (==6.2.0)", "magent (==0.2.2)", "pyglet (>=1.4.0)", "box2d-py (==2.3.5)", "scipy (>=1.4.1)", "pillow (>=8.0.1)"] +atari = ["multi-agent-ale-py (==0.1.11)", "pygame (==2.1.0)"] butterfly = ["pygame (==2.1.0)", "pymunk (==6.2.0)"] -classic = ["chess (==1.7.0)", "rlcard (==1.0.4)", "pygame (==2.1.0)", "hanabi_learning_environment (==0.0.1)"] -magent = ["magent (==0.2.0)"] +classic = ["chess (==1.7.0)", "rlcard (==1.0.4)", "pygame (==2.1.0)", "hanabi-learning-environment (==0.0.1)"] +magent = ["magent (==0.2.2)"] mpe = ["pyglet (>=1.4.0)"] other = ["pillow (>=8.0.1)"] sisl = ["pygame (==2.1.0)", "box2d-py (==2.3.5)", "scipy (>=1.4.1)"] -tests = ["pynput"] +tests = ["pynput", "pytest", "codespell", "flake8", "isort"] [[package]] name = "pexpect" @@ -4377,7 +4388,7 @@ tests = ["pytest", "pytest-cov", "pytest-env", "pytest-xdist", "pytype", "flake8 [[package]] name = "supersuit" -version = "3.3.4" +version = "3.4.0" description = "Wrappers for Gym and PettingZoo" category = "main" optional = true @@ -4385,8 +4396,8 @@ python-versions = ">=3.7" [package.dependencies] gym = ">=0.22.0" -opencv-python = ">=3.4.0,<3.5.0" pettingzoo = ">=1.15.0" +tinyscaler = ">=1.0.4" [[package]] name = "tensorboard" @@ -4503,6 +4514,17 @@ webencodings = ">=0.4" doc = ["sphinx", "sphinx-rtd-theme"] test = ["pytest", "pytest-cov", "pytest-flake8", "pytest-isort", "coverage"] +[[package]] +name = "tinyscaler" +version = "1.2.4" +description = "A tiny, simple image scaler" +category = "main" +optional = true +python-versions = "*" + +[package.dependencies] +numpy = "*" + [[package]] name = "toml" version = "0.10.2" @@ -4755,7 +4777,7 @@ cloud = ["boto3", "awscli"] docs = ["mkdocs-material"] envpool = ["envpool"] mujoco = ["free-mujoco-py"] -pettingzoo = ["pettingzoo", "pygame", "pymunk"] +pettingzoo = ["pettingzoo", "pygame", "pymunk", "SuperSuit", "multi-agent-ale-py"] plot = ["pandas", "seaborn"] procgen = ["procgen"] pybullet = ["pybullet"] @@ -4765,7 +4787,7 @@ spyder = ["spyder"] [metadata] lock-version = "1.1" python-versions = ">=3.7.1,<3.10" -content-hash = "ef31d9cebf0312d146bf141368d726815c2f603bc02b3aa112398e940c19891a" +content-hash = "eeb16be4f9bb0946d6b84e591dfc365b94b10013736fd38756719c245ba556ea" [metadata.files] absl-py = [ @@ -5578,6 +5600,18 @@ monotonic = [ {file = "monotonic-1.6-py2.py3-none-any.whl", hash = "sha256:68687e19a14f11f26d140dd5c86f3dba4bf5df58003000ed467e0e2a69bca96c"}, {file = "monotonic-1.6.tar.gz", hash = "sha256:3a55207bcfed53ddd5c5bae174524062935efed17792e9de2ad0205ce9ad63f7"}, ] +multi-agent-ale-py = [ + {file = "multi-agent-ale-py-0.1.11.tar.gz", hash = "sha256:ba3ff800420f65ff354574975bdfa79035ae1597e8938b37d1df12ffc4122edb"}, + {file = "multi_agent_ale_py-0.1.11-cp36-cp36m-macosx_10_15_x86_64.whl", hash = "sha256:b4169913de9e5245fe223c3a68bc5db3cbfd7ea7f9a032ff73f7ba3113cc7bbc"}, + {file = "multi_agent_ale_py-0.1.11-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bdcc603bbea8c6bbf32e0182012f2dba275bd24f633fd7ec0965ec19e1ff3169"}, + {file = "multi_agent_ale_py-0.1.11-cp37-cp37m-macosx_10_15_x86_64.whl", hash = "sha256:59c5ad594d34956ddd68df7ab96622581fb31a7bed3a8d8dcfea8675e339d9c4"}, + {file = "multi_agent_ale_py-0.1.11-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1686a1f5dc8f146b4ce08ee96215140d32b91c77febe02e885e7472eeec816b5"}, + {file = "multi_agent_ale_py-0.1.11-cp38-cp38-macosx_10_15_x86_64.whl", hash = "sha256:9ba47d47e307e10606bc93c5960b2571cd5371964cd81eaddb0b489f1cdaefd1"}, + {file = "multi_agent_ale_py-0.1.11-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:2b66288a1160e091901f4c6af97a53e45448ab17d2ca03710978e6022adec422"}, + {file = "multi_agent_ale_py-0.1.11-cp39-cp39-macosx_10_15_x86_64.whl", hash = "sha256:ce208dca1075408c41b7fe17b29df84b8fb7b8c09bd70897afbb8e767d624101"}, + {file = "multi_agent_ale_py-0.1.11-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:48a6729423e5b5f47c06b98a25c18e726e2227e60abfd3d70735dc9a48c549d7"}, + {file = "multi_agent_ale_py-0.1.11-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:7fd316dba5f05cdd2a29b0037433f9f15666fd4a0c2d98f3d85ca57a73d2b423"}, +] mypy-extensions = [ {file = "mypy_extensions-0.4.3-py2.py3-none-any.whl", hash = "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d"}, {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"}, @@ -5702,7 +5736,8 @@ pathtools = [ {file = "pathtools-0.1.2.tar.gz", hash = "sha256:7c35c5421a39bb82e58018febd90e3b6e5db34c5443aaaf742b3f33d4655f1c0"}, ] pettingzoo = [ - {file = "PettingZoo-1.16.0.tar.gz", hash = "sha256:01636b1f71f4b236fcda53e9b3a30553b8cb539ac2489f2922de1ec537949c1b"}, + {file = "PettingZoo-1.18.1-py3-none-any.whl", hash = "sha256:25ae45fcfa2c623800e1f81b98ae50f5f5a1af6caabc5946764248de71a0371d"}, + {file = "PettingZoo-1.18.1.tar.gz", hash = "sha256:7e6a3231dc3fc3801af83fe880f199f570d46a9acdcb990f2a223f121b6e5038"}, ] pexpect = [ {file = "pexpect-4.8.0-py2.py3-none-any.whl", hash = "sha256:0b48a55dcb3c05f3329815901ea4fc1537514d6ba867a152b581d69ae3710937"}, @@ -7191,7 +7226,8 @@ stable-baselines3 = [ {file = "stable_baselines3-1.2.0.tar.gz", hash = "sha256:170842f30c00adff0dcccef5be74921cfa0dd2650b3eb8600c62b5d43ff78c67"}, ] supersuit = [ - {file = "SuperSuit-3.3.4.tar.gz", hash = "sha256:dfbba2a0bdadbc66227c2505772cbf6b4897ef9005c12b94fed5947fb4ba108f"}, + {file = "SuperSuit-3.4.0-py3-none-any.whl", hash = "sha256:45b541b2b29faffd6494b53d649c8d94889966f407fd380b3e3211f9e68a49e9"}, + {file = "SuperSuit-3.4.0.tar.gz", hash = "sha256:5999beec8d7923c11c9511eaa9dec8a38269cb0d7af029e17903c79234233409"}, ] tensorboard = [ {file = "tensorboard-2.8.0-py3-none-any.whl", hash = "sha256:65a338e4424e9079f2604923bdbe301792adce2ace1be68da6b3ddf005170def"}, @@ -7227,6 +7263,10 @@ tinycss2 = [ {file = "tinycss2-1.1.1-py3-none-any.whl", hash = "sha256:fe794ceaadfe3cf3e686b22155d0da5780dd0e273471a51846d0a02bc204fec8"}, {file = "tinycss2-1.1.1.tar.gz", hash = "sha256:b2e44dd8883c360c35dd0d1b5aad0b610e5156c2cb3b33434634e539ead9d8bf"}, ] +tinyscaler = [ + {file = "tinyscaler-1.2.4-cp310-cp310-manylinux2010_x86_64.whl", hash = "sha256:d5230e57e8eb25a770afc782289d3241a55517ad3f345245c9ca2ef65f4d4d69"}, + {file = "tinyscaler-1.2.4.tar.gz", hash = "sha256:2f2a890c5314bf6cfe4532dc6e6c9946faeb7c15f0a8f98234c8b77cb7ad287c"}, +] toml = [ {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, diff --git a/pyproject.toml b/pyproject.toml index da51634f..1a6832ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,6 @@ AutoROM = {version = "^0.4.2", optional = true, extras = ["accept-rom-license"]} pybullet = {version = "3.1.8", optional = true} procgen = {version = "^0.10.4", optional = true} pettingzoo = {version = "^1.15.0", optional = true} -supersuit = {version = "^3.3.3", optional = true} pygame = {version = "^2.0.1", optional = true} pymunk = {version = "^6.2.0", optional = true} pandas = {version = "^1.3.3", optional = true} @@ -33,6 +32,8 @@ pytest = {version = "^6.2.5", optional = true} free-mujoco-py = {version = "^2.1.6", optional = true} mkdocs-material = {version = "^7.3.4", optional = true} envpool = {version = "^0.4.3", optional = true} +SuperSuit = {version = "^3.4.0", optional = true} +multi-agent-ale-py = {version = "^0.1.11", optional = true} [tool.poetry.dev-dependencies] pre-commit = "^2.17.0" @@ -45,7 +46,7 @@ build-backend = "poetry.core.masonry.api" atari = ["ale-py", "AutoROM"] pybullet = ["pybullet"] procgen = ["procgen"] -pettingzoo = ["pettingzoo", "pygame", "pymunk"] +pettingzoo = ["pettingzoo", "pygame", "pymunk", "SuperSuit", "multi-agent-ale-py"] plot = ["pandas", "seaborn"] cloud = ["boto3", "awscli"] spyder = ["spyder"] diff --git a/tests/test_pettingzoo_ma_atari.py b/tests/test_pettingzoo_ma_atari.py new file mode 100644 index 00000000..d5d9ed96 --- /dev/null +++ b/tests/test_pettingzoo_ma_atari.py @@ -0,0 +1,9 @@ +import subprocess + + +def test_ppo(): + subprocess.run( + "python cleanrl/ppo_pettingzoo_ma_atari.py --num-steps 32 --num-envs 6 --total-timesteps 256", + shell=True, + check=True, + )