Concepts

Two cores, not one

Everything below describes the RL core: LoopController, BaseAgent, episodes. There is a second, separate ML core (tensor_optix.ml_core) for supervised/unsupervised training: Trainer, BaseMLModel, epochs and batches. It is not a mode of the RL loop. An ML training epoch is not an RL episode. The older Optimizer(model, dataset) path treats a training epoch as a fake RL episode (see ML support); ml_core does not. The two cores share the same lower-level, algorithm-agnostic pieces (CheckpointRegistry, BackoffScheduler, SPSAOptimizer) but expose different contracts on top. See Train an ML model.

The five abstractions

LoopController (wrapped by RLOptimizer and, more simply, Optimizer) coordinates five things through abstract interfaces. It has no knowledge of TensorFlow, PyTorch, JAX, PPO, DQN, or SAC - only these contracts:

Abstraction Role
BaseAgent act(), learn(), hyperparams, save/load weights - the only thing the loop calls into
BasePipeline Produces EpisodeData - a Gymnasium env, a live stream, or a Dataset
BaseEvaluator Scores an episode into a single primary_score (higher is always better)
BaseOptimizer Proposes new hyperparameters from score history
LoopCallback Hooks into loop events (improvement, plateau, dormant, degradation, ...)

Any algorithm - PPO, DQN, SAC, CMA-ES, a custom evolutionary method - is usable by the loop as long as it implements BaseAgent's six methods. See Write a custom agent.

Loop states

ACTIVE → COOLING → DORMANT → (watchdog shutdown | policy spawn)
   ↑________________|
     (on improvement or degradation)
  • ACTIVE - the score is improving or it's early in training.
  • COOLING - plateau_threshold consecutive non-improving evals. Only windows in which at least one episode finished count as evals, and nothing counts until min_completed_episodes_before_dormant (default 10) episodes have finished.
  • DORMANT - dormant_threshold consecutive non-improving evals. By default the loop stops here and restores the best checkpoint. With a PolicyManagerCallback attached, DORMANT instead triggers a spawn/prune/stop decision.

Transitions are not point-to-point score comparisons. BackoffScheduler fits a linear trend over the most recent trend_window scores and compares the slope against an adaptive floor (noise_k × the standard deviation of the recent scores around their own linear trend, capped at 50% of |best_score|) - the noise estimate is detrended so that steady improvement is not mistaken for noise. A single unlucky episode in an otherwise-improving run does not look like a collapse, and a single lucky episode in an otherwise-flat run does not look like genuine progress.

Checkpointing is validation-only

When a val_pipeline is configured, primary_score is the validation score, not the training score. The training score can keep climbing while validation degrades - that's overfitting, and the loop is built to act on it rather than reward it.

run() always restores the best known checkpoint before returning, regardless of how the loop ended (convergence, stop(), or max_episodes). Pass checkpoint_score_fn to drive checkpoint selection from an independent, deterministic external evaluation instead of the noisy training-window mean.

By default, "best" is the single episode with the highest primary_score - a raw point comparison. That's fine most of the time, but a lucky episode (reward concentrated on one favorable step, not earned consistently) can score higher than anything a genuinely better policy produces later, and become a permanent, unbeatable "best." criteria_mode and checkpoint_confirmation (both opt-in, off by default) widen the measurement and require corroboration before trusting an improvement - see Avoiding unicorn checkpoints.

On-policy vs. off-policy rollback

BaseAgent.is_on_policy (default True) tells the loop whether rollback is safe:

  • On-policy (PPO, A2C) - each window is freshly generated by the current policy. Rolling back to a previous checkpoint is safe; the next window will be generated entirely by the restored policy.
  • Off-policy (SAC, DQN, TD3) - a replay buffer holds experience from all past policies. Rolling back weights without clearing the buffer means the agent immediately trains on stale, mismatched experience, corrupting Bellman targets. LoopController skips weight rollback for off-policy agents even when rollback_on_degradation=True.

Online vs. trial-level hyperparameter tuning

Two layers, meant to compose:

  • Online (BaseOptimizer subclasses: SPSA, Momentum, Backoff, PBT, Adaptive) - adapt hyperparameters within a single run, every episode, by probing and measuring score deltas. Good at tracking a non-stationary landscape; bad at exploring broadly.
  • Trial-level (TrialOrchestrator) - runs N independent short trials via Optuna TPE before the main run, then warm-starts the full run from the best trial's weights and config. Good at finding the right region of hyperparameter space; too slow to run continuously.

See Tune hyperparameters online and Run trial-level search.

DiagnosticController vs. the optimizer

SPSA-style optimizers are deliberately slow and blind to internals - they see only the score, and a meaningful update takes several episodes. That's fine for global search but useless against an acute failure happening right now: a loss spike, entropy collapse, a KL-divergence blowup, or an exhausted DQN exploration budget. DiagnosticController reads train_diagnostics from agent.learn() every episode and applies an immediate, single-parameter correction when a threshold is crossed - independent of, and faster than, the episode-level optimizer.

Ensembles and evolution

PolicyManager is deliberately separate from the optimizer: the optimizer tunes hyperparameters, PolicyManager evolves models. On DORMANT, MetaController reads the generalization gap (level and slope) and the validation improvement rate, then issues SPAWN, PRUNE, STOP, or NO_OP. See Ensembles and policy evolution.