{"record":{"id":"247186f83ed772ec","repo":"Lightning-AI/pytorch-lightning","slug":"the-metric-value-does-not-contain-a-single-ele","errorCode":null,"errorMessage":"The metric `{value}` does not contain a single element, thus it cannot be converted to a scalar.","messagePattern":"The metric `(.+?)` does not contain a single element, thus it cannot be converted to a scalar\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/lightning/fabric/utilities/apply_func.py","lineNumber":131,"sourceCode":"def convert_to_tensors(data: Any, device: _DEVICE) -> Any:\n    # convert non-tensors\n    for src_dtype, conversion_func in CONVERSION_DTYPES:\n        data = apply_to_collection(data, src_dtype, conversion_func, device=device)\n    return move_data_to_device(data, device)\n\n\ndef convert_tensors_to_scalars(data: Any) -> Any:\n    \"\"\"Recursively walk through a collection and convert single-item tensors to scalar values.\n\n    Raises:\n        ValueError:\n            If tensors inside ``metrics`` contains multiple elements, hence preventing conversion to a scalar.\n\n    \"\"\"\n\n    def to_item(value: Tensor) -> Union[int, float, bool]:\n        if value.numel() != 1:\n            raise ValueError(\n                f\"The metric `{value}` does not contain a single element, thus it cannot be converted to a scalar.\"\n            )\n        return value.item()\n\n    return apply_to_collection(data, Tensor, to_item)\n","sourceCodeStart":113,"sourceCodeEnd":137,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/fabric/utilities/apply_func.py#L113-L137","documentation":"The utility _to_/to_item conversion walks a metrics collection and calls .item() on every tensor; tensors with more than one element (numel() != 1) cannot be meaningfully converted to a Python scalar, so a ValueError is raised. This typically surfaces when logging a metric that is a vector/tensor of shape [N] instead of a scalar loss.","triggerScenarios":"Passing a multi-element tensor as a logged metric — e.g. self.log('preds', outputs) where outputs has shape [batch, ...], or fabric.log('metric', per_class_recall_vector) — anywhere Lightning converts collections via to_item (e.g. checkpoint/progress/metric conversion paths).","commonSituations":"Logging raw logits, per-class metric vectors, or confusion matrices; forgetting .mean()/.item() on a loss; refactors changing a metric from scalar to vector (per-class, per-token).","solutions":["Reduce the tensor to a scalar before logging: .mean(), .sum(), .max() or index a single element","If you intentionally need the full tensor, log it via a logger that supports tensors (e.g. TensorBoard add_histogram / Neptune artifacts) rather than scalar metric conversion","Check value.numel() == 1 in your metric computation before passing it on"],"exampleFix":"# before\nself.log('val_recall', per_class_recall)  # shape [num_classes]\n\n# after\nself.log('val_recall', per_class_recall.mean())","handlingStrategy":"validation","validationCode":"def scalar_or_fail(t):\n    assert t.numel() == 1, f'metric must be scalar, got shape {tuple(t.shape)}'\n    return t","typeGuard":"import torch\n\ndef is_scalar_tensor(t: torch.Tensor) -> bool:\n    return t.numel() == 1","tryCatchPattern":null,"preventionTips":["Reduce metrics (.mean()/.sum()) before logging","Unit-test metric shapes in your logging module","Use histogram/artifact loggers for non-scalar tensors"],"tags":["metrics","tensor","scalar","logging","value-error","lightning-fabric"],"backgroundTag":"tensor-to-scalar-conversion-failed","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}