{"record":{"id":"2b2a07e6deabd61e","repo":"Lightning-AI/pytorch-lightning","slug":"self-log-name-value-was-called-but-the-te","errorCode":null,"errorMessage":"`self.log({name}, {value})` was called, but the tensor must have a single element. You can try doing `self.log({name}, {value}.mean())`","messagePattern":"`self\\.log\\((.+?), (.+?)\\)` was called, but the tensor must have a single element\\. You can try doing `self\\.log\\((.+?), (.+?)\\.mean\\(\\)\\)`","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":666,"sourceCode":"\n    @staticmethod\n    def __check_not_nested(value: dict, name: str) -> None:\n        # self-imposed restriction. for simplicity\n        if any(isinstance(v, dict) for v in value.values()):\n            raise ValueError(f\"`self.log({name}, {value})` was called, but nested dictionaries cannot be logged\")\n\n    @staticmethod\n    def __check_allowed(v: Any, name: str, value: Any) -> None:\n        raise ValueError(f\"`self.log({name}, {value})` was called, but `{type(v).__name__}` values cannot be logged\")\n\n    def __to_tensor(self, value: Union[Tensor, numbers.Number], name: str) -> Tensor:\n        value = (\n            value.clone().detach()\n            if isinstance(value, Tensor)\n            else torch.tensor(value, device=self.device, dtype=_get_default_dtype())\n        )\n        if not torch.numel(value) == 1:\n            raise ValueError(\n                f\"`self.log({name}, {value})` was called, but the tensor must have a single element.\"\n                f\" You can try doing `self.log({name}, {value}.mean())`\"\n            )\n        value = value.squeeze()\n        return value\n\n    def all_gather(\n        self, data: Union[Tensor, dict, list, tuple], group: Optional[Any] = None, sync_grads: bool = False\n    ) -> Union[Tensor, dict, list, tuple]:\n        r\"\"\"Gather tensors or collections of tensors from multiple processes.\n\n        This method needs to be called on all processes and the tensors need to have the same shape across all\n        processes, otherwise your program will stall forever.\n\n        Args:\n            data: int, float, tensor of shape (batch, ...), or a (possibly nested) collection thereof.\n            group: the process group to gather results from. Defaults to all processes (world)\n            sync_grads: flag that allows users to synchronize gradients for the all_gather operation","sourceCodeStart":648,"sourceCodeEnd":684,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L648-L684","documentation":"__to_tensor requires every logged tensor to contain exactly one element (a scalar) so it can be aggregated. Tensors with more than one element (or zero) raise ValueError; the message suggests reducing via .mean().","triggerScenarios":"self.log('loss', per_sample_losses) where the tensor has shape [batch_size]; logging a vector, image tensor, or empty tensor.","commonSituations":"User logs unreduced loss over the batch, logs predictions array, or logs a tensor that got squeezed to empty.","solutions":["Reduce to a scalar: self.log('loss', loss.mean()) (or .sum()/.max() as appropriate)","Ensure losses computed in training_step are already reduced to one value","Log per-class values under separate scalar keys instead of one vector"],"exampleFix":"# before\nself.log('loss', losses)  # shape [B]\n\n# after\nself.log('loss', losses.mean())","handlingStrategy":"validation","validationCode":"import torch\ndef scalarize(t):\n    return t.mean() if isinstance(t, torch.Tensor) and t.numel() != 1 else t\nself.log(name, scalarize(value))","typeGuard":"def is_scalar_tensor(v) -> bool:\n    import torch\n    return not isinstance(v, torch.Tensor) or v.numel() == 1","tryCatchPattern":null,"preventionTips":["Reduce losses with .mean() before self.log","Assert one-element shape in debug builds for logged tensors"],"tags":["pytorch-lightning","self-log","tensor","scalar","shape-validation"],"backgroundTag":"non-scalar-log-value","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}