tensor-optix 2.0.2__tar.gz → 2.0.4__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 (167) hide show
  1. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/PKG-INFO +101 -9
  2. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/README.md +98 -8
  3. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/pyproject.toml +5 -1
  4. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/pytorch/torch_evaluator.py +9 -9
  5. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/tensorflow/tf_evaluator.py +9 -9
  6. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/tf_dqn.py +19 -11
  7. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/tf_ppo.py +9 -6
  8. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/tf_ppo_continuous.py +6 -5
  9. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/tf_sac.py +57 -22
  10. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/tf_td3.py +59 -18
  11. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_dqn.py +21 -9
  12. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_ppo.py +12 -5
  13. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_ppo_continuous.py +8 -5
  14. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_rainbow_dqn.py +18 -10
  15. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_recurrent_ppo.py +19 -1
  16. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_sac.py +50 -13
  17. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/torch_td3.py +46 -15
  18. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/callbacks/tensorboard_callback.py +7 -0
  19. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/callbacks/wandb_callback.py +7 -0
  20. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/cli.py +8 -0
  21. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/config.py +50 -8
  22. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/backoff_scheduler.py +9 -3
  23. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/base_evaluator.py +4 -1
  24. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/checkpoint_registry.py +6 -1
  25. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/diagnostic_controller.py +2 -1
  26. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/ensemble_agent.py +12 -0
  27. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/loop_controller.py +56 -47
  28. tensor_optix-2.0.4/tensor_optix/core/obs_utils.py +120 -0
  29. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/policy_manager.py +32 -2
  30. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/replay_buffer.py +60 -7
  31. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/reward_shape.py +16 -10
  32. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/trajectory_buffer.py +31 -5
  33. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/distributed/async_learner.py +9 -0
  34. tensor_optix-2.0.4/tensor_optix/encoders/__init__.py +15 -0
  35. tensor_optix-2.0.4/tensor_optix/encoders/obs_encoder.py +229 -0
  36. tensor_optix-2.0.4/tensor_optix/encoders/obs_encoder_tf.py +80 -0
  37. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/factory.py +327 -85
  38. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/callback.py +19 -0
  39. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/provenance.py +19 -7
  40. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ml/loss_registry.py +2 -1
  41. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ml/ml_agent.py +12 -0
  42. tensor_optix-2.0.4/tensor_optix/ml_core/__init__.py +53 -0
  43. tensor_optix-2.0.4/tensor_optix/ml_core/adapters/__init__.py +0 -0
  44. tensor_optix-2.0.4/tensor_optix/ml_core/adapters/flax_model.py +230 -0
  45. tensor_optix-2.0.4/tensor_optix/ml_core/adapters/tf_model.py +208 -0
  46. tensor_optix-2.0.4/tensor_optix/ml_core/adapters/torch_model.py +241 -0
  47. tensor_optix-2.0.4/tensor_optix/ml_core/base_model.py +150 -0
  48. tensor_optix-2.0.4/tensor_optix/ml_core/lr_schedules.py +67 -0
  49. tensor_optix-2.0.4/tensor_optix/ml_core/metrics.py +201 -0
  50. tensor_optix-2.0.4/tensor_optix/ml_core/metrics_impl/__init__.py +0 -0
  51. tensor_optix-2.0.4/tensor_optix/ml_core/metrics_impl/classification.py +101 -0
  52. tensor_optix-2.0.4/tensor_optix/ml_core/metrics_impl/regression.py +46 -0
  53. tensor_optix-2.0.4/tensor_optix/ml_core/trainer.py +240 -0
  54. tensor_optix-2.0.4/tensor_optix/ml_core/transfer.py +152 -0
  55. tensor_optix-2.0.4/tensor_optix/multi_agent/__init__.py +34 -0
  56. tensor_optix-2.0.4/tensor_optix/multi_agent/aec_pipeline.py +191 -0
  57. tensor_optix-2.0.4/tensor_optix/multi_agent/multi_agent_episode.py +18 -0
  58. tensor_optix-2.0.4/tensor_optix/multi_agent/multi_agent_runtime.py +53 -0
  59. tensor_optix-2.0.4/tensor_optix/multi_agent/parallel_pipeline.py +145 -0
  60. tensor_optix-2.0.4/tensor_optix/multi_agent/seat_env.py +81 -0
  61. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/selector.py +9 -3
  62. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/agent/graph_agent.py +74 -15
  63. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/controller/topology_controller.py +16 -4
  64. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/graph/neuron_graph.py +58 -2
  65. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/graph/topology_ops.py +51 -16
  66. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/hebbian.py +45 -4
  67. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/neuromodulator.py +12 -0
  68. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizer.py +17 -10
  69. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/backoff_optimizer.py +13 -4
  70. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/spsa_optimizer.py +18 -3
  71. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/pipeline/batch_pipeline.py +5 -0
  72. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/pipeline/live_pipeline.py +30 -6
  73. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/pipeline/vector_pipeline.py +19 -2
  74. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/baseline.py +8 -0
  75. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/live_runtime.py +12 -4
  76. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/pool.py +36 -1
  77. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/worker.py +7 -0
  78. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/selection/selector.py +17 -1
  79. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/simple.py +17 -3
  80. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/grammar.py +8 -0
  81. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/worker.py +14 -0
  82. tensor_optix-2.0.4/tensor_optix/utils/console.py +28 -0
  83. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/PKG-INFO +101 -9
  84. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/SOURCES.txt +24 -0
  85. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/requires.txt +3 -0
  86. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/setup.cfg +0 -0
  87. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/__init__.py +0 -0
  88. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/__init__.py +0 -0
  89. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/jax/__init__.py +0 -0
  90. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/jax/flax_agent.py +0 -0
  91. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/jax/flax_evaluator.py +0 -0
  92. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/pytorch/__init__.py +0 -0
  93. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/pytorch/torch_agent.py +0 -0
  94. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/tensorflow/__init__.py +0 -0
  95. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/adapters/tensorflow/tf_agent.py +0 -0
  96. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/__init__.py +0 -0
  97. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/algorithms/flax_ppo.py +0 -0
  98. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/callbacks/__init__.py +0 -0
  99. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/callbacks/rich_dashboard.py +0 -0
  100. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/__init__.py +0 -0
  101. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/async_callback.py +0 -0
  102. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/base_agent.py +0 -0
  103. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/base_optimizer.py +0 -0
  104. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/base_pipeline.py +0 -0
  105. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/checkpoint_confirmation.py +0 -0
  106. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/device.py +0 -0
  107. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/her_buffer.py +0 -0
  108. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/meta_controller.py +0 -0
  109. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/noisy_linear.py +0 -0
  110. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/normalizers.py +0 -0
  111. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/regime_detector.py +0 -0
  112. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/resume_state.py +0 -0
  113. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/core/types.py +0 -0
  114. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/distributed/__init__.py +0 -0
  115. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/distributed/vtrace.py +0 -0
  116. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/exploration/__init__.py +0 -0
  117. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/exploration/rnd.py +0 -0
  118. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/__init__.py +0 -0
  119. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/records.py +0 -0
  120. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/schema.py +0 -0
  121. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ledger/store.py +0 -0
  122. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ml/__init__.py +0 -0
  123. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/ml/dataset_pipeline.py +0 -0
  124. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/__init__.py +0 -0
  125. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/abstention.py +0 -0
  126. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/features.py +0 -0
  127. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/pooling.py +0 -0
  128. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/nanonets/smalln.py +0 -0
  129. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/__init__.py +0 -0
  130. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/agent/__init__.py +0 -0
  131. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/brain_network.py +0 -0
  132. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/controller/__init__.py +0 -0
  133. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/controller/topology_callback.py +0 -0
  134. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/graph/__init__.py +0 -0
  135. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/graph/neuron.py +0 -0
  136. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/optimizer/__init__.py +0 -0
  137. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/neuroevo/optimizer/topology_aware_adam.py +0 -0
  138. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/__init__.py +0 -0
  139. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/adaptive_optimizer.py +0 -0
  140. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/momentum_optimizer.py +0 -0
  141. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/optimizers/pbt_optimizer.py +0 -0
  142. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/orchestrator.py +0 -0
  143. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/pipeline/__init__.py +0 -0
  144. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/__init__.py +0 -0
  145. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/experiment_stage.py +0 -0
  146. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/observer.py +0 -0
  147. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/runtime/promote.py +0 -0
  148. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/__init__.py +0 -0
  149. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/_mp_common.py +0 -0
  150. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/budget.py +0 -0
  151. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/dedup.py +0 -0
  152. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/isolation.py +0 -0
  153. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/scheduler/retry.py +0 -0
  154. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/selection/__init__.py +0 -0
  155. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/selection/backfill.py +0 -0
  156. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/selection/uncertainty.py +0 -0
  157. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/__init__.py +0 -0
  158. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/candidate.py +0 -0
  159. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/comparator.py +0 -0
  160. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/promotion.py +0 -0
  161. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/strategy/runner.py +0 -0
  162. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/utils/__init__.py +0 -0
  163. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix/utils/window_size.py +0 -0
  164. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/dependency_links.txt +0 -0
  165. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/entry_points.txt +0 -0
  166. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tensor_optix.egg-info/top_level.txt +0 -0
  167. {tensor_optix-2.0.2 → tensor_optix-2.0.4}/tests/test_ml.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tensor-optix
3
- Version: 2.0.2
3
+ Version: 2.0.4
4
4
  Summary: Autonomous training loop for any sequential learning model — PPO, DQN, SAC, TD3, Rainbow DQN, Recurrent PPO for TensorFlow, PyTorch, and JAX/Flax; distributed async actor-learner (IMPALA + V-trace)
5
5
  Author: sup3rus3r
6
6
  License-Expression: MIT
@@ -35,6 +35,8 @@ Requires-Dist: gymnasium[atari]>=1.0.0; extra == "atari"
35
35
  Requires-Dist: ale-py>=0.8; extra == "atari"
36
36
  Provides-Extra: mujoco
37
37
  Requires-Dist: gymnasium[mujoco]>=1.0.0; extra == "mujoco"
38
+ Provides-Extra: pettingzoo
39
+ Requires-Dist: pettingzoo>=1.24.0; extra == "pettingzoo"
38
40
  Provides-Extra: all
39
41
  Requires-Dist: tensorflow>=2.18.0; extra == "all"
40
42
  Requires-Dist: torch>=2.11.0; extra == "all"
@@ -69,13 +71,22 @@ Requires-Dist: torch>=2.11.0; extra == "dev"
69
71
 
70
72
  # tensor-optix
71
73
 
72
- tensor-optix is a training loop framework with statistical convergence control, online hyperparameter optimisation, and an optional neuroevolution subsystem for dynamic topology.
74
+ tensor-optix is a training framework for reinforcement learning and for supervised/unsupervised machine learning. Both have statistical convergence control, online hyperparameter optimisation, and real checkpointing.
73
75
 
74
- The core loop runs your agent against a pipeline, maintains a separate validation signal, and manages four states: ACTIVE, COOLING, DORMANT, and watchdog shutdown. Convergence is detected using a corrected t-test on the smoothed score slope plus lag-1 autocorrelation, not a fixed patience counter. Hyperparameters are updated every episode via SPSA gradient estimates, with automatic routing to momentum-based or sign-only updates depending on the autocorrelation structure of the score landscape. Checkpointing and rollback are driven by the validation signal only, never training score. On DORMANT, a MetaController evaluates the generalization gap and its slope to decide between spawning a policy variant, pruning the ensemble, or stopping.
76
+ It has two parallel cores:
75
77
 
76
- The neuroevo subsystem (`pip install tensor-optix[neuroevo]`) represents the policy as a `NeuronGraph`: a mutable directed graph of heterogeneous scalar neurons (point, GRU, LSTM, trainable-GRU, trainable-LSTM) with variable-delay edges. Weights for excitatory and inhibitory neurons follow softplus Dale's Law: raw parameter θ maps to `softplus(θ)` (excitatory) or `-softplus(θ)` (inhibitory), eliminating gradient dead zones at weight boundaries. `TopologyController` runs as a loop callback and evaluates three independent signals per episode: improvement slope significance, residual autocorrelation structure, and gradient utilization across hidden neurons. All three must cross their thresholds before a grow operation fires. Pruning is by importance score (incident edge weight magnitude times mean absolute activation). Merging is by Pearson correlation of per-episode activation histories. After every structural mutation the controller calls `graph.invalidate_compile()` to reset for the new topology. `TopologyAwareAdam` resets momentum state for parameters affected by any structural change. `BrainNetwork` composes multiple named `NeuronGraph` regions with sparse learnable inter-region edges — when a neuron is pruned from a region, all inter-region edges referencing it are automatically cleaned up. `HebbianHook` accumulates co-activation products across each episode and applies an Oja-style weight update after the PPO gradient step. `NeuromodulatorSignal` maps a `RegimeDetector` output (trending / ranging / volatile) to simultaneous changes in Hebbian learning rate, entropy coefficient, and topology grow/prune thresholds.
78
+ - **RL core**. An episode-driven loop (`LoopController`/`RLOptimizer`) built around `BaseAgent`'s `act()`/`learn()` contract. Statistical convergence control, SPSA-based online hyperparameter tuning, and an optional neuroevolution subsystem for dynamic topology.
79
+ - **ML core** (`tensor_optix.ml_core`). An epoch/batch-driven loop (`Trainer`, wrapped by `BaseMLModel.fit()`) built around a sklearn-style `fit()`/`predict()`/`evaluate()` contract. Real classification metrics (accuracy, precision/recall/F1, confusion matrix) and regression metrics (MAE, RMSE, R²), validation-based early stopping, and checkpointing on the best metric.
77
80
 
78
- The entire system, including neuroevo, is accessed through a six-method `BaseAgent` interface:
81
+ Both cores reuse the same lower-level, algorithm-agnostic machinery: `CheckpointRegistry`, `BackoffScheduler`'s convergence/plateau detection, `SPSAOptimizer`. Each core has its own contract on top because an RL episode and a training epoch aren't the same shape. See [Concepts](https://sup3rus3r.github.io/tensor-optix/getting-started/concepts/).
82
+
83
+ ## RL core
84
+
85
+ The RL loop runs your agent against a pipeline, maintains a separate validation signal, and manages four states: ACTIVE, COOLING, DORMANT, and watchdog shutdown. Convergence is detected via a linear trend fit over the recent score window compared against an adaptive, noise-scaled floor, not a fixed patience counter (see [Concepts](https://sup3rus3r.github.io/tensor-optix/getting-started/concepts/) for the exact math; `BackoffScheduler` is the implementation). Hyperparameters are updated every episode via SPSA gradient estimates, with automatic routing to momentum-based or sign-only updates depending on the autocorrelation structure of the score landscape (`AdaptiveOptimizer`). Checkpointing and rollback are driven by the validation signal only, never training score. On DORMANT, a MetaController evaluates the generalization gap and its slope to decide between spawning a policy variant, pruning the ensemble, or stopping.
86
+
87
+ The neuroevo subsystem (`pip install tensor-optix[neuroevo]`) represents the policy as a `NeuronGraph`: a mutable directed graph of heterogeneous scalar neurons (point, GRU, LSTM, trainable-GRU, trainable-LSTM) with variable-delay edges. Weights for excitatory and inhibitory neurons follow softplus Dale's Law: raw parameter θ maps to `softplus(θ)` (excitatory) or `-softplus(θ)` (inhibitory), eliminating gradient dead zones at weight boundaries. `TopologyController` runs as a loop callback and evaluates three independent signals per episode: improvement slope significance, residual autocorrelation structure, and gradient utilization across hidden neurons. All three must cross their thresholds before a grow operation fires. Pruning is by importance score (incident edge weight magnitude times mean absolute activation). Merging is by Pearson correlation of per-episode activation histories. After every structural mutation the controller calls `graph.invalidate_compile()` to reset for the new topology. `TopologyAwareAdam` resets momentum state for parameters affected by any structural change. `BrainNetwork` composes multiple named `NeuronGraph` regions with sparse learnable inter-region edges. When a neuron is pruned from a region, all inter-region edges referencing it are automatically cleaned up. `HebbianHook` accumulates co-activation products across each episode and applies an Oja-style weight update after the PPO gradient step. `NeuromodulatorSignal` maps a `RegimeDetector` output (trending / ranging / volatile) to simultaneous changes in Hebbian learning rate, entropy coefficient, and topology grow/prune thresholds.
88
+
89
+ The RL core (including neuroevo) is accessed through a six-method `BaseAgent` interface:
79
90
 
80
91
  ```python
81
92
  class BaseAgent(ABC):
@@ -89,6 +100,40 @@ class BaseAgent(ABC):
89
100
 
90
101
  Fifteen agents are included across PyTorch, TensorFlow, and JAX/Flax. Bring your own by implementing the interface above.
91
102
 
103
+ ## ML core
104
+
105
+ The ML loop trains your model for a number of epochs, evaluates on a held-out validation set each epoch, and stops early once the validation metric plateaus. It restores the best checkpoint automatically. It is accessed through a `BaseMLModel` interface, with `fit()` as the one-call entry point built on top:
106
+
107
+ ```python
108
+ class BaseMLModel(ABC):
109
+ def predict(self, X) -> Any: ...
110
+ def train_step(self, batch) -> float: ...
111
+ def evaluate(self, data) -> MLMetrics: ...
112
+ def iter_batches(self, data, batch_size: int): ...
113
+ def save_weights(self, path: str) -> None: ...
114
+ def load_weights(self, path: str) -> None: ...
115
+ # fit(train_data, val_data, epochs, early_stopping_patience, ...) is provided
116
+ ```
117
+
118
+ ```python
119
+ import torch.nn as nn
120
+ from tensor_optix.ml_core import TorchMLModel
121
+
122
+ model = TorchMLModel(
123
+ nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)),
124
+ loss_fn=nn.CrossEntropyLoss(),
125
+ )
126
+ history = model.fit(
127
+ (X_train, y_train), (X_val, y_val),
128
+ epochs=50, early_stopping_patience=5, checkpoint_dir="./checkpoints",
129
+ )
130
+ print(history.val_metrics[-1].metrics) # {'accuracy': 0.94, 'f1_macro': 0.93, ...}
131
+ ```
132
+
133
+ Metrics are auto-detected from the target dtype. Integer/class-index targets get classification metrics (accuracy, per-class and macro precision/recall/F1, confusion matrix). Float targets get regression metrics (MAE, RMSE, R²). Pass `metrics="classification"`, `metrics="regression"`, or a list of custom `(y_true, y_pred) -> float` callables to override. `TorchMLModel`, `TFMLModel`, and `FlaxMLModel` are provided. The Torch and TF adapters accept a raw `(X, y)` array pair or a native `Dataset`/`DataLoader`/`tf.data.Dataset`; the Flax adapter accepts a raw `(X, y)` array pair only. `fit()` also takes `lr_schedule=` (see `tensor_optix.ml_core.lr_schedules`), `augment=` for per-batch data augmentation, and there are `freeze_layers()`/`unfreeze_layers()`/`load_pretrained_backbone()` helpers for transfer learning. See [Train an ML model](https://sup3rus3r.github.io/tensor-optix/guides/ml-core/) for the full guide.
134
+
135
+ There is also an older, RL-loop-based way to train an arbitrary `nn.Module`: `Optimizer(model, dataset)`, which runs the model through the RL loop as a fake episode. See [ML support](#ml-support) below. It predates `ml_core`, is kept for backward compatibility, and has no real classification/regression metrics and no validation-based early stopping. Use `ml_core` for new code.
136
+
92
137
  ---
93
138
 
94
139
  ## Install
@@ -117,7 +162,7 @@ pip install tensor-optix[torch]
117
162
  pip install tensor-optix[all]
118
163
  ```
119
164
 
120
- Environment extras: `[box2d]`, `[atari]`, `[mujoco]`
165
+ Environment extras: `[box2d]`, `[atari]`, `[mujoco]`, `[pettingzoo]` (multi-agent)
121
166
  Logging extras: `[wandb]`, `[tensorboard]`
122
167
  Export: `[onnx]`
123
168
 
@@ -149,7 +194,7 @@ All agents implement `BaseAgent` and are interchangeable with `RLOptimizer`.
149
194
 
150
195
  ### Auto-selection
151
196
 
152
- `make_agent` inspects the environment action space and returns a fully constructed agent. Pass an algorithm name as the first argument, or let it be inferred.
197
+ `make_agent` inspects the environment action space and returns a fully constructed agent. Pass an algorithm name as the first argument, or let it be inferred. Observations may be a flat `Box`, an image `Box` `(H, W, C)` (CNN encoder), or a `Dict` of those (see [Encoders](https://sup3rus3r.github.io/tensor-optix/reference/encoders/)).
153
198
 
154
199
  ```python
155
200
  from tensor_optix import make_agent
@@ -235,6 +280,32 @@ pipeline = VectorBatchPipeline(
235
280
  )
236
281
  ```
237
282
 
283
+ Notes:
284
+
285
+ - `VectorBatchPipeline` works with every built-in agent except `TorchRecurrentPPOAgent`: PPO agents compute GAE per env, and the off-policy agents (DQN, Rainbow, SAC, TD3) build replay transitions per env. Envs are created with Gymnasium's `SAME_STEP` autoreset so no action-ignored "reset" transitions enter the training data.
286
+ - `BatchPipeline` resets a recurrent agent's hidden state (`reset_hidden()`) at every episode boundary.
287
+ - `LivePipeline` applies backpressure: when the consumer is slower than the source, the producer waits instead of dropping samples or restarting the stream.
288
+
289
+ ### Multi-agent (PettingZoo)
290
+
291
+ `pip install tensor-optix[torch,pettingzoo]` adds pipelines for PettingZoo's Parallel and AEC (turn-based) APIs. Each seat is an ordinary agent; a window yields one `EpisodeData` per seat.
292
+
293
+ ```python
294
+ from pettingzoo.classic import rps_v2
295
+ from tensor_optix import make_agent
296
+ from tensor_optix.multi_agent import SeatEnvView, AECMultiAgentPipeline, MultiAgentRunner
297
+
298
+ env = rps_v2.env()
299
+ env.reset(seed=0)
300
+ views = {aid: SeatEnvView(env, aid) for aid in env.possible_agents}
301
+ agents = {aid: make_agent(views[aid]) for aid in env.possible_agents}
302
+
303
+ pipeline = AECMultiAgentPipeline(env, agents, window_size=400, views=views)
304
+ MultiAgentRunner(pipeline, agents).run(max_windows=500)
305
+ ```
306
+
307
+ In turn-based games each reward (including the terminal win/loss) is credited to the action that earned it. `MultiAgentRunner` is a minimal collect/learn driver - it does not run the convergence/checkpoint state machine. See [Multi-agent training](https://sup3rus3r.github.io/tensor-optix/guides/multi-agent/).
308
+
238
309
  ---
239
310
 
240
311
  ## The loop
@@ -264,7 +335,20 @@ opt.best_snapshot # -> PolicySnapshot: best weights + EvalMetrics + Hyperparam
264
335
 
265
336
  Loop state transitions: `ACTIVE` -> `COOLING` -> `DORMANT` -> watchdog shutdown or policy spawn.
266
337
 
267
- On shutdown the loop restores best-known weights, not the final checkpoint.
338
+ - Every non-improving eval counts toward `COOLING`/`DORMANT`, for on-policy and off-policy agents alike. While the score is flat the eval interval backs off (`backoff_factor`, default 2.0); set `backoff_factor=1.0` to evaluate every window.
339
+ - At `DORMANT` the loop stops by default. A `PolicyManagerCallback` with spawn budget remaining spawns a variant instead and training continues.
340
+ - `rollback_on_degradation=True` restores the best checkpoint when a degradation is confirmed (`min_consecutive_degradations` consecutive evals below `degradation_threshold x best`), for on-policy agents only - off-policy agents keep their weights because their replay buffer would immediately pull a restored policy back.
341
+ - On shutdown the loop restores best-known weights, not the final checkpoint.
342
+ - `verbose=True` prints a per-eval diagnostic block; it is safe on consoles that cannot render the box-drawing glyphs (they degrade to `?`).
343
+
344
+ ### YAML / CLI
345
+
346
+ ```bash
347
+ tensor-optix validate config.yaml
348
+ tensor-optix train config.yaml agent.learning_rate=1e-3 optimizer.max_episodes=200
349
+ ```
350
+
351
+ The `algorithm` key selects the agent class and must be buildable for the env (e.g. `TorchDQNAgent` needs a discrete action space; a mismatch is a build error, not a silent substitution). See [Configure via YAML / CLI](https://sup3rus3r.github.io/tensor-optix/guides/cli-config/).
268
352
 
269
353
  ---
270
354
 
@@ -327,12 +411,14 @@ best_config = orch.run()
327
411
  from tensor_optix import PolicyManager
328
412
 
329
413
  pm = PolicyManager(registry, max_spawns=4)
330
- cb = pm.as_callback(agent, agent_factory=make_agent)
414
+ cb = pm.as_callback(agent, agent_factory=lambda: make_agent(env)) # zero-argument factory
331
415
  cb.set_stop_fn(opt.stop)
332
416
  opt.add_callback(cb)
333
417
  opt.run()
334
418
  ```
335
419
 
420
+ Each `DORMANT` event with budget remaining spawns a variant and training continues; once the budget is exhausted the callback stops the loop with the best weights restored. A multi-member `EnsembleAgent` combines policies at inference time - for discrete PPO members `act()` returns the averaged probability vector, which you sample or `argmax`.
421
+
336
422
  ---
337
423
 
338
424
  ## Callbacks
@@ -605,6 +691,8 @@ graph.invalidate_compile()
605
691
 
606
692
  ## ML support
607
693
 
694
+ > **Use [`tensor_optix.ml_core`](#ml-core) for new code.** The `Optimizer(model, dataset)` path below is the original way to train an arbitrary `nn.Module`. It runs the model through the RL loop's `BaseAgent`/`RLOptimizer` machinery by treating each mini-batch as a fake RL episode (`reward = -loss`). It is deprecated but kept working for backward compatibility — `MLAgent` emits a `DeprecationWarning` pointing to `ml_core` on construction, and there is no removal planned. It has no real classification/regression metrics (checkpointing and rollback compare mean "episode return," which is just negative loss) and no validation-split-based early stopping. `ml_core`'s `BaseMLModel`/`Trainer` reuse the same convergence/checkpointing machinery through a real `fit()`/`evaluate()` contract with real metrics.
695
+
608
696
  tensor-optix also supports general ML training via `Optimizer`. Pass any `nn.Module` and a PyTorch `Dataset` or `DataLoader` — the same SPSA hyperparameter tuning, rollback on degradation, convergence detection, and checkpointing apply automatically.
609
697
 
610
698
  ```python
@@ -741,6 +829,8 @@ store.finalize_experiment(record.experiment_id, state=ExperimentState.COMPLETED)
741
829
 
742
830
  Writes are idempotent on `experiment_id`, and every method opens a short, single-statement transaction — nothing here ever holds a lock for the duration of training.
743
831
 
832
+ To record an ordinary training run, attach `ExperimentLedgerCallback(store, task_env=..., algorithm=..., checkpoint_dir=...)` (from `tensor_optix.ledger.callback`) to `RLOptimizer`. A run that raises is finalized `FAILED` automatically; an interrupted one `CANCELLED`.
833
+
744
834
  ### Concurrent trial scheduler
745
835
 
746
836
  `ConcurrentTrialScheduler` runs multiple Optuna trials as real OS processes, with the parent process as sole owner of the Optuna study and the ledger.
@@ -757,6 +847,8 @@ scheduler = ConcurrentTrialScheduler(
757
847
  best_params, best_score = scheduler.run()
758
848
  ```
759
849
 
850
+ A worker that dies without reporting (OOM-kill, crash) is detected, retried up to `max_retries` times, and then recorded as `FAILED` - the scheduler never waits on a dead process.
851
+
760
852
  ### Cross-task transfer (Nanonets)
761
853
 
762
854
  `NanonetsSelector` pools evidence from other tasks' ledger history when deciding how to allocate a new task's trial budget — but only when a conservative abstention gate confirms a source task's data is actually comparable (median performance at or above the target's own 95th percentile, both normalized against each task's own solve threshold so differently-scaled/signed scores are never compared on raw terms). When nothing passes the gate, it falls back to the non-learned baseline rather than guess.
@@ -1,12 +1,21 @@
1
1
  # tensor-optix
2
2
 
3
- tensor-optix is a training loop framework with statistical convergence control, online hyperparameter optimisation, and an optional neuroevolution subsystem for dynamic topology.
3
+ tensor-optix is a training framework for reinforcement learning and for supervised/unsupervised machine learning. Both have statistical convergence control, online hyperparameter optimisation, and real checkpointing.
4
4
 
5
- The core loop runs your agent against a pipeline, maintains a separate validation signal, and manages four states: ACTIVE, COOLING, DORMANT, and watchdog shutdown. Convergence is detected using a corrected t-test on the smoothed score slope plus lag-1 autocorrelation, not a fixed patience counter. Hyperparameters are updated every episode via SPSA gradient estimates, with automatic routing to momentum-based or sign-only updates depending on the autocorrelation structure of the score landscape. Checkpointing and rollback are driven by the validation signal only, never training score. On DORMANT, a MetaController evaluates the generalization gap and its slope to decide between spawning a policy variant, pruning the ensemble, or stopping.
5
+ It has two parallel cores:
6
6
 
7
- The neuroevo subsystem (`pip install tensor-optix[neuroevo]`) represents the policy as a `NeuronGraph`: a mutable directed graph of heterogeneous scalar neurons (point, GRU, LSTM, trainable-GRU, trainable-LSTM) with variable-delay edges. Weights for excitatory and inhibitory neurons follow softplus Dale's Law: raw parameter θ maps to `softplus(θ)` (excitatory) or `-softplus(θ)` (inhibitory), eliminating gradient dead zones at weight boundaries. `TopologyController` runs as a loop callback and evaluates three independent signals per episode: improvement slope significance, residual autocorrelation structure, and gradient utilization across hidden neurons. All three must cross their thresholds before a grow operation fires. Pruning is by importance score (incident edge weight magnitude times mean absolute activation). Merging is by Pearson correlation of per-episode activation histories. After every structural mutation the controller calls `graph.invalidate_compile()` to reset for the new topology. `TopologyAwareAdam` resets momentum state for parameters affected by any structural change. `BrainNetwork` composes multiple named `NeuronGraph` regions with sparse learnable inter-region edges — when a neuron is pruned from a region, all inter-region edges referencing it are automatically cleaned up. `HebbianHook` accumulates co-activation products across each episode and applies an Oja-style weight update after the PPO gradient step. `NeuromodulatorSignal` maps a `RegimeDetector` output (trending / ranging / volatile) to simultaneous changes in Hebbian learning rate, entropy coefficient, and topology grow/prune thresholds.
7
+ - **RL core**. An episode-driven loop (`LoopController`/`RLOptimizer`) built around `BaseAgent`'s `act()`/`learn()` contract. Statistical convergence control, SPSA-based online hyperparameter tuning, and an optional neuroevolution subsystem for dynamic topology.
8
+ - **ML core** (`tensor_optix.ml_core`). An epoch/batch-driven loop (`Trainer`, wrapped by `BaseMLModel.fit()`) built around a sklearn-style `fit()`/`predict()`/`evaluate()` contract. Real classification metrics (accuracy, precision/recall/F1, confusion matrix) and regression metrics (MAE, RMSE, R²), validation-based early stopping, and checkpointing on the best metric.
8
9
 
9
- The entire system, including neuroevo, is accessed through a six-method `BaseAgent` interface:
10
+ Both cores reuse the same lower-level, algorithm-agnostic machinery: `CheckpointRegistry`, `BackoffScheduler`'s convergence/plateau detection, `SPSAOptimizer`. Each core has its own contract on top because an RL episode and a training epoch aren't the same shape. See [Concepts](https://sup3rus3r.github.io/tensor-optix/getting-started/concepts/).
11
+
12
+ ## RL core
13
+
14
+ The RL loop runs your agent against a pipeline, maintains a separate validation signal, and manages four states: ACTIVE, COOLING, DORMANT, and watchdog shutdown. Convergence is detected via a linear trend fit over the recent score window compared against an adaptive, noise-scaled floor, not a fixed patience counter (see [Concepts](https://sup3rus3r.github.io/tensor-optix/getting-started/concepts/) for the exact math; `BackoffScheduler` is the implementation). Hyperparameters are updated every episode via SPSA gradient estimates, with automatic routing to momentum-based or sign-only updates depending on the autocorrelation structure of the score landscape (`AdaptiveOptimizer`). Checkpointing and rollback are driven by the validation signal only, never training score. On DORMANT, a MetaController evaluates the generalization gap and its slope to decide between spawning a policy variant, pruning the ensemble, or stopping.
15
+
16
+ The neuroevo subsystem (`pip install tensor-optix[neuroevo]`) represents the policy as a `NeuronGraph`: a mutable directed graph of heterogeneous scalar neurons (point, GRU, LSTM, trainable-GRU, trainable-LSTM) with variable-delay edges. Weights for excitatory and inhibitory neurons follow softplus Dale's Law: raw parameter θ maps to `softplus(θ)` (excitatory) or `-softplus(θ)` (inhibitory), eliminating gradient dead zones at weight boundaries. `TopologyController` runs as a loop callback and evaluates three independent signals per episode: improvement slope significance, residual autocorrelation structure, and gradient utilization across hidden neurons. All three must cross their thresholds before a grow operation fires. Pruning is by importance score (incident edge weight magnitude times mean absolute activation). Merging is by Pearson correlation of per-episode activation histories. After every structural mutation the controller calls `graph.invalidate_compile()` to reset for the new topology. `TopologyAwareAdam` resets momentum state for parameters affected by any structural change. `BrainNetwork` composes multiple named `NeuronGraph` regions with sparse learnable inter-region edges. When a neuron is pruned from a region, all inter-region edges referencing it are automatically cleaned up. `HebbianHook` accumulates co-activation products across each episode and applies an Oja-style weight update after the PPO gradient step. `NeuromodulatorSignal` maps a `RegimeDetector` output (trending / ranging / volatile) to simultaneous changes in Hebbian learning rate, entropy coefficient, and topology grow/prune thresholds.
17
+
18
+ The RL core (including neuroevo) is accessed through a six-method `BaseAgent` interface:
10
19
 
11
20
  ```python
12
21
  class BaseAgent(ABC):
@@ -20,6 +29,40 @@ class BaseAgent(ABC):
20
29
 
21
30
  Fifteen agents are included across PyTorch, TensorFlow, and JAX/Flax. Bring your own by implementing the interface above.
22
31
 
32
+ ## ML core
33
+
34
+ The ML loop trains your model for a number of epochs, evaluates on a held-out validation set each epoch, and stops early once the validation metric plateaus. It restores the best checkpoint automatically. It is accessed through a `BaseMLModel` interface, with `fit()` as the one-call entry point built on top:
35
+
36
+ ```python
37
+ class BaseMLModel(ABC):
38
+ def predict(self, X) -> Any: ...
39
+ def train_step(self, batch) -> float: ...
40
+ def evaluate(self, data) -> MLMetrics: ...
41
+ def iter_batches(self, data, batch_size: int): ...
42
+ def save_weights(self, path: str) -> None: ...
43
+ def load_weights(self, path: str) -> None: ...
44
+ # fit(train_data, val_data, epochs, early_stopping_patience, ...) is provided
45
+ ```
46
+
47
+ ```python
48
+ import torch.nn as nn
49
+ from tensor_optix.ml_core import TorchMLModel
50
+
51
+ model = TorchMLModel(
52
+ nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)),
53
+ loss_fn=nn.CrossEntropyLoss(),
54
+ )
55
+ history = model.fit(
56
+ (X_train, y_train), (X_val, y_val),
57
+ epochs=50, early_stopping_patience=5, checkpoint_dir="./checkpoints",
58
+ )
59
+ print(history.val_metrics[-1].metrics) # {'accuracy': 0.94, 'f1_macro': 0.93, ...}
60
+ ```
61
+
62
+ Metrics are auto-detected from the target dtype. Integer/class-index targets get classification metrics (accuracy, per-class and macro precision/recall/F1, confusion matrix). Float targets get regression metrics (MAE, RMSE, R²). Pass `metrics="classification"`, `metrics="regression"`, or a list of custom `(y_true, y_pred) -> float` callables to override. `TorchMLModel`, `TFMLModel`, and `FlaxMLModel` are provided. The Torch and TF adapters accept a raw `(X, y)` array pair or a native `Dataset`/`DataLoader`/`tf.data.Dataset`; the Flax adapter accepts a raw `(X, y)` array pair only. `fit()` also takes `lr_schedule=` (see `tensor_optix.ml_core.lr_schedules`), `augment=` for per-batch data augmentation, and there are `freeze_layers()`/`unfreeze_layers()`/`load_pretrained_backbone()` helpers for transfer learning. See [Train an ML model](https://sup3rus3r.github.io/tensor-optix/guides/ml-core/) for the full guide.
63
+
64
+ There is also an older, RL-loop-based way to train an arbitrary `nn.Module`: `Optimizer(model, dataset)`, which runs the model through the RL loop as a fake episode. See [ML support](#ml-support) below. It predates `ml_core`, is kept for backward compatibility, and has no real classification/regression metrics and no validation-based early stopping. Use `ml_core` for new code.
65
+
23
66
  ---
24
67
 
25
68
  ## Install
@@ -48,7 +91,7 @@ pip install tensor-optix[torch]
48
91
  pip install tensor-optix[all]
49
92
  ```
50
93
 
51
- Environment extras: `[box2d]`, `[atari]`, `[mujoco]`
94
+ Environment extras: `[box2d]`, `[atari]`, `[mujoco]`, `[pettingzoo]` (multi-agent)
52
95
  Logging extras: `[wandb]`, `[tensorboard]`
53
96
  Export: `[onnx]`
54
97
 
@@ -80,7 +123,7 @@ All agents implement `BaseAgent` and are interchangeable with `RLOptimizer`.
80
123
 
81
124
  ### Auto-selection
82
125
 
83
- `make_agent` inspects the environment action space and returns a fully constructed agent. Pass an algorithm name as the first argument, or let it be inferred.
126
+ `make_agent` inspects the environment action space and returns a fully constructed agent. Pass an algorithm name as the first argument, or let it be inferred. Observations may be a flat `Box`, an image `Box` `(H, W, C)` (CNN encoder), or a `Dict` of those (see [Encoders](https://sup3rus3r.github.io/tensor-optix/reference/encoders/)).
84
127
 
85
128
  ```python
86
129
  from tensor_optix import make_agent
@@ -166,6 +209,32 @@ pipeline = VectorBatchPipeline(
166
209
  )
167
210
  ```
168
211
 
212
+ Notes:
213
+
214
+ - `VectorBatchPipeline` works with every built-in agent except `TorchRecurrentPPOAgent`: PPO agents compute GAE per env, and the off-policy agents (DQN, Rainbow, SAC, TD3) build replay transitions per env. Envs are created with Gymnasium's `SAME_STEP` autoreset so no action-ignored "reset" transitions enter the training data.
215
+ - `BatchPipeline` resets a recurrent agent's hidden state (`reset_hidden()`) at every episode boundary.
216
+ - `LivePipeline` applies backpressure: when the consumer is slower than the source, the producer waits instead of dropping samples or restarting the stream.
217
+
218
+ ### Multi-agent (PettingZoo)
219
+
220
+ `pip install tensor-optix[torch,pettingzoo]` adds pipelines for PettingZoo's Parallel and AEC (turn-based) APIs. Each seat is an ordinary agent; a window yields one `EpisodeData` per seat.
221
+
222
+ ```python
223
+ from pettingzoo.classic import rps_v2
224
+ from tensor_optix import make_agent
225
+ from tensor_optix.multi_agent import SeatEnvView, AECMultiAgentPipeline, MultiAgentRunner
226
+
227
+ env = rps_v2.env()
228
+ env.reset(seed=0)
229
+ views = {aid: SeatEnvView(env, aid) for aid in env.possible_agents}
230
+ agents = {aid: make_agent(views[aid]) for aid in env.possible_agents}
231
+
232
+ pipeline = AECMultiAgentPipeline(env, agents, window_size=400, views=views)
233
+ MultiAgentRunner(pipeline, agents).run(max_windows=500)
234
+ ```
235
+
236
+ In turn-based games each reward (including the terminal win/loss) is credited to the action that earned it. `MultiAgentRunner` is a minimal collect/learn driver - it does not run the convergence/checkpoint state machine. See [Multi-agent training](https://sup3rus3r.github.io/tensor-optix/guides/multi-agent/).
237
+
169
238
  ---
170
239
 
171
240
  ## The loop
@@ -195,7 +264,20 @@ opt.best_snapshot # -> PolicySnapshot: best weights + EvalMetrics + Hyperparam
195
264
 
196
265
  Loop state transitions: `ACTIVE` -> `COOLING` -> `DORMANT` -> watchdog shutdown or policy spawn.
197
266
 
198
- On shutdown the loop restores best-known weights, not the final checkpoint.
267
+ - Every non-improving eval counts toward `COOLING`/`DORMANT`, for on-policy and off-policy agents alike. While the score is flat the eval interval backs off (`backoff_factor`, default 2.0); set `backoff_factor=1.0` to evaluate every window.
268
+ - At `DORMANT` the loop stops by default. A `PolicyManagerCallback` with spawn budget remaining spawns a variant instead and training continues.
269
+ - `rollback_on_degradation=True` restores the best checkpoint when a degradation is confirmed (`min_consecutive_degradations` consecutive evals below `degradation_threshold x best`), for on-policy agents only - off-policy agents keep their weights because their replay buffer would immediately pull a restored policy back.
270
+ - On shutdown the loop restores best-known weights, not the final checkpoint.
271
+ - `verbose=True` prints a per-eval diagnostic block; it is safe on consoles that cannot render the box-drawing glyphs (they degrade to `?`).
272
+
273
+ ### YAML / CLI
274
+
275
+ ```bash
276
+ tensor-optix validate config.yaml
277
+ tensor-optix train config.yaml agent.learning_rate=1e-3 optimizer.max_episodes=200
278
+ ```
279
+
280
+ The `algorithm` key selects the agent class and must be buildable for the env (e.g. `TorchDQNAgent` needs a discrete action space; a mismatch is a build error, not a silent substitution). See [Configure via YAML / CLI](https://sup3rus3r.github.io/tensor-optix/guides/cli-config/).
199
281
 
200
282
  ---
201
283
 
@@ -258,12 +340,14 @@ best_config = orch.run()
258
340
  from tensor_optix import PolicyManager
259
341
 
260
342
  pm = PolicyManager(registry, max_spawns=4)
261
- cb = pm.as_callback(agent, agent_factory=make_agent)
343
+ cb = pm.as_callback(agent, agent_factory=lambda: make_agent(env)) # zero-argument factory
262
344
  cb.set_stop_fn(opt.stop)
263
345
  opt.add_callback(cb)
264
346
  opt.run()
265
347
  ```
266
348
 
349
+ Each `DORMANT` event with budget remaining spawns a variant and training continues; once the budget is exhausted the callback stops the loop with the best weights restored. A multi-member `EnsembleAgent` combines policies at inference time - for discrete PPO members `act()` returns the averaged probability vector, which you sample or `argmax`.
350
+
267
351
  ---
268
352
 
269
353
  ## Callbacks
@@ -536,6 +620,8 @@ graph.invalidate_compile()
536
620
 
537
621
  ## ML support
538
622
 
623
+ > **Use [`tensor_optix.ml_core`](#ml-core) for new code.** The `Optimizer(model, dataset)` path below is the original way to train an arbitrary `nn.Module`. It runs the model through the RL loop's `BaseAgent`/`RLOptimizer` machinery by treating each mini-batch as a fake RL episode (`reward = -loss`). It is deprecated but kept working for backward compatibility — `MLAgent` emits a `DeprecationWarning` pointing to `ml_core` on construction, and there is no removal planned. It has no real classification/regression metrics (checkpointing and rollback compare mean "episode return," which is just negative loss) and no validation-split-based early stopping. `ml_core`'s `BaseMLModel`/`Trainer` reuse the same convergence/checkpointing machinery through a real `fit()`/`evaluate()` contract with real metrics.
624
+
539
625
  tensor-optix also supports general ML training via `Optimizer`. Pass any `nn.Module` and a PyTorch `Dataset` or `DataLoader` — the same SPSA hyperparameter tuning, rollback on degradation, convergence detection, and checkpointing apply automatically.
540
626
 
541
627
  ```python
@@ -672,6 +758,8 @@ store.finalize_experiment(record.experiment_id, state=ExperimentState.COMPLETED)
672
758
 
673
759
  Writes are idempotent on `experiment_id`, and every method opens a short, single-statement transaction — nothing here ever holds a lock for the duration of training.
674
760
 
761
+ To record an ordinary training run, attach `ExperimentLedgerCallback(store, task_env=..., algorithm=..., checkpoint_dir=...)` (from `tensor_optix.ledger.callback`) to `RLOptimizer`. A run that raises is finalized `FAILED` automatically; an interrupted one `CANCELLED`.
762
+
675
763
  ### Concurrent trial scheduler
676
764
 
677
765
  `ConcurrentTrialScheduler` runs multiple Optuna trials as real OS processes, with the parent process as sole owner of the Optuna study and the ledger.
@@ -688,6 +776,8 @@ scheduler = ConcurrentTrialScheduler(
688
776
  best_params, best_score = scheduler.run()
689
777
  ```
690
778
 
779
+ A worker that dies without reporting (OOM-kill, crash) is detected, retried up to `max_retries` times, and then recorded as `FAILED` - the scheduler never waits on a dead process.
780
+
691
781
  ### Cross-task transfer (Nanonets)
692
782
 
693
783
  `NanonetsSelector` pools evidence from other tasks' ledger history when deciding how to allocate a new task's trial budget — but only when a conservative abstention gate confirms a source task's data is actually comparable (median performance at or above the target's own 95th percentile, both normalized against each task's own solve threshold so differently-scaled/signed scores are never compared on raw terms). When nothing passes the gate, it falls back to the non-learned baseline rather than guess.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tensor-optix"
7
- version = "2.0.2"
7
+ version = "2.0.4"
8
8
  description = "Autonomous training loop for any sequential learning model — PPO, DQN, SAC, TD3, Rainbow DQN, Recurrent PPO for TensorFlow, PyTorch, and JAX/Flax; distributed async actor-learner (IMPALA + V-trace)"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -60,6 +60,10 @@ atari = [
60
60
  mujoco = [
61
61
  "gymnasium[mujoco]>=1.0.0",
62
62
  ]
63
+ # Multi-agent environments (tensor_optix.multi_agent)
64
+ pettingzoo = [
65
+ "pettingzoo>=1.24.0",
66
+ ]
63
67
  # Convenience bundles
64
68
  all = [
65
69
  "tensorflow>=2.18.0",
@@ -1,6 +1,7 @@
1
1
  import numpy as np
2
2
  from typing import Callable, Optional
3
3
  from tensor_optix.core.base_evaluator import BaseEvaluator
4
+ from tensor_optix.core.reward_shape import split_episode_returns
4
5
  from tensor_optix.core.types import EpisodeData, EvalMetrics
5
6
 
6
7
 
@@ -39,7 +40,8 @@ class TorchEvaluator(BaseEvaluator):
39
40
  if self._primary_score_fn is not None:
40
41
  primary = float(self._primary_score_fn(episode_data, train_diagnostics))
41
42
  else:
42
- primary = self._mean_episode_return(rewards, dones)
43
+ n_envs = int((episode_data.metadata or {}).get("n_envs", 1))
44
+ primary = self._mean_episode_return(rewards, dones, n_envs)
43
45
 
44
46
  metrics = {
45
47
  "primary_score": primary,
@@ -54,20 +56,18 @@ class TorchEvaluator(BaseEvaluator):
54
56
  episode_id=episode_data.episode_id)
55
57
 
56
58
  @staticmethod
57
- def _mean_episode_return(rewards: np.ndarray, dones: list) -> float:
59
+ def _mean_episode_return(rewards: np.ndarray, dones: list, n_envs: int = 1) -> float:
58
60
  """
59
61
  Compute mean return of episodes that completed in this window.
60
62
  dones should be terminated OR truncated — both signal an episode
61
63
  boundary. Falls back to mean per-step reward only if the window
62
64
  contains a single incomplete episode (very long envs, early training).
63
65
  """
64
- episode_returns = []
65
- current = 0.0
66
- for r, done in zip(rewards, dones):
67
- current += float(r)
68
- if done:
69
- episode_returns.append(current)
70
- current = 0.0
66
+ # Per-env accumulation: a VectorBatchPipeline window interleaves
67
+ # n_envs envs, and each episode's return must only sum its own env.
68
+ episode_returns = [
69
+ float(np.sum(seg)) for seg in split_episode_returns(rewards, dones, n_envs)
70
+ ]
71
71
  if episode_returns:
72
72
  return float(np.mean(episode_returns))
73
73
  return float(rewards.mean())
@@ -1,5 +1,6 @@
1
1
  import numpy as np
2
2
  from tensor_optix.core.base_evaluator import BaseEvaluator
3
+ from tensor_optix.core.reward_shape import split_episode_returns
3
4
  from tensor_optix.core.types import EpisodeData, EvalMetrics
4
5
 
5
6
 
@@ -36,7 +37,8 @@ class TFEvaluator(BaseEvaluator):
36
37
  if self._primary_score_fn is not None:
37
38
  primary = float(self._primary_score_fn(episode_data, train_diagnostics))
38
39
  else:
39
- primary = self._mean_episode_return(rewards, dones)
40
+ n_envs = int((episode_data.metadata or {}).get("n_envs", 1))
41
+ primary = self._mean_episode_return(rewards, dones, n_envs)
40
42
 
41
43
  metrics = {
42
44
  "primary_score": primary,
@@ -51,20 +53,18 @@ class TFEvaluator(BaseEvaluator):
51
53
  episode_id=episode_data.episode_id)
52
54
 
53
55
  @staticmethod
54
- def _mean_episode_return(rewards: np.ndarray, dones: list) -> float:
56
+ def _mean_episode_return(rewards: np.ndarray, dones: list, n_envs: int = 1) -> float:
55
57
  """
56
58
  Compute mean return of episodes that completed in this window.
57
59
  dones should be terminated OR truncated — both signal an episode
58
60
  boundary. Falls back to mean per-step reward only if the window
59
61
  contains a single incomplete episode (very long envs, early training).
60
62
  """
61
- episode_returns = []
62
- current = 0.0
63
- for r, done in zip(rewards, dones):
64
- current += float(r)
65
- if done:
66
- episode_returns.append(current)
67
- current = 0.0
63
+ # Per-env accumulation: a VectorBatchPipeline window interleaves
64
+ # n_envs envs, and each episode's return must only sum its own env.
65
+ episode_returns = [
66
+ float(np.sum(seg)) for seg in split_episode_returns(rewards, dones, n_envs)
67
+ ]
68
68
  if episode_returns:
69
69
  return float(np.mean(episode_returns))
70
70
  return float(rewards.mean())
@@ -6,7 +6,8 @@ import tensorflow as tf
6
6
 
7
7
  from tensor_optix.core.base_agent import BaseAgent
8
8
  from tensor_optix.core.types import EpisodeData, HyperparamSet
9
- from tensor_optix.core.replay_buffer import PrioritizedReplayBuffer
9
+ from tensor_optix.core.replay_buffer import PrioritizedReplayBuffer, episode_n_envs, window_transition_pairs
10
+ from tensor_optix.core.obs_utils import to_batch_numpy, to_tf_batch, already_batched_to_tf, batch_index
10
11
 
11
12
 
12
13
  class TFDQNAgent(BaseAgent):
@@ -97,7 +98,7 @@ class TFDQNAgent(BaseAgent):
97
98
  epsilon = float(self._hyperparams.params.get("epsilon", 0.1))
98
99
  if np.random.random() < epsilon:
99
100
  return np.random.randint(self._n_actions)
100
- obs = tf.cast(np.atleast_2d(observation), tf.float32)
101
+ obs = to_tf_batch(observation)
101
102
  q_values = self._q(obs, training=False)
102
103
  return int(tf.argmax(q_values, axis=-1).numpy()[0])
103
104
 
@@ -109,18 +110,25 @@ class TFDQNAgent(BaseAgent):
109
110
  epsilon_decay = float(hp.get("epsilon_decay", 0.995))
110
111
  epsilon_min = float(hp.get("epsilon_min", 0.05))
111
112
 
112
- obs_arr = np.array(episode_data.observations, dtype=np.float32)
113
+ # DQN pushes the RAW observation into the buffer (not pre-encoded)
114
+ # -- same single-network constraint as TorchDQNAgent, see
115
+ # torch_dqn.py's learn() comment for the full rationale.
116
+ obs_arr = to_batch_numpy(list(episode_data.observations))
113
117
  act_arr = episode_data.actions
114
118
  rew_arr = episode_data.rewards
115
119
  done_arr = episode_data.dones
116
120
 
117
121
  T = len(rew_arr)
118
- for t in range(T - 1):
119
- self._buffer.push(
120
- obs_arr[t], int(act_arr[t]), float(rew_arr[t]),
121
- obs_arr[t + 1], bool(done_arr[t]),
122
- )
123
- self._buffer.flush_episode()
122
+ # Pair each step with the NEXT step of the same environment. With a
123
+ # VectorBatchPipeline window the flat arrays interleave n_envs envs
124
+ # ([t * n_envs + i]), so index t + 1 belongs to a different env.
125
+ for env_pairs in window_transition_pairs(T, episode_n_envs(episode_data)):
126
+ for t, t_next in env_pairs:
127
+ self._buffer.push(
128
+ batch_index(obs_arr, t), int(act_arr[t]), float(rew_arr[t]),
129
+ batch_index(obs_arr, t_next), bool(done_arr[t]),
130
+ )
131
+ self._buffer.flush_episode()
124
132
 
125
133
  self._learn_calls += 1
126
134
  new_eps = max(epsilon_min, float(hp.get("epsilon", 1.0)) * epsilon_decay)
@@ -138,10 +146,10 @@ class TFDQNAgent(BaseAgent):
138
146
 
139
147
  for _ in range(n_updates):
140
148
  obs_b, act_b, rew_b, next_obs_b, done_b, weights, indices, n_steps = self._buffer.sample(batch_size)
141
- obs_b = tf.cast(obs_b, tf.float32)
149
+ obs_b = already_batched_to_tf(obs_b)
142
150
  act_b = tf.cast(act_b, tf.int32)
143
151
  rew_b = tf.cast(rew_b, tf.float32)
144
- next_obs_b = tf.cast(next_obs_b, tf.float32)
152
+ next_obs_b = already_batched_to_tf(next_obs_b)
145
153
  done_b = tf.cast(done_b, tf.float32)
146
154
  weights = tf.cast(weights, tf.float32)
147
155
  gammas_n = tf.cast(gamma ** n_steps.astype(np.float32), tf.float32)
@@ -4,6 +4,7 @@ import tensorflow as tf
4
4
  from tensor_optix.core.base_agent import BaseAgent
5
5
  from tensor_optix.core.types import EpisodeData, HyperparamSet
6
6
  from tensor_optix.core.trajectory_buffer import compute_gae, make_minibatches, resolve_gae_bootstrap
7
+ from tensor_optix.core.obs_utils import to_batch_numpy, to_tf_batch, already_batched_to_tf
7
8
 
8
9
 
9
10
  class TFPPOAgent(BaseAgent):
@@ -89,7 +90,7 @@ class TFPPOAgent(BaseAgent):
89
90
  Sample action from π(·|obs), cache log_prob and V(obs) for learn().
90
91
  Returns a Python int (action index).
91
92
  """
92
- obs = tf.cast(np.atleast_2d(observation), tf.float32)
93
+ obs = to_tf_batch(observation)
93
94
 
94
95
  logits = self._actor(obs, training=False) # [1, n_actions]
95
96
  log_probs_all = tf.nn.log_softmax(logits) # [1, n_actions]
@@ -98,7 +99,9 @@ class TFPPOAgent(BaseAgent):
98
99
 
99
100
  value = float(tf.squeeze(self._critic(obs, training=False)).numpy())
100
101
 
101
- self._cache_obs.append(np.squeeze(observation))
102
+ # Cache the raw observation -- learn() re-batches via
103
+ # to_batch_numpy(), which handles both array and dict observations.
104
+ self._cache_obs.append(np.squeeze(observation) if not isinstance(observation, dict) else observation)
102
105
  self._cache_log_probs.append(log_prob)
103
106
  self._cache_values.append(value)
104
107
 
@@ -134,7 +137,7 @@ class TFPPOAgent(BaseAgent):
134
137
  f"Cache underflow: expected >= {T} entries but got {len(self._cache_obs)}. "
135
138
  "Ensure act() is called exactly once per environment step."
136
139
  )
137
- obs_arr = np.array(self._cache_obs[:T], dtype=np.float32)
140
+ obs_arr = to_batch_numpy(self._cache_obs[:T])
138
141
  old_lp_arr = np.array(self._cache_log_probs[:T], dtype=np.float32)
139
142
  values_arr = np.array(self._cache_values[:T], dtype=np.float32)
140
143
  rewards = list(episode_data.rewards)
@@ -155,7 +158,7 @@ class TFPPOAgent(BaseAgent):
155
158
  # bootstrap value per env, and n_envs tells compute_gae how the
156
159
  # rewards/values array is interleaved across envs.
157
160
  def _critic_value(obs):
158
- obs_t = tf.cast(np.atleast_2d(obs), tf.float32)
161
+ obs_t = to_tf_batch(obs)
159
162
  return float(tf.squeeze(self._critic(obs_t, training=False)).numpy())
160
163
 
161
164
  last_value, n_envs = resolve_gae_bootstrap(episode_data, _critic_value)
@@ -183,7 +186,7 @@ class TFPPOAgent(BaseAgent):
183
186
 
184
187
  for _ in range(n_epochs):
185
188
  for batch in make_minibatches(rollout, mb_size):
186
- obs_b = tf.cast(batch["obs"], tf.float32)
189
+ obs_b = already_batched_to_tf(batch["obs"])
187
190
  act_b = tf.cast(batch["actions"], tf.int32)
188
191
  old_b = tf.cast(batch["old_lp"], tf.float32)
189
192
  adv_b = tf.cast(batch["advantages"], tf.float32)
@@ -248,7 +251,7 @@ class TFPPOAgent(BaseAgent):
248
251
  Used by PolicyManager.ensemble_action() to average distributions
249
252
  across ensemble members rather than averaging sampled actions.
250
253
  """
251
- obs = tf.cast(np.atleast_2d(observation), tf.float32)
254
+ obs = to_tf_batch(observation)
252
255
  logits = self._actor(obs, training=False)
253
256
  return tf.nn.softmax(logits)[0].numpy()
254
257