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
TYPE:
|
data
|
The training data can be any
TYPE:
|
batch_size
|
The number of examples in a batch.
TYPE:
|
batch_axes
|
A Example For a dataset of 100 examples
TYPE:
|
run_state
|
Auxiliary runtime state, that is passed to the loss function.
Can be updated via callbacks.
Defaults to
TYPE:
|
validation_data
|
Arbitrary
TYPE:
|
steps
|
Number of gradient updates to apply. Defaults to 1000.
TYPE:
|
loss
|
TYPE:
|
optimizer
|
The optimizer. Any optax gradient transform to calculate the updates for the model. Defaults to optax.adam(1e-3).
TYPE:
|
init_opt_state
|
The initial state of the optimizer. If
TYPE:
|
batcher
|
The data loader that splits inputs and targets into batches.
Defaults to
TYPE:
|
make_logger
|
Whether to create a
TYPE:
|
metrics
|
Sequence of metrics to be added to the
TYPE:
|
log_every
|
Interval for both metric evaluation and progress logging.
A value
TYPE:
|
verbose
|
Integer controlling the verbosity during training.
- 0: Nothing is printed.
- 1: A message is printed every
TYPE:
|
callbacks
|
List of Callbacks. They can be used to
implement early stopping, custom logging and more.
Defaults to
TYPE:
|
jit_compile
|
Whether to compile the function that computes the gradient
update step (this includes the loss function). You generally want
this to be
TYPE:
|
vmap_ensemble
|
If true, the step function and optimizer state
initialization are vmapped across the leading axis of the arrays in
the Note The batcher is not vmapped, meaning that all models in the ensemble will receive identical batches of data. Example
TYPE:
|
key
|
A
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[T, klax.History]
|
A tuple of the trained model and the training history. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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:
|
batch_size
|
The number of examples in a batch.
TYPE:
|
batch_axes
|
PyTree of batch-axis specifications. Each leaf is either
an
TYPE:
|
convert_to_numpy
|
If
TYPE:
|
key
|
A
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Generator[PyTree[Any, 'T'], None, None]
|
A |
| YIELDS | DESCRIPTION |
|---|---|
Generator[PyTree[Any, 'T'], None, None]
|
A |
Generator[PyTree[Any, 'T'], None, None]
|
leaf has been sliced to |
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
TYPE:
|
proportions
|
Proportions of the split that will be applied to the
data, e.g.,
TYPE:
|
batch_axes
|
PyTree of batch-axis specifications. Each leaf is either
an
TYPE:
|
key
|
A
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[T, ...]
|
Tuple of |
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: TheTrainingState.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
TYPE:
|
batch
|
The current batch of data.
TYPE:
|
loss
|
The loss function to optimize.
TYPE:
|
optimizer
|
The optax optimizer to use.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
klax.TrainingState
|
The updated |
klax.make_step(state, batch, loss, optimizer)
¤
Default step function used in fit.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Current training state
TYPE:
|
batch
|
Pytree of training data in the current batch.
TYPE:
|
loss
|
Loss function to minimize.
TYPE:
|
optimizer
|
Opatx optimizer to use for the update step.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TrainingState
|
Updated training state.
TYPE:
|
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:
|
callbacks
|
The list of callbacks to invoke.
TYPE:
|
step_function
|
The step function to call at each step.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TrainingContext
|
The updated training context.
TYPE:
|