{"record":{"id":"e665d27113ce054b","repo":"docling-project/docling","slug":"expected-scalar-like-tensor-with-one-element-got","errorCode":null,"errorMessage":"Expected scalar-like tensor with one element, got shape={tuple(value.shape)}","messagePattern":"Expected scalar-like tensor with one element, got shape=(.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"docling/models/inference_engines/common/hf_vision_base.py","lineNumber":128,"sourceCode":"        return self._id_to_label\n\n    @staticmethod\n    def _as_float(value: Any) -> float:\n        if isinstance(value, Real):\n            return float(value)\n\n        if isinstance(value, np.ndarray):\n            if value.size != 1:\n                raise TypeError(\n                    f\"Expected scalar-like ndarray with size 1, got shape={value.shape}\"\n                )\n            return float(value.reshape(-1)[0])\n\n        import torch\n\n        if isinstance(value, torch.Tensor):\n            if value.numel() != 1:\n                raise TypeError(\n                    f\"Expected scalar-like tensor with one element, got shape={tuple(value.shape)}\"\n                )\n            return float(value.item())\n\n        raise TypeError(f\"Unsupported score value type: {type(value)!r}\")\n\n    @staticmethod\n    def _as_int(value: Any) -> int:\n        if isinstance(value, Integral):\n            return int(value)\n\n        if isinstance(value, np.ndarray):\n            if value.size != 1:\n                raise TypeError(\n                    f\"Expected scalar-like ndarray with size 1, got shape={value.shape}\"\n                )\n            return int(value.reshape(-1)[0])\n","sourceCodeStart":110,"sourceCodeEnd":146,"githubUrl":"https://github.com/docling-project/docling/blob/61d76f1ff3f8428065465889f7b4577da7df704c/docling/models/inference_engines/common/hf_vision_base.py#L110-L146","documentation":"Raised as TypeError by HfVisionModelMixin._as_float when a torch.Tensor score does not contain exactly one element (numel() != 1). Same contract as the ndarray variant: score values must be scalar-like tensors before conversion to float.","triggerScenarios":"Passing a multi-element torch tensor (e.g. a [num_classes] score row or [1, num_boxes] slice) to _as_float.","commonSituations":"Feeding raw model logits rows into result construction without argmax/max reduction; batch post-processing that forgot to index per detection.","solutions":["Reduce the tensor to one element first: scores[i, labels[i]] or scores.max().","Call .item() yourself when you know it is scalar, or squeeze and assert numel()==1 in your post-processor.","Align your custom head output with the expected [N] scalar-score layout."],"exampleFix":"# before\nconf = model._as_float(scores_tensor[i])  # shape (num_classes,) -> TypeError\n\n# after\nconf = model._as_float(scores_tensor[i, labels[i]])  # numel()==1","handlingStrategy":"type-guard","validationCode":"if torch.is_tensor(score):\n    assert score.numel() == 1, f'score tensor must have 1 element, got {tuple(score.shape)}'","typeGuard":"import torch\n\ndef is_scalar_tensor(value) -> bool:\n    return not torch.is_tensor(value) or value.numel() == 1","tryCatchPattern":null,"preventionTips":["Index per detection (scores[i, labels[i]]) before conversion.","Prefer .item() where scalarity is guaranteed by construction.","Keep a single post-processing path shared by all model families."],"tags":["torch","post-processing","scores","type-error"],"backgroundTag":null,"analyzedSha":"61d76f1ff3f8428065465889f7b4577da7df704c","analyzedAt":"2026-08-14T23:53:18.727Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}