Lightning-AI/pytorch-lightning · error · ValueError

you tried to log {v} which is currently not supported. Try a

Error message

you tried to log {v} which is currently not supported. Try a dict or a scalar/tensor.

What it means

Raised by TensorBoardLogger's `log_metrics` when a metric value cannot be written via `experiment.add_scalar` — i.e. it is not a scalar number, a 0-d/1-element tensor, or a dict of such values. The bare `except Exception` wraps any backend failure into this ValueError.

Source

Thrown at src/lightning/fabric/loggers/tensorboard.py:216

    @override
    @rank_zero_only
    def log_metrics(self, metrics: Mapping[str, float], step: Optional[int] = None) -> None:
        assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0"

        metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR)

        for k, v in metrics.items():
            if isinstance(v, Tensor):
                v = v.item()

            if isinstance(v, dict):
                self.experiment.add_scalars(k, v, step)
            else:
                try:
                    self.experiment.add_scalar(k, v, step)
                # TODO(fabric): specify the possible exception
                except Exception as ex:
                    raise ValueError(
                        f"\n you tried to log {v} which is currently not supported. Try a dict or a scalar/tensor."
                    ) from ex

    @override
    @rank_zero_only
    def log_hyperparams(
        self,
        params: Union[dict[str, Any], Namespace],
        metrics: Optional[dict[str, Any]] = None,
        step: Optional[int] = None,
    ) -> None:
        """Record hyperparameters. TensorBoard logs with and without saved hyperparameters are incompatible, the
        hyperparameters are then not displayed in the TensorBoard. Please delete or move the previously saved logs to
        display the new ones with hyperparameters.

        Args:
            params: A dictionary-like container with the hyperparameters
            metrics: Dictionary with metric names as keys and measured quantities as values

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Reduce the value to a scalar before logging: `float(value.mean())` or `value.item()` for single-element tensors
  2. For multi-value data, log each entry as its own key or use a dedicated summary writer method (add_histogram etc.) outside log_metrics
  3. Sanitize your metrics dict: keep only numbers or 0-d tensors

Example fix

# before
logger.log_metrics({'preds': preds_batch, 'loss': loss})  # preds_batch is shape (B, C)

# after
logger.log_metrics({'loss': loss.item(), 'pred_mean': preds_batch.mean().item()})
Defensive patterns

Strategy: validation

Validate before calling

import math
def sanitize(metrics):
    return {k: (float(v) if not hasattr(v, 'mean') else float(v.mean())) for k, v in metrics.items()}

Try / catch

try:
    logger.log_metrics(metrics, step=step)
except ValueError:
    logger.log_metrics(sanitize(metrics), step=step)

Prevention

When it happens

Trigger: Passing metrics whose values are lists, multi-element tensors, strings, or None; nested dicts that fall into the non-dict branch; tensors with shape (N,) of multiple values. Also triggered when add_scalar itself rejects the value type.

Common situations: Logging a full prediction array, a confusion matrix, or a batch of losses instead of their mean; logging string metrics; logging numpy arrays with more than one element.

Related errors


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