Monitoring callbacks
Monitoring callbacks inspect completed training metrics on the Python host. They do not run inside the compiled update.
Early stopping
EarlyStopping follows Lightning's callback. It checks the monitored metric in on_train_metrics(), so it can monitor
metrics logged by the module with self.log() and metrics contributed by other callbacks. When it stops, it sets
Trainer.should_stop and logs the reason.
| Option | Behavior |
|---|---|
patience |
Stop once wait_count, the number of checks without improvement, reaches it |
min_delta |
Smallest change over best_score that counts as an improvement |
mode |
"min" for losses, "max" for scores where larger values are better |
check_finite |
Stop immediately on a NaN or infinite value; enabled by default |
check_every_n_steps |
Check only at global steps divisible by this interval, avoiding a host sync per step |
Checkpoints store wait_count, best_score, and stopped_step, so a resumed fit stops at the same step as an
uninterrupted one. They also store monitor, mode, and patience:
- Resuming with a different
monitorormodeskips the stored progress with a warning, because a best score of another metric is not comparable. - Resuming with a different
patiencekeeps the configured value and warns, sopatiencecan be changed on resume.
mode uses the public MonitorMode alias.
EarlyStopping
[source]
EarlyStopping(
monitor: str = "train/loss",
patience: int = 100,
mode: MonitorMode = "min",
min_delta: float = 0.0,
check_finite: bool = True,
check_every_n_steps: int = 1,
)
Bases: Callback
Stop training when a monitored scalar metric stops improving, following Lightning's EarlyStopping.
The callback checks the metric in :meth:on_train_metrics, after module-logged and callback metrics are merged,
and requests stopping through :attr:phijax.training.Trainer.should_stop.
Attributes:
| Name | Type | Description |
|---|---|---|
wait_count |
Consecutive checks without improvement. |
|
best_score |
float | None
|
Best monitored value so far, or |
stopped_step |
Global step at which this callback requested stopping, or |
Initialize metric-based early stopping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monitor
|
str
|
Scalar metric checked after each selected training step. |
'train/loss'
|
patience
|
int
|
Number of checks without improvement after which training stops. As in Lightning, training
stops once |
100
|
mode
|
MonitorMode
|
|
'min'
|
min_delta
|
float
|
Smallest absolute change over |
0.0
|
check_finite
|
bool
|
Whether to stop immediately when the monitored value is NaN or infinite. |
True
|
check_every_n_steps
|
int
|
Positive interval of global steps between checks. Each check transfers the metric to the host, so a larger interval avoids a device synchronization on every step. |
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
connect
[source]
Keep the Trainer whose should_stop flag this callback sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
Any
|
Host Trainer coordinating callback hooks. |
required |
on_train_metrics
[source]
Check the monitored metric and request stopping when patience runs out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
TrainerContext
|
Post-update context containing module-logged and callback metrics. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the monitored metric is absent. |
ValueError
|
If the monitored metric is not scalar. |
state_dict
[source]
Return the progress needed to resume early stopping exactly, with the settings it was measured under.
Returns:
| Type | Description |
|---|---|
Mapping[str, Any]
|
JSON-compatible progress ( |
Mapping[str, Any]
|
|
load_state_dict
[source]
Restore early-stopping progress from a checkpoint.
Progress recorded for a different monitor or mode is not comparable, so it is skipped with a warning. The
configured patience always wins; a different stored value only produces a warning. Checkpoints without
stored settings restore their progress.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Mapping[str, Any]
|
Mapping produced by :meth: |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a required progress entry is missing. |
Learning-rate monitoring
LoggingInterval represents the explicit "step" and "epoch" interval values. Passing None follows the Trainer
logging cadence.
LearningRateMonitor evaluates the Optax schedule at the optimizer count for each completed update. It sends
optimizer/lr-Adam to configured loggers when optimizer_name="Adam". logging_interval="step" evaluates every step,
while logging_interval="epoch" evaluates once at the end of fitting. The default None follows
trainer.log_every_n_steps and always records the final rate. Unlike a Lightning scheduler, a raw Optax schedule has
no interval field. PhiJAX therefore avoids evaluating the schedule on steps that will not be logged.
Like Lightning, this callback requires an experiment logger. Fitting raises before requesting the first batch when
LearningRateMonitor is enabled with logger=False, logger=None, or an empty logger collection. The default
logger=True is valid.
Optimizer names identify learning-rate series, while log_momentum and log_weight_decay add -momentum and
-weight_decay suffixes. PhiJAX requires optimizer_name because Optax transformations do not retain their factory
name. Metrics use the optimizer/ group by default; set log_key_prefix to replace it or pass None to disable
grouping. Optional momentum and weight-decay values must be supplied because Optax transformations do not expose
inspectable parameter groups.
LearningRateMonitor
[source]
LearningRateMonitor(
schedule: Callable[[int], Any] | None,
*,
optimizer_name: str,
log_momentum: bool = False,
log_weight_decay: bool = False,
log_key_prefix: str | None = "optimizer/",
logging_interval: LoggingInterval | None = None,
momentum: Any = 0.0,
weight_decay: Any = 0.0,
)
Bases: Callback
Publish optimizer hyperparameters through the standard trainer metric stream.
Optax schedules consume the pre-update optimizer count. A completed trainer step n therefore reports the value
evaluated at n - 1, matching the hyperparameters used for that update. Unlike stateful PyTorch optimizers, an
Optax transformation does not expose mutable parameter groups, so optional momentum and weight decay values are
supplied explicitly by configuration.
Initialize optimizer hyperparameter monitoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
Callable[[int], Any] | None
|
Optax-compatible callable receiving a zero-based optimizer step. |
required |
optimizer_name
|
str
|
Non-empty display name added to |
required |
log_momentum
|
bool
|
Whether to log |
False
|
log_weight_decay
|
bool
|
Whether to log |
False
|
log_key_prefix
|
str | None
|
Optional string prepended verbatim to every metric name. The default groups metrics under
|
'optimizer/'
|
logging_interval
|
LoggingInterval | None
|
|
None
|
momentum
|
Any
|
Optimizer momentum scalar or step-indexed schedule. |
0.0
|
weight_decay
|
Any
|
Optimizer weight-decay scalar or step-indexed schedule. |
0.0
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the schedule, logging flags, prefix, or optimizer hyperparameters have invalid types. |
ValueError
|
If |
setup
[source]
Verify an executable fit supplied a learning-rate schedule.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the callback was instantiated without a schedule. |
on_fit_start
[source]
Require an experiment logger before the first optimizer update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
TrainerContext
|
Initial Trainer context exposing logger availability. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the Trainer has no configured experiment logger. |
training_metrics
[source]
Evaluate the learning rate used by the completed optimizer update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
TrainerContext
|
Post-module context whose step counts completed optimizer updates. |
required |
Returns:
| Type | Description |
|---|---|
Mapping[str, Array]
|
Learning-rate metric and any enabled optimizer hyperparameter metrics. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no schedule was configured. |
ValueError
|
If a configured schedule does not return a scalar. |
state_dict
[source]
Return the most recently emitted optimizer step.
Returns:
| Type | Description |
|---|---|
Mapping[str, Any]
|
JSON-compatible monitor state. |
load_state_dict
[source]
Restore learning-rate emission bookkeeping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Mapping[str, Any]
|
Mapping containing an integer or null |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mapping shape or saved step is invalid. |