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,417 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import random
|
|
4
|
+
from typing import Any, Callable, Sequence
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from ..Environments.Game_Bridge_Env import GameFitnessBridge
|
|
8
|
+
from ..Interfaces.IEnvironment import IFitnessEnvironment
|
|
9
|
+
from ..Interfaces.ITrainer import ITrainer, ITrainingCallback, TrainingResult
|
|
10
|
+
from ..Models.Model_Builder import (
|
|
11
|
+
build_model,
|
|
12
|
+
ensure_built_if_tf,
|
|
13
|
+
get_weights_np,
|
|
14
|
+
set_weights_np,
|
|
15
|
+
)
|
|
16
|
+
from ..Serialization.Model_Serializer import load_genetic_model, save_genetic_model
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Aliases kept for backward compatibility with existing unit tests & game imports
|
|
20
|
+
_get_weights_np = get_weights_np
|
|
21
|
+
_set_weights_np = set_weights_np
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _new_model(
|
|
25
|
+
type_model: str,
|
|
26
|
+
input_size: int,
|
|
27
|
+
output_size: int,
|
|
28
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
29
|
+
) -> Any:
|
|
30
|
+
model = build_model(type_model, input_size, output_size, hidden_sizes=hidden_sizes)
|
|
31
|
+
ensure_built_if_tf(model, input_size)
|
|
32
|
+
return model
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def fitness_function(model: Any, target: Any) -> float:
|
|
36
|
+
"""Evaluate a single model against a fitness environment, callable, or game object."""
|
|
37
|
+
if isinstance(target, IFitnessEnvironment):
|
|
38
|
+
return float(target.evaluate_model(model))
|
|
39
|
+
bridge = GameFitnessBridge(target)
|
|
40
|
+
return bridge.evaluate_model(model)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def initialize_population(
|
|
44
|
+
type_model: str,
|
|
45
|
+
size: int,
|
|
46
|
+
input_size: int,
|
|
47
|
+
output_size: int,
|
|
48
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
49
|
+
) -> list[Any]:
|
|
50
|
+
"""Create an initial population of neural networks with random weights."""
|
|
51
|
+
return [
|
|
52
|
+
_new_model(type_model, input_size, output_size, hidden_sizes=hidden_sizes)
|
|
53
|
+
for _ in range(int(size))
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def evaluate_population(
|
|
58
|
+
population: Sequence[Any],
|
|
59
|
+
target: Any,
|
|
60
|
+
num_trials: int = 3,
|
|
61
|
+
) -> tuple[list[Any], list[float]]:
|
|
62
|
+
"""Evaluate every individual in `population` over `num_trials` episodes and return positive shifted fitness scores."""
|
|
63
|
+
bridge = target if isinstance(target, GameFitnessBridge) else GameFitnessBridge(target)
|
|
64
|
+
evaluated_population: list[Any] = []
|
|
65
|
+
raw_scores: list[float] = []
|
|
66
|
+
|
|
67
|
+
for model in population:
|
|
68
|
+
if bridge.should_stop():
|
|
69
|
+
break
|
|
70
|
+
trial_scores: list[float] = []
|
|
71
|
+
for _ in range(max(1, int(num_trials))):
|
|
72
|
+
trial_scores.append(bridge.evaluate_model(model))
|
|
73
|
+
if bridge.should_stop():
|
|
74
|
+
break
|
|
75
|
+
if not trial_scores:
|
|
76
|
+
break
|
|
77
|
+
evaluated_population.append(model)
|
|
78
|
+
raw_scores.append(sum(trial_scores) / len(trial_scores))
|
|
79
|
+
if bridge.should_stop():
|
|
80
|
+
break
|
|
81
|
+
|
|
82
|
+
if not raw_scores:
|
|
83
|
+
return [], []
|
|
84
|
+
|
|
85
|
+
min_score = abs(min(raw_scores)) if min(raw_scores) < 0 else 0.0
|
|
86
|
+
shifted_scores = [score + min_score + 1.0 for score in raw_scores]
|
|
87
|
+
return evaluated_population, shifted_scores
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def select_parents(
|
|
91
|
+
population: Sequence[Any],
|
|
92
|
+
fitness_scores: Sequence[float],
|
|
93
|
+
num_parents: int,
|
|
94
|
+
) -> list[Any]:
|
|
95
|
+
"""Select parents from the top 50% of the population using fitness-proportionate roulette selection."""
|
|
96
|
+
sorted_pop_fitness = sorted(zip(population, fitness_scores), key=lambda x: x[1], reverse=True)
|
|
97
|
+
top_count = max(2, len(sorted_pop_fitness) // 2)
|
|
98
|
+
top_population = [ind for ind, _ in sorted_pop_fitness[:top_count]]
|
|
99
|
+
top_fitness = [max(1e-6, float(fit)) for _, fit in sorted_pop_fitness[:top_count]]
|
|
100
|
+
return random.choices(top_population, weights=top_fitness, k=int(num_parents))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def crossover(
|
|
104
|
+
parent1: Any,
|
|
105
|
+
parent2: Any,
|
|
106
|
+
type_model: str,
|
|
107
|
+
input_size: int,
|
|
108
|
+
output_size: int,
|
|
109
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
110
|
+
) -> tuple[Any, Any]:
|
|
111
|
+
"""Uniform parameter-tensor crossover producing two offspring models."""
|
|
112
|
+
w1 = get_weights_np(parent1)
|
|
113
|
+
w2 = get_weights_np(parent2)
|
|
114
|
+
child1_w: list[np.ndarray] = []
|
|
115
|
+
child2_w: list[np.ndarray] = []
|
|
116
|
+
for a, b in zip(w1, w2):
|
|
117
|
+
mask = np.random.rand(*a.shape) > 0.5
|
|
118
|
+
child1_w.append(np.where(mask, a, b))
|
|
119
|
+
child2_w.append(np.where(mask, b, a))
|
|
120
|
+
|
|
121
|
+
child1 = _new_model(type_model, input_size, output_size, hidden_sizes)
|
|
122
|
+
child2 = _new_model(type_model, input_size, output_size, hidden_sizes)
|
|
123
|
+
set_weights_np(child1, child1_w)
|
|
124
|
+
set_weights_np(child2, child2_w)
|
|
125
|
+
return child1, child2
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def mutate(
|
|
129
|
+
model: Any,
|
|
130
|
+
mutation_rate: float = 0.01,
|
|
131
|
+
mutation_strength: float = 0.1,
|
|
132
|
+
strong_mutation_rate: float = 0.0,
|
|
133
|
+
strong_mutation_strength: float = 0.5,
|
|
134
|
+
) -> Any:
|
|
135
|
+
"""Apply fine Gaussian mutation and optional strong mutation impulses to model weights."""
|
|
136
|
+
weights = get_weights_np(model)
|
|
137
|
+
mutated: list[np.ndarray] = []
|
|
138
|
+
for w in weights:
|
|
139
|
+
mask = np.random.rand(*w.shape) < float(mutation_rate)
|
|
140
|
+
noise = np.random.randn(*w.shape) * float(mutation_strength)
|
|
141
|
+
updated = w + noise * mask
|
|
142
|
+
if strong_mutation_rate > 0.0:
|
|
143
|
+
strong_mask = np.random.rand(*w.shape) < float(strong_mutation_rate)
|
|
144
|
+
strong_noise = np.clip(
|
|
145
|
+
np.random.randn(*w.shape) * float(strong_mutation_strength),
|
|
146
|
+
-1.0,
|
|
147
|
+
1.0,
|
|
148
|
+
)
|
|
149
|
+
updated = updated + strong_noise * strong_mask
|
|
150
|
+
mutated.append(updated.astype(w.dtype, copy=False))
|
|
151
|
+
set_weights_np(model, mutated)
|
|
152
|
+
return model
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class GeneticTrainer(ITrainer):
|
|
156
|
+
"""Modular Neuroevolution trainer combining multi-backend support, elitism, adaptive mutation, and diversity injection."""
|
|
157
|
+
|
|
158
|
+
def __init__(
|
|
159
|
+
self,
|
|
160
|
+
input_size: int,
|
|
161
|
+
output_size: int,
|
|
162
|
+
type_model: str = "Pytorch",
|
|
163
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
164
|
+
generations: int = 100,
|
|
165
|
+
population_size: int = 20,
|
|
166
|
+
mutation_rate: float = 0.01,
|
|
167
|
+
mutation_strength: float = 0.1,
|
|
168
|
+
strong_mutation_rate: float = 0.0,
|
|
169
|
+
elitism: int = 2,
|
|
170
|
+
num_trials: int = 3,
|
|
171
|
+
adaptive_mutation: bool = True,
|
|
172
|
+
diversity_interval: int = 0,
|
|
173
|
+
diversity_ratio: float = 0.2,
|
|
174
|
+
save_path: str | None = None,
|
|
175
|
+
callbacks: Sequence[ITrainingCallback] | None = None,
|
|
176
|
+
verbose: bool = True,
|
|
177
|
+
) -> None:
|
|
178
|
+
self.input_size = int(input_size)
|
|
179
|
+
self.output_size = int(output_size)
|
|
180
|
+
self.type_model = type_model
|
|
181
|
+
self.hidden_sizes = list(hidden_sizes) if hidden_sizes is not None else [128]
|
|
182
|
+
self.generations = int(generations)
|
|
183
|
+
self.population_size = max(2, int(population_size))
|
|
184
|
+
self.initial_mutation_rate = float(mutation_rate)
|
|
185
|
+
self.mutation_rate = float(mutation_rate)
|
|
186
|
+
self.mutation_strength = float(mutation_strength)
|
|
187
|
+
self.strong_mutation_rate = float(strong_mutation_rate)
|
|
188
|
+
self.elitism = min(max(1, int(elitism)), self.population_size)
|
|
189
|
+
self.num_trials = max(1, int(num_trials))
|
|
190
|
+
self.adaptive_mutation = bool(adaptive_mutation)
|
|
191
|
+
self.diversity_interval = int(diversity_interval)
|
|
192
|
+
self.diversity_ratio = float(diversity_ratio)
|
|
193
|
+
self.save_path = save_path
|
|
194
|
+
self.callbacks = list(callbacks) if callbacks else []
|
|
195
|
+
self.verbose = bool(verbose)
|
|
196
|
+
|
|
197
|
+
self.best_model: Any = None
|
|
198
|
+
self.best_fitness: float = float("-inf")
|
|
199
|
+
self.last_result: TrainingResult | None = None
|
|
200
|
+
|
|
201
|
+
def train_with_result(self, target: Any) -> TrainingResult:
|
|
202
|
+
"""Run neuroevolution on `target` (IFitnessEnvironment, callable `fn(model)->float`, or game instance)."""
|
|
203
|
+
bridge = GameFitnessBridge(target)
|
|
204
|
+
population = initialize_population(
|
|
205
|
+
self.type_model,
|
|
206
|
+
self.population_size,
|
|
207
|
+
self.input_size,
|
|
208
|
+
self.output_size,
|
|
209
|
+
hidden_sizes=self.hidden_sizes,
|
|
210
|
+
)
|
|
211
|
+
self.best_fitness = float("-inf")
|
|
212
|
+
self.best_model = None
|
|
213
|
+
self.mutation_rate = self.initial_mutation_rate
|
|
214
|
+
history: list[float] = []
|
|
215
|
+
stopped_early = False
|
|
216
|
+
completed_gens = 0
|
|
217
|
+
|
|
218
|
+
for cb in self.callbacks:
|
|
219
|
+
cb.on_training_start(self)
|
|
220
|
+
|
|
221
|
+
for generation in range(self.generations):
|
|
222
|
+
if bridge.should_stop():
|
|
223
|
+
stopped_early = True
|
|
224
|
+
break
|
|
225
|
+
bridge.set_generation(generation)
|
|
226
|
+
|
|
227
|
+
evaluated_population, fitness_scores = evaluate_population(
|
|
228
|
+
population,
|
|
229
|
+
bridge,
|
|
230
|
+
num_trials=self.num_trials,
|
|
231
|
+
)
|
|
232
|
+
if not fitness_scores:
|
|
233
|
+
stopped_early = True
|
|
234
|
+
break
|
|
235
|
+
|
|
236
|
+
completed_gens = generation + 1
|
|
237
|
+
current_best = float(max(fitness_scores))
|
|
238
|
+
mean_fitness = float(sum(fitness_scores) / len(fitness_scores))
|
|
239
|
+
history.append(current_best)
|
|
240
|
+
|
|
241
|
+
if current_best > self.best_fitness:
|
|
242
|
+
self.best_fitness = current_best
|
|
243
|
+
best_idx = fitness_scores.index(current_best)
|
|
244
|
+
best_parent = evaluated_population[best_idx]
|
|
245
|
+
self.best_model = _new_model(
|
|
246
|
+
self.type_model,
|
|
247
|
+
self.input_size,
|
|
248
|
+
self.output_size,
|
|
249
|
+
self.hidden_sizes,
|
|
250
|
+
)
|
|
251
|
+
set_weights_np(self.best_model, get_weights_np(best_parent))
|
|
252
|
+
if self.adaptive_mutation:
|
|
253
|
+
self.mutation_rate = self.initial_mutation_rate
|
|
254
|
+
elif self.adaptive_mutation:
|
|
255
|
+
self.mutation_rate = min(self.mutation_rate * 1.35, 0.15)
|
|
256
|
+
|
|
257
|
+
if self.verbose:
|
|
258
|
+
print(f"Generation {generation}: Best Fitness = {current_best:.4f} (Mean = {mean_fitness:.4f})")
|
|
259
|
+
|
|
260
|
+
# Trigger callbacks
|
|
261
|
+
should_halt = False
|
|
262
|
+
for cb in self.callbacks:
|
|
263
|
+
if cb.on_iteration_end(generation, self.best_fitness, mean_fitness, self):
|
|
264
|
+
should_halt = True
|
|
265
|
+
if should_halt or bridge.should_stop():
|
|
266
|
+
stopped_early = should_halt or bridge.should_stop()
|
|
267
|
+
break
|
|
268
|
+
|
|
269
|
+
# Elitism
|
|
270
|
+
sorted_population = [
|
|
271
|
+
model
|
|
272
|
+
for _, model in sorted(
|
|
273
|
+
zip(fitness_scores, evaluated_population),
|
|
274
|
+
key=lambda pair: pair[0],
|
|
275
|
+
reverse=True,
|
|
276
|
+
)
|
|
277
|
+
]
|
|
278
|
+
new_population: list[Any] = []
|
|
279
|
+
for i in range(min(self.elitism, len(sorted_population))):
|
|
280
|
+
elite_copy = _new_model(
|
|
281
|
+
self.type_model,
|
|
282
|
+
self.input_size,
|
|
283
|
+
self.output_size,
|
|
284
|
+
self.hidden_sizes,
|
|
285
|
+
)
|
|
286
|
+
set_weights_np(elite_copy, get_weights_np(sorted_population[i]))
|
|
287
|
+
new_population.append(elite_copy)
|
|
288
|
+
|
|
289
|
+
num_offsprings = self.population_size - len(new_population)
|
|
290
|
+
parents = select_parents(evaluated_population, fitness_scores, max(2, num_offsprings))
|
|
291
|
+
offspring: list[Any] = []
|
|
292
|
+
for i in range(0, len(parents) - 1, 2):
|
|
293
|
+
c1, c2 = crossover(
|
|
294
|
+
parents[i],
|
|
295
|
+
parents[i + 1],
|
|
296
|
+
self.type_model,
|
|
297
|
+
self.input_size,
|
|
298
|
+
self.output_size,
|
|
299
|
+
self.hidden_sizes,
|
|
300
|
+
)
|
|
301
|
+
offspring.append(
|
|
302
|
+
mutate(
|
|
303
|
+
c1,
|
|
304
|
+
self.mutation_rate,
|
|
305
|
+
self.mutation_strength,
|
|
306
|
+
strong_mutation_rate=self.strong_mutation_rate,
|
|
307
|
+
)
|
|
308
|
+
)
|
|
309
|
+
offspring.append(
|
|
310
|
+
mutate(
|
|
311
|
+
c2,
|
|
312
|
+
self.mutation_rate,
|
|
313
|
+
self.mutation_strength,
|
|
314
|
+
strong_mutation_rate=self.strong_mutation_rate,
|
|
315
|
+
)
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
while len(offspring) < num_offsprings and not bridge.should_stop():
|
|
319
|
+
extra_parent = random.choice(population)
|
|
320
|
+
extra_child = _new_model(
|
|
321
|
+
self.type_model,
|
|
322
|
+
self.input_size,
|
|
323
|
+
self.output_size,
|
|
324
|
+
self.hidden_sizes,
|
|
325
|
+
)
|
|
326
|
+
set_weights_np(extra_child, get_weights_np(extra_parent))
|
|
327
|
+
offspring.append(
|
|
328
|
+
mutate(
|
|
329
|
+
extra_child,
|
|
330
|
+
self.mutation_rate,
|
|
331
|
+
self.mutation_strength,
|
|
332
|
+
strong_mutation_rate=self.strong_mutation_rate,
|
|
333
|
+
)
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
if bridge.should_stop():
|
|
337
|
+
stopped_early = True
|
|
338
|
+
break
|
|
339
|
+
|
|
340
|
+
next_population = new_population + offspring[:num_offsprings]
|
|
341
|
+
|
|
342
|
+
# Periodic diversity injection (from Snake_Game)
|
|
343
|
+
if (
|
|
344
|
+
self.diversity_interval > 0
|
|
345
|
+
and generation > 0
|
|
346
|
+
and generation % self.diversity_interval == 0
|
|
347
|
+
):
|
|
348
|
+
num_random = max(1, int(self.population_size * self.diversity_ratio))
|
|
349
|
+
num_keep = max(self.elitism, self.population_size - num_random)
|
|
350
|
+
random_models = initialize_population(
|
|
351
|
+
self.type_model,
|
|
352
|
+
self.population_size - num_keep,
|
|
353
|
+
self.input_size,
|
|
354
|
+
self.output_size,
|
|
355
|
+
hidden_sizes=self.hidden_sizes,
|
|
356
|
+
)
|
|
357
|
+
next_population = next_population[:num_keep] + random_models
|
|
358
|
+
|
|
359
|
+
population = next_population[: self.population_size]
|
|
360
|
+
|
|
361
|
+
if self.best_model is None and population:
|
|
362
|
+
self.best_model = population[0]
|
|
363
|
+
|
|
364
|
+
bridge.assign_best_model(self.best_model)
|
|
365
|
+
|
|
366
|
+
if self.save_path and self.best_model is not None:
|
|
367
|
+
save_genetic_model(self.best_model, optimizer=None, path=self.save_path)
|
|
368
|
+
|
|
369
|
+
result = TrainingResult(
|
|
370
|
+
best_model=self.best_model,
|
|
371
|
+
best_score=self.best_fitness,
|
|
372
|
+
history=history,
|
|
373
|
+
iterations_completed=completed_gens,
|
|
374
|
+
stopped_early=stopped_early,
|
|
375
|
+
)
|
|
376
|
+
self.last_result = result
|
|
377
|
+
for cb in self.callbacks:
|
|
378
|
+
cb.on_training_end(result, self)
|
|
379
|
+
return result
|
|
380
|
+
|
|
381
|
+
def train(self, target: Any = None) -> Any:
|
|
382
|
+
return self.train_with_result(target).best_model
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def genetic_algorithm(
|
|
386
|
+
game: Any,
|
|
387
|
+
type_model: str = "Pytorch",
|
|
388
|
+
input_size: int = 6,
|
|
389
|
+
output_size: int = 2,
|
|
390
|
+
generations: int = 100,
|
|
391
|
+
population_size: int = 20,
|
|
392
|
+
mutation_rate: float = 0.01,
|
|
393
|
+
mutation_strength: float = 0.1,
|
|
394
|
+
elitism: int = 2,
|
|
395
|
+
num_trials: int = 3,
|
|
396
|
+
hidden_sizes: Sequence[int] | None = None,
|
|
397
|
+
adaptive_mutation: bool = False,
|
|
398
|
+
diversity_interval: int = 0,
|
|
399
|
+
verbose: bool = True,
|
|
400
|
+
) -> Any:
|
|
401
|
+
"""Functional neuroevolution entry point preserving 100% compatibility with Pong_Game / Snake_Game."""
|
|
402
|
+
trainer = GeneticTrainer(
|
|
403
|
+
input_size=input_size,
|
|
404
|
+
output_size=output_size,
|
|
405
|
+
type_model=type_model,
|
|
406
|
+
hidden_sizes=hidden_sizes,
|
|
407
|
+
generations=generations,
|
|
408
|
+
population_size=population_size,
|
|
409
|
+
mutation_rate=mutation_rate,
|
|
410
|
+
mutation_strength=mutation_strength,
|
|
411
|
+
elitism=elitism,
|
|
412
|
+
num_trials=num_trials,
|
|
413
|
+
adaptive_mutation=adaptive_mutation,
|
|
414
|
+
diversity_interval=diversity_interval,
|
|
415
|
+
verbose=verbose,
|
|
416
|
+
)
|
|
417
|
+
return trainer.train(game)
|