neatrl 0.1.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- neatrl-0.1.2/LICENSE +21 -0
- neatrl-0.1.2/PKG-INFO +87 -0
- neatrl-0.1.2/README.md +60 -0
- neatrl-0.1.2/pyproject.toml +63 -0
- neatrl-0.1.2/setup.cfg +4 -0
- neatrl-0.1.2/src/neatrl/__init__.py +3 -0
- neatrl-0.1.2/src/neatrl/dqn.py +341 -0
- neatrl-0.1.2/src/neatrl.egg-info/PKG-INFO +87 -0
- neatrl-0.1.2/src/neatrl.egg-info/SOURCES.txt +10 -0
- neatrl-0.1.2/src/neatrl.egg-info/dependency_links.txt +1 -0
- neatrl-0.1.2/src/neatrl.egg-info/requires.txt +17 -0
- neatrl-0.1.2/src/neatrl.egg-info/top_level.txt +1 -0
neatrl-0.1.2/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Yuvraj Singh
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
neatrl-0.1.2/PKG-INFO
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: neatrl
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A Python library for reinforcement learning algorithms
|
|
5
|
+
Author-email: Yuvraj Singh <yuvrajsingh9886@example.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: torch
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: gymnasium
|
|
13
|
+
Requires-Dist: stable-baselines3
|
|
14
|
+
Requires-Dist: tqdm
|
|
15
|
+
Requires-Dist: wandb
|
|
16
|
+
Requires-Dist: huggingface_hub
|
|
17
|
+
Requires-Dist: imageio
|
|
18
|
+
Requires-Dist: opencv-python
|
|
19
|
+
Requires-Dist: imageio[ffmpeg]
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: ruff; extra == "dev"
|
|
22
|
+
Requires-Dist: mypy; extra == "dev"
|
|
23
|
+
Requires-Dist: black; extra == "dev"
|
|
24
|
+
Requires-Dist: build; extra == "dev"
|
|
25
|
+
Requires-Dist: twine; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# neatrl
|
|
29
|
+
|
|
30
|
+
[](https://github.com/YuvrajSingh-mist/NeatRL/actions/workflows/ci.yml)
|
|
31
|
+
[](https://pypi.org/project/neatrl/)
|
|
32
|
+
|
|
33
|
+
A Python library for reinforcement learning algorithms.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install -e .
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
For development:
|
|
42
|
+
```bash
|
|
43
|
+
pip install -e .[dev]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
Import the components:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from neatrl import QNet, LinearEpsilonDecay, make_env, evaluate
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To run the DQN training script:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python -m neatrl.dqn
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Development
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Install dev dependencies
|
|
64
|
+
make install-dev
|
|
65
|
+
|
|
66
|
+
# Run all checks
|
|
67
|
+
make all
|
|
68
|
+
|
|
69
|
+
# Run tests
|
|
70
|
+
make test
|
|
71
|
+
|
|
72
|
+
# Lint and format
|
|
73
|
+
make lint
|
|
74
|
+
make format
|
|
75
|
+
|
|
76
|
+
# Type check
|
|
77
|
+
make type-check
|
|
78
|
+
|
|
79
|
+
# Build package
|
|
80
|
+
make build
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Or directly:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python neatrl/src/neatrl/dqn.py
|
|
87
|
+
```
|
neatrl-0.1.2/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# neatrl
|
|
2
|
+
|
|
3
|
+
[](https://github.com/YuvrajSingh-mist/NeatRL/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/neatrl/)
|
|
5
|
+
|
|
6
|
+
A Python library for reinforcement learning algorithms.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install -e .
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
For development:
|
|
15
|
+
```bash
|
|
16
|
+
pip install -e .[dev]
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
Import the components:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from neatrl import QNet, LinearEpsilonDecay, make_env, evaluate
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
To run the DQN training script:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
python -m neatrl.dqn
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Development
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Install dev dependencies
|
|
37
|
+
make install-dev
|
|
38
|
+
|
|
39
|
+
# Run all checks
|
|
40
|
+
make all
|
|
41
|
+
|
|
42
|
+
# Run tests
|
|
43
|
+
make test
|
|
44
|
+
|
|
45
|
+
# Lint and format
|
|
46
|
+
make lint
|
|
47
|
+
make format
|
|
48
|
+
|
|
49
|
+
# Type check
|
|
50
|
+
make type-check
|
|
51
|
+
|
|
52
|
+
# Build package
|
|
53
|
+
make build
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Or directly:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
python neatrl/src/neatrl/dqn.py
|
|
60
|
+
```
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=65", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "neatrl"
|
|
7
|
+
version = "0.1.2"
|
|
8
|
+
description = "A Python library for reinforcement learning algorithms"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Yuvraj Singh", email = "yuvrajsingh9886@example.com" }
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
dependencies = [
|
|
17
|
+
"torch",
|
|
18
|
+
"numpy",
|
|
19
|
+
"gymnasium",
|
|
20
|
+
"stable-baselines3",
|
|
21
|
+
"tqdm",
|
|
22
|
+
"wandb",
|
|
23
|
+
"huggingface_hub",
|
|
24
|
+
"imageio",
|
|
25
|
+
"opencv-python",
|
|
26
|
+
"imageio[ffmpeg]",
|
|
27
|
+
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
dev = [
|
|
32
|
+
"ruff",
|
|
33
|
+
"mypy",
|
|
34
|
+
"black",
|
|
35
|
+
"build",
|
|
36
|
+
"twine"
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
line-length = 88
|
|
44
|
+
target-version = "py39"
|
|
45
|
+
|
|
46
|
+
[tool.ruff.lint]
|
|
47
|
+
select = [
|
|
48
|
+
"E", # pycodestyle errors
|
|
49
|
+
"W", # pycodestyle warnings
|
|
50
|
+
"F", # pyflakes
|
|
51
|
+
"I", # isort
|
|
52
|
+
"B", # flake8-bugbear
|
|
53
|
+
"C4", # flake8-comprehensions
|
|
54
|
+
"UP", # pyupgrade
|
|
55
|
+
]
|
|
56
|
+
ignore = [
|
|
57
|
+
"E501", # line too long, handled by black
|
|
58
|
+
"B008", # do not perform function calls in argument defaults
|
|
59
|
+
"C901", # too complex
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
[tool.ruff.lint.per-file-ignores]
|
|
63
|
+
"__init__.py" = ["F401"]
|
neatrl-0.1.2/setup.cfg
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import random
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import cv2
|
|
6
|
+
import gymnasium as gym
|
|
7
|
+
import imageio
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
import torch.optim as optim
|
|
12
|
+
from stable_baselines3.common.buffers import ReplayBuffer
|
|
13
|
+
from torch.utils.tensorboard import SummaryWriter
|
|
14
|
+
from tqdm import tqdm
|
|
15
|
+
|
|
16
|
+
import wandb
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# ===== CONFIGURATION =====
|
|
20
|
+
class Config:
|
|
21
|
+
# Experiment settings
|
|
22
|
+
exp_name = "DQN-CartPole"
|
|
23
|
+
seed = 42
|
|
24
|
+
env_id = "CartPole-v1"
|
|
25
|
+
|
|
26
|
+
# Training parameters
|
|
27
|
+
total_timesteps = 20000
|
|
28
|
+
learning_rate = 2.5e-4
|
|
29
|
+
buffer_size = 10000
|
|
30
|
+
gamma = 0.99
|
|
31
|
+
tau = 1.0
|
|
32
|
+
target_network_frequency = 50
|
|
33
|
+
batch_size = 128
|
|
34
|
+
start_e = 1.0
|
|
35
|
+
end_e = 0.05
|
|
36
|
+
exploration_fraction = 0.5
|
|
37
|
+
learning_starts = 1000
|
|
38
|
+
train_frequency = 10
|
|
39
|
+
|
|
40
|
+
# Logging & saving
|
|
41
|
+
capture_video = True
|
|
42
|
+
save_model = True
|
|
43
|
+
upload_model = True
|
|
44
|
+
hf_entity = "" # Your Hugging Face username
|
|
45
|
+
|
|
46
|
+
# WandB settings
|
|
47
|
+
use_wandb = True
|
|
48
|
+
wandb_project = "cleanRL"
|
|
49
|
+
wandb_entity = "" # Your WandB username/team
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class QNet(nn.Module):
|
|
53
|
+
def __init__(self, state_space, action_space):
|
|
54
|
+
super().__init__()
|
|
55
|
+
self.fc1 = nn.Linear(state_space, 256)
|
|
56
|
+
self.fc2 = nn.Linear(256, 512)
|
|
57
|
+
self.q_value = nn.Linear(512, action_space)
|
|
58
|
+
|
|
59
|
+
def forward(self, x):
|
|
60
|
+
return self.q_value(torch.relu(self.fc2(torch.relu(self.fc1(x)))))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class LinearEpsilonDecay(nn.Module):
|
|
64
|
+
def __init__(self, initial_eps, end_eps, total_timesteps):
|
|
65
|
+
super().__init__()
|
|
66
|
+
self.initial_eps = initial_eps
|
|
67
|
+
# self.decay_factor = decay_factor
|
|
68
|
+
self.total_timesteps = total_timesteps
|
|
69
|
+
self.end_eps = end_eps
|
|
70
|
+
|
|
71
|
+
def forward(self, current_timestep, decay_factor):
|
|
72
|
+
slope = (self.end_eps - self.initial_eps) / (
|
|
73
|
+
self.total_timesteps * decay_factor
|
|
74
|
+
)
|
|
75
|
+
return max(slope * current_timestep + self.initial_eps, self.end_eps)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def make_env(env_id, seed, capture_video, run_name, eval_mode=False):
|
|
79
|
+
"""Create environment with video recording"""
|
|
80
|
+
env = gym.make(env_id, render_mode="rgb_array")
|
|
81
|
+
env = gym.wrappers.RecordEpisodeStatistics(env)
|
|
82
|
+
|
|
83
|
+
# Video recording setup
|
|
84
|
+
if capture_video:
|
|
85
|
+
if eval_mode:
|
|
86
|
+
# Evaluation videos
|
|
87
|
+
video_prefix = f"videos/{run_name}/eval"
|
|
88
|
+
else:
|
|
89
|
+
# Training videos
|
|
90
|
+
video_prefix = f"videos/{run_name}/train"
|
|
91
|
+
env = gym.wrappers.RecordVideo(
|
|
92
|
+
env,
|
|
93
|
+
video_prefix,
|
|
94
|
+
episode_trigger=lambda x: x % 100 == 0, # Record every 100 episodes
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
env.action_space.seed(seed)
|
|
98
|
+
|
|
99
|
+
return env
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def evaluate(model, device, run_name, num_eval_eps=10, record=False):
|
|
103
|
+
eval_env = make_env(
|
|
104
|
+
env_id=Config.env_id,
|
|
105
|
+
seed=Config.seed,
|
|
106
|
+
capture_video=True,
|
|
107
|
+
run_name=run_name,
|
|
108
|
+
eval_mode=True,
|
|
109
|
+
)
|
|
110
|
+
eval_env.action_space.seed(Config.seed)
|
|
111
|
+
|
|
112
|
+
model = model.to(device)
|
|
113
|
+
model = model.eval()
|
|
114
|
+
returns = []
|
|
115
|
+
frames = []
|
|
116
|
+
|
|
117
|
+
for _ in range(num_eval_eps):
|
|
118
|
+
obs, _ = eval_env.reset()
|
|
119
|
+
done = False
|
|
120
|
+
episode_reward = 0.0
|
|
121
|
+
# episode_frames = []
|
|
122
|
+
|
|
123
|
+
while not done:
|
|
124
|
+
if record:
|
|
125
|
+
if episode_reward > 500:
|
|
126
|
+
print("Hooray! Episode reward exceeded 500, stopping early.")
|
|
127
|
+
break
|
|
128
|
+
frame = eval_env.render()
|
|
129
|
+
frames.append(frame) # Capture all frames
|
|
130
|
+
|
|
131
|
+
# with torch.no_grad():
|
|
132
|
+
action = (
|
|
133
|
+
model(torch.tensor(obs, device=device).unsqueeze(0)).argmax().item()
|
|
134
|
+
)
|
|
135
|
+
obs, reward, terminated, truncated, _ = eval_env.step(action)
|
|
136
|
+
done = terminated or truncated
|
|
137
|
+
episode_reward += reward
|
|
138
|
+
|
|
139
|
+
returns.append(episode_reward)
|
|
140
|
+
# if eps == 0: # Save frames only for the first episode (optional)
|
|
141
|
+
# frames = episode_frames.copy() # Avoid memory issues
|
|
142
|
+
|
|
143
|
+
eval_env.close()
|
|
144
|
+
|
|
145
|
+
# Save video
|
|
146
|
+
if frames:
|
|
147
|
+
os.makedirs(f"videos/{run_name}/eval", exist_ok=True)
|
|
148
|
+
imageio.mimsave(f"videos/{run_name}/eval/eval_video.mp4", frames, fps=30)
|
|
149
|
+
|
|
150
|
+
return returns, frames
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def train_dqn(
|
|
154
|
+
env_id="CartPole-v1",
|
|
155
|
+
total_timesteps=20000,
|
|
156
|
+
seed=42,
|
|
157
|
+
learning_rate=2.5e-4,
|
|
158
|
+
buffer_size=10000,
|
|
159
|
+
gamma=0.99,
|
|
160
|
+
tau=1.0,
|
|
161
|
+
target_network_frequency=50,
|
|
162
|
+
batch_size=128,
|
|
163
|
+
start_e=1.0,
|
|
164
|
+
end_e=0.05,
|
|
165
|
+
exploration_fraction=0.5,
|
|
166
|
+
learning_starts=1000,
|
|
167
|
+
train_frequency=10,
|
|
168
|
+
capture_video=False,
|
|
169
|
+
use_wandb=False,
|
|
170
|
+
wandb_project="cleanRL",
|
|
171
|
+
wandb_entity="",
|
|
172
|
+
exp_name="DQN",
|
|
173
|
+
):
|
|
174
|
+
"""
|
|
175
|
+
Train a DQN agent on a Gymnasium environment.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
env_id: Gymnasium environment ID
|
|
179
|
+
total_timesteps: Total training timesteps
|
|
180
|
+
seed: Random seed
|
|
181
|
+
learning_rate: Learning rate for optimizer
|
|
182
|
+
buffer_size: Replay buffer size
|
|
183
|
+
gamma: Discount factor
|
|
184
|
+
tau: Target network update rate
|
|
185
|
+
target_network_frequency: How often to update target network
|
|
186
|
+
batch_size: Batch size for training
|
|
187
|
+
start_e: Initial epsilon for exploration
|
|
188
|
+
end_e: Final epsilon for exploration
|
|
189
|
+
exploration_fraction: Fraction of timesteps for epsilon decay
|
|
190
|
+
learning_starts: When to start learning
|
|
191
|
+
train_frequency: How often to train
|
|
192
|
+
capture_video: Whether to capture training videos
|
|
193
|
+
use_wandb: Whether to use Weights & Biases logging
|
|
194
|
+
wandb_project: W&B project name
|
|
195
|
+
wandb_entity: W&B entity/username
|
|
196
|
+
exp_name: Experiment name
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
Trained Q-network model
|
|
200
|
+
"""
|
|
201
|
+
run_name = f"{env_id}__{exp_name}__{seed}__{int(time.time())}"
|
|
202
|
+
|
|
203
|
+
# Initialize WandB
|
|
204
|
+
if use_wandb:
|
|
205
|
+
wandb.init(
|
|
206
|
+
project=wandb_project,
|
|
207
|
+
entity=wandb_entity,
|
|
208
|
+
sync_tensorboard=True,
|
|
209
|
+
config=locals(),
|
|
210
|
+
name=run_name,
|
|
211
|
+
monitor_gym=True,
|
|
212
|
+
save_code=True,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
if capture_video:
|
|
216
|
+
os.makedirs(f"videos/{run_name}/train", exist_ok=True)
|
|
217
|
+
os.makedirs(f"videos/{run_name}/eval", exist_ok=True)
|
|
218
|
+
os.makedirs(f"runs/{run_name}", exist_ok=True)
|
|
219
|
+
writer = SummaryWriter(f"runs/{run_name}")
|
|
220
|
+
|
|
221
|
+
# Set seeds
|
|
222
|
+
random.seed(seed)
|
|
223
|
+
np.random.seed(seed)
|
|
224
|
+
torch.manual_seed(seed)
|
|
225
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
226
|
+
|
|
227
|
+
env = make_env(env_id, seed, capture_video, run_name)
|
|
228
|
+
q_network = QNet(env.observation_space.shape[0], env.action_space.n).to(device)
|
|
229
|
+
target_net = QNet(env.observation_space.shape[0], env.action_space.n).to(device)
|
|
230
|
+
target_net.load_state_dict(q_network.state_dict())
|
|
231
|
+
optimizer = optim.Adam(q_network.parameters(), lr=learning_rate)
|
|
232
|
+
eps_decay = LinearEpsilonDecay(start_e, end_e, total_timesteps)
|
|
233
|
+
|
|
234
|
+
q_network.train()
|
|
235
|
+
target_net.train()
|
|
236
|
+
|
|
237
|
+
replay_buffer = ReplayBuffer(
|
|
238
|
+
buffer_size,
|
|
239
|
+
env.observation_space,
|
|
240
|
+
env.action_space,
|
|
241
|
+
device=device,
|
|
242
|
+
handle_timeout_termination=False,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
obs, _ = env.reset()
|
|
246
|
+
|
|
247
|
+
for step in tqdm(range(total_timesteps)):
|
|
248
|
+
eps = eps_decay(step, exploration_fraction)
|
|
249
|
+
rnd = random.random()
|
|
250
|
+
|
|
251
|
+
if rnd < eps:
|
|
252
|
+
action = env.action_space.sample()
|
|
253
|
+
else:
|
|
254
|
+
action = (
|
|
255
|
+
q_network(torch.tensor(obs, device=device).unsqueeze(0)).argmax().item()
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
new_obs, reward, terminated, truncated, info = env.step(action)
|
|
259
|
+
done = terminated or truncated
|
|
260
|
+
replay_buffer.add(
|
|
261
|
+
obs, new_obs, np.array(action), np.array(reward), np.array(done), [info]
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
# Log episode returns
|
|
265
|
+
if "episode" in info:
|
|
266
|
+
print(
|
|
267
|
+
f"Step={step}, Return={info['episode']['r']:.2f}, Length={info['episode']['l']}"
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
# WandB logging
|
|
271
|
+
if use_wandb:
|
|
272
|
+
wandb.log(
|
|
273
|
+
{
|
|
274
|
+
"episodic_return": info["episode"]["r"],
|
|
275
|
+
"episodic_length": info["episode"]["l"],
|
|
276
|
+
"epsilon": eps,
|
|
277
|
+
"global_step": step,
|
|
278
|
+
}
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if step > learning_starts and step % train_frequency == 0:
|
|
282
|
+
data = replay_buffer.sample(batch_size)
|
|
283
|
+
|
|
284
|
+
target_max = target_net(data.next_observations).max(1)[0]
|
|
285
|
+
td_target = data.rewards.flatten() + gamma * target_max * (
|
|
286
|
+
1 - data.dones.flatten()
|
|
287
|
+
)
|
|
288
|
+
old_val = q_network(data.observations).gather(1, data.actions).squeeze()
|
|
289
|
+
|
|
290
|
+
optimizer.zero_grad()
|
|
291
|
+
loss = nn.functional.mse_loss(old_val, td_target)
|
|
292
|
+
loss.backward()
|
|
293
|
+
optimizer.step()
|
|
294
|
+
|
|
295
|
+
# Log loss and metrics every 100 steps
|
|
296
|
+
if step % 100 == 0:
|
|
297
|
+
if use_wandb:
|
|
298
|
+
wandb.log(
|
|
299
|
+
{
|
|
300
|
+
"losses/td_loss": loss.item(),
|
|
301
|
+
}
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
# Update target network
|
|
305
|
+
if step % target_network_frequency == 0:
|
|
306
|
+
for q_params, target_params in zip(
|
|
307
|
+
q_network.parameters(), target_net.parameters()
|
|
308
|
+
):
|
|
309
|
+
target_params.data.copy_(
|
|
310
|
+
tau * q_params.data + (1.0 - tau) * target_params.data
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
# Model evaluation & saving
|
|
314
|
+
if step % 1000 == 0:
|
|
315
|
+
episodic_returns, _ = evaluate(q_network, device, run_name)
|
|
316
|
+
avg_return = np.mean(episodic_returns)
|
|
317
|
+
|
|
318
|
+
if use_wandb:
|
|
319
|
+
wandb.log({"val_avg_return": avg_return, "val_step": step})
|
|
320
|
+
print(f"Evaluation returns: {episodic_returns}, Average: {avg_return:.2f}")
|
|
321
|
+
|
|
322
|
+
if done:
|
|
323
|
+
obs, _ = env.reset()
|
|
324
|
+
else:
|
|
325
|
+
obs = new_obs
|
|
326
|
+
|
|
327
|
+
# Save final video to WandB
|
|
328
|
+
if use_wandb:
|
|
329
|
+
train_video_path = "videos/final.mp4"
|
|
330
|
+
_, frames = evaluate(q_network, device, run_name, record=True)
|
|
331
|
+
imageio.mimsave(train_video_path, frames, fps=30)
|
|
332
|
+
print(f"Final training video saved to {train_video_path}")
|
|
333
|
+
wandb.finish()
|
|
334
|
+
|
|
335
|
+
if capture_video:
|
|
336
|
+
cv2.destroyAllWindows()
|
|
337
|
+
|
|
338
|
+
env.close()
|
|
339
|
+
writer.close()
|
|
340
|
+
|
|
341
|
+
return q_network
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: neatrl
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A Python library for reinforcement learning algorithms
|
|
5
|
+
Author-email: Yuvraj Singh <yuvrajsingh9886@example.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: torch
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: gymnasium
|
|
13
|
+
Requires-Dist: stable-baselines3
|
|
14
|
+
Requires-Dist: tqdm
|
|
15
|
+
Requires-Dist: wandb
|
|
16
|
+
Requires-Dist: huggingface_hub
|
|
17
|
+
Requires-Dist: imageio
|
|
18
|
+
Requires-Dist: opencv-python
|
|
19
|
+
Requires-Dist: imageio[ffmpeg]
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: ruff; extra == "dev"
|
|
22
|
+
Requires-Dist: mypy; extra == "dev"
|
|
23
|
+
Requires-Dist: black; extra == "dev"
|
|
24
|
+
Requires-Dist: build; extra == "dev"
|
|
25
|
+
Requires-Dist: twine; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# neatrl
|
|
29
|
+
|
|
30
|
+
[](https://github.com/YuvrajSingh-mist/NeatRL/actions/workflows/ci.yml)
|
|
31
|
+
[](https://pypi.org/project/neatrl/)
|
|
32
|
+
|
|
33
|
+
A Python library for reinforcement learning algorithms.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install -e .
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
For development:
|
|
42
|
+
```bash
|
|
43
|
+
pip install -e .[dev]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
Import the components:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from neatrl import QNet, LinearEpsilonDecay, make_env, evaluate
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To run the DQN training script:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python -m neatrl.dqn
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Development
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Install dev dependencies
|
|
64
|
+
make install-dev
|
|
65
|
+
|
|
66
|
+
# Run all checks
|
|
67
|
+
make all
|
|
68
|
+
|
|
69
|
+
# Run tests
|
|
70
|
+
make test
|
|
71
|
+
|
|
72
|
+
# Lint and format
|
|
73
|
+
make lint
|
|
74
|
+
make format
|
|
75
|
+
|
|
76
|
+
# Type check
|
|
77
|
+
make type-check
|
|
78
|
+
|
|
79
|
+
# Build package
|
|
80
|
+
make build
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Or directly:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
python neatrl/src/neatrl/dqn.py
|
|
87
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/neatrl/__init__.py
|
|
5
|
+
src/neatrl/dqn.py
|
|
6
|
+
src/neatrl.egg-info/PKG-INFO
|
|
7
|
+
src/neatrl.egg-info/SOURCES.txt
|
|
8
|
+
src/neatrl.egg-info/dependency_links.txt
|
|
9
|
+
src/neatrl.egg-info/requires.txt
|
|
10
|
+
src/neatrl.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
neatrl
|