{"record":{"id":"7cc47e448c848fb2","repo":"Lightning-AI/pytorch-lightning","slug":"invalid-value-for-save-top-k-self-save-top-k-mu","errorCode":null,"errorMessage":"Invalid value for save_top_k={self.save_top_k}. Must be >= -1","messagePattern":"Invalid value for save_top_k=(.+?)\\. Must be >= -1","errorType":"validation","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/callbacks/model_checkpoint.py","lineNumber":668,"sourceCode":"        # if `check_val_every_n_epoch != 1`, we can't say when the validation dataloader will be loaded\n        # so let's not enforce saving at every training epoch end\n        if trainer.check_val_every_n_epoch != 1:\n            return False\n\n        # no validation means save on train epoch end\n        num_val_batches = (\n            sum(trainer.num_val_batches) if isinstance(trainer.num_val_batches, list) else trainer.num_val_batches\n        )\n        if num_val_batches == 0:\n            return True\n\n        # if the user runs validation multiple times per training epoch, then we run after validation\n        # instead of on train epoch end\n        return trainer.val_check_interval == 1.0\n\n    def __validate_init_configuration(self) -> None:\n        if self.save_top_k < -1:\n            raise MisconfigurationException(f\"Invalid value for save_top_k={self.save_top_k}. Must be >= -1\")\n        if self._every_n_train_steps < 0:\n            raise MisconfigurationException(\n                f\"Invalid value for every_n_train_steps={self._every_n_train_steps}. Must be >= 0\"\n            )\n        if self._every_n_epochs < 0:\n            raise MisconfigurationException(f\"Invalid value for every_n_epochs={self._every_n_epochs}. Must be >= 0\")\n\n        every_n_train_steps_triggered = self._every_n_train_steps >= 1\n        every_n_epochs_triggered = self._every_n_epochs >= 1\n        train_time_interval_triggered = self._train_time_interval is not None\n        if every_n_train_steps_triggered + every_n_epochs_triggered + train_time_interval_triggered > 1:\n            raise MisconfigurationException(\n                f\"Combination of parameters every_n_train_steps={self._every_n_train_steps}, \"\n                f\"every_n_epochs={self._every_n_epochs} and train_time_interval={self._train_time_interval} \"\n                \"should be mutually exclusive.\"\n            )\n\n        if self.monitor is None and self.save_top_k not in (-1, 0, 1):","sourceCodeStart":650,"sourceCodeEnd":686,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/callbacks/model_checkpoint.py#L650-L686","documentation":"ModelCheckpoint's `save_top_k` must be >= -1 (0 saves nothing, -1 saves all, k>0 keeps the k best). `__validate_init_configuration`, called from `__init__`, raises MisconfigurationException for anything below -1.","triggerScenarios":"`ModelCheckpoint(save_top_k=-2)` or a computed value that goes negative. Validated at construction, so it fails before the Trainer runs.","commonSituations":"Config math like `save_top_k=num_checkpoints - 3` going negative; confusing semantics with every_n_epochs; typos or YAML values parsed as unexpected numbers.","solutions":["Use save_top_k=-1 (all), 0 (none), or a positive integer for k-best","Guard computed values: `max(save_top_k, -1)`","Remember separate knobs every_n_train_steps / every_n_epochs control frequency, not count"],"exampleFix":"# before\nModelCheckpoint(monitor='val_loss', save_top_k=-2)\n# after\nModelCheckpoint(monitor='val_loss', save_top_k=-1)  # keep all checkpoints","handlingStrategy":"type-guard","validationCode":"save_top_k = max(int(save_top_k), -1)\nassert save_top_k >= -1","typeGuard":"def valid_save_top_k(v) -> bool:\n    return isinstance(v, int) and not isinstance(v, bool) and v >= -1","tryCatchPattern":null,"preventionTips":["Clamp computed save_top_k values to >= -1","Use typed config validation for checkpoint settings"],"tags":["lightning","model-checkpoint","invalid-argument","callback-config"],"backgroundTag":"invalid-config-value","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}