mmorales34
commited on
Commit
•
c4ceb3a
1
Parent(s):
4ce79fe
pushing model
Browse files- .gitattributes +1 -0
- DQPN_x1.cleanrl_model +3 -0
- README.md +84 -0
- dqpn_freq_atari.py +350 -0
- events.out.tfevents.1696988249.redi.2203727.0 +3 -0
- poetry.lock +0 -0
- pyproject.toml +178 -0
- replay.mp4 +0 -0
- videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-0.mp4 +0 -0
- videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-1.mp4 +0 -0
- videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-8.mp4 +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
DQPN_x1.cleanrl_model filter=lfs diff=lfs merge=lfs -text
|
DQPN_x1.cleanrl_model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6b0d6150cc7829316e88643564492bd6671ddf5ff59cc483939b42beb556dbb7
|
3 |
+
size 6751815
|
README.md
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
tags:
|
3 |
+
- PongNoFrameskip-v4
|
4 |
+
- deep-reinforcement-learning
|
5 |
+
- reinforcement-learning
|
6 |
+
- custom-implementation
|
7 |
+
library_name: cleanrl
|
8 |
+
model-index:
|
9 |
+
- name: DQPN_freq
|
10 |
+
results:
|
11 |
+
- task:
|
12 |
+
type: reinforcement-learning
|
13 |
+
name: reinforcement-learning
|
14 |
+
dataset:
|
15 |
+
name: PongNoFrameskip-v4
|
16 |
+
type: PongNoFrameskip-v4
|
17 |
+
metrics:
|
18 |
+
- type: mean_reward
|
19 |
+
value: 19.03 +/- 0.00
|
20 |
+
name: mean_reward
|
21 |
+
verified: false
|
22 |
+
---
|
23 |
+
|
24 |
+
# (CleanRL) **DQPN_freq** Agent Playing **PongNoFrameskip-v4**
|
25 |
+
|
26 |
+
This is a trained model of a DQPN_freq agent playing PongNoFrameskip-v4.
|
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/DQPN_x1.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[DQPN_x1]"
|
36 |
+
python -m cleanrl_utils.enjoy --exp-name DQPN_x1 --env-id PongNoFrameskip-v4
|
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/pfunk/PongNoFrameskip-v4-DQPN_x1-seed3/raw/main/dqpn_freq_atari.py
|
46 |
+
curl -OL https://huggingface.co/pfunk/PongNoFrameskip-v4-DQPN_x1-seed3/raw/main/pyproject.toml
|
47 |
+
curl -OL https://huggingface.co/pfunk/PongNoFrameskip-v4-DQPN_x1-seed3/raw/main/poetry.lock
|
48 |
+
poetry install --all-extras
|
49 |
+
python dqpn_freq_atari.py --track --wandb-entity pfunk --wandb-project-name dqpn --capture-video true --save-model true --upload-model true --hf-entity pfunk --exp-name DQPN_x1 --target-network-frequency 1000 --policy-network-frequency 1000 --seed 3
|
50 |
+
```
|
51 |
+
|
52 |
+
# Hyperparameters
|
53 |
+
```python
|
54 |
+
{'alg_type': 'dqpn_freq_atari.py',
|
55 |
+
'batch_size': 32,
|
56 |
+
'buffer_size': 1000000,
|
57 |
+
'capture_video': True,
|
58 |
+
'cuda': True,
|
59 |
+
'double_learning': False,
|
60 |
+
'end_e': 0.05,
|
61 |
+
'env_id': 'PongNoFrameskip-v4',
|
62 |
+
'exp_name': 'DQPN_x1',
|
63 |
+
'exploration_fraction': 0.2,
|
64 |
+
'gamma': 0.99,
|
65 |
+
'hf_entity': 'pfunk',
|
66 |
+
'learning_rate': 0.0001,
|
67 |
+
'learning_starts': 10000,
|
68 |
+
'max_gradient_norm': inf,
|
69 |
+
'policy_network_frequency': 1000,
|
70 |
+
'policy_tau': 1.0,
|
71 |
+
'save_model': True,
|
72 |
+
'seed': 3,
|
73 |
+
'start_e': 1.0,
|
74 |
+
'target_network_frequency': 1000,
|
75 |
+
'target_tau': 1.0,
|
76 |
+
'torch_deterministic': True,
|
77 |
+
'total_timesteps': 10000000,
|
78 |
+
'track': True,
|
79 |
+
'train_frequency': 1,
|
80 |
+
'upload_model': True,
|
81 |
+
'wandb_entity': 'pfunk',
|
82 |
+
'wandb_project_name': 'dqpn'}
|
83 |
+
```
|
84 |
+
|
dqpn_freq_atari.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/dqn/#dqn_ataripy
|
2 |
+
import argparse
|
3 |
+
import os
|
4 |
+
import random
|
5 |
+
import time
|
6 |
+
from distutils.util import strtobool
|
7 |
+
|
8 |
+
import 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.atari_wrappers import (
|
15 |
+
ClipRewardEnv,
|
16 |
+
EpisodicLifeEnv,
|
17 |
+
FireResetEnv,
|
18 |
+
MaxAndSkipEnv,
|
19 |
+
NoopResetEnv,
|
20 |
+
)
|
21 |
+
from stable_baselines3.common.buffers import ReplayBuffer
|
22 |
+
from torch.utils.tensorboard import SummaryWriter
|
23 |
+
|
24 |
+
|
25 |
+
def parse_args():
|
26 |
+
# fmt: off
|
27 |
+
parser = argparse.ArgumentParser()
|
28 |
+
parser.add_argument("--exp-name", type=str, default=os.path.basename(__file__).rstrip(".py"),
|
29 |
+
help="the name of this experiment")
|
30 |
+
parser.add_argument("--seed", type=int, default=1,
|
31 |
+
help="seed of the experiment")
|
32 |
+
parser.add_argument("--torch-deterministic", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
|
33 |
+
help="if toggled, `torch.backends.cudnn.deterministic=False`")
|
34 |
+
parser.add_argument("--cuda", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True,
|
35 |
+
help="if toggled, cuda will be enabled by default")
|
36 |
+
parser.add_argument("--track", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
37 |
+
help="if toggled, this experiment will be tracked with Weights and Biases")
|
38 |
+
parser.add_argument("--wandb-project-name", type=str, default="cleanRL",
|
39 |
+
help="the wandb's project name")
|
40 |
+
parser.add_argument("--wandb-entity", type=str, default=None,
|
41 |
+
help="the entity (team) of wandb's project")
|
42 |
+
parser.add_argument("--capture-video", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
43 |
+
help="whether to capture videos of the agent performances (check out `videos` folder)")
|
44 |
+
parser.add_argument("--save-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
45 |
+
help="whether to save model into the `runs/{run_name}` folder")
|
46 |
+
parser.add_argument("--upload-model", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
47 |
+
help="whether to upload the saved model to huggingface")
|
48 |
+
parser.add_argument("--hf-entity", type=str, default="",
|
49 |
+
help="the user or org name of the model repository from the Hugging Face Hub")
|
50 |
+
|
51 |
+
# Algorithm specific arguments
|
52 |
+
parser.add_argument("--env-id", type=str, default="PongNoFrameskip-v4",
|
53 |
+
help="the id of the environment")
|
54 |
+
parser.add_argument("--total-timesteps", type=int, default=10000000,
|
55 |
+
help="total timesteps of the experiments")
|
56 |
+
parser.add_argument("--learning-rate", type=float, default=0.0001,
|
57 |
+
help="the learning rate of the optimizer")
|
58 |
+
parser.add_argument("--max-gradient-norm", type=float, default=float('inf'),
|
59 |
+
help="gradient clipping value")
|
60 |
+
parser.add_argument("--double-learning", type=lambda x: bool(strtobool(x)), default=False, nargs="?", const=True,
|
61 |
+
help="enable double learning DDQN")
|
62 |
+
parser.add_argument("--buffer-size", type=int, default=1000000,
|
63 |
+
help="the replay memory buffer size")
|
64 |
+
parser.add_argument("--gamma", type=float, default=0.99,
|
65 |
+
help="the discount factor gamma")
|
66 |
+
parser.add_argument("--target-tau", type=float, default=1.0,
|
67 |
+
help="the target network update rate")
|
68 |
+
parser.add_argument("--policy-tau", type=float, default=1.0,
|
69 |
+
help="the target network update rate")
|
70 |
+
parser.add_argument("--target-network-frequency", type=int, default=1000,
|
71 |
+
help="the timesteps it takes to update the target network")
|
72 |
+
parser.add_argument("--policy-network-frequency", type=int, default=5000,
|
73 |
+
help="the timesteps it takes to update the policy network")
|
74 |
+
parser.add_argument("--batch-size", type=int, default=32,
|
75 |
+
help="the batch size of sample from the reply memory")
|
76 |
+
parser.add_argument("--start-e", type=float, default=1.0,
|
77 |
+
help="the starting epsilon for exploration")
|
78 |
+
parser.add_argument("--end-e", type=float, default=0.05,
|
79 |
+
help="the ending epsilon for exploration")
|
80 |
+
parser.add_argument("--exploration-fraction", type=float, default=0.2,
|
81 |
+
help="the fraction of `total-timesteps` it takes from start-e to go end-e")
|
82 |
+
parser.add_argument("--learning-starts", type=int, default=10000,
|
83 |
+
help="timestep to start learning")
|
84 |
+
parser.add_argument("--train-frequency", type=int, default=1,
|
85 |
+
help="the frequency of training")
|
86 |
+
args = parser.parse_args()
|
87 |
+
# fmt: on
|
88 |
+
return args
|
89 |
+
|
90 |
+
|
91 |
+
def make_env(env_id, seed, idx, capture_video, run_name):
|
92 |
+
def thunk():
|
93 |
+
env = gym.make(env_id)
|
94 |
+
env = gym.wrappers.RecordEpisodeStatistics(env)
|
95 |
+
if capture_video:
|
96 |
+
if idx == 0:
|
97 |
+
env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
|
98 |
+
env = NoopResetEnv(env, noop_max=30)
|
99 |
+
env = MaxAndSkipEnv(env, skip=4)
|
100 |
+
env = EpisodicLifeEnv(env)
|
101 |
+
if "FIRE" in env.unwrapped.get_action_meanings():
|
102 |
+
env = FireResetEnv(env)
|
103 |
+
env = ClipRewardEnv(env)
|
104 |
+
env = gym.wrappers.ResizeObservation(env, (84, 84))
|
105 |
+
env = gym.wrappers.GrayScaleObservation(env)
|
106 |
+
env = gym.wrappers.FrameStack(env, 4)
|
107 |
+
env.seed(seed)
|
108 |
+
env.action_space.seed(seed)
|
109 |
+
env.observation_space.seed(seed)
|
110 |
+
return env
|
111 |
+
|
112 |
+
return thunk
|
113 |
+
|
114 |
+
|
115 |
+
# ALGO LOGIC: initialize agent here:
|
116 |
+
class QNetwork(nn.Module):
|
117 |
+
def __init__(self, env):
|
118 |
+
super().__init__()
|
119 |
+
self.network = nn.Sequential(
|
120 |
+
nn.Conv2d(4, 32, 8, stride=4),
|
121 |
+
nn.ReLU(),
|
122 |
+
nn.Conv2d(32, 64, 4, stride=2),
|
123 |
+
nn.ReLU(),
|
124 |
+
nn.Conv2d(64, 64, 3, stride=1),
|
125 |
+
nn.ReLU(),
|
126 |
+
nn.Flatten(),
|
127 |
+
nn.Linear(3136, 512),
|
128 |
+
nn.ReLU(),
|
129 |
+
nn.Linear(512, env.single_action_space.n),
|
130 |
+
)
|
131 |
+
|
132 |
+
def forward(self, x):
|
133 |
+
return self.network(x / 255.0)
|
134 |
+
|
135 |
+
|
136 |
+
def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
|
137 |
+
slope = (end_e - start_e) / duration
|
138 |
+
return max(slope * t + start_e, end_e)
|
139 |
+
|
140 |
+
|
141 |
+
if __name__ == "__main__":
|
142 |
+
args = parse_args()
|
143 |
+
run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
|
144 |
+
if args.track:
|
145 |
+
import wandb
|
146 |
+
|
147 |
+
args.alg_type = os.path.basename(__file__)
|
148 |
+
wandb_sess = wandb.init(
|
149 |
+
project=args.wandb_project_name,
|
150 |
+
entity=args.wandb_entity,
|
151 |
+
config=vars(args),
|
152 |
+
save_code=True,
|
153 |
+
# group='string',
|
154 |
+
name=run_name,
|
155 |
+
sync_tensorboard=False,
|
156 |
+
monitor_gym=True,
|
157 |
+
)
|
158 |
+
writer = SummaryWriter(f"runs/{run_name}")
|
159 |
+
writer.add_text(
|
160 |
+
"hyperparameters",
|
161 |
+
"|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
|
162 |
+
)
|
163 |
+
|
164 |
+
def log_value(name: str, x: float, y: int):
|
165 |
+
# writer.add_scalar(name, x, y)
|
166 |
+
wandb.log({name: x, "global_step": y})
|
167 |
+
|
168 |
+
# TRY NOT TO MODIFY: seeding
|
169 |
+
random.seed(args.seed)
|
170 |
+
np.random.seed(args.seed)
|
171 |
+
torch.manual_seed(args.seed)
|
172 |
+
torch.backends.cudnn.deterministic = args.torch_deterministic
|
173 |
+
|
174 |
+
device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
|
175 |
+
|
176 |
+
# env setup
|
177 |
+
envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
|
178 |
+
assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
|
179 |
+
|
180 |
+
q_network = QNetwork(envs).to(device)
|
181 |
+
optimizer = optim.RMSprop(q_network.parameters(), lr=args.learning_rate)
|
182 |
+
target_network = QNetwork(envs).to(device)
|
183 |
+
policy_network = QNetwork(envs).to(device)
|
184 |
+
target_network.load_state_dict(q_network.state_dict())
|
185 |
+
policy_network.load_state_dict(q_network.state_dict())
|
186 |
+
|
187 |
+
rb = ReplayBuffer(
|
188 |
+
args.buffer_size,
|
189 |
+
envs.single_observation_space,
|
190 |
+
envs.single_action_space,
|
191 |
+
device,
|
192 |
+
optimize_memory_usage=True,
|
193 |
+
handle_timeout_termination=True,
|
194 |
+
)
|
195 |
+
start_time = time.time()
|
196 |
+
target_update_counter = 0
|
197 |
+
policy_update_counter = 0
|
198 |
+
episode_returns = []
|
199 |
+
|
200 |
+
# TRY NOT TO MODIFY: start the game
|
201 |
+
obs = envs.reset()
|
202 |
+
for global_step in range(args.total_timesteps):
|
203 |
+
# ALGO LOGIC: put action logic here
|
204 |
+
epsilon = linear_schedule(args.start_e, args.end_e, args.exploration_fraction * args.total_timesteps, global_step)
|
205 |
+
|
206 |
+
if random.random() < epsilon:
|
207 |
+
actions = np.array([envs.single_action_space.sample() for _ in range(envs.num_envs)])
|
208 |
+
else:
|
209 |
+
q_values = policy_network(torch.Tensor(obs).to(device))
|
210 |
+
actions = torch.argmax(q_values, dim=1).cpu().numpy()
|
211 |
+
|
212 |
+
# TRY NOT TO MODIFY: execute the game and log data.
|
213 |
+
next_obs, rewards, dones, infos = envs.step(actions)
|
214 |
+
|
215 |
+
# TRY NOT TO MODIFY: record rewards for plotting purposes
|
216 |
+
for info in infos:
|
217 |
+
if "episode" in info.keys():
|
218 |
+
episode_returns.append(info['episode']['r'])
|
219 |
+
episode_returns = episode_returns[-100:]
|
220 |
+
print(f"step={global_step}, return={info['episode']['r']}, sps={int(global_step / (time.time() - start_time))}")
|
221 |
+
log_value("perf/episodic_return", info["episode"]["r"], global_step)
|
222 |
+
log_value("perf/episodic_return_mean_100", np.mean(episode_returns), global_step)
|
223 |
+
log_value("perf/episodic_return_std_100", np.std(episode_returns), global_step)
|
224 |
+
log_value("debug/episodic_length", info["episode"]["l"], global_step)
|
225 |
+
log_value("ex2/epsilon", epsilon, global_step)
|
226 |
+
break
|
227 |
+
|
228 |
+
# TRY NOT TO MODIFY: save data to reply buffer; handle `terminal_observation`
|
229 |
+
real_next_obs = next_obs.copy()
|
230 |
+
for idx, d in enumerate(dones):
|
231 |
+
if d:
|
232 |
+
real_next_obs[idx] = infos[idx]["terminal_observation"]
|
233 |
+
rb.add(obs, real_next_obs, actions, rewards, dones, infos)
|
234 |
+
|
235 |
+
# TRY NOT TO MODIFY: CRUCIAL step easy to overlook
|
236 |
+
obs = next_obs
|
237 |
+
|
238 |
+
# ALGO LOGIC: training.
|
239 |
+
if global_step > args.learning_starts:
|
240 |
+
# NOTE: Current code does not work with train_frequency != 1
|
241 |
+
if global_step % args.train_frequency == 0:
|
242 |
+
data = rb.sample(args.batch_size)
|
243 |
+
with torch.no_grad():
|
244 |
+
if args.double_learning:
|
245 |
+
argmax_a = q_network(data.next_observations).max(1)[1].unsqueeze(1)
|
246 |
+
else:
|
247 |
+
argmax_a = target_network(data.next_observations).max(1)[1].unsqueeze(1)
|
248 |
+
|
249 |
+
target_max = target_network(data.next_observations).gather(1, argmax_a).squeeze()
|
250 |
+
td_target = data.rewards.flatten() + args.gamma * target_max * (1 - data.dones.flatten())
|
251 |
+
|
252 |
+
old_val = q_network(data.observations).gather(1, data.actions).squeeze()
|
253 |
+
loss = F.mse_loss(td_target, old_val)
|
254 |
+
|
255 |
+
if global_step % 100 == 0:
|
256 |
+
|
257 |
+
prev = old_val.detach().cpu().numpy()
|
258 |
+
new = td_target.detach().cpu().numpy()
|
259 |
+
diff, a_diff = new-prev, np.abs(new-prev)
|
260 |
+
|
261 |
+
mean, a_mean = np.mean(diff), np.mean(a_diff)
|
262 |
+
median, a_median = np.median(diff), np.median(a_diff)
|
263 |
+
maximum, a_maximum = np.max(diff), np.max(a_diff)
|
264 |
+
minimum, a_minimum = np.min(diff), np.min(a_diff)
|
265 |
+
std, a_std = np.std(diff), np.std(a_diff)
|
266 |
+
below, a_below = mean - std, a_mean - a_std
|
267 |
+
above, a_above = mean + std, a_mean + a_std
|
268 |
+
pu_scalar, a_pu_scalar = 2 * mean / maximum, 2 * a_mean / a_maximum
|
269 |
+
policy_frequency_scalar_ratio = args.policy_network_frequency * pu_scalar
|
270 |
+
a_policy_frequency_scalar_ratio = args.policy_network_frequency * a_pu_scalar
|
271 |
+
|
272 |
+
log_value("losses/td_loss", loss, global_step)
|
273 |
+
log_value("losses/q_values", old_val.mean().item(), global_step)
|
274 |
+
log_value("td/mean", mean, global_step)
|
275 |
+
log_value("td/a_mean", a_mean, global_step)
|
276 |
+
log_value("td/median", median, global_step)
|
277 |
+
log_value("td/a_median", a_median, global_step)
|
278 |
+
log_value("td/max", maximum, global_step)
|
279 |
+
log_value("td/a_max", a_maximum, global_step)
|
280 |
+
log_value("td/min", minimum, global_step)
|
281 |
+
log_value("td/a_min", a_minimum, global_step)
|
282 |
+
log_value("td/std", std, global_step)
|
283 |
+
log_value("td/a_std", a_std, global_step)
|
284 |
+
log_value("td/below", below, global_step)
|
285 |
+
log_value("td/a_below", a_below, global_step)
|
286 |
+
log_value("td/above", above, global_step)
|
287 |
+
log_value("td/a_above", a_above, global_step)
|
288 |
+
log_value("alg/pu_scalar", pu_scalar, global_step)
|
289 |
+
log_value("alg/a_pu_scalar", a_pu_scalar, global_step)
|
290 |
+
log_value("alg/policy_frequency_scalar_ratio", policy_frequency_scalar_ratio, global_step)
|
291 |
+
log_value("alg/a_policy_frequency_scalar_ratio", a_policy_frequency_scalar_ratio, global_step)
|
292 |
+
log_value("debug/steps_per_second", int(global_step / (time.time() - start_time)), global_step)
|
293 |
+
|
294 |
+
# optimize the model
|
295 |
+
optimizer.zero_grad()
|
296 |
+
loss.backward()
|
297 |
+
torch.nn.utils.clip_grad_norm_(q_network.parameters(),
|
298 |
+
args.max_gradient_norm)
|
299 |
+
optimizer.step()
|
300 |
+
|
301 |
+
# update target network
|
302 |
+
if global_step % args.target_network_frequency == 0:
|
303 |
+
target_update_counter += 1
|
304 |
+
for target_network_param, q_network_param in zip(target_network.parameters(), q_network.parameters()):
|
305 |
+
target_network_param.data.copy_(
|
306 |
+
args.target_tau * q_network_param.data + (1.0 - args.target_tau) * target_network_param.data
|
307 |
+
)
|
308 |
+
|
309 |
+
# update policy network
|
310 |
+
if global_step % args.policy_network_frequency == 0:
|
311 |
+
policy_update_counter += 1
|
312 |
+
for policy_network_param, q_network_param in zip(policy_network.parameters(), q_network.parameters()):
|
313 |
+
policy_network_param.data.copy_(
|
314 |
+
args.policy_tau * q_network_param.data + (1.0 - args.policy_tau) * policy_network_param.data
|
315 |
+
)
|
316 |
+
|
317 |
+
if global_step % 100 == 0:
|
318 |
+
log_value("alg/n_target_update", target_update_counter, global_step)
|
319 |
+
log_value("alg/n_policy_update", policy_update_counter, global_step)
|
320 |
+
|
321 |
+
if args.save_model:
|
322 |
+
model_path = f"runs/{run_name}/{args.exp_name}.cleanrl_model"
|
323 |
+
torch.save(policy_network.state_dict(), model_path)
|
324 |
+
print(f"model saved to {model_path}")
|
325 |
+
from cleanrl_utils.evals.dqn_eval import evaluate
|
326 |
+
|
327 |
+
episodic_returns = evaluate(
|
328 |
+
model_path,
|
329 |
+
make_env,
|
330 |
+
args.env_id,
|
331 |
+
eval_episodes=10,
|
332 |
+
run_name=f"{run_name}-eval",
|
333 |
+
Model=QNetwork,
|
334 |
+
device=device,
|
335 |
+
epsilon=0.05,
|
336 |
+
)
|
337 |
+
for idx, episodic_return in enumerate(episodic_returns):
|
338 |
+
log_value("eval/episodic_return", episodic_return, idx)
|
339 |
+
|
340 |
+
|
341 |
+
if args.upload_model:
|
342 |
+
from cleanrl_utils.huggingface import push_to_hub
|
343 |
+
|
344 |
+
repo_name = f"{args.env_id}-{args.exp_name}-seed{args.seed}"
|
345 |
+
repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
|
346 |
+
push_to_hub(args, np.mean(episode_returns), repo_id, "DQPN_freq", f"runs/{run_name}", f"videos/{run_name}-eval")
|
347 |
+
|
348 |
+
wandb_sess.finish()
|
349 |
+
envs.close()
|
350 |
+
writer.close()
|
events.out.tfevents.1696988249.redi.2203727.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5a00ab08a645b99240f76cc2ffd63c4db80505c732711a94c6190791aafdd0be
|
3 |
+
size 751
|
poetry.lock
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pyproject.toml
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.10"
|
16 |
+
tensorboard = "^2.10.0"
|
17 |
+
wandb = "^0.13.6"
|
18 |
+
gym = "0.23.1"
|
19 |
+
torch = ">=1.12.1"
|
20 |
+
stable-baselines3 = "1.2.0"
|
21 |
+
gymnasium = "^0.26.3"
|
22 |
+
moviepy = "^1.0.3"
|
23 |
+
pygame = "2.1.0"
|
24 |
+
huggingface-hub = "^0.11.1"
|
25 |
+
|
26 |
+
ale-py = {version = "0.7.4", optional = true}
|
27 |
+
AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2"}
|
28 |
+
opencv-python = {version = "^4.6.0.66", optional = true}
|
29 |
+
pybullet = {version = "3.1.8", optional = true}
|
30 |
+
procgen = {version = "^0.10.7", optional = true}
|
31 |
+
pytest = {version = "^7.1.3", optional = true}
|
32 |
+
mujoco = {version = "^2.2", 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 |
+
jax = {version = "^0.3.17", optional = true}
|
38 |
+
jaxlib = {version = "^0.3.15", optional = true}
|
39 |
+
flax = {version = "^0.6.0", optional = true}
|
40 |
+
optuna = {version = "^3.0.1", optional = true}
|
41 |
+
optuna-dashboard = {version = "^0.7.2", optional = true}
|
42 |
+
rich = {version = "<12.0", 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 = "^0.1.0", optional = true}
|
50 |
+
dm-control = {version = "^1.0.8", optional = true}
|
51 |
+
|
52 |
+
[tool.poetry.group.dev.dependencies]
|
53 |
+
pre-commit = "^2.20.0"
|
54 |
+
|
55 |
+
[tool.poetry.group.atari]
|
56 |
+
optional = true
|
57 |
+
[tool.poetry.group.atari.dependencies]
|
58 |
+
ale-py = "0.7.4"
|
59 |
+
AutoROM = {extras = ["accept-rom-license"], version = "^0.4.2"}
|
60 |
+
opencv-python = "^4.6.0.66"
|
61 |
+
|
62 |
+
[tool.poetry.group.pybullet]
|
63 |
+
optional = true
|
64 |
+
[tool.poetry.group.pybullet.dependencies]
|
65 |
+
pybullet = "3.1.8"
|
66 |
+
|
67 |
+
[tool.poetry.group.procgen]
|
68 |
+
optional = true
|
69 |
+
[tool.poetry.group.procgen.dependencies]
|
70 |
+
procgen = "^0.10.7"
|
71 |
+
|
72 |
+
[tool.poetry.group.pytest]
|
73 |
+
optional = true
|
74 |
+
[tool.poetry.group.pytest.dependencies]
|
75 |
+
pytest = "^7.1.3"
|
76 |
+
|
77 |
+
[tool.poetry.group.mujoco]
|
78 |
+
optional = true
|
79 |
+
[tool.poetry.group.mujoco.dependencies]
|
80 |
+
mujoco = "^2.2"
|
81 |
+
imageio = "^2.14.1"
|
82 |
+
|
83 |
+
[tool.poetry.group.mujoco_py]
|
84 |
+
optional = true
|
85 |
+
[tool.poetry.group.mujoco_py.dependencies]
|
86 |
+
free-mujoco-py = "^2.1.6"
|
87 |
+
|
88 |
+
[tool.poetry.group.docs]
|
89 |
+
optional = true
|
90 |
+
[tool.poetry.group.docs.dependencies]
|
91 |
+
mkdocs-material = "^8.4.3"
|
92 |
+
markdown-include = "^0.7.0"
|
93 |
+
|
94 |
+
[tool.poetry.group.jax]
|
95 |
+
optional = true
|
96 |
+
[tool.poetry.group.jax.dependencies]
|
97 |
+
jax = "^0.3.17"
|
98 |
+
jaxlib = "^0.3.15"
|
99 |
+
flax = "^0.6.0"
|
100 |
+
|
101 |
+
[tool.poetry.group.optuna]
|
102 |
+
optional = true
|
103 |
+
[tool.poetry.group.optuna.dependencies]
|
104 |
+
optuna = "^3.0.1"
|
105 |
+
optuna-dashboard = "^0.7.2"
|
106 |
+
rich = "<12.0"
|
107 |
+
|
108 |
+
[tool.poetry.group.envpool]
|
109 |
+
optional = true
|
110 |
+
[tool.poetry.group.envpool.dependencies]
|
111 |
+
envpool = "^0.6.4"
|
112 |
+
|
113 |
+
[tool.poetry.group.pettingzoo]
|
114 |
+
optional = true
|
115 |
+
[tool.poetry.group.pettingzoo.dependencies]
|
116 |
+
PettingZoo = "1.18.1"
|
117 |
+
SuperSuit = "3.4.0"
|
118 |
+
multi-agent-ale-py = "0.1.11"
|
119 |
+
|
120 |
+
[tool.poetry.group.cloud]
|
121 |
+
optional = true
|
122 |
+
[tool.poetry.group.cloud.dependencies]
|
123 |
+
boto3 = "^1.24.70"
|
124 |
+
awscli = "^1.25.71"
|
125 |
+
|
126 |
+
[tool.poetry.group.isaacgym]
|
127 |
+
optional = true
|
128 |
+
[tool.poetry.group.isaacgym.dependencies]
|
129 |
+
isaacgymenvs = {git = "https://github.com/vwxyzjn/IsaacGymEnvs.git", rev = "poetry"}
|
130 |
+
isaacgym = {path = "cleanrl/ppo_continuous_action_isaacgym/isaacgym", develop = true}
|
131 |
+
|
132 |
+
[tool.poetry.group.dm_control]
|
133 |
+
optional = true
|
134 |
+
[tool.poetry.group.dm_control.dependencies]
|
135 |
+
shimmy = "^0.1.0"
|
136 |
+
dm-control = "^1.0.8"
|
137 |
+
mujoco = "^2.2"
|
138 |
+
|
139 |
+
[build-system]
|
140 |
+
requires = ["poetry-core"]
|
141 |
+
build-backend = "poetry.core.masonry.api"
|
142 |
+
|
143 |
+
[tool.poetry.extras]
|
144 |
+
atari = ["ale-py", "AutoROM", "opencv-python"]
|
145 |
+
pybullet = ["pybullet"]
|
146 |
+
procgen = ["procgen"]
|
147 |
+
plot = ["pandas", "seaborn"]
|
148 |
+
pytest = ["pytest"]
|
149 |
+
mujoco = ["mujoco", "imageio"]
|
150 |
+
mujoco_py = ["free-mujoco-py"]
|
151 |
+
jax = ["jax", "jaxlib", "flax"]
|
152 |
+
docs = ["mkdocs-material", "markdown-include"]
|
153 |
+
envpool = ["envpool"]
|
154 |
+
optuna = ["optuna", "optuna-dashboard", "rich"]
|
155 |
+
pettingzoo = ["PettingZoo", "SuperSuit", "multi-agent-ale-py"]
|
156 |
+
cloud = ["boto3", "awscli"]
|
157 |
+
dm_control = ["shimmy", "dm-control", "mujoco"]
|
158 |
+
|
159 |
+
# dependencies for algorithm variant (useful when you want to run a specific algorithm)
|
160 |
+
dqn = []
|
161 |
+
dqn_atari = ["ale-py", "AutoROM", "opencv-python"]
|
162 |
+
dqn_jax = ["jax", "jaxlib", "flax"]
|
163 |
+
dqn_atari_jax = [
|
164 |
+
"ale-py", "AutoROM", "opencv-python", # atari
|
165 |
+
"jax", "jaxlib", "flax" # jax
|
166 |
+
]
|
167 |
+
c51 = []
|
168 |
+
c51_atari = ["ale-py", "AutoROM", "opencv-python"]
|
169 |
+
c51_jax = ["jax", "jaxlib", "flax"]
|
170 |
+
c51_atari_jax = [
|
171 |
+
"ale-py", "AutoROM", "opencv-python", # atari
|
172 |
+
"jax", "jaxlib", "flax" # jax
|
173 |
+
]
|
174 |
+
ppo_atari_envpool_xla_jax_scan = [
|
175 |
+
"ale-py", "AutoROM", "opencv-python", # atari
|
176 |
+
"jax", "jaxlib", "flax", # jax
|
177 |
+
"envpool", # envpool
|
178 |
+
]
|
replay.mp4
ADDED
Binary file (320 kB). View file
|
|
videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-0.mp4
ADDED
Binary file (300 kB). View file
|
|
videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-1.mp4
ADDED
Binary file (343 kB). View file
|
|
videos/PongNoFrameskip-v4__DQPN_x1__3__1696988237-eval/rl-video-episode-8.mp4
ADDED
Binary file (320 kB). View file
|
|