vwxyzjn commited on
Commit
76ba6cc
1 Parent(s): ff73c5c

pushing model

Browse files
.gitattributes CHANGED
@@ -32,3 +32,6 @@ 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
+ videos/UpNDown-v5__sebulba_ppo_envpool_impala_atari_wrapper__2__c47264a3-10ad-4b79-bf69-4c29d56a060c-eval/0.mp4 filter=lfs diff=lfs merge=lfs -text
36
+ replay.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ 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
+ - UpNDown-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: UpNDown-v5
16
+ type: UpNDown-v5
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 355034.00 +/- 8475.42
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # (CleanRL) **PPO** Agent Playing **UpNDown-v5**
25
+
26
+ This is a trained model of a PPO agent playing UpNDown-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 UpNDown-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/UpNDown-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed2/raw/main/sebulba_ppo_envpool.py
46
+ curl -OL https://huggingface.co/cleanrl/UpNDown-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed2/raw/main/pyproject.toml
47
+ curl -OL https://huggingface.co/cleanrl/UpNDown-v5-sebulba_ppo_envpool_impala_atari_wrapper-seed2/raw/main/poetry.lock
48
+ poetry install --all-extras
49
+ python sebulba_ppo_envpool.py --exp-name sebulba_ppo_envpool_impala_atari_wrapper --actor-device-ids 0 --learner-device-ids 1 2 3 4 --track --save-model --upload-model --hf-entity cleanrl --env-id UpNDown-v5 --seed 2
50
+ ```
51
+
52
+ # Hyperparameters
53
+ ```python
54
+ {'actor_device_ids': [0],
55
+ 'anneal_lr': True,
56
+ 'async_batch_size': 16,
57
+ 'async_update': 4,
58
+ 'batch_size': 8192,
59
+ 'capture_video': False,
60
+ 'clip_coef': 0.1,
61
+ 'cuda': True,
62
+ 'ent_coef': 0.01,
63
+ 'env_id': 'UpNDown-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],
69
+ 'learning_rate': 0.00025,
70
+ 'max_grad_norm': 0.5,
71
+ 'minibatch_size': 2048,
72
+ 'norm_adv': True,
73
+ 'num_actor_threads': 1,
74
+ 'num_envs': 64,
75
+ 'num_minibatches': 4,
76
+ 'num_steps': 128,
77
+ 'num_updates': 6103,
78
+ 'profile': False,
79
+ 'save_model': True,
80
+ 'seed': 2,
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.1675909602.ip-26-0-141-11.180878.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e84f94c323c1b68428fd20cca2074e2d553d58d34a6c09246839be2ce560864e
3
+ size 8912676
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 <[email protected]>"]
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
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82ba356b95101ba79aec7ef50b78915412f4445f2384b78ef196a8b53e8d8fa0
3
+ size 4162466
sebulba_ppo_envpool.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 --num-envs 60 --async-batch-size 20 --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 --num-envs 60 --async-batch-size 20 --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=64,
82
+ help="the number of parallel game environments")
83
+ parser.add_argument("--async-batch-size", type=int, default=16,
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
+ def make_env(env_id, seed, num_envs, async_batch_size=1, num_threads=None, thread_affinity_offset=-1):
133
+ def thunk():
134
+ envs = envpool.make(
135
+ env_id,
136
+ env_type="gym",
137
+ num_envs=num_envs,
138
+ num_threads=num_threads if num_threads is not None else async_batch_size,
139
+ thread_affinity_offset=thread_affinity_offset,
140
+ batch_size=async_batch_size,
141
+ episodic_life=True, # Espeholt et al., 2018, Tab. G.1
142
+ repeat_action_probability=0, # Hessel et al., 2022 (Muesli) Tab. 10
143
+ noop_max=30, # Espeholt et al., 2018, Tab. C.1 "Up to 30 no-ops at the beginning of each episode."
144
+ full_action_space=False, # Espeholt et al., 2018, Appendix G., "Following related work, experts use game-specific action sets."
145
+ max_episode_steps=int(108000 / 4), # Hessel et al. 2018 (Rainbow DQN), Table 3, Max frames per episode
146
+ reward_clip=True,
147
+ seed=seed,
148
+ )
149
+ envs.num_envs = num_envs
150
+ envs.single_action_space = envs.action_space
151
+ envs.single_observation_space = envs.observation_space
152
+ envs.is_vector_env = True
153
+ return envs
154
+
155
+ return thunk
156
+
157
+
158
+ class ResidualBlock(nn.Module):
159
+ channels: int
160
+
161
+ @nn.compact
162
+ def __call__(self, x):
163
+ inputs = x
164
+ x = nn.relu(x)
165
+ x = nn.Conv(
166
+ self.channels,
167
+ kernel_size=(3, 3),
168
+ )(x)
169
+ x = nn.relu(x)
170
+ x = nn.Conv(
171
+ self.channels,
172
+ kernel_size=(3, 3),
173
+ )(x)
174
+ return x + inputs
175
+
176
+
177
+ class ConvSequence(nn.Module):
178
+ channels: int
179
+
180
+ @nn.compact
181
+ def __call__(self, x):
182
+ x = nn.Conv(
183
+ self.channels,
184
+ kernel_size=(3, 3),
185
+ )(x)
186
+ x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
187
+ x = ResidualBlock(self.channels)(x)
188
+ x = ResidualBlock(self.channels)(x)
189
+ return x
190
+
191
+
192
+ class Network(nn.Module):
193
+ channelss: Sequence[int] = (16, 32, 32)
194
+
195
+ @nn.compact
196
+ def __call__(self, x):
197
+ x = jnp.transpose(x, (0, 2, 3, 1))
198
+ x = x / (255.0)
199
+ for channels in self.channelss:
200
+ x = ConvSequence(channels)(x)
201
+ x = nn.relu(x)
202
+ x = x.reshape((x.shape[0], -1))
203
+ x = nn.Dense(256, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
204
+ x = nn.relu(x)
205
+ return x
206
+
207
+
208
+ class Critic(nn.Module):
209
+ @nn.compact
210
+ def __call__(self, x):
211
+ return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
212
+
213
+
214
+ class Actor(nn.Module):
215
+ action_dim: int
216
+
217
+ @nn.compact
218
+ def __call__(self, x):
219
+ return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
220
+
221
+
222
+ @flax.struct.dataclass
223
+ class AgentParams:
224
+ network_params: flax.core.FrozenDict
225
+ actor_params: flax.core.FrozenDict
226
+ critic_params: flax.core.FrozenDict
227
+
228
+
229
+ @partial(jax.jit, static_argnums=(3))
230
+ def get_action_and_value(
231
+ params: TrainState,
232
+ next_obs: np.ndarray,
233
+ key: jax.random.PRNGKey,
234
+ action_dim: int,
235
+ ):
236
+ hidden = Network().apply(params.network_params, next_obs)
237
+ logits = Actor(action_dim).apply(params.actor_params, hidden)
238
+ # sample action: Gumbel-softmax trick
239
+ # see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
240
+ key, subkey = jax.random.split(key)
241
+ u = jax.random.uniform(subkey, shape=logits.shape)
242
+ action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
243
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
244
+ value = Critic().apply(params.critic_params, hidden)
245
+ return action, logprob, value.squeeze(), key
246
+
247
+
248
+ @jax.jit
249
+ def prepare_data(
250
+ obs: list,
251
+ dones: list,
252
+ values: list,
253
+ actions: list,
254
+ logprobs: list,
255
+ env_ids: list,
256
+ rewards: list,
257
+ ):
258
+ obs = jnp.asarray(obs)
259
+ dones = jnp.asarray(dones)
260
+ values = jnp.asarray(values)
261
+ actions = jnp.asarray(actions)
262
+ logprobs = jnp.asarray(logprobs)
263
+ env_ids = jnp.asarray(env_ids)
264
+ rewards = jnp.asarray(rewards)
265
+
266
+ # TODO: in an unlikely event, one of the envs might have not stepped at all, which may results in unexpected behavior
267
+ T, B = env_ids.shape
268
+ index_ranges = jnp.arange(T * B, dtype=jnp.int32)
269
+ next_index_ranges = jnp.zeros_like(index_ranges, dtype=jnp.int32)
270
+ last_env_ids = jnp.zeros(args.num_envs, dtype=jnp.int32) - 1
271
+
272
+ def f(carry, x):
273
+ last_env_ids, next_index_ranges = carry
274
+ env_id, index_range = x
275
+ next_index_ranges = next_index_ranges.at[last_env_ids[env_id]].set(
276
+ jnp.where(last_env_ids[env_id] != -1, index_range, next_index_ranges[last_env_ids[env_id]])
277
+ )
278
+ last_env_ids = last_env_ids.at[env_id].set(index_range)
279
+ return (last_env_ids, next_index_ranges), None
280
+
281
+ (last_env_ids, next_index_ranges), _ = jax.lax.scan(
282
+ f,
283
+ (last_env_ids, next_index_ranges),
284
+ (env_ids.reshape(-1), index_ranges),
285
+ )
286
+
287
+ # rewards is off by one time step
288
+ rewards = rewards.reshape(-1)[next_index_ranges].reshape((args.num_steps) * args.async_update, args.async_batch_size)
289
+ advantages, returns, _, final_env_ids = compute_gae(env_ids, rewards, values, dones)
290
+ # b_inds = jnp.nonzero(final_env_ids.reshape(-1), size=(args.num_steps) * args.async_update * args.async_batch_size)[0] # useful for debugging
291
+ b_obs = obs.reshape((-1,) + obs.shape[2:])
292
+ b_actions = actions.reshape(-1)
293
+ b_logprobs = logprobs.reshape(-1)
294
+ b_advantages = advantages.reshape(-1)
295
+ b_returns = returns.reshape(-1)
296
+ return b_obs, b_actions, b_logprobs, b_advantages, b_returns
297
+
298
+
299
+ def rollout(
300
+ i,
301
+ num_threads, # =None,
302
+ thread_affinity_offset, # =-1,
303
+ key: jax.random.PRNGKey,
304
+ args,
305
+ rollout_queue,
306
+ params_queue: queue.Queue,
307
+ writer,
308
+ learner_devices,
309
+ ):
310
+ envs = make_env(args.env_id, args.seed, args.num_envs, args.async_batch_size, num_threads, thread_affinity_offset)()
311
+ len_actor_device_ids = len(args.actor_device_ids)
312
+ global_step = 0
313
+ # TRY NOT TO MODIFY: start the game
314
+ start_time = time.time()
315
+
316
+ # put data in the last index
317
+ episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
318
+ returned_episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
319
+ episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
320
+ returned_episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
321
+ envs.async_reset()
322
+
323
+ params_queue_get_time = deque(maxlen=10)
324
+ rollout_time = deque(maxlen=10)
325
+ data_transfer_time = deque(maxlen=10)
326
+ rollout_queue_put_time = deque(maxlen=10)
327
+ actor_policy_version = 0
328
+ for update in range(1, args.num_updates + 2):
329
+ # NOTE: This is a major difference from the sync version:
330
+ # at the end of the rollout phase, the sync version will have the next observation
331
+ # ready for the value bootstrap, but the async version will not have it.
332
+ # for this reason we do `num_steps + 1`` to get the extra states for value bootstrapping.
333
+ # but note that the extra states are not used for the loss computation in the next iteration,
334
+ # while the sync version will use the extra state for the loss computation.
335
+ update_time_start = time.time()
336
+ obs = []
337
+ dones = []
338
+ actions = []
339
+ logprobs = []
340
+ values = []
341
+ env_ids = []
342
+ rewards = []
343
+ truncations = []
344
+ terminations = []
345
+ env_recv_time = 0
346
+ inference_time = 0
347
+ storage_time = 0
348
+ env_send_time = 0
349
+
350
+ # NOTE: `update != 2` is actually IMPORTANT — it allows us to start running policy collection
351
+ # concurrently with the learning process. It also ensures the actor's policy version is only 1 step
352
+ # behind the learner's policy version
353
+ params_queue_get_time_start = time.time()
354
+ if update != 2:
355
+ params = params_queue.get()
356
+ actor_policy_version += 1
357
+ params_queue_get_time.append(time.time() - params_queue_get_time_start)
358
+ writer.add_scalar("stats/params_queue_get_time", np.mean(params_queue_get_time), global_step)
359
+ rollout_time_start = time.time()
360
+ for _ in range(
361
+ args.async_update, (args.num_steps + 1) * args.async_update
362
+ ): # num_steps + 1 to get the states for value bootstrapping.
363
+ env_recv_time_start = time.time()
364
+ next_obs, next_reward, next_done, info = envs.recv()
365
+ env_recv_time += time.time() - env_recv_time_start
366
+ global_step += len(next_done) * args.num_actor_threads * len_actor_device_ids
367
+ env_id = info["env_id"]
368
+
369
+ inference_time_start = time.time()
370
+ action, logprob, value, key = get_action_and_value(params, next_obs, key, envs.single_action_space.n)
371
+ inference_time += time.time() - inference_time_start
372
+
373
+ env_send_time_start = time.time()
374
+ envs.send(np.array(action), env_id)
375
+ env_send_time += time.time() - env_send_time_start
376
+ storage_time_start = time.time()
377
+ obs.append(next_obs)
378
+ dones.append(next_done)
379
+ values.append(value)
380
+ actions.append(action)
381
+ logprobs.append(logprob)
382
+ env_ids.append(env_id)
383
+ rewards.append(next_reward)
384
+ truncations.append(info["TimeLimit.truncated"])
385
+ terminations.append(info["terminated"])
386
+ episode_returns[env_id] += info["reward"]
387
+ returned_episode_returns[env_id] = np.where(
388
+ info["terminated"] + info["TimeLimit.truncated"], episode_returns[env_id], returned_episode_returns[env_id]
389
+ )
390
+ episode_returns[env_id] *= (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"])
391
+ episode_lengths[env_id] += 1
392
+ returned_episode_lengths[env_id] = np.where(
393
+ info["terminated"] + info["TimeLimit.truncated"], episode_lengths[env_id], returned_episode_lengths[env_id]
394
+ )
395
+ episode_lengths[env_id] *= (1 - info["terminated"]) * (1 - info["TimeLimit.truncated"])
396
+ storage_time += time.time() - storage_time_start
397
+ if args.profile:
398
+ action.block_until_ready()
399
+ rollout_time.append(time.time() - rollout_time_start)
400
+ writer.add_scalar("stats/rollout_time", np.mean(rollout_time), global_step)
401
+
402
+ avg_episodic_return = np.mean(returned_episode_returns)
403
+ writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
404
+ writer.add_scalar("charts/avg_episodic_length", np.mean(returned_episode_lengths), global_step)
405
+ if i == 0:
406
+ print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
407
+ print("SPS:", int(global_step / (time.time() - start_time)))
408
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
409
+
410
+ writer.add_scalar("stats/truncations", np.sum(truncations), global_step)
411
+ writer.add_scalar("stats/terminations", np.sum(terminations), global_step)
412
+ writer.add_scalar("stats/env_recv_time", env_recv_time, global_step)
413
+ writer.add_scalar("stats/inference_time", inference_time, global_step)
414
+ writer.add_scalar("stats/storage_time", storage_time, global_step)
415
+ writer.add_scalar("stats/env_send_time", env_send_time, global_step)
416
+
417
+ data_transfer_time_start = time.time()
418
+ b_obs, b_actions, b_logprobs, b_advantages, b_returns = prepare_data(
419
+ obs,
420
+ dones,
421
+ values,
422
+ actions,
423
+ logprobs,
424
+ env_ids,
425
+ rewards,
426
+ )
427
+ payload = (
428
+ global_step,
429
+ actor_policy_version,
430
+ update,
431
+ jnp.array_split(b_obs, len(learner_devices)),
432
+ jnp.array_split(b_actions, len(learner_devices)),
433
+ jnp.array_split(b_logprobs, len(learner_devices)),
434
+ jnp.array_split(b_advantages, len(learner_devices)),
435
+ jnp.array_split(b_returns, len(learner_devices)),
436
+ )
437
+ if args.profile:
438
+ payload[2][0].block_until_ready()
439
+ data_transfer_time.append(time.time() - data_transfer_time_start)
440
+ writer.add_scalar("stats/data_transfer_time", np.mean(data_transfer_time), global_step)
441
+ if update == 1 or not args.test_actor_learner_throughput:
442
+ rollout_queue_put_time_start = time.time()
443
+ rollout_queue.put(payload)
444
+ rollout_queue_put_time.append(time.time() - rollout_queue_put_time_start)
445
+ writer.add_scalar("stats/rollout_queue_put_time", np.mean(rollout_queue_put_time), global_step)
446
+
447
+ writer.add_scalar(
448
+ "charts/SPS_update",
449
+ int(
450
+ args.num_envs
451
+ * args.num_steps
452
+ * args.num_actor_threads
453
+ * len_actor_device_ids
454
+ / (time.time() - update_time_start)
455
+ ),
456
+ global_step,
457
+ )
458
+
459
+
460
+ @partial(jax.jit, static_argnums=(3))
461
+ def get_action_and_value2(
462
+ params: flax.core.FrozenDict,
463
+ x: np.ndarray,
464
+ action: np.ndarray,
465
+ action_dim: int,
466
+ ):
467
+ hidden = Network().apply(params.network_params, x)
468
+ logits = Actor(action_dim).apply(params.actor_params, hidden)
469
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
470
+ logits = logits - jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True)
471
+ logits = logits.clip(min=jnp.finfo(logits.dtype).min)
472
+ p_log_p = logits * jax.nn.softmax(logits)
473
+ entropy = -p_log_p.sum(-1)
474
+ value = Critic().apply(params.critic_params, hidden).squeeze()
475
+ return logprob, entropy, value
476
+
477
+
478
+ @jax.jit
479
+ def compute_gae(
480
+ env_ids: np.ndarray,
481
+ rewards: np.ndarray,
482
+ values: np.ndarray,
483
+ dones: np.ndarray,
484
+ ):
485
+ dones = jnp.asarray(dones)
486
+ values = jnp.asarray(values)
487
+ env_ids = jnp.asarray(env_ids)
488
+ rewards = jnp.asarray(rewards)
489
+
490
+ _, B = env_ids.shape
491
+ final_env_id_checked = jnp.zeros(args.num_envs, jnp.int32) - 1
492
+ final_env_ids = jnp.zeros(B, jnp.int32)
493
+ advantages = jnp.zeros(B)
494
+ lastgaelam = jnp.zeros(args.num_envs)
495
+ lastdones = jnp.zeros(args.num_envs) + 1
496
+ lastvalues = jnp.zeros(args.num_envs)
497
+
498
+ def compute_gae_once(carry, x):
499
+ lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked = carry
500
+ (
501
+ done,
502
+ value,
503
+ eid,
504
+ reward,
505
+ ) = x
506
+ nextnonterminal = 1.0 - lastdones[eid]
507
+ nextvalues = lastvalues[eid]
508
+ delta = jnp.where(final_env_id_checked[eid] == -1, 0, reward + args.gamma * nextvalues * nextnonterminal - value)
509
+ advantages = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam[eid]
510
+ final_env_ids = jnp.where(final_env_id_checked[eid] == 1, 1, 0)
511
+ final_env_id_checked = final_env_id_checked.at[eid].set(
512
+ jnp.where(final_env_id_checked[eid] == -1, 1, final_env_id_checked[eid])
513
+ )
514
+
515
+ # the last_ variables keeps track of the actual `num_steps`
516
+ lastgaelam = lastgaelam.at[eid].set(advantages)
517
+ lastdones = lastdones.at[eid].set(done)
518
+ lastvalues = lastvalues.at[eid].set(value)
519
+ return (lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked), (
520
+ advantages,
521
+ final_env_ids,
522
+ )
523
+
524
+ (_, _, _, _, final_env_ids, final_env_id_checked), (advantages, final_env_ids) = jax.lax.scan(
525
+ compute_gae_once,
526
+ (
527
+ lastvalues,
528
+ lastdones,
529
+ advantages,
530
+ lastgaelam,
531
+ final_env_ids,
532
+ final_env_id_checked,
533
+ ),
534
+ (
535
+ dones,
536
+ values,
537
+ env_ids,
538
+ rewards,
539
+ ),
540
+ reverse=True,
541
+ )
542
+ return advantages, advantages + values, final_env_id_checked, final_env_ids
543
+
544
+
545
+ def ppo_loss(params, x, a, logp, mb_advantages, mb_returns, action_dim):
546
+ newlogprob, entropy, newvalue = get_action_and_value2(params, x, a, action_dim)
547
+ logratio = newlogprob - logp
548
+ ratio = jnp.exp(logratio)
549
+ approx_kl = ((ratio - 1) - logratio).mean()
550
+
551
+ if args.norm_adv:
552
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
553
+
554
+ # Policy loss
555
+ pg_loss1 = -mb_advantages * ratio
556
+ pg_loss2 = -mb_advantages * jnp.clip(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
557
+ pg_loss = jnp.maximum(pg_loss1, pg_loss2).mean()
558
+
559
+ # Value loss
560
+ v_loss = 0.5 * ((newvalue - mb_returns) ** 2).mean()
561
+
562
+ entropy_loss = entropy.mean()
563
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
564
+ return loss, (pg_loss, v_loss, entropy_loss, jax.lax.stop_gradient(approx_kl))
565
+
566
+
567
+ @partial(jax.jit, static_argnums=(6))
568
+ def single_device_update(
569
+ agent_state: TrainState,
570
+ b_obs,
571
+ b_actions,
572
+ b_logprobs,
573
+ b_advantages,
574
+ b_returns,
575
+ action_dim,
576
+ key: jax.random.PRNGKey,
577
+ ):
578
+ ppo_loss_grad_fn = jax.value_and_grad(ppo_loss, has_aux=True)
579
+
580
+ def update_epoch(carry, _):
581
+ agent_state, key = carry
582
+ key, subkey = jax.random.split(key)
583
+
584
+ # taken from: https://github.com/google/brax/blob/main/brax/training/agents/ppo/train.py
585
+ def convert_data(x: jnp.ndarray):
586
+ x = jax.random.permutation(subkey, x)
587
+ x = jnp.reshape(x, (args.num_minibatches, -1) + x.shape[1:])
588
+ return x
589
+
590
+ def update_minibatch(agent_state, minibatch):
591
+ mb_obs, mb_actions, mb_logprobs, mb_advantages, mb_returns = minibatch
592
+ (loss, (pg_loss, v_loss, entropy_loss, approx_kl)), grads = ppo_loss_grad_fn(
593
+ agent_state.params,
594
+ mb_obs,
595
+ mb_actions,
596
+ mb_logprobs,
597
+ mb_advantages,
598
+ mb_returns,
599
+ action_dim,
600
+ )
601
+ grads = jax.lax.pmean(grads, axis_name="devices")
602
+ agent_state = agent_state.apply_gradients(grads=grads)
603
+ return agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
604
+
605
+ agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads) = jax.lax.scan(
606
+ update_minibatch,
607
+ agent_state,
608
+ (
609
+ convert_data(b_obs),
610
+ convert_data(b_actions),
611
+ convert_data(b_logprobs),
612
+ convert_data(b_advantages),
613
+ convert_data(b_returns),
614
+ ),
615
+ )
616
+ return (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
617
+
618
+ (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, _) = jax.lax.scan(
619
+ update_epoch, (agent_state, key), (), length=args.update_epochs
620
+ )
621
+ return agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key
622
+
623
+
624
+ if __name__ == "__main__":
625
+ devices = jax.devices("gpu")
626
+ args = parse_args()
627
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{uuid.uuid4()}"
628
+ if args.track:
629
+ import wandb
630
+
631
+ wandb.init(
632
+ project=args.wandb_project_name,
633
+ entity=args.wandb_entity,
634
+ sync_tensorboard=True,
635
+ config=vars(args),
636
+ name=run_name,
637
+ monitor_gym=True,
638
+ save_code=True,
639
+ )
640
+ print(devices)
641
+ writer = SummaryWriter(f"runs/{run_name}")
642
+ writer.add_text(
643
+ "hyperparameters",
644
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
645
+ )
646
+
647
+ # TRY NOT TO MODIFY: seeding
648
+ random.seed(args.seed)
649
+ np.random.seed(args.seed)
650
+ key = jax.random.PRNGKey(args.seed)
651
+ key, network_key, actor_key, critic_key = jax.random.split(key, 4)
652
+
653
+ # env setup
654
+ envs = make_env(args.env_id, args.seed, args.num_envs, args.async_batch_size)()
655
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
656
+
657
+ def linear_schedule(count):
658
+ # anneal learning rate linearly after one training iteration which contains
659
+ # (args.num_minibatches * args.update_epochs) gradient updates
660
+ frac = 1.0 - (count // (args.num_minibatches * args.update_epochs)) / args.num_updates
661
+ return args.learning_rate * frac
662
+
663
+ network = Network()
664
+ actor = Actor(action_dim=envs.single_action_space.n)
665
+ critic = Critic()
666
+ network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
667
+ agent_state = TrainState.create(
668
+ apply_fn=None,
669
+ params=AgentParams(
670
+ network_params,
671
+ actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
672
+ critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
673
+ ),
674
+ tx=optax.chain(
675
+ optax.clip_by_global_norm(args.max_grad_norm),
676
+ optax.inject_hyperparams(optax.adam)(
677
+ learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
678
+ ),
679
+ ),
680
+ )
681
+ learner_devices = [devices[d_id] for d_id in args.learner_device_ids]
682
+ actor_devices = [devices[d_id] for d_id in args.actor_device_ids]
683
+ agent_state = flax.jax_utils.replicate(agent_state, devices=learner_devices)
684
+
685
+ multi_device_update = jax.pmap(
686
+ single_device_update,
687
+ axis_name="devices",
688
+ devices=learner_devices,
689
+ in_axes=(0, 0, 0, 0, 0, 0, None, None),
690
+ out_axes=(0, 0, 0, 0, 0, 0, None),
691
+ static_broadcasted_argnums=(6),
692
+ )
693
+
694
+ rollout_queue = queue.Queue(maxsize=1)
695
+ params_queues = []
696
+ num_cpus = mp.cpu_count()
697
+ fair_num_cpus = num_cpus // len(args.actor_device_ids)
698
+
699
+ class DummyWriter:
700
+ def add_scalar(self, arg0, arg1, arg3):
701
+ pass
702
+
703
+ dummy_writer = DummyWriter()
704
+ for d_idx, d_id in enumerate(args.actor_device_ids):
705
+ for j in range(args.num_actor_threads):
706
+ params_queue = queue.Queue(maxsize=1)
707
+ params_queue.put(jax.device_put(flax.jax_utils.unreplicate(agent_state.params), devices[d_id]))
708
+ threading.Thread(
709
+ target=rollout,
710
+ args=(
711
+ j,
712
+ fair_num_cpus if args.num_actor_threads > 1 else None,
713
+ j * args.num_actor_threads if args.num_actor_threads > 1 else -1,
714
+ jax.device_put(key, devices[d_id]),
715
+ args,
716
+ rollout_queue,
717
+ params_queue,
718
+ writer if d_idx == 0 and j == 0 else dummy_writer,
719
+ learner_devices,
720
+ ),
721
+ ).start()
722
+ params_queues.append(params_queue)
723
+
724
+ rollout_queue_get_time = deque(maxlen=10)
725
+ learner_policy_version = 0
726
+ while True:
727
+ learner_policy_version += 1
728
+ if learner_policy_version == 1 or not args.test_actor_learner_throughput:
729
+ rollout_queue_get_time_start = time.time()
730
+ (
731
+ global_step,
732
+ actor_policy_version,
733
+ update,
734
+ b_obs,
735
+ b_actions,
736
+ b_logprobs,
737
+ b_advantages,
738
+ b_returns,
739
+ ) = rollout_queue.get()
740
+ rollout_queue_get_time.append(time.time() - rollout_queue_get_time_start)
741
+ writer.add_scalar("stats/rollout_queue_get_time", np.mean(rollout_queue_get_time), global_step)
742
+
743
+ training_time_start = time.time()
744
+ (agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, key) = multi_device_update(
745
+ agent_state,
746
+ jax.device_put_sharded(b_obs, learner_devices),
747
+ jax.device_put_sharded(b_actions, learner_devices),
748
+ jax.device_put_sharded(b_logprobs, learner_devices),
749
+ jax.device_put_sharded(b_advantages, learner_devices),
750
+ jax.device_put_sharded(b_returns, learner_devices),
751
+ envs.single_action_space.n,
752
+ key,
753
+ )
754
+ if learner_policy_version == 1 or not args.test_actor_learner_throughput:
755
+ for d_idx, d_id in enumerate(args.actor_device_ids):
756
+ for j in range(args.num_actor_threads):
757
+ params_queues[d_idx * args.num_actor_threads + j].put(
758
+ jax.device_put(flax.jax_utils.unreplicate(agent_state.params), devices[d_id])
759
+ )
760
+ if args.profile:
761
+ v_loss[-1, -1, -1].block_until_ready()
762
+ writer.add_scalar("stats/training_time", time.time() - training_time_start, global_step)
763
+ writer.add_scalar("stats/rollout_queue_size", rollout_queue.qsize(), global_step)
764
+ writer.add_scalar("stats/params_queue_size", params_queue.qsize(), global_step)
765
+ print(
766
+ global_step,
767
+ f"actor_policy_version={actor_policy_version}, actor_update={update}, learner_policy_version={learner_policy_version}, training time: {time.time() - training_time_start}s",
768
+ )
769
+
770
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
771
+ writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"][0].item(), global_step)
772
+ writer.add_scalar("losses/value_loss", v_loss[-1, -1, -1].item(), global_step)
773
+ writer.add_scalar("losses/policy_loss", pg_loss[-1, -1, -1].item(), global_step)
774
+ writer.add_scalar("losses/entropy", entropy_loss[-1, -1, -1].item(), global_step)
775
+ writer.add_scalar("losses/approx_kl", approx_kl[-1, -1, -1].item(), global_step)
776
+ writer.add_scalar("losses/loss", loss[-1, -1, -1].item(), global_step)
777
+ if update >= args.num_updates:
778
+ break
779
+
780
+ if args.save_model:
781
+ agent_state = flax.jax_utils.unreplicate(agent_state)
782
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
783
+ with open(model_path, "wb") as f:
784
+ f.write(
785
+ flax.serialization.to_bytes(
786
+ [
787
+ vars(args),
788
+ [
789
+ agent_state.params.network_params,
790
+ agent_state.params.actor_params,
791
+ agent_state.params.critic_params,
792
+ ],
793
+ ]
794
+ )
795
+ )
796
+ print(f"model saved to {model_path}")
797
+ from cleanrl_utils.evals.ppo_envpool_jax_eval import evaluate
798
+
799
+ episodic_returns = evaluate(
800
+ model_path,
801
+ make_env,
802
+ args.env_id,
803
+ eval_episodes=10,
804
+ run_name=f"{run_name}-eval",
805
+ Model=(Network, Actor, Critic),
806
+ )
807
+ for idx, episodic_return in enumerate(episodic_returns):
808
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
809
+
810
+ if args.upload_model:
811
+ from cleanrl_utils.huggingface import push_to_hub
812
+
813
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
814
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
815
+ push_to_hub(
816
+ args,
817
+ episodic_returns,
818
+ repo_id,
819
+ "PPO",
820
+ f"runs/{run_name}",
821
+ f"videos/{run_name}-eval",
822
+ extra_dependencies=["jax", "envpool", "atari"],
823
+ )
824
+
825
+ envs.close()
826
+ writer.close()
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:f709086379b2333c95cb26108fb8a8d8d330d149ba3d1a21dff9f2afc3e88f39
3
+ size 4365997
videos/UpNDown-v5__sebulba_ppo_envpool_impala_atari_wrapper__2__c47264a3-10ad-4b79-bf69-4c29d56a060c-eval/0.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82ba356b95101ba79aec7ef50b78915412f4445f2384b78ef196a8b53e8d8fa0
3
+ size 4162466