Lightning-AI/pytorch-lightning · error · MisconfigurationException

Could not find the `LightningModule` attribute for the `torc

Error message

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`.

What it means

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.

Source

Thrown at src/lightning/pytorch/core/module.py:500

                f"You called `self.log` with the key `{name}`"
                " but it should not contain information about `dataloader_idx` when `add_dataloader_idx=True`"
            )

        value = apply_to_collection(value, (Tensor, numbers.Number), self.__to_tensor, name)

        if trainer._logger_connector.should_reset_tensors(self._current_fx_name):
            # if we started a new epoch (running its first batch) the hook name has changed
            # reset any tensors for the new hook name
            results.reset(metrics=False, fx=self._current_fx_name)

        if metric_attribute is None and isinstance(value, Metric):
            if self._metric_attributes is None:
                # compute once
                self._metric_attributes = {
                    id(module): name for name, module in self.named_modules() if isinstance(module, Metric)
                }
                if not self._metric_attributes:
                    raise MisconfigurationException(
                        "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`."
                    )
            # try to find the passed metric in the LightningModule
            metric_attribute = self._metric_attributes.get(id(value), None)
            if metric_attribute is None:
                raise MisconfigurationException(
                    "Could not find the `LightningModule` attribute for the `torchmetrics.Metric` logged."
                    f" You can fix this by calling `self.log({name}, ..., metric_attribute=name)` where `name` is one"
                    f" of {list(self._metric_attributes.values())}"
                )

        if (
            trainer.training
            and is_param_in_hook_signature(self.training_step, "dataloader_iter", explicit=True)
            and batch_size is None
        ):
            raise MisconfigurationException(

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Create the metric in __init__ as an attribute: self.accuracy = torchmetrics.Accuracy()
  2. Ensure the metric container is an nn.ModuleList/nn.ModuleDict rather than a plain list/dict
  3. If the metric lives elsewhere, pass metric_attribute='name' explicitly (see the companion error)

Example fix

# before
def validation_step(self, batch, batch_idx):
    acc = torchmetrics.Accuracy(task='multiclass', num_classes=10)
    self.log('acc', acc(batch.y_hat, batch.y))

# after
def __init__(self):
    super().__init__()
    self.acc = torchmetrics.Accuracy(task='multiclass', num_classes=10)
def validation_step(self, batch, batch_idx):
    self.log('acc', self.acc(batch.y_hat, batch.y))
Defensive patterns

Strategy: validation

Validate before calling

from torchmetrics import Metric
registered = {id(m) for m in model.modules() if isinstance(m, Metric)}
if id(metric) not in registered:
    raise ValueError('assign metric as a module attribute (e.g. self.acc = ...) before logging')

Type guard

def is_registered_metric(module, metric) -> bool:
    return any(m is metric for m in module.modules())

Prevention

When it happens

Trigger: 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__.

Common situations: 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.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/204c6bf85ef628f6. Report an issue: GitHub.