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.
@@ -0,0 +1,307 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+ from typing import Any, Sequence
6
+ import numpy as np
7
+
8
+ try:
9
+ import torch
10
+ except ImportError:
11
+ torch = None # type: ignore[assignment]
12
+
13
+ from ..Models.Model_Builder import (
14
+ build_model,
15
+ ensure_built_if_tf,
16
+ get_weights_np,
17
+ infer_architecture,
18
+ is_tf_model,
19
+ is_torch_model,
20
+ load_tensorflow,
21
+ set_weights_np,
22
+ )
23
+
24
+
25
+ def save_model(
26
+ model: Any,
27
+ path: str,
28
+ optimizer: Any = None,
29
+ metadata: dict[str, Any] | None = None,
30
+ ) -> None:
31
+ """Save a PyTorch or TensorFlow model (and optional optimizer/metadata) to disk."""
32
+ if hasattr(model, "get_internal_model"):
33
+ model = model.get_internal_model()
34
+
35
+ parent_dir = os.path.dirname(os.path.abspath(path))
36
+ if parent_dir and not os.path.exists(parent_dir):
37
+ os.makedirs(parent_dir, exist_ok=True)
38
+
39
+ if is_torch_model(model):
40
+ _, in_size, out_size, hidden = infer_architecture(model)
41
+ payload: dict[str, Any] = {
42
+ "model_state_dict": model.state_dict(),
43
+ "optimizer_state_dict": optimizer.state_dict() if optimizer is not None else {},
44
+ "architecture": {
45
+ "input_size": in_size,
46
+ "output_size": out_size,
47
+ "hidden_sizes": hidden,
48
+ },
49
+ }
50
+ if metadata:
51
+ payload["metadata"] = metadata
52
+ torch.save(payload, path)
53
+ return
54
+
55
+ if is_tf_model(model):
56
+ weights = get_weights_np(model)
57
+ target_path = path if path.endswith(".npz") else path + ".npz"
58
+ np.savez(target_path, *weights)
59
+ return
60
+
61
+ raise TypeError(f"Unsupported model type for saving: {type(model).__name__}")
62
+
63
+
64
+ def _filtered_torch_load(model: Any, state_dict: dict[str, Any]) -> None:
65
+ target_state = model.state_dict()
66
+ filtered = {
67
+ key: value
68
+ for key, value in state_dict.items()
69
+ if key in target_state and target_state[key].shape == value.shape
70
+ }
71
+ model.load_state_dict(filtered, strict=False)
72
+
73
+
74
+ def load_model(
75
+ path: str,
76
+ model_or_type_model: Any = "Pytorch",
77
+ input_size: int | None = None,
78
+ output_size: int | None = None,
79
+ optimizer: Any = None,
80
+ hidden_sizes: Sequence[int] | None = None,
81
+ ) -> Any | None:
82
+ """Load a saved PyTorch or TensorFlow model with automatic architecture detection & legacy layer remapping."""
83
+ try:
84
+ # Handle pre-instantiated model passed directly
85
+ if not isinstance(model_or_type_model, str):
86
+ model = model_or_type_model
87
+ if is_torch_model(model):
88
+ checkpoint = torch.load(path, map_location="cpu")
89
+ state_dict = checkpoint.get("model_state_dict", checkpoint) if isinstance(checkpoint, dict) else checkpoint
90
+ _filtered_torch_load(model, state_dict)
91
+ if optimizer is not None and isinstance(checkpoint, dict) and checkpoint.get("optimizer_state_dict"):
92
+ optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
93
+ return model
94
+ if is_tf_model(model):
95
+ npz_path = path if path.endswith(".npz") else path + ".npz"
96
+ data = np.load(npz_path)
97
+ keys = sorted(data.files, key=lambda v: int(v.replace("arr_", "")))
98
+ set_weights_np(model, [data[k] for k in keys])
99
+ return model
100
+
101
+ type_model = str(model_or_type_model).strip().capitalize()
102
+
103
+ if type_model in ("Tensorflow", "Tf", "Keras"):
104
+ load_tensorflow(optional=False)
105
+ npz_path = path if path.endswith(".npz") and os.path.exists(path) else (
106
+ path + ".npz" if os.path.exists(path + ".npz") else path
107
+ )
108
+ data = np.load(npz_path)
109
+ keys = sorted(data.files, key=lambda v: int(v.replace("arr_", "")))
110
+ weights = [data[k] for k in keys]
111
+ in_sz = int(input_size or weights[0].shape[0])
112
+ out_sz = int(output_size or weights[-1].shape[0])
113
+ model = build_model("Tensorflow", in_sz, out_sz, hidden_sizes=hidden_sizes)
114
+ ensure_built_if_tf(model, in_sz)
115
+ set_weights_np(model, weights)
116
+ return model
117
+
118
+ if torch is None:
119
+ raise ImportError("PyTorch is not installed in the current environment.")
120
+
121
+ checkpoint = torch.load(path, map_location="cpu")
122
+ state_dict = checkpoint.get("model_state_dict", checkpoint) if isinstance(checkpoint, dict) else checkpoint
123
+ arch_meta = checkpoint.get("architecture", {}) if isinstance(checkpoint, dict) else {}
124
+
125
+ has_fc = any(k.startswith("fc1.") or k.startswith("fc2.") for k in state_dict.keys())
126
+ has_hidden = any(k.startswith("hidden_layers.") for k in state_dict.keys())
127
+
128
+ resolved_in = int(input_size or arch_meta.get("input_size") or 6)
129
+ resolved_out = int(output_size or arch_meta.get("output_size") or 2)
130
+
131
+ if has_hidden:
132
+ indices = sorted({int(k.split(".")[1]) for k in state_dict.keys() if k.startswith("hidden_layers.")})
133
+ sizes: list[int] = []
134
+ for idx in indices:
135
+ w_key = f"hidden_layers.{idx}.weight"
136
+ if w_key in state_dict:
137
+ sizes.append(int(state_dict[w_key].shape[0]))
138
+ if idx == 0 and input_size is None:
139
+ resolved_in = int(state_dict[w_key].shape[1])
140
+ if "output_layer.weight" in state_dict and output_size is None:
141
+ resolved_out = int(state_dict["output_layer.weight"].shape[0])
142
+ if not sizes:
143
+ sizes = list(hidden_sizes) if hidden_sizes else [128]
144
+ model = build_model(type_model, resolved_in, resolved_out, hidden_sizes=sizes)
145
+ _filtered_torch_load(model, state_dict)
146
+ elif has_fc:
147
+ if "fc1.weight" in state_dict:
148
+ first_hidden = int(state_dict["fc1.weight"].shape[0])
149
+ if input_size is None:
150
+ resolved_in = int(state_dict["fc1.weight"].shape[1])
151
+ else:
152
+ any_w = next((v for k, v in state_dict.items() if k.endswith(".weight")), None)
153
+ first_hidden = int(any_w.shape[0]) if any_w is not None else 128
154
+ model = build_model(type_model, resolved_in, resolved_out, hidden_sizes=[first_hidden])
155
+ remapped: dict[str, Any] = {}
156
+ if "fc1.weight" in state_dict:
157
+ remapped["hidden_layers.0.weight"] = state_dict["fc1.weight"]
158
+ if "fc1.bias" in state_dict:
159
+ remapped["hidden_layers.0.bias"] = state_dict["fc1.bias"]
160
+ out_w = state_dict.get("fc2.weight")
161
+ out_b = state_dict.get("fc2.bias")
162
+ if out_w is not None and out_b is not None:
163
+ if out_w.shape[0] == resolved_out and out_w.shape[1] == first_hidden and out_b.shape[0] == resolved_out:
164
+ remapped["output_layer.weight"] = out_w
165
+ remapped["output_layer.bias"] = out_b
166
+ _filtered_torch_load(model, remapped)
167
+ else:
168
+ model = build_model(type_model, resolved_in, resolved_out, hidden_sizes=hidden_sizes)
169
+ _filtered_torch_load(model, state_dict)
170
+
171
+ if optimizer is not None and isinstance(checkpoint, dict) and checkpoint.get("optimizer_state_dict"):
172
+ optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
173
+ return model
174
+ except FileNotFoundError:
175
+ return None
176
+ except Exception:
177
+ return None
178
+
179
+
180
+ # Backward-compatible aliases matching Pong_Game / Snake_Game signatures
181
+ def save_genetic_model(model: Any, optimizer: Any, path: str) -> None:
182
+ save_model(model=model, path=path, optimizer=optimizer)
183
+
184
+
185
+ def load_genetic_model(
186
+ path: str,
187
+ type_model: str,
188
+ input_size: int,
189
+ output_size: int,
190
+ optimizer: Any = None,
191
+ hidden_sizes: Sequence[int] | None = None,
192
+ ) -> Any | None:
193
+ return load_model(
194
+ path=path,
195
+ model_or_type_model=type_model,
196
+ input_size=input_size,
197
+ output_size=output_size,
198
+ optimizer=optimizer,
199
+ hidden_sizes=hidden_sizes,
200
+ )
201
+
202
+
203
+ def save_qlearning_model(model: Any, optimizer: Any, path: str) -> None:
204
+ save_model(model=model, path=path, optimizer=optimizer)
205
+
206
+
207
+ def load_qlearning_model(
208
+ path: str,
209
+ model_or_type_model: Any,
210
+ input_size: int | None = None,
211
+ output_size: int | None = None,
212
+ optimizer: Any = None,
213
+ hidden_sizes: Sequence[int] | None = None,
214
+ ) -> Any | None:
215
+ return load_model(
216
+ path=path,
217
+ model_or_type_model=model_or_type_model,
218
+ input_size=input_size,
219
+ output_size=output_size,
220
+ optimizer=optimizer,
221
+ hidden_sizes=hidden_sizes,
222
+ )
223
+
224
+
225
+ @dataclass(slots=True)
226
+ class AIModelLoadResult:
227
+ """Result object returned by AILoader when attempting to restore a trained model."""
228
+
229
+ model: Any = None
230
+ model_found: bool = False
231
+ error_message: str | None = None
232
+
233
+
234
+ class AILoader:
235
+ """Configuration-driven model loader compatible with game context/config dictionaries."""
236
+
237
+ def __init__(
238
+ self,
239
+ context_or_config: Any,
240
+ input_size: int = 6,
241
+ output_size: int = 2,
242
+ relative_model_path: str = os.path.join("AI", "best_model.pth"),
243
+ ) -> None:
244
+ if hasattr(context_or_config, "base_dir") and hasattr(context_or_config, "config_AI"):
245
+ self.config = context_or_config
246
+ elif hasattr(context_or_config, "config"):
247
+ self.config = context_or_config.config
248
+ else:
249
+ self.config = context_or_config
250
+ self.base_dir = getattr(self.config, "base_dir", ".")
251
+ self.input_size = int(input_size)
252
+ self.output_size = int(output_size)
253
+ self.relative_model_path = relative_model_path
254
+
255
+ def _get_config_ai(self) -> dict[str, Any]:
256
+ if isinstance(self.config, dict):
257
+ return self.config.get("config_AI", self.config)
258
+ return getattr(self.config, "config_AI", {})
259
+
260
+ def _get_selected_training(self) -> str:
261
+ cfg_ai = self._get_config_ai()
262
+ training = next((k for k, v in cfg_ai.get("type_training", {}).items() if v), None)
263
+ if training is None:
264
+ raise ValueError("No valid training type was specified in config_AI['type_training'].")
265
+ return training
266
+
267
+ def _get_selected_model(self) -> str:
268
+ cfg_ai = self._get_config_ai()
269
+ model_type = next((k for k, v in cfg_ai.get("type_model", {}).items() if v), None)
270
+ if model_type is None:
271
+ raise ValueError("No valid model backend was specified in config_AI['type_model'].")
272
+ return model_type
273
+
274
+ def _get_hidden_architecture(self) -> list[int]:
275
+ cfg_ai = self._get_config_ai()
276
+ nn_cfg = cfg_ai.get("nn", {"hidden_layers": 2, "neurons_per_layer": 6})
277
+ neurons = int(nn_cfg.get("neurons_per_layer", 6))
278
+ layers = int(nn_cfg.get("hidden_layers", 2))
279
+ return [neurons] * layers
280
+
281
+ def load_model_result(self, custom_path: str | None = None) -> AIModelLoadResult:
282
+ model_path = custom_path or os.path.join(self.base_dir, self.relative_model_path)
283
+ try:
284
+ _ = self._get_selected_training()
285
+ model_type = self._get_selected_model()
286
+ arch = self._get_hidden_architecture()
287
+ if not os.path.exists(model_path):
288
+ return AIModelLoadResult(model=None, model_found=False, error_message=None)
289
+ model = load_model(
290
+ path=model_path,
291
+ model_or_type_model=model_type,
292
+ input_size=self.input_size,
293
+ output_size=self.output_size,
294
+ hidden_sizes=arch,
295
+ )
296
+ if model is None:
297
+ return AIModelLoadResult(
298
+ model=None,
299
+ model_found=False,
300
+ error_message="Failed to deserialize the saved model file.",
301
+ )
302
+ return AIModelLoadResult(model=model, model_found=True, error_message=None)
303
+ except Exception as exc:
304
+ return AIModelLoadResult(model=None, model_found=False, error_message=str(exc))
305
+
306
+ def load_model(self, custom_path: str | None = None) -> Any | None:
307
+ return self.load_model_result(custom_path=custom_path).model
@@ -0,0 +1,21 @@
1
+ from .Model_Serializer import (
2
+ AILoader,
3
+ AIModelLoadResult,
4
+ load_genetic_model,
5
+ load_model,
6
+ load_qlearning_model,
7
+ save_genetic_model,
8
+ save_model,
9
+ save_qlearning_model,
10
+ )
11
+
12
+ __all__ = [
13
+ "AILoader",
14
+ "AIModelLoadResult",
15
+ "load_genetic_model",
16
+ "load_model",
17
+ "load_qlearning_model",
18
+ "save_genetic_model",
19
+ "save_model",
20
+ "save_qlearning_model",
21
+ ]