sdpkjc commited on
Commit
bd5fae0
·
1 Parent(s): 45c35eb

pushing model

Browse files
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - CartPole-v1
4
+ - deep-reinforcement-learning
5
+ - reinforcement-learning
6
+ - custom-implementation
7
+ library_name: cleanrl
8
+ model-index:
9
+ - name: DQN
10
+ results:
11
+ - task:
12
+ type: reinforcement-learning
13
+ name: reinforcement-learning
14
+ dataset:
15
+ name: CartPole-v1
16
+ type: CartPole-v1
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 45.10 +/- 9.18
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # (CleanRL) **DQN** Agent Playing **CartPole-v1**
25
+
26
+ This is a trained model of a DQN agent playing CartPole-v1.
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/dqn.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[dqn]"
36
+ python -m cleanrl_utils.enjoy --exp-name dqn --env-id CartPole-v1
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/sdpkjc/CartPole-v1-dqn-seed1/raw/main/dqn.py
46
+ curl -OL https://huggingface.co/sdpkjc/CartPole-v1-dqn-seed1/raw/main/pyproject.toml
47
+ curl -OL https://huggingface.co/sdpkjc/CartPole-v1-dqn-seed1/raw/main/poetry.lock
48
+ poetry install --all-extras
49
+ python dqn.py --total-timesteps 1000 --learning-starts 250 --save-model --hf-entity sdpkjc --upload-model
50
+ ```
51
+
52
+ # Hyperparameters
53
+ ```python
54
+ {'batch_size': 128,
55
+ 'buffer_size': 10000,
56
+ 'capture_video': False,
57
+ 'cuda': True,
58
+ 'end_e': 0.05,
59
+ 'env_id': 'CartPole-v1',
60
+ 'exp_name': 'dqn',
61
+ 'exploration_fraction': 0.5,
62
+ 'gamma': 0.99,
63
+ 'hf_entity': 'sdpkjc',
64
+ 'learning_rate': 0.00025,
65
+ 'learning_starts': 250,
66
+ 'num_envs': 1,
67
+ 'save_model': True,
68
+ 'seed': 1,
69
+ 'start_e': 1,
70
+ 'target_network_frequency': 500,
71
+ 'tau': 1.0,
72
+ 'torch_deterministic': True,
73
+ 'total_timesteps': 1000,
74
+ 'track': False,
75
+ 'train_frequency': 10,
76
+ 'upload_model': True,
77
+ 'wandb_entity': None,
78
+ 'wandb_project_name': 'cleanRL'}
79
+ ```
80
+
dqn.cleanrl_model ADDED
Binary file (45.8 kB). View file
 
dqn.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/dqn/#dqnpy
2
+ import argparse
3
+ import os
4
+ import random
5
+ import time
6
+ from distutils.util import strtobool
7
+
8
+ import gymnasium as gym
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import torch.optim as optim
14
+ from stable_baselines3.common.buffers import ReplayBuffer
15
+ from torch.utils.tensorboard import SummaryWriter
16
+
17
+
18
+ def parse_args():
19
+ # fmt: off
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
22
+ help="the name of this experiment")
23
+ parser.add_argument("--seed", type=int, default=1,
24
+ help="seed of the experiment")
25
+ parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
26
+ help="if toggled, `torch.backends.cudnn.deterministic=False`")
27
+ parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
28
+ help="if toggled, cuda will be enabled by default")
29
+ parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
30
+ help="if toggled, this experiment will be tracked with Weights and Biases")
31
+ parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
32
+ help="the wandb's project name")
33
+ parser.add_argument("--wandb-entity", type=str, default=None,
34
+ help="the entity (team) of wandb's project")
35
+ parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
36
+ help="whether to capture videos of the agent performances (check out `videos` folder)")
37
+ parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
38
+ help="whether to save model into the `runs/{run_name}` folder")
39
+ parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
40
+ help="whether to upload the saved model to huggingface")
41
+ parser.add_argument("--hf-entity", type=str, default="",
42
+ help="the user or org name of the model repository from the Hugging Face Hub")
43
+
44
+ # Algorithm specific arguments
45
+ parser.add_argument("--env-id", type=str, default="CartPole-v1",
46
+ help="the id of the environment")
47
+ parser.add_argument("--total-timesteps", type=int, default=500000,
48
+ help="total timesteps of the experiments")
49
+ parser.add_argument("--learning-rate", type=float, default=2.5e-4,
50
+ help="the learning rate of the optimizer")
51
+ parser.add_argument("--num-envs", type=int, default=1,
52
+ help="the number of parallel game environments")
53
+ parser.add_argument("--buffer-size", type=int, default=10000,
54
+ help="the replay memory buffer size")
55
+ parser.add_argument("--gamma", type=float, default=0.99,
56
+ help="the discount factor gamma")
57
+ parser.add_argument("--tau", type=float, default=1.,
58
+ help="the target network update rate")
59
+ parser.add_argument("--target-network-frequency", type=int, default=500,
60
+ help="the timesteps it takes to update the target network")
61
+ parser.add_argument("--batch-size", type=int, default=128,
62
+ help="the batch size of sample from the reply memory")
63
+ parser.add_argument("--start-e", type=float, default=1,
64
+ help="the starting epsilon for exploration")
65
+ parser.add_argument("--end-e", type=float, default=0.05,
66
+ help="the ending epsilon for exploration")
67
+ parser.add_argument("--exploration-fraction", type=float, default=0.5,
68
+ help="the fraction of `total-timesteps` it takes from start-e to go end-e")
69
+ parser.add_argument("--learning-starts", type=int, default=10000,
70
+ help="timestep to start learning")
71
+ parser.add_argument("--train-frequency", type=int, default=10,
72
+ help="the frequency of training")
73
+ args = parser.parse_args()
74
+ # fmt: on
75
+ assert args.num_envs == 1, "vectorized envs are not supported at the moment"
76
+
77
+ return args
78
+
79
+
80
+ def make_env(env_id, seed, idx, capture_video, run_name):
81
+ def thunk():
82
+ if capture_video and idx == 0:
83
+ env = gym.make(env_id, render_mode="rgb_array")
84
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
85
+ else:
86
+ env = gym.make(env_id)
87
+ env = gym.wrappers.RecordEpisodeStatistics(env)
88
+ env.action_space.seed(seed)
89
+
90
+ return env
91
+
92
+ return thunk
93
+
94
+
95
+ # ALGO LOGIC: initialize agent here:
96
+ class QNetwork(nn.Module):
97
+ def __init__(self, env):
98
+ super().__init__()
99
+ self.network = nn.Sequential(
100
+ nn.Linear(np.array(env.single_observation_space.shape).prod(), 120),
101
+ nn.ReLU(),
102
+ nn.Linear(120, 84),
103
+ nn.ReLU(),
104
+ nn.Linear(84, env.single_action_space.n),
105
+ )
106
+
107
+ def forward(self, x):
108
+ return self.network(x)
109
+
110
+
111
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
112
+ slope = (end_e - start_e) / duration
113
+ return max(slope * t + start_e, end_e)
114
+
115
+
116
+ if __name__ == "__main__":
117
+ import stable_baselines3 as sb3
118
+
119
+ if sb3.__version__ < "2.0":
120
+ raise ValueError(
121
+ """Ongoing migration: run the following command to install the new dependencies:
122
+
123
+ poetry run pip install "stable_baselines3==2.0.0a1"
124
+ """
125
+ )
126
+ args = parse_args()
127
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
128
+ if args.track:
129
+ import wandb
130
+
131
+ wandb.init(
132
+ project=args.wandb_project_name,
133
+ entity=args.wandb_entity,
134
+ sync_tensorboard=True,
135
+ config=vars(args),
136
+ name=run_name,
137
+ monitor_gym=True,
138
+ save_code=True,
139
+ )
140
+ writer = SummaryWriter(f"runs/{run_name}")
141
+ writer.add_text(
142
+ "hyperparameters",
143
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
144
+ )
145
+
146
+ # TRY NOT TO MODIFY: seeding
147
+ random.seed(args.seed)
148
+ np.random.seed(args.seed)
149
+ torch.manual_seed(args.seed)
150
+ torch.backends.cudnn.deterministic = args.torch_deterministic
151
+
152
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
153
+
154
+ # env setup
155
+ envs = gym.vector.SyncVectorEnv(
156
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
157
+ )
158
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
159
+
160
+ q_network = QNetwork(envs).to(device)
161
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
162
+ target_network = QNetwork(envs).to(device)
163
+ target_network.load_state_dict(q_network.state_dict())
164
+
165
+ rb = ReplayBuffer(
166
+ args.buffer_size,
167
+ envs.single_observation_space,
168
+ envs.single_action_space,
169
+ device,
170
+ handle_timeout_termination=False,
171
+ )
172
+ start_time = time.time()
173
+
174
+ # TRY NOT TO MODIFY: start the game
175
+ obs, _ = envs.reset(seed=args.seed)
176
+ for global_step in range(args.total_timesteps):
177
+ # ALGO LOGIC: put action logic here
178
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
179
+ if random.random() < epsilon:
180
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
181
+ else:
182
+ q_values = q_network(torch.Tensor(obs).to(device))
183
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
184
+
185
+ # TRY NOT TO MODIFY: execute the game and log data.
186
+ next_obs, rewards, terminated, truncated, infos = envs.step(actions)
187
+
188
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
189
+ if "final_info" in infos:
190
+ for info in infos["final_info"]:
191
+ # Skip the envs that are not done
192
+ if "episode" not in info:
193
+ continue
194
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
195
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
196
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
197
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
198
+
199
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
200
+ real_next_obs = next_obs.copy()
201
+ for idx, d in enumerate(truncated):
202
+ if d:
203
+ real_next_obs[idx] = infos["final_observation"][idx]
204
+ rb.add(obs, real_next_obs, actions, rewards, terminated, infos)
205
+
206
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
207
+ obs = next_obs
208
+
209
+ # ALGO LOGIC: training.
210
+ if global_step > args.learning_starts:
211
+ if global_step % args.train_frequency == 0:
212
+ data = rb.sample(args.batch_size)
213
+ with torch.no_grad():
214
+ target_max, _ = target_network(data.next_observations).max(dim=1)
215
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
216
+ old_val = q_network(data.observations).gather(1, data.actions).squeeze()
217
+ loss = F.mse_loss(td_target, old_val)
218
+
219
+ if global_step % 100 == 0:
220
+ writer.add_scalar("losses/td_loss", loss, global_step)
221
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
222
+ print("SPS:", int(global_step / (time.time() - start_time)))
223
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
224
+
225
+ # optimize the model
226
+ optimizer.zero_grad()
227
+ loss.backward()
228
+ optimizer.step()
229
+
230
+ # update target network
231
+ if global_step % args.target_network_frequency == 0:
232
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
233
+ target_network_param.data.copy_(
234
+ args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data
235
+ )
236
+
237
+ if args.save_model:
238
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
239
+ torch.save(q_network.state_dict(), model_path)
240
+ print(f"model saved to {model_path}")
241
+ from cleanrl_utils.evals.dqn_eval import evaluate
242
+
243
+ episodic_returns = evaluate(
244
+ model_path,
245
+ make_env,
246
+ args.env_id,
247
+ eval_episodes=10,
248
+ run_name=f"{run_name}-eval",
249
+ Model=QNetwork,
250
+ device=device,
251
+ epsilon=0.05,
252
+ )
253
+ for idx, episodic_return in enumerate(episodic_returns):
254
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
255
+
256
+ if args.upload_model:
257
+ from cleanrl_utils.huggingface import push_to_hub
258
+
259
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
260
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
261
+ push_to_hub(args, episodic_returns, repo_id, "DQN", f"runs/{run_name}", f"videos/{run_name}-eval")
262
+
263
+ envs.close()
264
+ writer.close()
events.out.tfevents.1687676607.4090-171.2587566.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:846a29c88dddd16aab9e767ddb0dc9e44142596a8ec624f5dfeba1687228c1f6
3
+ size 5421
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "cleanrl"
3
+ version = "1.1.0"
4
+ description = "High-quality single file implementation of Deep Reinforcement Learning algorithms with research-friendly features"
5
+ authors = ["Costa Huang <[email protected]>"]
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.11"
16
+ tensorboard = "^2.10.0"
17
+ wandb = "^0.13.11"
18
+ gym = "0.23.1"
19
+ torch = ">=1.12.1"
20
+ stable-baselines3 = "1.2.0"
21
+ gymnasium = ">=0.28.1"
22
+ moviepy = "^1.0.3"
23
+ pygame = "2.1.0"
24
+ huggingface-hub = "^0.11.1"
25
+ rich = "<12.0"
26
+
27
+ ale-py = {version = "0.7.4", optional = true}
28
+ AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2", optional = true}
29
+ opencv-python = {version = "^4.6.0.66", optional = true}
30
+ procgen = {version = "^0.10.7", optional = true}
31
+ pytest = {version = "^7.1.3", optional = true}
32
+ mujoco = {version = "<=2.3.3", 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
+ openrlbenchmark = {version = "^0.1.1b4", optional = true}
38
+ jax = {version = "^0.3.17", optional = true}
39
+ jaxlib = {version = "^0.3.15", optional = true}
40
+ flax = {version = "^0.6.0", optional = true}
41
+ optuna = {version = "^3.0.1", optional = true}
42
+ optuna-dashboard = {version = "^0.7.2", optional = true}
43
+ envpool = {version = "^0.6.4", 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 = ">=1.0.0", extras = ["dm-control"], optional = true}
50
+
51
+ [tool.poetry.group.dev.dependencies]
52
+ pre-commit = "^2.20.0"
53
+
54
+
55
+ [tool.poetry.group.isaacgym]
56
+ optional = true
57
+ [tool.poetry.group.isaacgym.dependencies]
58
+ isaacgymenvs = {git = "https://github.com/vwxyzjn/IsaacGymEnvs.git", rev = "poetry", python = ">=3.7.1,<3.10"}
59
+ isaacgym = {path = "cleanrl/ppo_continuous_action_isaacgym/isaacgym", develop = true}
60
+
61
+
62
+ [build-system]
63
+ requires = ["poetry-core"]
64
+ build-backend = "poetry.core.masonry.api"
65
+
66
+ [tool.poetry.extras]
67
+ atari = ["ale-py", "AutoROM", "opencv-python"]
68
+ procgen = ["procgen"]
69
+ plot = ["pandas", "seaborn"]
70
+ pytest = ["pytest"]
71
+ mujoco = ["mujoco", "imageio"]
72
+ mujoco_py = ["free-mujoco-py"]
73
+ jax = ["jax", "jaxlib", "flax"]
74
+ docs = ["mkdocs-material", "markdown-include", "openrlbenchmark"]
75
+ envpool = ["envpool"]
76
+ optuna = ["optuna", "optuna-dashboard"]
77
+ pettingzoo = ["PettingZoo", "SuperSuit", "multi-agent-ale-py"]
78
+ cloud = ["boto3", "awscli"]
79
+ dm_control = ["shimmy", "mujoco"]
80
+
81
+ # dependencies for algorithm variant (useful when you want to run a specific algorithm)
82
+ dqn = []
83
+ dqn_atari = ["ale-py", "AutoROM", "opencv-python"]
84
+ dqn_jax = ["jax", "jaxlib", "flax"]
85
+ dqn_atari_jax = [
86
+ "ale-py", "AutoROM", "opencv-python", # atari
87
+ "jax", "jaxlib", "flax" # jax
88
+ ]
89
+ c51 = []
90
+ c51_atari = ["ale-py", "AutoROM", "opencv-python"]
91
+ c51_jax = ["jax", "jaxlib", "flax"]
92
+ c51_atari_jax = [
93
+ "ale-py", "AutoROM", "opencv-python", # atari
94
+ "jax", "jaxlib", "flax" # jax
95
+ ]
96
+ ppo_atari_envpool_xla_jax_scan = [
97
+ "ale-py", "AutoROM", "opencv-python", # atari
98
+ "jax", "jaxlib", "flax", # jax
99
+ "envpool", # envpool
100
+ ]
101
+ qdagger_dqn_atari_impalacnn = [
102
+ "ale-py", "AutoROM", "opencv-python"
103
+ ]
104
+ qdagger_dqn_atari_jax_impalacnn = [
105
+ "ale-py", "AutoROM", "opencv-python", # atari
106
+ "jax", "jaxlib", "flax", # jax
107
+ ]
replay.mp4 ADDED
Binary file (5.69 kB). View file
 
videos/CartPole-v1__dqn__1__1687676607-eval/rl-video-episode-0.mp4 ADDED
Binary file (5.53 kB). View file
 
videos/CartPole-v1__dqn__1__1687676607-eval/rl-video-episode-1.mp4 ADDED
Binary file (6.14 kB). View file
 
videos/CartPole-v1__dqn__1__1687676607-eval/rl-video-episode-8.mp4 ADDED
Binary file (5.69 kB). View file