{"record":{"id":"46d3c19d73f524f7","repo":"Lightning-AI/pytorch-lightning","slug":"saving-a-checkpoint-is-only-possible-if-a-model-is","errorCode":null,"errorMessage":"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}`?","messagePattern":"Saving a checkpoint is only possible if a model is attached to the Trainer\\. Did you call `Trainer\\.save_checkpoint\\(\\)` before calling `Trainer\\.(.+?)`\\?","errorType":"validation","errorClass":"AttributeError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/trainer/trainer.py","lineNumber":1464,"sourceCode":"        self, filepath: _PATH, weights_only: Optional[bool] = None, storage_options: Optional[Any] = None\n    ) -> None:\n        r\"\"\"Runs routine to create a checkpoint.\n\n        This method needs to be called on all processes in case the selected strategy is handling distributed\n        checkpointing.\n\n        Args:\n            filepath: Path where checkpoint is saved.\n            weights_only: If ``True``, will only save the model weights.\n            storage_options: parameter for how to save to storage, passed to ``CheckpointIO`` plugin\n\n        Raises:\n            AttributeError:\n                If the model is not attached to the Trainer before calling this method.\n\n        \"\"\"\n        if self.model is None:\n            raise AttributeError(\n                \"Saving a checkpoint is only possible if a model is attached to the Trainer. Did you call\"\n                \" `Trainer.save_checkpoint()` before calling `Trainer.{fit,validate,test,predict}`?\"\n            )\n        with self.profiler.profile(\"save_checkpoint\"):\n            checkpoint = self._checkpoint_connector.dump_checkpoint(weights_only)\n            self.strategy.save_checkpoint(checkpoint, filepath, storage_options=storage_options)\n            self.strategy.barrier(\"Trainer.save_checkpoint\")\n\n    \"\"\"\n    State properties\n    \"\"\"\n\n    @property\n    def interrupted(self) -> bool:\n        return self.state.status == TrainerStatus.INTERRUPTED\n\n    @property\n    def training(self) -> bool:","sourceCodeStart":1446,"sourceCodeEnd":1482,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/trainer/trainer.py#L1446-L1482","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Call save_checkpoint only after trainer.fit(model) (or validate/test/predict) has attached the model","To save weights directly from a model, use model.save_checkpoint(filepath) (LightningModule method) or torch.save(model.state_dict(), path) instead","If using the LR finder / scale_batch_size, pass the model to the tuner entrypoint so it attaches first"],"exampleFix":"# before\ntrainer = Trainer()\ntrainer.save_checkpoint(\"init.ckpt\")\n# after\ntrainer = Trainer()\ntrainer.fit(model)\ntrainer.save_checkpoint(\"model.ckpt\")\n# or, to save an untrained model directly:\n# torch.save(model.state_dict(), \"init.ckpt\")","handlingStrategy":"type-guard","validationCode":"if trainer.model is not None:\n    trainer.save_checkpoint(filepath)\nelse:\n    torch.save(model.state_dict(), filepath)  # direct fallback","typeGuard":"def can_save_checkpoint(t) -> bool:\n    return t.model is not None","tryCatchPattern":null,"preventionTips":["Only call trainer.save_checkpoint after a run has attached the model","Use torch.save(model.state_dict()) for pre-training snapshots"],"tags":["trainer","checkpoint","save","no-model-attached","pytorch-lightning"],"backgroundTag":"saving-without-attached-model","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}