vwxyzjn commited on
Commit
9e9648d
1 Parent(s): c5f1f0e

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
+ ppo_atari_envpool_async_jax_scan_impalanet_machado.cleanrl_model filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - Alien-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: Alien-v5
16
+ type: Alien-v5
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 5393.00 +/- 2804.27
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # (CleanRL) **PPO** Agent Playing **Alien-v5**
25
+
26
+ This is a trained model of a PPO agent playing Alien-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/ppo_atari_envpool_async_jax_scan_impalanet_machado.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[ppo_atari_envpool_async_jax_scan_impalanet_machado]"
36
+ python -m cleanrl_utils.enjoy --exp-name ppo_atari_envpool_async_jax_scan_impalanet_machado --env-id Alien-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/Alien-v5-ppo_atari_envpool_async_jax_scan_impalanet_machado-seed1/raw/main/ppo_atari_envpool_async_jax_scan_impalanet_machado.py
46
+ curl -OL https://huggingface.co/cleanrl/Alien-v5-ppo_atari_envpool_async_jax_scan_impalanet_machado-seed1/raw/main/pyproject.toml
47
+ curl -OL https://huggingface.co/cleanrl/Alien-v5-ppo_atari_envpool_async_jax_scan_impalanet_machado-seed1/raw/main/poetry.lock
48
+ poetry install --all-extras
49
+ python ppo_atari_envpool_async_jax_scan_impalanet_machado.py --track --wandb-project-name envpool-atari --save-model --upload-model --hf-entity cleanrl --env-id Alien-v5 --seed 1
50
+ ```
51
+
52
+ # Hyperparameters
53
+ ```python
54
+ {'anneal_lr': True,
55
+ 'async_batch_size': 16,
56
+ 'batch_size': 2048,
57
+ 'capture_video': False,
58
+ 'clip_coef': 0.1,
59
+ 'cuda': True,
60
+ 'ent_coef': 0.01,
61
+ 'env_id': 'Alien-v5',
62
+ 'exp_name': 'ppo_atari_envpool_async_jax_scan_impalanet_machado',
63
+ 'gae': True,
64
+ 'gae_lambda': 0.95,
65
+ 'gamma': 0.99,
66
+ 'hf_entity': 'cleanrl',
67
+ 'learning_rate': 0.00025,
68
+ 'max_grad_norm': 0.5,
69
+ 'minibatch_size': 1024,
70
+ 'norm_adv': True,
71
+ 'num_envs': 64,
72
+ 'num_minibatches': 2,
73
+ 'num_steps': 32,
74
+ 'num_updates': 24414,
75
+ 'save_model': True,
76
+ 'seed': 1,
77
+ 'target_kl': None,
78
+ 'torch_deterministic': True,
79
+ 'total_timesteps': 50000000,
80
+ 'track': True,
81
+ 'update_epochs': 2,
82
+ 'upload_model': True,
83
+ 'vf_coef': 0.5,
84
+ 'wandb_entity': None,
85
+ 'wandb_project_name': 'envpool-atari'}
86
+ ```
87
+
events.out.tfevents.1672543324.pop-os.1270332.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3629da37c9426f21be1249970976b57a5667ae9cf1e27b6c6282701d4eb21422
3
+ size 21373446
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
ppo_atari_envpool_async_jax_scan_impalanet_machado.cleanrl_model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dbbffd58f89063f827aa27ebb966bb706842c60ef16ea406059047caa988171
3
+ size 4378225
ppo_atari_envpool_async_jax_scan_impalanet_machado.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # https://gregorygundersen.com/blog/2020/02/09/log-sum-exp/
3
+ import argparse
4
+ import os
5
+ import random
6
+ import time
7
+ from distutils.util import strtobool
8
+ from typing import Sequence
9
+
10
+ os.environ[
11
+ "XLA_PYTHON_CLIENT_MEM_FRACTION"
12
+ ] = "0.7" # see https://github.com/google/jax/discussions/6332#discussioncomment-1279991
13
+
14
+ import envpool
15
+ import flax
16
+ import flax.linen as nn
17
+ import gym
18
+ import jax
19
+ import jax.numpy as jnp
20
+ import numpy as np
21
+ import optax
22
+ from flax.linen.initializers import constant, orthogonal
23
+ from flax.training.train_state import TrainState
24
+ from torch.utils.tensorboard import SummaryWriter
25
+
26
+
27
+ def parse_args():
28
+ # fmt: off
29
+ parser = argparse.ArgumentParser()
30
+ parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
31
+ help="the name of this experiment")
32
+ parser.add_argument("--seed", type=int, default=1,
33
+ help="seed of the experiment")
34
+ parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
35
+ help="if toggled, `torch.backends.cudnn.deterministic=False`")
36
+ parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
37
+ help="if toggled, cuda will be enabled by default")
38
+ parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
39
+ help="if toggled, this experiment will be tracked with Weights and Biases")
40
+ parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
41
+ help="the wandb's project name")
42
+ parser.add_argument("--wandb-entity", type=str, default=None,
43
+ help="the entity (team) of wandb's project")
44
+ parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
45
+ help="weather to capture videos of the agent performances (check out `videos` folder)")
46
+ parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
47
+ help="whether to save model into the `runs/{run_name}` folder")
48
+ parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
49
+ help="whether to upload the saved model to huggingface")
50
+ parser.add_argument("--hf-entity", type=str, default="",
51
+ help="the user or org name of the model repository from the Hugging Face Hub")
52
+
53
+ # Algorithm specific arguments
54
+ parser.add_argument("--env-id", type=str, default="Breakout-v5",
55
+ help="the id of the environment")
56
+ parser.add_argument("--total-timesteps", type=int, default=50000000,
57
+ help="total timesteps of the experiments")
58
+ parser.add_argument("--learning-rate", type=float, default=2.5e-4,
59
+ help="the learning rate of the optimizer")
60
+ parser.add_argument("--num-envs", type=int, default=64,
61
+ help="the number of parallel game environments")
62
+ parser.add_argument("--async-batch-size", type=int, default=16,
63
+ help="the envpool's batch size in the async mode")
64
+ parser.add_argument("--num-steps", type=int, default=32,
65
+ help="the number of steps to run in each environment per policy rollout")
66
+ parser.add_argument("--anneal-lr", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
67
+ help="Toggle learning rate annealing for policy and value networks")
68
+ parser.add_argument("--gae", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
69
+ help="Use GAE for advantage computation")
70
+ parser.add_argument("--gamma", type=float, default=0.99,
71
+ help="the discount factor gamma")
72
+ parser.add_argument("--gae-lambda", type=float, default=0.95,
73
+ help="the lambda for the general advantage estimation")
74
+ parser.add_argument("--num-minibatches", type=int, default=2,
75
+ help="the number of mini-batches")
76
+ parser.add_argument("--update-epochs", type=int, default=2,
77
+ help="the K epochs to update the policy")
78
+ parser.add_argument("--norm-adv", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
79
+ help="Toggles advantages normalization")
80
+ parser.add_argument("--clip-coef", type=float, default=0.1,
81
+ help="the surrogate clipping coefficient")
82
+ parser.add_argument("--ent-coef", type=float, default=0.01,
83
+ help="coefficient of the entropy")
84
+ parser.add_argument("--vf-coef", type=float, default=0.5,
85
+ help="coefficient of the value function")
86
+ parser.add_argument("--max-grad-norm", type=float, default=0.5,
87
+ help="the maximum norm for the gradient clipping")
88
+ parser.add_argument("--target-kl", type=float, default=None,
89
+ help="the target KL divergence threshold")
90
+ args = parser.parse_args()
91
+ args.batch_size = int(args.num_envs * args.num_steps)
92
+ args.minibatch_size = int(args.batch_size // args.num_minibatches)
93
+ args.num_updates = args.total_timesteps // args.batch_size
94
+ # fmt: on
95
+ return args
96
+
97
+
98
+ def make_env(env_id, seed, num_envs, async_batch_size=1):
99
+ def thunk():
100
+ envs = envpool.make(
101
+ env_id,
102
+ env_type="gym",
103
+ num_envs=num_envs,
104
+ batch_size=async_batch_size,
105
+ episodic_life=False, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 6
106
+ repeat_action_probability=0.25, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 12
107
+ noop_max=1, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 12 (no-op is deprecated in favor of sticky action, right?)
108
+ full_action_space=True, # Machado et al. 2017 (Revisitng ALE: Eval protocols) Tab. 5
109
+ max_episode_steps=int(108000 / 4), # Hessel et al. 2018 (Rainbow DQN), Table 3, Max frames per episode
110
+ reward_clip=True,
111
+ seed=seed,
112
+ )
113
+ envs.num_envs = num_envs
114
+ envs.single_action_space = envs.action_space
115
+ envs.single_observation_space = envs.observation_space
116
+ envs.is_vector_env = True
117
+ return envs
118
+
119
+ return thunk
120
+
121
+
122
+ class ResidualBlock(nn.Module):
123
+ channels: int
124
+
125
+ @nn.compact
126
+ def __call__(self, x):
127
+ inputs = x
128
+ x = nn.relu(x)
129
+ x = nn.Conv(
130
+ self.channels,
131
+ kernel_size=(3, 3),
132
+ )(x)
133
+ x = nn.relu(x)
134
+ x = nn.Conv(
135
+ self.channels,
136
+ kernel_size=(3, 3),
137
+ )(x)
138
+ return x + inputs
139
+
140
+
141
+ class ConvSequence(nn.Module):
142
+ channels: int
143
+
144
+ @nn.compact
145
+ def __call__(self, x):
146
+ x = nn.Conv(
147
+ self.channels,
148
+ kernel_size=(3, 3),
149
+ )(x)
150
+ x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
151
+ x = ResidualBlock(self.channels)(x)
152
+ x = ResidualBlock(self.channels)(x)
153
+ return x
154
+
155
+
156
+ class Network(nn.Module):
157
+ channelss: Sequence[int] = (16, 32, 32)
158
+
159
+ @nn.compact
160
+ def __call__(self, x):
161
+ x = jnp.transpose(x, (0, 2, 3, 1))
162
+ x = x / (255.0)
163
+ for channels in self.channelss:
164
+ x = ConvSequence(channels)(x)
165
+ x = nn.relu(x)
166
+ x = x.reshape((x.shape[0], -1))
167
+ x = nn.Dense(256, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
168
+ x = nn.relu(x)
169
+ return x
170
+
171
+
172
+ class Critic(nn.Module):
173
+ @nn.compact
174
+ def __call__(self, x):
175
+ return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
176
+
177
+
178
+ class Actor(nn.Module):
179
+ action_dim: Sequence[int]
180
+
181
+ @nn.compact
182
+ def __call__(self, x):
183
+ return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
184
+
185
+
186
+ @flax.struct.dataclass
187
+ class AgentParams:
188
+ network_params: flax.core.FrozenDict
189
+ actor_params: flax.core.FrozenDict
190
+ critic_params: flax.core.FrozenDict
191
+
192
+
193
+ if __name__ == "__main__":
194
+ args = parse_args()
195
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
196
+ if args.track:
197
+ import wandb
198
+
199
+ wandb.init(
200
+ project=args.wandb_project_name,
201
+ entity=args.wandb_entity,
202
+ sync_tensorboard=True,
203
+ config=vars(args),
204
+ name=run_name,
205
+ monitor_gym=True,
206
+ save_code=True,
207
+ )
208
+ writer = SummaryWriter(f"runs/{run_name}")
209
+ writer.add_text(
210
+ "hyperparameters",
211
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
212
+ )
213
+
214
+ # TRY NOT TO MODIFY: seeding
215
+ random.seed(args.seed)
216
+ np.random.seed(args.seed)
217
+ key = jax.random.PRNGKey(args.seed)
218
+ key, network_key, actor_key, critic_key = jax.random.split(key, 4)
219
+
220
+ # env setup
221
+ envs = make_env(args.env_id, args.seed, args.num_envs, args.async_batch_size)()
222
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
223
+
224
+ def linear_schedule(count):
225
+ # anneal learning rate linearly after one training iteration which contains
226
+ # (args.num_minibatches * args.update_epochs) gradient updates
227
+ frac = 1.0 - (count // (args.num_minibatches * args.update_epochs)) / args.num_updates
228
+ return args.learning_rate * frac
229
+
230
+ network = Network()
231
+ actor = Actor(action_dim=envs.single_action_space.n)
232
+ critic = Critic()
233
+ network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
234
+ agent_state = TrainState.create(
235
+ apply_fn=None,
236
+ params=AgentParams(
237
+ network_params,
238
+ actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
239
+ critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
240
+ ),
241
+ tx=optax.chain(
242
+ optax.clip_by_global_norm(args.max_grad_norm),
243
+ optax.inject_hyperparams(optax.adam)(
244
+ learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
245
+ ),
246
+ ),
247
+ )
248
+
249
+ @jax.jit
250
+ def get_action_and_value(
251
+ agent_state: TrainState,
252
+ next_obs: np.ndarray,
253
+ key: jax.random.PRNGKey,
254
+ ):
255
+ hidden = network.apply(agent_state.params.network_params, next_obs)
256
+ logits = actor.apply(agent_state.params.actor_params, hidden)
257
+ # sample action: Gumbel-softmax trick
258
+ # see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
259
+ key, subkey = jax.random.split(key)
260
+ u = jax.random.uniform(subkey, shape=logits.shape)
261
+ action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
262
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
263
+ value = critic.apply(agent_state.params.critic_params, hidden)
264
+ return action, logprob, value.squeeze(), key
265
+
266
+ @jax.jit
267
+ def get_action_and_value2(
268
+ params: flax.core.FrozenDict,
269
+ x: np.ndarray,
270
+ action: np.ndarray,
271
+ ):
272
+ hidden = network.apply(params.network_params, x)
273
+ logits = actor.apply(params.actor_params, hidden)
274
+ logprob = jax.nn.log_softmax(logits)[jnp.arange(action.shape[0]), action]
275
+ logits = logits - jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True)
276
+ logits = logits.clip(min=jnp.finfo(logits.dtype).min)
277
+ p_log_p = logits * jax.nn.softmax(logits)
278
+ entropy = -p_log_p.sum(-1)
279
+ value = critic.apply(params.critic_params, hidden).squeeze()
280
+ return logprob, entropy, value
281
+
282
+ def compute_gae_once(carry, x):
283
+ lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked = carry
284
+ (
285
+ done,
286
+ value,
287
+ eid,
288
+ reward,
289
+ ) = x
290
+ nextnonterminal = 1.0 - lastdones[eid]
291
+ nextvalues = lastvalues[eid]
292
+ delta = jnp.where(final_env_id_checked[eid] == -1, 0, reward + args.gamma * nextvalues * nextnonterminal - value)
293
+ advantages = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam[eid]
294
+ final_env_ids = jnp.where(final_env_id_checked[eid] == 1, 1, 0)
295
+ final_env_id_checked = final_env_id_checked.at[eid].set(
296
+ jnp.where(final_env_id_checked[eid] == -1, 1, final_env_id_checked[eid])
297
+ )
298
+
299
+ # the last_ variables keeps track of the actual `num_steps`
300
+ lastgaelam = lastgaelam.at[eid].set(advantages)
301
+ lastdones = lastdones.at[eid].set(done)
302
+ lastvalues = lastvalues.at[eid].set(value)
303
+ return (lastvalues, lastdones, advantages, lastgaelam, final_env_ids, final_env_id_checked), (
304
+ advantages,
305
+ final_env_ids,
306
+ )
307
+
308
+ @jax.jit
309
+ def compute_gae(
310
+ env_ids: np.ndarray,
311
+ rewards: np.ndarray,
312
+ values: np.ndarray,
313
+ dones: np.ndarray,
314
+ ):
315
+ dones = jnp.asarray(dones)
316
+ values = jnp.asarray(values)
317
+ env_ids = jnp.asarray(env_ids)
318
+ rewards = jnp.asarray(rewards)
319
+
320
+ _, B = env_ids.shape
321
+ final_env_id_checked = jnp.zeros(args.num_envs, jnp.int32) - 1
322
+ final_env_ids = jnp.zeros(B, jnp.int32)
323
+ advantages = jnp.zeros(B)
324
+ lastgaelam = jnp.zeros(args.num_envs)
325
+ lastdones = jnp.zeros(args.num_envs) + 1
326
+ lastvalues = jnp.zeros(args.num_envs)
327
+
328
+ (_, _, _, _, final_env_ids, final_env_id_checked), (advantages, final_env_ids) = jax.lax.scan(
329
+ compute_gae_once,
330
+ (
331
+ lastvalues,
332
+ lastdones,
333
+ advantages,
334
+ lastgaelam,
335
+ final_env_ids,
336
+ final_env_id_checked,
337
+ ),
338
+ (
339
+ dones,
340
+ values,
341
+ env_ids,
342
+ rewards,
343
+ ),
344
+ reverse=True,
345
+ )
346
+ return advantages, advantages + values, final_env_id_checked, final_env_ids
347
+
348
+ def ppo_loss(params, x, a, logp, mb_advantages, mb_returns):
349
+ newlogprob, entropy, newvalue = get_action_and_value2(params, x, a)
350
+ logratio = newlogprob - logp
351
+ ratio = jnp.exp(logratio)
352
+ approx_kl = ((ratio - 1) - logratio).mean()
353
+
354
+ if args.norm_adv:
355
+ mb_advantages = (mb_advantages - mb_advantages.mean()) / (mb_advantages.std() + 1e-8)
356
+
357
+ # Policy loss
358
+ pg_loss1 = -mb_advantages * ratio
359
+ pg_loss2 = -mb_advantages * jnp.clip(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
360
+ pg_loss = jnp.maximum(pg_loss1, pg_loss2).mean()
361
+
362
+ # Value loss
363
+ v_loss = 0.5 * ((newvalue - mb_returns) ** 2).mean()
364
+
365
+ entropy_loss = entropy.mean()
366
+ loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef
367
+ return loss, (pg_loss, v_loss, entropy_loss, jax.lax.stop_gradient(approx_kl))
368
+
369
+ ppo_loss_grad_fn = jax.value_and_grad(ppo_loss, has_aux=True)
370
+
371
+ @jax.jit
372
+ def update_ppo(
373
+ agent_state: TrainState,
374
+ obs: list,
375
+ dones: list,
376
+ values: list,
377
+ actions: list,
378
+ logprobs: list,
379
+ env_ids: list,
380
+ rewards: list,
381
+ key: jax.random.PRNGKey,
382
+ ):
383
+ obs = jnp.asarray(obs)
384
+ dones = jnp.asarray(dones)
385
+ values = jnp.asarray(values)
386
+ actions = jnp.asarray(actions)
387
+ logprobs = jnp.asarray(logprobs)
388
+ env_ids = jnp.asarray(env_ids)
389
+ rewards = jnp.asarray(rewards)
390
+
391
+ # TODO: in an unlikely event, one of the envs might have not stepped at all, which may results in unexpected behavior
392
+ T, B = env_ids.shape
393
+ index_ranges = jnp.arange(T * B, dtype=jnp.int32)
394
+ next_index_ranges = jnp.zeros_like(index_ranges, dtype=jnp.int32)
395
+ last_env_ids = jnp.zeros(args.num_envs, dtype=jnp.int32) - 1
396
+
397
+ def f(carry, x):
398
+ last_env_ids, next_index_ranges = carry
399
+ env_id, index_range = x
400
+ next_index_ranges = next_index_ranges.at[last_env_ids[env_id]].set(
401
+ jnp.where(last_env_ids[env_id] != -1, index_range, next_index_ranges[last_env_ids[env_id]])
402
+ )
403
+ last_env_ids = last_env_ids.at[env_id].set(index_range)
404
+ return (last_env_ids, next_index_ranges), None
405
+
406
+ (last_env_ids, next_index_ranges), _ = jax.lax.scan(
407
+ f,
408
+ (last_env_ids, next_index_ranges),
409
+ (env_ids.reshape(-1), index_ranges),
410
+ )
411
+
412
+ # rewards is off by one time step
413
+ rewards = rewards.reshape(-1)[next_index_ranges].reshape((args.num_steps) * async_update, args.async_batch_size)
414
+ advantages, returns, _, final_env_ids = compute_gae(env_ids, rewards, values, dones)
415
+ b_inds = jnp.nonzero(final_env_ids.reshape(-1), size=(args.num_steps) * async_update * args.async_batch_size)[0]
416
+ b_obs = obs.reshape((-1,) + envs.single_observation_space.shape)
417
+ b_actions = actions.reshape(-1)
418
+ b_logprobs = logprobs.reshape(-1)
419
+ b_advantages = advantages.reshape(-1)
420
+ b_returns = returns.reshape(-1)
421
+
422
+ def update_epoch(carry, _):
423
+ agent_state, key = carry
424
+ key, subkey = jax.random.split(key)
425
+
426
+ # taken from: https://github.com/google/brax/blob/main/brax/training/agents/ppo/train.py
427
+ def convert_data(x: jnp.ndarray):
428
+ x = jax.random.permutation(subkey, x)
429
+ x = jnp.reshape(x, (args.num_minibatches, -1) + x.shape[1:])
430
+ return x
431
+
432
+ def update_minibatch(agent_state, minibatch):
433
+ mb_obs, mb_actions, mb_logprobs, mb_advantages, mb_returns = minibatch
434
+ (loss, (pg_loss, v_loss, entropy_loss, approx_kl)), grads = ppo_loss_grad_fn(
435
+ agent_state.params,
436
+ mb_obs,
437
+ mb_actions,
438
+ mb_logprobs,
439
+ mb_advantages,
440
+ mb_returns,
441
+ )
442
+ agent_state = agent_state.apply_gradients(grads=grads)
443
+ return agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
444
+
445
+ agent_state, (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads) = jax.lax.scan(
446
+ update_minibatch,
447
+ agent_state,
448
+ (
449
+ convert_data(b_obs),
450
+ convert_data(b_actions),
451
+ convert_data(b_logprobs),
452
+ convert_data(b_advantages),
453
+ convert_data(b_returns),
454
+ ),
455
+ )
456
+ return (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, grads)
457
+
458
+ (agent_state, key), (loss, pg_loss, v_loss, entropy_loss, approx_kl, _) = jax.lax.scan(
459
+ update_epoch, (agent_state, key), (), length=args.update_epochs
460
+ )
461
+ return agent_state, loss, pg_loss, v_loss, entropy_loss, approx_kl, advantages, returns, b_inds, final_env_ids, key
462
+
463
+ # TRY NOT TO MODIFY: start the game
464
+ global_step = 0
465
+ start_time = time.time()
466
+ async_update = int(args.num_envs / args.async_batch_size)
467
+
468
+ # put data in the last index
469
+ episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
470
+ returned_episode_returns = np.zeros((args.num_envs,), dtype=np.float32)
471
+ episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
472
+ returned_episode_lengths = np.zeros((args.num_envs,), dtype=np.float32)
473
+ envs.async_reset()
474
+ final_env_ids = np.zeros((async_update, args.async_batch_size), dtype=np.int32)
475
+
476
+ for update in range(1, args.num_updates + 2):
477
+ update_time_start = time.time()
478
+ obs = []
479
+ dones = []
480
+ actions = []
481
+ logprobs = []
482
+ values = []
483
+ env_ids = []
484
+ rewards = []
485
+ env_recv_time = 0
486
+ inference_time = 0
487
+ storage_time = 0
488
+ env_send_time = 0
489
+
490
+ # NOTE: This is a major difference from the sync version:
491
+ # at the end of the rollout phase, the sync version will have the next observation
492
+ # ready for the value bootstrap, but the async version will not have it.
493
+ # for this reason we do `num_steps + 1`` to get the extra states for value bootstrapping.
494
+ # but note that the extra states are not used for the loss computation in the next iteration,
495
+ # while the sync version will use the extra state for the loss computation.
496
+ for step in range(
497
+ async_update, (args.num_steps + 1) * async_update
498
+ ): # num_steps + 1 to get the states for value bootstrapping.
499
+ env_recv_time_start = time.time()
500
+ next_obs, next_reward, next_done, info = envs.recv()
501
+ env_recv_time += time.time() - env_recv_time_start
502
+ global_step += len(next_done)
503
+ env_id = info["env_id"]
504
+
505
+ inference_time_start = time.time()
506
+ action, logprob, value, key = get_action_and_value(agent_state, next_obs, key)
507
+ inference_time += time.time() - inference_time_start
508
+
509
+ env_send_time_start = time.time()
510
+ envs.send(np.array(action), env_id)
511
+ env_send_time += time.time() - env_send_time_start
512
+ storage_time_start = time.time()
513
+ obs.append(next_obs)
514
+ dones.append(next_done)
515
+ values.append(value)
516
+ actions.append(action)
517
+ logprobs.append(logprob)
518
+ env_ids.append(env_id)
519
+ rewards.append(next_reward)
520
+ episode_returns[env_id] += info["reward"]
521
+ returned_episode_returns[env_id] = np.where(
522
+ info["terminated"], episode_returns[env_id], returned_episode_returns[env_id]
523
+ )
524
+ episode_returns[env_id] *= 1 - info["terminated"]
525
+ episode_lengths[env_id] += 1
526
+ returned_episode_lengths[env_id] = np.where(
527
+ info["terminated"], episode_lengths[env_id], returned_episode_lengths[env_id]
528
+ )
529
+ episode_lengths[env_id] *= 1 - info["terminated"]
530
+ storage_time += time.time() - storage_time_start
531
+
532
+ avg_episodic_return = np.mean(returned_episode_returns)
533
+ # print(returned_episode_returns)
534
+ print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
535
+ writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
536
+ training_time_start = time.time()
537
+ (
538
+ agent_state,
539
+ loss,
540
+ pg_loss,
541
+ v_loss,
542
+ entropy_loss,
543
+ approx_kl,
544
+ advantages,
545
+ returns,
546
+ b_inds,
547
+ final_env_ids,
548
+ key,
549
+ ) = update_ppo(
550
+ agent_state,
551
+ obs,
552
+ dones,
553
+ values,
554
+ actions,
555
+ logprobs,
556
+ env_ids,
557
+ rewards,
558
+ key,
559
+ )
560
+ writer.add_scalar("stats/training_time", time.time() - training_time_start, global_step)
561
+ # writer.add_scalar("stats/advantages", advantages.mean().item(), global_step)
562
+ # writer.add_scalar("stats/returns", returns.mean().item(), global_step)
563
+
564
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
565
+ writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"].item(), global_step)
566
+ writer.add_scalar("losses/value_loss", v_loss[-1, -1].item(), global_step)
567
+ writer.add_scalar("losses/policy_loss", pg_loss[-1, -1].item(), global_step)
568
+ writer.add_scalar("losses/entropy", entropy_loss[-1, -1].item(), global_step)
569
+ writer.add_scalar("losses/approx_kl", approx_kl[-1, -1].item(), global_step)
570
+ writer.add_scalar("losses/loss", loss[-1, -1].item(), global_step)
571
+ print("SPS:", int(global_step / (time.time() - start_time)))
572
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
573
+ writer.add_scalar(
574
+ "charts/SPS_update", int(args.num_envs * args.num_steps / (time.time() - update_time_start)), global_step
575
+ )
576
+ writer.add_scalar("stats/env_recv_time", env_recv_time, global_step)
577
+ writer.add_scalar("stats/inference_time", inference_time, global_step)
578
+ writer.add_scalar("stats/storage_time", storage_time, global_step)
579
+ writer.add_scalar("stats/env_send_time", env_send_time, global_step)
580
+ writer.add_scalar("stats/update_time", time.time() - update_time_start, global_step)
581
+
582
+ if args.save_model:
583
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
584
+ with open(model_path, "wb") as f:
585
+ f.write(
586
+ flax.serialization.to_bytes(
587
+ [
588
+ vars(args),
589
+ [
590
+ agent_state.params.network_params,
591
+ agent_state.params.actor_params,
592
+ agent_state.params.critic_params,
593
+ ],
594
+ ]
595
+ )
596
+ )
597
+ print(f"model saved to {model_path}")
598
+ from cleanrl_utils.evals.ppo_envpool_jax_eval import evaluate
599
+
600
+ episodic_returns = evaluate(
601
+ model_path,
602
+ make_env,
603
+ args.env_id,
604
+ eval_episodes=10,
605
+ run_name=f"{run_name}-eval",
606
+ Model=(Network, Actor, Critic),
607
+ )
608
+ for idx, episodic_return in enumerate(episodic_returns):
609
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
610
+
611
+ if args.upload_model:
612
+ from cleanrl_utils.huggingface import push_to_hub
613
+
614
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
615
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
616
+ push_to_hub(args, episodic_returns, repo_id, "PPO", f"runs/{run_name}", f"videos/{run_name}-eval")
617
+
618
+ envs.close()
619
+ writer.close()
pyproject.toml ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "cleanrl-test"
3
+ version = "1.1.2"
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.7.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.7.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 (143 kB). View file
 
videos/Alien-v5__ppo_atari_envpool_async_jax_scan_impalanet_machado__1__1672543322-eval/0.mp4 ADDED
Binary file (143 kB). View file