vwxyzjn commited on
Commit
aa50710
1 Parent(s): ed97ab6

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