pushing model
Browse files- .gitattributes +1 -0
- README.md +96 -0
- cleanba_impala_envpool_machado_atari_wrapper.py +774 -0
- cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4.cleanrl_model +3 -0
- events.out.tfevents.1679763897.ip-26-0-129-1 +3 -0
- poetry.lock +0 -0
- pyproject.toml +34 -0
- replay.mp4 +0 -0
- videos/WizardOfWor-v5__cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4__1__c3f36fae-d16b-49a1-b5a9-1e174fb701d7-eval/0.mp4 +0 -0
.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_impala_envpool_machado_atari_wrapper_a0_l1_d4.cleanrl_model filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
tags:
|
3 |
+
- WizardOfWor-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: WizardOfWor-v5
|
16 |
+
type: WizardOfWor-v5
|
17 |
+
metrics:
|
18 |
+
- type: mean_reward
|
19 |
+
value: 5430.00 +/- 3764.85
|
20 |
+
name: mean_reward
|
21 |
+
verified: false
|
22 |
+
---
|
23 |
+
|
24 |
+
# (CleanRL) **PPO** Agent Playing **WizardOfWor-v5**
|
25 |
+
|
26 |
+
This is a trained model of a PPO agent playing WizardOfWor-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_impala_envpool_machado_atari_wrapper_a0_l1_d4.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_impala_envpool_machado_atari_wrapper_a0_l1_d4 --env-id WizardOfWor-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/WizardOfWor-v5-cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4-seed1/raw/main/cleanba_impala_envpool_machado_atari_wrapper.py
|
46 |
+
curl -OL https://huggingface.co/cleanrl/WizardOfWor-v5-cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4-seed1/raw/main/pyproject.toml
|
47 |
+
curl -OL https://huggingface.co/cleanrl/WizardOfWor-v5-cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4-seed1/raw/main/poetry.lock
|
48 |
+
poetry install --all-extras
|
49 |
+
python cleanba_impala_envpool_machado_atari_wrapper.py --exp-name cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4 --distributed --learner-device-ids 1 --local-num-envs 30 --track --wandb-project-name cleanba --save-model --upload-model --hf-entity cleanrl --env-id WizardOfWor-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': 30,
|
58 |
+
'async_update': 1,
|
59 |
+
'batch_size': 2400,
|
60 |
+
'capture_video': False,
|
61 |
+
'cuda': True,
|
62 |
+
'distributed': True,
|
63 |
+
'ent_coef': 0.01,
|
64 |
+
'env_id': 'WizardOfWor-v5',
|
65 |
+
'exp_name': 'cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4',
|
66 |
+
'gamma': 0.99,
|
67 |
+
'global_learner_decices': ['gpu:1', 'gpu:3', 'gpu:5', 'gpu:7'],
|
68 |
+
'hf_entity': 'cleanrl',
|
69 |
+
'learner_device_ids': [1],
|
70 |
+
'learner_devices': ['gpu:1'],
|
71 |
+
'learning_rate': 0.00025,
|
72 |
+
'local_batch_size': 600,
|
73 |
+
'local_minibatch_size': 300,
|
74 |
+
'local_num_envs': 30,
|
75 |
+
'local_rank': 0,
|
76 |
+
'max_grad_norm': 0.5,
|
77 |
+
'minibatch_size': 1200,
|
78 |
+
'num_envs': 120,
|
79 |
+
'num_minibatches': 2,
|
80 |
+
'num_steps': 20,
|
81 |
+
'num_updates': 20833,
|
82 |
+
'profile': False,
|
83 |
+
'save_model': True,
|
84 |
+
'seed': 1,
|
85 |
+
'target_kl': None,
|
86 |
+
'test_actor_learner_throughput': False,
|
87 |
+
'torch_deterministic': True,
|
88 |
+
'total_timesteps': 50000000,
|
89 |
+
'track': True,
|
90 |
+
'upload_model': True,
|
91 |
+
'vf_coef': 0.5,
|
92 |
+
'wandb_entity': None,
|
93 |
+
'wandb_project_name': 'cleanba',
|
94 |
+
'world_size': 4}
|
95 |
+
```
|
96 |
+
|
cleanba_impala_envpool_machado_atari_wrapper.py
ADDED
@@ -0,0 +1,774 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import time
|
5 |
+
import uuid
|
6 |
+
from collections import deque
|
7 |
+
from distutils.util import strtobool
|
8 |
+
from functools import partial
|
9 |
+
from typing import Sequence
|
10 |
+
|
11 |
+
os.environ[
|
12 |
+
"XLA_PYTHON_CLIENT_MEM_FRACTION"
|
13 |
+
] = "0.6" # see https://github.com/google/jax/discussions/6332#discussioncomment-1279991
|
14 |
+
os.environ["XLA_FLAGS"] = "--xla_cpu_multi_thread_eigen=false " "intra_op_parallelism_threads=1"
|
15 |
+
import queue
|
16 |
+
import threading
|
17 |
+
|
18 |
+
import envpool
|
19 |
+
import flax
|
20 |
+
import flax.linen as nn
|
21 |
+
import gym
|
22 |
+
import jax
|
23 |
+
import jax.numpy as jnp
|
24 |
+
import numpy as np
|
25 |
+
import optax
|
26 |
+
import rlax
|
27 |
+
from flax.linen.initializers import constant, orthogonal
|
28 |
+
from flax.training.train_state import TrainState
|
29 |
+
from tensorboardX 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="whether 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("--num-steps", type=int, default=20,
|
68 |
+
help="the number of steps to run in each environment per policy rollout")
|
69 |
+
parser.add_argument("--anneal-lr", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
|
70 |
+
help="Toggle learning rate annealing for policy and value networks")
|
71 |
+
parser.add_argument("--gamma", type=float, default=0.99,
|
72 |
+
help="the discount factor gamma")
|
73 |
+
parser.add_argument("--num-minibatches", type=int, default=2,
|
74 |
+
help="the number of mini-batches")
|
75 |
+
parser.add_argument("--ent-coef", type=float, default=0.01,
|
76 |
+
help="coefficient of the entropy")
|
77 |
+
parser.add_argument("--vf-coef", type=float, default=0.5,
|
78 |
+
help="coefficient of the value function")
|
79 |
+
parser.add_argument("--max-grad-norm", type=float, default=0.5,
|
80 |
+
help="the maximum norm for the gradient clipping")
|
81 |
+
parser.add_argument("--target-kl", type=float, default=None,
|
82 |
+
help="the target KL divergence threshold")
|
83 |
+
|
84 |
+
parser.add_argument("--actor-device-ids", type=int, nargs="+", default=[0], # type is actually List[int]
|
85 |
+
help="the device ids that actor workers will use (currently only support 1 device)")
|
86 |
+
parser.add_argument("--learner-device-ids", type=int, nargs="+", default=[0], # type is actually List[int]
|
87 |
+
help="the device ids that learner workers will use")
|
88 |
+
parser.add_argument("--distributed", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
89 |
+
help="whether to use `jax.distirbuted`")
|
90 |
+
parser.add_argument("--profile", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
91 |
+
help="whether to call block_until_ready() for profiling")
|
92 |
+
parser.add_argument("--test-actor-learner-throughput", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
93 |
+
help="whether to test actor-learner throughput by removing the actor-learner communication")
|
94 |
+
args = parser.parse_args()
|
95 |
+
args.async_batch_size = args.local_num_envs # local_num_envs must be equal to async_batch_size due to limitation of `rlax`
|
96 |
+
args.local_batch_size = int(args.local_num_envs * args.num_steps)
|
97 |
+
args.local_minibatch_size = int(args.local_batch_size // args.num_minibatches)
|
98 |
+
args.num_updates = args.total_timesteps // args.local_batch_size
|
99 |
+
args.async_update = int(args.local_num_envs / args.async_batch_size)
|
100 |
+
assert len(args.actor_device_ids) == 1, "only 1 actor_device_ids is supported now"
|
101 |
+
# fmt: on
|
102 |
+
return args
|
103 |
+
|
104 |
+
|
105 |
+
ATARI_MAX_FRAMES = int(
|
106 |
+
108000 / 4
|
107 |
+
) # 108000 is the max number of frames in an Atari game, divided by 4 to account for frame skipping
|
108 |
+
|
109 |
+
|
110 |
+
def make_env(env_id, seed, num_envs, async_batch_size=1):
|
111 |
+
def thunk():
|
112 |
+
envs = envpool.make(
|
113 |
+
env_id,
|
114 |
+
env_type="gym",
|
115 |
+
num_envs=num_envs,
|
116 |
+
batch_size=async_batch_size,
|
117 |
+
episodic_life=False, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 6
|
118 |
+
repeat_action_probability=0.25, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 12
|
119 |
+
noop_max=1, # Machado et al. 2017 (Revisitng ALE: Eval protocols) p. 12 (no-op is deprecated in favor of sticky action, right?)
|
120 |
+
full_action_space=True, # Machado et al. 2017 (Revisitng ALE: Eval protocols) Tab. 5
|
121 |
+
max_episode_steps=ATARI_MAX_FRAMES, # Hessel et al. 2018 (Rainbow DQN), Table 3, Max frames per episode
|
122 |
+
reward_clip=True,
|
123 |
+
seed=seed,
|
124 |
+
)
|
125 |
+
envs.num_envs = num_envs
|
126 |
+
envs.single_action_space = envs.action_space
|
127 |
+
envs.single_observation_space = envs.observation_space
|
128 |
+
envs.is_vector_env = True
|
129 |
+
return envs
|
130 |
+
|
131 |
+
return thunk
|
132 |
+
|
133 |
+
|
134 |
+
class ResidualBlock(nn.Module):
|
135 |
+
channels: int
|
136 |
+
|
137 |
+
@nn.compact
|
138 |
+
def __call__(self, x):
|
139 |
+
inputs = x
|
140 |
+
x = nn.relu(x)
|
141 |
+
x = nn.Conv(
|
142 |
+
self.channels,
|
143 |
+
kernel_size=(3, 3),
|
144 |
+
)(x)
|
145 |
+
x = nn.relu(x)
|
146 |
+
x = nn.Conv(
|
147 |
+
self.channels,
|
148 |
+
kernel_size=(3, 3),
|
149 |
+
)(x)
|
150 |
+
return x + inputs
|
151 |
+
|
152 |
+
|
153 |
+
class ConvSequence(nn.Module):
|
154 |
+
channels: int
|
155 |
+
|
156 |
+
@nn.compact
|
157 |
+
def __call__(self, x):
|
158 |
+
x = nn.Conv(
|
159 |
+
self.channels,
|
160 |
+
kernel_size=(3, 3),
|
161 |
+
)(x)
|
162 |
+
x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
|
163 |
+
x = ResidualBlock(self.channels)(x)
|
164 |
+
x = ResidualBlock(self.channels)(x)
|
165 |
+
return x
|
166 |
+
|
167 |
+
|
168 |
+
class Network(nn.Module):
|
169 |
+
channelss: Sequence[int] = (16, 32, 32)
|
170 |
+
|
171 |
+
@nn.compact
|
172 |
+
def __call__(self, x):
|
173 |
+
x = jnp.transpose(x, (0, 2, 3, 1))
|
174 |
+
x = x / (255.0)
|
175 |
+
for channels in self.channelss:
|
176 |
+
x = ConvSequence(channels)(x)
|
177 |
+
x = nn.relu(x)
|
178 |
+
x = x.reshape((x.shape[0], -1))
|
179 |
+
x = nn.Dense(256, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0))(x)
|
180 |
+
x = nn.relu(x)
|
181 |
+
return x
|
182 |
+
|
183 |
+
|
184 |
+
class Critic(nn.Module):
|
185 |
+
@nn.compact
|
186 |
+
def __call__(self, x):
|
187 |
+
return nn.Dense(1, kernel_init=orthogonal(1), bias_init=constant(0.0))(x)
|
188 |
+
|
189 |
+
|
190 |
+
class Actor(nn.Module):
|
191 |
+
action_dim: int
|
192 |
+
|
193 |
+
@nn.compact
|
194 |
+
def __call__(self, x):
|
195 |
+
return nn.Dense(self.action_dim, kernel_init=orthogonal(0.01), bias_init=constant(0.0))(x)
|
196 |
+
|
197 |
+
|
198 |
+
@flax.struct.dataclass
|
199 |
+
class AgentParams:
|
200 |
+
network_params: flax.core.FrozenDict
|
201 |
+
actor_params: flax.core.FrozenDict
|
202 |
+
critic_params: flax.core.FrozenDict
|
203 |
+
|
204 |
+
|
205 |
+
@partial(jax.jit, static_argnums=(3))
|
206 |
+
def get_action(
|
207 |
+
params: flax.core.FrozenDict,
|
208 |
+
next_obs: np.ndarray,
|
209 |
+
key: jax.random.PRNGKey,
|
210 |
+
action_dim: int,
|
211 |
+
):
|
212 |
+
next_obs = jnp.array(next_obs)
|
213 |
+
hidden = Network().apply(params.network_params, next_obs)
|
214 |
+
logits = Actor(action_dim).apply(params.actor_params, hidden)
|
215 |
+
# sample action: Gumbel-softmax trick
|
216 |
+
# see https://stats.stackexchange.com/questions/359442/sampling-from-a-categorical-distribution
|
217 |
+
key, subkey = jax.random.split(key)
|
218 |
+
u = jax.random.uniform(subkey, shape=logits.shape)
|
219 |
+
action = jnp.argmax(logits - jnp.log(-jnp.log(u)), axis=1)
|
220 |
+
return next_obs, action, logits, key
|
221 |
+
|
222 |
+
|
223 |
+
def prepare_data(
|
224 |
+
obs: list,
|
225 |
+
dones: list,
|
226 |
+
actions: list,
|
227 |
+
logitss: list,
|
228 |
+
firststeps: list,
|
229 |
+
env_ids: list,
|
230 |
+
rewards: list,
|
231 |
+
):
|
232 |
+
obs = jnp.asarray(obs)
|
233 |
+
dones = jnp.asarray(dones)
|
234 |
+
actions = jnp.asarray(actions)
|
235 |
+
logitss = jnp.asarray(logitss)
|
236 |
+
firststeps = jnp.asarray(firststeps)
|
237 |
+
env_ids = jnp.asarray(env_ids)
|
238 |
+
rewards = jnp.asarray(rewards)
|
239 |
+
return obs, dones, actions, logitss, firststeps, env_ids, rewards
|
240 |
+
|
241 |
+
|
242 |
+
@jax.jit
|
243 |
+
def make_bulk_array(
|
244 |
+
obs: list,
|
245 |
+
actions: list,
|
246 |
+
logitss: list,
|
247 |
+
):
|
248 |
+
obs = jnp.asarray(obs)
|
249 |
+
actions = jnp.asarray(actions)
|
250 |
+
logitss = jnp.asarray(logitss)
|
251 |
+
return obs, actions, logitss
|
252 |
+
|
253 |
+
|
254 |
+
def rollout(
|
255 |
+
key: jax.random.PRNGKey,
|
256 |
+
args,
|
257 |
+
rollout_queue,
|
258 |
+
params_queue: queue.Queue,
|
259 |
+
writer,
|
260 |
+
learner_devices,
|
261 |
+
):
|
262 |
+
envs = make_env(args.env_id, args.seed + jax.process_index(), args.local_num_envs, args.async_batch_size)()
|
263 |
+
len_actor_device_ids = len(args.actor_device_ids)
|
264 |
+
global_step = 0
|
265 |
+
# TRY NOT TO MODIFY: start the game
|
266 |
+
start_time = time.time()
|
267 |
+
|
268 |
+
# put data in the last index
|
269 |
+
episode_returns = np.zeros((args.local_num_envs,), dtype=np.float32)
|
270 |
+
returned_episode_returns = np.zeros((args.local_num_envs,), dtype=np.float32)
|
271 |
+
episode_lengths = np.zeros((args.local_num_envs,), dtype=np.float32)
|
272 |
+
returned_episode_lengths = np.zeros((args.local_num_envs,), dtype=np.float32)
|
273 |
+
envs.async_reset()
|
274 |
+
|
275 |
+
params_queue_get_time = deque(maxlen=10)
|
276 |
+
rollout_time = deque(maxlen=10)
|
277 |
+
rollout_queue_put_time = deque(maxlen=10)
|
278 |
+
actor_policy_version = 0
|
279 |
+
obs = []
|
280 |
+
dones = []
|
281 |
+
actions = []
|
282 |
+
logitss = []
|
283 |
+
env_ids = []
|
284 |
+
rewards = []
|
285 |
+
truncations = []
|
286 |
+
terminations = []
|
287 |
+
firststeps = [] # first step of an episode
|
288 |
+
for update in range(1, args.num_updates + 2):
|
289 |
+
# NOTE: This is a major difference from the sync version:
|
290 |
+
# at the end of the rollout phase, the sync version will have the next observation
|
291 |
+
# ready for the value bootstrap, but the async version will not have it.
|
292 |
+
# for this reason we do `num_steps + 1`` to get the extra states for value bootstrapping.
|
293 |
+
# but note that the extra states are not used for the loss computation in the next iteration,
|
294 |
+
# while the sync version will use the extra state for the loss computation.
|
295 |
+
update_time_start = time.time()
|
296 |
+
env_recv_time = 0
|
297 |
+
inference_time = 0
|
298 |
+
storage_time = 0
|
299 |
+
env_send_time = 0
|
300 |
+
|
301 |
+
num_steps_with_bootstrap = args.num_steps + 1 + int(len(obs) == 0)
|
302 |
+
# NOTE: `update != 2` is actually IMPORTANT — it allows us to start running policy collection
|
303 |
+
# concurrently with the learning process. It also ensures the actor's policy version is only 1 step
|
304 |
+
# behind the learner's policy version
|
305 |
+
params_queue_get_time_start = time.time()
|
306 |
+
if update != 2:
|
307 |
+
params = params_queue.get()
|
308 |
+
actor_policy_version += 1
|
309 |
+
params_queue_get_time.append(time.time() - params_queue_get_time_start)
|
310 |
+
writer.add_scalar("stats/params_queue_get_time", np.mean(params_queue_get_time), global_step)
|
311 |
+
rollout_time_start = time.time()
|
312 |
+
for _ in range(
|
313 |
+
args.async_update, (num_steps_with_bootstrap) * args.async_update
|
314 |
+
): # num_steps + 1 to get the states for value bootstrapping.
|
315 |
+
env_recv_time_start = time.time()
|
316 |
+
next_obs, next_reward, next_done, info = envs.recv()
|
317 |
+
env_recv_time += time.time() - env_recv_time_start
|
318 |
+
global_step += len(next_done) * len_actor_device_ids * args.world_size
|
319 |
+
env_id = info["env_id"]
|
320 |
+
|
321 |
+
inference_time_start = time.time()
|
322 |
+
next_obs, action, logits, key = get_action(params, next_obs, key, envs.single_action_space.n)
|
323 |
+
inference_time += time.time() - inference_time_start
|
324 |
+
|
325 |
+
env_send_time_start = time.time()
|
326 |
+
envs.send(np.array(action), env_id)
|
327 |
+
env_send_time += time.time() - env_send_time_start
|
328 |
+
storage_time_start = time.time()
|
329 |
+
obs.append(next_obs)
|
330 |
+
dones.append(next_done)
|
331 |
+
actions.append(action)
|
332 |
+
logitss.append(logits)
|
333 |
+
env_ids.append(env_id)
|
334 |
+
rewards.append(next_reward)
|
335 |
+
firststeps.append(info["elapsed_step"] == 0)
|
336 |
+
|
337 |
+
# info["TimeLimit.truncated"] has a bug https://github.com/sail-sg/envpool/issues/239
|
338 |
+
# so we use our own truncated flag
|
339 |
+
truncated = info["elapsed_step"] >= envs.spec.config.max_episode_steps
|
340 |
+
truncations.append(truncated)
|
341 |
+
terminations.append(info["terminated"])
|
342 |
+
episode_returns[env_id] += info["reward"]
|
343 |
+
returned_episode_returns[env_id] = np.where(
|
344 |
+
info["terminated"] + truncated, episode_returns[env_id], returned_episode_returns[env_id]
|
345 |
+
)
|
346 |
+
episode_returns[env_id] *= (1 - info["terminated"]) * (1 - truncated)
|
347 |
+
episode_lengths[env_id] += 1
|
348 |
+
returned_episode_lengths[env_id] = np.where(
|
349 |
+
info["terminated"] + truncated, episode_lengths[env_id], returned_episode_lengths[env_id]
|
350 |
+
)
|
351 |
+
episode_lengths[env_id] *= (1 - info["terminated"]) * (1 - truncated)
|
352 |
+
storage_time += time.time() - storage_time_start
|
353 |
+
if args.profile:
|
354 |
+
action.block_until_ready()
|
355 |
+
rollout_time.append(time.time() - rollout_time_start)
|
356 |
+
writer.add_scalar("stats/rollout_time", np.mean(rollout_time), global_step)
|
357 |
+
|
358 |
+
avg_episodic_return = np.mean(returned_episode_returns)
|
359 |
+
writer.add_scalar("charts/avg_episodic_return", avg_episodic_return, global_step)
|
360 |
+
writer.add_scalar("charts/avg_episodic_length", np.mean(returned_episode_lengths), global_step)
|
361 |
+
print(f"global_step={global_step}, avg_episodic_return={avg_episodic_return}")
|
362 |
+
print("SPS:", int(global_step / (time.time() - start_time)))
|
363 |
+
writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
|
364 |
+
|
365 |
+
writer.add_scalar("stats/truncations", np.sum(truncations), global_step)
|
366 |
+
writer.add_scalar("stats/terminations", np.sum(terminations), global_step)
|
367 |
+
writer.add_scalar("stats/env_recv_time", env_recv_time, global_step)
|
368 |
+
writer.add_scalar("stats/inference_time", inference_time, global_step)
|
369 |
+
writer.add_scalar("stats/storage_time", storage_time, global_step)
|
370 |
+
writer.add_scalar("stats/env_send_time", env_send_time, global_step)
|
371 |
+
# `make_bulk_array` is actually important. It accumulates the data from the lists
|
372 |
+
# into single bulk arrays, which later makes transferring the data to the learner's
|
373 |
+
# device slightly faster. See https://wandb.ai/costa-huang/cleanRL/reports/data-transfer-optimization--VmlldzozNjU5MTg1
|
374 |
+
c_obs, c_actions, c_logitss = obs, actions, logitss
|
375 |
+
if args.learner_device_ids[0] != args.actor_device_ids[0]:
|
376 |
+
c_obs, c_actions, c_logitss = make_bulk_array(
|
377 |
+
obs,
|
378 |
+
actions,
|
379 |
+
logitss,
|
380 |
+
)
|
381 |
+
|
382 |
+
payload = (
|
383 |
+
global_step,
|
384 |
+
actor_policy_version,
|
385 |
+
update,
|
386 |
+
c_obs,
|
387 |
+
c_actions,
|
388 |
+
c_logitss,
|
389 |
+
firststeps,
|
390 |
+
dones,
|
391 |
+
env_ids,
|
392 |
+
rewards,
|
393 |
+
np.mean(params_queue_get_time),
|
394 |
+
)
|
395 |
+
if update == 1 or not args.test_actor_learner_throughput:
|
396 |
+
rollout_queue_put_time_start = time.time()
|
397 |
+
rollout_queue.put(payload)
|
398 |
+
rollout_queue_put_time.append(time.time() - rollout_queue_put_time_start)
|
399 |
+
writer.add_scalar("stats/rollout_queue_put_time", np.mean(rollout_queue_put_time), global_step)
|
400 |
+
|
401 |
+
writer.add_scalar(
|
402 |
+
"charts/SPS_update",
|
403 |
+
int(
|
404 |
+
args.local_num_envs
|
405 |
+
* args.num_steps
|
406 |
+
* len_actor_device_ids
|
407 |
+
* args.world_size
|
408 |
+
/ (time.time() - update_time_start)
|
409 |
+
),
|
410 |
+
global_step,
|
411 |
+
)
|
412 |
+
|
413 |
+
obs = obs[-args.async_update :]
|
414 |
+
dones = dones[-args.async_update :]
|
415 |
+
actions = actions[-args.async_update :]
|
416 |
+
logitss = logitss[-args.async_update :]
|
417 |
+
env_ids = env_ids[-args.async_update :]
|
418 |
+
rewards = rewards[-args.async_update :]
|
419 |
+
truncations = truncations[-args.async_update :]
|
420 |
+
terminations = terminations[-args.async_update :]
|
421 |
+
firststeps = firststeps[-args.async_update :]
|
422 |
+
|
423 |
+
|
424 |
+
@partial(jax.jit, static_argnums=(2))
|
425 |
+
def get_action_and_value2(
|
426 |
+
params: flax.core.FrozenDict,
|
427 |
+
x: np.ndarray,
|
428 |
+
action_dim: int,
|
429 |
+
):
|
430 |
+
hidden = Network().apply(params.network_params, x)
|
431 |
+
raw_logits = Actor(action_dim).apply(params.actor_params, hidden)
|
432 |
+
value = Critic().apply(params.critic_params, hidden).squeeze()
|
433 |
+
return raw_logits, value
|
434 |
+
|
435 |
+
|
436 |
+
def policy_gradient_loss(logits, *args):
|
437 |
+
"""rlax.policy_gradient_loss, but with sum(loss) and [T, B, ...] inputs."""
|
438 |
+
mean_per_batch = jax.vmap(rlax.policy_gradient_loss, in_axes=1)(logits, *args)
|
439 |
+
total_loss_per_batch = mean_per_batch * logits.shape[0]
|
440 |
+
return jnp.sum(total_loss_per_batch)
|
441 |
+
|
442 |
+
|
443 |
+
def entropy_loss_fn(logits, *args):
|
444 |
+
"""rlax.entropy_loss, but with sum(loss) and [T, B, ...] inputs."""
|
445 |
+
mean_per_batch = jax.vmap(rlax.entropy_loss, in_axes=1)(logits, *args)
|
446 |
+
total_loss_per_batch = mean_per_batch * logits.shape[0]
|
447 |
+
return jnp.sum(total_loss_per_batch)
|
448 |
+
|
449 |
+
|
450 |
+
def impala_loss(params, x, a, logitss, rewards, dones, firststeps, action_dim):
|
451 |
+
discounts = (1.0 - dones) * args.gamma
|
452 |
+
mask = 1.0 - firststeps
|
453 |
+
policy_logits, newvalue = jax.vmap(get_action_and_value2, in_axes=(None, 0, None))(params, x, action_dim)
|
454 |
+
|
455 |
+
v_t = newvalue[1:]
|
456 |
+
# Remove bootstrap timestep from non-timesteps.
|
457 |
+
v_tm1 = newvalue[:-1]
|
458 |
+
policy_logits = policy_logits[:-1]
|
459 |
+
logitss = logitss[:-1]
|
460 |
+
a = a[:-1]
|
461 |
+
mask = mask[:-1]
|
462 |
+
rewards = rewards[:-1]
|
463 |
+
discounts = discounts[:-1]
|
464 |
+
|
465 |
+
rhos = rlax.categorical_importance_sampling_ratios(policy_logits, logitss, a)
|
466 |
+
vtrace_td_error_and_advantage = jax.vmap(rlax.vtrace_td_error_and_advantage, in_axes=1, out_axes=1)
|
467 |
+
|
468 |
+
vtrace_returns = vtrace_td_error_and_advantage(v_tm1, v_t, rewards, discounts, rhos)
|
469 |
+
pg_advs = vtrace_returns.pg_advantage
|
470 |
+
pg_loss = policy_gradient_loss(policy_logits, a, pg_advs, mask)
|
471 |
+
|
472 |
+
baseline_loss = 0.5 * jnp.sum(jnp.square(vtrace_returns.errors) * mask)
|
473 |
+
ent_loss = entropy_loss_fn(policy_logits, mask)
|
474 |
+
|
475 |
+
total_loss = pg_loss
|
476 |
+
total_loss += args.vf_coef * baseline_loss
|
477 |
+
total_loss += args.ent_coef * ent_loss
|
478 |
+
return total_loss, (pg_loss, baseline_loss, ent_loss)
|
479 |
+
|
480 |
+
|
481 |
+
@partial(jax.jit, static_argnames=("action_dim"))
|
482 |
+
def single_device_update(
|
483 |
+
agent_state: TrainState,
|
484 |
+
obs,
|
485 |
+
actions,
|
486 |
+
logitss,
|
487 |
+
rewards,
|
488 |
+
dones,
|
489 |
+
firststeps,
|
490 |
+
action_dim,
|
491 |
+
key: jax.random.PRNGKey,
|
492 |
+
):
|
493 |
+
impala_loss_grad_fn = jax.value_and_grad(impala_loss, has_aux=True)
|
494 |
+
|
495 |
+
def update_minibatch(agent_state, minibatch):
|
496 |
+
mb_obs, mb_actions, mb_logitss, mb_rewards, mb_dones, mb_firststeps = minibatch
|
497 |
+
(loss, (pg_loss, v_loss, entropy_loss)), grads = impala_loss_grad_fn(
|
498 |
+
agent_state.params,
|
499 |
+
mb_obs,
|
500 |
+
mb_actions,
|
501 |
+
mb_logitss,
|
502 |
+
mb_rewards,
|
503 |
+
mb_dones,
|
504 |
+
mb_firststeps,
|
505 |
+
action_dim,
|
506 |
+
)
|
507 |
+
grads = jax.lax.pmean(grads, axis_name="local_devices")
|
508 |
+
agent_state = agent_state.apply_gradients(grads=grads)
|
509 |
+
return agent_state, (loss, pg_loss, v_loss, entropy_loss)
|
510 |
+
|
511 |
+
agent_state, (loss, pg_loss, v_loss, entropy_loss) = jax.lax.scan(
|
512 |
+
update_minibatch,
|
513 |
+
agent_state,
|
514 |
+
(
|
515 |
+
jnp.array(jnp.split(obs, args.num_minibatches, axis=1)),
|
516 |
+
jnp.array(jnp.split(actions, args.num_minibatches, axis=1)),
|
517 |
+
jnp.array(jnp.split(logitss, args.num_minibatches, axis=1)),
|
518 |
+
jnp.array(jnp.split(rewards, args.num_minibatches, axis=1)),
|
519 |
+
jnp.array(jnp.split(dones, args.num_minibatches, axis=1)),
|
520 |
+
jnp.array(jnp.split(firststeps, args.num_minibatches, axis=1)),
|
521 |
+
),
|
522 |
+
)
|
523 |
+
return agent_state, loss, pg_loss, v_loss, entropy_loss, key
|
524 |
+
|
525 |
+
|
526 |
+
if __name__ == "__main__":
|
527 |
+
args = parse_args()
|
528 |
+
if args.distributed:
|
529 |
+
jax.distributed.initialize(
|
530 |
+
local_device_ids=range(len(args.learner_device_ids) + len(args.actor_device_ids)),
|
531 |
+
)
|
532 |
+
print(list(range(len(args.learner_device_ids) + len(args.actor_device_ids))))
|
533 |
+
|
534 |
+
args.world_size = jax.process_count()
|
535 |
+
args.local_rank = jax.process_index()
|
536 |
+
args.num_envs = args.local_num_envs * args.world_size
|
537 |
+
args.batch_size = args.local_batch_size * args.world_size
|
538 |
+
args.minibatch_size = args.local_minibatch_size * args.world_size
|
539 |
+
args.num_updates = args.total_timesteps // (args.local_batch_size * args.world_size)
|
540 |
+
args.async_update = int(args.local_num_envs / args.async_batch_size)
|
541 |
+
local_devices = jax.local_devices()
|
542 |
+
global_devices = jax.devices()
|
543 |
+
learner_devices = [local_devices[d_id] for d_id in args.learner_device_ids]
|
544 |
+
actor_devices = [local_devices[d_id] for d_id in args.actor_device_ids]
|
545 |
+
global_learner_decices = [
|
546 |
+
global_devices[d_id + process_index * len(local_devices)]
|
547 |
+
for process_index in range(args.world_size)
|
548 |
+
for d_id in args.learner_device_ids
|
549 |
+
]
|
550 |
+
print("global_learner_decices", global_learner_decices)
|
551 |
+
args.global_learner_decices = [str(item) for item in global_learner_decices]
|
552 |
+
args.actor_devices = [str(item) for item in actor_devices]
|
553 |
+
args.learner_devices = [str(item) for item in learner_devices]
|
554 |
+
|
555 |
+
run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{uuid.uuid4()}"
|
556 |
+
if args.track and args.local_rank == 0:
|
557 |
+
import wandb
|
558 |
+
|
559 |
+
wandb.init(
|
560 |
+
project=args.wandb_project_name,
|
561 |
+
entity=args.wandb_entity,
|
562 |
+
sync_tensorboard=True,
|
563 |
+
config=vars(args),
|
564 |
+
name=run_name,
|
565 |
+
monitor_gym=True,
|
566 |
+
save_code=True,
|
567 |
+
)
|
568 |
+
writer = SummaryWriter(f"runs/{run_name}")
|
569 |
+
writer.add_text(
|
570 |
+
"hyperparameters",
|
571 |
+
"|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
|
572 |
+
)
|
573 |
+
|
574 |
+
# TRY NOT TO MODIFY: seeding
|
575 |
+
random.seed(args.seed)
|
576 |
+
np.random.seed(args.seed)
|
577 |
+
key = jax.random.PRNGKey(args.seed)
|
578 |
+
key, network_key, actor_key, critic_key = jax.random.split(key, 4)
|
579 |
+
|
580 |
+
# env setup
|
581 |
+
envs = make_env(args.env_id, args.seed, args.local_num_envs, args.async_batch_size)()
|
582 |
+
assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
|
583 |
+
|
584 |
+
def linear_schedule(count):
|
585 |
+
# anneal learning rate linearly after one training iteration which contains
|
586 |
+
# (args.num_minibatches) gradient updates
|
587 |
+
frac = 1.0 - (count // (args.num_minibatches)) / args.num_updates
|
588 |
+
return args.learning_rate * frac
|
589 |
+
|
590 |
+
network = Network()
|
591 |
+
actor = Actor(action_dim=envs.single_action_space.n)
|
592 |
+
critic = Critic()
|
593 |
+
network_params = network.init(network_key, np.array([envs.single_observation_space.sample()]))
|
594 |
+
agent_state = TrainState.create(
|
595 |
+
apply_fn=None,
|
596 |
+
params=AgentParams(
|
597 |
+
network_params,
|
598 |
+
actor.init(actor_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
|
599 |
+
critic.init(critic_key, network.apply(network_params, np.array([envs.single_observation_space.sample()]))),
|
600 |
+
),
|
601 |
+
tx=optax.chain(
|
602 |
+
optax.clip_by_global_norm(args.max_grad_norm),
|
603 |
+
optax.inject_hyperparams(optax.adam)(
|
604 |
+
learning_rate=linear_schedule if args.anneal_lr else args.learning_rate, eps=1e-5
|
605 |
+
),
|
606 |
+
),
|
607 |
+
)
|
608 |
+
agent_state = flax.jax_utils.replicate(agent_state, devices=learner_devices)
|
609 |
+
|
610 |
+
multi_device_update = jax.pmap(
|
611 |
+
single_device_update,
|
612 |
+
axis_name="local_devices",
|
613 |
+
devices=global_learner_decices,
|
614 |
+
in_axes=(0, 0, 0, 0, 0, 0, 0, None, None),
|
615 |
+
out_axes=(0, 0, 0, 0, 0, None),
|
616 |
+
static_broadcasted_argnums=(7),
|
617 |
+
)
|
618 |
+
|
619 |
+
rollout_queue = queue.Queue(maxsize=1)
|
620 |
+
params_queues = []
|
621 |
+
for d_idx, d_id in enumerate(args.actor_device_ids):
|
622 |
+
params_queue = queue.Queue(maxsize=1)
|
623 |
+
params_queue.put(jax.device_put(flax.jax_utils.unreplicate(agent_state.params), local_devices[d_id]))
|
624 |
+
threading.Thread(
|
625 |
+
target=rollout,
|
626 |
+
args=(
|
627 |
+
jax.device_put(key, local_devices[d_id]),
|
628 |
+
args,
|
629 |
+
rollout_queue,
|
630 |
+
params_queue,
|
631 |
+
writer,
|
632 |
+
learner_devices,
|
633 |
+
),
|
634 |
+
).start()
|
635 |
+
params_queues.append(params_queue)
|
636 |
+
|
637 |
+
rollout_queue_get_time = deque(maxlen=10)
|
638 |
+
data_transfer_time = deque(maxlen=10)
|
639 |
+
learner_policy_version = 0
|
640 |
+
prepare_data = jax.jit(prepare_data, device=learner_devices[0])
|
641 |
+
while True:
|
642 |
+
learner_policy_version += 1
|
643 |
+
if learner_policy_version == 1 or not args.test_actor_learner_throughput:
|
644 |
+
rollout_queue_get_time_start = time.time()
|
645 |
+
(
|
646 |
+
global_step,
|
647 |
+
actor_policy_version,
|
648 |
+
update,
|
649 |
+
obs,
|
650 |
+
actions,
|
651 |
+
logitss,
|
652 |
+
firststeps,
|
653 |
+
dones,
|
654 |
+
env_ids,
|
655 |
+
rewards,
|
656 |
+
avg_params_queue_get_time,
|
657 |
+
) = rollout_queue.get()
|
658 |
+
rollout_queue_get_time.append(time.time() - rollout_queue_get_time_start)
|
659 |
+
writer.add_scalar("stats/rollout_queue_get_time", np.mean(rollout_queue_get_time), global_step)
|
660 |
+
writer.add_scalar(
|
661 |
+
"stats/rollout_params_queue_get_time_diff",
|
662 |
+
np.mean(rollout_queue_get_time) - avg_params_queue_get_time,
|
663 |
+
global_step,
|
664 |
+
)
|
665 |
+
|
666 |
+
data_transfer_time_start = time.time()
|
667 |
+
obs, dones, actions, logitss, firststeps, env_ids, rewards = prepare_data(
|
668 |
+
obs,
|
669 |
+
dones,
|
670 |
+
actions,
|
671 |
+
logitss,
|
672 |
+
firststeps,
|
673 |
+
env_ids,
|
674 |
+
rewards,
|
675 |
+
)
|
676 |
+
|
677 |
+
obs = jnp.array_split(obs, len(learner_devices), axis=1)
|
678 |
+
actions = jnp.array_split(actions, len(learner_devices), axis=1)
|
679 |
+
logitss = jnp.array_split(logitss, len(learner_devices), axis=1)
|
680 |
+
rewards = jnp.array_split(rewards, len(learner_devices), axis=1)
|
681 |
+
dones = jnp.array_split(dones, len(learner_devices), axis=1)
|
682 |
+
firststeps = jnp.array_split(firststeps, len(learner_devices), axis=1)
|
683 |
+
data_transfer_time.append(time.time() - data_transfer_time_start)
|
684 |
+
writer.add_scalar("stats/data_transfer_time", np.mean(data_transfer_time), global_step)
|
685 |
+
|
686 |
+
training_time_start = time.time()
|
687 |
+
(agent_state, loss, pg_loss, v_loss, entropy_loss, key) = multi_device_update(
|
688 |
+
agent_state,
|
689 |
+
jax.device_put_sharded(obs, learner_devices),
|
690 |
+
jax.device_put_sharded(actions, learner_devices),
|
691 |
+
jax.device_put_sharded(logitss, learner_devices),
|
692 |
+
jax.device_put_sharded(rewards, learner_devices),
|
693 |
+
jax.device_put_sharded(dones, learner_devices),
|
694 |
+
jax.device_put_sharded(firststeps, learner_devices),
|
695 |
+
envs.single_action_space.n,
|
696 |
+
key,
|
697 |
+
)
|
698 |
+
if learner_policy_version == 1 or not args.test_actor_learner_throughput:
|
699 |
+
for d_idx, d_id in enumerate(args.actor_device_ids):
|
700 |
+
params_queues[d_idx].put(jax.device_put(flax.jax_utils.unreplicate(agent_state.params), local_devices[d_id]))
|
701 |
+
if args.profile:
|
702 |
+
v_loss[-1, -1, -1].block_until_ready()
|
703 |
+
writer.add_scalar("stats/training_time", time.time() - training_time_start, global_step)
|
704 |
+
writer.add_scalar("stats/rollout_queue_size", rollout_queue.qsize(), global_step)
|
705 |
+
writer.add_scalar("stats/params_queue_size", params_queue.qsize(), global_step)
|
706 |
+
print(
|
707 |
+
global_step,
|
708 |
+
f"actor_policy_version={actor_policy_version}, actor_update={update}, learner_policy_version={learner_policy_version}, training time: {time.time() - training_time_start}s",
|
709 |
+
)
|
710 |
+
|
711 |
+
# TRY NOT TO MODIFY: record rewards for plotting purposes
|
712 |
+
writer.add_scalar("charts/learning_rate", agent_state.opt_state[1].hyperparams["learning_rate"][0].item(), global_step)
|
713 |
+
writer.add_scalar("losses/value_loss", v_loss[-1, -1].item(), global_step)
|
714 |
+
writer.add_scalar("losses/policy_loss", pg_loss[-1, -1].item(), global_step)
|
715 |
+
writer.add_scalar("losses/entropy", entropy_loss[-1, -1].item(), global_step)
|
716 |
+
writer.add_scalar("losses/loss", loss[-1, -1].item(), global_step)
|
717 |
+
if update >= args.num_updates:
|
718 |
+
break
|
719 |
+
|
720 |
+
# print weights
|
721 |
+
# sum_params(agent_state.params)
|
722 |
+
# print("network_params", agent_state.params.network_params['params']["Dense_0"]["kernel"])
|
723 |
+
# print("actor_params", agent_state.params.actor_params['params']["Dense_0"]["kernel"])
|
724 |
+
# print("critic_params", agent_state.params.critic_params['params']["Dense_0"]["kernel"])
|
725 |
+
|
726 |
+
if args.save_model and args.local_rank == 0:
|
727 |
+
if args.distributed:
|
728 |
+
jax.distributed.shutdown()
|
729 |
+
agent_state = flax.jax_utils.unreplicate(agent_state)
|
730 |
+
model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
|
731 |
+
with open(model_path, "wb") as f:
|
732 |
+
f.write(
|
733 |
+
flax.serialization.to_bytes(
|
734 |
+
[
|
735 |
+
vars(args),
|
736 |
+
[
|
737 |
+
agent_state.params.network_params,
|
738 |
+
agent_state.params.actor_params,
|
739 |
+
agent_state.params.critic_params,
|
740 |
+
],
|
741 |
+
]
|
742 |
+
)
|
743 |
+
)
|
744 |
+
print(f"model saved to {model_path}")
|
745 |
+
from cleanrl_utils.evals.ppo_envpool_jax_eval import evaluate
|
746 |
+
|
747 |
+
episodic_returns = evaluate(
|
748 |
+
model_path,
|
749 |
+
make_env,
|
750 |
+
args.env_id,
|
751 |
+
eval_episodes=10,
|
752 |
+
run_name=f"{run_name}-eval",
|
753 |
+
Model=(Network, Actor, Critic),
|
754 |
+
)
|
755 |
+
for idx, episodic_return in enumerate(episodic_returns):
|
756 |
+
writer.add_scalar("eval/episodic_return", episodic_return, idx)
|
757 |
+
|
758 |
+
if args.upload_model:
|
759 |
+
from cleanrl_utils.huggingface import push_to_hub
|
760 |
+
|
761 |
+
repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
|
762 |
+
repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
|
763 |
+
push_to_hub(
|
764 |
+
args,
|
765 |
+
episodic_returns,
|
766 |
+
repo_id,
|
767 |
+
"PPO",
|
768 |
+
f"runs/{run_name}",
|
769 |
+
f"videos/{run_name}-eval",
|
770 |
+
extra_dependencies=["jax", "envpool", "atari"],
|
771 |
+
)
|
772 |
+
|
773 |
+
envs.close()
|
774 |
+
writer.close()
|
cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4.cleanrl_model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e8b425fa5db6ee9735866c3bf3fbf9a1fee24b2a7c7949c8b0a31ac5dd744e3e
|
3 |
+
size 4378458
|
events.out.tfevents.1679763897.ip-26-0-129-1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:446f5898f55f266ff892af475e043f0561417a66fac18e04105d79212e060825
|
3 |
+
size 30557659
|
poetry.lock
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pyproject.toml
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[tool.poetry]
|
2 |
+
name = "cleanba"
|
3 |
+
version = "0.1.0"
|
4 |
+
description = ""
|
5 |
+
authors = ["Costa Huang <costa.huang@outlook.com>"]
|
6 |
+
readme = "README.md"
|
7 |
+
packages = [
|
8 |
+
{ include = "cleanba" },
|
9 |
+
{ include = "cleanrl_utils" },
|
10 |
+
]
|
11 |
+
|
12 |
+
[tool.poetry.dependencies]
|
13 |
+
python = "^3.8"
|
14 |
+
tensorboard = "^2.12.0"
|
15 |
+
envpool = "^0.8.1"
|
16 |
+
jax = "0.3.25"
|
17 |
+
flax = "0.6.0"
|
18 |
+
optax = "0.1.3"
|
19 |
+
huggingface-hub = "^0.12.0"
|
20 |
+
jaxlib = "0.3.25"
|
21 |
+
wandb = "^0.13.10"
|
22 |
+
tensorboardx = "^2.5.1"
|
23 |
+
chex = "0.1.5"
|
24 |
+
gym = "0.23.1"
|
25 |
+
opencv-python = "^4.7.0.68"
|
26 |
+
moviepy = "^1.0.3"
|
27 |
+
|
28 |
+
|
29 |
+
[tool.poetry.group.dev.dependencies]
|
30 |
+
pre-commit = "^3.0.4"
|
31 |
+
|
32 |
+
[build-system]
|
33 |
+
requires = ["poetry-core"]
|
34 |
+
build-backend = "poetry.core.masonry.api"
|
replay.mp4
ADDED
Binary file (63 kB). View file
|
|
videos/WizardOfWor-v5__cleanba_impala_envpool_machado_atari_wrapper_a0_l1_d4__1__c3f36fae-d16b-49a1-b5a9-1e174fb701d7-eval/0.mp4
ADDED
Binary file (63 kB). View file
|
|