braintools.trainer module#
Trainer module for PyTorch Lightning-like training in JAX.
This module provides a comprehensive training framework including: - LightningModule: Base class for defining training models - Trainer: Orchestration class for training loops - Callbacks: Hook system for customizing training behavior - Loggers: Pluggable logging backends (TensorBoard, WandB, CSV, etc.) - DataLoader: JAX-compatible data loading with distributed support - Distributed: Strategies for multi-device and multi-host training
Example
>>> import braintools
>>> import brainstate
>>>
>>> class MyModel(braintools.trainer.LightningModule):
... def __init__(self):
... super().__init__()
... self.linear = brainstate.nn.Linear(784, 10)
...
... def __call__(self, x):
... return self.linear(x)
...
... def training_step(self, batch, batch_idx):
... x, y = batch['x'], batch['y']
... logits = self(x)
... loss = jnp.mean((logits - y) ** 2)
... self.log('train_loss', loss)
... return {'loss': loss}
...
... def configure_optimizers(self):
... return braintools.optim.Adam(lr=1e-3)
...
>>> model = MyModel()
>>> trainer = braintools.trainer.Trainer(max_epochs=10)
>>> train_loader = braintools.trainer.DataLoader(data, batch_size=32)
>>> trainer.fit(model, train_loader)
A PyTorch-Lightning-style training framework for JAX / brainstate models.
It bundles the training loop, validation/testing/prediction, a callback and
logging system, checkpointing, data loading, and multi-device strategies into a
single high-level API.
Overview#
The braintools.trainer module provides:
LightningModule – base class for defining models, training/validation steps, and optimizers.
Trainer – orchestrates the full fit/validate/test/predict loops.
Callbacks – hooks for checkpointing, early stopping, LR monitoring, etc.
Loggers – pluggable logging backends (CSV, TensorBoard, WandB, …).
DataLoader – JAX-compatible batching, shuffling, and sampling.
Distributed strategies – single-device, data-parallel, sharded, and FSDP.
Checkpointing – save/restore model and optimizer state.
Note
Metrics logged via LightningModule.log() are referenced by the trainer
and callbacks under the name you pass. The trainer prefixes aggregated
validation/test metrics with val_/test_ only when the name does not
already start with that prefix, so self.log('val_loss', ...) is surfaced
as val_loss (not val_val_loss).
Core Classes#
The two classes you interact with most: subclass LightningModule to
define your model and call Trainer.fit() to train it.
Base class for all training modules. |
|
Orchestrates the training process. |
|
Container for trainer state during training. |
|
Output container for training step. |
|
Output container for evaluation steps (validation/test). |
Callbacks#
Callbacks hook into the training loop to add behavior without modifying the
model. Callback is the base class; CallbackList dispatches to a list of
callbacks.
Base class for callbacks. |
|
Container for multiple callbacks. |
|
Save model checkpoints based on monitored metric. |
|
Stop training when a monitored metric has stopped improving. |
|
Monitor and log learning rate during training. |
|
Placeholder callback for gradient clipping configuration. |
|
Track training time. |
|
Rich progress bar for training visualization. |
|
TQDM progress bar for training visualization. |
|
Create a callback from lambda functions. |
|
Simple callback that prints training progress. |
Loggers#
Pluggable logging backends. Pass an instance (or list) to the logger
argument of Trainer.
Abstract base class for all loggers. |
|
CSV file logging backend. |
|
TensorBoard logging backend. |
|
Weights & Biases logging backend. |
|
Neptune.ai logging backend. |
|
MLflow logging backend. |
|
Combine multiple loggers. |
Data Loading#
JAX-compatible datasets, samplers, and loaders.
JAX-compatible data loader. |
|
DataLoader for distributed training. |
|
Abstract base class for datasets. |
|
Dataset wrapping arrays. |
|
Dataset wrapping a dictionary of arrays. |
|
Dataset wrapping an iterable. |
|
Base class for samplers. |
|
Samples elements randomly. |
|
Samples elements sequentially. |
|
Wraps a sampler to yield batches of indices. |
|
Sampler for distributed training. |
Create batches suitable for distributed training with pmap. |
Distributed Strategies#
Strategies that control how the model and data are distributed across devices.
Abstract base class for distributed training strategies. |
|
Single device strategy (no distribution). |
|
Data parallel strategy using pmap. |
|
Sharded data parallel strategy using jax.sharding. |
|
Fully Sharded Data Parallel (FSDP) strategy. |
|
Automatically select the best strategy based on available devices. |
Get a distributed training strategy by name. |
|
All-reduce tensor across devices. |
|
Broadcast tensor from source device to all devices. |
Checkpointing#
Utilities to save and restore training state.
Manager for saving and loading checkpoints. |
Save a checkpoint to disk. |
|
Load a checkpoint from disk. |
|
Find a checkpoint file in a directory. |
|
List all checkpoints in a directory. |
Progress Bars#
Abstract base class for progress bars. |
|
Simple text-based progress bar with no dependencies. |
|
Progress bar wrapper using tqdm. |
|
Progress bar wrapper using rich. |
Get a progress bar instance. |