{"record":{"id":"d9c7c419f28503c5","repo":"Lightning-AI/pytorch-lightning","slug":"trying-to-restore-optimizer-state-but-checkpoint-c","errorCode":null,"errorMessage":"Trying to restore optimizer state but checkpoint contains only the model. This is probably due to `ModelCheckpoint.save_weights_only` being set to `True`.","messagePattern":"Trying to restore optimizer state but checkpoint contains only the model\\. This is probably due to `ModelCheckpoint\\.save_weights_only` being set to `True`\\.","errorType":"validation","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/trainer/connectors/checkpoint_connector.py","lineNumber":375,"sourceCode":"        if (\n            self.trainer.max_epochs != -1\n            and self.trainer.max_epochs is not None\n            and self.trainer.current_epoch > self.trainer.max_epochs\n        ):\n            raise MisconfigurationException(\n                f\"You restored a checkpoint with current_epoch={self.trainer.current_epoch},\"\n                f\" but you have set Trainer(max_epochs={self.trainer.max_epochs}).\"\n            )\n\n    def restore_optimizers_and_schedulers(self) -> None:\n        \"\"\"Restores the optimizers and learning rate scheduler states from the pre-loaded checkpoint.\"\"\"\n        if not self._loaded_checkpoint:\n            return\n\n        if self.trainer.strategy.lightning_restore_optimizer:\n            # validation\n            if \"optimizer_states\" not in self._loaded_checkpoint:\n                raise KeyError(\n                    \"Trying to restore optimizer state but checkpoint contains only the model.\"\n                    \" This is probably due to `ModelCheckpoint.save_weights_only` being set to `True`.\"\n                )\n            self.restore_optimizers()\n\n        if \"lr_schedulers\" not in self._loaded_checkpoint:\n            raise KeyError(\n                \"Trying to restore learning rate scheduler state but checkpoint contains only the model.\"\n                \" This is probably due to `ModelCheckpoint.save_weights_only` being set to `True`.\"\n            )\n        self.restore_lr_schedulers()\n\n    def restore_optimizers(self) -> None:\n        \"\"\"Restores the optimizer states from the pre-loaded checkpoint.\"\"\"\n        if not self._loaded_checkpoint:\n            return\n\n        # restore the optimizers","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/trainer/connectors/checkpoint_connector.py#L357-L393","documentation":"Raised as KeyError in restore_optimizers_and_schedulers when resuming training state: the strategy wants to restore optimizer state (lightning_restore_optimizer true) but the loaded checkpoint lacks the 'optimizer_states' key. This happens when the checkpoint was saved with weights only.","triggerScenarios":"ModelCheckpoint(save_weights_only=True) during the original fit (or load_from_checkpoint-produced weights), then trainer.fit(model, ckpt_path=that_file) with a strategy that restores optimizers (default single-device/DDL; false for e.g. some fault-tolerant flows).","commonSituations":"Saving compact checkpoints to save disk and later deciding to resume training from them; downloading a released weights-only .ckpt; upgrading from versions where save_weights_only defaults or semantics differed.","solutions":["Re-save or originally save with ModelCheckpoint(save_weights_only=False) so optimizer states are included","Start fresh optimizers: load only weights (model.load_from_checkpoint) and call fit without ckpt_path resume, or use a strategy/setup with lightning_restore_optimizer=False","If the full checkpoint exists elsewhere, resume from it instead"],"exampleFix":"# before\nckpt = ModelCheckpoint(save_weights_only=True)  # later: fit(ckpt_path=...) -> KeyError\n# after\nckpt = ModelCheckpoint(save_weights_only=False)\ntrainer.fit(model, ckpt_path=ckpt.best_model_path)  # now restores optimizer state","handlingStrategy":"validation","validationCode":"import torch\nckpt = torch.load(path, map_location=\"cpu\", weights_only=False)\nhas_full_state = \"optimizer_states\" in ckpt\nif trainer.strategy.lightning_restore_optimizer and not has_full_state:\n    # avoid KeyError: load weights only and start fresh\n    model = type(model).load_from_checkpoint(path)\n    trainer.fit(model)  # no ckpt_path","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Save with save_weights_only=False for resumable checkpoints","Inspect keys ('optimizer_states','lr_schedulers') before fit(ckpt_path=...)","Keep weights-only files for inference only"],"tags":["lightning","resume","optimizer-state","weights-only","checkpoint"],"backgroundTag":"weights-only-checkpoint-resume","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}