{"record":{"id":"242d976ae0f51c0d","repo":"Stability-AI/generative-models","slug":"unknown-optimizer-idx-optimizer-idx","errorCode":null,"errorMessage":"Unknown optimizer_idx {optimizer_idx}","messagePattern":"Unknown optimizer_idx (.+?)","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"sgm/modules/autoencoding/losses/discriminator_loss.py","lineNumber":292,"sourceCode":"            return loss, log\n        elif optimizer_idx == 1:\n            # second pass for discriminator update\n            logits_real = self.discriminator(inputs.contiguous().detach())\n            logits_fake = self.discriminator(reconstructions.contiguous().detach())\n\n            if global_step >= self.discriminator_iter_start or not self.training:\n                d_loss = self.disc_factor * self.disc_loss(logits_real, logits_fake)\n            else:\n                d_loss = torch.tensor(0.0, requires_grad=True)\n\n            log = {\n                f\"{split}/loss/disc\": d_loss.clone().detach().mean(),\n                f\"{split}/logits/real\": logits_real.detach().mean(),\n                f\"{split}/logits/fake\": logits_fake.detach().mean(),\n            }\n            return d_loss, log\n        else:\n            raise NotImplementedError(f\"Unknown optimizer_idx {optimizer_idx}\")\n\n    def get_nll_loss(\n        self,\n        rec_loss: torch.Tensor,\n        weights: Optional[Union[float, torch.Tensor]] = None,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar\n        weighted_nll_loss = nll_loss\n        if weights is not None:\n            weighted_nll_loss = weights * nll_loss\n        weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]\n        nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]\n\n        return nll_loss, weighted_nll_loss\n","sourceCodeStart":274,"sourceCodeEnd":307,"githubUrl":"https://github.com/Stability-AI/generative-models/blob/e8cd657656fa5d61688191730d0e03242bf4ed44/sgm/modules/autoencoding/losses/discriminator_loss.py#L274-L307","documentation":"The discriminator loss module's forward computes either the generator loss (optimizer_idx 0) or discriminator loss (optimizer_idx 1); any other value hits the else and raises this NotImplementedError. Like error 6, it means the training loop is invoking the loss with an unexpected optimizer index.","triggerScenarios":"Calling LPIPSWithDiscriminator(..., optimizer_idx=2) directly, or training a Lightning module whose loop passes an optimizer_idx outside {0,1} into this loss's forward.","commonSituations":"Older-Lightning-style manual optimization loops passing optimizer_idx; custom training scripts iterating over more than two optimizers; copied training_step code with wrong indexing.","solutions":["Pass optimizer_idx 0 (generator) or 1 (discriminator) only when calling the loss.","Ensure the Lightning module's configure_optimizers returns exactly two optimizers when using this dual-objective loss.","If manual optimization is used, loop over exactly [0, 1] and pass the matching index into each forward call."],"exampleFix":"// before\nfor idx in range(3):\n    loss, log = disc_loss(inputs, reconstructions, split=\"train\", optimizer_idx=idx)\n// after\nfor idx in (0, 1):\n    loss, log = disc_loss(inputs, reconstructions, split=\"train\", optimizer_idx=idx)","handlingStrategy":"validation","validationCode":"# before each loss call in manual optimization\nassert optimizer_idx in (0, 1), f\"optimizer_idx must be 0 (gen) or 1 (disc), got {optimizer_idx}\"","typeGuard":null,"tryCatchPattern":"try:\n    loss, log = disc_loss(x, rec, split=\"train\", optimizer_idx=idx)\nexcept NotImplementedError as e:\n    if \"Unknown optimizer_idx\" in str(e):\n        raise RuntimeError(\"Loss supports optimizer_idx 0/1 only\") from e","preventionTips":["Iterate exactly over (0, 1) in dual-generator/discriminator loops.","Prefer Lightning automatic optimization over hand-rolled optimizer_idx loops."],"tags":["training-loop","optimizer","loss-function"],"backgroundTag":"invalid-optimizer-index","analyzedSha":"e8cd657656fa5d61688191730d0e03242bf4ed44","analyzedAt":"2026-08-29T11:23:43.234Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}