-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppo_rnn.py
545 lines (479 loc) · 18.5 KB
/
ppo_rnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import argparse
import os
import sys
import jax
import jax.numpy as jnp
import flax.linen as nn
import numpy as np
import optax
import time
from flax.training import orbax_utils
from orbax.checkpoint import (
PyTreeCheckpointer,
CheckpointManagerOptions,
CheckpointManager,
)
import wandb
from flax.linen.initializers import constant, orthogonal
from typing import Sequence, NamedTuple, Dict
from flax.training.train_state import TrainState
import distrax
import functools
from wrappers import (
LogWrapper,
OptimisticResetVecEnvWrapper,
BatchEnvWrapper,
)
from logz.batch_logging import create_log_dict, batch_log
from craftax.craftax_env import make_craftax_env_from_name
# Code adapted from the original implementation made by Chris Lu
# Original code located at https://github.com/luchris429/purejaxrl
class ScannedRNN(nn.Module):
@functools.partial(
nn.scan,
variable_broadcast="params",
in_axes=0,
out_axes=0,
split_rngs={"params": False},
)
@nn.compact
def __call__(self, carry, x):
"""Applies the module."""
rnn_state = carry
ins, resets = x
rnn_state = jnp.where(
resets[:, np.newaxis],
self.initialize_carry(ins.shape[0], ins.shape[1]),
rnn_state,
)
new_rnn_state, y = nn.GRUCell(features=ins.shape[1])(rnn_state, ins)
return new_rnn_state, y
@staticmethod
def initialize_carry(batch_size, hidden_size):
# Use a dummy key since the default state init fn is just zeros.
cell = nn.GRUCell(features=hidden_size)
return cell.initialize_carry(jax.random.PRNGKey(0), (batch_size, hidden_size))
class ActorCriticRNN(nn.Module):
action_dim: Sequence[int]
config: Dict
@nn.compact
def __call__(self, hidden, x):
obs, dones = x
embedding = nn.Dense(
self.config["LAYER_SIZE"],
kernel_init=orthogonal(np.sqrt(2)),
bias_init=constant(0.0),
)(obs)
embedding = nn.relu(embedding)
rnn_in = (embedding, dones)
hidden, embedding = ScannedRNN()(hidden, rnn_in)
actor_mean = nn.Dense(
self.config["LAYER_SIZE"],
kernel_init=orthogonal(2),
bias_init=constant(0.0),
)(embedding)
actor_mean = nn.relu(actor_mean)
actor_mean = nn.Dense(
self.config["LAYER_SIZE"],
kernel_init=orthogonal(2),
bias_init=constant(0.0),
)(actor_mean)
actor_mean = nn.relu(actor_mean)
actor_mean = nn.Dense(
self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0)
)(actor_mean)
pi = distrax.Categorical(logits=actor_mean)
critic = nn.Dense(
self.config["LAYER_SIZE"],
kernel_init=orthogonal(2),
bias_init=constant(0.0),
)(embedding)
critic = nn.relu(critic)
critic = nn.Dense(
self.config["LAYER_SIZE"],
kernel_init=orthogonal(2),
bias_init=constant(0.0),
)(critic)
critic = nn.relu(critic)
critic = nn.Dense(1, kernel_init=orthogonal(1.0), bias_init=constant(0.0))(
critic
)
return hidden, pi, jnp.squeeze(critic, axis=-1)
class Transition(NamedTuple):
done: jnp.ndarray
action: jnp.ndarray
value: jnp.ndarray
reward: jnp.ndarray
log_prob: jnp.ndarray
obs: jnp.ndarray
info: jnp.ndarray
def make_train(config):
config["NUM_UPDATES"] = (
config["TOTAL_TIMESTEPS"] // config["NUM_STEPS"] // config["NUM_ENVS"]
)
config["MINIBATCH_SIZE"] = (
config["NUM_ENVS"] * config["NUM_STEPS"] // config["NUM_MINIBATCHES"]
)
# Create environment
env = make_craftax_env_from_name(
config["ENV_NAME"], not config["USE_OPTIMISTIC_RESETS"]
)
env_params = env.default_params
# Wrap with some extra logging
env = LogWrapper(env)
# Wrap with a batcher, maybe using optimistic resets
if config["USE_OPTIMISTIC_RESETS"]:
env = OptimisticResetVecEnvWrapper(
env,
num_envs=config["NUM_ENVS"],
reset_ratio=min(config["OPTIMISTIC_RESET_RATIO"], config["NUM_ENVS"]),
)
else:
env = BatchEnvWrapper(env, num_envs=config["NUM_ENVS"])
def linear_schedule(count):
frac = (
1.0
- (count // (config["NUM_MINIBATCHES"] * config["UPDATE_EPOCHS"]))
/ config["NUM_UPDATES"]
)
return config["LR"] * frac
def train(rng):
# INIT NETWORK
network = ActorCriticRNN(env.action_space(env_params).n, config=config)
rng, _rng = jax.random.split(rng)
init_x = (
jnp.zeros(
(1, config["NUM_ENVS"], *env.observation_space(env_params).shape)
),
jnp.zeros((1, config["NUM_ENVS"])),
)
init_hstate = ScannedRNN.initialize_carry(
config["NUM_ENVS"], config["LAYER_SIZE"]
)
network_params = network.init(_rng, init_hstate, init_x)
if config["ANNEAL_LR"]:
tx = optax.chain(
optax.clip_by_global_norm(config["MAX_GRAD_NORM"]),
optax.adam(learning_rate=linear_schedule, eps=1e-5),
)
else:
tx = optax.chain(
optax.clip_by_global_norm(config["MAX_GRAD_NORM"]),
optax.adam(config["LR"], eps=1e-5),
)
train_state = TrainState.create(
apply_fn=network.apply,
params=network_params,
tx=tx,
)
# INIT ENV
rng, _rng = jax.random.split(rng)
obsv, env_state = env.reset(_rng, env_params)
init_hstate = ScannedRNN.initialize_carry(
config["NUM_ENVS"], config["LAYER_SIZE"]
)
# TRAIN LOOP
def _update_step(runner_state, unused):
# COLLECT TRAJECTORIES
def _env_step(runner_state, unused):
(
train_state,
env_state,
last_obs,
last_done,
hstate,
rng,
update_step,
) = runner_state
rng, _rng = jax.random.split(rng)
# SELECT ACTION
ac_in = (last_obs[np.newaxis, :], last_done[np.newaxis, :])
hstate, pi, value = network.apply(train_state.params, hstate, ac_in)
action = pi.sample(seed=_rng)
log_prob = pi.log_prob(action)
value, action, log_prob = (
value.squeeze(0),
action.squeeze(0),
log_prob.squeeze(0),
)
# STEP ENV
rng, _rng = jax.random.split(rng)
obsv, env_state, reward, done, info = env.step(
_rng, env_state, action, env_params
)
transition = Transition(
last_done, action, value, reward, log_prob, last_obs, info
)
runner_state = (
train_state,
env_state,
obsv,
done,
hstate,
rng,
update_step,
)
return runner_state, transition
initial_hstate = runner_state[-3]
runner_state, traj_batch = jax.lax.scan(
_env_step, runner_state, None, config["NUM_STEPS"]
)
# CALCULATE ADVANTAGE
(
train_state,
env_state,
last_obs,
last_done,
hstate,
rng,
update_step,
) = runner_state
ac_in = (last_obs[np.newaxis, :], last_done[np.newaxis, :])
_, _, last_val = network.apply(train_state.params, hstate, ac_in)
last_val = last_val.squeeze(0)
def _calculate_gae(traj_batch, last_val, last_done):
def _get_advantages(carry, transition):
gae, next_value, next_done = carry
done, value, reward = (
transition.done,
transition.value,
transition.reward,
)
delta = (
reward + config["GAMMA"] * next_value * (1 - next_done) - value
)
gae = (
delta
+ config["GAMMA"] * config["GAE_LAMBDA"] * (1 - next_done) * gae
)
return (gae, value, done), gae
_, advantages = jax.lax.scan(
_get_advantages,
(jnp.zeros_like(last_val), last_val, last_done),
traj_batch,
reverse=True,
unroll=16,
)
return advantages, advantages + traj_batch.value
advantages, targets = _calculate_gae(traj_batch, last_val, last_done)
# UPDATE NETWORK
def _update_epoch(update_state, unused):
def _update_minbatch(train_state, batch_info):
init_hstate, traj_batch, advantages, targets = batch_info
def _loss_fn(params, init_hstate, traj_batch, gae, targets):
# RERUN NETWORK
_, pi, value = network.apply(
params, init_hstate[0], (traj_batch.obs, traj_batch.done)
)
log_prob = pi.log_prob(traj_batch.action)
# CALCULATE VALUE LOSS
value_pred_clipped = traj_batch.value + (
value - traj_batch.value
).clip(-config["CLIP_EPS"], config["CLIP_EPS"])
value_losses = jnp.square(value - targets)
value_losses_clipped = jnp.square(value_pred_clipped - targets)
value_loss = (
0.5 * jnp.maximum(value_losses, value_losses_clipped).mean()
)
# CALCULATE ACTOR LOSS
ratio = jnp.exp(log_prob - traj_batch.log_prob)
gae = (gae - gae.mean()) / (gae.std() + 1e-8)
loss_actor1 = ratio * gae
loss_actor2 = (
jnp.clip(
ratio,
1.0 - config["CLIP_EPS"],
1.0 + config["CLIP_EPS"],
)
* gae
)
loss_actor = -jnp.minimum(loss_actor1, loss_actor2)
loss_actor = loss_actor.mean()
entropy = pi.entropy().mean()
total_loss = (
loss_actor
+ config["VF_COEF"] * value_loss
- config["ENT_COEF"] * entropy
)
return total_loss, (value_loss, loss_actor, entropy)
grad_fn = jax.value_and_grad(_loss_fn, has_aux=True)
total_loss, grads = grad_fn(
train_state.params, init_hstate, traj_batch, advantages, targets
)
train_state = train_state.apply_gradients(grads=grads)
return train_state, total_loss
(
train_state,
init_hstate,
traj_batch,
advantages,
targets,
rng,
) = update_state
rng, _rng = jax.random.split(rng)
permutation = jax.random.permutation(_rng, config["NUM_ENVS"])
batch = (init_hstate, traj_batch, advantages, targets)
shuffled_batch = jax.tree.map(
lambda x: jnp.take(x, permutation, axis=1), batch
)
minibatches = jax.tree.map(
lambda x: jnp.swapaxes(
jnp.reshape(
x,
[x.shape[0], config["NUM_MINIBATCHES"], -1]
+ list(x.shape[2:]),
),
1,
0,
),
shuffled_batch,
)
train_state, total_loss = jax.lax.scan(
_update_minbatch, train_state, minibatches
)
update_state = (
train_state,
init_hstate,
traj_batch,
advantages,
targets,
rng,
)
return update_state, total_loss
init_hstate = initial_hstate[None, :] # TBH
update_state = (
train_state,
init_hstate,
traj_batch,
advantages,
targets,
rng,
)
update_state, loss_info = jax.lax.scan(
_update_epoch, update_state, None, config["UPDATE_EPOCHS"]
)
train_state = update_state[0]
metric = jax.tree.map(
lambda x: (x * traj_batch.info["returned_episode"]).sum()
/ traj_batch.info["returned_episode"].sum(),
traj_batch.info,
)
rng = update_state[-1]
if config["DEBUG"] and config["USE_WANDB"]:
def callback(metric, update_step):
to_log = create_log_dict(metric, config)
batch_log(update_step, to_log, config)
jax.debug.callback(callback, metric, update_step)
runner_state = (
train_state,
env_state,
last_obs,
last_done,
hstate,
rng,
update_step + 1,
)
return runner_state, metric
rng, _rng = jax.random.split(rng)
runner_state = (
train_state,
env_state,
obsv,
jnp.zeros((config["NUM_ENVS"]), dtype=bool),
init_hstate,
_rng,
0,
)
runner_state, metric = jax.lax.scan(
_update_step, runner_state, None, config["NUM_UPDATES"]
)
return {"runner_state": runner_state, "metric": metric}
return train
def run_ppo(config):
config = {k.upper(): v for k, v in config.__dict__.items()}
if config["USE_WANDB"]:
wandb.init(
project=config["WANDB_PROJECT"],
entity=config["WANDB_ENTITY"],
config=config,
name=config["ENV_NAME"]
+ "-PPO_RNN-"
+ str(int(config["TOTAL_TIMESTEPS"] // 1e6))
+ "M",
)
rng = jax.random.PRNGKey(config["SEED"])
rngs = jax.random.split(rng, config["NUM_REPEATS"])
train_jit = jax.jit(make_train(config))
train_vmap = jax.vmap(train_jit)
t0 = time.time()
out = train_vmap(rngs)
t1 = time.time()
print("Time to run experiment", t1 - t0)
print("SPS: ", config["TOTAL_TIMESTEPS"] / (t1 - t0))
if config["USE_WANDB"]:
def _save_network(rs_index, dir_name):
train_states = out["runner_state"][rs_index]
train_state = jax.tree.map(lambda x: x[0], train_states)
orbax_checkpointer = PyTreeCheckpointer()
options = CheckpointManagerOptions(max_to_keep=1, create=True)
path = os.path.join(wandb.run.dir, dir_name)
checkpoint_manager = CheckpointManager(path, orbax_checkpointer, options)
print(f"saved runner state to {path}")
save_args = orbax_utils.save_args_from_target(train_state)
checkpoint_manager.save(
config["TOTAL_TIMESTEPS"],
train_state,
save_kwargs={"save_args": save_args},
)
if config["SAVE_POLICY"]:
_save_network(0, "policies")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--env_name", type=str, default="Craftax-Symbolic-v1")
parser.add_argument(
"--num_envs",
type=int,
default=1024,
)
parser.add_argument("--total_timesteps", type=lambda x: int(float(x)), default=1e9)
parser.add_argument("--lr", type=float, default=2e-4)
parser.add_argument("--num_steps", type=int, default=64)
parser.add_argument("--update_epochs", type=int, default=4)
parser.add_argument("--num_minibatches", type=int, default=8)
parser.add_argument("--gamma", type=float, default=0.99)
parser.add_argument("--gae_lambda", type=float, default=0.8)
parser.add_argument("--clip_eps", type=float, default=0.2)
parser.add_argument("--ent_coef", type=float, default=0.01)
parser.add_argument("--vf_coef", type=float, default=0.5)
parser.add_argument("--max_grad_norm", type=float, default=1.0)
parser.add_argument("--activation", type=str, default="tanh")
parser.add_argument(
"--anneal_lr", action=argparse.BooleanOptionalAction, default=True
)
parser.add_argument("--debug", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--jit", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--seed", type=int, default=np.random.randint(2**31))
parser.add_argument(
"--use_wandb", action=argparse.BooleanOptionalAction, default=True
)
parser.add_argument(
"--save_policy", action=argparse.BooleanOptionalAction, default=False
)
parser.add_argument("--num_repeats", type=int, default=1)
parser.add_argument("--layer_size", type=int, default=512)
parser.add_argument("--wandb_project", type=str)
parser.add_argument("--wandb_entity", type=str)
parser.add_argument(
"--use_optimistic_resets", action=argparse.BooleanOptionalAction, default=True
)
parser.add_argument("--optimistic_reset_ratio", type=int, default=16)
args, rest_args = parser.parse_known_args(sys.argv[1:])
if rest_args:
raise ValueError(f"Unknown args {rest_args}")
if args.seed is None:
args.seed = np.random.randint(2**31)
if args.jit:
run_ppo(args)
else:
with jax.disable_jit():
run_ppo(args)