{"record":{"id":"54717f65290d853c","repo":"Lightning-AI/pytorch-lightning","slug":"self-log-name-value-was-called-but-type","errorCode":null,"errorMessage":"`self.log({name}, {value})` was called, but `{type(v).__name__}` values cannot be logged","messagePattern":"`self\\.log\\((.+?), (.+?)\\)` was called, but `(.+?)` values cannot be logged","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":657,"sourceCode":"            return\n\n        if any(isinstance(v, dict) for v in dictionary.values()):\n            raise ValueError(f\"`self.log_dict({dictionary})` was called, but nested dictionaries cannot be logged\")\n        for name, value in dictionary.items():\n            apply_to_collection(value, object, self.__check_allowed, name, value, wrong_dtype=(numbers.Number, Tensor))\n\n        assert self._fabric is not None\n        self._fabric.log_dict(metrics=dictionary)  # type: ignore[arg-type]\n\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]:","sourceCodeStart":639,"sourceCodeEnd":675,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L639-L675","documentation":"__check_allowed runs apply_to_collection over logged values and raises for any element whose type is neither a numbers.Number nor a Tensor. Strings, lists of strings, arbitrary objects, etc. cannot be logged as metrics.","triggerScenarios":"self.log('label', 'cat') (a str), self.log('names', ['a','b']), or logging a non-numeric object under Fabric.","commonSituations":"User tries to log text predictions, class names, or configuration strings as if they were metrics; accidentally passes a tuple/list of mixed objects.","solutions":["Log only numbers/Tensors; convert strings to ids or log text via a dedicated text logger (e.g. TensorBoardLogger.add_text)","For categorical values, map to integer codes before logging","Remove non-numeric entries from the logged dict"],"exampleFix":"# before\nself.log('pred_label', 'cat')\n\n# after\ncode = label_to_id('cat')\nself.log('pred_label_id', code)\n# or: self.logger.experiment.add_text('pred_label', 'cat', step)","handlingStrategy":"type-guard","validationCode":"import numbers\nfrom torch import Tensor\ndef loggable(v) -> bool:\n    return isinstance(v, (numbers.Number, Tensor))\nmetrics = {k: v for k, v in metrics.items() if loggable(v)}","typeGuard":"def is_loggable_value(v) -> bool:\n    import numbers\n    from torch import Tensor\n    return isinstance(v, (numbers.Number, Tensor))","tryCatchPattern":null,"preventionTips":["Filter dicts to numeric/tensor values before logging","Use add_text/experiment loggers for strings"],"tags":["pytorch-lightning","fabric","self-log","type-validation","non-numeric"],"backgroundTag":"non-scalar-log-value","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}