mallycrip commited on
Commit
39bb281
1 Parent(s): fdfcf8b

pushing model

Browse files
README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - SpaceInvadersNoFrameskip-v4
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: SpaceInvadersNoFrameskip-v4
16
+ type: SpaceInvadersNoFrameskip-v4
17
+ metrics:
18
+ - type: mean_reward
19
+ value: 705.50 +/- 237.55
20
+ name: mean_reward
21
+ verified: false
22
+ ---
23
+
24
+ # DQN **SpaceInvadersNoFrameskip-v4**
25
+
26
+ # Hyperparameters
27
+ ```python
28
+ {'batch_size': 32,
29
+ 'buffer_size': 100000,
30
+ 'capture_video': False,
31
+ 'cuda': True,
32
+ 'end_e': 0.01,
33
+ 'env_id': 'SpaceInvadersNoFrameskip-v4',
34
+ 'exp_name': 'dqn_atari_e',
35
+ 'exploration_fraction': 0.1,
36
+ 'gamma': 0.99,
37
+ 'hf_entity': 'mallycrip',
38
+ 'learning_rate': 0.0001,
39
+ 'learning_starts': 80000,
40
+ 'save_model': False,
41
+ 'seed': 1,
42
+ 'start_e': 1,
43
+ 'target_network_frequency': 1000,
44
+ 'tau': 1.0,
45
+ 'torch_deterministic': True,
46
+ 'total_timesteps': 10000000,
47
+ 'track': False,
48
+ 'train_frequency': 4,
49
+ 'upload_model': True,
50
+ 'wandb_entity': None,
51
+ 'wandb_project_name': 'cleanRL'}
52
+ ```
53
+
dqn_atari_e.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=True, nargs="?", const=True,
47
+ help="whether to upload the saved model to huggingface")
48
+ parser.add_argument("--hf-entity", type=str, default="mallycrip",
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="BreakoutNoFrameskip-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=1e-4,
57
+ help="the learning rate of the optimizer")
58
+ parser.add_argument("--buffer-size", type=int, default=100000,
59
+ help="the replay memory buffer size")
60
+ parser.add_argument("--gamma", type=float, default=0.99,
61
+ help="the discount factor gamma")
62
+ parser.add_argument("--tau", type=float, default=1.,
63
+ help="the target network update rate")
64
+ parser.add_argument("--target-network-frequency", type=int, default=1000,
65
+ help="the timesteps it takes to update the target network")
66
+ parser.add_argument("--batch-size", type=int, default=32,
67
+ help="the batch size of sample from the reply memory")
68
+ parser.add_argument("--start-e", type=float, default=1,
69
+ help="the starting epsilon for exploration")
70
+ parser.add_argument("--end-e", type=float, default=0.01,
71
+ help="the ending epsilon for exploration")
72
+ parser.add_argument("--exploration-fraction", type=float, default=0.10,
73
+ help="the fraction of `total-timesteps` it takes from start-e to go end-e")
74
+ parser.add_argument("--learning-starts", type=int, default=80000,
75
+ help="timestep to start learning")
76
+ parser.add_argument("--train-frequency", type=int, default=4,
77
+ help="the frequency of training")
78
+ args = parser.parse_args()
79
+ # fmt: on
80
+ return args
81
+
82
+
83
+ def make_env(env_id, seed, idx, capture_video, run_name):
84
+ def thunk():
85
+ env = gym.make(env_id)
86
+ env = gym.wrappers.RecordEpisodeStatistics(env)
87
+ if capture_video:
88
+ if idx == 0:
89
+ env = gym.wrappers.RecordVideo(env, f"videos/{run_name}")
90
+ env = NoopResetEnv(env, noop_max=30)
91
+ env = MaxAndSkipEnv(env, skip=4)
92
+ env = EpisodicLifeEnv(env)
93
+ if "FIRE" in env.unwrapped.get_action_meanings():
94
+ env = FireResetEnv(env)
95
+ env = ClipRewardEnv(env)
96
+ env = gym.wrappers.ResizeObservation(env, (84, 84))
97
+ env = gym.wrappers.GrayScaleObservation(env)
98
+ env = gym.wrappers.FrameStack(env, 4)
99
+ env.seed(seed)
100
+ env.action_space.seed(seed)
101
+ env.observation_space.seed(seed)
102
+ return env
103
+
104
+ return thunk
105
+
106
+
107
+ # ALGO LOGIC: initialize agent here:
108
+ class QNetwork(nn.Module):
109
+ def __init__(self, env):
110
+ super().__init__()
111
+ self.network = nn.Sequential(
112
+ nn.Conv2d(4, 32, 8, stride=4),
113
+ nn.ReLU(),
114
+ nn.Conv2d(32, 64, 4, stride=2),
115
+ nn.ReLU(),
116
+ nn.Conv2d(64, 64, 3, stride=1),
117
+ nn.ReLU(),
118
+ nn.Flatten(),
119
+ nn.Linear(3136, 512),
120
+ nn.ReLU(),
121
+ nn.Linear(512, env.single_action_space.n),
122
+ )
123
+
124
+ def forward(self, x):
125
+ return self.network(x / 255.0)
126
+
127
+
128
+ def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
129
+ slope = (end_e - start_e) / duration
130
+ return max(slope * t + start_e, end_e)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ args = parse_args()
135
+ run_name = f"{args.env_id}__{args.exp_name}__{args.seed}__{int(time.time())}"
136
+
137
+ run_name = f"SpaceInvadersNoFrameskip-v4__dqn_atari__1__1675730632"
138
+ if args.track:
139
+ import wandb
140
+
141
+ wandb.init(
142
+ project=args.wandb_project_name,
143
+ entity=args.wandb_entity,
144
+ sync_tensorboard=True,
145
+ config=vars(args),
146
+ name=run_name,
147
+ monitor_gym=True,
148
+ save_code=True,
149
+ )
150
+ writer = SummaryWriter(f"runs/{run_name}")
151
+ writer.add_text(
152
+ "hyperparameters",
153
+ "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])),
154
+ )
155
+
156
+ # TRY NOT TO MODIFY: seeding
157
+ random.seed(args.seed)
158
+ np.random.seed(args.seed)
159
+ torch.manual_seed(args.seed)
160
+ torch.backends.cudnn.deterministic = args.torch_deterministic
161
+
162
+ device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")
163
+
164
+ # env setup
165
+ envs = gym.vector.SyncVectorEnv([make_env(args.env_id, args.seed, 0, args.capture_video, run_name)])
166
+ assert isinstance(envs.single_action_space, gym.spaces.Discrete), "only discrete action space is supported"
167
+
168
+ q_network = QNetwork(envs).to(device)
169
+ optimizer = optim.Adam(q_network.parameters(), lr=args.learning_rate)
170
+ target_network = QNetwork(envs).to(device)
171
+ target_network.load_state_dict(q_network.state_dict())
172
+
173
+ rb = ReplayBuffer(
174
+ args.buffer_size,
175
+ envs.single_observation_space,
176
+ envs.single_action_space,
177
+ device,
178
+ optimize_memory_usage=True,
179
+ handle_timeout_termination=True,
180
+ )
181
+
182
+ model_path = f"../runs/{run_name}/dqn_atari.cleanrl_model"
183
+ print(f"model saved to {model_path}")
184
+ from evals.dqn_eval import evaluate
185
+
186
+ episodic_returns = evaluate(
187
+ model_path,
188
+ make_env,
189
+ args.env_id,
190
+ eval_episodes=10,
191
+ run_name=f"{run_name}-eval",
192
+ Model=QNetwork,
193
+ device=device,
194
+ epsilon=0.05,
195
+ )
196
+ for idx, episodic_return in enumerate(episodic_returns):
197
+ writer.add_scalar("eval/episodic_return", episodic_return, idx)
198
+
199
+ if args.upload_model:
200
+ from huggingface import push_to_hub
201
+
202
+ repo_name = f"{args.env_id}-{args.exp_name}-2"
203
+ repo_id = f"{args.hf_entity}/{repo_name}" if args.hf_entity else repo_name
204
+ push_to_hub(args, episodic_returns, repo_id, "DQN", f"runs/{run_name}", f"videos/{run_name}-eval")
205
+
206
+ envs.close()
207
+ writer.close()
events.out.tfevents.1675770588.DESKTOP-AEVJ67Q.12507.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce0e8325e3737ee22bef471d20456e4b2e7920b99c287a8c4ec61110751d4767
3
+ size 1214
events.out.tfevents.1675771147.DESKTOP-AEVJ67Q.12633.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87df3029e5ea10b2d57a87edd0bca1877d57daf706aefdcfcb7cb03c4eedd5bb
3
+ size 1214
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 <costa.huang@outlook.com>"]
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 (535 kB). View file
 
videos/SpaceInvadersNoFrameskip-v4__dqn_atari__1__1675730632-eval/rl-video-episode-0.mp4 ADDED
Binary file (607 kB). View file
 
videos/SpaceInvadersNoFrameskip-v4__dqn_atari__1__1675730632-eval/rl-video-episode-1.mp4 ADDED
Binary file (511 kB). View file
 
videos/SpaceInvadersNoFrameskip-v4__dqn_atari__1__1675730632-eval/rl-video-episode-8.mp4 ADDED
Binary file (535 kB). View file