### Run tensor-optix CLI commands Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/installation.md After installation, the `tensor-optix` command is available. Use `train` with a config file and optional overrides, or `validate` to validate a config. ```bash tensor-optix train config.yaml seed=42 agent.learning_rate=1e-3 tensor-optix validate config.yaml ``` -------------------------------- ### What you get back Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/quickstart.md After run() returns, the agent's weights are the best known checkpoint, not the last trained. Access the best snapshot via opt.best_snapshot. ```python opt.run() opt.best_snapshot # PolicySnapshot: best weights + EvalMetrics + HyperparamSet ``` -------------------------------- ### Usage example for setting and getting the global device Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/core/device.md Shows how to set the global device with tx.set_device() and read it with tx.get_device(). Accepts strings like 'cuda' or 'cpu', CUDA device indices like 'cuda:1', or torch.device objects. ```python import tensor_optix as tx tx.set_device("cuda") # or "cpu", "cuda:1", torch.device(...) # Or read the current device: dev = tx.get_device() ``` -------------------------------- ### ExperimentStore usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to create, start, record progress, finalize, and query experiments using ExperimentStore. Requires a SQLite file path and uses ExperimentState and EvaluationStatus enums. ```python from tensor_optix.ledger import ExperimentStore, ExperimentState, EvaluationStatus store = ExperimentStore("./experiments.sqlite3") record = store.create_experiment( task_env="CartPole-v1", algorithm="PPO", framework="torch", seed=0, checkpoint_dir="./ckpt", solve_threshold=475.0, ) store.start_experiment(record.experiment_id) store.record_progress(record.experiment_id, best_primary_score=480.0) store.finalize_experiment( record.experiment_id, state=ExperimentState.COMPLETED, evaluation_status=EvaluationStatus.VALIDATED, ) rows = store.query_experiments(task_env="CartPole-v1", state=ExperimentState.COMPLETED) store.close() ``` -------------------------------- ### BasePipeline.setup() Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/site/reference/core/base_pipeline/index.html Initialize the data source. Called once before the loop starts. ```APIDOC ## BasePipeline.setup() ### Description Initialize the data source. Called once before the loop starts. ### Method setup ### Signature ```python @abstractmethod def setup(self) -> None ``` ### Parameters None ### Returns None ``` -------------------------------- ### Install tensor-optix with neuroevo extra Source: https://github.com/sup3rus3r/tensor-optix/blob/main/README.md Installs the package with the neuroevo extra to enable neuroevolution features. ```bash pip install tensor-optix[neuroevo] ``` -------------------------------- ### VectorBatchPipeline usage example Source: https://github.com/sup3rus3r/tensor-optix Example of using VectorBatchPipeline with 8 parallel CartPole environments. Creates pipeline with async_envs=True, calls setup(), iterates episodes, and prints total steps (256 * 8 = 2048). ```python from tensor_optix import VectorBatchPipeline env_fns = [lambda: gym.make("CartPole-v1")] * 8 pipeline = VectorBatchPipeline(env_fns=env_fns, agent=agent, window_size=256, async_envs=True) pipeline.setup() for episode in pipeline.episodes(): print("total steps", len(episode.rewards)) # 256 * 8 = 2048 pipeline.teardown() ``` -------------------------------- ### PolicyManager usage examples Source: https://github.com/sup3rus3r/tensor-optix Examples demonstrating how to use PolicyManager with callbacks, ensemble construction, regime-adaptive boosting, and MetaController-driven runs. ```python from tensor_optix import PolicyManager, RLOptimizer pm = PolicyManager(registry, max_spawns=3) cb = pm.as_callback(agent, agent_factory=make_agent) cb.set_stop_fn(opt.stop) opt.add_callback(cb) opt.run() ``` ```python from tensor_optix.core import EnsembleAgent, RegimeDetector pm = PolicyManager(registry) pm.add_agent(primary, weight=1.0) variant = pm.spawn_variant(SecondaryAgent(), noise_scale=0.05) pm.add_agent(variant, weight=0.5) ensemble = EnsembleAgent(pm, primary_agent=primary) regime = RegimeDetector().detect(metrics_history) pm.set_regime(regime) if regime == "volatile": pm.boost(variant, factor=2.0) ``` ```python mc = MetaController(gap_threshold=0.2, gap_slope_threshold=0.02) cb = pm.as_callback(agent, agent_factory=make_agent, meta_controller=mc) cb.set_stop_fn(opt.stop) opt.add_callback(cb) opt.run() print(pm.training_report()) ``` -------------------------------- ### Install tensor-optix with optional extras Source: https://github.com/sup3rus3r/tensor-optix/blob/main/README.md Install the core package or add framework-specific algorithm implementations. Use the CUDA 12.8 PyTorch install for GPU support on Linux/WSL2. Environment, logging, and export extras are available. ```bash # Core loop only, no algorithm implementations pip install tensor-optix # PyTorch algorithms pip install tensor-optix[torch] # TensorFlow algorithms pip install tensor-optix[tensorflow] # JAX/Flax pip install tensor-optix[jax] # Neuroevo (requires torch) pip install tensor-optix[neuroevo] # GPU (Linux/WSL2, CUDA 12.8) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128 pip install tensor-optix[torch] # All frameworks and environment extras pip install tensor-optix[all] ``` -------------------------------- ### Choosing an algorithm explicitly Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/quickstart.md Selects a specific algorithm by name, with optional framework choice for SAC. ```python agent = make_agent("DQN", env) agent = make_agent("RAINBOW", env) agent = make_agent("SAC", env, framework="tf") ``` -------------------------------- ### Clone and install tensor-optix for development Source: https://github.com/sup3rus3r/tensor-optix/blob/main/CONTRIBUTING.md Sets up a local development environment by cloning the repository and installing it in editable mode with development dependencies. ```bash git clone https://github.com/sup3rus3r/tensor-optix cd tensor-optix pip install -e ".[dev]" ``` -------------------------------- ### Optimizer.run() Source: https://github.com/sup3rus3r/tensor-optix Starts training and blocks until max_episodes or KeyboardInterrupt. Delegates to the wrapped RLOptimizer.run(). ```APIDOC ## Optimizer.run() ### Description Starts training and blocks until max_episodes or KeyboardInterrupt. Delegates to the wrapped RLOptimizer.run(). ### Method run ### Signature ```python def run(self): ``` ### Parameters None ### Returns None ``` -------------------------------- ### Optimizer.run() Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/optimizer.md Starts training. Blocks until max_episodes or KeyboardInterrupt. ```APIDOC ## Optimizer.run() ### Description Start training. Blocks until max_episodes or KeyboardInterrupt. ### Method ```python def run(self): ... ``` ``` -------------------------------- ### RL example: SAC agent with neuroevo and Optimizer Source: https://github.com/sup3rus3r/tensor-optix Creates a Gymnasium environment, an SAC agent with neuroevo enabled, and an Optimizer, then runs it. Requires tensor_optix and gymnasium. ```python import gymnasium as gym from tensor_optix import make_agent, Optimizer env = gym.make("HumanoidStandup-v5") agent = make_agent("SAC", env, neuroevo=True) opt = Optimizer(agent, env) opt.run() ``` -------------------------------- ### Optimizer run method Source: https://github.com/sup3rus3r/tensor-optix Starts training and blocks until max_episodes or KeyboardInterrupt. Delegates to the wrapped RLOptimizer.run(). ```python def run(self): ``` -------------------------------- ### Positional overloading examples Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/factory.md Shows two ways to call make_agent: with only the environment (algorithm inferred from action space) or with an explicit algorithm string as the first argument. ```python agent = make_agent(env) # algorithm inferred from action space agent = make_agent("SAC", env) # algorithm explicit ``` -------------------------------- ### Discrete action space (CartPole) Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/quickstart.md Creates a CartPole-v1 environment, builds a default TorchPPOAgent, and runs optimization. make_agent inspects the action and observation spaces to configure the agent. ```python import gymnasium as gym from tensor_optix import make_agent, Optimizer env = gym.make("CartPole-v1") agent = make_agent(env) # -> TorchPPOAgent (discrete default) opt = Optimizer(agent, env) opt.run() ``` -------------------------------- ### Install tensor-optix with ONNX extras Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/onnx-export.md Install the package with the ONNX extra to enable ONNX export functionality. ```bash pip install tensor-optix[onnx] ``` -------------------------------- ### ExperimentStore.start_experiment Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/site/reference/learning-to-learn/index.html Marks an experiment as started. This method updates the experiment's state to indicate it is in progress. ```APIDOC ## ExperimentStore.start_experiment ### Description Marks an experiment as started. This method updates the experiment's state to indicate it is in progress. ### Method Method ### Signature `start_experiment(self, experiment_id: str) -> None` ### Parameters - **experiment_id** (str) - Required - The ID of the experiment to start. ``` -------------------------------- ### Parallel environments Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/quickstart.md Runs optimization with 8 parallel environments. When n_envs > 1, pass env as a zero-arg callable so each worker builds its own instance. ```python opt = Optimizer(agent, lambda: gym.make("CartPole-v1"), n_envs=8) opt.run() ``` -------------------------------- ### AsyncActorLearner usage example Source: https://github.com/sup3rus3r/tensor-optix Example of creating an AsyncActorLearner with 8 actors and running it for 10 million steps, printing steps per second and total updates. ```python from tensor_optix.distributed import AsyncActorLearner import gymnasium as gym learner = AsyncActorLearner( actor=actor, critic=critic, optimizer=optimizer, env_factory=lambda: gym.make("ALE/Pong-v5"), n_actors=8, trajectory_len=64, ) stats = learner.run(max_steps=10_000_000) print("steps/sec:", stats["steps_per_second"]) print("updates:", learner.total_updates) ``` -------------------------------- ### CheckpointRegistry usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to create a registry, save a snapshot, restore best weights, and perform SWA over top-3 within a 10% band. ```python from tensor_optix.core import CheckpointRegistry registry = CheckpointRegistry("./checkpoints", max_snapshots=10) registry.save(agent, eval_metrics, hyperparams) registry.load_best(agent) # restore best weights registry.load_ensemble(agent, top_k=3) # SWA over top-3 within 10% band ``` -------------------------------- ### TrialOrchestrator usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to instantiate TrialOrchestrator with a custom param_space and run trials, then print the best parameters and weights path. ```python from tensor_optix import TrialOrchestrator, make_agent, BatchPipeline orch = TrialOrchestrator( agent_factory=make_agent, pipeline_factory=lambda: BatchPipeline(env=gym.make("CartPole-v1"), window_size=2048), param_space={ "learning_rate": ("log_float", 1e-4, 3e-3), "clip_ratio": ("float", 0.1, 0.3), "batch_size": ("int", 32, 512), }, n_trials=20, trial_steps=50_000, ) best_params, best_score = orch.run() print("best", best_params, best_score) print("best weights path:", orch.best_weights_path) ``` -------------------------------- ### Continuous action space Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/getting-started/quickstart.md Builds a TorchSACAgent for LunarLanderContinuous-v3, or a TorchTD3Agent when deterministic=True, then runs optimization. ```python env = gym.make("LunarLanderContinuous-v3") agent = make_agent(env) # -> TorchSACAgent (continuous default) agent = make_agent(env, deterministic=True) # -> TorchTD3Agent opt = Optimizer(agent, env) opt.run() ``` -------------------------------- ### Example YAML configuration for Tensor-Optix Source: https://github.com/sup3rus3r/tensor-optix Defines environment, algorithm, seed, agent hyperparameters, and optimizer settings. The optimizer block includes max_episodes, verbose, and checkpoint_dir. This YAML is loaded by load_config in the usage example. ```yaml env: CartPole-v1 algorithm: TorchPPOAgent seed: 42 agent: learning_rate: 3e-4 clip_ratio: 0.2 gamma: 0.99 optimizer: max_episodes: 300 verbose: true checkpoint_dir: ./checkpoints ``` -------------------------------- ### Example: Using ObsNormalizer and RewardNormalizer Source: https://github.com/sup3rus3r/tensor-optix Shows how to use ObsNormalizer to normalize observations and RewardNormalizer to scale rewards by return standard deviation. The example updates the normalizers with batches and then normalizes data. ```python from tensor_optix import ObsNormalizer, RewardNormalizer obs_norm = ObsNormalizer(shape=(4,)) obs_norm.update(obs_batch) normalized = obs_norm.normalize(obs) rew_norm = RewardNormalizer() for r in rewards: rew_norm.step(r) scaled_rewards = rew_norm.normalize(rewards) rew_norm.reset() ``` -------------------------------- ### TensorBoard logging with TensorBoardCallback Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/logging-callbacks.md Requires `pip install torch` (ships with `torch.utils.tensorboard`) or `pip install tensor-optix[tensorboard]`. Logs the same signal groups as `WandbCallback`, using TensorBoard's `/`-separated scalar tag convention for grouped panels. ```python from tensor_optix.callbacks import TensorBoardCallback opt.add_callback(TensorBoardCallback(log_dir="./runs/cartpole")) ``` -------------------------------- ### Usage example for HERReplayBuffer Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/core/her_buffer.md Shows how to instantiate HERReplayBuffer with a PrioritizedReplayBuffer and store episodes. Agents should not call push() per step; instead, collect full episodes and call store_episode() once per episode. The sample() method returns a batch with additional fields. ```python from tensor_optix.core.replay_buffer import PrioritizedReplayBuffer from tensor_optix.core.her_buffer import HERReplayBuffer inner = PrioritizedReplayBuffer(capacity=1_000_000, alpha=0.0) her = HERReplayBuffer(inner, k=4, strategy="future") # At end of each episode: her.store_episode( obs_list, act_list, rew_list, next_obs_list, done_list, achieved_goals, # shape [T, goal_dim] - achieved goal AFTER each step compute_reward, # env.compute_reward(achieved, desired, info) -> float ) # Inside agent._update_step(): obs_b, act_b, rew_b, next_b, done_b, w, idx, n = her.sample(batch_size) ``` -------------------------------- ### Usage example for compute_gae and make_minibatches Source: https://github.com/sup3rus3r/tensor-optix Shows how to import and use compute_gae and make_minibatches together. Computes advantages with GAE and then creates minibatches of size 64 from a dict containing observations and advantages. ```python from tensor_optix import compute_gae, make_minibatches adv = compute_gae(rewards, values, dones, gamma=0.99, gae_lambda=0.95) for batch in make_minibatches({"obs": obs, "adv": adv}, minibatch_size=64): ... ``` -------------------------------- ### MLAgent usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to instantiate MLAgent with a model and a resolved loss function, then save weights to a file. Uses resolve_loss from tensor_optix.ml.loss_registry. ```python from tensor_optix.ml import MLAgent from tensor_optix.ml.loss_registry import resolve_loss ml_agent = MLAgent(model, resolve_loss("cross_entropy", dataset=ds)) ml_agent.save_weights("model.pt") ``` -------------------------------- ### Usage example for TopologyAwareAdam Source: https://github.com/sup3rus3r/tensor-optix Shows how to instantiate TopologyAwareAdam with a custom learning rate and call notify_topology_change after grow/prune/merge operations. ```python from tensor_optix.neuroevo import TopologyAwareAdam opt = TopologyAwareAdam(graph.parameters(), lr=3e-4) # after grow/prune/merge: opt.notify_topology_change(new_params) ``` -------------------------------- ### TensorBoardCallback usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to instantiate and add TensorBoardCallback to an optimizer with log_dir and comment parameters. ```python from tensor_optix.callbacks import TensorBoardCallback opt.add_callback(TensorBoardCallback(log_dir="./tb", comment="v2")) ``` -------------------------------- ### CheckpointConfirmationTracker usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to observe a score and evaluate a candidate score against a baseline, printing the acceptance result and reason. ```python from tensor_optix.core.checkpoint_confirmation import CheckpointConfirmationTracker tracker = CheckpointConfirmationTracker(noise_k=2.0, confirm_window=3) tracker.observe(480.0) accepted, reason = tracker.evaluate_candidate(487.0, 480.0) print(accepted, reason) ``` -------------------------------- ### run() Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/site/reference/core/loop_controller/index.html Starts the training loop and blocks until convergence, stop(), or max_episodes is reached. When it returns, the agent holds the best known weights. ```APIDOC ## run() ### Description Start the loop. Blocks until convergence, stop(), or max_episodes. When run() returns, the agent always holds the best known weights - whether stopped by convergence, budget, or manual stop(). ### Method run ### Signature ```python def run(self) -> None: ``` ``` -------------------------------- ### resolve_loss usage examples Source: https://github.com/sup3rus3r/tensor-optix Shows how to call resolve_loss with 'auto' (requires dataset) and with an nn.Module instance. The 'auto' mode inspects n_samples (default 64) from the dataset for detection. ```python from tensor_optix.ml.loss_registry import resolve_loss loss = resolve_loss("auto", dataset=train_dataset) loss = resolve_loss(nn.HuberLoss()) ``` -------------------------------- ### LivePipeline usage example with custom data source Source: https://github.com/sup3rus3r/tensor-optix Shows how to create a custom data source with a stream() generator and instantiate LivePipeline with an episode boundary of every 300 seconds. The source runs in a background thread with a bounded queue. ```python class MyFeed: def stream(self): while True: yield (obs, 0.0, False, False, {}) # raw sensor stream from tensor_optix import LivePipeline pipeline = LivePipeline( data_source=MyFeed(), agent=agent, episode_boundary_fn=LivePipeline.every_n_seconds(300), ) ``` -------------------------------- ### Quick start: Optimizer with nn.Module and Dataset Source: https://github.com/sup3rus3r/tensor-optix Trains a PyTorch nn.Module against a Dataset or DataLoader using SPSA tuning, rollback-on-degradation, convergence detection, and checkpointing. Auto-detects ML mode when agent is an nn.Module and env is a Dataset/DataLoader. ```python import tensor_optix as optix import torch.nn as nn model = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) opt = optix.Optimizer(model, train_dataset, loss="cross_entropy") opt.run() ``` -------------------------------- ### Set up and run LiveAdaptiveRuntime Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/learning-to-learn.md Initializes a baseline and runs the live adaptive runtime loop. Requires a store, agent factory, pipeline factory, and evaluator. The runtime runs for a specified number of cycles and returns observations and recommendations. ```python from tensor_optix.runtime import LiveAdaptiveRuntime, RuntimeConfig, establish_baseline from tensor_optix.adapters.pytorch.torch_evaluator import TorchEvaluator baseline_id = establish_baseline( store, agent_factory=make_agent, pipeline_factory=make_pipeline, evaluator=TorchEvaluator(), task_env="CartPole-v1", algorithm="PPO", study_id="my_deployment", trial_steps=20_000, ) config = RuntimeConfig(task_env="CartPole-v1", algorithm="PPO", study_id="my_deployment", max_cycles=20) runtime = LiveAdaptiveRuntime(store, config, agent_factory=make_agent, pipeline_factory=make_pipeline) observations, recommendations = runtime.run() ``` -------------------------------- ### VectorBatchPipeline constructor Source: https://github.com/sup3rus3r/tensor-optix Constructor for VectorBatchPipeline. Runs N environments in parallel via gymnasium.vector, SyncVectorEnv or AsyncVectorEnv. If async_envs=True and env_fns are not picklable, setup() falls back to SyncVectorEnv with a warning. ```python def __init__( self, env_fns: List[Callable], agent=None, window_size: int = 256, async_envs: bool = False, ): ``` -------------------------------- ### RLOptimizer.run Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/optimizer.md Starts the autonomous loop. Blocks until stopped or max_episodes reached. If param_space, agent_factory, and pipeline_factory are provided, runs trial search first, then full training with best params. ```APIDOC ## RLOptimizer.run ### Description Starts the autonomous loop. Blocks until stopped or max_episodes reached. If param_space, agent_factory, and pipeline_factory are provided, runs trial search first, then full training with best params. ### Method run ### Signature ```python def run(self) -> None: ``` ### Behavior - If param_space + agent_factory + pipeline_factory were provided: 1. Runs TrialOrchestrator to find best hyperparameter configuration. 2. Calls agent_factory(best_params) and pipeline_factory() to build the agent and pipeline for the full training run. 3. Runs the main loop with those params + SPSA online adaptation. ``` -------------------------------- ### PromotionPolicy.__init__ Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/learning-to-learn.md Initializes a PromotionPolicy instance with configuration for strategy promotion. The policy evaluates candidate strategies against criteria and can operate in human or auto approval mode. ```APIDOC ## PromotionPolicy.__init__ ### Description Initializes a PromotionPolicy instance with configuration for strategy promotion. The policy evaluates candidate strategies against criteria and can operate in human or auto approval mode. ### Method Constructor ### Signature ```python PromotionPolicy( store: ExperimentStore, *, margin: float = 0.0, min_seeds: int = 3, min_held_out_tasks: int = 1, max_compute_ratio: float = 1.5, approval_mode: str = "human" # "human" | "auto" -- ValueError otherwise ) ``` ### Parameters - **store** (ExperimentStore) - Required - The experiment store used for persistence. - **margin** (float) - Optional - Margin for baseline comparison. Defaults to 0.0. - **min_seeds** (int) - Optional - Minimum number of seeds required. Defaults to 3. - **min_held_out_tasks** (int) - Optional - Minimum number of held-out tasks required. Defaults to 1. - **max_compute_ratio** (float) - Optional - Maximum compute ratio allowed. Defaults to 1.5. - **approval_mode** (str) - Optional - Approval mode: "human" or "auto". Defaults to "human". Raises ValueError for other values. ### Response No return value. ``` -------------------------------- ### Optimizer initialization with various loss functions Source: https://github.com/sup3rus3r/tensor-optix Shows how to create an Optimizer with different loss configurations: auto loss, MSE, reconstruction, VAE, contrastive, DataLoader, custom nn.Module, and cosine. The VAE model must return (recon, mu, logvar), and the contrastive dataset must yield (view1, view2). ```python opt = optix.Optimizer(model, train_dataset) # auto loss opt = optix.Optimizer(model, train_dataset, loss="mse") opt = optix.Optimizer(autoencoder, train_dataset, loss="reconstruction") opt = optix.Optimizer(vae, train_dataset, loss="vae") # model returns (recon, mu, logvar) opt = optix.Optimizer(encoder, pairs_dataset, loss="contrastive") # dataset yields (view1, view2) opt = optix.Optimizer(model, DataLoader(dataset, batch_size=64)) opt = optix.Optimizer(model, dataset, loss=nn.HuberLoss()) # any nn.Module opt = optix.Optimizer(model, dataset, loss="cosine") opt.run() ``` -------------------------------- ### HebbianHook Usage Example Source: https://github.com/sup3rus3r/tensor-optix Example showing how to instantiate and use HebbianHook in a training loop. ```APIDOC ## HebbianHook Usage Example ### Description Example showing how to instantiate and use HebbianHook in a training loop. ### Example ```python from tensor_optix.neuroevo import HebbianHook hook = HebbianHook(graph, hebbian_lr=1e-3, weight_decay=1e-4) for step in episode: action = agent.act(obs); hook.record() obs, reward, done, _ = env.step(action) agent.learn(episode_data); hook.apply(); hook.reset() ``` ``` -------------------------------- ### Load config, build agent, and round-trip to dict in Python Source: https://github.com/sup3rus3r/tensor-optix Shows how to load a YAML config with overrides, build an agent from it, and convert the config back to a dict. The overrides parameter updates optimizer.max_episodes to 500. Requires the config.yaml file from the example above. ```python from tensor_optix import load_config, config_to_dict from tensor_optix.config import build_agent_from_config cfg = load_config("config.yaml", overrides=["optimizer.max_episodes=500"]) print(cfg.env, cfg.seed, cfg.agent) agent, hyperparams = build_agent_from_config(cfg) print(hyperparams.params) # Round-trip back to a dict d = config_to_dict(cfg) ``` -------------------------------- ### VectorBatchPipeline.setup Source: https://github.com/sup3rus3r/tensor-optix Sets up the pipeline, initializing the vector environment. If async_envs=True and env_fns are not picklable, falls back to SyncVectorEnv with a warning. ```APIDOC ## VectorBatchPipeline.setup ### Description Sets up the pipeline, initializing the vector environment. If async_envs=True and env_fns are not picklable, falls back to SyncVectorEnv with a warning. ### Method Method ### Signature ```python def setup(self): ``` ### Notes - This method is called before iterating over `episodes()`. ``` -------------------------------- ### compute_vtrace_targets usage example Source: https://github.com/sup3rus3r/tensor-optix Example of calling compute_vtrace_targets with rewards, values, behaviour_log_probs, current_log_probs, dones, and default hyperparameters. ```python from tensor_optix.distributed import compute_vtrace_targets vs, adv = compute_vtrace_targets( rewards, values, behaviour_log_probs, current_log_probs, dones, gamma=0.99, rho_bar=1.0, c_bar=1.0, ) ``` -------------------------------- ### HebbianHook usage example Source: https://github.com/sup3rus3r/tensor-optix Example of using HebbianHook in a training loop: create hook, record co-activation after each action, then apply and reset after learning. ```python from tensor_optix.neuroevo import HebbianHook hook = HebbianHook(graph, hebbian_lr=1e-3, weight_decay=1e-4) for step in episode: action = agent.act(obs); hook.record() obs, reward, done, _ = env.step(action) agent.learn(episode_data); hook.apply(); hook.reset() ``` -------------------------------- ### BatchPipeline usage example Source: https://github.com/sup3rus3r/tensor-optix Example of creating a BatchPipeline with a Gymnasium CartPole-v1 env and iterating over episodes. The loop breaks after 2 episodes and calls teardown(). ```python import gymnasium as gym from tensor_optix import BatchPipeline, make_agent agent = make_agent(gym.make("CartPole-v1")) pipeline = BatchPipeline(env=gym.make("CartPole-v1"), agent=agent, window_size=2048) for episode in pipeline.episodes(): print(episode.episode_id, episode.length, episode.total_reward) if episode.episode_id >= 2: break pipeline.teardown() ``` -------------------------------- ### ExperimentLedgerCallback usage example Source: https://github.com/sup3rus3r/tensor-optix Example of creating an ExperimentLedgerCallback and adding it to an optimizer (opt) with an ExperimentStore. The store is backed by a SQLite file, and the callback records the loop for the Learning-to-Learn Engine. ```python from tensor_optix.ledger import ExperimentStore from tensor_optix.callbacks import ExperimentLedgerCallback store = ExperimentStore("./exp.sqlite3") opt.add_callback(ExperimentLedgerCallback( store=store, task_env="CartPole-v1", algorithm="PPO", seed=0, checkpoint_dir="./ckpt", )) ``` -------------------------------- ### BrainNetwork usage example Source: https://github.com/sup3rus3r/tensor-optix Example of creating a BrainNetwork, adding regions, adding a pathway, and attaching a TopologyController. Note that add_pathway and add_inter_region_edge raise ValueError for unknown regions or regions with no connectible neurons. ```python from tensor_optix.neuroevo import BrainNetwork, NeuronGraph, TopologyController brain = BrainNetwork() brain.add_region("sensory", sensory_graph) brain.add_region("executive", exec_graph) brain.add_pathway("sensory", "executive", n_connections=8, delay=1) tc = TopologyController.for_brain(brain, scheduler=opt._scheduler) opt.add_callback(tc) ``` -------------------------------- ### Create and manage experiment ledger with ExperimentStore Source: https://github.com/sup3rus3r/tensor-optix/blob/main/README.md Records an experiment with full provenance and lifecycle in a SQLite-backed ledger. Writes are idempotent on experiment_id and each method uses a short, single-statement transaction. ```python from tensor_optix.ledger import ExperimentStore, ExperimentState store = ExperimentStore("./experiments.sqlite3") record = store.create_experiment( task_env="CartPole-v1", algorithm="PPO", framework="torch", seed=0, checkpoint_dir="./ckpt", solve_threshold=475.0, ) store.start_experiment(record.experiment_id) store.record_progress(record.experiment_id, best_primary_score=480.0) store.finalize_experiment(record.experiment_id, state=ExperimentState.COMPLETED) ``` -------------------------------- ### Dale's Law clamp mode Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/neuroevo.md Clamp mode (default) clamps outgoing weights post-step. Excitatory neurons get weights >= 0, inhibitory neurons get weights <= 0. Use for simple enforcement. ```python # clamp mode (default): outgoing weights clamped post-step graph = NeuronGraph(dale_mode="clamp") graph.add_neuron(role="hidden", activation="relu", cell_type="excitatory") # weights >= 0 graph.add_neuron(role="hidden", activation="tanh", cell_type="inhibitory") # weights <= 0 ``` -------------------------------- ### BaseAgent.get_hyperparams Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/custom-agent.md Get the current hyperparameters of the agent. ```APIDOC ## BaseAgent.get_hyperparams ### Description Get the current hyperparameters of the agent. ### Method get_hyperparams ### Returns - **HyperparamSet** - The current hyperparameters. ``` -------------------------------- ### DiagnosticController.__init__ Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/core/diagnostic_controller.md Initializes the DiagnosticController with configurable thresholds and rules for monitoring agent training diagnostics. Parameters control loss spike detection, entropy collapse, KL divergence, and DQN epsilon reset behavior. ```APIDOC ## DiagnosticController.__init__ ### Description Initializes the DiagnosticController with configurable thresholds and rules for monitoring agent training diagnostics. Parameters control loss spike detection, entropy collapse, KL divergence, and DQN epsilon reset behavior. ### Method Constructor ### Parameters #### Constructor Parameters - **loss_spike_factor** (float) - Optional - Fire loss-explosion rule when loss > N × rolling mean. Default 5.0 - catches genuine explosions, not noise. - **loss_window** (int) - Optional - Rolling window for computing mean loss. Default 10. - **entropy_floor** (Optional[float]) - Optional - PPO: fire entropy-collapse rule below this value. Default 0.05 (nats). Env-specific - set to None to disable. - **target_kl** (Optional[float]) - Optional - PPO: fire KL-too-high rule above 2 × this value. Default 0.02. Set to None to disable. - **epsilon_patience** (int) - Optional - DQN: episodes at epsilon_min before reset fires. Default 20. Set to 0 to disable. - **epsilon_reset_value** (float) - Optional - DQN: value to reset epsilon to. Default 0.3. - **epsilon_score_threshold** (float) - Optional - DQN: only reset epsilon if score is below this. Prevents resetting during active exploitation. Default 20.0 (well above random CartPole ~9). - **min_episodes** (int) - Optional - Minimum episodes before any rule can fire. Default 5 - lets the loss mean stabilise first. - **verbose** (bool) - Optional - Print a line whenever a rule fires. ``` -------------------------------- ### TrialOrchestrator.trials_dataframe Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/orchestrator.md Returns a pandas DataFrame of all trial results. Requires pandas to be installed. ```APIDOC ## TrialOrchestrator.trials_dataframe ### Description Return a pandas DataFrame of all trial results (requires pandas). ### Method trials_dataframe() ### Parameters None ### Returns - **pandas.DataFrame** - DataFrame containing all trial results. ``` -------------------------------- ### reset_state() Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/neuroevo/neuron-graph.md Zeros all neuron histories. Call at episode start. ```APIDOC ## reset_state() ### Description Zeros all neuron histories. Call at episode start. ### Method reset_state ### Parameters None ### Returns None ``` -------------------------------- ### state (property) Source: https://github.com/sup3rus3r/tensor-optix Gets the current LoopState of the loop. ```APIDOC ## state (property) ### Description Current LoopState. ### Method state ### Signature ```python @property def state(self) -> LoopState: ``` ### Returns - **LoopState** - The current loop state. ``` -------------------------------- ### ExperimentStore.start_experiment Source: https://github.com/sup3rus3r/tensor-optix Transitions an experiment from CREATED to RUNNING state. ```APIDOC ## ExperimentStore.start_experiment ### Description Transitions an experiment from CREATED to RUNNING state. ### Method Method ### Parameters #### Parameters - **experiment_id** (str) - Required - The ID of the experiment to start. ``` -------------------------------- ### TrialOrchestrator.run Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/orchestrator.md Runs all trials and returns the best parameters and score. Each trial uses TPE to suggest a configuration, builds a fresh agent and pipeline via factories, and runs RLOptimizer for at most trial_steps environment steps. ```APIDOC ## TrialOrchestrator.run ### Description Run all trials and return (best_params, best_score). Each trial: TPE suggests a config → fresh agent/pipeline built via factories → RLOptimizer runs for at most trial_steps env steps → best smoothed score reported to Optuna → MedianPruner may stop the trial early if the score is poor. The best trial's weights are accessible via best_weights_path. ### Method run() ### Parameters None ### Returns - **best_params** (Dict[str, Any]) - The best hyperparameters found. - **best_score** (float) - The best score achieved. ``` -------------------------------- ### HebbianHook.reset Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/neuroevo/hebbian.md Clears all accumulated co-activation data. Call at episode start or end. ```APIDOC ## reset ### Description Clears all accumulated co-activation data. Call at episode start or end. ### Method Instance method ### Signature ```python def reset(self) -> None ``` ### Parameters None ### Returns None ``` -------------------------------- ### Initialize and run LiveAdaptiveRuntime Source: https://github.com/sup3rus3r/tensor-optix/blob/main/README.md Configures and runs the LiveAdaptiveRuntime loop for a CartPole environment with PPO, issuing recommendation records without approving strategies. ```python from tensor_optix.runtime import LiveAdaptiveRuntime, RuntimeConfig config = RuntimeConfig(task_env="CartPole-v1", algorithm="PPO", max_cycles=20) runtime = LiveAdaptiveRuntime(store, config, agent_factory=make_agent, pipeline_factory=make_pipeline) observations, recommendations = runtime.run() ``` -------------------------------- ### run() Source: https://github.com/sup3rus3r/tensor-optix Starts the autonomous optimization loop. This method blocks until the loop is stopped. ```APIDOC ## run() ### Description Starts the autonomous optimization loop. This method blocks until the loop is stopped. ### Method run ### Signature ```python def run(self) -> None: ``` ### Behavior - In factory mode (agent_factory + pipeline_factory + param_space): 1. Runs `TrialOrchestrator` to find best hyperparameters. 2. Calls `agent_factory(best_params)` and `pipeline_factory()`. 3. Warm-starts weights from the best trial checkpoint (best weights loaded), then removes the trial checkpoint dirs. 4. Runs the main loop with those params plus SPSA online adaptation. - In non-factory mode, runs the main loop directly. ### Errors - Raises `RuntimeError` if no controller available and no factory mode. ``` -------------------------------- ### best_snapshot (property) Source: https://github.com/sup3rus3r/tensor-optix Gets the best known checkpoint (PolicySnapshot) recorded so far. ```APIDOC ## best_snapshot (property) ### Description Best known checkpoint. ### Method best_snapshot ### Signature ```python @property def best_snapshot(self) -> Optional[PolicySnapshot]: ``` ### Returns - **Optional[PolicySnapshot]** - The best known checkpoint, or None if none exists. ``` -------------------------------- ### Optimizer constructor Source: https://github.com/sup3rus3r/tensor-optix Creates an Optimizer instance that wraps RLOptimizer with sensible defaults. It auto-computes window_size, wires neuroevo callbacks, activates SPSA when the agent has default_param_bounds, and handles both RL and ML paths. ```APIDOC ## Optimizer constructor ### Description Creates an Optimizer instance that wraps RLOptimizer with sensible defaults. It auto-computes window_size, wires neuroevo callbacks, activates SPSA when the agent has default_param_bounds, and handles both RL and ML paths. ### Method Constructor ### Signature ```python def __init__( self, agent, env, n_envs: int = 1, window_size: Optional[int] = None, max_episodes: Optional[int] = None, callbacks: Optional[List] = None, rollback_on_degradation: bool = False, checkpoint_dir: str = "./tensor_optix_checkpoints", optimizer=None, loss="auto", batch_size: int = 64, shuffle: bool = True, **kwargs, ): ``` ### Parameters - **agent** (BaseAgent | nn.Module) - Required - RL agent or ML model - **env** (env | callable | Dataset | DataLoader) - Required - RL env (or factory), or ML dataset - **n_envs** (int) - Optional - Default: `1` - Parallel envs; >1 requires env as callable/list - **window_size** (int | None) - Optional - Default: `None` - Pipeline window; auto if `None` - **max_episodes** (int | None) - Optional - Default: `None` - Episode budget (RL path) / epochs (ML path) - **callbacks** (list) - Optional - Default: `None` - Extra `LoopCallback`s - **rollback_on_degradation** (bool) - Optional - Default: `False` - Restore best weights on degradation - **checkpoint_dir** (str) - Optional - Default: `"./tensor_optix_checkpoints"` - Snapshot dir - **optimizer** (BaseOptimizer) - Optional - Default: `None` → SPSA from agent bounds - Hyperparameter tuner - **loss** (str | nn.Module) - Optional - Default: `"auto"` - ML path only — loss key or module - **batch_size** (int) - Optional - Default: `64` - ML path batch size - **shuffle** (bool) - Optional - Default: `True` - ML path shuffle - **kwargs** (—) - Optional - Forwarded to `RLOptimizer` ### ML-mode detection ML mode is selected when `agent` is an `nn.Module` (and not a `BaseAgent`) AND `env` is a `Dataset` or `DataLoader`. In ML mode, an `MLAgent` + `DatasetPipeline` and SPSA are wired automatically. In ML mode the same `Optimizer` / `run()` surface is preserved via an internal `RLOptimizer` wrapping `MLAgent` + `DatasetPipeline`. ``` -------------------------------- ### Optimizer Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/optimizer.md Simplified entry point for training. Wraps RLOptimizer with sensible defaults. ```APIDOC ## Optimizer ### Description Simplified entry point for training. Wraps RLOptimizer with sensible defaults. ### Constructor ```python Optimizer( agent, env, n_envs: int = 1, window_size: Optional[int] = None, max_episodes: Optional[int] = None, callbacks: Optional[List] = None, rollback_on_degradation: bool = False, checkpoint_dir: str = "./tensor_optix_checkpoints", optimizer=None, loss="auto", batch_size: int = 64, shuffle: bool = True, **kwargs, ) ``` ### Parameters - **agent** - Required - A fully-constructed agent from make_agent() or built manually. - **env** - Required - A Gymnasium environment. Used for window_size estimation and as the training environment when n_envs=1. - **n_envs** (int) - Optional - Number of parallel environments. When >1, pass env as a callable (``lambda: gym.make("EnvName")``) or a list of callables. - **window_size** (Optional[int]) - Optional - Number of steps per training window. When None, computed automatically from env and agent type. - **max_episodes** (Optional[int]) - Optional - Stop after this many episodes. None means run indefinitely. - **callbacks** (Optional[List]) - Optional - Additional LoopCallback instances to attach. - **rollback_on_degradation** (bool) - Optional - Roll back to the best checkpoint when performance degrades. - **checkpoint_dir** (str) - Optional - Directory for saving policy snapshots. - **kwargs** - Optional - Additional keyword arguments forwarded to RLOptimizer. ``` -------------------------------- ### get_device() Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/core/device.md Returns the global tensor-optix device as a torch.device. Lazily imports torch so the call works once PyTorch is installed. ```APIDOC ## get_device() ### Description Returns the global tensor-optix device as a torch.device. Lazily imports torch so the call works once PyTorch is installed. ### Method Function ### Signature `get_device() -> "torch.device"` ### Returns - **torch.device** - The current global device. ``` -------------------------------- ### Create and manage an experiment with ExperimentStore Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/guides/learning-to-learn.md Use the SQLite-backed ExperimentStore to record a trial's provenance, lifecycle state, and scores. Every write is idempotent on experiment_id and each method opens a short, single-statement transaction. ```python from tensor_optix.ledger import ExperimentStore, ExperimentState, EvaluationStatus store = ExperimentStore("./experiments.sqlite3") record = store.create_experiment( task_env="CartPole-v1", algorithm="PPO", framework="torch", seed=0, checkpoint_dir="./ckpt", solve_threshold=475.0, ) store.start_experiment(record.experiment_id) store.record_progress(record.experiment_id, best_primary_score=480.0) store.finalize_experiment( record.experiment_id, state=ExperimentState.COMPLETED, evaluation_status=EvaluationStatus.VALIDATED, ) ``` -------------------------------- ### Use BatchPipeline, LivePipeline, and VectorBatchPipeline Source: https://github.com/sup3rus3r/tensor-optix/blob/main/README.md Three pipeline implementations step an environment or data source, collect EpisodeData, and yield it to the agent. BatchPipeline steps a Gymnasium env continuously without reset between windows; LivePipeline uses a background thread with bounded queue and configurable episode boundaries; VectorBatchPipeline runs N parallel envs via gymnasium.vector, sync or async subprocess. ```python from tensor_optix import BatchPipeline, LivePipeline, VectorBatchPipeline # Gymnasium env: steps continuously, no reset between windows pipeline = BatchPipeline(env=gym.make("CartPole-v1"), agent=agent, window_size=200) # External data stream: background thread with bounded queue, configurable episode boundaries pipeline = LivePipeline( data_source=MyFeed(), agent=agent, episode_boundary_fn=LivePipeline.every_n_seconds(300), ) # N parallel envs via gymnasium.vector, sync or async subprocess pipeline = VectorBatchPipeline( env_fns=[lambda: gym.make("CartPole-v1")] * 8, agent=agent, window_size=200, ) ``` -------------------------------- ### Usage example Source: https://github.com/sup3rus3r/tensor-optix/blob/main/tensor-optix-docs/docs/reference/neuroevo/neuromodulator.md Shows how to instantiate NeuromodulatorSignal with a RegimeDetector and optional hooks, call step() after each episode, or wire it as a callback to Optimizer. ```python from tensor_optix.neuroevo import NeuromodulatorSignal from tensor_optix.core import RegimeDetector signal = NeuromodulatorSignal( detector=RegimeDetector(), hebbian_hook=hook, agent=agent, topology_controller=tc, ) # In your training loop, after each episode: signal.step(metrics_history) # Or wire as a callback - called automatically each episode opt = Optimizer(agent, env, callbacks=[hook, signal]) opt.run() ``` -------------------------------- ### RichDashboardCallback usage example Source: https://github.com/sup3rus3r/tensor-optix Shows how to instantiate and add RichDashboardCallback to an optimizer with custom title and refresh rate. ```python from tensor_optix.callbacks import RichDashboardCallback opt.add_callback(RichDashboardCallback(title="My run", refresh_per_second=8)) ```