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:
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 |
|
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 |
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 |
required |
accelerator
|
Accelerator
|
Device backend selected when |
'auto'
|
devices
|
DeviceSelection
|
Positive device count per process, explicit local device indices, or |
1
|
precision
|
PrecisionName | PrecisionPolicy
|
Precision name or resolved policy. Supported names are |
'32-true'
|
matmul_precision
|
MatmulPrecision | None
|
Optional |
None
|
derivative_dtype
|
Any | None
|
Optional floating batch and coordinate-derivative dtype override. |
None
|
initial_loss_scale
|
float | None
|
Initial dynamic scale for |
None
|
loss_scale_growth_interval
|
int | None
|
Finite optimizer updates between FP16 scale increases. |
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 |
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 |
None
|
compilation_cache
|
Mapping[str, Any] | None
|
Optional mapping with |
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
Return the configured experiment logger collection.
Returns:
| Type | Description |
|---|---|
LoggerCollection
|
Active logger collection. |
interrupted
property
writable
Return whether the latest fit was interrupted.
Returns:
| Type | Description |
|---|---|
bool
|
Current signal connector interruption state. |
received_sigterm
property
writable
Return whether the latest fit received SIGTERM.
Returns:
| Type | Description |
|---|---|
bool
|
Current signal connector termination flag. |
logged_metrics
property
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
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
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: |
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
|
hyperparameters
|
Mapping[str, Any] | None
|
Optional resolved configuration recorded before the first update. |
None
|
ckpt_path
|
str | Path | None
|
Optional Orbax checkpoint root, or |
None
|
ckpt_step
|
int | None
|
Exact checkpoint step, or |
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 |
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 |
required |
batches
|
Iterable[Mapping[str, Any]] | None
|
Optional finite prediction batch iterable. When omitted, use |
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 |
None
|
ckpt_step
|
int | None
|
Exact checkpoint step, or |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a module blueprint has no |
BaseException
|
Re-raises prediction lifecycle errors after cleanup. |
prepare_batch_source
[source]
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 |
required |
Returns:
| Type | Description |
|---|---|
SourceT
|
Source prepared for the selected Strategy, or the original source when preparation is unsupported. |
prepare_batch
[source]
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 |
()
|
Returns:
| Type | Description |
|---|---|
Any
|
Precision-normalized batch placed or sharded for compiled execution. |
callback_state_dict
[source]
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]
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 Lightning-style precision and accelerator information on global rank zero.
close
[source]
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.