pyforgeai-engine 1.0.0__tar.gz → 1.1.0__tar.gz

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.
Files changed (41) hide show
  1. {pyforgeai_engine-1.0.0/src/pyforgeai_engine.egg-info → pyforgeai_engine-1.1.0}/PKG-INFO +3 -2
  2. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/README.md +2 -1
  3. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/pyproject.toml +1 -1
  4. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/AI_Factory.py +1 -1
  5. pyforgeai_engine-1.1.0/src/pyforgeai/Environments/Game_Bridge_Env.py +135 -0
  6. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Environments/__init__.py +2 -1
  7. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Interfaces/IEnvironment.py +17 -2
  8. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Models/Model_Builder.py +7 -0
  9. pyforgeai_engine-1.1.0/src/pyforgeai/Models/Neural_Network_Pytorch.py +120 -0
  10. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Models/Neural_Network_Tensorflow.py +39 -9
  11. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Serialization/Model_Serializer.py +142 -35
  12. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Trainers/Genetic_Algorithm.py +135 -44
  13. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Trainers/Q_Learning.py +79 -51
  14. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/__init__.py +14 -3
  15. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0/src/pyforgeai_engine.egg-info}/PKG-INFO +3 -2
  16. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/tests/test_genetic_trainer.py +22 -6
  17. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/tests/test_qlearning_trainer.py +11 -6
  18. pyforgeai_engine-1.0.0/src/pyforgeai/Environments/Game_Bridge_Env.py +0 -117
  19. pyforgeai_engine-1.0.0/src/pyforgeai/Models/Neural_Network_Pytorch.py +0 -72
  20. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/LICENSE +0 -0
  21. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/setup.cfg +0 -0
  22. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/AI_Controller.py +0 -0
  23. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Adapters/Mock_Adapter.py +0 -0
  24. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Adapters/PyTorch_Adapter.py +0 -0
  25. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Adapters/TensorFlow_Adapter.py +0 -0
  26. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Adapters/__init__.py +0 -0
  27. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Environments/Target_Seek_Env.py +0 -0
  28. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Interfaces/IAIModel.py +0 -0
  29. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Interfaces/ITrainer.py +0 -0
  30. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Interfaces/__init__.py +0 -0
  31. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Models/__init__.py +0 -0
  32. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Serialization/__init__.py +0 -0
  33. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Trainers/Training_Callbacks.py +0 -0
  34. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai/Trainers/__init__.py +0 -0
  35. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai_engine.egg-info/SOURCES.txt +0 -0
  36. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai_engine.egg-info/dependency_links.txt +0 -0
  37. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai_engine.egg-info/requires.txt +0 -0
  38. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/src/pyforgeai_engine.egg-info/top_level.txt +0 -0
  39. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/tests/test_factory_and_envs.py +0 -0
  40. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/tests/test_models_and_adapters.py +0 -0
  41. {pyforgeai_engine-1.0.0 → pyforgeai_engine-1.1.0}/tests/test_serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyforgeai-engine
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: A modular, multi-backend game AI training and inference library featuring Neuroevolution (Genetic Algorithms) and Deep Q-Learning (DQN) for Pygame and Python simulations.
5
5
  Author: Drakonosinc
6
6
  License: MIT
@@ -33,6 +33,7 @@ Dynamic: license-file
33
33
  # PyForgeAI
34
34
 
35
35
  [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-4B32C3?logo=read-the-docs&logoColor=white)](https://deepwiki.com/Drakonosinc/PyForgeAI)
36
+ [![PyPI version](https://img.shields.io/pypi/v/pyforgeai-engine.svg)](https://pypi.org/project/pyforgeai-engine/)
36
37
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
37
38
  [![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-EE4C2C.svg?logo=pytorch&logoColor=white)](https://pytorch.org/)
38
39
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
@@ -78,7 +79,7 @@ flowchart TD
78
79
 
79
80
  ## Installation
80
81
 
81
- ### From PyPI (once published)
82
+ ### From PyPI
82
83
  ```bash
83
84
  pip install pyforgeai-engine
84
85
  ```
@@ -1,6 +1,7 @@
1
1
  # PyForgeAI
2
2
 
3
3
  [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-4B32C3?logo=read-the-docs&logoColor=white)](https://deepwiki.com/Drakonosinc/PyForgeAI)
4
+ [![PyPI version](https://img.shields.io/pypi/v/pyforgeai-engine.svg)](https://pypi.org/project/pyforgeai-engine/)
4
5
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
5
6
  [![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-EE4C2C.svg?logo=pytorch&logoColor=white)](https://pytorch.org/)
6
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
@@ -46,7 +47,7 @@ flowchart TD
46
47
 
47
48
  ## Installation
48
49
 
49
- ### From PyPI (once published)
50
+ ### From PyPI
50
51
  ```bash
51
52
  pip install pyforgeai-engine
52
53
  ```
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyforgeai-engine"
7
- version = "1.0.0"
7
+ version = "1.1.0"
8
8
  description = "A modular, multi-backend game AI training and inference library featuring Neuroevolution (Genetic Algorithms) and Deep Q-Learning (DQN) for Pygame and Python simulations."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -81,7 +81,7 @@ class AIFactory:
81
81
  cfg = self._merge(config)
82
82
  cfg.update(kwargs)
83
83
  return QLearningTrainer(
84
- game=cfg.get("game"),
84
+ env=cfg.get("env"),
85
85
  type_model=cfg.get("type_model", "Pytorch"),
86
86
  input_size=int(cfg.get("input_size", 6)),
87
87
  output_size=int(cfg.get("output_size", 2)),
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Callable, Sequence
4
+ import numpy as np
5
+
6
+ from ..Interfaces.IEnvironment import IEnvironment, IFitnessEnvironment
7
+
8
+
9
+ class FunctionalFitnessEnvironment(IFitnessEnvironment):
10
+ """Domain-agnostic adapter turning pure Python callables into an `IFitnessEnvironment`.
11
+
12
+ Supports both single-agent evaluation (`fitness_fn(model) -> float`) and vectorized/multi-agent
13
+ population evaluation (`batch_fitness_fn(population_list) -> list[float]`), without assuming
14
+ any specific application or game object structure.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ target: Callable[[Any], float] | IFitnessEnvironment | None = None,
20
+ batch_fitness_fn: Callable[[list[Any]], Sequence[float]] | None = None,
21
+ stop_fn: Callable[[], bool] | None = None,
22
+ on_generation_fn: Callable[[int], None] | None = None,
23
+ on_best_fn: Callable[[Any], None] | None = None,
24
+ ) -> None:
25
+ if target is None and batch_fitness_fn is None:
26
+ raise TypeError(
27
+ "Must provide either `target` (a callable `fn(model) -> float` or `IFitnessEnvironment`) "
28
+ "or `batch_fitness_fn` (`fn(population) -> Sequence[float]`)."
29
+ )
30
+ if target is not None and not isinstance(target, IFitnessEnvironment) and not callable(target):
31
+ raise TypeError(
32
+ f"Expected `target` to be a callable `fn(model) -> float` or an `IFitnessEnvironment`, got {type(target).__name__}."
33
+ )
34
+ self.target = target
35
+ self._batch_fitness_fn = batch_fitness_fn
36
+ self._stop_fn = stop_fn
37
+ self._on_generation_fn = on_generation_fn
38
+ self._on_best_fn = on_best_fn
39
+
40
+ def evaluate_model(self, model: Any) -> float:
41
+ if isinstance(self.target, IFitnessEnvironment):
42
+ return float(self.target.evaluate_model(model))
43
+ if callable(self.target):
44
+ return float(self.target(model))
45
+ if self._batch_fitness_fn is not None:
46
+ scores = self._batch_fitness_fn([model])
47
+ return float(scores[0]) if len(scores) > 0 else 0.0
48
+ raise RuntimeError("No single-model evaluation function configured.")
49
+
50
+ def is_batch_population_target(self) -> bool:
51
+ """Return True if this environment evaluates an entire population list at once."""
52
+ if self._batch_fitness_fn is not None:
53
+ return True
54
+ if isinstance(self.target, IFitnessEnvironment):
55
+ # Check if subclass overrides evaluate_population
56
+ return type(self.target).evaluate_population is not IFitnessEnvironment.evaluate_population
57
+ return False
58
+
59
+ def evaluate_population(self, population: list[Any]) -> list[float] | None:
60
+ if self._batch_fitness_fn is not None:
61
+ scores = self._batch_fitness_fn(list(population))
62
+ return [float(s) for s in scores]
63
+ if isinstance(self.target, IFitnessEnvironment):
64
+ return self.target.evaluate_population(list(population))
65
+ return None
66
+
67
+ def evaluate_population_batch(self, population: Sequence[Any]) -> list[float]:
68
+ res = self.evaluate_population(list(population))
69
+ if res is not None:
70
+ return res
71
+ return [self.evaluate_model(m) for m in population]
72
+
73
+ def should_stop(self) -> bool:
74
+ if self._stop_fn is not None:
75
+ return bool(self._stop_fn())
76
+ if isinstance(self.target, IFitnessEnvironment):
77
+ return bool(self.target.should_stop())
78
+ return False
79
+
80
+ def on_generation_start(self, generation: int) -> None:
81
+ if self._on_generation_fn is not None:
82
+ self._on_generation_fn(int(generation))
83
+ elif isinstance(self.target, IFitnessEnvironment):
84
+ self.target.on_generation_start(int(generation))
85
+
86
+ def on_best_model(self, model: Any) -> None:
87
+ if self._on_best_fn is not None:
88
+ self._on_best_fn(model)
89
+ elif isinstance(self.target, IFitnessEnvironment):
90
+ self.target.on_best_model(model)
91
+
92
+
93
+ # Alias kept for backward import compatibility
94
+ GameFitnessBridge = FunctionalFitnessEnvironment
95
+
96
+
97
+ class CallbackRLEnvironment(IEnvironment):
98
+ """Creates a step-by-step RL environment from user-supplied callables (`reset_fn`, `step_fn`)."""
99
+
100
+ def __init__(
101
+ self,
102
+ state_size: int,
103
+ action_size: int,
104
+ reset_fn: Callable[[], np.ndarray],
105
+ step_fn: Callable[[int], tuple[np.ndarray, float, bool] | tuple[np.ndarray, float, bool, dict[str, Any]]],
106
+ stop_fn: Callable[[], bool] | None = None,
107
+ ) -> None:
108
+ self._state_size = int(state_size)
109
+ self._action_size = int(action_size)
110
+ self._reset_fn = reset_fn
111
+ self._step_fn = step_fn
112
+ self._stop_fn = stop_fn
113
+
114
+ @property
115
+ def state_size(self) -> int:
116
+ return self._state_size
117
+
118
+ @property
119
+ def action_size(self) -> int:
120
+ return self._action_size
121
+
122
+ def reset(self) -> np.ndarray:
123
+ return np.asarray(self._reset_fn(), dtype=np.float32)
124
+
125
+ def step(self, action: int) -> tuple[np.ndarray, float, bool, dict[str, Any]]:
126
+ result = self._step_fn(int(action))
127
+ if len(result) == 3:
128
+ next_state, reward, done = result
129
+ info: dict[str, Any] = {}
130
+ else:
131
+ next_state, reward, done, info = result
132
+ return np.asarray(next_state, dtype=np.float32), float(reward), bool(done), info
133
+
134
+ def should_stop(self) -> bool:
135
+ return bool(self._stop_fn()) if self._stop_fn is not None else False
@@ -1,8 +1,9 @@
1
- from .Game_Bridge_Env import CallbackRLEnvironment, GameFitnessBridge
1
+ from .Game_Bridge_Env import CallbackRLEnvironment, FunctionalFitnessEnvironment, GameFitnessBridge
2
2
  from .Target_Seek_Env import TargetSeekEnvironment
3
3
 
4
4
  __all__ = [
5
5
  "CallbackRLEnvironment",
6
+ "FunctionalFitnessEnvironment",
6
7
  "GameFitnessBridge",
7
8
  "TargetSeekEnvironment",
8
9
  ]
@@ -31,7 +31,7 @@ class IEnvironment(ABC):
31
31
  pass
32
32
 
33
33
  def should_stop(self) -> bool:
34
- """Return True if the host application/window requested an immediate exit."""
34
+ """Return True if the host application requested an immediate training stop."""
35
35
  return False
36
36
 
37
37
 
@@ -43,6 +43,21 @@ class IFitnessEnvironment(ABC):
43
43
  """Run one complete episode/trial controlled by `model` and return its scalar fitness score."""
44
44
  pass
45
45
 
46
+ def evaluate_population(self, population: list[Any]) -> list[float] | None:
47
+ """Optional batch hook: evaluate an entire population simultaneously and return per-model scores.
48
+
49
+ Returns `None` by default, indicating the trainer should call `evaluate_model` individually.
50
+ """
51
+ return None
52
+
46
53
  def should_stop(self) -> bool:
47
- """Return True if the host application/window requested an immediate exit."""
54
+ """Return True if the host application requested an immediate training stop."""
48
55
  return False
56
+
57
+ def on_generation_start(self, generation: int) -> None:
58
+ """Optional lifecycle hook invoked at the beginning of each generation."""
59
+ pass
60
+
61
+ def on_best_model(self, model: Any) -> None:
62
+ """Optional lifecycle hook invoked when a new best model is found or training finishes."""
63
+ pass
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import os
3
4
  from typing import Any, Sequence
4
5
  import numpy as np
5
6
 
@@ -11,6 +12,8 @@ except ImportError:
11
12
 
12
13
  def load_tensorflow(optional: bool = True):
13
14
  """Lazily import TensorFlow, optionally raising an informative error if missing."""
15
+ os.environ.setdefault("TF_ENABLE_ONEDNN_OPTS", "0")
16
+ os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
14
17
  try:
15
18
  import tensorflow as tf
16
19
  return tf
@@ -51,6 +54,7 @@ def build_model(
51
54
  hidden_sizes: Sequence[int] | None = None,
52
55
  activation: str = "relu",
53
56
  record_activations: bool = True,
57
+ output_activation: str | None = None,
54
58
  ) -> Any:
55
59
  """Instantiate a neural network for the requested backend ('Pytorch' or 'Tensorflow')."""
56
60
  normalized = type_model.strip().capitalize()
@@ -65,6 +69,7 @@ def build_model(
65
69
  hidden_sizes=hidden_sizes,
66
70
  activation=activation,
67
71
  record_activations=record_activations,
72
+ output_activation=output_activation,
68
73
  )
69
74
  if normalized in ("Tensorflow", "Tf", "Keras"):
70
75
  load_tensorflow(optional=False)
@@ -149,6 +154,7 @@ def clone_model(
149
154
  target_hidden = list(hidden_sizes) if hidden_sizes is not None else inferred_hidden
150
155
  record_act = getattr(model, "record_activations", True)
151
156
  activation = getattr(model, "activation_name", "relu")
157
+ output_activation = getattr(model, "output_activation_name", None)
152
158
 
153
159
  cloned = build_model(
154
160
  target_type,
@@ -157,6 +163,7 @@ def clone_model(
157
163
  hidden_sizes=target_hidden,
158
164
  activation=activation,
159
165
  record_activations=record_act,
166
+ output_activation=output_activation,
160
167
  )
161
168
  set_weights_np(cloned, get_weights_np(model))
162
169
  return cloned
@@ -0,0 +1,120 @@
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
+ output_activation: str | None = None,
30
+ ) -> None:
31
+ super().__init__()
32
+ if input_size <= 0 or output_size <= 0:
33
+ raise ValueError("input_size and output_size must be positive integers.")
34
+
35
+ if hidden_sizes is None or len(hidden_sizes) == 0:
36
+ hidden_sizes = [128]
37
+
38
+ self.input_size = int(input_size)
39
+ self.output_size = int(output_size)
40
+ self.hidden_sizes = [int(h) for h in hidden_sizes]
41
+ self.activation_name = activation.lower()
42
+ if self.activation_name not in _ACTIVATION_MAP:
43
+ raise ValueError(f"Unsupported activation '{activation}'. Choose from {list(_ACTIVATION_MAP.keys())}.")
44
+ self._activation_fn = _ACTIVATION_MAP[self.activation_name]
45
+ self.output_activation_name = output_activation.lower() if output_activation else None
46
+ if self.output_activation_name is not None and self.output_activation_name not in _ACTIVATION_MAP:
47
+ raise ValueError(
48
+ f"Unsupported output_activation '{output_activation}'. Choose from {list(_ACTIVATION_MAP.keys())}."
49
+ )
50
+ self._output_activation_fn = (
51
+ _ACTIVATION_MAP[self.output_activation_name] if self.output_activation_name else None
52
+ )
53
+ self.record_activations = bool(record_activations)
54
+
55
+ self.hidden_layers = nn.ModuleList()
56
+ in_features = self.input_size
57
+ for h in self.hidden_sizes:
58
+ self.hidden_layers.append(nn.Linear(in_features, h))
59
+ in_features = h
60
+
61
+ self.output_layer = nn.Linear(in_features, self.output_size)
62
+ # Aliases preserved for HUD weight inspection & legacy compatibility
63
+ self.fc1 = self.hidden_layers[0]
64
+ if len(self.hidden_layers) >= 2:
65
+ self.fc2 = self.hidden_layers[1]
66
+ self.fc3 = self.output_layer
67
+ else:
68
+ self.fc2 = self.output_layer
69
+ self.fc3 = self.output_layer
70
+ self.activations: np.ndarray | None = None
71
+ self.layer_activations: list[np.ndarray] | None = None
72
+
73
+ @staticmethod
74
+ def _normalize_vec(vec: np.ndarray) -> np.ndarray:
75
+ v = np.asarray(vec, dtype=np.float32).flatten()
76
+ if v.size == 0:
77
+ return v
78
+ if v.size == 1:
79
+ return 1.0 / (1.0 + np.exp(-np.clip(v, -15.0, 15.0)))
80
+ vmin = float(np.min(v))
81
+ vmax = float(np.max(v))
82
+ span = vmax - vmin
83
+ if span > 1e-6:
84
+ return (v - vmin) / span
85
+ return 1.0 / (1.0 + np.exp(-np.clip(v, -15.0, 15.0)))
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ is_single = x.dim() == 1 or (x.dim() >= 2 and x.shape[0] == 1)
89
+ should_record = self.record_activations and (is_single or self.layer_activations is None)
90
+
91
+ if should_record:
92
+ with torch.no_grad():
93
+ x0 = x if x.dim() == 1 else x[0]
94
+ recorded_layers: list[np.ndarray] = [self._normalize_vec(x0.detach().cpu().numpy())]
95
+
96
+ for i, layer in enumerate(self.hidden_layers):
97
+ x = self._activation_fn(layer(x))
98
+ if should_record:
99
+ with torch.no_grad():
100
+ h0 = x if x.dim() == 1 else x[0]
101
+ norm_h = self._normalize_vec(h0.detach().cpu().numpy())
102
+ recorded_layers.append(norm_h)
103
+ if i == 0:
104
+ self.activations = norm_h.reshape(1, -1)
105
+
106
+ out = self.output_layer(x)
107
+ if self._output_activation_fn is not None:
108
+ out = self._output_activation_fn(out)
109
+
110
+ if should_record:
111
+ with torch.no_grad():
112
+ o0 = out if out.dim() == 1 else out[0]
113
+ recorded_layers.append(self._normalize_vec(o0.detach().cpu().numpy()))
114
+ self.layer_activations = recorded_layers
115
+
116
+ return out
117
+
118
+
119
+ # Alias for backward compatibility with projects importing SimpleNN directly
120
+ SimpleNN = SimpleNN_Pytorch
@@ -38,6 +38,7 @@ class SimpleNN_Tensorflow:
38
38
  self.output_layer = layers.Dense(self.output_size)
39
39
  self.fc1 = self.hidden_layers[0]
40
40
  self.activations: np.ndarray | None = None
41
+ self.layer_activations: list[np.ndarray] | None = None
41
42
 
42
43
  inputs = tf.keras.Input(shape=(self.input_size,), dtype=tf.float32)
43
44
  x = inputs
@@ -47,6 +48,20 @@ class SimpleNN_Tensorflow:
47
48
  self._keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
48
49
  self.built = True
49
50
 
51
+ @staticmethod
52
+ def _normalize_vec(vec: np.ndarray) -> np.ndarray:
53
+ v = np.asarray(vec, dtype=np.float32).flatten()
54
+ if v.size == 0:
55
+ return v
56
+ if v.size == 1:
57
+ return 1.0 / (1.0 + np.exp(-np.clip(v, -15.0, 15.0)))
58
+ vmin = float(np.min(v))
59
+ vmax = float(np.max(v))
60
+ span = vmax - vmin
61
+ if span > 1e-6:
62
+ return (v - vmin) / span
63
+ return 1.0 / (1.0 + np.exp(-np.clip(v, -15.0, 15.0)))
64
+
50
65
  @property
51
66
  def trainable_variables(self) -> Any:
52
67
  return self._keras_model.trainable_variables
@@ -69,20 +84,35 @@ class SimpleNN_Tensorflow:
69
84
  x_tensor = tf.convert_to_tensor(x, dtype=tf.float32)
70
85
  if len(x_tensor.shape) == 1:
71
86
  x_tensor = tf.expand_dims(x_tensor, axis=0)
87
+
88
+ is_single = x_tensor.shape[0] == 1
89
+ should_record = self.record_activations and (is_single or self.layer_activations is None)
90
+ recorded_layers: list[np.ndarray] = []
91
+ if should_record:
92
+ try:
93
+ recorded_layers.append(self._normalize_vec(x_tensor[0].numpy()))
94
+ except Exception:
95
+ should_record = False
96
+
72
97
  for i, layer in enumerate(self.hidden_layers):
73
98
  x_tensor = layer(x_tensor)
74
- if i == 0 and self.record_activations:
99
+ if should_record:
75
100
  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
101
+ norm_h = self._normalize_vec(x_tensor[0].numpy())
102
+ recorded_layers.append(norm_h)
103
+ if i == 0:
104
+ self.activations = norm_h.reshape(1, -1)
83
105
  except Exception:
84
106
  pass
85
- return self.output_layer(x_tensor)
107
+
108
+ out = self.output_layer(x_tensor)
109
+ if should_record:
110
+ try:
111
+ recorded_layers.append(self._normalize_vec(out[0].numpy()))
112
+ self.layer_activations = recorded_layers
113
+ except Exception:
114
+ pass
115
+ return out
86
116
 
87
117
  def call(self, x: Any, training: bool = False) -> Any:
88
118
  return self.forward(x)