Skip to content

Trainer API

Battery remains the public workflow facade. Its checkpoint, fitting, training, standalone validation, testing, prediction, and streaming-prediction methods are documented here even though their implementations are organized into focused private trainer modules. Applications should continue importing only Battery from torch_batteries or torch_batteries.trainer.

Use fit() for combined training and optional validation, train() for training-only work, and validate() for a required single validation pass. fit() can validate on absolute epoch multiples through validate_every_n_epochs. Train and fit results include cumulative completion counters and a stop reason. Use request_stop(reason) from callbacks for an orderly stop.

torch_batteries.trainer

Event-driven model training, evaluation, and prediction.

Public API

  • Battery — orchestrates device placement, steps, optimization, metrics, callbacks, checkpoints, testing, and prediction.
  • StepOutput — explicit loss, predictions, targets, and manual metrics returned from a train, validation, or test step.
  • FitResult — per-epoch training and optional validation histories.
  • TrainResult — per-epoch training histories.
  • ValidationResult — aggregate standalone validation loss and metrics.
  • TestResult — aggregate test loss and metrics.
  • PredictResult — collected or recursively concatenated prediction output.

Battery Source

Bases: CheckpointMixin, TrainingMixin, EvaluationMixin, PredictionMixin

Run event-driven training, evaluation, and prediction for a PyTorch model.

Battery discovers model methods decorated with :func:~torch_batteries.charge and dispatches lifecycle events to the model and configured callbacks. It moves the model and batches to the selected device, aggregates losses and metrics, and can save complete resumable training state.

Parameters:

Name Type Description Default
model Module

Model containing the charged step methods. It is moved to device.

required
device str | device

Explicit PyTorch device or "auto". Automatic selection prefers CUDA, then MPS, then CPU.

'auto'
optimizer Optimizer | None

Optimizer used by :meth:train. It is optional for testing and prediction.

None
metrics MetricsConfig | None

Named callable or stateful metrics. When metrics are configured, train, validation, and test steps must return :class:StepOutput with predictions and targets.

None
callbacks list | None

Ordered callback objects. Callback order is significant for provider-style optimization events.

None
data_pack DataPack | None

Optional event-driven dataset and DataLoader configuration. When attached, workflow loaders may be omitted.

None
metric_error_policy Literal['raise', 'warn']

"raise" to propagate metric lifecycle exceptions. "warn" logs the failure and skips that metric for the phase.

'raise'
Note

Epoch values exposed through event contexts are one-based. Prediction output stays on its current device unless move_to_cpu=True is requested.

model property

Get the model.

device property

Get the device.

data_pack property

Get the event-driven data configuration attached to this Battery.

optimizer property writable

Get the optimizer.

metrics property writable

Get the metrics dictionary.

metric_error_policy property writable

Get the configured metric exception handling policy.

stop_training property writable

Get the stop_training flag.

request_stop(reason) Source

Request training stop after the current epoch.

Parameters:

Name Type Description Default
reason str

Non-empty reason reported in the run result.

required

save_checkpoint(path) Source

Save complete resumable training state atomically.

Parameters:

Name Type Description Default
path str | Path

Destination checkpoint path. Parent directories are created.

required

Raises:

Type Description
OSError

If the destination cannot be created or replaced.

Exception

If PyTorch serialization fails.

load_checkpoint(path) Source

Restore a full checkpoint or raw model state.

Parameters:

Name Type Description Default
path str | Path

Trusted checkpoint or model-state path.

required

Raises:

Type Description
ValueError

If saved state is incompatible with this Battery.

TypeError

If the checkpoint structure is invalid.

RuntimeError

If strict PyTorch state restoration fails.

train(train_loader=None, epochs=1, verbose=1, *, resume_from=None, resume_epochs_mode='total') Source

Train with explicit loaders or the attached DataPack.

Use fit for combined training and validation.

Parameters:

Name Type Description Default
train_loader DataLoader | None

Optional sized, non-empty training loader.

None
epochs int

Positive epoch count or resume target.

1
verbose int

0 for silent, 1 for bars, or 2 for summaries.

1
resume_from str | Path | None

Optional full checkpoint restored before data setup.

None
resume_epochs_mode str

"total" or "additional".

'total'

Returns:

Type Description
TrainResult

Per-epoch loss and named metric histories.

fit(train_loader=None, val_loader=None, epochs=1, verbose=1, *, resume_from=None, resume_epochs_mode='total', validate_every_n_epochs=1) Source

Train with optional per-epoch validation.

Parameters:

Name Type Description Default
train_loader DataLoader | None

Optional sized, non-empty training loader.

None
val_loader DataLoader | None

Optional validation loader for direct-loader mode.

None
epochs int

Positive epoch count or resume target.

1
verbose int

0 for silent, 1 for bars, or 2 for summaries.

1
resume_from str | Path | None

Optional full checkpoint restored before data setup.

None
resume_epochs_mode str

"total" or "additional".

'total'
validate_every_n_epochs int

Run validation on absolute epoch multiples.

1

Returns:

Type Description
FitResult

Per-epoch training histories and optional validation histories. Validation

FitResult

histories are empty when validation data is unavailable.

validate(val_loader=None, verbose=1) Source

Run one standalone validation pass.

Parameters:

Name Type Description Default
val_loader DataLoader | None

Optional sized, non-empty validation loader. When omitted, the attached DataPack must provide validation data.

None
verbose int

0 for silent, 1 for a bar, or 2 for a summary.

1

Returns:

Type Description
ValidationResult

Aggregate validation loss and optional named validation metrics.

test(test_loader=None, verbose=1, *, dataset=None) Source

Evaluate an explicit or DataPack-provided test dataset.

Parameters:

Name Type Description Default
test_loader DataLoader | None

Optional sized, non-empty test loader.

None
verbose int

0 for silent, 1 for a bar, or 2 for a summary.

1
dataset str | None

Optional DataPack test dataset name.

None

Returns:

Type Description
TestResult

One aggregate result with named dataset metrics when applicable.

predict(data_loader=None, verbose=1, *, move_to_cpu=False, concatenate=False, dataset=None) Source

Collect predictions from an explicit or DataPack loader.

Parameters:

Name Type Description Default
data_loader DataLoader | None

Optional sized, non-empty prediction loader.

None
verbose int

0 for silent, 1 for a bar, or 2 for a summary.

1
move_to_cpu bool

Detach tensor outputs and move them to CPU.

False
concatenate bool

Concatenate compatible batch output structures.

False
dataset str | None

Optional DataPack prediction dataset name.

None

Returns:

Type Description
PredictResult

One result, with predictions keyed by dataset when several run.

predict_iter(data_loader=None, verbose=1, *, move_to_cpu=False, dataset=None) Source

Yield predictions from an explicit or DataPack loader.

Parameters:

Name Type Description Default
data_loader DataLoader | None

Optional sized, non-empty prediction loader.

None
verbose int

0 for silent, 1 for a bar, or 2 for a summary.

1
move_to_cpu bool

Detach tensor outputs and move them to CPU.

False
dataset str | None

Optional DataPack prediction dataset name.

None

Yields:

Type Description
Generator[Any]

One prediction-step output at a time.

FitResult Source

Bases: TypedDict

Result from fitting.

Attributes:

Name Type Description
train_loss list[float]

Average training loss for every completed epoch.

val_loss list[float]

Average validation loss for every completed epoch, or an empty list when validation data was unavailable.

train_metrics dict[str, list[float]]

Named training metric histories.

val_metrics dict[str, list[float]]

Named validation metric histories, or an empty mapping when validation data was unavailable.

epochs_completed int

Cumulative completed epochs, including resumed history.

optimizer_steps int

Cumulative optimizer steps, including resumed history.

stopped_early bool

Whether a stop was requested during this run.

stop_reason str | None

Reason supplied to request_stop, or None.

PredictResult Source

Bases: TypedDict

Collected prediction output.

Attributes:

Name Type Description
predictions Any

Batch list or recursively concatenated prediction structure.

StepOutput Source dataclass

Explicit output from a training, validation, or test step.

Test steps may omit loss when no meaningful loss exists; the test result then has no test_loss. All test steps in a run must agree on whether they return a loss. Training and validation steps always require it.

Outputs can be combined with +, for example to build a multi-head step from one output per head. Losses are summed, while predictions, targets, and metrics are merged by key. Missing losses are skipped, and sum(outputs) is supported as well.

Parameters:

Name Type Description Default
loss Tensor | None

Scalar tensor used for reporting and, during training, backward. Optional for test steps only.

None
predictions StructuredTensors | None

Outputs produced by the same forward pass as loss.

None
targets StructuredTensors | None

Ground-truth tensors corresponding to predictions.

None
metrics dict[str, float | Tensor]

Named scalar tensors or numeric values calculated by the step.

dict()

Raises:

Type Description
ValueError

On + when both sides share a predictions, targets, or metrics key.

TypeError

On + when both sides set predictions or targets and they are not both dictionaries.

TestResult Source

Bases: TypedDict

Result from testing.

Attributes:

Name Type Description
test_loss float

Average test loss across all batches.

test_metrics dict[str, float]

Named average test metrics.

TrainResult Source

Bases: TypedDict

Result from training.

Attributes:

Name Type Description
train_loss list[float]

Average training loss for every completed epoch.

train_metrics dict[str, list[float]]

Named training metric histories.

epochs_completed int

Cumulative completed epochs, including resumed history.

optimizer_steps int

Cumulative optimizer steps, including resumed history.

stopped_early bool

Whether a stop was requested during this run.

stop_reason str | None

Reason supplied to request_stop, or None.

ValidationResult Source

Bases: TypedDict

Result from one standalone validation pass.

Attributes:

Name Type Description
val_loss float

Average validation loss.

val_metrics dict[str, float]

Named validation metrics when any are produced.