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:
|
__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:
|
| 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:
|
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
TYPE:
|
batch_generator
|
A
TYPE:
|
name
|
A string prefix to prepend to the keys returned by loss.
TYPE:
|
vmap_ensemble
|
Whether to vmap over the training state when
evaluating the loss function. Set to
TYPE:
|
jit_compile
|
Whether to jit compile the loss function for faster metric computations.
TYPE:
|
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:
|
step
|
The step, at which the new value is inserted.
TYPE:
|
value
|
The actual
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the provided |
keys()
¤
Get the names of the metrics stored in the history.
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
A list of metric names. |
save(path, indent=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:
|
| 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
TYPE:
|
| 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:
|
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:
|
exclude_keys
|
Metric names to exclude when plotting.
TYPE:
|
ax
|
Matplotlib axes to plot into. If None` then a new axis is created. (Defaults to None.)
TYPE:
|
kwargs
|
Dictionary of keyword arguments passed to the
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ImportError
|
If |
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:
|
log_every
|
Frequency of logging metrics in steps. Defaults to 100.
TYPE:
|
| 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
TYPE:
|
update_every
|
The step interval at which the progress meter shall be updated during training.
TYPE:
|
keys
|
The keys of the metrics that shall be printed alongside the progress meter.
TYPE:
|
exclude_keys
|
The keys of the metrics that shell be excluded from
the progress meter. This parameter is ignored, if
TYPE:
|