{"record":{"id":"204c6bf85ef628f6","repo":"Lightning-AI/pytorch-lightning","slug":"could-not-find-the-lightningmodule-attribute-for","errorCode":null,"errorMessage":"Could not find the `LightningModule` attribute for the `torchmetrics.Metric` logged. You can fix this by setting an attribute for the metric in your `LightningModule`.","messagePattern":"Could not find the `LightningModule` attribute for the `torchmetrics\\.Metric` logged\\. You can fix this by setting an attribute for the metric in your `LightningModule`\\.","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":500,"sourceCode":"                f\"You called `self.log` with the key `{name}`\"\n                \" but it should not contain information about `dataloader_idx` when `add_dataloader_idx=True`\"\n            )\n\n        value = apply_to_collection(value, (Tensor, numbers.Number), self.__to_tensor, name)\n\n        if trainer._logger_connector.should_reset_tensors(self._current_fx_name):\n            # if we started a new epoch (running its first batch) the hook name has changed\n            # reset any tensors for the new hook name\n            results.reset(metrics=False, fx=self._current_fx_name)\n\n        if metric_attribute is None and isinstance(value, Metric):\n            if self._metric_attributes is None:\n                # compute once\n                self._metric_attributes = {\n                    id(module): name for name, module in self.named_modules() if isinstance(module, Metric)\n                }\n                if not self._metric_attributes:\n                    raise MisconfigurationException(\n                        \"Could not find the `LightningModule` attribute for the `torchmetrics.Metric` logged.\"\n                        \" You can fix this by setting an attribute for the metric in your `LightningModule`.\"\n                    )\n            # try to find the passed metric in the LightningModule\n            metric_attribute = self._metric_attributes.get(id(value), None)\n            if metric_attribute is None:\n                raise MisconfigurationException(\n                    \"Could not find the `LightningModule` attribute for the `torchmetrics.Metric` logged.\"\n                    f\" You can fix this by calling `self.log({name}, ..., metric_attribute=name)` where `name` is one\"\n                    f\" of {list(self._metric_attributes.values())}\"\n                )\n\n        if (\n            trainer.training\n            and is_param_in_hook_signature(self.training_step, \"dataloader_iter\", explicit=True)\n            and batch_size is None\n        ):\n            raise MisconfigurationException(","sourceCodeStart":482,"sourceCodeEnd":518,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L482-L518","documentation":"When self.log receives a torchmetrics.Metric, Lightning persists the metric by finding its attribute name in named_modules() so it can restore state across epochs. If no Metric instances are registered as module attributes, it cannot map the metric and raises MisconfigurationException.","triggerScenarios":"Calling self.log('acc', some_metric) where some_metric was created inside training_step (a local variable) and never assigned as a self attribute in __init__.","commonSituations":"User instantiates Metric() inline per step for 'freshness' instead of storing it on the module; metric is held inside a plain dict or list that named_modules doesn't traverse as a module.","solutions":["Create the metric in __init__ as an attribute: self.accuracy = torchmetrics.Accuracy()","Ensure the metric container is an nn.ModuleList/nn.ModuleDict rather than a plain list/dict","If the metric lives elsewhere, pass metric_attribute='name' explicitly (see the companion error)"],"exampleFix":"# before\ndef validation_step(self, batch, batch_idx):\n    acc = torchmetrics.Accuracy(task='multiclass', num_classes=10)\n    self.log('acc', acc(batch.y_hat, batch.y))\n\n# after\ndef __init__(self):\n    super().__init__()\n    self.acc = torchmetrics.Accuracy(task='multiclass', num_classes=10)\ndef validation_step(self, batch, batch_idx):\n    self.log('acc', self.acc(batch.y_hat, batch.y))","handlingStrategy":"validation","validationCode":"from torchmetrics import Metric\nregistered = {id(m) for m in model.modules() if isinstance(m, Metric)}\nif id(metric) not in registered:\n    raise ValueError('assign metric as a module attribute (e.g. self.acc = ...) before logging')","typeGuard":"def is_registered_metric(module, metric) -> bool:\n    return any(m is metric for m in module.modules())","tryCatchPattern":null,"preventionTips":["Instantiate all torchmetrics in __init__ as self attributes","Use nn.ModuleDict for metric collections"],"tags":["pytorch-lightning","self-log","torchmetrics","metric-registration"],"backgroundTag":"metric-not-registered-on-module","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}