{"record":{"id":"2b896a9ae37d798d","repo":"Lightning-AI/pytorch-lightning","slug":"could-not-find-the-lightningmodule-attribute-for-2b896a","errorCode":null,"errorMessage":"Could not find the `LightningModule` attribute for the `torchmetrics.Metric` logged. You can fix this by calling `self.log({name}, ..., metric_attribute=name)` where `name` is one of {list(self._metric_attributes.values)}","messagePattern":"Could not find the `LightningModule` attribute for the `torchmetrics\\.Metric` logged\\. You can fix this by calling `self\\.log\\((.+?), \\.\\.\\., metric_attribute=name\\)` where `name` is one of (.+?)","errorType":"exception","errorClass":"MisconfigurationException","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":507,"sourceCode":"            # 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(\n                \"With `def training_step(self, dataloader_iter)`, `self.log(..., batch_size=...)` should be provided.\"\n            )\n\n        if logger and trainer.logger is None:\n            rank_zero_warn(\n                f\"You called `self.log({name!r}, ..., logger=True)` but have no logger configured. You can enable one\"\n                \" by doing `Trainer(logger=ALogger(...))`\"","sourceCodeStart":489,"sourceCodeEnd":525,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L489-L525","documentation":"The logged torchmetrics.Metric object was not found among the module's registered metric attributes (id lookup in _metric_attributes failed). Lightning needs an attribute path to checkpoint/restore the metric, so you must tell it where the metric lives via metric_attribute.","triggerScenarios":"Calling self.log('acc', metric) where metric is a duplicate object, a copy, or held in a structure whose attribute name doesn't match any registered Metric (e.g. created ad hoc but other metrics exist on the module).","commonSituations":"User deep-copied a metric, wrapped it in a custom container, or logs a metric stored in a plain python dict attribute; mismatch after reload/mutation of metric objects.","solutions":["Log the exact attribute object: self.log('acc', self.my_metric)","Pass the attribute name: self.log('acc', metric, metric_attribute='my_metric')","Store metrics in nn.ModuleDict so they are discoverable by named_modules"],"exampleFix":"# before\nself.log('acc', my_local_metric)  # not the registered attribute object\n\n# after\nself.log('acc', my_local_metric, metric_attribute='my_metric')\n# where self.my_metric was defined in __init__","handlingStrategy":"validation","validationCode":"attr = next((n for n, m in self.named_modules() if m is metric), None)\nif attr is None:\n    self.log(name, metric.compute(), batch_size=bs)  # log value instead\nelse:\n    self.log(name, metric)","typeGuard":"def metric_attribute_of(module, metric):\n    return next((n for n, m in module.named_modules() if m is metric), None)","tryCatchPattern":null,"preventionTips":["Log the exact stored attribute object, not copies","Pass metric_attribute explicitly when wrapping metrics in containers"],"tags":["pytorch-lightning","self-log","torchmetrics","metric-attribute"],"backgroundTag":"metric-not-registered-on-module","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}