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,60 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+ import numpy as np
6
+
7
+
8
+ class IAIModel(ABC):
9
+ """Unified contract for AI model adapters across backends (PyTorch, TensorFlow, Mock)."""
10
+
11
+ @abstractmethod
12
+ def predict(self, state: np.ndarray | list[float]) -> np.ndarray:
13
+ """Run a forward pass on a 1D or 2D state array and return raw output logits/values."""
14
+ pass
15
+
16
+ def predict_probabilities(self, state: np.ndarray | list[float]) -> np.ndarray:
17
+ """Return softmax-normalized action probabilities from raw model predictions."""
18
+ logits = np.asarray(self.predict(state), dtype=np.float32).flatten()
19
+ shifted = logits - np.max(logits)
20
+ exp_scores = np.exp(shifted)
21
+ total = np.sum(exp_scores)
22
+ if total == 0.0 or not np.isfinite(total):
23
+ return np.full_like(logits, 1.0 / max(1, len(logits)))
24
+ return exp_scores / total
25
+
26
+ def predict_action(self, state: np.ndarray | list[float], deterministic: bool = True) -> int:
27
+ """Select a discrete action index from the model output."""
28
+ if deterministic:
29
+ raw = np.asarray(self.predict(state), dtype=np.float32).flatten()
30
+ return int(np.argmax(raw))
31
+ probs = self.predict_probabilities(state)
32
+ return int(np.random.choice(len(probs), p=probs))
33
+
34
+ @abstractmethod
35
+ def save(self, path: str) -> None:
36
+ """Persist model weights/state to disk."""
37
+ pass
38
+
39
+ @abstractmethod
40
+ def load(self, path: str) -> None:
41
+ """Restore model weights/state from disk."""
42
+ pass
43
+
44
+ @abstractmethod
45
+ def get_internal_model(self) -> Any:
46
+ """Return the underlying framework model (e.g., torch.nn.Module or tf.keras.Model)."""
47
+ pass
48
+
49
+ def get_weights(self) -> list[np.ndarray]:
50
+ """Extract all trainable parameter tensors as a list of detached NumPy arrays."""
51
+ raise NotImplementedError("Weight extraction is not implemented for this adapter.")
52
+
53
+ def set_weights(self, weights: list[np.ndarray]) -> None:
54
+ """Inject a list of NumPy parameter arrays into the underlying model."""
55
+ raise NotImplementedError("Weight assignment is not implemented for this adapter.")
56
+
57
+ def get_activations(self) -> np.ndarray | None:
58
+ """Return normalized hidden-layer activations (shape: [1, N] in [0, 1]) for UI visualization."""
59
+ model = self.get_internal_model()
60
+ return getattr(model, "activations", None) if model is not None else None
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+ import numpy as np
6
+
7
+
8
+ class IEnvironment(ABC):
9
+ """Gym-style Reinforcement Learning environment interface for step-by-step training (DQN/Q-Learning)."""
10
+
11
+ @property
12
+ @abstractmethod
13
+ def state_size(self) -> int:
14
+ """Dimensionality of the state observation vector."""
15
+ pass
16
+
17
+ @property
18
+ @abstractmethod
19
+ def action_size(self) -> int:
20
+ """Number of discrete actions available to the agent."""
21
+ pass
22
+
23
+ @abstractmethod
24
+ def reset(self) -> np.ndarray:
25
+ """Reset the environment to an initial state and return the initial observation vector."""
26
+ pass
27
+
28
+ @abstractmethod
29
+ def step(self, action: int) -> tuple[np.ndarray, float, bool, dict[str, Any]]:
30
+ """Execute one environment step and return (next_state, reward, done, info)."""
31
+ pass
32
+
33
+ def should_stop(self) -> bool:
34
+ """Return True if the host application/window requested an immediate exit."""
35
+ return False
36
+
37
+
38
+ class IFitnessEnvironment(ABC):
39
+ """Episode-level evaluation contract for neuroevolution / Genetic Algorithms."""
40
+
41
+ @abstractmethod
42
+ def evaluate_model(self, model: Any) -> float:
43
+ """Run one complete episode/trial controlled by `model` and return its scalar fitness score."""
44
+ pass
45
+
46
+ def should_stop(self) -> bool:
47
+ """Return True if the host application/window requested an immediate exit."""
48
+ return False
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+
8
+ @dataclass(slots=True)
9
+ class TrainingResult:
10
+ """Structured summary produced at the end of a training run."""
11
+
12
+ best_model: Any
13
+ best_score: float
14
+ history: list[float] = field(default_factory=list)
15
+ iterations_completed: int = 0
16
+ stopped_early: bool = False
17
+ metadata: dict[str, Any] = field(default_factory=dict)
18
+
19
+
20
+ class ITrainingCallback(ABC):
21
+ """Hook interface for observing and controlling training loops (UI updates, logging, checkpoints, early stopping)."""
22
+
23
+ def on_training_start(self, trainer: Any) -> None:
24
+ pass
25
+
26
+ def on_iteration_end(
27
+ self,
28
+ iteration: int,
29
+ best_score: float,
30
+ mean_score: float,
31
+ trainer: Any,
32
+ ) -> bool | None:
33
+ """Called after each generation or episode. Return True to stop training early."""
34
+ return False
35
+
36
+ def on_training_end(self, result: TrainingResult, trainer: Any) -> None:
37
+ pass
38
+
39
+
40
+ class ITrainer(ABC):
41
+ """Unified interface for AI training algorithms (Genetic Algorithm, Deep Q-Learning, etc.)."""
42
+
43
+ @abstractmethod
44
+ def train(self, target: Any = None) -> Any:
45
+ """Execute the training loop and return the best trained model."""
46
+ pass
@@ -0,0 +1,12 @@
1
+ from .IAIModel import IAIModel
2
+ from .IEnvironment import IEnvironment, IFitnessEnvironment
3
+ from .ITrainer import ITrainer, ITrainingCallback, TrainingResult
4
+
5
+ __all__ = [
6
+ "IAIModel",
7
+ "IEnvironment",
8
+ "IFitnessEnvironment",
9
+ "ITrainer",
10
+ "ITrainingCallback",
11
+ "TrainingResult",
12
+ ]
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Sequence
4
+ import numpy as np
5
+
6
+ try:
7
+ import torch
8
+ except ImportError:
9
+ torch = None # type: ignore[assignment]
10
+
11
+
12
+ def load_tensorflow(optional: bool = True):
13
+ """Lazily import TensorFlow, optionally raising an informative error if missing."""
14
+ try:
15
+ import tensorflow as tf
16
+ return tf
17
+ except ImportError:
18
+ if optional:
19
+ return None
20
+ raise ImportError("TensorFlow is not installed in the current environment.")
21
+
22
+
23
+ def is_torch_model(model: Any) -> bool:
24
+ return torch is not None and hasattr(model, "parameters") and isinstance(model, torch.nn.Module)
25
+
26
+
27
+ def is_tf_model(model: Any) -> bool:
28
+ if not hasattr(model, "trainable_variables") and not hasattr(model, "_keras_model"):
29
+ return False
30
+ if hasattr(model, "_keras_model"):
31
+ return True
32
+ tf = load_tensorflow(optional=True)
33
+ return (tf is not None) and isinstance(model, tf.keras.Model)
34
+
35
+
36
+ def ensure_built_if_tf(model: Any, input_size: int) -> None:
37
+ if is_tf_model(model):
38
+ try:
39
+ if not getattr(model, "built", False) or len(model.weights) == 0:
40
+ tf = load_tensorflow(optional=False)
41
+ dummy = tf.zeros((1, int(input_size)), dtype=tf.float32)
42
+ _ = model(dummy, training=False)
43
+ except Exception:
44
+ pass
45
+
46
+
47
+ def build_model(
48
+ type_model: str,
49
+ input_size: int,
50
+ output_size: int,
51
+ hidden_sizes: Sequence[int] | None = None,
52
+ activation: str = "relu",
53
+ record_activations: bool = True,
54
+ ) -> Any:
55
+ """Instantiate a neural network for the requested backend ('Pytorch' or 'Tensorflow')."""
56
+ normalized = type_model.strip().capitalize()
57
+ if normalized in ("Pytorch", "Torch"):
58
+ if torch is None:
59
+ raise ImportError("PyTorch is not installed in the current environment.")
60
+ from .Neural_Network_Pytorch import SimpleNN_Pytorch
61
+
62
+ return SimpleNN_Pytorch(
63
+ input_size=input_size,
64
+ output_size=output_size,
65
+ hidden_sizes=hidden_sizes,
66
+ activation=activation,
67
+ record_activations=record_activations,
68
+ )
69
+ if normalized in ("Tensorflow", "Tf", "Keras"):
70
+ load_tensorflow(optional=False)
71
+ from .Neural_Network_Tensorflow import SimpleNN_Tensorflow
72
+
73
+ model = SimpleNN_Tensorflow(
74
+ input_size=input_size,
75
+ output_size=output_size,
76
+ hidden_sizes=hidden_sizes,
77
+ activation=activation,
78
+ record_activations=record_activations,
79
+ )
80
+ ensure_built_if_tf(model, input_size)
81
+ return model
82
+ raise ValueError(f"Unknown type_model: '{type_model}'. Supported backends: 'Pytorch', 'Tensorflow'.")
83
+
84
+
85
+ def get_weights_np(model: Any) -> list[np.ndarray]:
86
+ """Extract all parameters from a PyTorch or TensorFlow model as a list of NumPy arrays."""
87
+ if hasattr(model, "get_internal_model"):
88
+ model = model.get_internal_model()
89
+ if is_torch_model(model):
90
+ return [p.detach().cpu().numpy().copy() for p in model.parameters()]
91
+ if is_tf_model(model):
92
+ return [w.copy() for w in model.get_weights()]
93
+ raise TypeError(f"Unsupported model type for weight extraction: {type(model).__name__}")
94
+
95
+
96
+ def set_weights_np(model: Any, weights: Sequence[np.ndarray]) -> None:
97
+ """Copy a sequence of NumPy weight arrays into a PyTorch or TensorFlow model in-place."""
98
+ if hasattr(model, "get_internal_model"):
99
+ model = model.get_internal_model()
100
+ if is_torch_model(model):
101
+ with torch.no_grad():
102
+ for p, w in zip(model.parameters(), weights):
103
+ tensor_w = torch.from_numpy(np.array(w, copy=False)).to(p.device, dtype=p.dtype)
104
+ p.copy_(tensor_w)
105
+ return
106
+ if is_tf_model(model):
107
+ model.set_weights([np.array(w, copy=False) for w in weights])
108
+ return
109
+ raise TypeError(f"Unsupported model type for weight assignment: {type(model).__name__}")
110
+
111
+
112
+ def infer_architecture(model: Any) -> tuple[str, int, int, list[int]]:
113
+ """Infer (type_model, input_size, output_size, hidden_sizes) from an existing model instance."""
114
+ if hasattr(model, "get_internal_model"):
115
+ model = model.get_internal_model()
116
+ type_model = "Pytorch" if is_torch_model(model) else ("Tensorflow" if is_tf_model(model) else "Unknown")
117
+ input_size = getattr(model, "input_size", None)
118
+ output_size = getattr(model, "output_size", None)
119
+ hidden_sizes = getattr(model, "hidden_sizes", None)
120
+
121
+ if is_torch_model(model):
122
+ if input_size is None and hasattr(model, "hidden_layers") and len(model.hidden_layers) > 0:
123
+ input_size = int(model.hidden_layers[0].in_features)
124
+ if output_size is None and hasattr(model, "output_layer"):
125
+ output_size = int(model.output_layer.out_features)
126
+ if hidden_sizes is None and hasattr(model, "hidden_layers"):
127
+ hidden_sizes = [int(layer.out_features) for layer in model.hidden_layers]
128
+
129
+ return (
130
+ type_model,
131
+ int(input_size or 1),
132
+ int(output_size or 1),
133
+ list(hidden_sizes) if hidden_sizes is not None else [128],
134
+ )
135
+
136
+
137
+ def clone_model(
138
+ model: Any,
139
+ type_model: str | None = None,
140
+ input_size: int | None = None,
141
+ output_size: int | None = None,
142
+ hidden_sizes: Sequence[int] | None = None,
143
+ ) -> Any:
144
+ """Create a deep copy of a model preserving architecture and weights."""
145
+ inferred_type, inferred_in, inferred_out, inferred_hidden = infer_architecture(model)
146
+ target_type = type_model or inferred_type
147
+ target_in = input_size or inferred_in
148
+ target_out = output_size or inferred_out
149
+ target_hidden = list(hidden_sizes) if hidden_sizes is not None else inferred_hidden
150
+ record_act = getattr(model, "record_activations", True)
151
+ activation = getattr(model, "activation_name", "relu")
152
+
153
+ cloned = build_model(
154
+ target_type,
155
+ target_in,
156
+ target_out,
157
+ hidden_sizes=target_hidden,
158
+ activation=activation,
159
+ record_activations=record_act,
160
+ )
161
+ set_weights_np(cloned, get_weights_np(model))
162
+ return cloned
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+
10
+ _ACTIVATION_MAP = {
11
+ "relu": torch.relu,
12
+ "tanh": torch.tanh,
13
+ "sigmoid": torch.sigmoid,
14
+ "leaky_relu": F.leaky_relu,
15
+ "elu": F.elu,
16
+ }
17
+
18
+
19
+ class SimpleNN_Pytorch(nn.Module):
20
+ """Configurable multi-layer perceptron in PyTorch with normalized activation tracking for HUD visualization."""
21
+
22
+ def __init__(
23
+ self,
24
+ input_size: int,
25
+ output_size: int,
26
+ hidden_sizes: Sequence[int] | None = None,
27
+ activation: str = "relu",
28
+ record_activations: bool = True,
29
+ ) -> None:
30
+ super().__init__()
31
+ if input_size <= 0 or output_size <= 0:
32
+ raise ValueError("input_size and output_size must be positive integers.")
33
+
34
+ if hidden_sizes is None or len(hidden_sizes) == 0:
35
+ hidden_sizes = [128]
36
+
37
+ self.input_size = int(input_size)
38
+ self.output_size = int(output_size)
39
+ self.hidden_sizes = [int(h) for h in hidden_sizes]
40
+ self.activation_name = activation.lower()
41
+ if self.activation_name not in _ACTIVATION_MAP:
42
+ raise ValueError(f"Unsupported activation '{activation}'. Choose from {list(_ACTIVATION_MAP.keys())}.")
43
+ self._activation_fn = _ACTIVATION_MAP[self.activation_name]
44
+ self.record_activations = bool(record_activations)
45
+
46
+ self.hidden_layers = nn.ModuleList()
47
+ in_features = self.input_size
48
+ for h in self.hidden_sizes:
49
+ self.hidden_layers.append(nn.Linear(in_features, h))
50
+ in_features = h
51
+
52
+ self.output_layer = nn.Linear(in_features, self.output_size)
53
+ # Alias preserved for HUD weight inspection compatibility (e.g. Pong_Game / Snake_Game)
54
+ self.fc1 = self.hidden_layers[0]
55
+ self.activations: np.ndarray | None = None
56
+
57
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
58
+ for i, layer in enumerate(self.hidden_layers):
59
+ x = self._activation_fn(layer(x))
60
+ if i == 0 and self.record_activations:
61
+ with torch.no_grad():
62
+ act = x.detach().cpu().numpy().reshape(1, -1)
63
+ span = act.max() - act.min()
64
+ if span != 0.0:
65
+ self.activations = (act - act.min()) / span
66
+ else:
67
+ self.activations = act
68
+ return self.output_layer(x)
69
+
70
+
71
+ # Alias for backward compatibility with projects importing SimpleNN directly
72
+ SimpleNN = SimpleNN_Pytorch
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Sequence
4
+ import numpy as np
5
+
6
+
7
+ class SimpleNN_Tensorflow:
8
+ """Configurable multi-layer perceptron in TensorFlow/Keras with normalized activation tracking and lazy TF loading."""
9
+
10
+ def __init__(
11
+ self,
12
+ input_size: int,
13
+ output_size: int,
14
+ hidden_sizes: Sequence[int] | None = None,
15
+ activation: str = "relu",
16
+ record_activations: bool = True,
17
+ ) -> None:
18
+ try:
19
+ import tensorflow as tf
20
+ from tensorflow.keras import layers
21
+ except ImportError as exc:
22
+ raise ImportError("TensorFlow is not installed in the current environment.") from exc
23
+
24
+ if input_size <= 0 or output_size <= 0:
25
+ raise ValueError("input_size and output_size must be positive integers.")
26
+
27
+ if hidden_sizes is None or len(hidden_sizes) == 0:
28
+ hidden_sizes = [128]
29
+
30
+ self._tf = tf
31
+ self.input_size = int(input_size)
32
+ self.output_size = int(output_size)
33
+ self.hidden_sizes = [int(h) for h in hidden_sizes]
34
+ self.activation_name = activation.lower()
35
+ self.record_activations = bool(record_activations)
36
+
37
+ self.hidden_layers = [layers.Dense(h, activation=self.activation_name) for h in self.hidden_sizes]
38
+ self.output_layer = layers.Dense(self.output_size)
39
+ self.fc1 = self.hidden_layers[0]
40
+ self.activations: np.ndarray | None = None
41
+
42
+ inputs = tf.keras.Input(shape=(self.input_size,), dtype=tf.float32)
43
+ x = inputs
44
+ for layer in self.hidden_layers:
45
+ x = layer(x)
46
+ outputs = self.output_layer(x)
47
+ self._keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
48
+ self.built = True
49
+
50
+ @property
51
+ def trainable_variables(self) -> Any:
52
+ return self._keras_model.trainable_variables
53
+
54
+ @property
55
+ def weights(self) -> Any:
56
+ return self._keras_model.weights
57
+
58
+ def get_weights(self) -> list[np.ndarray]:
59
+ return self._keras_model.get_weights()
60
+
61
+ def set_weights(self, weights: Sequence[np.ndarray]) -> None:
62
+ self._keras_model.set_weights([np.array(w, copy=False) for w in weights])
63
+
64
+ def save(self, path: str) -> None:
65
+ self._keras_model.save(path)
66
+
67
+ def forward(self, x: Any) -> Any:
68
+ tf = self._tf
69
+ x_tensor = tf.convert_to_tensor(x, dtype=tf.float32)
70
+ if len(x_tensor.shape) == 1:
71
+ x_tensor = tf.expand_dims(x_tensor, axis=0)
72
+ for i, layer in enumerate(self.hidden_layers):
73
+ x_tensor = layer(x_tensor)
74
+ if i == 0 and self.record_activations:
75
+ try:
76
+ activations_np = x_tensor.numpy().reshape(1, -1)
77
+ min_val = np.min(activations_np)
78
+ max_val = np.max(activations_np)
79
+ if max_val - min_val != 0:
80
+ self.activations = (activations_np - min_val) / (max_val - min_val)
81
+ else:
82
+ self.activations = activations_np
83
+ except Exception:
84
+ pass
85
+ return self.output_layer(x_tensor)
86
+
87
+ def call(self, x: Any, training: bool = False) -> Any:
88
+ return self.forward(x)
89
+
90
+ def __call__(self, x: Any, training: bool = False) -> Any:
91
+ return self.forward(x)
@@ -0,0 +1,28 @@
1
+ from .Model_Builder import (
2
+ build_model,
3
+ clone_model,
4
+ ensure_built_if_tf,
5
+ get_weights_np,
6
+ infer_architecture,
7
+ is_tf_model,
8
+ is_torch_model,
9
+ load_tensorflow,
10
+ set_weights_np,
11
+ )
12
+ from .Neural_Network_Pytorch import SimpleNN, SimpleNN_Pytorch
13
+ from .Neural_Network_Tensorflow import SimpleNN_Tensorflow
14
+
15
+ __all__ = [
16
+ "SimpleNN",
17
+ "SimpleNN_Pytorch",
18
+ "SimpleNN_Tensorflow",
19
+ "build_model",
20
+ "clone_model",
21
+ "ensure_built_if_tf",
22
+ "get_weights_np",
23
+ "infer_architecture",
24
+ "is_tf_model",
25
+ "is_torch_model",
26
+ "load_tensorflow",
27
+ "set_weights_np",
28
+ ]