{"record":{"id":"50ec0c6a13f6ca7a","repo":"Lightning-AI/pytorch-lightning","slug":"an-optimizer-should-be-passed-only-once-to-the-se","errorCode":null,"errorMessage":"An optimizer should be passed only once to the `setup` method.","messagePattern":"An optimizer should be passed only once to the `setup` method\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/lightning/fabric/fabric.py","lineNumber":1206,"sourceCode":"                \" or change your code to directly call `fabric = Fabric(...); fabric.setup(...)` etc.\"\n            )\n        # wrap the run method, so we can inject setup logic or spawn processes for the user\n        setattr(self, \"run\", partial(self._wrap_and_launch, self.run))\n\n    def _validate_launched(self) -> None:\n        if not self._launched and not isinstance(self._strategy, (SingleDeviceStrategy, DataParallelStrategy)):\n            raise RuntimeError(\n                \"To use Fabric with more than one device, you must call `.launch()` or use the CLI:\"\n                \" `fabric run --help`.\"\n            )\n\n    def _validate_setup(self, module: nn.Module, optimizers: Sequence[Optimizer]) -> None:\n        self._validate_launched()\n        if isinstance(module, _FabricModule):\n            raise ValueError(\"A model should be passed only once to the `setup` method.\")\n\n        if any(isinstance(opt, _FabricOptimizer) for opt in optimizers):\n            raise ValueError(\"An optimizer should be passed only once to the `setup` method.\")\n\n        if isinstance(self._strategy, FSDPStrategy) and any(\n            _has_meta_device_parameters_or_buffers(optimizer) for optimizer in optimizers\n        ):\n            raise RuntimeError(\n                \"The optimizer has references to the model's meta-device parameters. Materializing them is\"\n                \" is currently not supported unless you to set up the model and optimizer(s) separately.\"\n                \" Create and set up the model first through `model = fabric.setup_module(model)`. Then create the\"\n                \" optimizer and set it up: `optimizer = fabric.setup_optimizers(optimizer)`.\"\n            )\n\n    def _validate_setup_module(self, module: nn.Module) -> None:\n        self._validate_launched()\n        if isinstance(module, _FabricModule):\n            raise ValueError(\"A model should be passed only once to the `setup_module` method.\")\n\n    def _validate_setup_optimizers(self, optimizers: Sequence[Optimizer]) -> None:\n        self._validate_launched()","sourceCodeStart":1188,"sourceCodeEnd":1224,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/fabric.py#L1188-L1224","documentation":"Same double-setup guard as for models, but for optimizers: if any optimizer passed to fabric.setup()/setup_optimizers() is already a _FabricOptimizer, Fabric raises ValueError because re-wrapping would break the strategy's optimizer state.","triggerScenarios":"optimizer = fabric.setup_optimizers(optimizer) called twice, or calling fabric.setup(model, optimizer) after the optimizer was already set up in a previous call.","commonSituations":"Splitting model and optimizer setup across epochs or restarts; a training loop that re-enters an init function containing setup calls.","solutions":["Set up each optimizer exactly once; keep the returned reference","If the model is already wrapped, only pass the new optimizer: fabric.setup_optimizers(new_opt)"],"exampleFix":"# before\nopt = fabric.setup_optimizers(opt)\n...\nopt = fabric.setup_optimizers(opt)  # second time\n# after\nopt = fabric.setup_optimizers(opt)  # only once; reuse opt thereafter","handlingStrategy":"type-guard","validationCode":"from lightning.fabric.wrappers import _FabricOptimizer\nassert not any(isinstance(o, _FabricOptimizer) for o in optimizers)","typeGuard":"from lightning.fabric.wrappers import _FabricOptimizer\ndef needs_opt_setup(optimizers):\n    return not any(isinstance(o, _FabricOptimizer) for o in optimizers)","tryCatchPattern":null,"preventionTips":["Treat setup as one call per object, tracked in variables; don't re-enter init code containing setup"],"tags":["lightning","fabric","setup","optimizer","double-setup"],"backgroundTag":"double-initialization","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}