vwxyzjn commited on
Commit
4855287
1 Parent(s): 3fd71ed

pushing model

Browse files
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - CartPole-v1
4
+ - deep-reinforcement-learning
5
+ - reinforcement-learning
6
+ - custom-implementation
7
+ model-index:
8
+ - name: DQN
9
+ results:
10
+ - task:
11
+ type: reinforcement-learning
12
+ name: reinforcement-learning
13
+ dataset:
14
+ name: CartPole-v1
15
+ type: CartPole-v1
16
+ metrics:
17
+ - type: mean_reward
18
+ value: 500.00 +/- 0.00
19
+ name: mean_reward
20
+ verified: false
21
+ ---
22
+
23
+ # (CleanRL) **DQN** Agent Playing **CartPole-v1**
24
+
25
+ This is a trained model of a DQN agent playing CartPole-v1.
26
+ The model was trained by using [CleanRL](https://github.com/vwxyzjn/cleanrl) and the most up-to-date training code can be
27
+ found [here](https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/dqn_jax.py).
28
+
29
+ ## Command to reproduce the training
30
+
31
+ ```bash
32
+ curl -OL https://huggingface.co/cleanrl/CartPole-v1-dqn_jax-seed1/raw/main/dqn.py
33
+ curl -OL https://huggingface.co/cleanrl/CartPole-v1-dqn_jax-seed1/raw/main/pyproject.toml
34
+ curl -OL https://huggingface.co/cleanrl/CartPole-v1-dqn_jax-seed1/raw/main/poetry.lock
35
+ poetry install --all-extras
36
+ python dqn_jax.py --save-model --upload-model --hf-entity cleanrl --seed 1
37
+ ```
38
+
39
+ # Hyperparameters
40
+ ```python
41
+ {'batch_size': 128,
42
+ 'buffer_size': 10000,
43
+ 'capture_video': False,
44
+ 'end_e': 0.05,
45
+ 'env_id': 'CartPole-v1',
46
+ 'exp_name': 'dqn_jax',
47
+ 'exploration_fraction': 0.5,
48
+ 'gamma': 0.99,
49
+ 'hf_entity': 'cleanrl',
50
+ 'learning_rate': 0.00025,
51
+ 'learning_starts': 10000,
52
+ 'save_model': True,
53
+ 'seed': 1,
54
+ 'start_e': 1,
55
+ 'target_network_frequency': 500,
56
+ 'total_timesteps': 500000,
57
+ 'track': False,
58
+ 'train_frequency': 10,
59
+ 'upload_model': True,
60
+ 'wandb_entity': None,
61
+ 'wandb_project_name': 'cleanRL'}
62
+ ```
63
+
dqn_jax.cleanrl_model ADDED
Binary file (43.9 kB). View file
 
dqn_jax.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/dqn/#dqn_jaxpy
2
+ import argparse
3
+ import os
4
+ import random
5
+ import time
6
+ from distutils.util import strtobool
7
+
8
+ import flax
9
+ import flax.linen as nn
10
+ import gym
11
+ import jax
12
+ import jax.numpy as jnp
13
+ import numpy as np
14
+ import optax
15
+ from flax.training.train_state import TrainState
16
+ from stable_baselines3.common.buffers import ReplayBuffer
17
+ from torch.utils.tensorboard import SummaryWriter
18
+
19
+
20
+ def parse_args():
21
+ # fmt: off
22
+ parser = argparse.ArgumentParser()
23
+ parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
24
+ help="the name of this experiment")
25
+ parser.add_argument("--seed", type=int, default=1,
26
+ help="seed of the experiment")
27
+ parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
28
+ help="if toggled, this experiment will be tracked with Weights and Biases")
29
+ parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
30
+ help="the wandb's project name")
31
+ parser.add_argument("--wandb-entity", type=str, default=None,
32
+ help="the entity (team) of wandb's project")
33
+ parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
34
+ help="whether to capture videos of the agent performances (check out `videos` folder)")
35
+ parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
36
+ help="whether to save model into the `runs/{run_name}` folder")
37
+ parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
38
+ help="whether to upload the saved model to huggingface")
39
+ parser.add_argument("--hf-entity", type=str, default="",
40
+ help="the user or org name of the model repository from the Hugging Face Hub")
41
+
42
+ # Algorithm specific arguments
43
+ parser.add_argument("--env-id", type=str, default="CartPole-v1",
44
+ help="the id of the environment")
45
+ parser.add_argument("--total-timesteps", type=int, default=500000,
46
+ help="total timesteps of the experiments")
47
+ parser.add_argument("--learning-rate", type=float, default=2.5e-4,
48
+ help="the learning rate of the optimizer")
49
+ parser.add_argument("--buffer-size", type=int, default=10000,
50
+ help="the replay memory buffer size")
51
+ parser.add_argument("--gamma", type=float, default=0.99,
52
+ help="the discount factor gamma")
53
+ parser.add_argument("--target-network-frequency", type=int, default=500,
54
+ help="the timesteps it takes to update the target network")
55
+ parser.add_argument("--batch-size", type=int, default=128,
56
+ help="the batch size of sample from the reply memory")
57
+ parser.add_argument("--start-e", type=float, default=1,
58
+ help="the starting epsilon for exploration")
59
+ parser.add_argument("--end-e", type=float, default=0.05,
60
+ help="the ending epsilon for exploration")
61
+ parser.add_argument("--exploration-fraction", type=float, default=0.5,
62
+ help="the fraction of `total-timesteps` it takes from start-e to go end-e")
63
+ parser.add_argument("--learning-starts", type=int, default=10000,
64
+ help="timestep to start learning")
65
+ parser.add_argument("--train-frequency", type=int, default=10,
66
+ help="the frequency of training")
67
+ args = parser.parse_args()
68
+ # fmt: on
69
+ return args
70
+
71
+
72
+ def make_env(env_id, seed, idx, capture_video, run_name):
73
+ def thunk():
74
+ env = gym.make(env_id)
75
+ env = gym.wrappers.RecordEpisodeStatistics(env)
76
+ if capture_video:
77
+ if idx == 0:
78
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
79
+ env.seed(seed)
80
+ env.action_space.seed(seed)
81
+ env.observation_space.seed(seed)
82
+ return env
83
+
84
+ return thunk
85
+
86
+
87
+ # ALGO LOGIC: initialize agent here:
88
+ class QNetwork(nn.Module):
89
+ action_dim: int
90
+
91
+ @nn.compact
92
+ def __call__(self, x: jnp.ndarray):
93
+ x = nn.Dense(120)(x)
94
+ x = nn.relu(x)
95
+ x = nn.Dense(84)(x)
96
+ x = nn.relu(x)
97
+ x = nn.Dense(self.action_dim)(x)
98
+ return x
99
+
100
+
101
+ class TrainState(TrainState):
102
+ target_params: flax.core.FrozenDict
103
+
104
+
105
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
106
+ slope = (end_e - start_e) / duration
107
+ return max(slope * t + start_e, end_e)
108
+
109
+
110
+ if __name__ == "__main__":
111
+ args = parse_args()
112
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
113
+ if args.track:
114
+ import wandb
115
+
116
+ wandb.init(
117
+ project=args.wandb_project_name,
118
+ entity=args.wandb_entity,
119
+ sync_tensorboard=True,
120
+ config=vars(args),
121
+ name=run_name,
122
+ monitor_gym=True,
123
+ save_code=True,
124
+ )
125
+ writer = SummaryWriter(f"runs/{run_name}")
126
+ writer.add_text(
127
+ "hyperparameters",
128
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
129
+ )
130
+
131
+ # TRY NOT TO MODIFY: seeding
132
+ random.seed(args.seed)
133
+ np.random.seed(args.seed)
134
+ key = jax.random.PRNGKey(args.seed)
135
+ key, q_key = jax.random.split(key, 2)
136
+
137
+ # env setup
138
+ envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
139
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
140
+
141
+ obs = envs.reset()
142
+
143
+ q_network = QNetwork(action_dim=envs.single_action_space.n)
144
+
145
+ q_state = TrainState.create(
146
+ apply_fn=q_network.apply,
147
+ params=q_network.init(q_key, obs),
148
+ target_params=q_network.init(q_key, obs),
149
+ tx=optax.adam(learning_rate=args.learning_rate),
150
+ )
151
+
152
+ q_network.apply = jax.jit(q_network.apply)
153
+ # This step is not necessary as init called on same observation and key will always lead to same initializations
154
+ q_state = q_state.replace(target_params=optax.incremental_update(q_state.params, q_state.target_params, 1))
155
+
156
+ rb = ReplayBuffer(
157
+ args.buffer_size,
158
+ envs.single_observation_space,
159
+ envs.single_action_space,
160
+ "cpu",
161
+ handle_timeout_termination=True,
162
+ )
163
+
164
+ @jax.jit
165
+ def update(q_state, observations, actions, next_observations, rewards, dones):
166
+ q_next_target = q_network.apply(q_state.target_params, next_observations) # (batch_size, num_actions)
167
+ q_next_target = jnp.max(q_next_target, axis=-1) # (batch_size,)
168
+ next_q_value = rewards + (1 - dones) * args.gamma * q_next_target
169
+
170
+ def mse_loss(params):
171
+ q_pred = q_network.apply(params, observations) # (batch_size, num_actions)
172
+ q_pred = q_pred[np.arange(q_pred.shape[0]), actions.squeeze()] # (batch_size,)
173
+ return ((q_pred - next_q_value) ** 2).mean(), q_pred
174
+
175
+ (loss_value, q_pred), grads = jax.value_and_grad(mse_loss, has_aux=True)(q_state.params)
176
+ q_state = q_state.apply_gradients(grads=grads)
177
+ return loss_value, q_pred, q_state
178
+
179
+ start_time = time.time()
180
+
181
+ # TRY NOT TO MODIFY: start the game
182
+ obs = envs.reset()
183
+ for global_step in range(args.total_timesteps):
184
+ # ALGO LOGIC: put action logic here
185
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
186
+ if random.random() < epsilon:
187
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
188
+ else:
189
+ q_values = q_network.apply(q_state.params, obs)
190
+ actions = q_values.argmax(axis=-1)
191
+ actions = jax.device_get(actions)
192
+
193
+ # TRY NOT TO MODIFY: execute the game and log data.
194
+ next_obs, rewards, dones, infos = envs.step(actions)
195
+
196
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
197
+ for info in infos:
198
+ if "episode" in info.keys():
199
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
200
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
201
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
202
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
203
+ break
204
+
205
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `terminal_observation`
206
+ real_next_obs = next_obs.copy()
207
+ for idx, d in enumerate(dones):
208
+ if d:
209
+ real_next_obs[idx] = infos[idx]["terminal_observation"]
210
+ rb.add(obs, real_next_obs, actions, rewards, dones, infos)
211
+
212
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
213
+ obs = next_obs
214
+
215
+ # ALGO LOGIC: training.
216
+ if global_step > args.learning_starts and global_step % args.train_frequency == 0:
217
+ data = rb.sample(args.batch_size)
218
+ # perform a gradient-descent step
219
+ loss, old_val, q_state = update(
220
+ q_state,
221
+ data.observations.numpy(),
222
+ data.actions.numpy(),
223
+ data.next_observations.numpy(),
224
+ data.rewards.flatten().numpy(),
225
+ data.dones.flatten().numpy(),
226
+ )
227
+
228
+ if global_step % 100 == 0:
229
+ writer.add_scalar("losses/td_loss", jax.device_get(loss), global_step)
230
+ writer.add_scalar("losses/q_values", jax.device_get(old_val).mean(), global_step)
231
+ print("SPS:", int(global_step / (time.time() - start_time)))
232
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
233
+
234
+ # update the target network
235
+ if global_step % args.target_network_frequency == 0:
236
+ q_state = q_state.replace(target_params=optax.incremental_update(q_state.params, q_state.target_params, 1))
237
+
238
+ if args.save_model:
239
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
240
+ with open(model_path, "wb") as f:
241
+ f.write(flax.serialization.to_bytes(q_state.params))
242
+ print(f"model saved to {model_path}")
243
+ from cleanrl_utils.evals.dqn_jax_eval import evaluate
244
+
245
+ episodic_returns = evaluate(
246
+ model_path,
247
+ make_env,
248
+ args.env_id,
249
+ eval_episodes=10,
250
+ run_name=f"{run_name}-eval",
251
+ Model=QNetwork,
252
+ epsilon=0.05,
253
+ )
254
+ for idx, episodic_return in enumerate(episodic_returns):
255
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
256
+
257
+ if args.upload_model:
258
+ from cleanrl_utils.huggingface import push_to_hub
259
+
260
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
261
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
262
+ push_to_hub(args, episodic_returns, repo_id, "DQN", f"runs/{run_name}", f"videos/{run_name}-eval")
263
+
264
+ envs.close()
265
+ writer.close()
events.out.tfevents.1668717427.pop-os.3662910.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b64cefe331992e4359953c3c8e93dd8b08932f76211005261cff85d27ae84a2
3
+ size 1511787
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "cleanrl"
3
+ version = "1.0.0"
4
+ description = "High-quality single file implementation of Deep Reinforcement Learning algorithms with research-friendly features"
5
+ authors = ["Costa Huang <costa.huang@outlook.com>"]
6
+ include = ["cleanrl_utils"]
7
+ keywords = ["reinforcement", "machine", "learning", "research"]
8
+ license="MIT"
9
+ readme = "README.md"
10
+
11
+ [tool.poetry.dependencies]
12
+ python = ">=3.7.1,<3.10"
13
+ tensorboard = "^2.10.0"
14
+ wandb = "^0.13.3"
15
+ gym = {version = "0.23.1", extras = ["classic_control"]}
16
+ torch = "^1.12.1"
17
+ stable-baselines3 = "1.2.0"
18
+
19
+ [tool.poetry.group.dev.dependencies]
20
+ pre-commit = "^2.20.0"
21
+
22
+ [tool.poetry.group.atari]
23
+ optional = true
24
+ [tool.poetry.group.atari.dependencies]
25
+ ale-py = "0.7.4"
26
+ AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2"}
27
+ opencv-python = "^4.6.0.66"
28
+
29
+ [tool.poetry.group.pybullet]
30
+ optional = true
31
+ [tool.poetry.group.pybullet.dependencies]
32
+ pybullet = "3.1.8"
33
+
34
+ [tool.poetry.group.procgen]
35
+ optional = true
36
+ [tool.poetry.group.procgen.dependencies]
37
+ procgen = "^0.10.7"
38
+
39
+ [tool.poetry.group.pytest]
40
+ optional = true
41
+ [tool.poetry.group.pytest.dependencies]
42
+ pytest = "^7.1.3"
43
+
44
+ [tool.poetry.group.mujoco]
45
+ optional = true
46
+ [tool.poetry.group.mujoco.dependencies]
47
+ free-mujoco-py = "^2.1.6"
48
+
49
+ [tool.poetry.group.docs]
50
+ optional = true
51
+ [tool.poetry.group.docs.dependencies]
52
+ mkdocs-material = "^8.4.3"
53
+ markdown-include = "^0.7.0"
54
+
55
+ [tool.poetry.group.jax]
56
+ optional = true
57
+ [tool.poetry.group.jax.dependencies]
58
+ jax = "^0.3.17"
59
+ jaxlib = "^0.3.15"
60
+ flax = "^0.6.0"
61
+
62
+ [tool.poetry.group.optuna]
63
+ optional = true
64
+ [tool.poetry.group.optuna.dependencies]
65
+ optuna = "^3.0.1"
66
+ optuna-dashboard = "^0.7.2"
67
+ rich = "<12.0"
68
+
69
+ [tool.poetry.group.envpool]
70
+ optional = true
71
+ [tool.poetry.group.envpool.dependencies]
72
+ envpool = "^0.6.4"
73
+
74
+ [tool.poetry.group.pettingzoo]
75
+ optional = true
76
+ [tool.poetry.group.pettingzoo.dependencies]
77
+ PettingZoo = "1.18.1"
78
+ SuperSuit = "3.4.0"
79
+ multi-agent-ale-py = "0.1.11"
80
+
81
+
82
+ [tool.poetry.group.cloud]
83
+ optional = true
84
+ [tool.poetry.group.cloud.dependencies]
85
+ boto3 = "^1.24.70"
86
+ awscli = "^1.25.71"
87
+
88
+ [tool.poetry.group.isaacgym]
89
+ optional = true
90
+ [tool.poetry.group.isaacgym.dependencies]
91
+ isaacgymenvs = {git = "https://github.com/vwxyzjn/IsaacGymEnvs.git", rev = "poetry"}
92
+ isaacgym = {path = "cleanrl/ppo_continuous_action_isaacgym/isaacgym", develop = true}
93
+
94
+ [build-system]
95
+ requires = ["poetry-core"]
96
+ build-backend = "poetry.core.masonry.api"
replay.mp4 ADDED
Binary file (67.7 kB). View file
 
videos/CartPole-v1__dqn_jax__1__1668717427-eval/rl-video-episode-0.mp4 ADDED
Binary file (67.2 kB). View file
 
videos/CartPole-v1__dqn_jax__1__1668717427-eval/rl-video-episode-1.mp4 ADDED
Binary file (66.8 kB). View file
 
videos/CartPole-v1__dqn_jax__1__1668717427-eval/rl-video-episode-8.mp4 ADDED
Binary file (67.7 kB). View file