Skip to content

Trainer

Trainer runs the host side of fitting and prediction. It prepares data sources, places arrays, calls one compiled update per step, dispatches hooks, logs metrics, saves checkpoints, handles interruption, and releases task resources.

Basic use

Construct a Trainer, fit a PhiModule blueprint, and pass the returned FitResult to predict():

from phijax import Trainer

trainer = Trainer(max_steps=10_000, accelerator="auto")
result = trainer.fit(
    module,
    datamodule=data_module,
    optimizer=optimizer,
    seed=0,
)
predictions = trainer.predict(result, datamodule=data_module)

The Trainer initializes the model and functional state during fit(). Applications do not need to call close() after a normal fit or prediction task. See Train and predict for checkpoint restoration, adaptive loss balancing, interruption, and the explicit state API.

What the Trainer manages

The Trainer owns orchestration around the compiled numerical update:

DataModule source -> cast and place batch -> compiled update -> hooks -> logging and checkpointing
                                              |
                                              +-> explicit TrainState

It manages:

  • DataModule setup, named batch construction, prediction batches, and teardown;
  • model initialization and independent runtime, sampling, and balancer PRNG streams;
  • precision conversion and device or data-parallel placement;
  • callback and module lifecycle ordering;
  • metric routing, progress displays, model summaries, and experiment loggers;
  • checkpoint restoration and persistence; and
  • graceful interruption and resource cleanup.

Losses, derivatives, gradients, balancing, and Optax updates remain inside the JIT-compiled step. Python hooks and filesystem operations remain outside it.

Configuration

Execution

Argument Supported values Default
max_steps Positive integer Required
callbacks Ordered iterable of callback instances ()
compilation_cache Mapping with enabled and, when enabled, directory None

max_steps is the global optimizer step at which training stops, as in Lightning. A fit resumed from step N runs max_steps - N updates. When the restored step already reaches max_steps, the fit runs its start and end hooks without training.

Deterministic GPU execution

The Trainer does not configure process-wide GPU determinism. Launch Python with the deterministic XLA options set before importing JAX:

XLA_FLAGS="--xla_gpu_exclude_nondeterministic_ops --xla_gpu_autotune_level=0" python train.py

See Randomness and reproducibility for seed requirements, performance and compilation trade-offs, and the official OpenXLA and JAX references.

Devices and precision

Argument Supported values Default
accelerator "auto", "cpu", "gpu", "tpu" "auto"
devices Positive count per process, local device-index sequence, or "auto" 1
strategy A configured Strategy, which replaces accelerator and devices None
precision "64-true", "32-true", "16-true", "bf16-true", "16-mixed", "bf16-mixed" "32-true"
matmul_precision None, "default", "high", "highest" None
derivative_dtype Floating dtype override None
initial_loss_scale Positive FP16 dynamic-loss scale; None uses 32768.0 None
loss_scale_growth_interval Positive interval between finite FP16 scale increases; None uses 2000 None

precision also accepts a resolved PrecisionPolicy, which already fixes its dtypes and loss scaling. Combining one with derivative_dtype, initial_loss_scale, or loss_scale_growth_interval raises ValueError instead of silently ignoring the option.

An explicit Strategy controls placement and distributed behavior. See Precision for dtype behavior and supported device combinations.

Logging and display

Argument Supported values Default
logger True, False, None, one logger, or an iterable of loggers True
default_root_dir Parent directory for default versioned logs "."
log_every_n_steps Positive scalar-logging interval 10
enable_progress_bar Boolean True
enable_model_summary Boolean True

logger=True selects TensorBoard when it is installed and CSV otherwise. The Trainer adds a TQDM progress bar and a plain model summary unless callbacks provide replacements. See Loggers and Callbacks for backend and display options.

Common and advanced workflows

The Trainer has two tasks, as Lightning's does: fit() and predict(). fit() builds and binds the model, compiles one train step, creates or restores the state, and obtains batches from the DataModule.

To predict later from a saved run, pass the module blueprint and the checkpoint: trainer.predict(module, ckpt_path=..., datamodule=data_module). The Trainer builds the model with the input statistics and periods stored in the checkpoint and restores only the model state, so prediction needs no optimizer, balancer, or fit-stage data.

A custom BasePhiModule takes part in both tasks by overriding configure_model(), which builds its model and returns its model state. prepare_batch_source() and prepare_batch() expose the Trainer's placement and precision policies to integrations.

Checkpoint-enabled applications resume with fit(..., ckpt_path="last"), and transfer weights with fit(..., ckpt_path=..., weights_only=True).

Metrics and status

The Trainer exposes the latest metric views without attaching mutable Trainer state to a module:

Property Contents
callback_metrics Complete merged metric mapping available to callbacks
logged_metrics Scalar metrics selected for experiment loggers
progress_bar_metrics Scalar metrics selected for progress displays
interrupted Whether the latest fit stopped after an interrupt
received_sigterm Whether the latest fit received SIGTERM
logger Configured logger collection

Metric mappings contain device values until a logger, display, checkpoint monitor, or caller requires host conversion. See Logging and monitoring for module and callback metric routing.

Cleanup and interruption

Each fit() and predict() call releases DataModule, callback, logger, and checkpoint resources after success, interruption, or failure. A Trainer can be reused without an explicit close() call. The idempotent close() method and context-manager support remain available for integrations that open resources outside a Trainer task.

The first Ctrl+C returns the last completed state with FitResult.interrupted=True. SIGTERM runs exception hooks and cleanup before exiting with the standard signal status. Environment information is printed when the Trainer is created and only on global rank zero.

API reference

Trainer [source]

Trainer(
    max_steps: int,
    *,
    accelerator: Accelerator = "auto",
    devices: DeviceSelection = 1,
    precision: PrecisionName | PrecisionPolicy = "32-true",
    matmul_precision: MatmulPrecision | None = None,
    derivative_dtype: Any | None = None,
    initial_loss_scale: float | None = None,
    loss_scale_growth_interval: int | None = None,
    log_every_n_steps: int = 10,
    enable_progress_bar: bool = True,
    enable_model_summary: bool = True,
    callbacks: Iterable[Callback] = (),
    logger: bool
    | ExperimentLogger
    | Iterable[ExperimentLogger]
    | None = True,
    default_root_dir: str | Path = ".",
    loggers: Iterable[ExperimentLogger] | None = None,
    strategy: Strategy | None = None,
    compilation_cache: Mapping[str, Any] | None = None,
)

Coordinate compiled JAX updates, callbacks, logging, and checkpointing on the host.

The trainer never owns a mutable model object and never places Python hooks inside :func:jax.jit. Numerical behavior remains in the module and its compiled train step; this class orchestrates their lifecycle.

Attributes:

Name Type Description
prediction_writer

Configured prediction artifact callback, or None.

should_stop

Whether a callback has requested that fitting stop. The fit loop resets it when a fit starts and checks it before each step and after each step's on_train_metrics hooks, as in Lightning.

Initialize host-side training orchestration.

Parameters:

Name Type Description Default
max_steps int

Global optimizer step at which training stops. A fit resumed from a checkpoint runs only the remaining max_steps - step updates.

required
accelerator Accelerator

Device backend selected when strategy is absent. Choose auto, cpu, gpu, or tpu.

'auto'
devices DeviceSelection

Positive device count per process, explicit local device indices, or auto for all matching devices. A multi-process run selects the same local devices on every process.

1
precision PrecisionName | PrecisionPolicy

Precision name or resolved policy. Supported names are 64-true, 32-true, 16-true, bf16-true, 16-mixed, and bf16-mixed; common dtype aliases are also accepted. The name 64-true enables JAX x64 for the whole process. A resolved policy cannot be combined with derivative_dtype, initial_loss_scale, or loss_scale_growth_interval.

'32-true'
matmul_precision MatmulPrecision | None

Optional default, high, or highest JAX matrix-multiplication precision override.

None
derivative_dtype Any | None

Optional floating batch and coordinate-derivative dtype override.

None
initial_loss_scale float | None

Initial dynamic scale for 16-mixed training. None uses 32768.0.

None
loss_scale_growth_interval int | None

Finite optimizer updates between FP16 scale increases. None uses 2000.

None
log_every_n_steps int

Positive interval between scalar logger updates.

10
enable_progress_bar bool

Whether to enable a TQDM or explicitly configured progress callback.

True
enable_model_summary bool

Whether to add a plain model summary when none is supplied explicitly.

True
callbacks Iterable[Callback]

Ordered host-side lifecycle callbacks.

()
logger bool | ExperimentLogger | Iterable[ExperimentLogger] | None

Default logger flag, one backend, several backends, or None to disable logging.

True
default_root_dir str | Path

Parent directory for versioned default local logs.

'.'
loggers Iterable[ExperimentLogger] | None

Deprecated plural alias for an explicit iterable of logging backends.

None
strategy Strategy | None

Explicit placement strategy overriding accelerator and devices.

None
compilation_cache Mapping[str, Any] | None

Optional mapping with enabled and directory values applied before device discovery.

None

Raises:

Type Description
TypeError

If a display flag or logger configuration has an invalid type.

ValueError

If a step, interval, callback, logger, precision, or matrix-multiplication precision option is invalid.

logger property

logger: LoggerCollection

Return the configured experiment logger collection.

Returns:

Type Description
LoggerCollection

Active logger collection.

interrupted property writable

interrupted: bool

Return whether the latest fit was interrupted.

Returns:

Type Description
bool

Current signal connector interruption state.

received_sigterm property writable

received_sigterm: bool

Return whether the latest fit received SIGTERM.

Returns:

Type Description
bool

Current signal connector termination flag.

logged_metrics property

logged_metrics: Mapping[str, Any]

Return metrics selected for experiment loggers at the latest completed step.

Returns:

Type Description
Mapping[str, Any]

Immutable-by-convention logger metric mapping.

progress_bar_metrics property

progress_bar_metrics: Mapping[str, Any]

Return metrics selected for progress display at the latest completed step.

Returns:

Type Description
Mapping[str, Any]

Immutable-by-convention progress metric mapping.

callback_metrics property

callback_metrics: Mapping[str, Any]

Return the complete latest metric mapping used by callbacks and fit results.

Returns:

Type Description
Mapping[str, Any]

Complete merged metric mapping.

fit [source]

fit(
    module: BasePhiModule,
    *,
    datamodule: PhiDataModule,
    optimizer: GradientTransformation,
    seed: int | Array,
    balancer: LossBalancer | None = None,
    hyperparameters: Mapping[str, Any] | None = None,
    ckpt_path: str | Path | None = None,
    ckpt_step: int | None = None,
    weights_only: bool = False,
) -> FitResult

Build a module's model, optionally restore a checkpoint, and fit it.

Parameters:

Name Type Description Default
module BasePhiModule

Module blueprint. The Trainer builds its model with :meth:~phijax.core.BasePhiModule.configure_model, so the blueprint itself is not modified.

required
datamodule PhiDataModule

Application DataModule supplying training batches and normalization statistics. Its statistics apply to fresh and weights-only runs; a full resume uses the statistics stored in the checkpoint.

required
optimizer GradientTransformation

Optax transformation used to initialize state and compile updates.

required
seed int | Array

Integer seed or valid JAX key. PhiJAX does not modify Python or NumPy global random state.

required
balancer LossBalancer | None

Functional loss balancer, or None for equal static weights.

None
hyperparameters Mapping[str, Any] | None

Optional resolved configuration recorded before the first update.

None
ckpt_path str | Path | None

Optional Orbax checkpoint root, or "last" for the configured callback's latest checkpoint.

None
ckpt_step int | None

Exact checkpoint step, or None for the latest committed step.

None
weights_only bool

Whether to restore only model weights into the fresh state.

False

Returns:

Type Description
FitResult

Bound module, final state, metrics, and termination status.

Raises:

Type Description
TypeError

If seed is not an integer or JAX key, or balancer does not implement LossBalancer.

ValueError

If the balancer's loss names differ from the module's, the module declares no batch keys, or checkpoint options are inconsistent.

predict [source]

predict(
    model: BasePhiModule | FitResult,
    batches: Iterable[Mapping[str, Any]] | None = None,
    *,
    datamodule: PhiDataModule | None = None,
    ckpt_path: str | Path | None = None,
    ckpt_step: int | None = None,
    metadata: Mapping[str, Any] | None = None,
    return_predictions: bool = True,
) -> np.ndarray | None

Predict with a fit result, or with a module blueprint loaded from a checkpoint.

This follows Lightning's Trainer.predict(model, ckpt_path=...). A :class:FitResult predicts with its bound module and final model state, or with the model state stored at ckpt_path. An unbound :class:PhiModule requires ckpt_path: the Trainer builds its model with the checkpoint's input statistics and periods and restores only the model state, so prediction needs no optimizer, balancer, or fit-stage data.

Checkpoints written by PhiJAX 0.2.0b5 and earlier store no input statistics or periods. With one, a fit result keeps its module's values, and a module takes them from the fit stage of datamodule with a warning.

When batches is omitted, the Trainer sets up datamodule for prediction and requests its batch source. Prediction is skipped when neither source is available.

Parameters:

Name Type Description Default
model BasePhiModule | FitResult

Fit result, or unbound module blueprint restored from ckpt_path.

required
batches Iterable[Mapping[str, Any]] | None

Optional finite prediction batch iterable. When omitted, use datamodule.

None
datamodule PhiDataModule | None

Optional DataModule supplying prediction batches, and the input statistics and periods of a legacy checkpoint.

None
ckpt_path str | Path | None

Optional Orbax checkpoint root, or "last" for the configured callback's latest checkpoint.

None
ckpt_step int | None

Exact checkpoint step, or None for the latest committed step.

None
metadata Mapping[str, Any] | None

Optional immutable metadata exposed to prediction callbacks.

None
return_predictions bool

Whether to concatenate and return host predictions.

True

Returns:

Type Description
ndarray | None

Concatenated host predictions, or None when collection is disabled or prediction data is unavailable.

Raises:

Type Description
ValueError

If a module blueprint has no ckpt_path, checkpoint options are invalid, a legacy checkpoint has no datamodule to take inputs from, or a provided batch source is empty.

BaseException

Re-raises prediction lifecycle errors after cleanup.

prepare_batch_source [source]

prepare_batch_source(source: SourceT) -> SourceT

Prepare persistent sampler state for this Trainer's process-local root device.

Sources without a callable prepare method are returned unchanged, preserving support for ordinary callables and finite iterables. Built-in PhiJAX sources transfer finite candidate pools, generation bounds, templates, and PRNG keys once instead of transferring sampled training batches from the host on every step.

Batch sizes are per device. A source exposing for_devices(count) is first scaled by this process's device count; other sources are used as they are, so their batches are the rows of this process.

Parameters:

Name Type Description Default
source SourceT

Training batch callable or iterable, optionally exposing prepare(device).

required

Returns:

Type Description
SourceT

Source prepared for the selected Strategy, or the original source when preparation is unsupported.

prepare_batch [source]

prepare_batch(
    batch: Any, replicated: Collection[str] = ()
) -> Any

Cast and place one batch according to the configured precision and Strategy.

NumPy floating leaves are cast on the host before transfer. Device-resident sampler outputs retain their placement when the Strategy target is unchanged, while data-parallel Strategies apply final batch sharding.

Parameters:

Name Type Description Default
batch Any

Arbitrary host or device batch PyTree.

required
replicated Collection[str]

Top-level batch names placed in full on every device, such as batches drawn with all.

()

Returns:

Type Description
Any

Precision-normalized batch placed or sharded for compiled execution.

callback_state_dict [source]

callback_state_dict() -> dict[str, Mapping[str, Any]]

Collect JSON-compatible persistent state from every callback.

Returns:

Type Description
dict[str, Mapping[str, Any]]

Stable callback identifiers mapped to persistent callback state.

Raises:

Type Description
TypeError

If a callback returns a non-mapping or non-JSON-compatible state.

load_callback_state_dict [source]

load_callback_state_dict(
    states: Mapping[str, Mapping[str, Any]],
) -> None

Restore callback states using stable identifiers, following Lightning.

Callbacks without a stored state, such as callbacks added since the checkpoint was written or stateless callbacks, keep their fresh state. Non-empty stored states without a matching callback are skipped with a warning.

Parameters:

Name Type Description Default
states Mapping[str, Mapping[str, Any]]

Checkpoint callback states.

required

Raises:

Type Description
ValueError

If a callback rejects its stored state.

print_environment_info [source]

print_environment_info() -> None

Print Lightning-style precision and accelerator information on global rank zero.

close [source]

close() -> None

Release any checkpoint resources opened outside a Trainer task.

Fit and prediction stages already close their resources automatically. Calling this method is optional and remains supported for explicit lifecycle management and context-manager use.