Tensor-Optix: Training Loops That Know When to Stop

Tensor-Optix: Training Loops That Know When to Stop

Backer ●2 ●6 ●9
calendar_today ago • schedule8 min read

A deep dive into tensor-optix 2.2.6: statistical convergence control, online hyperparameter tuning, real checkpointing, and a discovery engine that questions your data before you train on it.

Most training scripts end with a guess. You pick an epoch count, watch a curve, and hope the weights you saved last are the best ones. tensor-optix takes that job over: it reads the score stream, decides whether the run is still learning, tunes hyperparameters as it goes, and hands back the best checkpoint.

It is a Python framework (MIT-licensed, Python 3.11+) for both reinforcement learning (RL) and supervised or unsupervised machine learning. It has three layers on shared machinery:

Layer What it answers Main entry points
RL core How do I train an agent without babysitting it? make_agent, RLOptimizer, Optimizer
ML core How do I fit a model and stop at the right time? TorchMLModel, TFMLModel, FlaxMLModel
Discovery What is in my data, and what should I train? discover()

The design idea is simple: the framework owns the loop, you own the model. Both cores reuse the same checkpoint registry, convergence monitor and SPSA optimizer, but each has its own contract, because an RL episode and a training epoch are not the same thing.

Install and quickstart

pip install tensor-optix

In 2.2.6 this base install already pulls in PyTorch (2.11+), Gymnasium with Box2D, NumPy, Optuna, Matplotlib, PyYAML and SWIG. The README calls it "core loop only", but the package metadata says otherwise, so expect a large download. Extras add the rest: [tensorflow], [jax], [pandas], [discovery-boost], [pettingzoo], [atari], [mujoco], [wandb], [tensorboard] and [onnx].

Here is a complete CartPole run with a custom callback:

import gymnasium as gym
from tensor_optix import make_agent, RLOptimizer, BatchPipeline, LoopCallback

env = gym.make("CartPole-v1")
agent = make_agent(env)          # discrete actions -> TorchPPOAgent
pipeline = BatchPipeline(env=env, agent=agent, window_size=2048)

class LogBest(LoopCallback):
    def on_improvement(self, snapshot):
        print(f"new best: {snapshot.eval_metrics.primary_score:.1f}")

opt = RLOptimizer(agent=agent, pipeline=pipeline,
                  checkpoint_dir="./checkpoints", max_episodes=60,
                  callbacks=[LogBest()])
opt.run()
print(opt.best_snapshot.eval_metrics.primary_score)

In a test run for this article, the best score reached 500.0, the maximum for CartPole-v1. That is one run on an easy environment, not a benchmark.

If you want even less code, Optimizer(agent, env).run() computes the window size for you and enables tuning when the agent declares parameter bounds.

The RL core

The RL loop runs your agent against a data pipeline, evaluates it, tunes it, checkpoints it, and decides when to stop.

interact -> evaluate -> compare -> tune -> repeat
                 |
      ACTIVE -> COOLING -> DORMANT -> stop, or spawn a policy variant
                 |
      best weights restored on shutdown

Convergence that reads the curve

A single slope over the last few points is easy to fool: a collapse followed by recovery looks like progress. ConvergenceMonitor instead reads short, medium and long trends against the run's own peak, and estimates noise and autocorrelation from the curve itself. It labels each observation as warmup, improving, plateau, regressed and climbing, regressed and stalled, or collapsing. Climbing back to old ground is not counted as improvement.

Tuning while training

The default tuning method is SPSA (Simultaneous Perturbation Stochastic Approximation). It probes all bounded hyperparameters at once, so one gradient estimate costs two episodes however many parameters you tune. No restarts are needed.

Optimizer Suited to
SPSAOptimizer Noisy scores with no autocorrelation
MomentumOptimizer Positive lag-1 autocorrelation (smooth landscape)
BackoffOptimizer Negative autocorrelation (oscillation); sign-only updates
PBTOptimizer Poor scores relative to history; exploits earlier checkpoints
AdaptiveOptimizer Routes between the four automatically

For search before the main run, TrialOrchestrator runs short Optuna TPE trials and warm-starts from the winner.

Checkpoints and rollback

Pass a separate val_pipeline and checkpoint decisions use validation scores, not training scores. With rollback_on_degradation=True, a confirmed degradation restores the best weights. This applies to on-policy agents only: off-policy agents keep their weights, because the replay buffer would pull a restored policy straight back.

Bring your own agent

Any model that implements six methods can use the loop:

class BaseAgent(ABC):
    def act(self, observation): ...
    def learn(self, episode_data): ...
    def get_hyperparams(self): ...
    def set_hyperparams(self, hyperparams): ...
    def save_weights(self, path): ...
    def load_weights(self, path): ...

Built-in algorithms

Framework Agents
PyTorch PPO (discrete, continuous, recurrent), DQN, Rainbow DQN, SAC, TD3
TensorFlow PPO (discrete, continuous), DQN, SAC, TD3
JAX/Flax PPO

make_agent picks from the action space: PPO for discrete, SAC for continuous, and TD3 if you pass deterministic=True. It also handles image and dictionary observations. If you choose Rainbow, set v_min and v_max for your environment: the defaults (0 to 500) only suit CartPole-like returns.

Pipelines and callbacks

  • BatchPipeline steps a Gymnasium environment in windows.
  • VectorBatchPipeline runs many environments in parallel (not with recurrent PPO).
  • LivePipeline consumes an external stream and applies backpressure instead of dropping samples.
  • Callbacks hook improvement, plateau, degradation and more. Rich dashboard, Weights & Biases and TensorBoard callbacks are included.

The ML core

tensor_optix.ml_core gives you a scikit-learn-style fit() / predict() / evaluate() contract, and you do not have to choose an epoch count.

import torch, torch.nn as nn
from tensor_optix.ml_core import TorchMLModel

torch.manual_seed(0)
X = torch.randn(2000, 20)
y = (X[:, 0] + X[:, 1] * X[:, 2] > 0).long()

model = TorchMLModel(
    nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 2)),
    loss_fn=nn.CrossEntropyLoss(),
)
history = model.fit((X[:1600], y[:1600]), (X[1600:], y[1600:]),
                    metrics="classification", checkpoint_dir="./ml_ckpt")
print(history.stop_reason, len(history.val_metrics))

On our test run this stopped on its own with converged after 73 epochs.

  • Two modes. Leave epochs unset and training runs until the monitor goes dormant. Set epochs=N for a fixed budget, optionally with early_stopping_patience.
  • Real metrics. Accuracy, precision, recall, F1 and confusion matrix for classification; MAE, RMSE and R² for regression. Custom callables work too. Setting metrics= explicitly also silences the auto-detection message.
  • Best weights back. With checkpoint_dir set, the best checkpoint is restored before fit() returns, even after an exception. Without it, you get the final weights.
  • Extras. Learning-rate schedules, batch augmentation, layer freezing and pretrained backbone loading for transfer learning.
  • Frameworks. PyTorch, TensorFlow and Flax adapters; the Flax one accepts raw (X, y) arrays only.

There is also an older path, Optimizer(model, dataset), which treats each batch as a fake RL episode. It still works and covers losses such as VAE and contrastive, but it is deprecated. Use ml_core for new code.

Discovery: evidence before training

discover() profiles a dataset, tests how it should be split, compares model families under a fixed budget, and recommends one with its uncertainty.

To try it, we built a synthetic churn table of 1,500 rows and planted a leak: a refund_flag column that copies the target.

from tensor_optix.discovery import discover

report = discover(df, target="churned")
report.to_html("discovery.html")   # self-contained, works offline
print(report.summary())

What it reported:

  • The leak was caught. refund_flag alone scored AUC 1.0, and discovery excluded it from its experiments.
  • The recommendation was honest. It chose a linear model but labelled it "Too close to call" against the other families.
  • The holdout was stated with uncertainty. AUC 0.80 (95% CI 0.74 to 0.85) on 224 untouched rows, against 0.50 for a dummy baseline.

One gotcha worth knowing

Every finding has an ID and a severity, and you accept or reject each one. build() applies only accepted findings, and refuses only while a critical one is pending. Our leak was a warning, so build() went ahead and trained on the leaked column, with a UserWarning. Accept the finding first:

report.accept("leakage.single_feature:col=refund_flag")
solution = report.build()
solution.fit(df, target="churned")

Without that line, flipping refund_flag changed every prediction. With it, flipping the column changed none. Read the findings before you build.

What else it does

  • Detects grouped rows and time order, and cuts the holdout to match.
  • Checks leakage and train/test shift, and runs cheap landmark models to test for signal.
  • Compares linear, naive Bayes, k-NN, MLP and boosted-tree families on identical folds.
  • Optionally searches for new feature expressions (expressions=True) and confirms them on rows the search never saw.
  • For a Gymnasium environment, probes it, trains the applicable algorithms on the same seeds and steps, and recommends one. Set a Budget to cap the cost.

If LightGBM and XGBoost are absent, it uses the library's own NumPy gradient-boosted trees (tensor_optix.gbdt), which you can also use directly. They are noticeably slower; the report itself says about 10x on its benchmark.

The wider toolkit

Contextual bandits

For one-step decisions there are LinUCB, linear Thompson sampling and a neural-linear agent. They can learn from logged data, and you can evaluate a policy offline with IPS, SNIPS, direct-method and doubly robust estimators, with confidence intervals and overlap diagnostics.

Multi-agent and self-play

PettingZoo Parallel and turn-based (AEC) environments are supported. Each seat gets its own agent, checkpoints and convergence check. SelfPlayPipeline plays a learner against past snapshots of itself.

Scaling and ensembles

  • AsyncActorLearner implements IMPALA-style actor processes with shared-memory weights and V-trace correction.
  • PolicyManager can spawn policy variants when a run goes dormant, and EnsembleAgent combines them.
  • Utilities include prioritized and hindsight replay (HERReplayBuffer), observation and reward normalizers, curiosity-style exploration (RND) and regime detection.

Neuroevolution

The neuroevo subsystem represents a policy as a mutable NeuronGraph that can grow, prune and merge neurons during training. It supports GRU and LSTM neurons, multi-region BrainNetworks, Hebbian updates, Dale's Law constraints and checkpoints that restore the topology along with the weights. A grow step needs three separate signals to agree. Treat this as the experimental frontier and compare it against a plain PPO or SAC baseline.

agent = make_agent(env, neuroevo=True)

Experiment ledger and the Learning-to-Learn Engine

ExperimentStore records runs in SQLite with provenance such as code revision and library versions. On top of it sit a multi-process trial scheduler, cross-task budget allocation (NanonetsSelector, which abstains when other tasks are not comparable), and strategy search over a closed set of training operations, never generated code.

The live runtime is recommend-only. It never promotes a change itself; a human has to approve and promote it.

Config files and CLI

# config.yaml
env: CartPole-v1
algorithm: TorchPPOAgent
seed: 42
optimizer:
  max_episodes: 300
  checkpoint_dir: ./checkpoints
tensor-optix validate config.yaml
tensor-optix train config.yaml agent.learning_rate=1e-3

validate is handy in CI. The config route covers a subset of agents: PPO, SAC, TD3 and DQN in PyTorch, and PPO, SAC and TD3 in TensorFlow.

Trade-offs and verdict

tensor-optix is most useful when you are tired of hand-managing training runs and want the stopping, tuning and checkpointing decisions made by explicit statistics. Weigh these before adopting it:

  • Breadth is a cost. The package is roughly 48,000 lines of Python spanning RL, ML, AutoML-style discovery and experiment management. Learn one layer at a time.
  • Heavy base install. PyTorch comes along even if you only want TensorFlow or JAX.
  • Automation needs checking. Convergence rules and SPSA probes are heuristics on noisy data. Run several seeds and keep your own held-out test.
  • Limited tests in the source archive. The 2.2.6 archive ships one test file, covering the ML side. All 45 tests passed for us, but they say little about the RL core.
  • Trust your checkpoints. Some load paths use torch.load(..., weights_only=False), which can execute code. Never load checkpoint files from strangers.
  • No benchmark claims here. We checked that examples run, not that tensor-optix beats Stable-Baselines3, RLlib or scikit-learn.

Where to start: run discover() on a dataset you know well and see whether its findings match what you know. Then move one existing training script to fit() or RLOptimizer and compare the stopping point with your own.


Resources: Documentation · PyPI

Tested on version 2.2.6 with Python 3.13 and PyTorch 2.15. Examples not shown with a result were taken from the project's documentation or source and were not all executed.

Want more #machinelearning & #datascience deep dives?

Join 6,139+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

Sealing My Own Experiment

Ken W. Algerverified - Dec 1

Breaking the AI Data Bottleneck: How Hammerspace's AI Data Platform Eliminates Migration Nightmares

Tom Smithverified - Mar 16

Cisco's Amy Chang: A Model's "Passport" Doesn't Tell You Where It Actually Came From

Tom Smithverified - Aug 27

Make for Small Business: What It Is, What It Costs, and When to Use It

floxolab - Oct 23

Stop trusting verdicts your policy no longer supports

VEACESLAV - Dec 1
chevron_left
1.8k Points • 17 Badges
Cape Town, South Africa • mokhan.co.za
4Posts
0Comments
38Connections
I'm an independent developer specializing in AI systems architecture, machine learning platforms, an... Show more

Related Jobs

View all jobs →

Commenters (This Week)

12 comments
5 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!