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,156 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Callable
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from .Adapters import MockAdapter, PyTorchAdapter, TensorFlowAdapter, wrap_model
|
|
7
|
+
from .Interfaces.IAIModel import IAIModel
|
|
8
|
+
from .Serialization.Model_Serializer import load_model, save_model
|
|
9
|
+
from .Trainers.Q_Learning import QLearningTrainer, get_active_qlearning_trainer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AIController:
|
|
13
|
+
"""Reusable runtime AI controller managing inference adapters and episodic Q-Learning state transitions."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
state_provider: Callable[[], np.ndarray] | None = None,
|
|
18
|
+
action_dispatcher: Callable[[int | np.ndarray], None] | None = None,
|
|
19
|
+
default_backend: str = "Pytorch",
|
|
20
|
+
output_size: int = 2,
|
|
21
|
+
) -> None:
|
|
22
|
+
self.state_provider = state_provider
|
|
23
|
+
self.action_dispatcher = action_dispatcher
|
|
24
|
+
self.default_backend = default_backend
|
|
25
|
+
self.output_size = int(output_size)
|
|
26
|
+
|
|
27
|
+
self.model_adapter: IAIModel | None = None
|
|
28
|
+
self.prev_state: np.ndarray | None = None
|
|
29
|
+
self.prev_action: int | None = None
|
|
30
|
+
self.prev_reward: float = 0.0
|
|
31
|
+
|
|
32
|
+
def set_model(self, model_adapter: IAIModel) -> None:
|
|
33
|
+
self.model_adapter = model_adapter
|
|
34
|
+
|
|
35
|
+
def clear_model(self) -> None:
|
|
36
|
+
self.model_adapter = None
|
|
37
|
+
|
|
38
|
+
def set_runtime_model(self, model: Any, type_model: str | None = None) -> IAIModel | None:
|
|
39
|
+
"""Wrap and bind a raw PyTorch/TensorFlow model or IAIModel adapter only when it changes."""
|
|
40
|
+
if model is None:
|
|
41
|
+
return None
|
|
42
|
+
if isinstance(model, IAIModel):
|
|
43
|
+
self.model_adapter = model
|
|
44
|
+
return self.model_adapter
|
|
45
|
+
|
|
46
|
+
current_internal = self.model_adapter.get_internal_model() if self.model_adapter is not None else None
|
|
47
|
+
if current_internal is model:
|
|
48
|
+
return self.model_adapter
|
|
49
|
+
|
|
50
|
+
backend = (type_model or self.default_backend).strip().capitalize()
|
|
51
|
+
if backend in ("Pytorch", "Torch"):
|
|
52
|
+
self.model_adapter = PyTorchAdapter(model)
|
|
53
|
+
elif backend in ("Tensorflow", "Tf", "Keras"):
|
|
54
|
+
self.model_adapter = TensorFlowAdapter(model)
|
|
55
|
+
else:
|
|
56
|
+
self.model_adapter = wrap_model(model, output_size=self.output_size)
|
|
57
|
+
return self.model_adapter
|
|
58
|
+
|
|
59
|
+
def get_state(self) -> np.ndarray:
|
|
60
|
+
if self.state_provider is not None:
|
|
61
|
+
return np.asarray(self.state_provider(), dtype=np.float32)
|
|
62
|
+
if self.prev_state is not None:
|
|
63
|
+
return self.prev_state.copy()
|
|
64
|
+
raise RuntimeError("No state_provider configured and no previous state available.")
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def softmax(x: np.ndarray | list[float]) -> np.ndarray:
|
|
68
|
+
arr = np.asarray(x, dtype=np.float32).flatten()
|
|
69
|
+
exp_x = np.exp(arr - np.max(arr))
|
|
70
|
+
total = np.sum(exp_x)
|
|
71
|
+
return exp_x / total if total != 0.0 else np.full_like(arr, 1.0 / max(1, len(arr)))
|
|
72
|
+
|
|
73
|
+
def predict(self, state: np.ndarray | list[float] | None = None) -> np.ndarray | None:
|
|
74
|
+
if self.model_adapter is None:
|
|
75
|
+
return None
|
|
76
|
+
obs = np.asarray(state, dtype=np.float32) if state is not None else self.get_state()
|
|
77
|
+
return self.model_adapter.predict(obs)
|
|
78
|
+
|
|
79
|
+
def select_action(self, state: np.ndarray | list[float] | None = None, deterministic: bool = True) -> int | None:
|
|
80
|
+
if self.model_adapter is None:
|
|
81
|
+
return None
|
|
82
|
+
obs = np.asarray(state, dtype=np.float32) if state is not None else self.get_state()
|
|
83
|
+
action = self.model_adapter.predict_action(obs, deterministic=deterministic)
|
|
84
|
+
if self.action_dispatcher is not None:
|
|
85
|
+
self.action_dispatcher(action)
|
|
86
|
+
return action
|
|
87
|
+
|
|
88
|
+
def step_qlearning(
|
|
89
|
+
self,
|
|
90
|
+
current_state: np.ndarray | list[float],
|
|
91
|
+
current_reward: float,
|
|
92
|
+
done: bool = False,
|
|
93
|
+
trainer: QLearningTrainer | None = None,
|
|
94
|
+
use_reward_delta: bool = True,
|
|
95
|
+
) -> int | None:
|
|
96
|
+
"""Process one Q-Learning frame: record transition from previous frame, optimize, and return next action."""
|
|
97
|
+
active_trainer = trainer or get_active_qlearning_trainer()
|
|
98
|
+
if active_trainer is None:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
curr_state_arr = np.asarray(current_state, dtype=np.float32)
|
|
102
|
+
if self.prev_state is not None and self.prev_action is not None:
|
|
103
|
+
step_reward = (float(current_reward) - self.prev_reward) if use_reward_delta else float(current_reward)
|
|
104
|
+
active_trainer.store_experience(
|
|
105
|
+
self.prev_state,
|
|
106
|
+
self.prev_action,
|
|
107
|
+
step_reward,
|
|
108
|
+
curr_state_arr,
|
|
109
|
+
bool(done),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
action = active_trainer.get_action(curr_state_arr)
|
|
113
|
+
if self.action_dispatcher is not None:
|
|
114
|
+
self.action_dispatcher(action)
|
|
115
|
+
|
|
116
|
+
self.prev_state = curr_state_arr.copy()
|
|
117
|
+
self.prev_action = action
|
|
118
|
+
self.prev_reward = float(current_reward)
|
|
119
|
+
if done:
|
|
120
|
+
self.reset_qlearning_state()
|
|
121
|
+
return action
|
|
122
|
+
|
|
123
|
+
def reset_qlearning_state(self) -> None:
|
|
124
|
+
self.prev_state = None
|
|
125
|
+
self.prev_action = None
|
|
126
|
+
self.prev_reward = 0.0
|
|
127
|
+
|
|
128
|
+
def manual_save_model(self, path: str) -> None:
|
|
129
|
+
if self.model_adapter is not None:
|
|
130
|
+
internal = self.model_adapter.get_internal_model()
|
|
131
|
+
if internal is not None:
|
|
132
|
+
save_model(internal, path)
|
|
133
|
+
else:
|
|
134
|
+
self.model_adapter.save(path)
|
|
135
|
+
|
|
136
|
+
def manual_load_model(
|
|
137
|
+
self,
|
|
138
|
+
path: str,
|
|
139
|
+
input_size: int | None = None,
|
|
140
|
+
output_size: int | None = None,
|
|
141
|
+
hidden_sizes: list[int] | None = None,
|
|
142
|
+
) -> IAIModel | None:
|
|
143
|
+
loaded = load_model(
|
|
144
|
+
path=path,
|
|
145
|
+
model_or_type_model=self.default_backend,
|
|
146
|
+
input_size=input_size,
|
|
147
|
+
output_size=output_size or self.output_size,
|
|
148
|
+
hidden_sizes=hidden_sizes,
|
|
149
|
+
)
|
|
150
|
+
if loaded is not None:
|
|
151
|
+
return self.set_runtime_model(loaded, type_model=self.default_backend)
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# Alias for backward compatibility with Pong_Game / Snake_Game
|
|
156
|
+
AIHandler = AIController
|
pyforgeai/AI_Factory.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from .Adapters import MockAdapter, PyTorchAdapter, TensorFlowAdapter, wrap_model
|
|
6
|
+
from .AI_Controller import AIController
|
|
7
|
+
from .Environments import CallbackRLEnvironment, GameFitnessBridge, TargetSeekEnvironment
|
|
8
|
+
from .Interfaces import IAIModel, ITrainer
|
|
9
|
+
from .Models import build_model
|
|
10
|
+
from .Serialization import AILoader, load_model, save_model
|
|
11
|
+
from .Trainers import (
|
|
12
|
+
CheckpointCallback,
|
|
13
|
+
DQNAgent,
|
|
14
|
+
EarlyStoppingCallback,
|
|
15
|
+
GeneticTrainer,
|
|
16
|
+
HistoryCallback,
|
|
17
|
+
QLearningTrainer,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AIFactory:
|
|
22
|
+
"""Centralized factory for creating models, adapters, trainers, and controllers (mirrors PyForgeUI's ElementsFactory)."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, defaults: dict[str, Any] | None = None) -> None:
|
|
25
|
+
self.defaults = dict(defaults) if defaults else {}
|
|
26
|
+
|
|
27
|
+
def _merge(self, config: dict[str, Any] | None) -> dict[str, Any]:
|
|
28
|
+
merged = dict(self.defaults)
|
|
29
|
+
if config:
|
|
30
|
+
merged.update(config)
|
|
31
|
+
return merged
|
|
32
|
+
|
|
33
|
+
def create_Model(self, config: dict[str, Any] | None = None, **kwargs: Any) -> Any:
|
|
34
|
+
cfg = self._merge(config)
|
|
35
|
+
cfg.update(kwargs)
|
|
36
|
+
return build_model(
|
|
37
|
+
type_model=cfg.get("type_model", "Pytorch"),
|
|
38
|
+
input_size=int(cfg.get("input_size", 6)),
|
|
39
|
+
output_size=int(cfg.get("output_size", 2)),
|
|
40
|
+
hidden_sizes=cfg.get("hidden_sizes", [128]),
|
|
41
|
+
activation=cfg.get("activation", "relu"),
|
|
42
|
+
record_activations=bool(cfg.get("record_activations", True)),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def create_Adapter(self, model: Any = None, config: dict[str, Any] | None = None, **kwargs: Any) -> IAIModel:
|
|
46
|
+
cfg = self._merge(config)
|
|
47
|
+
cfg.update(kwargs)
|
|
48
|
+
if model is None and "model" in cfg:
|
|
49
|
+
model = cfg["model"]
|
|
50
|
+
if model is None:
|
|
51
|
+
return MockAdapter(
|
|
52
|
+
output_size=int(cfg.get("output_size", 2)),
|
|
53
|
+
fixed_output=cfg.get("fixed_output"),
|
|
54
|
+
)
|
|
55
|
+
return wrap_model(model, output_size=int(cfg.get("output_size", 2)))
|
|
56
|
+
|
|
57
|
+
def create_GeneticTrainer(self, config: dict[str, Any] | None = None, **kwargs: Any) -> GeneticTrainer:
|
|
58
|
+
cfg = self._merge(config)
|
|
59
|
+
cfg.update(kwargs)
|
|
60
|
+
return GeneticTrainer(
|
|
61
|
+
input_size=int(cfg.get("input_size", 6)),
|
|
62
|
+
output_size=int(cfg.get("output_size", 2)),
|
|
63
|
+
type_model=cfg.get("type_model", "Pytorch"),
|
|
64
|
+
hidden_sizes=cfg.get("hidden_sizes", [128]),
|
|
65
|
+
generations=int(cfg.get("generations", cfg.get("generation_value", 100))),
|
|
66
|
+
population_size=int(cfg.get("population_size", cfg.get("population_value", 20))),
|
|
67
|
+
mutation_rate=float(cfg.get("mutation_rate", 0.01)),
|
|
68
|
+
mutation_strength=float(cfg.get("mutation_strength", 0.1)),
|
|
69
|
+
strong_mutation_rate=float(cfg.get("strong_mutation_rate", 0.0)),
|
|
70
|
+
elitism=int(cfg.get("elitism", 2)),
|
|
71
|
+
num_trials=int(cfg.get("num_trials", cfg.get("try_for_ai", 3))),
|
|
72
|
+
adaptive_mutation=bool(cfg.get("adaptive_mutation", True)),
|
|
73
|
+
diversity_interval=int(cfg.get("diversity_interval", 0)),
|
|
74
|
+
diversity_ratio=float(cfg.get("diversity_ratio", 0.2)),
|
|
75
|
+
save_path=cfg.get("save_path"),
|
|
76
|
+
callbacks=cfg.get("callbacks"),
|
|
77
|
+
verbose=bool(cfg.get("verbose", True)),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def create_QLearningTrainer(self, config: dict[str, Any] | None = None, **kwargs: Any) -> QLearningTrainer:
|
|
81
|
+
cfg = self._merge(config)
|
|
82
|
+
cfg.update(kwargs)
|
|
83
|
+
return QLearningTrainer(
|
|
84
|
+
game=cfg.get("game"),
|
|
85
|
+
type_model=cfg.get("type_model", "Pytorch"),
|
|
86
|
+
input_size=int(cfg.get("input_size", 6)),
|
|
87
|
+
output_size=int(cfg.get("output_size", 2)),
|
|
88
|
+
episodes=int(cfg.get("episodes", 500)),
|
|
89
|
+
lr=float(cfg.get("lr", cfg.get("learning_rate", 1e-3))),
|
|
90
|
+
gamma=float(cfg.get("gamma", 0.99)),
|
|
91
|
+
epsilon_start=float(cfg.get("epsilon_start", 1.0)),
|
|
92
|
+
epsilon_end=float(cfg.get("epsilon_end", 0.01)),
|
|
93
|
+
epsilon_decay=float(cfg.get("epsilon_decay", 0.995)),
|
|
94
|
+
memory_size=int(cfg.get("memory_size", 10000)),
|
|
95
|
+
batch_size=int(cfg.get("batch_size", 32)),
|
|
96
|
+
target_update=int(cfg.get("target_update", 100)),
|
|
97
|
+
hidden_sizes=cfg.get("hidden_sizes", [128]),
|
|
98
|
+
double_dqn=bool(cfg.get("double_dqn", True)),
|
|
99
|
+
save_path=cfg.get("save_path"),
|
|
100
|
+
callbacks=cfg.get("callbacks"),
|
|
101
|
+
verbose=bool(cfg.get("verbose", True)),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def create_DQNAgent(self, config: dict[str, Any] | None = None, **kwargs: Any) -> DQNAgent:
|
|
105
|
+
cfg = self._merge(config)
|
|
106
|
+
cfg.update(kwargs)
|
|
107
|
+
return DQNAgent(
|
|
108
|
+
type_model=cfg.get("type_model", "Pytorch"),
|
|
109
|
+
state_size=int(cfg.get("state_size", cfg.get("input_size", 6))),
|
|
110
|
+
action_size=int(cfg.get("action_size", cfg.get("output_size", 2))),
|
|
111
|
+
lr=float(cfg.get("lr", cfg.get("learning_rate", 1e-3))),
|
|
112
|
+
gamma=float(cfg.get("gamma", 0.99)),
|
|
113
|
+
epsilon_start=float(cfg.get("epsilon_start", 1.0)),
|
|
114
|
+
epsilon_end=float(cfg.get("epsilon_end", 0.01)),
|
|
115
|
+
epsilon_decay=float(cfg.get("epsilon_decay", 0.995)),
|
|
116
|
+
memory_size=int(cfg.get("memory_size", 10000)),
|
|
117
|
+
batch_size=int(cfg.get("batch_size", 32)),
|
|
118
|
+
target_update=int(cfg.get("target_update", 100)),
|
|
119
|
+
hidden_sizes=cfg.get("hidden_sizes", [128]),
|
|
120
|
+
double_dqn=bool(cfg.get("double_dqn", True)),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
def create_Controller(self, config: dict[str, Any] | None = None, **kwargs: Any) -> AIController:
|
|
124
|
+
cfg = self._merge(config)
|
|
125
|
+
cfg.update(kwargs)
|
|
126
|
+
return AIController(
|
|
127
|
+
state_provider=cfg.get("state_provider"),
|
|
128
|
+
action_dispatcher=cfg.get("action_dispatcher"),
|
|
129
|
+
default_backend=cfg.get("type_model", "Pytorch"),
|
|
130
|
+
output_size=int(cfg.get("output_size", 2)),
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def create_Trainer_from_game_config(
|
|
134
|
+
self,
|
|
135
|
+
config_ai: dict[str, Any],
|
|
136
|
+
input_size: int,
|
|
137
|
+
output_size: int,
|
|
138
|
+
save_path: str | None = None,
|
|
139
|
+
verbose: bool = True,
|
|
140
|
+
) -> ITrainer:
|
|
141
|
+
"""Build a GeneticTrainer or QLearningTrainer directly from a Pong/Snake `config_AI` dictionary."""
|
|
142
|
+
nn_cfg = config_ai.get("nn", {"hidden_layers": 2, "neurons_per_layer": 6})
|
|
143
|
+
arch = [int(nn_cfg.get("neurons_per_layer", 6))] * int(nn_cfg.get("hidden_layers", 2))
|
|
144
|
+
type_model = next((k for k, v in config_ai.get("type_model", {"Pytorch": True}).items() if v), "Pytorch")
|
|
145
|
+
training_type = next((k for k, v in config_ai.get("type_training", {"Genetic": True}).items() if v), "Genetic")
|
|
146
|
+
effective_save = save_path if config_ai.get("model_save", False) else None
|
|
147
|
+
|
|
148
|
+
if training_type.lower().startswith("genetic"):
|
|
149
|
+
gen_cfg = config_ai.get("genetic", {})
|
|
150
|
+
return self.create_GeneticTrainer(
|
|
151
|
+
input_size=input_size,
|
|
152
|
+
output_size=output_size,
|
|
153
|
+
type_model=type_model,
|
|
154
|
+
hidden_sizes=arch,
|
|
155
|
+
generations=gen_cfg.get("generation_value", 100),
|
|
156
|
+
population_size=gen_cfg.get("population_value", 20),
|
|
157
|
+
num_trials=gen_cfg.get("try_for_ai", 3),
|
|
158
|
+
save_path=effective_save,
|
|
159
|
+
verbose=verbose,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
q_cfg = config_ai.get("q_learning", {})
|
|
163
|
+
return self.create_QLearningTrainer(
|
|
164
|
+
input_size=input_size,
|
|
165
|
+
output_size=output_size,
|
|
166
|
+
type_model=type_model,
|
|
167
|
+
hidden_sizes=arch,
|
|
168
|
+
episodes=q_cfg.get("episodes", 500),
|
|
169
|
+
lr=q_cfg.get("learning_rate", 1e-3),
|
|
170
|
+
gamma=q_cfg.get("gamma", 0.99),
|
|
171
|
+
epsilon_start=q_cfg.get("epsilon_start", 1.0),
|
|
172
|
+
epsilon_end=q_cfg.get("epsilon_end", 0.01),
|
|
173
|
+
epsilon_decay=q_cfg.get("epsilon_decay", 0.995),
|
|
174
|
+
save_path=effective_save,
|
|
175
|
+
verbose=verbose,
|
|
176
|
+
)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from ..Interfaces.IAIModel import IAIModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MockAdapter(IAIModel):
|
|
9
|
+
"""Lightweight mock model adapter for testing game loops and UI without neural network overhead."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, output_size: int = 2, fixed_output: np.ndarray | list[float] | None = None) -> None:
|
|
12
|
+
self.output_size = int(output_size)
|
|
13
|
+
self.fixed_output = (
|
|
14
|
+
np.asarray(fixed_output, dtype=np.float32).flatten() if fixed_output is not None else None
|
|
15
|
+
)
|
|
16
|
+
self.saved_paths: list[str] = []
|
|
17
|
+
self.loaded_paths: list[str] = []
|
|
18
|
+
|
|
19
|
+
def predict(self, state: np.ndarray | list[float]) -> np.ndarray:
|
|
20
|
+
if self.fixed_output is not None:
|
|
21
|
+
return self.fixed_output.copy()
|
|
22
|
+
return np.random.uniform(-1.0, 1.0, self.output_size).astype(np.float32)
|
|
23
|
+
|
|
24
|
+
def save(self, path: str) -> None:
|
|
25
|
+
self.saved_paths.append(path)
|
|
26
|
+
|
|
27
|
+
def load(self, path: str) -> None:
|
|
28
|
+
self.loaded_paths.append(path)
|
|
29
|
+
|
|
30
|
+
def get_internal_model(self) -> None:
|
|
31
|
+
return None
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
from ..Interfaces.IAIModel import IAIModel
|
|
7
|
+
from ..Models.Model_Builder import get_weights_np, set_weights_np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PyTorchAdapter(IAIModel):
|
|
11
|
+
"""Adapter wrapping a PyTorch nn.Module under the unified IAIModel interface."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, model: torch.nn.Module, device: str | torch.device | None = None) -> None:
|
|
14
|
+
self.model = model
|
|
15
|
+
if device is None:
|
|
16
|
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
17
|
+
else:
|
|
18
|
+
self.device = torch.device(device)
|
|
19
|
+
self.model.to(self.device)
|
|
20
|
+
|
|
21
|
+
def predict(self, state: np.ndarray | list[float]) -> np.ndarray:
|
|
22
|
+
self.model.eval()
|
|
23
|
+
with torch.no_grad():
|
|
24
|
+
state_arr = np.asarray(state, dtype=np.float32)
|
|
25
|
+
state_tensor = torch.as_tensor(state_arr, dtype=torch.float32, device=self.device)
|
|
26
|
+
output = self.model(state_tensor)
|
|
27
|
+
return output.detach().cpu().numpy().flatten()
|
|
28
|
+
|
|
29
|
+
def save(self, path: str) -> None:
|
|
30
|
+
torch.save(self.model.state_dict(), path)
|
|
31
|
+
|
|
32
|
+
def load(self, path: str) -> None:
|
|
33
|
+
checkpoint = torch.load(path, map_location=self.device)
|
|
34
|
+
state_dict = checkpoint.get("model_state_dict", checkpoint) if isinstance(checkpoint, dict) else checkpoint
|
|
35
|
+
self.model.load_state_dict(state_dict)
|
|
36
|
+
|
|
37
|
+
def get_internal_model(self) -> torch.nn.Module:
|
|
38
|
+
return self.model
|
|
39
|
+
|
|
40
|
+
def get_weights(self) -> list[np.ndarray]:
|
|
41
|
+
return get_weights_np(self.model)
|
|
42
|
+
|
|
43
|
+
def set_weights(self, weights: list[np.ndarray]) -> None:
|
|
44
|
+
set_weights_np(self.model, weights)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from ..Interfaces.IAIModel import IAIModel
|
|
7
|
+
from ..Models.Model_Builder import get_weights_np, load_tensorflow, set_weights_np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TensorFlowAdapter(IAIModel):
|
|
11
|
+
"""Adapter wrapping a TensorFlow/Keras Model under the unified IAIModel interface."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, model: Any) -> None:
|
|
14
|
+
self.tf = load_tensorflow(optional=False)
|
|
15
|
+
self.model = model
|
|
16
|
+
|
|
17
|
+
def predict(self, state: np.ndarray | list[float]) -> np.ndarray:
|
|
18
|
+
x = self.tf.convert_to_tensor(np.asarray(state, dtype=np.float32), dtype=self.tf.float32)
|
|
19
|
+
if len(x.shape) == 1:
|
|
20
|
+
x = self.tf.expand_dims(x, axis=0)
|
|
21
|
+
out = self.model(x, training=False)
|
|
22
|
+
return out.numpy().flatten()
|
|
23
|
+
|
|
24
|
+
def save(self, path: str) -> None:
|
|
25
|
+
if path.endswith(".npz"):
|
|
26
|
+
weights = get_weights_np(self.model)
|
|
27
|
+
np.savez(path, *weights)
|
|
28
|
+
elif hasattr(self.model, "save"):
|
|
29
|
+
self.model.save(path)
|
|
30
|
+
|
|
31
|
+
def load(self, path: str) -> None:
|
|
32
|
+
if path.endswith(".npz"):
|
|
33
|
+
data = np.load(path)
|
|
34
|
+
keys = sorted(data.files, key=lambda k: int(k.replace("arr_", "")))
|
|
35
|
+
set_weights_np(self.model, [data[k] for k in keys])
|
|
36
|
+
else:
|
|
37
|
+
self.model = self.tf.keras.models.load_model(path)
|
|
38
|
+
|
|
39
|
+
def get_internal_model(self) -> Any:
|
|
40
|
+
return self.model
|
|
41
|
+
|
|
42
|
+
def get_weights(self) -> list[np.ndarray]:
|
|
43
|
+
return get_weights_np(self.model)
|
|
44
|
+
|
|
45
|
+
def set_weights(self, weights: list[np.ndarray]) -> None:
|
|
46
|
+
set_weights_np(self.model, weights)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ..Interfaces.IAIModel import IAIModel
|
|
6
|
+
from ..Models.Model_Builder import is_tf_model, is_torch_model
|
|
7
|
+
from .Mock_Adapter import MockAdapter
|
|
8
|
+
from .PyTorch_Adapter import PyTorchAdapter
|
|
9
|
+
from .TensorFlow_Adapter import TensorFlowAdapter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def wrap_model(model: Any, output_size: int = 2) -> IAIModel:
|
|
13
|
+
"""Automatically wrap a raw PyTorch or TensorFlow model into its corresponding IAIModel adapter."""
|
|
14
|
+
if isinstance(model, IAIModel):
|
|
15
|
+
return model
|
|
16
|
+
if is_torch_model(model):
|
|
17
|
+
return PyTorchAdapter(model)
|
|
18
|
+
if is_tf_model(model):
|
|
19
|
+
return TensorFlowAdapter(model)
|
|
20
|
+
return MockAdapter(output_size=output_size)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"MockAdapter",
|
|
25
|
+
"PyTorchAdapter",
|
|
26
|
+
"TensorFlowAdapter",
|
|
27
|
+
"wrap_model",
|
|
28
|
+
]
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from typing import Any, Callable
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from ..Interfaces.IEnvironment import IEnvironment, IFitnessEnvironment
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _is_plain_callable(obj: Any) -> bool:
|
|
11
|
+
"""Return True if `obj` is a function, lambda, or bound method rather than a game object or MagicMock."""
|
|
12
|
+
return inspect.isfunction(obj) or inspect.ismethod(obj) or inspect.isbuiltin(obj)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GameFitnessBridge(IFitnessEnvironment):
|
|
16
|
+
"""Bridges an `IFitnessEnvironment`, a pure function `fn(model) -> float`, or a Pygame `game` instance."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
target: Any,
|
|
21
|
+
stop_fn: Callable[[], bool] | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.target = target
|
|
24
|
+
self._stop_fn = stop_fn
|
|
25
|
+
|
|
26
|
+
def evaluate_model(self, model: Any) -> float:
|
|
27
|
+
if isinstance(self.target, IFitnessEnvironment):
|
|
28
|
+
return float(self.target.evaluate_model(model))
|
|
29
|
+
|
|
30
|
+
if _is_plain_callable(self.target):
|
|
31
|
+
return float(self.target(model))
|
|
32
|
+
|
|
33
|
+
game = self.target
|
|
34
|
+
# Support Pong_Game style (`game.model` + `game.ai_handler.set_runtime_model` + `game.run_with_model()`)
|
|
35
|
+
if hasattr(game, "run_with_model"):
|
|
36
|
+
game.model = model
|
|
37
|
+
if hasattr(game, "ai_handler") and hasattr(game.ai_handler, "set_runtime_model"):
|
|
38
|
+
game.ai_handler.set_runtime_model(model)
|
|
39
|
+
return float(game.run_with_model())
|
|
40
|
+
|
|
41
|
+
# Support Snake_Game / Flappy_Ghost style (`game.models` + `game.run_with_models()`)
|
|
42
|
+
if hasattr(game, "run_with_models"):
|
|
43
|
+
game.models = model
|
|
44
|
+
return float(game.run_with_models())
|
|
45
|
+
|
|
46
|
+
if callable(self.target):
|
|
47
|
+
return float(self.target(model))
|
|
48
|
+
|
|
49
|
+
raise TypeError(
|
|
50
|
+
"Target passed to GameFitnessBridge must be a callable `fn(model) -> float`, "
|
|
51
|
+
"an IFitnessEnvironment, or a game instance defining `run_with_model()`."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def should_stop(self) -> bool:
|
|
55
|
+
if self._stop_fn is not None:
|
|
56
|
+
return bool(self._stop_fn())
|
|
57
|
+
if isinstance(self.target, IFitnessEnvironment):
|
|
58
|
+
return bool(self.target.should_stop())
|
|
59
|
+
if _is_plain_callable(self.target):
|
|
60
|
+
return False
|
|
61
|
+
exit_attr = getattr(self.target, "exit", False)
|
|
62
|
+
return bool(exit_attr) if isinstance(exit_attr, bool) else False
|
|
63
|
+
|
|
64
|
+
def set_generation(self, generation: int) -> None:
|
|
65
|
+
if not isinstance(self.target, IFitnessEnvironment) and not _is_plain_callable(self.target):
|
|
66
|
+
try:
|
|
67
|
+
self.target.generation = generation
|
|
68
|
+
except Exception:
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
def assign_best_model(self, model: Any) -> None:
|
|
72
|
+
if not isinstance(self.target, IFitnessEnvironment) and not _is_plain_callable(self.target):
|
|
73
|
+
try:
|
|
74
|
+
self.target.model = model
|
|
75
|
+
except Exception:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class CallbackRLEnvironment(IEnvironment):
|
|
80
|
+
"""Creates a step-by-step RL environment from user-supplied callables (`reset_fn`, `step_fn`)."""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
state_size: int,
|
|
85
|
+
action_size: int,
|
|
86
|
+
reset_fn: Callable[[], np.ndarray],
|
|
87
|
+
step_fn: Callable[[int], tuple[np.ndarray, float, bool] | tuple[np.ndarray, float, bool, dict[str, Any]]],
|
|
88
|
+
stop_fn: Callable[[], bool] | None = None,
|
|
89
|
+
) -> None:
|
|
90
|
+
self._state_size = int(state_size)
|
|
91
|
+
self._action_size = int(action_size)
|
|
92
|
+
self._reset_fn = reset_fn
|
|
93
|
+
self._step_fn = step_fn
|
|
94
|
+
self._stop_fn = stop_fn
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def state_size(self) -> int:
|
|
98
|
+
return self._state_size
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def action_size(self) -> int:
|
|
102
|
+
return self._action_size
|
|
103
|
+
|
|
104
|
+
def reset(self) -> np.ndarray:
|
|
105
|
+
return np.asarray(self._reset_fn(), dtype=np.float32)
|
|
106
|
+
|
|
107
|
+
def step(self, action: int) -> tuple[np.ndarray, float, bool, dict[str, Any]]:
|
|
108
|
+
result = self._step_fn(int(action))
|
|
109
|
+
if len(result) == 3:
|
|
110
|
+
next_state, reward, done = result
|
|
111
|
+
info: dict[str, Any] = {}
|
|
112
|
+
else:
|
|
113
|
+
next_state, reward, done, info = result
|
|
114
|
+
return np.asarray(next_state, dtype=np.float32), float(reward), bool(done), info
|
|
115
|
+
|
|
116
|
+
def should_stop(self) -> bool:
|
|
117
|
+
return bool(self._stop_fn()) if self._stop_fn is not None else False
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from ..Adapters import wrap_model
|
|
7
|
+
from ..Interfaces.IEnvironment import IEnvironment, IFitnessEnvironment
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TargetSeekEnvironment(IEnvironment, IFitnessEnvironment):
|
|
11
|
+
"""Built-in 1D paddle/ball intercept simulation environment for testing and benchmarking Genetic & DQN trainers."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, max_steps: int = 80, seed: int | None = None) -> None:
|
|
14
|
+
self.max_steps = int(max_steps)
|
|
15
|
+
self.rng = np.random.default_rng(seed)
|
|
16
|
+
self.agent_y = 0.5
|
|
17
|
+
self.target_y = 0.5
|
|
18
|
+
self.target_vy = 0.02
|
|
19
|
+
self.steps = 0
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def state_size(self) -> int:
|
|
23
|
+
return 4
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def action_size(self) -> int:
|
|
27
|
+
return 3 # 0: UP, 1: STAY, 2: DOWN
|
|
28
|
+
|
|
29
|
+
def _get_obs(self) -> np.ndarray:
|
|
30
|
+
dy = self.target_y - self.agent_y
|
|
31
|
+
return np.array([self.agent_y, self.target_y, dy, self.target_vy], dtype=np.float32)
|
|
32
|
+
|
|
33
|
+
def reset(self) -> np.ndarray:
|
|
34
|
+
self.agent_y = float(self.rng.uniform(0.1, 0.9))
|
|
35
|
+
self.target_y = float(self.rng.uniform(0.1, 0.9))
|
|
36
|
+
self.target_vy = float(self.rng.choice([-0.03, 0.03]))
|
|
37
|
+
self.steps = 0
|
|
38
|
+
return self._get_obs()
|
|
39
|
+
|
|
40
|
+
def step(self, action: int) -> tuple[np.ndarray, float, bool, dict[str, Any]]:
|
|
41
|
+
if action == 0:
|
|
42
|
+
self.agent_y = max(0.0, self.agent_y - 0.05)
|
|
43
|
+
elif action == 2:
|
|
44
|
+
self.agent_y = min(1.0, self.agent_y + 0.05)
|
|
45
|
+
|
|
46
|
+
self.target_y += self.target_vy
|
|
47
|
+
if self.target_y <= 0.0 or self.target_y >= 1.0:
|
|
48
|
+
self.target_vy *= -1.0
|
|
49
|
+
self.target_y = float(np.clip(self.target_y, 0.0, 1.0))
|
|
50
|
+
|
|
51
|
+
self.steps += 1
|
|
52
|
+
distance = abs(self.target_y - self.agent_y)
|
|
53
|
+
reward = 1.0 - (distance * 2.0)
|
|
54
|
+
if distance < 0.08:
|
|
55
|
+
reward += 1.0
|
|
56
|
+
|
|
57
|
+
done = self.steps >= self.max_steps
|
|
58
|
+
return self._get_obs(), float(reward), done, {"distance": distance}
|
|
59
|
+
|
|
60
|
+
def evaluate_model(self, model: Any) -> float:
|
|
61
|
+
adapter = wrap_model(model, output_size=self.action_size)
|
|
62
|
+
state = self.reset()
|
|
63
|
+
total_reward = 0.0
|
|
64
|
+
done = False
|
|
65
|
+
while not done:
|
|
66
|
+
action = adapter.predict_action(state, deterministic=True)
|
|
67
|
+
state, reward, done, _ = self.step(action)
|
|
68
|
+
total_reward += reward
|
|
69
|
+
return float(total_reward)
|