Lightning-AI/pytorch-lightning · error · AttributeError

Saving a checkpoint is only possible if a model is attached

Error message

Saving a checkpoint is only possible if a model is attached to the Trainer. Did you call `Trainer.save_checkpoint()` before calling `Trainer.{fit,validate,test,predict}`?

What it means

trainer.save_checkpoint(filepath) was called but self.model is None, meaning no LightningModule is attached. A model only becomes attached after fit/validate/test/predict (or manually setting the strategy's module), so saving before any run has no weights to serialize and raises AttributeError. Internal callers (on_exception, _lr_find, _scale_batch_size) can also surface this when the tuner runs on a Trainer without an attached model.

Source

Thrown at src/lightning/pytorch/trainer/trainer.py:1464

        self, filepath: _PATH, weights_only: Optional[bool] = None, storage_options: Optional[Any] = None
    ) -> None:
        r"""Runs routine to create a checkpoint.

        This method needs to be called on all processes in case the selected strategy is handling distributed
        checkpointing.

        Args:
            filepath: Path where checkpoint is saved.
            weights_only: If ``True``, will only save the model weights.
            storage_options: parameter for how to save to storage, passed to ``CheckpointIO`` plugin

        Raises:
            AttributeError:
                If the model is not attached to the Trainer before calling this method.

        """
        if self.model is None:
            raise AttributeError(
                "Saving a checkpoint is only possible if a model is attached to the Trainer. Did you call"
                " `Trainer.save_checkpoint()` before calling `Trainer.{fit,validate,test,predict}`?"
            )
        with self.profiler.profile("save_checkpoint"):
            checkpoint = self._checkpoint_connector.dump_checkpoint(weights_only)
            self.strategy.save_checkpoint(checkpoint, filepath, storage_options=storage_options)
            self.strategy.barrier("Trainer.save_checkpoint")

    """
    State properties
    """

    @property
    def interrupted(self) -> bool:
        return self.state.status == TrainerStatus.INTERRUPTED

    @property
    def training(self) -> bool:

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Call save_checkpoint only after trainer.fit(model) (or validate/test/predict) has attached the model
  2. To save weights directly from a model, use model.save_checkpoint(filepath) (LightningModule method) or torch.save(model.state_dict(), path) instead
  3. If using the LR finder / scale_batch_size, pass the model to the tuner entrypoint so it attaches first

Example fix

# before
trainer = Trainer()
trainer.save_checkpoint("init.ckpt")
# after
trainer = Trainer()
trainer.fit(model)
trainer.save_checkpoint("model.ckpt")
# or, to save an untrained model directly:
# torch.save(model.state_dict(), "init.ckpt")
Defensive patterns

Strategy: type-guard

Validate before calling

if trainer.model is not None:
    trainer.save_checkpoint(filepath)
else:
    torch.save(model.state_dict(), filepath)  # direct fallback

Type guard

def can_save_checkpoint(t) -> bool:
    return t.model is not None

Prevention

When it happens

Trigger: trainer = Trainer(); trainer.save_checkpoint("model.ckpt") before any fit/validate/test/predict; or wiring save_checkpoint into a checkpoint callback that fires before the model is set up.

Common situations: Scripts that build a Trainer and try to snapshot an initial checkpoint before training, or call save_checkpoint in on_exception handlers / tuner flows where the model was never attached.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/46d3c19d73f524f7. Report an issue: GitHub.