pushing model
Browse files- README.md +1 -1
- dqn.py +241 -0
- events.out.tfevents.1668612393.pop-os.1029385.0 +3 -0
- events.out.tfevents.1668612395.pop-os.1029385.1 +3 -0
- replay.mp4 +0 -0
- videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-0.mp4 +0 -0
- videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-1.mp4 +0 -0
- videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-8.mp4 +0 -0
README.md
CHANGED
@@ -29,7 +29,7 @@ found [here](https://github.com/vwxyzjn/cleanrl/blob/master/cleanrl/dqn.py).
|
|
29 |
## Command to reproduce the training
|
30 |
|
31 |
```bash
|
32 |
-
dqn.py --cuda False --save-model --upload-model --total-timesteps 500
|
33 |
```
|
34 |
|
35 |
# Hyperparameters
|
|
|
29 |
## Command to reproduce the training
|
30 |
|
31 |
```bash
|
32 |
+
python dqn.py --cuda False --save-model --upload-model --total-timesteps 500
|
33 |
```
|
34 |
|
35 |
# Hyperparameters
|
dqn.py
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 sys
|
6 |
+
import time
|
7 |
+
from distutils.util import strtobool
|
8 |
+
|
9 |
+
import gym
|
10 |
+
import numpy as np
|
11 |
+
import torch
|
12 |
+
import torch.nn as nn
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torch.optim as optim
|
15 |
+
from stable_baselines3.common.buffers import ReplayBuffer
|
16 |
+
from torch.utils.tensorboard import SummaryWriter
|
17 |
+
|
18 |
+
|
19 |
+
def parse_args():
|
20 |
+
# fmt: off
|
21 |
+
parser = argparse.ArgumentParser()
|
22 |
+
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
|
23 |
+
help="the name of this experiment")
|
24 |
+
parser.add_argument("--seed", type=int, default=1,
|
25 |
+
help="seed of the experiment")
|
26 |
+
parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
|
27 |
+
help="if toggled, `torch.backends.cudnn.deterministic=False`")
|
28 |
+
parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
|
29 |
+
help="if toggled, cuda will be enabled by default")
|
30 |
+
parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
31 |
+
help="if toggled, this experiment will be tracked with Weights and Biases")
|
32 |
+
parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
|
33 |
+
help="the wandb's project name")
|
34 |
+
parser.add_argument("--wandb-entity", type=str, default=None,
|
35 |
+
help="the entity (team) of wandb's project")
|
36 |
+
parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
37 |
+
help="whether to capture videos of the agent performances (check out `videos` folder)")
|
38 |
+
parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
39 |
+
help="whether to save model into the `runs/{run_name}` folder")
|
40 |
+
parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
41 |
+
help="whether to upload the saved model to huggingface")
|
42 |
+
parser.add_argument("--hf-entity", type=str, default="",
|
43 |
+
help="the user or org name of the model repository from the Hugging Face Hub")
|
44 |
+
|
45 |
+
# Algorithm specific arguments
|
46 |
+
parser.add_argument("--env-id", type=str, default="CartPole-v1",
|
47 |
+
help="the id of the environment")
|
48 |
+
parser.add_argument("--total-timesteps", type=int, default=500000,
|
49 |
+
help="total timesteps of the experiments")
|
50 |
+
parser.add_argument("--learning-rate", type=float, default=2.5e-4,
|
51 |
+
help="the learning rate of the optimizer")
|
52 |
+
parser.add_argument("--buffer-size", type=int, default=10000,
|
53 |
+
help="the replay memory buffer size")
|
54 |
+
parser.add_argument("--gamma", type=float, default=0.99,
|
55 |
+
help="the discount factor gamma")
|
56 |
+
parser.add_argument("--target-network-frequency", type=int, default=500,
|
57 |
+
help="the timesteps it takes to update the target network")
|
58 |
+
parser.add_argument("--batch-size", type=int, default=128,
|
59 |
+
help="the batch size of sample from the reply memory")
|
60 |
+
parser.add_argument("--start-e", type=float, default=1,
|
61 |
+
help="the starting epsilon for exploration")
|
62 |
+
parser.add_argument("--end-e", type=float, default=0.05,
|
63 |
+
help="the ending epsilon for exploration")
|
64 |
+
parser.add_argument("--exploration-fraction", type=float, default=0.5,
|
65 |
+
help="the fraction of `total-timesteps` it takes from start-e to go end-e")
|
66 |
+
parser.add_argument("--learning-starts", type=int, default=10000,
|
67 |
+
help="timestep to start learning")
|
68 |
+
parser.add_argument("--train-frequency", type=int, default=10,
|
69 |
+
help="the frequency of training")
|
70 |
+
args = parser.parse_args()
|
71 |
+
# fmt: on
|
72 |
+
return args
|
73 |
+
|
74 |
+
|
75 |
+
def make_env(env_id, seed, idx, capture_video, run_name):
|
76 |
+
def thunk():
|
77 |
+
env = gym.make(env_id)
|
78 |
+
env = gym.wrappers.RecordEpisodeStatistics(env)
|
79 |
+
if capture_video:
|
80 |
+
if idx == 0:
|
81 |
+
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
|
82 |
+
env.seed(seed)
|
83 |
+
env.action_space.seed(seed)
|
84 |
+
env.observation_space.seed(seed)
|
85 |
+
return env
|
86 |
+
|
87 |
+
return thunk
|
88 |
+
|
89 |
+
|
90 |
+
# ALGO LOGIC: initialize agent here:
|
91 |
+
class QNetwork(nn.Module):
|
92 |
+
def __init__(self, env):
|
93 |
+
super().__init__()
|
94 |
+
self.network = nn.Sequential(
|
95 |
+
nn.Linear(np.array(env.single_observation_space.shape).prod(), 120),
|
96 |
+
nn.ReLU(),
|
97 |
+
nn.Linear(120, 84),
|
98 |
+
nn.ReLU(),
|
99 |
+
nn.Linear(84, env.single_action_space.n),
|
100 |
+
)
|
101 |
+
|
102 |
+
def forward(self, x):
|
103 |
+
return self.network(x)
|
104 |
+
|
105 |
+
|
106 |
+
def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
|
107 |
+
slope = (end_e - start_e) / duration
|
108 |
+
return max(slope * t + start_e, end_e)
|
109 |
+
|
110 |
+
|
111 |
+
if __name__ == "__main__":
|
112 |
+
args = parse_args()
|
113 |
+
run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
|
114 |
+
if args.track:
|
115 |
+
import wandb
|
116 |
+
|
117 |
+
wandb.init(
|
118 |
+
project=args.wandb_project_name,
|
119 |
+
entity=args.wandb_entity,
|
120 |
+
sync_tensorboard=True,
|
121 |
+
config=vars(args),
|
122 |
+
name=run_name,
|
123 |
+
monitor_gym=True,
|
124 |
+
save_code=True,
|
125 |
+
)
|
126 |
+
writer = SummaryWriter(f"runs/{run_name}")
|
127 |
+
writer.add_text(
|
128 |
+
"hyperparameters",
|
129 |
+
"|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
|
130 |
+
)
|
131 |
+
|
132 |
+
# TRY NOT TO MODIFY: seeding
|
133 |
+
random.seed(args.seed)
|
134 |
+
np.random.seed(args.seed)
|
135 |
+
torch.manual_seed(args.seed)
|
136 |
+
torch.backends.cudnn.deterministic = args.torch_deterministic
|
137 |
+
|
138 |
+
device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
|
139 |
+
|
140 |
+
# env setup
|
141 |
+
envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
|
142 |
+
assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
|
143 |
+
|
144 |
+
q_network = QNetwork(envs).to(device)
|
145 |
+
optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
|
146 |
+
target_network = QNetwork(envs).to(device)
|
147 |
+
target_network.load_state_dict(q_network.state_dict())
|
148 |
+
|
149 |
+
rb = ReplayBuffer(
|
150 |
+
args.buffer_size,
|
151 |
+
envs.single_observation_space,
|
152 |
+
envs.single_action_space,
|
153 |
+
device,
|
154 |
+
handle_timeout_termination=True,
|
155 |
+
)
|
156 |
+
start_time = time.time()
|
157 |
+
|
158 |
+
# TRY NOT TO MODIFY: start the game
|
159 |
+
obs = envs.reset()
|
160 |
+
for global_step in range(args.total_timesteps):
|
161 |
+
# ALGO LOGIC: put action logic here
|
162 |
+
epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
|
163 |
+
if random.random() < epsilon:
|
164 |
+
actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
|
165 |
+
else:
|
166 |
+
q_values = q_network(torch.Tensor(obs).to(device))
|
167 |
+
actions = torch.argmax(q_values, dim=1).cpu().numpy()
|
168 |
+
|
169 |
+
# TRY NOT TO MODIFY: execute the game and log data.
|
170 |
+
next_obs, rewards, dones, infos = envs.step(actions)
|
171 |
+
|
172 |
+
# TRY NOT TO MODIFY: record rewards for plotting purposes
|
173 |
+
for info in infos:
|
174 |
+
if "episode" in info.keys():
|
175 |
+
print(f"global_step={global_step}, episodic_return={info['episode']['r']}")
|
176 |
+
writer.add_scalar("charts/episodic_return", info["episode"]["r"], global_step)
|
177 |
+
writer.add_scalar("charts/episodic_length", info["episode"]["l"], global_step)
|
178 |
+
writer.add_scalar("charts/epsilon", epsilon, global_step)
|
179 |
+
break
|
180 |
+
|
181 |
+
# TRY NOT TO MODIFY: save data to reply buffer; handle `terminal_observation`
|
182 |
+
real_next_obs = next_obs.copy()
|
183 |
+
for idx, d in enumerate(dones):
|
184 |
+
if d:
|
185 |
+
real_next_obs[idx] = infos[idx]["terminal_observation"]
|
186 |
+
rb.add(obs, real_next_obs, actions, rewards, dones, infos)
|
187 |
+
|
188 |
+
# TRY NOT TO MODIFY: CRUCIAL step easy to overlook
|
189 |
+
obs = next_obs
|
190 |
+
|
191 |
+
# ALGO LOGIC: training.
|
192 |
+
if global_step > args.learning_starts and global_step % args.train_frequency == 0:
|
193 |
+
data = rb.sample(args.batch_size)
|
194 |
+
with torch.no_grad():
|
195 |
+
target_max, _ = target_network(data.next_observations).max(dim=1)
|
196 |
+
td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
|
197 |
+
old_val = q_network(data.observations).gather(1, data.actions).squeeze()
|
198 |
+
loss = F.mse_loss(td_target, old_val)
|
199 |
+
|
200 |
+
if global_step % 100 == 0:
|
201 |
+
writer.add_scalar("losses/td_loss", loss, global_step)
|
202 |
+
writer.add_scalar("losses/q_values", old_val.mean().item(), global_step)
|
203 |
+
print("SPS:", int(global_step / (time.time() - start_time)))
|
204 |
+
writer.add_scalar("charts/SPS", int(global_step / (time.time() - start_time)), global_step)
|
205 |
+
|
206 |
+
# optimize the model
|
207 |
+
optimizer.zero_grad()
|
208 |
+
loss.backward()
|
209 |
+
optimizer.step()
|
210 |
+
|
211 |
+
# update the target network
|
212 |
+
if global_step % args.target_network_frequency == 0:
|
213 |
+
target_network.load_state_dict(q_network.state_dict())
|
214 |
+
|
215 |
+
envs.close()
|
216 |
+
writer.close()
|
217 |
+
|
218 |
+
if args.save_model:
|
219 |
+
torch.save(q_network.state_dict(), f"runs/{run_name}/q_network.pth")
|
220 |
+
print(f"model saved to ./runs/{run_name}/q_network.pth")
|
221 |
+
from cleanrl_utils.evals.dqn_eval import evaluate
|
222 |
+
|
223 |
+
episodic_returns = evaluate(
|
224 |
+
f"runs/{run_name}/q_network.pth",
|
225 |
+
make_env,
|
226 |
+
args.env_id,
|
227 |
+
eval_episodes=10,
|
228 |
+
run_name=f"{run_name}-eval",
|
229 |
+
Model=QNetwork,
|
230 |
+
device=device,
|
231 |
+
epsilon=0.05,
|
232 |
+
)
|
233 |
+
for idx, episodic_return in enumerate(episodic_returns):
|
234 |
+
writer.add_scalar("eval/episodic_return", episodic_return, idx)
|
235 |
+
|
236 |
+
if args.upload_model:
|
237 |
+
from cleanrl_utils.huggingface import push_to_hub
|
238 |
+
|
239 |
+
repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
|
240 |
+
repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
|
241 |
+
push_to_hub(args, episodic_returns, repo_id, "DQN", f"runs/{run_name}", f"videos/{run_name}-eval")
|
events.out.tfevents.1668612393.pop-os.1029385.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bfdf9296dd95288259e308b1dec0568655e54d36a19866cc8813db7b8b90cd7b
|
3 |
+
size 1805
|
events.out.tfevents.1668612395.pop-os.1029385.1
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f462f14da438bf7fc5f1f6ecfef9d808355a1f39d3af970866cbb4e9647dcb7b
|
3 |
+
size 618
|
replay.mp4
ADDED
Binary file (10.8 kB). View file
|
|
videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-0.mp4
ADDED
Binary file (12.6 kB). View file
|
|
videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-1.mp4
ADDED
Binary file (8.84 kB). View file
|
|
videos/CartPole-v1__dqn__1__1668612393-eval/rl-video-episode-8.mp4
ADDED
Binary file (10.8 kB). View file
|
|