Trainer#
- class braintools.trainer.Trainer(max_epochs=1000, min_epochs=1, max_steps=-1, val_check_interval=1.0, check_val_every_n_epoch=1, callbacks=None, logger=True, enable_progress_bar=True, enable_checkpointing=True, default_root_dir=None, gradient_clip_val=None, gradient_clip_algorithm='norm', accumulate_grad_batches=1, devices='auto', strategy='auto', precision='32', deterministic=False, benchmark=False, seed=None)#
Orchestrates the training process.
The Trainer handles the training loop, validation, testing, and prediction, integrating callbacks, logging, checkpointing, and distributed training.
- Parameters:
max_epochs (
int) – Maximum number of training epochs.min_epochs (
int) – Minimum number of training epochs.max_steps (
int) – Maximum number of training steps. -1 means no limit. A “step” is counted per processed batch; whenaccumulate_grad_batches > 1this counts micro-batches rather than optimizer updates.val_check_interval (
int|float) – How often to run validation within a training epoch. Integer = every N batches, float = fraction of epoch.check_val_every_n_epoch (
int) – Run validation every N epochs.callbacks (
List[Callback] |None) – List of callbacks to use.logger (
Logger|List[Logger] |bool) – Logger(s) to use. True = CSVLogger, False = no logging.enable_progress_bar (
bool) – Whether to show progress bars.enable_checkpointing (
bool) – Whether to enable automatic checkpointing.default_root_dir (
str|None) – Default root directory for logs and checkpoints.gradient_clip_val (
float|None) – Value for gradient clipping.gradient_clip_algorithm (
str) – Gradient clipping algorithm (‘norm’ or ‘value’).accumulate_grad_batches (
int) – Number of batches to accumulate gradients over before each optimizer step. Must be >= 1.devices (
int|List[int] |str) – Devices to use for training.'auto'uses all visible JAX devices; anintselects the first N; a list selects by index.strategy (
str|Strategy) – Distributed training strategy. The active training loop drives a single optimizer on the selected device(s); multi-host strategies are provided but not exercised byfit().precision (
str) – Requested compute precision ('32','16','bf16', optionally with a'-mixed'/'-true'suffix). Recorded for API compatibility; the loop currently computes in float32 and emits a warning for any non-32 value. Cast your model/data explicitly for reduced precision.deterministic (
bool) – Recorded for API compatibility. Determinism in JAX is governed by the PRNG keys you use and XLA flags; this flag does not itself change execution.benchmark (
bool) – Recorded for API compatibility; has no effect (XLA autotunes and there is no cuDNN benchmark switch in JAX). A warning is emitted if set.seed (
int|None) – Random seed for reproducibility. Seeds both NumPy andbrainstate.
Notes
Only the first optimizer returned by
LightningModule.configure_optimizers()is stepped by the training loop; configuring several emits a warning. Freeze parameters withLightningModule.freeze()before callingfit()to exclude them from gradients and optimizer updates.Examples
Basic usage:
>>> trainer = Trainer(max_epochs=10) >>> trainer.fit(model, train_loader, val_loader)
With callbacks and logging:
>>> trainer = Trainer( ... max_epochs=100, ... callbacks=[ ... ModelCheckpoint(dirpath='checkpoints/', monitor='val_loss'), ... EarlyStopping(monitor='val_loss', patience=5), ... ], ... logger=TensorBoardLogger('logs/'), ... ) >>> trainer.fit(model, train_loader, val_loader)
- fit(model, train_dataloaders=None, val_dataloaders=None, ckpt_path=None)[source]#
Run the full training loop.
- Parameters:
model (
LightningModule) – Model to train.train_dataloaders (
DataLoader|None) – Training data loader.val_dataloaders (
DataLoader|List[DataLoader] |None) – Validation data loader(s).
Examples
>>> trainer.fit(model, train_loader, val_loader)
- predict(model=None, dataloaders=None, ckpt_path=None)[source]#
Run prediction.
- Parameters:
model (
LightningModule|None) – Model to use for prediction.dataloaders (
DataLoader|List[DataLoader] |None) – Prediction data loader(s).
- Returns:
Predictions for each batch.
- Return type:
- test(model=None, dataloaders=None, ckpt_path=None, verbose=True)[source]#
Run testing.
- Parameters:
model (
LightningModule|None) – Model to test.dataloaders (
DataLoader|List[DataLoader] |None) – Test data loader(s).verbose (
bool) – Whether to print results.
- Returns:
Test metrics.
- Return type:
- validate(model=None, dataloaders=None, ckpt_path=None, verbose=True)[source]#
Run validation.
- Parameters:
model (
LightningModule|None) – Model to validate. Uses self.model if not provided.dataloaders (
DataLoader|List[DataLoader] |None) – Validation data loader(s).verbose (
bool) – Whether to print results.
- Returns:
Validation metrics.
- Return type: