Skill Tracer
Skills › Scientific Agent Skills › pytorch-lightning › callbacks.md

callbacks.md

117 lines · skills/pytorch-lightning/references/callbacks.md at 5f2bc03

Open on GitHub
1# Callback contracts
2
3Targets Lightning 2.6.6. Examples below with project model/data names are
4illustrative; CPU tests exercise checkpoint, early-stopping, learning-rate,
5prediction and state-restoration hooks.
6

Callback contracts

Targets Lightning 2.6.6. Examples below with project model/data names are illustrative; CPU tests exercise checkpoint, early-stopping, learning-rate, prediction and state-restoration hooks.

Raw lines 1 to 6
7## Built-in callbacks
8
9```python
10from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
11from lightning.pytorch.loggers import CSVLogger
13checkpoint = ModelCheckpoint(
14 dirpath="checkpoints",
15 filename="epoch-{epoch:02d}-step-{step:06d}",
16 auto_insert_metric_name=False,
17 monitor="val/loss", mode="min", save_top_k=3, save_last=True,
19callbacks = [checkpoint, EarlyStopping(monitor="val/loss", patience=10),
20 LearningRateMonitor(logging_interval="step")]
21trainer = L.Trainer(callbacks=callbacks, logger=CSVLogger("logs"))
22```
24`save_top_k > 1` requires a monitor. `save_top_k=-1` retains all snapshots.
25`save_last=True` updates at the callback's save events; it is not a guarantee
26against sudden process termination. Use the returned `best_model_path`,
27`last_model_path`, and `best_k_models` instead of guessing a directory. A slash
28in a metric name can create nested paths when automatically inserted into a
29filename; the example uses epoch/step and disables metric-name insertion.
30Align saving with fresh validation metrics. `every_n_train_steps`,
31`train_time_interval`, and `every_n_epochs` are mutually exclusive triggers;
32step-based monitoring may defer saving until validation makes the metric
33available. `save_on_exception=True` is available in 2.6.6, but cannot catch an
34uninterruptible host kill.
36EarlyStopping `patience` counts **checks with no improvement**, not epochs.
37Changing validation frequency changes how long it waits. It defaults to
38`strict=True` and checks finite values. Validation losses logged only during
39sanity checking cannot drive regular checkpoint/early-stop decisions.
41LearningRateMonitor needs an enabled logger. DeviceStatsMonitor reports
42backend-dependent metrics; CPU monitoring needs `psutil`. RichProgressBar and
43RichModelSummary need `rich`. Do not promise identical GPU/CPU/TPU metric names.
44Timer accepts a duration string, `timedelta` or dict and `interval="step"` or
45`"epoch"`; `"batch"` is not valid.
47For scheduled accumulation:
49```python
50from lightning.pytorch.callbacks import GradientAccumulationScheduler
51trainer = L.Trainer(callbacks=[
52 GradientAccumulationScheduler(scheduling={0: 4, 5: 2}),
53])
54```
56This is for automatic optimization and is not supported by every strategy.
57BatchSizeFinder or `Tuner.scale_batch_size` probes a batch-size attribute on the
58model/DataModule; it does not discover a scientifically optimal batch size. It
59needs representative data and spare memory, and tuning support depends on the
60strategy. Prefer the built-in `Tuner.lr_find` to a homemade callback that leaves
61changed weights/LR behind. StochasticWeightAveraging changes model averaging
62and the learning-rate schedule: validate its effect and batch-normalization
63statistics for the actual model.

Built-in callbacks

from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
from lightning.pytorch.loggers import CSVLogger

checkpoint = ModelCheckpoint(
    dirpath="checkpoints",
    filename="epoch-{epoch:02d}-step-{step:06d}",
    auto_insert_metric_name=False,
    monitor="val/loss", mode="min", save_top_k=3, save_last=True,
)
callbacks = [checkpoint, EarlyStopping(monitor="val/loss", patience=10),
             LearningRateMonitor(logging_interval="step")]
trainer = L.Trainer(callbacks=callbacks, logger=CSVLogger("logs"))

save_top_k > 1 requires a monitor. save_top_k=-1 retains all snapshots. save_last=True updates at the callback's save events; it is not a guarantee against sudden process termination. Use the returned best_model_path, last_model_path, and best_k_models instead of guessing a directory. A slash in a metric name can create nested paths when automatically inserted into a filename; the example uses epoch/step and disables metric-name insertion. Align saving with fresh validation metrics. every_n_train_steps, train_time_interval, and every_n_epochs are mutually exclusive triggers; step-based monitoring may defer saving until validation makes the metric available. save_on_exception=True is available in 2.6.6, but cannot catch an uninterruptible host kill.

EarlyStopping patience counts checks with no improvement, not epochs. Changing validation frequency changes how long it waits. It defaults to strict=True and checks finite values. Validation losses logged only during sanity checking cannot drive regular checkpoint/early-stop decisions.

LearningRateMonitor needs an enabled logger. DeviceStatsMonitor reports backend-dependent metrics; CPU monitoring needs psutil. RichProgressBar and RichModelSummary need rich. Do not promise identical GPU/CPU/TPU metric names. Timer accepts a duration string, timedelta or dict and interval="step" or "epoch"; "batch" is not valid.

For scheduled accumulation:

from lightning.pytorch.callbacks import GradientAccumulationScheduler
trainer = L.Trainer(callbacks=[
    GradientAccumulationScheduler(scheduling={0: 4, 5: 2}),
])

This is for automatic optimization and is not supported by every strategy. BatchSizeFinder or Tuner.scale_batch_size probes a batch-size attribute on the model/DataModule; it does not discover a scientifically optimal batch size. It needs representative data and spare memory, and tuning support depends on the strategy. Prefer the built-in Tuner.lr_find to a homemade callback that leaves changed weights/LR behind. StochasticWeightAveraging changes model averaging and the learning-rate schedule: validate its effect and batch-normalization statistics for the actual model.

Raw lines 7 to 64
65## Custom state and hooks
67```python
68from lightning.pytorch.callbacks import Callback
70class BatchCounter(Callback):
71 def __init__(self):
72 self.count = 0
74 @property
75 def state_key(self):
76 return "batch-counter"
78 def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
79 self.count += 1
81 def state_dict(self):
82 return {"count": self.count}
84 def load_state_dict(self, state_dict):
85 self.count = state_dict["count"]
86```
88Give differently configured instances unique `state_key` values. Pass callbacks
89to the resumed Trainer to restore their state. `on_save_checkpoint` and
90`on_load_checkpoint` are notification hooks; persistent callback state belongs
91in `state_dict`/`load_state_dict`.
93- Setup/teardown: `setup(trainer, pl_module, stage)` and `teardown(...)`, including
94 standalone validation.
95- Train batches: `on_train_batch_end(trainer, pl_module, outputs, batch, batch_idx)`.
96- Evaluation/prediction batches additionally accept `dataloader_idx=0`, e.g.
97 `on_predict_batch_end(trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0)`.
98- Inspect unscaled accumulated gradients at
99 `on_before_optimizer_step(trainer, pl_module, optimizer)`.
100- Exceptions: `on_exception(trainer, pl_module, exception)`.
102Do not include sanity-validation metrics in an experiment report: check
103`trainer.sanity_checking`. Detach/copy values when retaining metric snapshots.
104Callbacks generally follow registration order, with documented exceptions such
105as ModelCheckpoint running last; design independent callbacks instead of
106relying on incidental ordering.
108For distributed checkpointing call `trainer.save_checkpoint` on every rank:
109strategies may need collectives. For prediction, write bounded CPU batches to
110rank-specific files using BasePredictionWriter; concatenate by stable sample ID
111and verify duplicates/missing samples. Do not let every rank overwrite the same
112file, or assume rank zero's local predictions include all other ranks.
114Sources: [callback hook signatures](https://github.com/Lightning-AI/pytorch-lightning/blob/2.6.6/src/lightning/pytorch/callbacks/callback.py),
115[ModelCheckpoint](https://github.com/Lightning-AI/pytorch-lightning/blob/2.6.6/src/lightning/pytorch/callbacks/model_checkpoint.py),
116[EarlyStopping](https://github.com/Lightning-AI/pytorch-lightning/blob/2.6.6/src/lightning/pytorch/callbacks/early_stopping.py),
117[Timer](https://github.com/Lightning-AI/pytorch-lightning/blob/2.6.6/src/lightning/pytorch/callbacks/timer.py).

Custom state and hooks

from lightning.pytorch.callbacks import Callback

class BatchCounter(Callback):
    def __init__(self):
        self.count = 0

    @property
    def state_key(self):
        return "batch-counter"

    def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
        self.count += 1

    def state_dict(self):
        return {"count": self.count}

    def load_state_dict(self, state_dict):
        self.count = state_dict["count"]

Give differently configured instances unique state_key values. Pass callbacks to the resumed Trainer to restore their state. on_save_checkpoint and on_load_checkpoint are notification hooks; persistent callback state belongs in state_dict/load_state_dict.

  • Setup/teardown: setup(trainer, pl_module, stage) and teardown(...), including standalone validation.
  • Train batches: on_train_batch_end(trainer, pl_module, outputs, batch, batch_idx).
  • Evaluation/prediction batches additionally accept dataloader_idx=0, e.g. on_predict_batch_end(trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0).
  • Inspect unscaled accumulated gradients at on_before_optimizer_step(trainer, pl_module, optimizer).
  • Exceptions: on_exception(trainer, pl_module, exception).

Do not include sanity-validation metrics in an experiment report: check trainer.sanity_checking. Detach/copy values when retaining metric snapshots. Callbacks generally follow registration order, with documented exceptions such as ModelCheckpoint running last; design independent callbacks instead of relying on incidental ordering.

For distributed checkpointing call trainer.save_checkpoint on every rank: strategies may need collectives. For prediction, write bounded CPU batches to rank-specific files using BasePredictionWriter; concatenate by stable sample ID and verify duplicates/missing samples. Do not let every rank overwrite the same file, or assume rank zero's local predictions include all other ranks.

Sources: callback hook signatures, ModelCheckpoint, EarlyStopping, Timer.

Raw lines 65 to 117