Lightning-AI/pytorch-lightning · error · MisconfigurationException

error

Error message

error

What it means

When reduce_fx is given as a string, _parse_reduce_fx lowercases it, maps 'avg' to 'mean', and only accepts {'min','max','mean','sum'}; any other string raises this MisconfigurationException. Non-builtin reductions must be expressed via a torchmetrics.Metric, not a custom callable.

Source

Thrown at src/lightning/pytorch/trainer/connectors/logger_connector/result.py:137

    _sync: Optional[_Sync] = None

    def __post_init__(self) -> None:
        if not self.on_step and not self.on_epoch:
            raise MisconfigurationException("`self.log(on_step=False, on_epoch=False)` is not useful.")
        self._parse_reduce_fx()

    def _parse_reduce_fx(self) -> None:
        error = (
            "Only `self.log(..., reduce_fx={min,max,mean,sum})` are supported."
            " If you need a custom reduction, please log a `torchmetrics.Metric` instance instead."
            f" Found: {self.reduce_fx}"
        )
        if isinstance(self.reduce_fx, str):
            reduce_fx = self.reduce_fx.lower()
            if reduce_fx == "avg":
                reduce_fx = "mean"
            if reduce_fx not in ("min", "max", "mean", "sum"):
                raise MisconfigurationException(error)
            self.reduce_fx = getattr(torch, reduce_fx)
        elif self.is_custom_reduction:
            raise MisconfigurationException(error)

    @property
    def sync(self) -> _Sync:
        assert self._sync is not None
        return self._sync

    @sync.setter
    def sync(self, sync: _Sync) -> None:
        if sync.op is None:
            sync.op = self.reduce_fx.__name__
        self._sync = sync

    @property
    def forked(self) -> bool:
        return self.on_step and self.on_epoch

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Use one of the supported strings: reduce_fx='mean' (or 'min'/'max'/'sum'); note 'avg' also works via aliasing
  2. For median/std/custom reductions, log a torchmetrics.Metric instance instead of a tensor with reduce_fx
  3. Pass a supported torch function directly if the string variant is limiting, keeping within the supported set

Example fix

# before
self.log('loss', loss, reduce_fx='median')

# after
self.median = torchmetrics.Median()
self.log('loss', self.median(loss))  # or use a torchmetrics aggregation metric
Defensive patterns

Strategy: validation

Validate before calling

assert reduce_fx in ("min", "max", "mean", "sum", "avg"), "unsupported reduce_fx string"

Type guard

from typing import Union

def is_supported_reduce_str(reduce_fx: str) -> bool:
    return reduce_fx.lower() in ("min", "max", "mean", "sum", "avg")

Prevention

When it happens

Trigger: self.log('x', x, reduce_fx='median'), reduce_fx='AVG' is fine (mapped to mean) but reduce_fx='std' or 'rms' raises; any string outside min/max/mean/sum (after the avg->mean aliasing).

Common situations: Porting code that used 'avg' in older Lightning plus adding other names like 'average' (invalid); trying to get median or std of a metric via a string shortcut instead of implementing a Metric.

Related errors


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