vwxyzjn commited on
Commit
1e93e43
1 Parent(s): 42ef1f1

pushing model

Browse files
.gitattributes CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ sebulba_ppo_envpool_impala_atari_wrapper.cleanrl_model filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - Breakout-v5
4
+ - deep-reinforcement-learning
5
+ - reinforcement-learning
6
+ - custom-implementation
7
+ library_name: cleanrl
8
+ model-index:
9
+ - name: PPO
10
+ results:
11
+ - task:
12
+ type: reinforcement-learning
13
+ name: reinforcement-learning
14
+ dataset:
15
+ name: Breakout-v5
16
+ type: Breakout-v5
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 818.30 +/- 130.50
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # (CleanRL) **PPO** Agent Playing **Breakout-v5**
25
+
26
+ This is a trained model of a PPO agent playing Breakout-v5.
27
+ The model was trained by using [CleanRL](https://github.com/vwxyzjn/cleanrl) and the most up-to-date training code can be
28
+ found [here](https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/sebulba_ppo_envpool_impala_atari_wrapper.py).
29
+
30
+ ## Get Started
31
+
32
+ To use this model, please install the `cleanrl` package with the following command:
33
+
34
+ ```
35
+ pip install "cleanrl[jax,envpool,atari]"
36
+ python -m cleanrl_utils.enjoy --exp-name sebulba_ppo_envpool_impala_atari_wrapper --env-id Breakout-v5
37
+ ```
38
+
39
+ Please refer to the [documentation](https://docs.cleanrl.dev/get-started/zoo/) for more detail.
40
+
41
+
42
+ ## Command to reproduce the training
43
+
44
+ ```bash
45
+ curl -OL https://huggingface.co/cleanrl/Breakout-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed3/raw/main/sebulba_ppo_envpool_impala_atari_wrapper.py
46
+ curl -OL https://huggingface.co/cleanrl/Breakout-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed3/raw/main/pyproject.toml
47
+ curl -OL https://huggingface.co/cleanrl/Breakout-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed3/raw/main/poetry.lock
48
+ poetry install --all-extras
49
+ python sebulba_ppo_envpool_impala_atari_wrapper.py --actor-device-ids 0 --learner-device-ids 1 2 3 4 5 6 --track --save-model --upload-model --hf-entity cleanrl --env-id Breakout-v5 --seed 3
50
+ ```
51
+
52
+ # Hyperparameters
53
+ ```python
54
+ {'actor_device_ids': [0],
55
+ 'anneal_lr': True,
56
+ 'async_batch_size': 20,
57
+ 'async_update': 3,
58
+ 'batch_size': 7680,
59
+ 'capture_video': False,
60
+ 'clip_coef': 0.1,
61
+ 'cuda': True,
62
+ 'ent_coef': 0.01,
63
+ 'env_id': 'Breakout-v5',
64
+ 'exp_name': 'sebulba_ppo_envpool_impala_atari_wrapper',
65
+ 'gae_lambda': 0.95,
66
+ 'gamma': 0.99,
67
+ 'hf_entity': 'cleanrl',
68
+ 'learner_device_ids': [1, 2, 3, 4, 5, 6],
69
+ 'learning_rate': 0.00025,
70
+ 'max_grad_norm': 0.5,
71
+ 'minibatch_size': 1920,
72
+ 'norm_adv': True,
73
+ 'num_actor_threads': 1,
74
+ 'num_envs': 60,
75
+ 'num_minibatches': 4,
76
+ 'num_steps': 128,
77
+ 'num_updates': 6510,
78
+ 'profile': False,
79
+ 'save_model': True,
80
+ 'seed': 3,
81
+ 'target_kl': None,
82
+ 'test_actor_learner_throughput': False,
83
+ 'torch_deterministic': True,
84
+ 'total_timesteps': 50000000,
85
+ 'track': True,
86
+ 'update_epochs': 4,
87
+ 'upload_model': True,
88
+ 'vf_coef': 0.5,
89
+ 'wandb_entity': None,
90
+ 'wandb_project_name': 'cleanRL'}
91
+ ```
92
+
events.out.tfevents.1676007465.ip-26-0-142-3.136428.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b02f025b5110810026bb3b0a073e70cbaa2502c1b1a4e2958d099430bc615a5
3
+ size 9506854
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "cleanrl"
3
+ version = "1.1.0"
4
+ description = "High-quality single file implementation of Deep Reinforcement Learning algorithms with research-friendly features"
5
+ authors = ["Costa Huang <costa.huang@outlook.com>"]
6
+ packages = [
7
+ { include = "cleanrl" },
8
+ { include = "cleanrl_utils" },
9
+ ]
10
+ keywords = ["reinforcement", "machine", "learning", "research"]
11
+ license="MIT"
12
+ readme = "README.md"
13
+
14
+ [tool.poetry.dependencies]
15
+ python = ">=3.7.1,<3.10"
16
+ tensorboard = "^2.10.0"
17
+ wandb = "^0.13.6"
18
+ gym = "0.23.1"
19
+ torch = ">=1.12.1"
20
+ stable-baselines3 = "1.2.0"
21
+ gymnasium = "^0.26.3"
22
+ moviepy = "^1.0.3"
23
+ pygame = "2.1.0"
24
+ huggingface-hub = "^0.11.1"
25
+
26
+ ale-py = {version = "0.7.4", optional = true}
27
+ AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2"}
28
+ opencv-python = {version = "^4.6.0.66", optional = true}
29
+ pybullet = {version = "3.1.8", optional = true}
30
+ procgen = {version = "^0.10.7", optional = true}
31
+ pytest = {version = "^7.1.3", optional = true}
32
+ mujoco = {version = "^2.2", optional = true}
33
+ imageio = {version = "^2.14.1", optional = true}
34
+ free-mujoco-py = {version = "^2.1.6", optional = true}
35
+ mkdocs-material = {version = "^8.4.3", optional = true}
36
+ markdown-include = {version = "^0.7.0", optional = true}
37
+ jax = {version = "^0.3.17", optional = true}
38
+ jaxlib = {version = "^0.3.15", optional = true}
39
+ flax = {version = "^0.6.0", optional = true}
40
+ optuna = {version = "^3.0.1", optional = true}
41
+ optuna-dashboard = {version = "^0.7.2", optional = true}
42
+ rich = {version = "<12.0", optional = true}
43
+ envpool = {version = "^0.8.1", optional = true}
44
+ PettingZoo = {version = "1.18.1", optional = true}
45
+ SuperSuit = {version = "3.4.0", optional = true}
46
+ multi-agent-ale-py = {version = "0.1.11", optional = true}
47
+ boto3 = {version = "^1.24.70", optional = true}
48
+ awscli = {version = "^1.25.71", optional = true}
49
+ shimmy = {version = "^0.1.0", optional = true}
50
+ dm-control = {version = "^1.0.8", optional = true}
51
+
52
+ [tool.poetry.group.dev.dependencies]
53
+ pre-commit = "^2.20.0"
54
+
55
+ [tool.poetry.group.atari]
56
+ optional = true
57
+ [tool.poetry.group.atari.dependencies]
58
+ ale-py = "0.7.4"
59
+ AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2"}
60
+ opencv-python = "^4.6.0.66"
61
+
62
+ [tool.poetry.group.pybullet]
63
+ optional = true
64
+ [tool.poetry.group.pybullet.dependencies]
65
+ pybullet = "3.1.8"
66
+
67
+ [tool.poetry.group.procgen]
68
+ optional = true
69
+ [tool.poetry.group.procgen.dependencies]
70
+ procgen = "^0.10.7"
71
+
72
+ [tool.poetry.group.pytest]
73
+ optional = true
74
+ [tool.poetry.group.pytest.dependencies]
75
+ pytest = "^7.1.3"
76
+
77
+ [tool.poetry.group.mujoco]
78
+ optional = true
79
+ [tool.poetry.group.mujoco.dependencies]
80
+ mujoco = "^2.2"
81
+ imageio = "^2.14.1"
82
+
83
+ [tool.poetry.group.mujoco_py]
84
+ optional = true
85
+ [tool.poetry.group.mujoco_py.dependencies]
86
+ free-mujoco-py = "^2.1.6"
87
+
88
+ [tool.poetry.group.docs]
89
+ optional = true
90
+ [tool.poetry.group.docs.dependencies]
91
+ mkdocs-material = "^8.4.3"
92
+ markdown-include = "^0.7.0"
93
+
94
+ [tool.poetry.group.jax]
95
+ optional = true
96
+ [tool.poetry.group.jax.dependencies]
97
+ jax = "^0.3.17"
98
+ jaxlib = "^0.3.15"
99
+ flax = "^0.6.0"
100
+
101
+ [tool.poetry.group.optuna]
102
+ optional = true
103
+ [tool.poetry.group.optuna.dependencies]
104
+ optuna = "^3.0.1"
105
+ optuna-dashboard = "^0.7.2"
106
+ rich = "<12.0"
107
+
108
+ [tool.poetry.group.envpool]
109
+ optional = true
110
+ [tool.poetry.group.envpool.dependencies]
111
+ envpool = "^0.8.1"
112
+
113
+ [tool.poetry.group.pettingzoo]
114
+ optional = true
115
+ [tool.poetry.group.pettingzoo.dependencies]
116
+ PettingZoo = "1.18.1"
117
+ SuperSuit = "3.4.0"
118
+ multi-agent-ale-py = "0.1.11"
119
+
120
+ [tool.poetry.group.cloud]
121
+ optional = true
122
+ [tool.poetry.group.cloud.dependencies]
123
+ boto3 = "^1.24.70"
124
+ awscli = "^1.25.71"
125
+
126
+ [tool.poetry.group.isaacgym]
127
+ optional = true
128
+ [tool.poetry.group.isaacgym.dependencies]
129
+ isaacgymenvs = {git = "https://github.com/vwxyzjn/IsaacGymEnvs.git", rev = "poetry"}
130
+ isaacgym = {path = "cleanrl/ppo_continuous_action_isaacgym/isaacgym", develop = true}
131
+
132
+ [tool.poetry.group.dm_control]
133
+ optional = true
134
+ [tool.poetry.group.dm_control.dependencies]
135
+ shimmy = "^0.1.0"
136
+ dm-control = "^1.0.8"
137
+ mujoco = "^2.2"
138
+
139
+ [build-system]
140
+ requires = ["poetry-core"]
141
+ build-backend = "poetry.core.masonry.api"
142
+
143
+ [tool.poetry.extras]
144
+ atari = ["ale-py", "AutoROM", "opencv-python"]
145
+ pybullet = ["pybullet"]
146
+ procgen = ["procgen"]
147
+ plot = ["pandas", "seaborn"]
148
+ pytest = ["pytest"]
149
+ mujoco = ["mujoco", "imageio"]
150
+ mujoco_py = ["free-mujoco-py"]
151
+ jax = ["jax", "jaxlib", "flax"]
152
+ docs = ["mkdocs-material", "markdown-include"]
153
+ envpool = ["envpool"]
154
+ optuna = ["optuna", "optuna-dashboard", "rich"]
155
+ pettingzoo = ["PettingZoo", "SuperSuit", "multi-agent-ale-py"]
156
+ cloud = ["boto3", "awscli"]
157
+ dm_control = ["shimmy", "dm-control", "mujoco"]
158
+
159
+ # dependencies for algorithm variant (useful when you want to run a specific algorithm)
160
+ dqn = []
161
+ dqn_atari = ["ale-py", "AutoROM", "opencv-python"]
162
+ dqn_jax = ["jax", "jaxlib", "flax"]
163
+ dqn_atari_jax = [
164
+ "ale-py", "AutoROM", "opencv-python", # atari
165
+ "jax", "jaxlib", "flax" # jax
166
+ ]
167
+ c51 = []
168
+ c51_atari = ["ale-py", "AutoROM", "opencv-python"]
169
+ c51_jax = ["jax", "jaxlib", "flax"]
170
+ c51_atari_jax = [
171
+ "ale-py", "AutoROM", "opencv-python", # atari
172
+ "jax", "jaxlib", "flax" # jax
173
+ ]
174
+ ppo_atari_envpool_xla_jax_scan = [
175
+ "ale-py", "AutoROM", "opencv-python", # atari
176
+ "jax", "jaxlib", "flax", # jax
177
+ "envpool", # envpool
178
+ ]
replay.mp4 ADDED
Binary file (362 kB). View file
 
sebulba_ppo_envpool_impala_atari_wrapper.cleanrl_model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa2cd94df306d08ecdc08fc31a57b921f6b256fc8d4a94fa327faafb693841f0
3
+ size 4363948
sebulba_ppo_envpool_impala_atari_wrapper.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * 🥼 Test throughput (see docs):
3
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 --profile --test-actor-learner-throughput --total-timesteps 500000 --track
4
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 2 --profile --test-actor-learner-throughput --total-timesteps 500000 --track
5
+ * this will help us diagnose the throughput issue
6
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --num-actor-threads 2 --learner-device-ids 1 --profile --test-actor-learner-throughput --total-timesteps 500000 --track
7
+ * 🔥 Best performance so far (more GPUs -> faster)
8
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 0 --track
9
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 0 1 --track
10
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 2 3 --track
11
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 2 3 4 --track
12
+ * python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 2 3 4 5 6 --track
13
+ * (this actually doesn't work that well) python sebulba_ppo_envpool.py --actor-device-ids 0 --learner-device-ids 1 2 3 4 5 6 7 --num-envs 70 --async-batch-size 35 --track
14
+ """
15
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_atari_envpool_async_jax_scan_impalanet_machadopy
16
+ import argparse
17
+ import os
18
+ import random
19
+ import time
20
+ import uuid
21
+ import warnings
22
+ from collections import deque
23
+ from distutils.util import strtobool
24
+ from functools import partial
25
+ from typing import Sequence
26
+
27
+ os.environ[
28
+ "XLA_PYTHON_CLIENT_MEM_FRACTION"
29
+ ] = "0.6" # see https://github.com/google/jax/discussions/6332#discussioncomment-1279991
30
+ os.environ["XLA_FLAGS"] = "--xla_cpu_multi_thread_eigen=false " "intra_op_parallelism_threads=1"
31
+ import multiprocessing as mp
32
+ import queue
33
+ import threading
34
+
35
+ import envpool
36
+ import flax
37
+ import flax.linen as nn
38
+ import gym
39
+ import jax
40
+ import jax.numpy as jnp
41
+ import numpy as np
42
+ import optax
43
+ from flax.linen.initializers import constant, orthogonal
44
+ from flax.training.train_state import TrainState
45
+ from torch.utils.tensorboard import SummaryWriter
46
+
47
+
48
+ def parse_args():
49
+ # fmt: off
50
+ parser = argparse.ArgumentParser()
51
+ parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
52
+ help="the name of this experiment")
53
+ parser.add_argument("--seed", type=int, default=1,
54
+ help="seed of the experiment")
55
+ parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
56
+ help="if toggled, `torch.backends.cudnn.deterministic=False`")
57
+ parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
58
+ help="if toggled, cuda will be enabled by default")
59
+ parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
60
+ help="if toggled, this experiment will be tracked with Weights and Biases")
61
+ parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
62
+ help="the wandb's project name")
63
+ parser.add_argument("--wandb-entity", type=str, default=None,
64
+ help="the entity (team) of wandb's project")
65
+ parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
66
+ help="weather to capture videos of the agent performances (check out `videos` folder)")
67
+ parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
68
+ help="whether to save model into the `runs/{run_name}` folder")
69
+ parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
70
+ help="whether to upload the saved model to huggingface")
71
+ parser.add_argument("--hf-entity", type=str, default="",
72
+ help="the user or org name of the model repository from the Hugging Face Hub")
73
+
74
+ # Algorithm specific arguments
75
+ parser.add_argument("--env-id", type=str, default="Breakout-v5",
76
+ help="the id of the environment")
77
+ parser.add_argument("--total-timesteps", type=int, default=50000000,
78
+ help="total timesteps of the experiments")
79
+ parser.add_argument("--learning-rate", type=float, default=2.5e-4,
80
+ help="the learning rate of the optimizer")
81
+ parser.add_argument("--num-envs", type=int, default=60,
82
+ help="the number of parallel game environments")
83
+ parser.add_argument("--async-batch-size", type=int, default=20,
84
+ help="the envpool's batch size in the async mode")
85
+ parser.add_argument("--num-steps", type=int, default=128,
86
+ help="the number of steps to run in each environment per policy rollout")
87
+ parser.add_argument("--anneal-lr", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
88
+ help="Toggle learning rate annealing for policy and value networks")
89
+ parser.add_argument("--gamma", type=float, default=0.99,
90
+ help="the discount factor gamma")
91
+ parser.add_argument("--gae-lambda", type=float, default=0.95,
92
+ help="the lambda for the general advantage estimation")
93
+ parser.add_argument("--num-minibatches", type=int, default=4,
94
+ help="the number of mini-batches")
95
+ parser.add_argument("--update-epochs", type=int, default=4,
96
+ help="the K epochs to update the policy")
97
+ parser.add_argument("--norm-adv", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
98
+ help="Toggles advantages normalization")
99
+ parser.add_argument("--clip-coef", type=float, default=0.1,
100
+ help="the surrogate clipping coefficient")
101
+ parser.add_argument("--ent-coef", type=float, default=0.01,
102
+ help="coefficient of the entropy")
103
+ parser.add_argument("--vf-coef", type=float, default=0.5,
104
+ help="coefficient of the value function")
105
+ parser.add_argument("--max-grad-norm", type=float, default=0.5,
106
+ help="the maximum norm for the gradient clipping")
107
+ parser.add_argument("--target-kl", type=float, default=None,
108
+ help="the target KL divergence threshold")
109
+
110
+ parser.add_argument("--actor-device-ids", type=int, nargs="+", default=[0], # type is actually List[int]
111
+ help="the device ids that actor workers will use")
112
+ parser.add_argument("--learner-device-ids", type=int, nargs="+", default=[0], # type is actually List[int]
113
+ help="the device ids that actor workers will use")
114
+ parser.add_argument("--num-actor-threads", type=int, default=1,
115
+ help="the number of actor threads")
116
+ parser.add_argument("--profile", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
117
+ help="whether to call block_until_ready() for profiling")
118
+ parser.add_argument("--test-actor-learner-throughput", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
119
+ help="whether to test actor-learner throughput by removing the actor-learner communication")
120
+ args = parser.parse_args()
121
+ args.batch_size = int(args.num_envs * args.num_steps)
122
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
123
+ args.num_updates = args.total_timesteps // args.batch_size
124
+ args.async_update = int(args.num_envs / args.async_batch_size)
125
+ assert len(args.actor_device_ids) == 1, "only 1 actor_device_ids is supported now"
126
+ if args.num_actor_threads > 1:
127
+ warnings.warn("⚠️ !!!! `num_actor_threads` > 1 is not tested with learning; see docs for detail")
128
+ # fmt: on
129
+ return args
130
+
131
+
132
+ ATARI_MAX_FRAMES = int(
133
+ 108000 / 4
134
+ ) # 108000 is the max number of frames in an Atari game, divided by 4 to account for frame skipping
135
+
136
+
137
+ def make_env(env_id, seed, num_envs, async_batch_size=1, num_threads=None, thread_affinity_offset=-1):
138
+ def thunk():
139
+ envs = envpool.make(
140
+ env_id,
141
+ env_type="gym",
142
+ num_envs=num_envs,
143
+ num_threads=num_threads if num_threads is not None else async_batch_size,
144
+ thread_affinity_offset=thread_affinity_offset,
145
+ batch_size=async_batch_size,
146
+ episodic_life=True, # Espeholt et al., 2018, Tab. G.1
147
+ repeat_action_probability=0, # Hessel et al., 2022 (Muesli) Tab. 10
148
+ noop_max=30, # Espeholt et al., 2018, Tab. C.1 "Up to 30 no-ops at the beginning of each episode."
149
+ full_action_space=False, # Espeholt et al., 2018, Appendix G., "Following related work, experts use game-specific action sets."
150
+ max_episode_steps=ATARI_MAX_FRAMES, # Hessel et al. 2018 (Rainbow DQN), Table 3, Max frames per episode
151
+ reward_clip=True,
152
+ seed=seed,
153
+ )
154
+ envs.num_envs = num_envs
155
+ envs.single_action_space = envs.action_space
156
+ envs.single_observation_space = envs.observation_space
157
+ envs.is_vector_env = True
158
+ return envs
159
+
160
+ return thunk
161
+
162
+
163
+ class ResidualBlock(nn.Module):
164
+ channels: int
165
+
166
+ @nn.compact
167
+ def __call__(self, x):
168
+ inputs = x
169
+ x = nn.relu(x)
170
+ x = nn.Conv(
171
+ self.channels,
172
+ kernel_size=(3, 3),
173
+ )(x)
174
+ x = nn.relu(x)
175
+ x = nn.Conv(
176
+ self.channels,
177
+ kernel_size=(3, 3),
178
+ )(x)
179
+ return x + inputs
180
+
181
+
182
+ class ConvSequence(nn.Module):
183
+ channels: int
184
+
185
+ @nn.compact
186
+ def __call__(self, x):
187
+ x = nn.Conv(
188
+ self.channels,
189
+ kernel_size=(3, 3),
190
+ )(x)
191
+ x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
192
+ x = ResidualBlock(self.channels)(x)
193
+ x = ResidualBlock(self.channels)(x)
194
+ return x
195
+
196
+
197
+ class Network(nn.Module):
198
+ channelss: Sequence[int] = (16, 32, 32)
199
+
200
+ @nn.compact
201
+ def __call__(self, x):
202
+ x = jnp.transpose(x, (0, 2, 3, 1))
203
+ x = x / (255.0)
204
+ for channels in self.channelss:
205
+ x = ConvSequence(channels)(x)
206
+ x = nn.relu(x)
207
+ x = x.reshape((x.shape[0], -1))
208
+ x = nn.Dense(256, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
209
+ x = nn.relu(x)
210
+ return x
211
+
212
+
213
+ class Critic(nn.Module):
214
+ @nn.compact
215
+ def __call__(self, x):
216
+ return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
217
+
218
+
219
+ class Actor(nn.Module):
220
+ action_dim: int
221
+
222
+ @nn.compact
223
+ def __call__(self, x):
224
+ return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
225
+
226
+
227
+ @flax.struct.dataclass
228
+ class AgentParams:
229
+ network_params: flax.core.FrozenDict
230
+ actor_params: flax.core.FrozenDict
231
+ critic_params: flax.core.FrozenDict
232
+
233
+
234
+ @partial(jax.jit, static_argnums=(3))
235
+ def get_action_and_value(
236
+ params: TrainState,
237
+ next_obs: np.ndarray,
238
+ key: jax.random.PRNGKey,
239
+ action_dim: int,
240
+ ):
241
+ hidden = Network().apply(params.network_params, next_obs)
242
+ logits = Actor(action_dim).apply(params.actor_params, hidden)
243
+ # sample action: Gumbel-softmax trick
244
+ # see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
245
+ key, subkey = jax.random.split(key)
246
+ u = jax.random.uniform(subkey, shape=logits.shape)
247
+ action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
248
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
249
+ value = Critic().apply(params.critic_params, hidden)
250
+ return action, logprob, value.squeeze(), key
251
+
252
+
253
+ @jax.jit
254
+ def prepare_data(
255
+ obs: list,
256
+ dones: list,
257
+ values: list,
258
+ actions: list,
259
+ logprobs: list,
260
+ env_ids: list,
261
+ rewards: list,
262
+ ):
263
+ obs = jnp.asarray(obs)
264
+ dones = jnp.asarray(dones)
265
+ values = jnp.asarray(values)
266
+ actions = jnp.asarray(actions)
267
+ logprobs = jnp.asarray(logprobs)
268
+ env_ids = jnp.asarray(env_ids)
269
+ rewards = jnp.asarray(rewards)
270
+
271
+ # TODO: in an unlikely event, one of the envs might have not stepped at all, which may results in unexpected behavior
272
+ T, B = env_ids.shape
273
+ index_ranges = jnp.arange(T * B, dtype=jnp.int32)
274
+ next_index_ranges = jnp.zeros_like(index_ranges, dtype=jnp.int32)
275
+ last_env_ids = jnp.zeros(args.num_envs, dtype=jnp.int32) - 1
276
+
277
+ def f(carry, x):
278
+ last_env_ids, next_index_ranges = carry
279
+ env_id, index_range = x
280
+ next_index_ranges = next_index_ranges.at[last_env_ids[env_id]].set(
281
+ jnp.where(last_env_ids[env_id] != -1, index_range, next_index_ranges[last_env_ids[env_id]])
282
+ )
283
+ last_env_ids = last_env_ids.at[env_id].set(index_range)
284
+ return (last_env_ids, next_index_ranges), None
285
+
286
+ (last_env_ids, next_index_ranges), _ = jax.lax.scan(
287
+ f,
288
+ (last_env_ids, next_index_ranges),
289
+ (env_ids.reshape(-1), index_ranges),
290
+ )
291
+
292
+ # rewards is off by one time step
293
+ rewards = rewards.reshape(-1)[next_index_ranges].reshape((args.num_steps) * args.async_update, args.async_batch_size)
294
+ advantages, returns, _, final_env_ids = compute_gae(env_ids, rewards, values, dones)
295
+ # b_inds = jnp.nonzero(final_env_ids.reshape(-1), size=(args.num_steps) * args.async_update * args.async_batch_size)[0] # useful for debugging
296
+ b_obs = obs.reshape((-1,) + obs.shape[2:])
297
+ b_actions = actions.reshape(-1)
298
+ b_logprobs = logprobs.reshape(-1)
299
+ b_advantages = advantages.reshape(-1)
300
+ b_returns = returns.reshape(-1)
301
+ return b_obs, b_actions, b_logprobs, b_advantages, b_returns
302
+
303
+
304
+ def rollout(
305
+ i,
306
+ num_threads, # =None,
307
+ thread_affinity_offset, # =-1,
308
+ key: jax.random.PRNGKey,
309
+ args,
310
+ rollout_queue,
311
+ params_queue: queue.Queue,
312
+ writer,
313
+ learner_devices,
314
+ ):
315
+ envs = make_env(args.env_id, args.seed, args.num_envs, args.async_batch_size, num_threads, thread_affinity_offset)()
316
+ len_actor_device_ids = len(args.actor_device_ids)
317
+ global_step = 0
318
+ # TRY NOT TO MODIFY: start the game
319
+ start_time = time.time()
320
+
321
+ # put data in the last index
322
+ episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
323
+ returned_episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
324
+ episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
325
+ returned_episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
326
+ envs.async_reset()
327
+
328
+ params_queue_get_time = deque(maxlen=10)
329
+ rollout_time = deque(maxlen=10)
330
+ data_transfer_time = deque(maxlen=10)
331
+ rollout_queue_put_time = deque(maxlen=10)
332
+ actor_policy_version = 0
333
+ for update in range(1, args.num_updates + 2):
334
+ # NOTE: This is a major difference from the sync version:
335
+ # at the end of the rollout phase, the sync version will have the next observation
336
+ # ready for the value bootstrap, but the async version will not have it.
337
+ # for this reason we do `num_steps + 1`` to get the extra states for value bootstrapping.
338
+ # but note that the extra states are not used for the loss computation in the next iteration,
339
+ # while the sync version will use the extra state for the loss computation.
340
+ update_time_start = time.time()
341
+ obs = []
342
+ dones = []
343
+ actions = []
344
+ logprobs = []
345
+ values = []
346
+ env_ids = []
347
+ rewards = []
348
+ truncations = []
349
+ terminations = []
350
+ env_recv_time = 0
351
+ inference_time = 0
352
+ storage_time = 0
353
+ env_send_time = 0
354
+
355
+ # NOTE: `update != 2` is actually IMPORTANT — it allows us to start running policy collection
356
+ # concurrently with the learning process. It also ensures the actor's policy version is only 1 step
357
+ # behind the learner's policy version
358
+ params_queue_get_time_start = time.time()
359
+ if update != 2:
360
+ params = params_queue.get()
361
+ actor_policy_version += 1
362
+ params_queue_get_time.append(time.time() - params_queue_get_time_start)
363
+ writer.add_scalar("stats/params_queue_get_time", np.mean(params_queue_get_time), global_step)
364
+ rollout_time_start = time.time()
365
+ for _ in range(
366
+ args.async_update, (args.num_steps + 1) * args.async_update
367
+ ): # num_steps + 1 to get the states for value bootstrapping.
368
+ env_recv_time_start = time.time()
369
+ next_obs, next_reward, next_done, info = envs.recv()
370
+ env_recv_time += time.time() - env_recv_time_start
371
+ global_step += len(next_done) * args.num_actor_threads * len_actor_device_ids
372
+ env_id = info["env_id"]
373
+
374
+ inference_time_start = time.time()
375
+ action, logprob, value, key = get_action_and_value(params, next_obs, key, envs.single_action_space.n)
376
+ inference_time += time.time() - inference_time_start
377
+
378
+ env_send_time_start = time.time()
379
+ envs.send(np.array(action), env_id)
380
+ env_send_time += time.time() - env_send_time_start
381
+ storage_time_start = time.time()
382
+ obs.append(next_obs)
383
+ dones.append(next_done)
384
+ values.append(value)
385
+ actions.append(action)
386
+ logprobs.append(logprob)
387
+ env_ids.append(env_id)
388
+ rewards.append(next_reward)
389
+
390
+ # info["TimeLimit.truncated"] has a bug https://github.com/sail-sg/envpool/issues/239
391
+ # so we use our own truncated flag
392
+ truncated = info["elapsed_step"] >= ATARI_MAX_FRAMES
393
+ truncations.append(truncated)
394
+ terminations.append(info["terminated"])
395
+ episode_returns[env_id] += info["reward"]
396
+ returned_episode_returns[env_id] = np.where(
397
+ info["terminated"] + truncated, episode_returns[env_id], returned_episode_returns[env_id]
398
+ )
399
+ episode_returns[env_id] *= (1 - info["terminated"]) * (1 - truncated)
400
+ episode_lengths[env_id] += 1
401
+ returned_episode_lengths[env_id] = np.where(
402
+ info["terminated"] + truncated, episode_lengths[env_id], returned_episode_lengths[env_id]
403
+ )
404
+ episode_lengths[env_id] *= (1 - info["terminated"]) * (1 - truncated)
405
+ storage_time += time.time() - storage_time_start
406
+ if args.profile:
407
+ action.block_until_ready()
408
+ rollout_time.append(time.time() - rollout_time_start)
409
+ writer.add_scalar("stats/rollout_time", np.mean(rollout_time), global_step)
410
+
411
+ avg_episodic_return = np.mean(returned_episode_returns)
412
+ writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
413
+ writer.add_scalar("charts/avg_episodic_length", np.mean(returned_episode_lengths), global_step)
414
+ if i == 0:
415
+ print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
416
+ print("SPS:", int(global_step / (time.time() - start_time)))
417
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
418
+
419
+ writer.add_scalar("stats/truncations", np.sum(truncations), global_step)
420
+ writer.add_scalar("stats/terminations", np.sum(terminations), global_step)
421
+ writer.add_scalar("stats/env_recv_time", env_recv_time, global_step)
422
+ writer.add_scalar("stats/inference_time", inference_time, global_step)
423
+ writer.add_scalar("stats/storage_time", storage_time, global_step)
424
+ writer.add_scalar("stats/env_send_time", env_send_time, global_step)
425
+
426
+ data_transfer_time_start = time.time()
427
+ b_obs, b_actions, b_logprobs, b_advantages, b_returns = prepare_data(
428
+ obs,
429
+ dones,
430
+ values,
431
+ actions,
432
+ logprobs,
433
+ env_ids,
434
+ rewards,
435
+ )
436
+ payload = (
437
+ global_step,
438
+ actor_policy_version,
439
+ update,
440
+ jnp.array_split(b_obs, len(learner_devices)),
441
+ jnp.array_split(b_actions, len(learner_devices)),
442
+ jnp.array_split(b_logprobs, len(learner_devices)),
443
+ jnp.array_split(b_advantages, len(learner_devices)),
444
+ jnp.array_split(b_returns, len(learner_devices)),
445
+ )
446
+ if args.profile:
447
+ payload[2][0].block_until_ready()
448
+ data_transfer_time.append(time.time() - data_transfer_time_start)
449
+ writer.add_scalar("stats/data_transfer_time", np.mean(data_transfer_time), global_step)
450
+ if update == 1 or not args.test_actor_learner_throughput:
451
+ rollout_queue_put_time_start = time.time()
452
+ rollout_queue.put(payload)
453
+ rollout_queue_put_time.append(time.time() - rollout_queue_put_time_start)
454
+ writer.add_scalar("stats/rollout_queue_put_time", np.mean(rollout_queue_put_time), global_step)
455
+
456
+ writer.add_scalar(
457
+ "charts/SPS_update",
458
+ int(
459
+ args.num_envs
460
+ * args.num_steps
461
+ * args.num_actor_threads
462
+ * len_actor_device_ids
463
+ / (time.time() - update_time_start)
464
+ ),
465
+ global_step,
466
+ )
467
+
468
+
469
+ @partial(jax.jit, static_argnums=(3))
470
+ def get_action_and_value2(
471
+ params: flax.core.FrozenDict,
472
+ x: np.ndarray,
473
+ action: np.ndarray,
474
+ action_dim: int,
475
+ ):
476
+ hidden = Network().apply(params.network_params, x)
477
+ logits = Actor(action_dim).apply(params.actor_params, hidden)
478
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
479
+ logits = logits - jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True)
480
+ logits = logits.clip(min=jnp.finfo(logits.dtype).min)
481
+ p_log_p = logits * jax.nn.softmax(logits)
482
+ entropy = -p_log_p.sum(-1)
483
+ value = Critic().apply(params.critic_params, hidden).squeeze()
484
+ return logprob, entropy, value
485
+
486
+
487
+ @jax.jit
488
+ def compute_gae(
489
+ env_ids: np.ndarray,
490
+ rewards: np.ndarray,
491
+ values: np.ndarray,
492
+ dones: np.ndarray,
493
+ ):
494
+ dones = jnp.asarray(dones)
495
+ values = jnp.asarray(values)
496
+ env_ids = jnp.asarray(env_ids)
497
+ rewards = jnp.asarray(rewards)
498
+
499
+ _, B = env_ids.shape
500
+ final_env_id_checked = jnp.zeros(args.num_envs, jnp.int32) - 1
501
+ final_env_ids = jnp.zeros(B, jnp.int32)
502
+ advantages = jnp.zeros(B)
503
+ lastgaelam = jnp.zeros(args.num_envs)
504
+ lastdones = jnp.zeros(args.num_envs) + 1
505
+ lastvalues = jnp.zeros(args.num_envs)
506
+
507
+ def compute_gae_once(carry, x):
508
+ lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked = carry
509
+ (
510
+ done,
511
+ value,
512
+ eid,
513
+ reward,
514
+ ) = x
515
+ nextnonterminal = 1.0 - lastdones[eid]
516
+ nextvalues = lastvalues[eid]
517
+ delta = jnp.where(final_env_id_checked[eid] == -1, 0, reward + args.gamma * nextvalues * nextnonterminal - value)
518
+ advantages = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam[eid]
519
+ final_env_ids = jnp.where(final_env_id_checked[eid] == 1, 1, 0)
520
+ final_env_id_checked = final_env_id_checked.at[eid].set(
521
+ jnp.where(final_env_id_checked[eid] == -1, 1, final_env_id_checked[eid])
522
+ )
523
+
524
+ # the last_ variables keeps track of the actual `num_steps`
525
+ lastgaelam = lastgaelam.at[eid].set(advantages)
526
+ lastdones = lastdones.at[eid].set(done)
527
+ lastvalues = lastvalues.at[eid].set(value)
528
+ return (lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked), (
529
+ advantages,
530
+ final_env_ids,
531
+ )
532
+
533
+ (_, _, _, _, final_env_ids, final_env_id_checked), (advantages, final_env_ids) = jax.lax.scan(
534
+ compute_gae_once,
535
+ (
536
+ lastvalues,
537
+ lastdones,
538
+ advantages,
539
+ lastgaelam,
540
+ final_env_ids,
541
+ final_env_id_checked,
542
+ ),
543
+ (
544
+ dones,
545
+ values,
546
+ env_ids,
547
+ rewards,
548
+ ),
549
+ reverse=True,
550
+ )
551
+ return advantages, advantages + values, final_env_id_checked, final_env_ids
552
+
553
+
554
+ def ppo_loss(params, x, a, logp, mb_advantages, mb_returns, action_dim):
555
+ newlogprob, entropy, newvalue = get_action_and_value2(params, x, a, action_dim)
556
+ logratio = newlogprob - logp
557
+ ratio = jnp.exp(logratio)
558
+ approx_kl = ((ratio - 1) - logratio).mean()
559
+
560
+ if args.norm_adv:
561
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
562
+
563
+ # Policy loss
564
+ pg_loss1 = -mb_advantages * ratio
565
+ pg_loss2 = -mb_advantages * jnp.clip(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
566
+ pg_loss = jnp.maximum(pg_loss1, pg_loss2).mean()
567
+
568
+ # Value loss
569
+ v_loss = 0.5 * ((newvalue - mb_returns) ** 2).mean()
570
+
571
+ entropy_loss = entropy.mean()
572
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
573
+ return loss, (pg_loss, v_loss, entropy_loss, jax.lax.stop_gradient(approx_kl))
574
+
575
+
576
+ @partial(jax.jit, static_argnums=(6))
577
+ def single_device_update(
578
+ agent_state: TrainState,
579
+ b_obs,
580
+ b_actions,
581
+ b_logprobs,
582
+ b_advantages,
583
+ b_returns,
584
+ action_dim,
585
+ key: jax.random.PRNGKey,
586
+ ):
587
+ ppo_loss_grad_fn = jax.value_and_grad(ppo_loss, has_aux=True)
588
+
589
+ def update_epoch(carry, _):
590
+ agent_state, key = carry
591
+ key, subkey = jax.random.split(key)
592
+
593
+ # taken from: https://github.com/google/brax/blob/main/brax/training/agents/ppo/train.py
594
+ def convert_data(x: jnp.ndarray):
595
+ x = jax.random.permutation(subkey, x)
596
+ x = jnp.reshape(x, (args.num_minibatches, -1) + x.shape[1:])
597
+ return x
598
+
599
+ def update_minibatch(agent_state, minibatch):
600
+ mb_obs, mb_actions, mb_logprobs, mb_advantages, mb_returns = minibatch
601
+ (loss, (pg_loss, v_loss, entropy_loss, approx_kl)), grads = ppo_loss_grad_fn(
602
+ agent_state.params,
603
+ mb_obs,
604
+ mb_actions,
605
+ mb_logprobs,
606
+ mb_advantages,
607
+ mb_returns,
608
+ action_dim,
609
+ )
610
+ grads = jax.lax.pmean(grads, axis_name="devices")
611
+ agent_state = agent_state.apply_gradients(grads=grads)
612
+ return agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
613
+
614
+ agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads) = jax.lax.scan(
615
+ update_minibatch,
616
+ agent_state,
617
+ (
618
+ convert_data(b_obs),
619
+ convert_data(b_actions),
620
+ convert_data(b_logprobs),
621
+ convert_data(b_advantages),
622
+ convert_data(b_returns),
623
+ ),
624
+ )
625
+ return (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
626
+
627
+ (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, _) = jax.lax.scan(
628
+ update_epoch, (agent_state, key), (), length=args.update_epochs
629
+ )
630
+ return agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key
631
+
632
+
633
+ if __name__ == "__main__":
634
+ devices = jax.devices("gpu")
635
+ args = parse_args()
636
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{uuid.uuid4()}"
637
+ if args.track:
638
+ import wandb
639
+
640
+ wandb.init(
641
+ project=args.wandb_project_name,
642
+ entity=args.wandb_entity,
643
+ sync_tensorboard=True,
644
+ config=vars(args),
645
+ name=run_name,
646
+ monitor_gym=True,
647
+ save_code=True,
648
+ )
649
+ print(devices)
650
+ writer = SummaryWriter(f"runs/{run_name}")
651
+ writer.add_text(
652
+ "hyperparameters",
653
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
654
+ )
655
+
656
+ # TRY NOT TO MODIFY: seeding
657
+ random.seed(args.seed)
658
+ np.random.seed(args.seed)
659
+ key = jax.random.PRNGKey(args.seed)
660
+ key, network_key, actor_key, critic_key = jax.random.split(key, 4)
661
+
662
+ # env setup
663
+ envs = make_env(args.env_id, args.seed, args.num_envs, args.async_batch_size)()
664
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
665
+
666
+ def linear_schedule(count):
667
+ # anneal learning rate linearly after one training iteration which contains
668
+ # (args.num_minibatches * args.update_epochs) gradient updates
669
+ frac = 1.0 - (count // (args.num_minibatches * args.update_epochs)) / args.num_updates
670
+ return args.learning_rate * frac
671
+
672
+ network = Network()
673
+ actor = Actor(action_dim=envs.single_action_space.n)
674
+ critic = Critic()
675
+ network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
676
+ agent_state = TrainState.create(
677
+ apply_fn=None,
678
+ params=AgentParams(
679
+ network_params,
680
+ actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
681
+ critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
682
+ ),
683
+ tx=optax.chain(
684
+ optax.clip_by_global_norm(args.max_grad_norm),
685
+ optax.inject_hyperparams(optax.adam)(
686
+ learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
687
+ ),
688
+ ),
689
+ )
690
+ learner_devices = [devices[d_id] for d_id in args.learner_device_ids]
691
+ actor_devices = [devices[d_id] for d_id in args.actor_device_ids]
692
+ agent_state = flax.jax_utils.replicate(agent_state, devices=learner_devices)
693
+
694
+ multi_device_update = jax.pmap(
695
+ single_device_update,
696
+ axis_name="devices",
697
+ devices=learner_devices,
698
+ in_axes=(0, 0, 0, 0, 0, 0, None, None),
699
+ out_axes=(0, 0, 0, 0, 0, 0, None),
700
+ static_broadcasted_argnums=(6),
701
+ )
702
+
703
+ rollout_queue = queue.Queue(maxsize=1)
704
+ params_queues = []
705
+ num_cpus = mp.cpu_count()
706
+ fair_num_cpus = num_cpus // len(args.actor_device_ids)
707
+
708
+ class DummyWriter:
709
+ def add_scalar(self, arg0, arg1, arg3):
710
+ pass
711
+
712
+ dummy_writer = DummyWriter()
713
+ for d_idx, d_id in enumerate(args.actor_device_ids):
714
+ for j in range(args.num_actor_threads):
715
+ params_queue = queue.Queue(maxsize=1)
716
+ params_queue.put(jax.device_put(flax.jax_utils.unreplicate(agent_state.params), devices[d_id]))
717
+ threading.Thread(
718
+ target=rollout,
719
+ args=(
720
+ j,
721
+ fair_num_cpus if args.num_actor_threads > 1 else None,
722
+ j * args.num_actor_threads if args.num_actor_threads > 1 else -1,
723
+ jax.device_put(key, devices[d_id]),
724
+ args,
725
+ rollout_queue,
726
+ params_queue,
727
+ writer if d_idx == 0 and j == 0 else dummy_writer,
728
+ learner_devices,
729
+ ),
730
+ ).start()
731
+ params_queues.append(params_queue)
732
+
733
+ rollout_queue_get_time = deque(maxlen=10)
734
+ learner_policy_version = 0
735
+ while True:
736
+ learner_policy_version += 1
737
+ if learner_policy_version == 1 or not args.test_actor_learner_throughput:
738
+ rollout_queue_get_time_start = time.time()
739
+ (
740
+ global_step,
741
+ actor_policy_version,
742
+ update,
743
+ b_obs,
744
+ b_actions,
745
+ b_logprobs,
746
+ b_advantages,
747
+ b_returns,
748
+ ) = rollout_queue.get()
749
+ rollout_queue_get_time.append(time.time() - rollout_queue_get_time_start)
750
+ writer.add_scalar("stats/rollout_queue_get_time", np.mean(rollout_queue_get_time), global_step)
751
+
752
+ training_time_start = time.time()
753
+ (agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key) = multi_device_update(
754
+ agent_state,
755
+ jax.device_put_sharded(b_obs, learner_devices),
756
+ jax.device_put_sharded(b_actions, learner_devices),
757
+ jax.device_put_sharded(b_logprobs, learner_devices),
758
+ jax.device_put_sharded(b_advantages, learner_devices),
759
+ jax.device_put_sharded(b_returns, learner_devices),
760
+ envs.single_action_space.n,
761
+ key,
762
+ )
763
+ if learner_policy_version == 1 or not args.test_actor_learner_throughput:
764
+ for d_idx, d_id in enumerate(args.actor_device_ids):
765
+ for j in range(args.num_actor_threads):
766
+ params_queues[d_idx * args.num_actor_threads + j].put(
767
+ jax.device_put(flax.jax_utils.unreplicate(agent_state.params), devices[d_id])
768
+ )
769
+ if args.profile:
770
+ v_loss[-1, -1, -1].block_until_ready()
771
+ writer.add_scalar("stats/training_time", time.time() - training_time_start, global_step)
772
+ writer.add_scalar("stats/rollout_queue_size", rollout_queue.qsize(), global_step)
773
+ writer.add_scalar("stats/params_queue_size", params_queue.qsize(), global_step)
774
+ print(
775
+ global_step,
776
+ f"actor_policy_version={actor_policy_version}, actor_update={update}, learner_policy_version={learner_policy_version}, training time: {time.time() - training_time_start}s",
777
+ )
778
+
779
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
780
+ writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"][0].item(), global_step)
781
+ writer.add_scalar("losses/value_loss", v_loss[-1, -1, -1].item(), global_step)
782
+ writer.add_scalar("losses/policy_loss", pg_loss[-1, -1, -1].item(), global_step)
783
+ writer.add_scalar("losses/entropy", entropy_loss[-1, -1, -1].item(), global_step)
784
+ writer.add_scalar("losses/approx_kl", approx_kl[-1, -1, -1].item(), global_step)
785
+ writer.add_scalar("losses/loss", loss[-1, -1, -1].item(), global_step)
786
+ if update >= args.num_updates:
787
+ break
788
+
789
+ if args.save_model:
790
+ agent_state = flax.jax_utils.unreplicate(agent_state)
791
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
792
+ with open(model_path, "wb") as f:
793
+ f.write(
794
+ flax.serialization.to_bytes(
795
+ [
796
+ vars(args),
797
+ [
798
+ agent_state.params.network_params,
799
+ agent_state.params.actor_params,
800
+ agent_state.params.critic_params,
801
+ ],
802
+ ]
803
+ )
804
+ )
805
+ print(f"model saved to {model_path}")
806
+ from cleanrl_utils.evals.ppo_envpool_jax_eval import evaluate
807
+
808
+ episodic_returns = evaluate(
809
+ model_path,
810
+ make_env,
811
+ args.env_id,
812
+ eval_episodes=10,
813
+ run_name=f"{run_name}-eval",
814
+ Model=(Network, Actor, Critic),
815
+ )
816
+ for idx, episodic_return in enumerate(episodic_returns):
817
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
818
+
819
+ if args.upload_model:
820
+ from cleanrl_utils.huggingface import push_to_hub
821
+
822
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
823
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
824
+ push_to_hub(
825
+ args,
826
+ episodic_returns,
827
+ repo_id,
828
+ "PPO",
829
+ f"runs/{run_name}",
830
+ f"videos/{run_name}-eval",
831
+ extra_dependencies=["jax", "envpool", "atari"],
832
+ )
833
+
834
+ envs.close()
835
+ writer.close()
videos/Breakout-v5__sebulba_ppo_envpool_impala_atari_wrapper__3__182b3023-d4cb-4eec-8816-5920632a2e91-eval/0.mp4 ADDED
Binary file (362 kB). View file