odiaz1066 commited on
Commit
23555fd
1 Parent(s): 895b44c

pushing model

Browse files
LunarLander-Show.cleanrl_model ADDED
Binary file (48.4 kB). View file
 
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - LunarLander-v2
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: LunarLander-v2
16
+ type: LunarLander-v2
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 227.09 +/- 33.24
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # (CleanRL) **DQN** Agent Playing **LunarLander-v2**
25
+
26
+ This is a trained model of a DQN agent playing LunarLander-v2.
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/LunarLander-Show.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[LunarLander-Show]"
36
+ python -m cleanrl_utils.enjoy --exp-name LunarLander-Show --env-id LunarLander-v2
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/odiaz1066/LunarLander-v2-LunarLander-Show-seed42/raw/main/dqn.py
46
+ curl -OL https://huggingface.co/odiaz1066/LunarLander-v2-LunarLander-Show-seed42/raw/main/pyproject.toml
47
+ curl -OL https://huggingface.co/odiaz1066/LunarLander-v2-LunarLander-Show-seed42/raw/main/poetry.lock
48
+ poetry install --all-extras
49
+ python dqn.py --track --save-model --capture-video --exp-name LunarLander-Show --seed 42 --env-id LunarLander-v2 --upload-model --hf-entity odiaz1066
50
+ ```
51
+
52
+ # Hyperparameters
53
+ ```python
54
+ {'batch_size': 128,
55
+ 'buffer_size': 10000,
56
+ 'capture_video': True,
57
+ 'cuda': True,
58
+ 'end_e': 0.05,
59
+ 'env_id': 'LunarLander-v2',
60
+ 'exp_name': 'LunarLander-Show',
61
+ 'exploration_fraction': 0.5,
62
+ 'gamma': 0.99,
63
+ 'hf_entity': 'odiaz1066',
64
+ 'learning_rate': 0.00025,
65
+ 'learning_starts': 10000,
66
+ 'num_envs': 1,
67
+ 'save_model': True,
68
+ 'seed': 42,
69
+ 'start_e': 1,
70
+ 'target_network_frequency': 500,
71
+ 'tau': 1.0,
72
+ 'torch_deterministic': True,
73
+ 'total_timesteps': 500000,
74
+ 'track': True,
75
+ 'train_frequency': 10,
76
+ 'upload_model': True,
77
+ 'wandb_entity': None,
78
+ 'wandb_project_name': 'lagomorph'}
79
+ ```
80
+
dqn.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Callable
17
+ from dotenv import load_dotenv
18
+ import sys
19
+ sys.path.append(".")
20
+
21
+ def parse_args():
22
+ # fmt: off
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
25
+ help="the name of this experiment")
26
+ parser.add_argument("--seed", type=int, default=1,
27
+ help="seed of the experiment")
28
+ parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
29
+ help="if toggled, `torch.backends.cudnn.deterministic=False`")
30
+ parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
31
+ help="if toggled, cuda will be enabled by default")
32
+ parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
33
+ help="if toggled, this experiment will be tracked with Weights and Biases")
34
+ parser.add_argument("--wandb-project-name", type=str, default="lagomorph",
35
+ help="the wandb's project name")
36
+ parser.add_argument("--wandb-entity", type=str, default=None,
37
+ help="the entity (team) of wandb's project")
38
+ parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
39
+ help="whether to capture videos of the agent performances (check out `videos` folder)")
40
+ parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
41
+ help="whether to save model into the `runs/{run_name}` folder")
42
+ parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
43
+ help="whether to upload the saved model to huggingface")
44
+ parser.add_argument("--hf-entity", type=str, default="",
45
+ help="the user or org name of the model repository from the Hugging Face Hub")
46
+
47
+ # Algorithm specific arguments
48
+ parser.add_argument("--env-id", type=str, default="CartPole-v1",
49
+ help="the id of the environment")
50
+ parser.add_argument("--total-timesteps", type=int, default=500000,
51
+ help="total timesteps of the experiments")
52
+ parser.add_argument("--learning-rate", type=float, default=2.5e-4,
53
+ help="the learning rate of the optimizer")
54
+ parser.add_argument("--num-envs", type=int, default=1,
55
+ help="the number of parallel game environments")
56
+ parser.add_argument("--buffer-size", type=int, default=10000,
57
+ help="the replay memory buffer size")
58
+ parser.add_argument("--gamma", type=float, default=0.99,
59
+ help="the discount factor gamma")
60
+ parser.add_argument("--tau", type=float, default=1.,
61
+ help="the target network update rate")
62
+ parser.add_argument("--target-network-frequency", type=int, default=500,
63
+ help="the timesteps it takes to update the target network")
64
+ parser.add_argument("--batch-size", type=int, default=128,
65
+ help="the batch size of sample from the reply memory")
66
+ parser.add_argument("--start-e", type=float, default=1,
67
+ help="the starting epsilon for exploration")
68
+ parser.add_argument("--end-e", type=float, default=0.05,
69
+ help="the ending epsilon for exploration")
70
+ parser.add_argument("--exploration-fraction", type=float, default=0.5,
71
+ help="the fraction of `total-timesteps` it takes from start-e to go end-e")
72
+ parser.add_argument("--learning-starts", type=int, default=10000,
73
+ help="timestep to start learning")
74
+ parser.add_argument("--train-frequency", type=int, default=10,
75
+ help="the frequency of training")
76
+ args = parser.parse_args()
77
+ # fmt: on
78
+ assert args.num_envs == 1, "vectorized envs are not supported at the moment"
79
+
80
+ return args
81
+
82
+
83
+ def make_env(env_id, seed, idx, capture_video, run_name):
84
+ def thunk():
85
+ if capture_video and idx == 0:
86
+ env = gym.make(env_id, render_mode="rgb_array")
87
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
88
+ else:
89
+ env = gym.make(env_id)
90
+ env = gym.wrappers.RecordEpisodeStatistics(env)
91
+ env.action_space.seed(seed)
92
+
93
+ return env
94
+
95
+ return thunk
96
+
97
+
98
+ # ALGO LOGIC: initialize agent here:
99
+ class QNetwork(nn.Module):
100
+ def __init__(self, env):
101
+ super().__init__()
102
+ self.network = nn.Sequential(
103
+ nn.Linear(np.array(env.single_observation_space.shape).prod(), 120),
104
+ nn.ReLU(),
105
+ nn.Linear(120, 84),
106
+ nn.ReLU(),
107
+ nn.Linear(84, env.single_action_space.n),
108
+ )
109
+
110
+ def forward(self, x):
111
+ return self.network(x)
112
+
113
+
114
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
115
+ slope = (end_e - start_e) / duration
116
+ return max(slope * t + start_e, end_e)
117
+
118
+ def evaluate(
119
+ model_path: str,
120
+ make_env: Callable,
121
+ env_id: str,
122
+ eval_episodes: int,
123
+ run_name: str,
124
+ Model: torch.nn.Module,
125
+ device: torch.device = torch.device("cpu"),
126
+ epsilon: float = 0.05,
127
+ capture_video: bool = True,
128
+ ):
129
+ envs = gym.vector.SyncVectorEnv([make_env(env_id, 0, 0, capture_video, run_name)])
130
+ model = Model(envs).to(device)
131
+ model.load_state_dict(torch.load(model_path, map_location=device))
132
+ model.eval()
133
+
134
+ obs, _ = envs.reset()
135
+ episodic_returns = []
136
+ while len(episodic_returns) < eval_episodes:
137
+ if random.random() < epsilon:
138
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
139
+ else:
140
+ q_values = model(torch.Tensor(obs).to(device))
141
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
142
+ next_obs, _, _, _, infos = envs.step(actions)
143
+ if "final_info" in infos:
144
+ for info in infos["final_info"]:
145
+ if "episode" in info:
146
+ print(f"eval_episode={len(episodic_returns)}, episodic_return={info['episode']['r']}")
147
+ episodic_returns += [info["episode"]["r"]]
148
+ obs = next_obs
149
+
150
+ return episodic_returns
151
+
152
+ if __name__ == "__main__":
153
+ import stable_baselines3 as sb3
154
+
155
+ if sb3.__version__ < "2.0":
156
+ raise ValueError(
157
+ """Ongoing migration: run the following command to install the new dependencies:
158
+
159
+ poetry run pip install "stable_baselines3==2.0.0a1"
160
+ """
161
+ )
162
+ args = parse_args()
163
+ load_dotenv()
164
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
165
+ if args.track:
166
+ import wandb
167
+
168
+ wandb.init(
169
+ project=args.wandb_project_name,
170
+ entity=args.wandb_entity,
171
+ sync_tensorboard=True,
172
+ config=vars(args),
173
+ name=run_name,
174
+ monitor_gym=True,
175
+ save_code=True,
176
+ )
177
+ writer = SummaryWriter(f"runs/{run_name}")
178
+ writer.add_text(
179
+ "hyperparameters",
180
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
181
+ )
182
+
183
+ # TRY NOT TO MODIFY: seeding
184
+ random.seed(args.seed)
185
+ np.random.seed(args.seed)
186
+ torch.manual_seed(args.seed)
187
+ torch.backends.cudnn.deterministic = args.torch_deterministic
188
+
189
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
190
+
191
+ # env setup
192
+ envs = gym.vector.SyncVectorEnv(
193
+ [make_env(args.env_id, args.seed + i, i, args.capture_video, run_name) for i in range(args.num_envs)]
194
+ )
195
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
196
+
197
+ q_network = QNetwork(envs).to(device)
198
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
199
+ target_network = QNetwork(envs).to(device)
200
+ target_network.load_state_dict(q_network.state_dict())
201
+
202
+ rb = ReplayBuffer(
203
+ args.buffer_size,
204
+ envs.single_observation_space,
205
+ envs.single_action_space,
206
+ device,
207
+ handle_timeout_termination=False,
208
+ )
209
+ start_time = time.time()
210
+
211
+ # TRY NOT TO MODIFY: start the game
212
+ obs, _ = envs.reset(seed=args.seed)
213
+ for global_step in range(args.total_timesteps):
214
+ # ALGO LOGIC: put action logic here
215
+ epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
216
+ if random.random() < epsilon:
217
+ actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
218
+ else:
219
+ q_values = q_network(torch.Tensor(obs).to(device))
220
+ actions = torch.argmax(q_values, dim=1).cpu().numpy()
221
+
222
+ # TRY NOT TO MODIFY: execute the game and log data.
223
+ next_obs, rewards, terminated, truncated, infos = envs.step(actions)
224
+
225
+ # TRY NOT TO MODIFY: record rewards for plotting purposes
226
+ if "final_info" in infos:
227
+ for info in infos["final_info"]:
228
+ # Skip the envs that are not done
229
+ if "episode" not in info:
230
+ continue
231
+ print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
232
+ writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
233
+ writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
234
+ writer.add_scalar("charts/epsilon", epsilon, global_step)
235
+
236
+ # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation`
237
+ real_next_obs = next_obs.copy()
238
+ for idx, d in enumerate(truncated):
239
+ if d:
240
+ real_next_obs[idx] = infos["final_observation"][idx]
241
+ rb.add(obs, real_next_obs, actions, rewards, terminated, infos)
242
+
243
+ # TRY NOT TO MODIFY: CRUCIAL step easy to overlook
244
+ obs = next_obs
245
+
246
+ # ALGO LOGIC: training.
247
+ if global_step > args.learning_starts:
248
+ if global_step % args.train_frequency == 0:
249
+ data = rb.sample(args.batch_size)
250
+ with torch.no_grad():
251
+ target_max, _ = target_network(data.next_observations).max(dim=1)
252
+ td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
253
+ old_val = q_network(data.observations).gather(1, data.actions).squeeze()
254
+ loss = F.mse_loss(td_target, old_val)
255
+
256
+ if global_step % 100 == 0:
257
+ writer.add_scalar("losses/td_loss", loss, global_step)
258
+ writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
259
+ print("SPS:", int(global_step / (time.time() - start_time)))
260
+ writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
261
+
262
+ # optimize the model
263
+ optimizer.zero_grad()
264
+ loss.backward()
265
+ optimizer.step()
266
+
267
+ # update target network
268
+ if global_step % args.target_network_frequency == 0:
269
+ for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
270
+ target_network_param.data.copy_(
271
+ args.tau * q_network_param.data + (1.0 - args.tau) * target_network_param.data
272
+ )
273
+
274
+ if args.save_model:
275
+ model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
276
+ torch.save(q_network.state_dict(), model_path)
277
+ print(f"model saved to {model_path}")
278
+ if args.track:
279
+ artifact = wandb.Artifact(f"{args.exp_name}_model", "model")
280
+ artifact.add_file(model_path)
281
+ wandb.log_artifact(artifact)
282
+
283
+ episodic_returns = evaluate(
284
+ model_path,
285
+ make_env,
286
+ args.env_id,
287
+ eval_episodes=10,
288
+ run_name=f"{run_name}-eval",
289
+ Model=QNetwork,
290
+ device=device,
291
+ epsilon=0.05,
292
+ )
293
+ for idx, episodic_return in enumerate(episodic_returns):
294
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
295
+
296
+ if args.upload_model:
297
+ #TODO: Currently gives an error. *Maybe* I'll get around to fixing it once everything else works correctly.
298
+ from utils.huggingface import push_to_hub
299
+
300
+ repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
301
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
302
+ push_to_hub(args, episodic_returns, repo_id, "DQN", f"runs/{run_name}", f"videos/{run_name}-eval")
303
+
304
+ envs.close()
305
+ writer.close()
events.out.tfevents.1688132825.20b896d7cec9.13932.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea48f0293a3f6087db6a09a725a7f9aea7e8dfdb2cd44710fbb6387dcbb0ce67
3
+ size 1066200
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "lagomorph"
3
+ version = "0.1.0"
4
+ description = "Fork of CleanRL focused on DQN training"
5
+ packages = [
6
+ { include = "envs" },
7
+ { include = "utils" },
8
+ ]
9
+ keywords = ["reinforcement", "machine", "learning", "research"]
10
+ license="MIT"
11
+ readme = "README.md"
replay.mp4 ADDED
Binary file (91.5 kB). View file
 
videos/LunarLander-v2__LunarLander-Show__42__1688132822-eval/rl-video-episode-0.mp4 ADDED
Binary file (81.2 kB). View file
 
videos/LunarLander-v2__LunarLander-Show__42__1688132822-eval/rl-video-episode-1.mp4 ADDED
Binary file (103 kB). View file
 
videos/LunarLander-v2__LunarLander-Show__42__1688132822-eval/rl-video-episode-8.mp4 ADDED
Binary file (91.5 kB). View file