Skip to content

Logging

Klax's logging is built around Metrics that are evaluated during training and whose outputs are recorded in the History by a MetricLogger callback. A metric computes a dictionary that maps strings (usually the metric names) to arrays. The LossMetric conveniently combines a loss object and a dataset into a metric, that reports the loss's auxiliary output. Meanwhile, the ProgressMeter callback retrieves the latest metric values from the history and prints them either directly or via a tqdm progress bar.

Metrics¤

klax.Metric ¤

Abstract metric.

At its core, a metric is a simple function that computes a dictionary dict[str, Array] from a given training state. A metric additionally has a name that is used as a prefix to the dictionary keys. This avoids name conflicts, if the same keys are used in different metrics, e.g., "training/loss" and "validation/loss" for two metrics with names "training" and "validation".

Metrics are given to the MetricLogger callback, which evaluates the metrics periodically during training and adds the key value pairs to the History.

Warning

Stateful metrics can carry information about past evaluations and should therefore not be reused for different training runs.

__init__(name) ¤

Initialize the metric.

PARAMETER DESCRIPTION
name

The metrics namespace prefix.

TYPE: str

__call__(state) ¤

Compute the metric values and prefix the key by the metrics name.

PARAMETER DESCRIPTION
state

The current training state on which the metric is evaluated.

TYPE: klax.TrainingState

RETURNS DESCRIPTION
dict[str, Array]

A dictionary with pairs of metric names prefixed by the metrics name and the corresponding values.

klax.metric(name) ¤

Metric decorator.

Create a metric from a function using a decorator.

Example

@klax.metric(name="model_components")
def my_metric(state: klax.TrainingState) -> dict[str, Array]:
    return {"bias": state.model.bias, "weight": state.model.weight}
PARAMETER DESCRIPTION
name

Name for the metric namespace.

TYPE: str

klax.LossMetric(klax.Metric) ¤

A metric based on a loss and a dataset.

A stateful metric, that owns it own batch generator to evaluate a loss function. The metric values are given by the loss' auxiliary quantities.

Warning

Reusing the same LossMetric instance for multiple training runs may result in different logged metric values due to the stateful nature of a batch generator. It is therefore recommended to create a new LossMetric instance for each run.

__init__(loss, batch_generator, name='', vmap_ensemble=False, jit_compile=True) ¤

Initialize the LossMetric.

PARAMETER DESCRIPTION
loss

A loss returning a scalar a dictionary of arrays values via the aux return.

TYPE: klax.Loss

batch_generator

A Generator returning a batch of data on which the loss is evaluated, every time the LossMetric is called.

TYPE: Generator[PyTree, None, None]

name

A string prefix to prepend to the keys returned by loss.

TYPE: str DEFAULT: ''

vmap_ensemble

Whether to vmap over the training state when evaluating the loss function. Set to True if the TrainingState passed to LossMetric contains an ensemble.

TYPE: bool DEFAULT: False

jit_compile

Whether to jit compile the loss function for faster metric computations.

TYPE: bool DEFAULT: True


History¤

klax.History ¤

A pytree holding a history of metrics over multiple trainig steps.

append(key, step, value) ¤

Add an entry to the history.

If the key does not exist yet, it is created. If the key already exists, the new value is appended to the existing list of values for that key.

PARAMETER DESCRIPTION
key

The metric name for which a new value is inserted.

TYPE: str

step

The step, at which the new value is inserted.

TYPE: int

value

The actual ArrayLike value that is inserted.

TYPE: ArrayLike

RAISES DESCRIPTION
ValueError

If the provided step is not strictly increasing for the series specified by key.

keys() ¤

Get the names of the metrics stored in the history.

RETURNS DESCRIPTION
list[str]

A list of metric names.

save(path, indent=2) ¤

Dump the history to a JSON file on the disk.

PARAMETER DESCRIPTION
path

Destination filepath where the history will be stored.

TYPE: str | pathlib.Path

indent

Indentation level for JSON dump.

TYPE: int DEFAULT: 2

load(path) classmethod ¤

Restore a history that was saved with History.save.

PARAMETER DESCRIPTION
path

File path to load the serialized history from.

TYPE: str | pathlib.Path

RETURNS DESCRIPTION
typing.Self

A populated history object.

stack(histories) classmethod ¤

Combine multiple histories into a single history, differentiated by a prefix.

Tip

Use this method to combine multiple histories from different training stages of a single model trianing run. For example:

klax.History.stack({"pretrain": history1, "finetune": history2})

PARAMETER DESCRIPTION
histories

Dictionary mapping prefixes to History objects. Each prefix will be prepended to the metric names in the resulting combined history.

TYPE: dict[str, History]

RETURNS DESCRIPTION
Self

History object containing all metrics from the input histories, with metric names prefixed by their corresponding keys in the input dictionary.

TYPE: typing.Self

plot(*keys, exclude_keys=None, ax=None, **kwargs) ¤

Plot the stored metrics using matplotlib.

Note

This method requires matplotlib.

PARAMETER DESCRIPTION
keys

Metric names to plot. If empty, all metrics are plotted.

TYPE: str

exclude_keys

Metric names to exclude when plotting.

TYPE: Iterable[str] | None DEFAULT: None

ax

Matplotlib axes to plot into. If None` then a new axis is created. (Defaults to None.)

TYPE: Any DEFAULT: None

kwargs

Dictionary of keyword arguments passed to the matplotlib.pyplot.plot function.

TYPE: Any

RAISES DESCRIPTION
ImportError

If matplotlib is not installed.


Callbacks¤

klax.MetricLogger(klax.Callback) ¤

Callback for logging metrics in a history during training.

__init__(metrics, log_every=100) ¤

Initialize the MetricLogger.

PARAMETER DESCRIPTION
metrics

Sequence of metrics to evaluate and log.

TYPE: Sequence[klax.Metric]

log_every

Frequency of logging metrics in steps. Defaults to 100.

TYPE: int DEFAULT: 100

RAISES DESCRIPTION
ValueError

If multiple metrics use the same name(-space).

klax.ProgressMeter(klax.Callback) ¤

A callback for reporting the training progress.

__init__(progress_bar=True, update_every=100, keys=None, exclude_keys=None) ¤

Initialize a ProgressMeter.

PARAMETER DESCRIPTION
progress_bar

Whether to print a progress bar. (Requires tqdm.)

TYPE: bool DEFAULT: True

update_every

The step interval at which the progress meter shall be updated during training.

TYPE: int DEFAULT: 100

keys

The keys of the metrics that shall be printed alongside the progress meter.

TYPE: Iterable[str] | None DEFAULT: None

exclude_keys

The keys of the metrics that shell be excluded from the progress meter. This parameter is ignored, if keys is not None.

TYPE: Iterable[str] | None DEFAULT: None