Skip to content

Calibration and Data Handling

klax.fit(model, data, *, batch_size=32, batch_axes=0, run_state=None, validation_data=None, steps=1000, loss=<klax._losses.loss.<locals>.FuncLoss object at 0x7113b503d400>, optimizer=GradientTransformationExtraArgs(init=<function chain.<locals>.init_fn>, update=<function chain.<locals>.update_fn>), init_opt_state=None, batcher=<function batch_data>, make_logger=True, metrics=None, log_every=100, verbose=2, callbacks=None, jit_compile=True, vmap_ensemble=False, key) ¤

Train a model using an optimizer from optax.

This is a convenient wrapper around run_training_loop that sets up optimizer, training state and callbacks.

PARAMETER DESCRIPTION
model

The model instance, which should be trained. It must be a subclass of equinox.Module. The model may contain klax.Unwrappable wrappers.

TYPE: T

data

The training data can be any PyTree with at least some ArrayLike leaves. Most likely you'll want data to be a tuple (x, y) with model inputs x and model outputs y.

TYPE: PyTree[Any]

batch_size

The number of examples in a batch.

TYPE: int DEFAULT: 32

batch_axes

A PyTree denoting, which axis is the batch axis for arrays in data. Each leaf is either an int (positional axis on an array leaf) or None (the corresponding subtree is not batched). batch_axes must be a prefix of data. By specifying batch_axes as a PyTree it is possible to specify different batch axes for different leaves of data. (Defaults to 0, meaning the first axes of arrays in data are batch dimensions.)

Example

For a dataset of 100 examples data = (x, (y1, y2), "some_string") where x has shape (32, 100), y1 has shape (100,) and y2 has shape (100, 10), an appropriate batch_axes would be batch_axes = (1, 0, None) indicating that the batch axis for x is the second axis, for y1 and y2 the first axis and that there is no batch axis for the string.

TYPE: PyTree[None | int] DEFAULT: 0

run_state

Auxiliary runtime state, that is passed to the loss function. Can be updated via callbacks. Defaults to None.

TYPE: PyTree[Any] DEFAULT: None

validation_data

Arbitrary PyTree used for validation during training. Must have the same tree structure as data. (Defaults to None.) Internally, the validation data is used to create a LossMetric for logging. Each time the metric is evaluated, the loss is computed on a batch from the validation dataset with batch size 4*batch_size. Defaults to None

TYPE: PyTree[Any] DEFAULT: None

steps

Number of gradient updates to apply. Defaults to 1000.

TYPE: int DEFAULT: 1000

loss

Loss object defining the loss function. Defaults to mse.

TYPE: klax.Loss DEFAULT: <klax._losses.loss.<locals>.FuncLoss object at 0x7113b503d400>

optimizer

The optimizer. Any optax gradient transform to calculate the updates for the model. Defaults to optax.adam(1e-3).

TYPE: optax.GradientTransformation | optax.GradientTransformationExtraArgs DEFAULT: GradientTransformationExtraArgs(init=<function chain.<locals>.init_fn>, update=<function chain.<locals>.update_fn>)

init_opt_state

The initial state of the optimizer. If None, the optimizer is initialized from scratch. By providing a value for init_opt_state, the user can resume training from a previous state (e.g., obtained from history.final_opt_state). Defaults to None.

TYPE: PyTree[Any] DEFAULT: None

batcher

The data loader that splits inputs and targets into batches. Defaults to batch_data.

TYPE: klax._datahandler.Batcher DEFAULT: <function batch_data>

make_logger

Whether to create a MetricLogger.

TYPE: bool DEFAULT: True

metrics

Sequence of metrics to be added to the MetricLogger. To overwrite the default metrics "training" and "validation" (if validation_data is set) use make_logger=False and create your own metric logger and pass it as a callback. Defaults to None.

TYPE: Sequence[klax.Metric] | None DEFAULT: None

log_every

Interval for both metric evaluation and progress logging. A value log_every=n means that every n steps during the training the metrics are evaluated and (if verbose>0) the training progress and selected metric values are printed.

TYPE: int DEFAULT: 100

verbose

Integer controlling the verbosity during training. - 0: Nothing is printed. - 1: A message is printed every log_every steps. - 2: A progressbar is used and updated every log_every steps. Defaults to 2.

TYPE: Literal[0, 1, 2] DEFAULT: 2

callbacks

List of Callbacks. They can be used to implement early stopping, custom logging and more. Defaults to None.

TYPE: Sequence[klax.Callback] | None DEFAULT: None

jit_compile

Whether to compile the function that computes the gradient update step (this includes the loss function). You generally want this to be True. However, in cases where the loss function itself is not jit-able (e.g., when computing different parts of the loss on different hardware, such as GPU and CPU) it might be advantageous to have more fine grained control over the compilation.

TYPE: bool DEFAULT: True

vmap_ensemble

If true, the step function and optimizer state initialization are vmapped across the leading axis of the arrays in the TrainingState, i.e., model, optimizer state and run state. This is useful to train multiple instances of the same model (ensemble) in a single call to fit.

Note

The batcher is not vmapped, meaning that all models in the ensemble will receive identical batches of data.

Example

    @eqx.filter_vmap
    def make_ensemble(key):
        return klax.nn.MLP("scalar", "scalar", [16, 16], key=key)

    mlp_ensemble = make_ensemble(jr.split(key, 10))

    mlp_ensemble, history = klax.fit(mlp_ensemble, ..., vmap_ensemble=True, ...)

    @eqx.filter_vmap(in_axes=(eqx.if_array(0), None))
    def evaluate_ensemble(ensemble, x):
        return ensemble(x)

    evaluate_ensemble(mlp_ensemble, jax.random.normal(key, (2,)))

TYPE: bool DEFAULT: False

key

A jax.random.PRNGKey used to provide randomness for batch generation.

TYPE: PRNGKeyArray

RETURNS DESCRIPTION
tuple[T, klax.History]

A tuple of the trained model and the training history.

RAISES DESCRIPTION
ValueError

If metrics are provided, but make_logger=False.


Data handling¤

klax.batch_data(data, batch_size, batch_axes=0, convert_to_numpy=True, *, key) ¤

Create a Generator that draws subsets of data without replacement.

The data can be any PyTree whose leaves are arrays or non-array Python values. batch_axes is a PyTree whose leaves are either positional axis indices (int) for array leaves or None for leaves that should not be batched. A generator is returned that indefinitely yields batches of data with size batch_size. Examples are drawn without replacement until the remaining dataset is smaller than batch_size, at which point the dataset is reshuffled and the process starts over.

Example
>>> import klax
>>> import jax
>>> import jax.numpy as jnp
>>>
>>> x = jnp.array([1., 2.])
>>> y = jnp.array([[1.], [2.]])
>>> data = (x, {"a": 1.0, "b": y})
>>> batch_axes = (0, {"a": None, "b": 0})
>>> batch = klax.batch_data(
...     data,
...     32,
...     batch_axes,
...     key=jax.random.key(0)
... )
PARAMETER DESCRIPTION
data

The data that shall be batched.

TYPE: PyTree[Any, 'T']

batch_size

The number of examples in a batch.

TYPE: int

batch_axes

PyTree of batch-axis specifications. Each leaf is either an int (positional axis on an array leaf) or None (do not batch this subtree). batch_axes must have the same structure as data or have data as a prefix. (Defaults to 0, meaning all array leaves in data are batched along their first dimension.)

TYPE: PyTree[None | int] DEFAULT: 0

convert_to_numpy

If True, batched array leaves are converted to NumPy arrays before batching. Numpy's slicing is much faster than JAX's when running on CPU.

TYPE: bool DEFAULT: True

key

A jax.random.PRNGKey used to provide randomness for batch generation. (Keyword only argument.)

TYPE: PRNGKeyArray

RETURNS DESCRIPTION
Generator[PyTree[Any, 'T'], None, None]

A Generator that yields a random batch of data.

YIELDS DESCRIPTION
Generator[PyTree[Any, 'T'], None, None]

A PyTree with the same structure as data, where each batched

Generator[PyTree[Any, 'T'], None, None]

leaf has been sliced to batch_size along its batch dimension.

Note

Note that if the size of the dataset is smaller than batch_size, the used batch_size will be reduced.

klax.split_data(data, proportions, batch_axes=0, *, key) ¤

Split a PyTree of data into multiply randomly drawn subsets.

This function is useful for splitting into training and test datasets. The axis of the split is controlled by the batch_axes argument, which specifies the batch axis for each leaf in data (positional int for array leaves, or None to leave a leaf unsplit).

Example
>>> import klax
>>> import jax
>>>
>>> x = jax.numpy.array([1., 2., 3.])
>>> data = (x, {"a": 1.0, "b": x})
>>> s1, s2 = klax.split_data(
...     data,
...     (2, 1),
...     key=jax.random.key(0)
... )
>>> s1
(Array([1., 2.], dtype=float32), {'a': 1.0, 'b': Array([1., 2.], dtype=float32)})
>>> s2
(Array([3.], dtype=float32), {'a': 1.0, 'b': Array([3.], dtype=float32)})
PARAMETER DESCRIPTION
data

Data that shall be split. It can be any PyTree.

TYPE: T

proportions

Proportions of the split that will be applied to the data, e.g., (80, 20) for a 80% to 20% split. The proportions must be non-negative.

TYPE: Sequence[int | float]

batch_axes

PyTree of batch-axis specifications. Each leaf is either an int (positional axis on an array leaf) or None (do not split this subtree). batch_axes must have the same structure as data or have data as a prefix. (Defaults to 0.)

TYPE: PyTree[None | int] DEFAULT: 0

key

A jax.random.PRNGKey used to provide randomness to the split. (Keyword only argument.)

TYPE: PRNGKeyArray

RETURNS DESCRIPTION
tuple[T, ...]

Tuple of PyTrees.


Behind the scenes¤

Internally klax.fit assembles a TrainingState and a TrainingContext, sets up basic metrics and logging and then runs the optimization via run_training_loop. These internals can be freely used to construct more complex training setups, that go beyond the capabilities of klax.fit

klax.TrainingState ¤

PyTree of the training state, i.e., model, optimizer state and run state.

This class essentially behaves just like

from collections import namedtuple

TrainingState = namedtuple(
    "TrainingState", ["model", "opt_state", "run_state"]
)

Internally, however, it implements the unflattening trick, mentioned in equinox low-overhead-training-loops. This means that instead of storing the PyTree directly, the flattened tree is stored. Only when a specific attribute, e.g., state.model is used, the flat internal representation is unflattened. To avoid repeated unflattening, the unflattend PyTree is cached. When crossing jit boundaries the cache is emptied, ensuring that inside a jit-region the pytree is always first unflattened. This yields performance benefits in tight training loops, where the state is repeatedly passed to a jitted function performing a single gradient update step. Normally, JAX would flatten and unflatten the PyTree when entering and exiting the jit-region. Since this class ensures that the unflattend state is stored outside of jit, we effectively canceled out the flattening and unflattening outside of jit.

RAISES DESCRIPTION
AttributeError

When trying to modify the attributes.

klax.TrainingContext ¤

Collection of all training relevant objects.

This includes:

  • state: The TrainingState.
  • optimizer: The optax optimizer.
  • loss: The Loss function.
  • batch_generator: The generator object responsible for creating data batches.
  • step: The number of currently completed training steps.
  • steps: The total number of scheduled optimization steps for the training run.

klax.StepFunction ¤

__call__(state, batch, loss, optimizer) ¤

Perform one update step in the iterative training process.

PARAMETER DESCRIPTION
state

The current TrainingState.

TYPE: klax.TrainingState

batch

The current batch of data.

TYPE: PyTree

loss

The loss function to optimize.

TYPE: klax.Loss

optimizer

The optax optimizer to use.

TYPE: optax.GradientTransformationExtraArgs

RETURNS DESCRIPTION
klax.TrainingState

The updated TrainingState.

klax.make_step(state, batch, loss, optimizer) ¤

Default step function used in fit.

PARAMETER DESCRIPTION
state

Current training state

TYPE: TrainingState

batch

Pytree of training data in the current batch.

TYPE: PyTree

loss

Loss function to minimize.

TYPE: Loss

optimizer

Opatx optimizer to use for the update step.

TYPE: GradientTransformationExtraArgs

RETURNS DESCRIPTION
TrainingState

Updated training state.

TYPE: klax.TrainingState

klax.run_training_loop(context, callbacks, step_function) ¤

Run training loop.

Repeatedly call the step_function for a given number of steps, applying the specified step function and invoking callbacks.

PARAMETER DESCRIPTION
context

The initial training context.

TYPE: TrainingContext

callbacks

The list of callbacks to invoke.

TYPE: Sequence[Callback]

step_function

The step function to call at each step.

TYPE: StepFunction

RETURNS DESCRIPTION
TrainingContext

The updated training context.

TYPE: klax.TrainingContext