Data
PhiJAX keeps application data construction on the host and accelerator placement in the trainer. A DataModule owns immutable pools and sampling policy; it does not need to know which device the trainer selected.
DataModule lifecycle
prepare_data()
setup("fit" | "predict")
train_batch_source(...) | predict_batch_source()
Trainer prepares source and places batches
teardown("fit" | "predict")
prepare_data may generate or obtain shared artifacts. Build process-local NumPy pools in setup. The Trainer runs
this lifecycle once per fit() or predict() call, and always calls teardown(), even after a failed setup(). It
sets up fitting before requesting optional model normalization statistics, then retrieves sources. The base input_statistics() returns None; override it to opt into input normalization. The Trainer stores
the returned statistics in TrainState, so a full resume and prediction from a checkpoint use the statistics the model
was trained with. See input normalization statistics. Override
input_periods() to declare the physical period of periodic input axes; see
periodic features. Return None from
predict_batch_source() to skip prediction. Prediction sources must be finite and repeatable; training sources may
sample indefinitely from the global optimizer step.
Default sources
Most DataModules only build pools. Pass the source sizes to PhiDataModule.__init__() and override setup():
| Hook | Default |
|---|---|
train_batch_source(batch_keys, key) |
Random rows from the pool named by each batch key, sized by batch_sizes |
prediction_pool() |
The pool named predict, or None |
predict_batch_source() |
batch_sizes["predict"] rows per device from prediction_pool(), or None without that pool |
batch_sizes["predict"] may be "all", which predicts the whole pool in one chunk split over the devices. This gives
one compiled shape and no chunk loop, but the whole grid must fit in device memory in one forward pass. In training,
"all" instead gives every device the full pool.
A default source raises an error when a size is missing or a batch key names no pool. Override the hook for custom
sampling, such as a SpaceTimeSampler.
Multi-process runs
In a run with several JAX processes, the Trainer prepares data in three steps:
- Global process zero calls
prepare_data(). No other process calls it. - Every process waits at
Strategy.barrier()until process zero has finished. - Every process calls
setup()and builds its own pools.
prepare_data() therefore runs once per run, and no process reads a file that is still being written. A single-process
run is unaffected: process zero prepares the data, and the barrier returns immediately.
Write prepared files to storage that every host can read, such as a shared filesystem. If the files are on
process zero's local disk, setup() fails on the other hosts because they cannot read them. Keep prepare_data() free
of state that setup() needs, such as attributes, because other processes never run it.
Lightning defaults to prepare_data_per_node=True, which runs prepare_data() on one process per machine. PhiJAX
always uses global process zero instead. JAX usually runs one process per host, so a per-machine rule would make
every process prepare the same files.
PhiDataModule
[source]
Bases: ABC
Define a Lightning-inspired host data lifecycle for PhiJAX applications.
Application subclasses construct immutable pools in :meth:setup. The default :meth:train_batch_source samples
those pools with batch_sizes, and the default :meth:predict_batch_source chunks the predict pool with
batch_sizes["predict"]. Override either hook for custom sampling. The module is mutable host-side orchestration
state; model, optimizer, balancer, and PRNG state used by compiled training remain explicit and functional.
The Trainer runs the lifecycle: :meth:prepare_data on global process zero, then :meth:setup and
:meth:teardown around each fit or predict task.
Attributes:
| Name | Type | Description |
|---|---|---|
pools |
Mapping[str, HostPool]
|
Immutable application pools populated by :meth: |
Initialize an empty pool mapping and the default source sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_sizes
|
Mapping[str, BatchSize] | None
|
Optional per-device batch size keyed by pool name, used by the default
:meth: |
None
|
prepare_data
[source]
Prepare external artifacts before application pools are constructed.
The base implementation performs no work. Subclasses may generate or download files. The Trainer calls this
method only on global process zero, and every process waits for it before :meth:setup. Write files to storage
every host can read, and do not assign attributes that :meth:setup needs: other processes never run this
method. Runtime pools belong in :meth:setup, which runs on every process.
setup
[source]
abstractmethod
Populate immutable application pools for one execution stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
DataStage
|
Requested |
required |
train_batch_source
[source]
Build a deterministic step-indexed training batch source.
The default draws random rows from the pool named by each batch key, with the size from batch_sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_keys
|
tuple[str, ...]
|
Objective batch keys in stable declaration order. |
required |
key
|
Array
|
Explicit root sampling key. |
required |
Returns:
| Type | Description |
|---|---|
TrainingBatchSource
|
Unprepared step-indexed source that the Trainer places before sampling. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
ValueError
|
If |
KeyError
|
If a batch key names no pool or has no batch size. |
predict_batch_source
[source]
Build an optional finite ordered host-backed prediction batch source.
The default chunks :meth:prediction_pool into batch_sizes["predict"] rows per device. With "all", one
chunk holds every row and is split over the devices.
Returns:
| Type | Description |
|---|---|
PredictionBatchSource | None
|
Re-iterable source whose batches the Trainer places before prediction, or |
PredictionBatchSource | None
|
not provide prediction data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a prediction pool exists but |
prediction_pool
[source]
Return the optional ordered host pool represented by prediction batches.
Returns:
| Type | Description |
|---|---|
HostPool | None
|
The pool named |
normalization_pools
[source]
Select host pools used to derive shared model input statistics.
The default excludes the prediction source's pool so a dense evaluation grid does not dominate training-coordinate statistics. Applications may override this policy when one pool best represents the physical domain.
Returns:
| Type | Description |
|---|---|
Mapping[str, HostPool]
|
Non-empty training-oriented host-pool mapping. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If excluding the prediction pool leaves no pools. |
input_statistics
[source]
Return optional model-input normalization statistics.
The base implementation disables input normalization. Applications can opt in by overriding this method and
returning empirical statistics from :func:phijax.data.input_statistics or exact statistics for a continuous
sampling distribution.
The Trainer stores the statistics in the training state. A full resume and prediction from a checkpoint use the
stored statistics; fresh and weights-only runs use this method. For transfer learning with the source model's
statistics, return :func:phijax.training.load_input_statistics here.
Returns:
| Type | Description |
|---|---|
tuple[NDArray[Any], NDArray[Any]] | None
|
Per-coordinate mean and safely positive standard deviation arrays, or |
input_periods
[source]
Return optional physical periods of periodic input axes.
Models with periodic features embed each declared axis as cos(2*pi*x/T) and sin(2*pi*x/T) of the physical
coordinate, independently of input normalization. Return a period computed from the data, such as a measured
cardiac cycle, or a fixed one, such as 2*pi for an angle. A model's periodic_features_kwargs['periods']
overrides or adds axes.
The Trainer stores the periods the model applies in the training state. A full resume and prediction from a checkpoint use the stored periods; fresh and weights-only runs use this method.
Returns:
| Type | Description |
|---|---|
Mapping[int, float] | None
|
Physical period keyed by input axis index, or |
teardown
[source]
Release application resources after one lifecycle stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
DataStage
|
Completed |
required |
Host pools
A pool is a set of rows. inputs is a rank-two NumPy array. Omit targets for an automatically created zero-width
target array. aux and metadata default to immutable empty mappings. When omitted, reference_shape becomes
(sample_count,) and flat_index becomes arange(sample_count). Array-valued aux fields share the sample axis.
HostPool.from_grid() builds a pool from dense grid arrays shaped
[*grid, features]. An optional Boolean mask with shape grid keeps only part of the grid, such as a masked
physical domain. The pool records the grid in reference_shape and the kept positions in flat_index, so
reconstruct_predictions() returns [*grid, outputs] with NaN outside the
mask.
HostPool
[source]
dataclass
HostPool(
inputs: NDArray[Any],
targets: NDArray[Any] | None = None,
aux: Mapping[str, Any] | None = None,
metadata: Mapping[str, Any] | None = None,
reference_shape: tuple[int, ...] | None = None,
flat_index: NDArray[Any] | None = None,
)
Represent one immutable host-side subset with stable row ordering.
Copy arrays, fill safe defaults, validate dimensions, and freeze storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
NDArray[Any]
|
Rank-two coordinate array with shape |
required |
targets
|
NDArray[Any] | None
|
Optional rank-two target array. Omission creates a zero-width array. |
None
|
aux
|
Mapping[str, Any] | None
|
Optional sample-wise auxiliary arrays with one leading row per sample. Names |
None
|
metadata
|
Mapping[str, Any] | None
|
Optional structural or reconstruction metadata. |
None
|
reference_shape
|
tuple[int, ...] | None
|
Optional dense reconstruction shape. Omission uses |
None
|
flat_index
|
NDArray[Any] | None
|
Optional flattened reconstruction indices. Omission uses sequential row indices. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
from_grid
[source]
classmethod
from_grid(
inputs: NDArray[Any],
targets: NDArray[Any] | None = None,
*,
mask: NDArray[Any] | None = None,
aux: Mapping[str, Any] | None = None,
metadata: Mapping[str, Any] | None = None,
) -> HostPool
Build a pool from dense grid arrays, keeping the grid so predictions can be put back on it.
Every array starts with the same grid axes. Rows are taken in C order, and only where mask is True.
The pool records the grid as reference_shape and the selected positions as flat_index, so
:func:reconstruct_predictions returns [*grid, outputs] with NaN outside the mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
NDArray[Any]
|
Coordinates with shape |
required |
targets
|
NDArray[Any] | None
|
Optional targets with shape |
None
|
mask
|
NDArray[Any] | None
|
Optional Boolean array with shape |
None
|
aux
|
Mapping[str, Any] | None
|
Optional fields. Arrays have shape |
None
|
metadata
|
Mapping[str, Any] | None
|
Optional structural metadata. |
None
|
Returns:
| Type | Description |
|---|---|
HostPool
|
Pool with one row per selected grid point. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
fields
[source]
Collect dense sample-wise fields for one device transfer.
Returns:
| Type | Description |
|---|---|
Mapping[str, NDArray[Any]]
|
Read-only mapping containing |
input_statistics
[source]
Compute shared coordinate normalization statistics across named pools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pools
|
Mapping[str, HostPool]
|
Non-empty named host pools with a common input width. |
required |
Returns:
| Type | Description |
|---|---|
tuple[NDArray[Any], NDArray[Any]]
|
Per-coordinate mean and safely floored standard deviation as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no pools are supplied or their input widths differ. |
reconstruct_predictions
[source]
Scatter flat predictions back to a pool's dense reference grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
NDArray[Any]
|
Flat prediction array with shape |
required |
pool
|
HostPool
|
Host pool carrying reference shape and flattened row indices. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[Any]
|
Dense prediction array with shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If prediction rows, indices, or reference shape are inconsistent, or if indices repeat. |
Prediction artifacts
Prediction artifacts can be saved and loaded without callbacks. The canonical NPZ stores physical arrays, output scales, schema information, and safe application metadata. Optional MATLAB files store the same physical values and may use application-specific field names.
save_prediction_artifact
[source]
save_prediction_artifact(
output_path: str | Path,
predictions: object,
pool: HostPool,
*,
save_mat: bool = False,
mat_field_names: Mapping[str, str] | None = None,
) -> Path
Save a canonical NumPy prediction artifact and an optional MATLAB sidecar.
Model predictions and compatible pool targets are multiplied by application-provided output_scales before
serialization. Missing scales resolve to ones. Both formats store physical values, the applied scales, schema
version 2, and value_space="physical".
Each file is written to a temporary sibling and renamed into place, so an interrupted save never leaves a partial artifact and keeps any previous file at the destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str | Path
|
Destination compressed NumPy artifact path ending in |
required |
predictions
|
object
|
Flat normalized model predictions ordered like |
required |
pool
|
HostPool
|
Host prediction pool supplying normalized targets, reconstruction metadata, and optional
|
required |
save_mat
|
bool
|
Whether to also save a |
False
|
mat_field_names
|
Mapping[str, str] | None
|
Optional mapping from generic prediction-array names to MATLAB variable names. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Absolute path to the saved |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ModuleNotFoundError
|
If |
ValueError
|
If the destination suffix, predictions, targets, output scales, or MATLAB names are invalid, or if
|
load_prediction_artifact
[source]
Load and validate a physical PhiJAX prediction artifact without pickle support.
Missing output_scales default to one for every output channel, leaving stored physical values unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Schema-version-2 |
required |
Returns:
| Type | Description |
|---|---|
PredictionArtifact
|
Immutable artifact with combined arrays, named output views, and separated metadata. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
KeyError
|
If a required schema array is absent. |
ValueError
|
If schema metadata, shapes, names, indices, scales, or values are inconsistent. |
PredictionArtifact
[source]
dataclass
PredictionArtifact(
prediction: NDArray[Any],
target: NDArray[Any],
flat_prediction: NDArray[Any],
flat_target: NDArray[Any],
inputs: NDArray[Any],
dense_inputs: NDArray[Any],
mask: NDArray[bool_],
flat_index: NDArray[int64],
reference_shape: tuple[int, ...],
coordinate_names: tuple[str, ...],
output_names: tuple[str, ...],
output_scales: NDArray[Any],
outputs: Mapping[str, NDArray[Any]],
targets: Mapping[str, NDArray[Any]],
metadata: Mapping[str, NDArray[Any]],
)
Expose one validated physical prediction artifact and named channel views.
Attributes:
| Name | Type | Description |
|---|---|---|
prediction |
NDArray[Any]
|
Dense physical predictions with shape |
target |
NDArray[Any]
|
Dense physical targets with zero or all output channels. |
flat_prediction |
NDArray[Any]
|
Physical predictions at the rows represented by |
flat_target |
NDArray[Any]
|
Physical targets at the rows represented by |
inputs |
NDArray[Any]
|
Flat model coordinates in the application's configured coordinate space. |
dense_inputs |
NDArray[Any]
|
Coordinates reconstructed on the reference grid. |
mask |
NDArray[bool_]
|
Boolean reference-grid mask selecting represented rows. |
flat_index |
NDArray[int64]
|
Flat reference-grid index for every represented row. |
reference_shape |
tuple[int, ...]
|
Dense reference-grid shape. |
coordinate_names |
tuple[str, ...]
|
Semantic name of every input coordinate. |
output_names |
tuple[str, ...]
|
Semantic name of every predicted output. |
output_scales |
NDArray[Any]
|
Physical multiplier applied to each normalized model output during serialization. |
outputs |
Mapping[str, NDArray[Any]]
|
Read-only mapping from each output name to its dense physical prediction view. |
targets |
Mapping[str, NDArray[Any]]
|
Read-only mapping from each output name to its dense physical target view, or an empty mapping when the prediction pool has no targets. |
metadata |
Mapping[str, NDArray[Any]]
|
Read-only mapping containing schema, structural, and application-provided metadata arrays. |
to_matlab_prediction_arrays
[source]
to_matlab_prediction_arrays(
arrays: Mapping[str, Any],
*,
field_names: Mapping[str, str] | None = None,
) -> dict[str, Any]
Rename reconstructed prediction arrays for MATLAB export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arrays
|
Mapping[str, Any]
|
Reconstructed prediction arrays and optional nested metadata keyed by generic PhiJAX names. |
required |
field_names
|
Mapping[str, str] | None
|
Optional mapping from generic top-level or metadata names to MATLAB variable names. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Independent mapping suitable for :func: |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
TypeError
|
If a configured source or destination name is not a string. |
ValueError
|
If a destination is not a MATLAB identifier or multiple arrays use the same destination. |
Samplers
| Sampler | Source | Typical PINN use |
|---|---|---|
RandomRowSampler |
Finite aligned pool | Initial, boundary, or supervised samples |
UniformDomainSampler |
Continuous rectangular bounds | Fresh PDE collocation coordinates |
SpaceTimeSampler |
Fixed spatial mesh + fresh times | Time-dependent PDE collocation |
Construct samplers directly in train_batch_source().
prepare(device) moves persistent arrays once. sample(key, batch_size) remains explicitly keyed and returns a fixed
leading dimension.
BatchSampler
[source]
Bases: ABC
Define one immutable explicit-key batch sampling policy.
prepare
[source]
Prepare persistent sampler state for one trainer-selected device.
Stateless custom samplers may inherit this implementation. Samplers owning arrays should override it and
return an immutable copy whose persistent storage resides on device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
BatchSampler
|
Device-ready sampler. |
sample
[source]
abstractmethod
Draw one fixed-size batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit JAX PRNG key controlling this draw. |
required |
batch_size
|
int
|
Positive number of requested rows. |
required |
Returns:
| Type | Description |
|---|---|
DevicePool
|
Sample-wise device arrays sharing the requested leading dimension. |
sample_all
[source]
Return the complete finite source when supported.
Returns:
| Type | Description |
|---|---|
DevicePool
|
Complete sample-wise device arrays. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sampler represents a continuous distribution without a finite source. |
RandomRowSampler
[source]
dataclass
Bases: BatchSampler
Sample aligned rows from one finite pool.
Attributes:
| Name | Type | Description |
|---|---|---|
pool |
Mapping[str, Any]
|
Sample-wise host or device arrays with a shared leading dimension. |
replace |
bool
|
Whether randomly drawn indices may repeat. |
sort_axis |
int | None
|
Optional input-coordinate column used to sort every returned field consistently. |
__post_init__
[source]
Validate the finite source and optional input sort axis.
Raises:
| Type | Description |
|---|---|
KeyError
|
If the pool has no |
ValueError
|
If pool fields have inconsistent row counts or |
prepare
[source]
Place the finite candidate pool once on the trainer-selected device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
RandomRowSampler
|
Immutable sampler sharing policy values with a device-resident pool. |
sample
[source]
Sample aligned finite-pool rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit JAX PRNG key controlling row indices. |
required |
batch_size
|
int
|
Positive number of requested rows. |
required |
Returns:
| Type | Description |
|---|---|
DevicePool
|
Random aligned pool fields, optionally sorted by one input coordinate. |
sample_all
[source]
Return every finite-pool row exactly once.
Returns:
| Type | Description |
|---|---|
DevicePool
|
Complete aligned pool fields, optionally sorted by one input coordinate. |
UniformDomainSampler
[source]
dataclass
UniformDomainSampler(
bounds: Any,
templates: Mapping[str, Any],
dtype: DTypeLike = jnp.float32,
sort_axis: int | None = None,
)
Bases: BatchSampler
Generate fresh coordinates uniformly inside a rectangular domain.
Attributes:
| Name | Type | Description |
|---|---|---|
bounds |
Any
|
Array with shape |
templates |
Mapping[str, Any]
|
Non-input field values broadcast to every generated coordinate. |
dtype |
DTypeLike
|
Floating dtype used for generated coordinates. |
sort_axis |
int | None
|
Optional coordinate column used to sort each generated batch. |
__post_init__
[source]
Validate domain bounds, templates, dtype, and sort policy.
Raises:
| Type | Description |
|---|---|
ValueError
|
If bounds are not finite increasing intervals, a template is named |
prepare
[source]
Place domain bounds and field templates once on the trainer-selected device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
UniformDomainSampler
|
Immutable sampler with device-resident generation metadata. |
sample
[source]
Generate one fresh fixed-size domain batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit JAX PRNG key controlling coordinate generation. |
required |
batch_size
|
int
|
Positive number of requested coordinates. |
required |
Returns:
| Type | Description |
|---|---|
DevicePool
|
Generated |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
SpaceTimeSampler
[source]
dataclass
SpaceTimeSampler(
pool: Mapping[str, Any],
time_bounds: tuple[float, float],
time_axis: int = 0,
replace: bool = True,
sort_axis: int | None = 0,
)
Bases: BatchSampler
Pair fresh uniform times with rows sampled from a fixed spatial mesh.
Attributes:
| Name | Type | Description |
|---|---|---|
pool |
Mapping[str, Any]
|
Finite host or device pool whose |
time_bounds |
tuple[float, float]
|
Increasing lower and upper time bounds. |
time_axis |
int
|
Input-coordinate column replaced with fresh uniform times. |
replace |
bool
|
Whether sampled spatial rows may repeat. |
sort_axis |
int | None
|
Optional input-coordinate column used to sort every returned field. |
__post_init__
[source]
Validate the finite mesh and temporal settings.
Raises:
| Type | Description |
|---|---|
ValueError
|
If bounds, the temporal axis, target semantics, or sorting are invalid. |
prepare
[source]
Place the finite spatial mesh once on the trainer-selected device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
SpaceTimeSampler
|
Immutable sampler with device-resident mesh fields. |
sample
[source]
Sample spatial rows and replace their temporal coordinate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit JAX PRNG key split across mesh and temporal draws. |
required |
batch_size
|
int
|
Positive number of requested rows. |
required |
Returns:
| Type | Description |
|---|---|
DevicePool
|
Aligned pool fields with fresh uniformly generated time coordinates. |
Batch sources
NamedBatchSource folds its root key with the global step, then splits keys in sampler declaration order. A restored
checkpoint therefore continues the same sampling sequence. The "all" batch-size policy works only with finite row
sources.
Each step draws every sampler with an integer batch size in one compiled call. The compiled draw is cached per set of
batch sizes, so steps reuse it and adaptive-balancer diagnostics with their own sizes compile once more. Sampler
arrays are passed to the compiled call as device buffers rather than baked into it. A sampler with the "all" policy
returns its complete pool outside the compiled call. Samplers must therefore be traceable by jax.jit.
NamedBatchSource.from_pools() is the concise path for aligned finite datasets. It creates ordered
RandomRowSampler instances and validates requested pool names and batch-size policies.
Define one batch-size policy per pool in the DataModule, then reuse the objective's inferred order:
self.batch_sizes = {"initial": "all", "boundary": 128, "pde": 4096}
def train_batch_source(self, batch_keys, key):
return NamedBatchSource.from_pools(self.pools, self.batch_sizes, key, names=batch_keys)
An integer samples that many rows per device on every optimizer step. The "all" policy uses every row, is available
only for finite pools, and places the whole pool on every device. See batch sizes.
ChunkedPredictionSource pads its final host batch to batch_size. Each batch carries a Boolean valid_predict_mask
that is True for pool rows and False for padding, and prediction removes padded rows before output assembly. The
name is reserved: a prediction pool with an auxiliary array named valid_predict_mask raises ValueError.
Custom batch sources
A custom source implements TrainingBatchSource or
PredictionBatchSource. To support per-device batch sizes on
several devices, also define for_devices(count), returning a copy whose integer sizes are multiplied by count. The
Trainer passes this process's device count for training sources and the total device count for prediction sources.
Without the method, a training source's batches are the rows of the whole process and must divide by its device count.
See device strategies.
TrainingBatchSource
[source]
Bases: Protocol
Define deterministic step-indexed training and diagnostic batch delivery.
Batch sizes are per device. A source may also define an optional for_devices(count: int) -> Self method that
returns a copy drawing count times every integer batch size, as :meth:NamedBatchSource.for_devices does. The
Trainer calls it before :meth:prepare with this process's device count, because each process draws its own batch
and splits it over its devices. Diagnostic sizes passed to :meth:sample are not scaled. A source without
for_devices is used as it is, so its batches are the rows of the whole process and their leading dimension must
divide by the process's device count.
prepare
[source]
Prepare persistent source state for one trainer-selected device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Device-ready source preserving sampling policy and deterministic key behavior. |
__call__
[source]
Produce one named training batch for a global optimizer step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
int
|
Non-negative global optimizer step, including a restored checkpoint offset. |
required |
Returns:
| Type | Description |
|---|---|
NamedBatches
|
Named fixed-structure training batches. |
sample
[source]
Produce explicitly keyed batches with optional size overrides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit root sampling key. |
required |
batch_sizes
|
Mapping[str, BatchSize] | None
|
Optional per-stream batch-size overrides used by diagnostics such as exact NTK balancing. |
None
|
Returns:
| Type | Description |
|---|---|
NamedBatches
|
Named fixed-structure batches. |
PredictionBatchSource
[source]
Bases: Protocol
Define finite ordered prediction batches and their reconstruction pool.
Chunk sizes are per device. A source may also define an optional for_devices(count: int) -> Self method that
returns a copy with count times larger chunks, as :meth:ChunkedPredictionSource.for_devices does. The Trainer
calls it with the total device count, because every process iterates the same chunks and splits each one over all
devices. A source without for_devices is used as it is; its chunks are padded to divide over the devices.
__iter__
[source]
Iterate over fixed-size host-backed padded prediction batches.
NamedBatchSource
[source]
dataclass
NamedBatchSource(
samplers: Mapping[str, BatchSampler],
batch_sizes: Mapping[str, BatchSize],
key: Array,
)
Compose named immutable samplers into deterministic step-indexed batches.
Every sampler with an integer batch size is drawn in one compiled call per step, so a step costs one dispatch
instead of one per array operation. Samplers must therefore be traceable by :func:jax.jit. A sampler with the
all policy returns its complete pool outside the compiled call, which avoids copying the pool on every step.
Attributes:
| Name | Type | Description |
|---|---|---|
samplers |
Mapping[str, BatchSampler]
|
Named sampling policies aligned with objective batch keys. |
batch_sizes |
Mapping[str, BatchSize]
|
Per-sampler positive integer or |
key |
Array
|
Explicit root key folded with each global optimizer step. |
from_pools
[source]
classmethod
from_pools(
pools: Mapping[str, HostPool],
batch_sizes: Mapping[str, BatchSize],
key: Array,
*,
names: tuple[str, ...] | None = None,
replace: bool = True,
sort_axes: Mapping[str, int | None] | None = None,
) -> Self
Construct aligned finite-row samplers from named host pools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pools
|
Mapping[str, HostPool]
|
Finite host pools keyed by application batch name. |
required |
batch_sizes
|
Mapping[str, BatchSize]
|
Sampling policies keyed by the same names. |
required |
key
|
Array
|
Explicit root key folded with each optimizer step. |
required |
names
|
tuple[str, ...] | None
|
Optional stable subset and ordering. The batch-size declaration order is used when omitted. |
None
|
replace
|
bool
|
Whether sampled rows may repeat. |
True
|
sort_axes
|
Mapping[str, int | None] | None
|
Optional input-coordinate sort axis per selected pool. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Deterministic named source containing one :class: |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a selected name is absent from |
ValueError
|
If selected names are empty or duplicated. |
__post_init__
[source]
Validate sampler names and batch-size policies.
Raises:
| Type | Description |
|---|---|
KeyError
|
If a sampler has no batch-size policy. |
ValueError
|
If no samplers are supplied or a policy is invalid for its sampler. |
for_devices
[source]
Return a copy that draws every integer batch size once per device.
Batch sizes are per device, as in Lightning. The Trainer calls this with the number of devices that share
each sampled batch, so every device receives the configured rows. all policies keep the whole pool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Positive number of devices that split each batch. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
This source when |
prepare
[source]
Place persistent sampler arrays and the root key on a trainer-selected device.
Preparing once retains device-side row selection and generated-coordinate sampling without requiring an application DataModule to know which accelerator the Trainer selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
JaxDevice
|
Trainer Strategy's process-local root device. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Immutable device-ready source. |
__call__
[source]
Sample every named policy for one global optimizer step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
int
|
Non-negative global optimizer step, including any restored checkpoint offset. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, DevicePool]
|
Named fixed-structure training batches. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
sample
[source]
Sample named policies with an explicit key and optional size overrides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Explicit root key split in sampler declaration order. |
required |
batch_sizes
|
Mapping[str, BatchSize] | None
|
Optional replacement policies, used for fixed balancer diagnostic batches. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, DevicePool]
|
Named batches aligned with sampler declaration order. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a sampler has no selected batch-size policy. |
ValueError
|
If an override is invalid or requests |
ChunkedPredictionSource
[source]
dataclass
Lazily construct fixed-size prediction batches from an immutable host pool.
The source retains the complete dataset on the host. The Trainer places only the currently yielded padded batch on its selected device, reducing peak device memory while preserving deterministic row order.
Attributes:
| Name | Type | Description |
|---|---|---|
pool |
HostPool
|
Immutable host prediction pool carrying dense reconstruction metadata. |
batch_size |
BatchSize
|
Positive fixed number of rows yielded per batch, for each device that shares it, or |
__post_init__
[source]
Validate prediction row and fixed batch sizes and the reserved valid_predict_mask field.
Raises:
| Type | Description |
|---|---|
ValueError
|
If pool rows or |
for_devices
[source]
Return a copy whose chunks hold batch_size rows for each device.
The chunk size is per device, as in Lightning. The Trainer calls this with the number of devices that share each chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Positive number of devices that split each chunk. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
This source when |
__len__
[source]
Return the finite number of padded prediction batches.
Returns:
| Type | Description |
|---|---|
int
|
At least one batch, including for an empty prediction pool. |
__iter__
[source]
Yield host-sliced and padded prediction batches.
Yields:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Field mappings with a fixed leading dimension and a Boolean |
dict[str, ndarray]
|
rows and |
Array IO
load_arrays supports NPZ, MATLAB, and HDF5 files. NPZ needs only NumPy. MATLAB and HDF5 files require the io extra,
pip install "phijax[io]". SciPy reads classic MATLAB files. mat73 restores MATLAB's logical
array order from v7.3 HDF5 files, while generic HDF5 input keeps its stored order. get_array accepts slash-delimited
nested keys. Build pools from the loaded arrays with NumPy and HostPool or HostPool.from_grid().
load_arrays
[source]
Load an NPZ, MATLAB, or HDF5 artifact into host memory.
File access and decoding remain entirely NumPy-based so this function can run without initializing a JAX backend. HDF5 groups and MATLAB structs are represented by nested dictionaries, while all HDF5 datasets are materialized before the file is closed. Automatic mode uses the file suffix and recognizes HDF5 content when the suffix is unknown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Source |
required |
file_format
|
ArrayFormat
|
Explicit file format or |
'auto'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Mapping of source field names to NumPy arrays or nested field mappings. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ModuleNotFoundError
|
If a MATLAB or HDF5 file is read without the optional |
ValueError
|
If the requested format is invalid or automatic detection fails. |
get_array
[source]
Read one array using a top-level key or slash-delimited nested path.
A direct mapping key takes precedence over path traversal so NPZ fields containing / remain addressable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arrays
|
Mapping[str, Any]
|
Mapping returned by :func: |
required |
key
|
str
|
Top-level field name or nested path such as |
required |
Returns:
| Type | Description |
|---|---|
NDArray[Any]
|
Requested value represented as a NumPy array. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key or one of its path components is absent. |
TypeError
|
If the key resolves to a group rather than an array value. |
ValueError
|
If |
Host transforms
Reusable transforms operate on NumPy arrays while building host data. They derive statistics from finite values and preserve non-finite entries. They also accept fixed statistics, so prediction can reuse values derived from training data. Keep application-specific physical scaling in the application DataModule.
log_compress
[source]
log_compress(
values: ArrayLike,
*,
percentile: float = 99.0,
dynamic_range: float = 40.0,
) -> NDArray[np.floating[Any]]
Compress power-like values into a normalized relative-decibel range.
Finite values above the percentile-derived reference are clipped, non-positive finite values are mapped to the
floating-point epsilon before applying the logarithm, and the retained decibel interval is mapped to [0, 1].
Non-finite entries are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Power-like values to compress. |
required |
percentile
|
float
|
Finite upper-reference percentile in |
99.0
|
dynamic_range
|
float
|
Positive relative-decibel range retained below the reference. |
40.0
|
Returns:
| Type | Description |
|---|---|
NDArray[floating[Any]]
|
Floating array with finite values in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
minmax_scale
[source]
minmax_scale(
values: ArrayLike,
*,
minimum: ArrayLike | None = None,
maximum: ArrayLike | None = None,
feature_range: Sequence[float] = (0.0, 1.0),
) -> NDArray[np.floating[Any]]
Scale finite values from a supplied or data-derived interval.
Explicit minimum and maximum arrays may be reused across datasets and follow NumPy broadcasting. When either
statistic is omitted, it is derived globally from finite entries in values. A constant source interval maps to
the lower endpoint of feature_range, and non-finite entries are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Values to scale. |
required |
minimum
|
ArrayLike | None
|
Optional finite lower statistic. Defaults to the finite global minimum of |
None
|
maximum
|
ArrayLike | None
|
Optional finite upper statistic. Defaults to the finite global maximum of |
None
|
feature_range
|
Sequence[float]
|
Two finite values defining the strictly increasing output interval. |
(0.0, 1.0)
|
Returns:
| Type | Description |
|---|---|
NDArray[floating[Any]]
|
Floating array with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the output interval or explicit source statistics are invalid. |
standardize
[source]
standardize(
values: ArrayLike,
*,
mean: ArrayLike | None = None,
std: ArrayLike | None = None,
eps: float = 1e-12,
) -> NDArray[np.floating[Any]]
Center and scale finite values with reusable statistics.
Explicit mean and std arrays follow NumPy broadcasting. Missing statistics are derived globally from finite
entries in values. A standard deviation no greater than eps produces zeros for finite entries, and non-finite
entries are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Values to standardize. |
required |
mean
|
ArrayLike | None
|
Optional finite centering statistic. Defaults to the finite global mean of |
None
|
std
|
ArrayLike | None
|
Optional finite non-negative scale statistic. Defaults to the finite global standard deviation. |
None
|
eps
|
float
|
Non-negative threshold below which the scale is treated as zero. |
1e-12
|
Returns:
| Type | Description |
|---|---|
NDArray[floating[Any]]
|
Floating array with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
scale_by_max
[source]
scale_by_max(
values: ArrayLike,
*,
percentile: float | None = None,
clip: bool | None = None,
) -> NDArray[np.floating[Any]]
Scale finite values by their maximum or an upper percentile.
Percentile scaling clips by default so outliers do not produce values above one. Exact-maximum scaling does not clip by default. Non-finite entries are excluded from statistic estimation and preserved in the returned array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Values to scale. |
required |
percentile
|
float | None
|
Optional finite upper percentile in |
None
|
clip
|
bool | None
|
Whether to clip finite values to the divisor before scaling. Defaults to whether |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[floating[Any]]
|
Floating array with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
See Building an application DataModule for a complete implementation.