Checkpoint on final train batch can leave FitLoop in RESTARTED_MID_EPOCH and replay an epoch on resume
Bug description
When a checkpoint is saved by ModelCheckpoint(every_n_train_steps=...) exactly on an epoch's last
training batch, _FitLoop.reset() fast-forwards the epoch progress by marking the current epoch as
processed/completed, but leaves _restart_stage == RESTARTED_MID_EPOCH.
As a result, the next call to on_advance_start() still treats the loop as if it were resuming the
previous epoch and skips:
increment_ready()
on_train_epoch_start()
increment_started()However, _FitLoop.advance() still runs, so a full new training epoch executes without being reflected
in the fit-level ready / started counters.
A checkpoint saved during that untracked epoch can therefore contain:
ready == started == processed == completedeven though another epoch has actually run.
On a subsequent resume, this state looks like there is no epoch in flight. Lightning therefore starts
the next epoch again instead of recognizing that it has already been executed. In the reproducer, this
causes the final epoch to run twice and attempts scheduler step 61 even though
OneCycleLR(total_steps=60) has a fixed budget of 60 steps.
What version are you seeing the problem on?
master
Reproduced in studio
No response
How to reproduce the bug
import os
import shutil
import lightning.pytorch as pl
import torch
import torch.nn as nn
from lightning.pytorch.callbacks import Callback, ModelCheckpoint
from torch.utils.data import DataLoader, TensorDataset
CKPT_DIR = "./repro_ckpts"
class StopAfterEpoch(Callback):
def __init__(self, stop_epoch):
self.stop_epoch = stop_epoch
def on_train_epoch_end(self, trainer, pl_module):
if trainer.current_epoch == self.stop_epoch:
trainer.should_stop = True
class PrintProgress(Callback):
def _print(self, trainer, where):
p = trainer.fit_loop.epoch_progress.current
print(
f"[{where}] "
f"epoch={trainer.current_epoch} "
f"global_step={trainer.global_step} "
f"ready={p.ready} "
f"started={p.started} "
f"processed={p.processed} "
f"completed={p.completed}"
)
def on_train_epoch_start(self, trainer, pl_module):
self._print(trainer, "epoch_start")
def on_save_checkpoint(self, trainer, pl_module, checkpoint):
self._print(trainer, "checkpoint")
class Model(pl.LightningModule):
def __init__(self):
super().__init__()
self.net = nn.Linear(10, 1)
def training_step(self, batch, batch_idx):
x, y = batch
return torch.nn.functional.mse_loss(self.net(x), y)
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.parameters(), lr=0.1)
scheduler = torch.optim.lr_scheduler.OneCycleLR(
optimizer,
max_lr=0.1,
total_steps=self.trainer.estimated_stepping_batches,
)
return {
"optimizer": optimizer,
"lr_scheduler": {
"scheduler": scheduler,
"interval": "step",
},
}
def make_checkpoint_callback():
return ModelCheckpoint(
dirpath=CKPT_DIR,
filename="epoch={epoch}-step={step}",
auto_insert_metric_name=False,
every_n_train_steps=2,
save_top_k=-1,
)
def main():
shutil.rmtree(CKPT_DIR, ignore_errors=True)
os.makedirs(CKPT_DIR)
loader = DataLoader(
TensorDataset(torch.randn(20, 10), torch.randn(20, 1)),
batch_size=10,
)
trainer_kwargs = dict(
max_epochs=4,
limit_train_batches=2,
limit_val_batches=0,
accelerator="cpu",
devices=1,
enable_progress_bar=False,
logger=False,
)
# Phase A:
# Run epochs 0, 1, 2.
# The checkpoint at step 6 is saved by on_train_batch_end
# on epoch 2's last training batch.
print("\n=== PHASE A ===")
ckpt_cb = make_checkpoint_callback()
trainer = pl.Trainer(
**trainer_kwargs,
callbacks=[ckpt_cb, PrintProgress(), StopAfterEpoch(2)],
)
trainer.fit(Model(), loader)
ckpt_a = os.path.join(CKPT_DIR, "epoch=2-step=6.ckpt")
# Phase B:
# Resume and run the final epoch (epoch 3).
print("\n=== PHASE B ===")
ckpt_cb = make_checkpoint_callback()
trainer = pl.Trainer(
**trainer_kwargs,
callbacks=[ckpt_cb, PrintProgress()],
)
trainer.fit(Model(), loader, ckpt_path=ckpt_a)
ckpt_b = os.path.join(CKPT_DIR, "epoch=3-step=8.ckpt")
# Phase C:
# max_epochs=4 has already been reached, so this should be a no-op.
# Instead, Lightning starts epoch 3 again and OneCycleLR receives step 9/8.
print("\n=== PHASE C ===")
trainer = pl.Trainer(
**trainer_kwargs,
callbacks=[PrintProgress()],
)
trainer.fit(Model(), loader, ckpt_path=ckpt_b)
if __name__ == "__main__":
main()Error messages and logs
# Error messages and logs here pleaseEnvironment
Current environment- PyTorch Lightning Version: 2.6.5
- PyTorch Version: 2.9.1
- Python version: 3.10More info
No response
cc @ethanwharris
Source: Lightning-AI/pytorch-lightning