Repository navigation
Expand file tree
/
Copy pathPER-DQN.py
More file actions
260 lines (206 loc) · 10.3 KB
/
Copy pathPER-DQN.py
File metadata and controls
260 lines (206 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import os
import os
import time
import random
import csv
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from zoo_env import ZooEnv
class PrioritizedReplayBuffer:
def __init__(self, capacity, alpha=0.6):
self.capacity, self.alpha, self.buffer, self.pos = capacity, alpha, [], 0
self.priorities = np.zeros((capacity,), dtype=np.float32)
def push(self, state, action, reward, next_state, done):
max_prio = self.priorities.max() if self.buffer else 1.0
if len(self.buffer) < self.capacity: self.buffer.append((state, action, reward, next_state, done))
else: self.buffer[self.pos] = (state, action, reward, next_state, done)
self.priorities[self.pos] = max_prio
self.pos = (self.pos + 1) % self.capacity
def sample(self, batch_size, beta=0.4):
prios = self.priorities[:len(self.buffer)]
probs = (prios ** self.alpha) / (prios ** self.alpha).sum()
indices = np.random.choice(len(self.buffer), batch_size, p=probs)
samples = [self.buffer[idx] for idx in indices]
weights = (len(self.buffer) * probs[indices]) ** (-beta)
return samples, indices, torch.FloatTensor(weights / weights.max())
def update_priorities(self, batch_indices, batch_priorities):
for idx, prio in zip(batch_indices, batch_priorities): self.priorities[idx] = prio + 1e-5
class DQNNet(nn.Module):
def __init__(self, obs_dim, act_dim):
super(DQNNet, self).__init__()
self.fc = nn.Sequential(nn.Linear(obs_dim, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, act_dim))
def forward(self, x): return self.fc(x)
class DQNAgent:
def __init__(self, obs_dim, act_dim):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.q_net = DQNNet(obs_dim, act_dim).to(self.device)
self.target_net = DQNNet(obs_dim, act_dim).to(self.device)
self.target_net.load_state_dict(self.q_net.state_dict())
self.optimizer = optim.Adam(self.q_net.parameters(), lr=3e-4)
self.memory = PrioritizedReplayBuffer(100000)
self.batch_size, self.gamma, self.epsilon, self.epsilon_min, self.epsilon_decay, self.beta = 128, 0.99, 1.0, 0.05, 0.99998, 0.4
def select_action(self, state):
if random.random() < self.epsilon: return random.randint(0, 4)
state_t = torch.FloatTensor(state).unsqueeze(0).to(self.device)
with torch.no_grad(): return self.q_net(state_t).argmax().item()
def update(self):
if len(self.memory.buffer) < self.batch_size: return 0.0
self.beta = min(1.0, self.beta + 0.0001)
samples, indices, weights = self.memory.sample(self.batch_size, self.beta)
s, a, r, sn, d = zip(*samples)
s, a, r, sn, d = torch.FloatTensor(np.array(s)).to(self.device), torch.LongTensor(a).to(self.device), torch.FloatTensor(r).to(self.device), torch.FloatTensor(np.array(sn)).to(self.device), torch.FloatTensor(d).to(self.device)
q = self.q_net(s).gather(1, a.unsqueeze(1)).squeeze(1)
with torch.no_grad(): nq = self.target_net(sn).max(1)[0]
targets = r + (self.gamma * nq * (1 - d))
loss = (weights.to(self.device) * (targets - q).pow(2)).mean()
self.optimizer.zero_grad(); loss.backward(); self.optimizer.step()
self.memory.update_priorities(indices, torch.abs(targets - q).detach().cpu().numpy())
if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay
return loss.item()
"""
DQN Training Loop — Fixed Version
Fixes:
1. Target network updated every N steps (not every 100 episodes)
2. Escapes logged as windowed average (not last episode's cumulative)
3. Loss averaged over actual update count (not fixed 125)
"""
import csv
import time
import numpy as np
import torch
# ── Config ────────────────────────────────────────────────────────────────────
TARGET_UPDATE_FREQ = 1000 # steps between target net hard updates
LOG_INTERVAL = 100 # episodes between CSV rows / console prints
TOTAL_EPISODES = 24000
MAX_STEPS_PER_EP = 125
SAVE_PATH = "./outputs/"
# ── Training ──────────────────────────────────────────────────────────────────
def train():
env = ZooEnv()
agent = DQNAgent(obs_dim=24, act_dim=5)
log_file = open(SAVE_PATH + "training_log.csv", mode="w", newline="")
writer = csv.writer(log_file)
writer.writerow(["Update", "Steps", "Mean_Rew", "Avg_Escapes", "Loss", "Epsilon"])
best_reward = -np.inf
all_rewards = [] # per-episode totals
all_escapes = [] # per-episode escape counts ← FIX 2
total_steps = 0
start_time = time.time()
print(f"Training on {agent.device}. Logs/models → {SAVE_PATH}")
print("-" * 90)
print(f"{'Update':<8} | {'Steps':<10} | {'Mean Rew':<11} | "
f"{'Avg Esc':<9} | {'Loss':<9} | {'Epsilon':<8}")
print("-" * 90)
for ep in range(1, TOTAL_EPISODES + 1):
state, _ = env.reset()
ep_reward = 0.0
ep_loss = 0.0
ep_updates = 0 # actual gradient steps this episode ← FIX 3
ep_escapes = 0 # escapes THIS episode ← FIX 2
if ep % 2000 == 0:
env.start_recording()
for step in range(MAX_STEPS_PER_EP):
action = agent.select_action(state)
next_state, reward, done, _, info = env.step(action)
agent.memory.push(state, action, reward, next_state, done)
state = next_state
ep_reward += reward
total_steps += 1
# ── Gradient step ─────────────────────────────────────────────
loss = agent.update()
if len(agent.memory.buffer) >= agent.batch_size: # only count real updates
ep_loss += loss
ep_updates += 1 # ← FIX 3: count real updates
# ── FIX 1: target net on step cadence, not episode cadence ────
if total_steps % TARGET_UPDATE_FREQ == 0:
agent.target_net.load_state_dict(agent.q_net.state_dict())
if done:
break
ep_escapes = info["escapes"]
all_rewards.append(ep_reward)
all_escapes.append(ep_escapes)
if ep % LOG_INTERVAL == 0:
window = slice(-LOG_INTERVAL, None)
avg_rew = np.mean(all_rewards[window])
avg_esc = np.mean(all_escapes[window]) # ← FIX 2
avg_loss = (ep_loss / ep_updates # ← FIX 3
if ep_updates > 0 else 0.0)
update_idx = ep // LOG_INTERVAL
writer.writerow([
update_idx,
total_steps,
round(float(avg_rew), 2),
round(float(avg_esc), 2),
round(float(avg_loss), 4),
round(float(agent.epsilon), 3),
])
log_file.flush()
print(f"{update_idx:<8} | {total_steps:<10d} | {avg_rew:<11.1f} | "
f"{avg_esc:<9.2f} | {avg_loss:<9.3f} | {agent.epsilon:<8.3f}")
# Save best model
if avg_rew > best_reward:
best_reward = avg_rew
torch.save(agent.q_net, SAVE_PATH + "best_model.pth")
# ── Animation snapshot ────────────────────────────────────────────
if ep % 2000 == 0:
env.stop_recording()
env.save_animation(SAVE_PATH + f"progress_step_{total_steps}.gif")
log_file.close()
torch.save(agent.q_net, SAVE_PATH + "final_model.pth")
elapsed = time.time() - start_time
print("-" * 90)
print(f"Training complete in {elapsed/60:.1f} min. Best avg reward: {best_reward:.2f}")
def run_evaluation(model_name="best_model.pth", n_episodes=10, seed=42):
import __main__
LOCAL_PATH = "/content/dqn_eval_ep1_seed42.gif" # ← local only, no Drive
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_path = "/content/drive/MyDrive/RL/perfect_model.pth"
if not os.path.exists(model_path):
print(f"Error: Model file not found at {model_path}")
return
try:
if hasattr(torch.serialization, 'add_safe_globals'):
torch.serialization.add_safe_globals([__main__.DQNNet])
agent_net = torch.load(model_path, map_location=device, weights_only=False)
agent_net.eval()
print(f"Loaded {model_name} successfully on {device}")
except Exception as e:
print(f"Failed to load model: {e}")
return
print(f"\nStarting Evaluation for {n_episodes} Episodes (seed={seed})...")
print("-" * 65)
rewards, escapes_list = [], []
for ep in range(n_episodes):
env = ZooEnv(seed=40 + ep, n_animals=6)
state, _ = env.reset()
if ep == 0:
env.start_recording()
total_reward = 0.0
for step in range(125):
state_tensor = torch.FloatTensor(state).unsqueeze(0).to(device)
with torch.no_grad():
action = torch.argmax(agent_net(state_tensor)).item()
state, reward, terminated, truncated, info = env.step(action)
total_reward += reward
if terminated or truncated:
break
rewards.append(total_reward)
escapes_list.append(info["escapes"])
if ep == 0:
env.stop_recording()
env.save_animation(LOCAL_PATH, fps=6)
print(f" GIF saved : {LOCAL_PATH}")
print(f" Ep {ep+1:2d}: reward={total_reward:8.1f} escapes={info['escapes']} feedings={info['feedings']}")
print("-" * 65)
print(f" Mean reward : {np.mean(rewards):.1f}")
print(f" Std reward : {np.std(rewards):.1f}")
print(f" Mean escapes: {np.mean(escapes_list):.2f}")
print(f" GIF saved : {LOCAL_PATH}")
if __name__ == "__main__":
train()
run_evaluation(model_name="best_model.pth", n_episodes=10, seed=42)