pyforgeai-engine 1.0.0__py3-none-any.whl
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.
- pyforgeai/AI_Controller.py +156 -0
- pyforgeai/AI_Factory.py +176 -0
- pyforgeai/Adapters/Mock_Adapter.py +31 -0
- pyforgeai/Adapters/PyTorch_Adapter.py +44 -0
- pyforgeai/Adapters/TensorFlow_Adapter.py +46 -0
- pyforgeai/Adapters/__init__.py +28 -0
- pyforgeai/Environments/Game_Bridge_Env.py +117 -0
- pyforgeai/Environments/Target_Seek_Env.py +69 -0
- pyforgeai/Environments/__init__.py +8 -0
- pyforgeai/Interfaces/IAIModel.py +60 -0
- pyforgeai/Interfaces/IEnvironment.py +48 -0
- pyforgeai/Interfaces/ITrainer.py +46 -0
- pyforgeai/Interfaces/__init__.py +12 -0
- pyforgeai/Models/Model_Builder.py +162 -0
- pyforgeai/Models/Neural_Network_Pytorch.py +72 -0
- pyforgeai/Models/Neural_Network_Tensorflow.py +91 -0
- pyforgeai/Models/__init__.py +28 -0
- pyforgeai/Serialization/Model_Serializer.py +307 -0
- pyforgeai/Serialization/__init__.py +21 -0
- pyforgeai/Trainers/Genetic_Algorithm.py +417 -0
- pyforgeai/Trainers/Q_Learning.py +413 -0
- pyforgeai/Trainers/Training_Callbacks.py +97 -0
- pyforgeai/Trainers/__init__.py +53 -0
- pyforgeai/__init__.py +109 -0
- pyforgeai_engine-1.0.0.dist-info/METADATA +200 -0
- pyforgeai_engine-1.0.0.dist-info/RECORD +29 -0
- pyforgeai_engine-1.0.0.dist-info/WHEEL +5 -0
- pyforgeai_engine-1.0.0.dist-info/licenses/LICENSE +21 -0
- pyforgeai_engine-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import random
|
|
5
|
+
from collections import deque
|
|
6
|
+
from typing import Any, Callable, Sequence
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn as nn
|
|
10
|
+
import torch.optim as optim
|
|
11
|
+
|
|
12
|
+
from ..Interfaces.IEnvironment import IEnvironment
|
|
13
|
+
from ..Interfaces.ITrainer import ITrainer, ITrainingCallback, TrainingResult
|
|
14
|
+
from ..Models.Neural_Network_Pytorch import SimpleNN_Pytorch
|
|
15
|
+
from ..Serialization.Model_Serializer import load_qlearning_model, save_qlearning_model
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _build_qlearning_model(
|
|
19
|
+
type_model: str,
|
|
20
|
+
state_size: int,
|
|
21
|
+
action_size: int,
|
|
22
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
23
|
+
) -> SimpleNN_Pytorch:
|
|
24
|
+
if type_model.strip().capitalize() not in ("Pytorch", "Torch"):
|
|
25
|
+
raise NotImplementedError("Q-Learning / DQN currently supports the 'Pytorch' backend.")
|
|
26
|
+
return SimpleNN_Pytorch(state_size, action_size, hidden_sizes=hidden_sizes)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ReplayMemory:
|
|
30
|
+
"""Fixed-capacity experience replay buffer storing (state, action, reward, next_state, done) transitions."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, capacity: int = 10000) -> None:
|
|
33
|
+
self.memory: deque[tuple[Any, ...]] = deque(maxlen=int(capacity))
|
|
34
|
+
|
|
35
|
+
def push(self, transition: tuple[Any, ...]) -> None:
|
|
36
|
+
self.memory.append(transition)
|
|
37
|
+
|
|
38
|
+
def sample(self, batch_size: int) -> list[tuple[Any, ...]]:
|
|
39
|
+
return random.sample(self.memory, int(batch_size))
|
|
40
|
+
|
|
41
|
+
def __len__(self) -> int:
|
|
42
|
+
return len(self.memory)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class DQNAgent:
|
|
46
|
+
"""Deep Q-Network agent supporting Double-DQN, configurable Huber/MSE loss, and epsilon-greedy exploration."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
type_model: str = "Pytorch",
|
|
51
|
+
state_size: int = 6,
|
|
52
|
+
action_size: int = 2,
|
|
53
|
+
lr: float = 1e-3,
|
|
54
|
+
gamma: float = 0.99,
|
|
55
|
+
epsilon_start: float = 1.0,
|
|
56
|
+
epsilon_end: float = 0.01,
|
|
57
|
+
epsilon_decay: float = 0.995,
|
|
58
|
+
memory_size: int = 10000,
|
|
59
|
+
batch_size: int = 32,
|
|
60
|
+
target_update: int = 100,
|
|
61
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
62
|
+
double_dqn: bool = True,
|
|
63
|
+
loss_type: str = "mse",
|
|
64
|
+
grad_clip: float | None = 1.0,
|
|
65
|
+
device: str | torch.device | None = None,
|
|
66
|
+
) -> None:
|
|
67
|
+
self.type_model = type_model
|
|
68
|
+
self.state_size = int(state_size)
|
|
69
|
+
self.action_size = int(action_size)
|
|
70
|
+
self._hidden_sizes = list(hidden_sizes) if hidden_sizes is not None else None
|
|
71
|
+
self.gamma = float(gamma)
|
|
72
|
+
self.epsilon = float(epsilon_start)
|
|
73
|
+
self.epsilon_min = float(epsilon_end)
|
|
74
|
+
self.epsilon_decay = float(epsilon_decay)
|
|
75
|
+
self.batch_size = int(batch_size)
|
|
76
|
+
self.steps_done = 0
|
|
77
|
+
self.target_update = max(1, int(target_update))
|
|
78
|
+
self.double_dqn = bool(double_dqn)
|
|
79
|
+
self.grad_clip = grad_clip
|
|
80
|
+
|
|
81
|
+
if device is None:
|
|
82
|
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
83
|
+
else:
|
|
84
|
+
self.device = torch.device(device)
|
|
85
|
+
|
|
86
|
+
self.policy_net = _build_qlearning_model(
|
|
87
|
+
type_model,
|
|
88
|
+
self.state_size,
|
|
89
|
+
self.action_size,
|
|
90
|
+
hidden_sizes=self._hidden_sizes,
|
|
91
|
+
).to(self.device)
|
|
92
|
+
self.target_net = _build_qlearning_model(
|
|
93
|
+
type_model,
|
|
94
|
+
self.state_size,
|
|
95
|
+
self.action_size,
|
|
96
|
+
hidden_sizes=self._hidden_sizes,
|
|
97
|
+
).to(self.device)
|
|
98
|
+
self.target_net.load_state_dict(self.policy_net.state_dict())
|
|
99
|
+
self.target_net.eval()
|
|
100
|
+
|
|
101
|
+
self.optimizer = optim.Adam(self.policy_net.parameters(), lr=float(lr))
|
|
102
|
+
self.memory = ReplayMemory(memory_size)
|
|
103
|
+
self.loss_fn = nn.SmoothL1Loss() if loss_type.lower() == "huber" else nn.MSELoss()
|
|
104
|
+
|
|
105
|
+
def select_action(self, state: np.ndarray | list[float]) -> int:
|
|
106
|
+
if random.random() < self.epsilon:
|
|
107
|
+
return random.randrange(self.action_size)
|
|
108
|
+
with torch.no_grad():
|
|
109
|
+
tensor_state = torch.as_tensor(
|
|
110
|
+
np.asarray(state, dtype=np.float32),
|
|
111
|
+
dtype=torch.float32,
|
|
112
|
+
device=self.device,
|
|
113
|
+
)
|
|
114
|
+
q_values = self.policy_net(tensor_state)
|
|
115
|
+
return int(torch.argmax(q_values).item())
|
|
116
|
+
|
|
117
|
+
def store_transition(
|
|
118
|
+
self,
|
|
119
|
+
state: np.ndarray | list[float],
|
|
120
|
+
action: int,
|
|
121
|
+
reward: float,
|
|
122
|
+
next_state: np.ndarray | list[float],
|
|
123
|
+
done: bool,
|
|
124
|
+
) -> None:
|
|
125
|
+
self.memory.push((state, int(action), float(reward), next_state, bool(done)))
|
|
126
|
+
|
|
127
|
+
def optimize_model(self) -> float | None:
|
|
128
|
+
if len(self.memory) < self.batch_size:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
transitions = self.memory.sample(self.batch_size)
|
|
132
|
+
states, actions, rewards, next_states, dones = zip(*transitions)
|
|
133
|
+
|
|
134
|
+
states_t = torch.as_tensor(np.asarray(states, dtype=np.float32), dtype=torch.float32, device=self.device)
|
|
135
|
+
actions_t = torch.as_tensor(actions, dtype=torch.int64, device=self.device).unsqueeze(1)
|
|
136
|
+
rewards_t = torch.as_tensor(rewards, dtype=torch.float32, device=self.device).unsqueeze(1)
|
|
137
|
+
next_states_t = torch.as_tensor(
|
|
138
|
+
np.asarray(next_states, dtype=np.float32),
|
|
139
|
+
dtype=torch.float32,
|
|
140
|
+
device=self.device,
|
|
141
|
+
)
|
|
142
|
+
dones_t = torch.as_tensor(dones, dtype=torch.float32, device=self.device).unsqueeze(1)
|
|
143
|
+
|
|
144
|
+
current_q = self.policy_net(states_t).gather(1, actions_t)
|
|
145
|
+
|
|
146
|
+
with torch.no_grad():
|
|
147
|
+
if self.double_dqn:
|
|
148
|
+
best_next_actions = self.policy_net(next_states_t).argmax(dim=1, keepdim=True)
|
|
149
|
+
next_q = self.target_net(next_states_t).gather(1, best_next_actions)
|
|
150
|
+
else:
|
|
151
|
+
next_q = self.target_net(next_states_t).max(1)[0].unsqueeze(1)
|
|
152
|
+
expected_q = rewards_t + (1.0 - dones_t) * self.gamma * next_q
|
|
153
|
+
|
|
154
|
+
loss = self.loss_fn(current_q, expected_q)
|
|
155
|
+
self.optimizer.zero_grad()
|
|
156
|
+
loss.backward()
|
|
157
|
+
if self.grad_clip is not None:
|
|
158
|
+
nn.utils.clip_grad_norm_(self.policy_net.parameters(), max_norm=float(self.grad_clip))
|
|
159
|
+
self.optimizer.step()
|
|
160
|
+
|
|
161
|
+
self.epsilon = max(self.epsilon_min, self.epsilon * self.epsilon_decay)
|
|
162
|
+
self.steps_done += 1
|
|
163
|
+
if self.steps_done % self.target_update == 0:
|
|
164
|
+
self.target_net.load_state_dict(self.policy_net.state_dict())
|
|
165
|
+
|
|
166
|
+
return float(loss.item())
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class QLearningTrainer(ITrainer):
|
|
170
|
+
"""Deep Q-Learning trainer supporting both Gym-style `IEnvironment` loops and event-driven Pygame loops."""
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
game: Any = None,
|
|
175
|
+
type_model: str = "Pytorch",
|
|
176
|
+
input_size: int = 6,
|
|
177
|
+
output_size: int = 2,
|
|
178
|
+
episodes: int = 500,
|
|
179
|
+
lr: float = 1e-3,
|
|
180
|
+
gamma: float = 0.99,
|
|
181
|
+
epsilon_start: float = 1.0,
|
|
182
|
+
epsilon_end: float = 0.01,
|
|
183
|
+
epsilon_decay: float = 0.995,
|
|
184
|
+
memory_size: int = 10000,
|
|
185
|
+
batch_size: int = 32,
|
|
186
|
+
target_update: int = 100,
|
|
187
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
188
|
+
double_dqn: bool = True,
|
|
189
|
+
save_path: str | None = None,
|
|
190
|
+
callbacks: Sequence[ITrainingCallback] | None = None,
|
|
191
|
+
verbose: bool = True,
|
|
192
|
+
) -> None:
|
|
193
|
+
self.game = game
|
|
194
|
+
self.type_model = type_model
|
|
195
|
+
self.input_size = int(input_size)
|
|
196
|
+
self.output_size = int(output_size)
|
|
197
|
+
self.episodes = int(episodes)
|
|
198
|
+
self.current_episode = 0
|
|
199
|
+
self.best_reward = float("-inf")
|
|
200
|
+
self.best_model: SimpleNN_Pytorch | None = None
|
|
201
|
+
self.rewards_history: list[float] = []
|
|
202
|
+
self.save_path = save_path
|
|
203
|
+
self.callbacks = list(callbacks) if callbacks else []
|
|
204
|
+
self.verbose = bool(verbose)
|
|
205
|
+
self.last_result: TrainingResult | None = None
|
|
206
|
+
|
|
207
|
+
self.agent = DQNAgent(
|
|
208
|
+
type_model=type_model,
|
|
209
|
+
state_size=self.input_size,
|
|
210
|
+
action_size=self.output_size,
|
|
211
|
+
lr=lr,
|
|
212
|
+
gamma=gamma,
|
|
213
|
+
epsilon_start=epsilon_start,
|
|
214
|
+
epsilon_end=epsilon_end,
|
|
215
|
+
epsilon_decay=epsilon_decay,
|
|
216
|
+
memory_size=memory_size,
|
|
217
|
+
batch_size=batch_size,
|
|
218
|
+
target_update=target_update,
|
|
219
|
+
hidden_sizes=hidden_sizes,
|
|
220
|
+
double_dqn=double_dqn,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def get_action(self, state: np.ndarray | list[float]) -> int:
|
|
224
|
+
return self.agent.select_action(state)
|
|
225
|
+
|
|
226
|
+
def store_experience(
|
|
227
|
+
self,
|
|
228
|
+
state: np.ndarray | list[float],
|
|
229
|
+
action: int,
|
|
230
|
+
reward: float,
|
|
231
|
+
next_state: np.ndarray | list[float],
|
|
232
|
+
done: bool,
|
|
233
|
+
) -> float | None:
|
|
234
|
+
self.agent.store_transition(state, action, reward, next_state, done)
|
|
235
|
+
return self.agent.optimize_model()
|
|
236
|
+
|
|
237
|
+
def episode_complete(self, total_reward: float) -> bool:
|
|
238
|
+
self.rewards_history.append(float(total_reward))
|
|
239
|
+
if total_reward > self.best_reward:
|
|
240
|
+
self.best_reward = float(total_reward)
|
|
241
|
+
self.best_model = copy.deepcopy(self.agent.policy_net)
|
|
242
|
+
|
|
243
|
+
if self.verbose and self.current_episode % 10 == 0:
|
|
244
|
+
window = self.rewards_history[-10:]
|
|
245
|
+
avg_reward = float(np.mean(window))
|
|
246
|
+
print(
|
|
247
|
+
f"Episode {self.current_episode}/{self.episodes}: "
|
|
248
|
+
f"Avg Reward = {avg_reward:.2f}, Epsilon = {self.agent.epsilon:.3f}"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
self.current_episode += 1
|
|
252
|
+
if self.current_episode >= self.episodes:
|
|
253
|
+
if self.verbose:
|
|
254
|
+
print(f"Q-Learning training completed. Best reward: {self.best_reward:.2f}")
|
|
255
|
+
return True
|
|
256
|
+
return False
|
|
257
|
+
|
|
258
|
+
def get_best_model(self) -> SimpleNN_Pytorch:
|
|
259
|
+
return self.best_model if self.best_model is not None else self.agent.policy_net
|
|
260
|
+
|
|
261
|
+
def train_environment_with_result(self, env: IEnvironment, max_steps_per_episode: int = 1000) -> TrainingResult:
|
|
262
|
+
"""Train directly against a step-based `IEnvironment` (Gym-like interface)."""
|
|
263
|
+
self.current_episode = 0
|
|
264
|
+
self.best_reward = float("-inf")
|
|
265
|
+
self.rewards_history.clear()
|
|
266
|
+
stopped_early = False
|
|
267
|
+
|
|
268
|
+
for cb in self.callbacks:
|
|
269
|
+
cb.on_training_start(self)
|
|
270
|
+
|
|
271
|
+
for ep in range(self.episodes):
|
|
272
|
+
if env.should_stop():
|
|
273
|
+
stopped_early = True
|
|
274
|
+
break
|
|
275
|
+
|
|
276
|
+
state = env.reset()
|
|
277
|
+
total_reward = 0.0
|
|
278
|
+
done = False
|
|
279
|
+
steps = 0
|
|
280
|
+
|
|
281
|
+
while not done and steps < max_steps_per_episode:
|
|
282
|
+
if env.should_stop():
|
|
283
|
+
stopped_early = True
|
|
284
|
+
break
|
|
285
|
+
action = self.get_action(state)
|
|
286
|
+
next_state, reward, done, _ = env.step(action)
|
|
287
|
+
self.store_experience(state, action, reward, next_state, done)
|
|
288
|
+
state = next_state
|
|
289
|
+
total_reward += reward
|
|
290
|
+
steps += 1
|
|
291
|
+
|
|
292
|
+
training_complete = self.episode_complete(total_reward)
|
|
293
|
+
mean_recent = float(np.mean(self.rewards_history[-10:]))
|
|
294
|
+
|
|
295
|
+
should_halt = False
|
|
296
|
+
for cb in self.callbacks:
|
|
297
|
+
if cb.on_iteration_end(ep, self.best_reward, mean_recent, self):
|
|
298
|
+
should_halt = True
|
|
299
|
+
if should_halt or training_complete or stopped_early:
|
|
300
|
+
stopped_early = should_halt or stopped_early
|
|
301
|
+
break
|
|
302
|
+
|
|
303
|
+
best = self.get_best_model()
|
|
304
|
+
if self.save_path and best is not None:
|
|
305
|
+
save_qlearning_model(best, self.agent.optimizer, self.save_path)
|
|
306
|
+
|
|
307
|
+
result = TrainingResult(
|
|
308
|
+
best_model=best,
|
|
309
|
+
best_score=self.best_reward,
|
|
310
|
+
history=list(self.rewards_history),
|
|
311
|
+
iterations_completed=self.current_episode,
|
|
312
|
+
stopped_early=stopped_early,
|
|
313
|
+
)
|
|
314
|
+
self.last_result = result
|
|
315
|
+
for cb in self.callbacks:
|
|
316
|
+
cb.on_training_end(result, self)
|
|
317
|
+
return result
|
|
318
|
+
|
|
319
|
+
def train(self, target: Any = None) -> SimpleNN_Pytorch:
|
|
320
|
+
"""Run training against an `IEnvironment` or a game instance defining `run_with_model()`."""
|
|
321
|
+
target_obj = target if target is not None else self.game
|
|
322
|
+
if isinstance(target_obj, IEnvironment):
|
|
323
|
+
return self.train_environment_with_result(target_obj).best_model
|
|
324
|
+
|
|
325
|
+
if target_obj is None:
|
|
326
|
+
raise ValueError("A target IEnvironment or game instance must be provided to QLearningTrainer.train().")
|
|
327
|
+
|
|
328
|
+
# Event-driven game loop mode (compatible with Pong_Game)
|
|
329
|
+
global _qlearning_trainer
|
|
330
|
+
_qlearning_trainer = self
|
|
331
|
+
target_obj.qlearning_trainer = self
|
|
332
|
+
target_obj._qlearning_state = None
|
|
333
|
+
target_obj._qlearning_prev_reward = 0
|
|
334
|
+
|
|
335
|
+
for cb in self.callbacks:
|
|
336
|
+
cb.on_training_start(self)
|
|
337
|
+
|
|
338
|
+
while self.current_episode < self.episodes:
|
|
339
|
+
target_obj.generation = self.current_episode
|
|
340
|
+
total_reward = float(target_obj.run_with_model())
|
|
341
|
+
training_complete = self.episode_complete(total_reward)
|
|
342
|
+
mean_recent = float(np.mean(self.rewards_history[-10:]))
|
|
343
|
+
should_halt = any(
|
|
344
|
+
cb.on_iteration_end(self.current_episode - 1, self.best_reward, mean_recent, self)
|
|
345
|
+
for cb in self.callbacks
|
|
346
|
+
)
|
|
347
|
+
if training_complete or should_halt or getattr(target_obj, "exit", False):
|
|
348
|
+
break
|
|
349
|
+
|
|
350
|
+
best_model = self.get_best_model()
|
|
351
|
+
for attr in ("_qlearning_state", "_qlearning_prev_reward", "qlearning_trainer"):
|
|
352
|
+
if hasattr(target_obj, attr):
|
|
353
|
+
delattr(target_obj, attr)
|
|
354
|
+
_qlearning_trainer = None
|
|
355
|
+
target_obj.model = best_model
|
|
356
|
+
|
|
357
|
+
if self.save_path and best_model is not None:
|
|
358
|
+
save_qlearning_model(best_model, self.agent.optimizer, self.save_path)
|
|
359
|
+
|
|
360
|
+
result = TrainingResult(
|
|
361
|
+
best_model=best_model,
|
|
362
|
+
best_score=self.best_reward,
|
|
363
|
+
history=list(self.rewards_history),
|
|
364
|
+
iterations_completed=self.current_episode,
|
|
365
|
+
stopped_early=bool(getattr(target_obj, "exit", False)),
|
|
366
|
+
)
|
|
367
|
+
self.last_result = result
|
|
368
|
+
for cb in self.callbacks:
|
|
369
|
+
cb.on_training_end(result, self)
|
|
370
|
+
return best_model
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
# Kept for backward compatibility with legacy event-driven Pong_Game imports
|
|
374
|
+
_qlearning_trainer: QLearningTrainer | None = None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def get_active_qlearning_trainer(game: Any = None) -> QLearningTrainer | None:
|
|
378
|
+
"""Retrieve the active QLearningTrainer from `game.qlearning_trainer` or module fallback."""
|
|
379
|
+
if game is not None and hasattr(game, "qlearning_trainer"):
|
|
380
|
+
return game.qlearning_trainer
|
|
381
|
+
return _qlearning_trainer
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def q_learning_algorithm(
|
|
385
|
+
game: Any,
|
|
386
|
+
type_model: str = "Pytorch",
|
|
387
|
+
input_size: int = 6,
|
|
388
|
+
output_size: int = 2,
|
|
389
|
+
episodes: int = 500,
|
|
390
|
+
lr: float = 1e-3,
|
|
391
|
+
gamma: float = 0.99,
|
|
392
|
+
epsilon_start: float = 1.0,
|
|
393
|
+
epsilon_end: float = 0.01,
|
|
394
|
+
epsilon_decay: float = 0.995,
|
|
395
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
396
|
+
verbose: bool = True,
|
|
397
|
+
) -> SimpleNN_Pytorch:
|
|
398
|
+
"""Functional Q-Learning entry point preserving 100% compatibility with Pong_Game."""
|
|
399
|
+
trainer = QLearningTrainer(
|
|
400
|
+
game=game,
|
|
401
|
+
type_model=type_model,
|
|
402
|
+
input_size=input_size,
|
|
403
|
+
output_size=output_size,
|
|
404
|
+
episodes=episodes,
|
|
405
|
+
lr=lr,
|
|
406
|
+
gamma=gamma,
|
|
407
|
+
epsilon_start=epsilon_start,
|
|
408
|
+
epsilon_end=epsilon_end,
|
|
409
|
+
epsilon_decay=epsilon_decay,
|
|
410
|
+
hidden_sizes=hidden_sizes,
|
|
411
|
+
verbose=verbose,
|
|
412
|
+
)
|
|
413
|
+
return trainer.train(game)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ..Interfaces.ITrainer import ITrainingCallback, TrainingResult
|
|
6
|
+
from ..Serialization.Model_Serializer import save_model
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class EarlyStoppingCallback(ITrainingCallback):
|
|
10
|
+
"""Stop training early when `target_score` is reached or when score stops improving for `patience` iterations."""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
patience: int | None = None,
|
|
15
|
+
min_delta: float = 1e-4,
|
|
16
|
+
target_score: float | None = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
self.patience = patience
|
|
19
|
+
self.min_delta = float(min_delta)
|
|
20
|
+
self.target_score = target_score
|
|
21
|
+
self._best_seen = float("-inf")
|
|
22
|
+
self._stagnant_iters = 0
|
|
23
|
+
|
|
24
|
+
def on_training_start(self, trainer: Any) -> None:
|
|
25
|
+
self._best_seen = float("-inf")
|
|
26
|
+
self._stagnant_iters = 0
|
|
27
|
+
|
|
28
|
+
def on_iteration_end(
|
|
29
|
+
self,
|
|
30
|
+
iteration: int,
|
|
31
|
+
best_score: float,
|
|
32
|
+
mean_score: float,
|
|
33
|
+
trainer: Any,
|
|
34
|
+
) -> bool:
|
|
35
|
+
if self.target_score is not None and best_score >= self.target_score:
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
if best_score > self._best_seen + self.min_delta:
|
|
39
|
+
self._best_seen = best_score
|
|
40
|
+
self._stagnant_iters = 0
|
|
41
|
+
else:
|
|
42
|
+
self._stagnant_iters += 1
|
|
43
|
+
|
|
44
|
+
if self.patience is not None and self._stagnant_iters >= self.patience:
|
|
45
|
+
return True
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CheckpointCallback(ITrainingCallback):
|
|
50
|
+
"""Automatically save the best model to `save_path` whenever a new record score is achieved."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, save_path: str) -> None:
|
|
53
|
+
self.save_path = save_path
|
|
54
|
+
self._best_saved = float("-inf")
|
|
55
|
+
|
|
56
|
+
def on_training_start(self, trainer: Any) -> None:
|
|
57
|
+
self._best_saved = float("-inf")
|
|
58
|
+
|
|
59
|
+
def on_iteration_end(
|
|
60
|
+
self,
|
|
61
|
+
iteration: int,
|
|
62
|
+
best_score: float,
|
|
63
|
+
mean_score: float,
|
|
64
|
+
trainer: Any,
|
|
65
|
+
) -> bool:
|
|
66
|
+
if best_score > self._best_saved:
|
|
67
|
+
self._best_saved = best_score
|
|
68
|
+
best_model = getattr(trainer, "best_model", None)
|
|
69
|
+
if best_model is not None:
|
|
70
|
+
save_model(best_model, self.save_path)
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class HistoryCallback(ITrainingCallback):
|
|
75
|
+
"""Track per-iteration best and mean scores for plotting or analysis."""
|
|
76
|
+
|
|
77
|
+
def __init__(self) -> None:
|
|
78
|
+
self.best_scores: list[float] = []
|
|
79
|
+
self.mean_scores: list[float] = []
|
|
80
|
+
|
|
81
|
+
def on_training_start(self, trainer: Any) -> None:
|
|
82
|
+
self.best_scores.clear()
|
|
83
|
+
self.mean_scores.clear()
|
|
84
|
+
|
|
85
|
+
def on_iteration_end(
|
|
86
|
+
self,
|
|
87
|
+
iteration: int,
|
|
88
|
+
best_score: float,
|
|
89
|
+
mean_score: float,
|
|
90
|
+
trainer: Any,
|
|
91
|
+
) -> bool:
|
|
92
|
+
self.best_scores.append(float(best_score))
|
|
93
|
+
self.mean_scores.append(float(mean_score))
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
def on_training_end(self, result: TrainingResult, trainer: Any) -> None:
|
|
97
|
+
pass
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from .Genetic_Algorithm import (
|
|
2
|
+
GeneticTrainer,
|
|
3
|
+
_get_weights_np,
|
|
4
|
+
_set_weights_np,
|
|
5
|
+
crossover,
|
|
6
|
+
evaluate_population,
|
|
7
|
+
fitness_function,
|
|
8
|
+
genetic_algorithm,
|
|
9
|
+
initialize_population,
|
|
10
|
+
load_genetic_model,
|
|
11
|
+
mutate,
|
|
12
|
+
save_genetic_model,
|
|
13
|
+
select_parents,
|
|
14
|
+
)
|
|
15
|
+
from .Q_Learning import (
|
|
16
|
+
DQNAgent,
|
|
17
|
+
QLearningTrainer,
|
|
18
|
+
ReplayMemory,
|
|
19
|
+
get_active_qlearning_trainer,
|
|
20
|
+
load_qlearning_model,
|
|
21
|
+
q_learning_algorithm,
|
|
22
|
+
save_qlearning_model,
|
|
23
|
+
)
|
|
24
|
+
from .Training_Callbacks import (
|
|
25
|
+
CheckpointCallback,
|
|
26
|
+
EarlyStoppingCallback,
|
|
27
|
+
HistoryCallback,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"CheckpointCallback",
|
|
32
|
+
"DQNAgent",
|
|
33
|
+
"EarlyStoppingCallback",
|
|
34
|
+
"GeneticTrainer",
|
|
35
|
+
"HistoryCallback",
|
|
36
|
+
"QLearningTrainer",
|
|
37
|
+
"ReplayMemory",
|
|
38
|
+
"_get_weights_np",
|
|
39
|
+
"_set_weights_np",
|
|
40
|
+
"crossover",
|
|
41
|
+
"evaluate_population",
|
|
42
|
+
"fitness_function",
|
|
43
|
+
"genetic_algorithm",
|
|
44
|
+
"get_active_qlearning_trainer",
|
|
45
|
+
"initialize_population",
|
|
46
|
+
"load_genetic_model",
|
|
47
|
+
"load_qlearning_model",
|
|
48
|
+
"mutate",
|
|
49
|
+
"q_learning_algorithm",
|
|
50
|
+
"save_genetic_model",
|
|
51
|
+
"save_qlearning_model",
|
|
52
|
+
"select_parents",
|
|
53
|
+
]
|
pyforgeai/__init__.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""PyForgeAI: Modular Neuroevolution (Genetic Algorithms) and Deep Q-Learning library for Pygame and Python simulations."""
|
|
2
|
+
|
|
3
|
+
from .Adapters import MockAdapter, PyTorchAdapter, TensorFlowAdapter, wrap_model
|
|
4
|
+
from .AI_Controller import AIController, AIHandler
|
|
5
|
+
from .AI_Factory import AIFactory
|
|
6
|
+
from .Environments import CallbackRLEnvironment, GameFitnessBridge, TargetSeekEnvironment
|
|
7
|
+
from .Interfaces import (
|
|
8
|
+
IAIModel,
|
|
9
|
+
IEnvironment,
|
|
10
|
+
IFitnessEnvironment,
|
|
11
|
+
ITrainer,
|
|
12
|
+
ITrainingCallback,
|
|
13
|
+
TrainingResult,
|
|
14
|
+
)
|
|
15
|
+
from .Models import (
|
|
16
|
+
SimpleNN,
|
|
17
|
+
SimpleNN_Pytorch,
|
|
18
|
+
SimpleNN_Tensorflow,
|
|
19
|
+
build_model,
|
|
20
|
+
clone_model,
|
|
21
|
+
get_weights_np,
|
|
22
|
+
infer_architecture,
|
|
23
|
+
is_tf_model,
|
|
24
|
+
is_torch_model,
|
|
25
|
+
set_weights_np,
|
|
26
|
+
)
|
|
27
|
+
from .Serialization import (
|
|
28
|
+
AILoader,
|
|
29
|
+
AIModelLoadResult,
|
|
30
|
+
load_genetic_model,
|
|
31
|
+
load_model,
|
|
32
|
+
load_qlearning_model,
|
|
33
|
+
save_genetic_model,
|
|
34
|
+
save_model,
|
|
35
|
+
save_qlearning_model,
|
|
36
|
+
)
|
|
37
|
+
from .Trainers import (
|
|
38
|
+
CheckpointCallback,
|
|
39
|
+
DQNAgent,
|
|
40
|
+
EarlyStoppingCallback,
|
|
41
|
+
GeneticTrainer,
|
|
42
|
+
HistoryCallback,
|
|
43
|
+
QLearningTrainer,
|
|
44
|
+
ReplayMemory,
|
|
45
|
+
crossover,
|
|
46
|
+
evaluate_population,
|
|
47
|
+
fitness_function,
|
|
48
|
+
genetic_algorithm,
|
|
49
|
+
get_active_qlearning_trainer,
|
|
50
|
+
initialize_population,
|
|
51
|
+
mutate,
|
|
52
|
+
q_learning_algorithm,
|
|
53
|
+
select_parents,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
__version__ = "1.0.0"
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"AIController",
|
|
60
|
+
"AIFactory",
|
|
61
|
+
"AIHandler",
|
|
62
|
+
"AILoader",
|
|
63
|
+
"AIModelLoadResult",
|
|
64
|
+
"CallbackRLEnvironment",
|
|
65
|
+
"CheckpointCallback",
|
|
66
|
+
"DQNAgent",
|
|
67
|
+
"EarlyStoppingCallback",
|
|
68
|
+
"GameFitnessBridge",
|
|
69
|
+
"GeneticTrainer",
|
|
70
|
+
"HistoryCallback",
|
|
71
|
+
"IAIModel",
|
|
72
|
+
"IEnvironment",
|
|
73
|
+
"IFitnessEnvironment",
|
|
74
|
+
"ITrainer",
|
|
75
|
+
"ITrainingCallback",
|
|
76
|
+
"MockAdapter",
|
|
77
|
+
"PyTorchAdapter",
|
|
78
|
+
"QLearningTrainer",
|
|
79
|
+
"ReplayMemory",
|
|
80
|
+
"SimpleNN",
|
|
81
|
+
"SimpleNN_Pytorch",
|
|
82
|
+
"SimpleNN_Tensorflow",
|
|
83
|
+
"TargetSeekEnvironment",
|
|
84
|
+
"TensorFlowAdapter",
|
|
85
|
+
"TrainingResult",
|
|
86
|
+
"build_model",
|
|
87
|
+
"clone_model",
|
|
88
|
+
"crossover",
|
|
89
|
+
"evaluate_population",
|
|
90
|
+
"fitness_function",
|
|
91
|
+
"genetic_algorithm",
|
|
92
|
+
"get_active_qlearning_trainer",
|
|
93
|
+
"get_weights_np",
|
|
94
|
+
"infer_architecture",
|
|
95
|
+
"initialize_population",
|
|
96
|
+
"is_tf_model",
|
|
97
|
+
"is_torch_model",
|
|
98
|
+
"load_genetic_model",
|
|
99
|
+
"load_model",
|
|
100
|
+
"load_qlearning_model",
|
|
101
|
+
"mutate",
|
|
102
|
+
"q_learning_algorithm",
|
|
103
|
+
"save_genetic_model",
|
|
104
|
+
"save_model",
|
|
105
|
+
"save_qlearning_model",
|
|
106
|
+
"select_parents",
|
|
107
|
+
"set_weights_np",
|
|
108
|
+
"wrap_model",
|
|
109
|
+
]
|