docling-project/docling · error · TypeError

Expected scalar-like ndarray with size 1, got shape={value.s

Error message

Expected scalar-like ndarray with size 1, got shape={value.shape}

What it means

Raised as TypeError by HfVisionModelMixin._as_float when a numpy ndarray score does not contain exactly one element. Model outputs are expected to be scalar-like (e.g. per-box score arrays squeezed to size 1); a multi-element array means the post-processing passed an un-reduced slice.

Source

Thrown at docling/models/inference_engines/common/hf_vision_base.py:119

                for label_id, label_name in config.id2label.items()
            }
        except Exception as exc:
            raise RuntimeError(
                f"Failed to load label mapping from model config at {model_folder}: {exc}"
            )

    def get_label_mapping(self) -> Dict[int, str]:
        """Get the label mapping for this model."""
        return self._id_to_label

    @staticmethod
    def _as_float(value: Any) -> float:
        if isinstance(value, Real):
            return float(value)

        if isinstance(value, np.ndarray):
            if value.size != 1:
                raise TypeError(
                    f"Expected scalar-like ndarray with size 1, got shape={value.shape}"
                )
            return float(value.reshape(-1)[0])

        import torch

        if isinstance(value, torch.Tensor):
            if value.numel() != 1:
                raise TypeError(
                    f"Expected scalar-like tensor with one element, got shape={tuple(value.shape)}"
                )
            return float(value.item())

        raise TypeError(f"Unsupported score value type: {type(value)!r}")

    @staticmethod
    def _as_int(value: Any) -> int:
        if isinstance(value, Integral):

View on GitHub (pinned to 61d76f1ff3)

Solutions

  1. Squeeze/select the scalar before conversion: pass score[cls_idx] or float(scores.max()) instead of the row.
  2. Fix the post-processor to emit one scalar score per detection box.
  3. If you control the model wrapper, ensure inference output shapes match the expected [num_detections] score vector.

Example fix

# before
score = scores[row]          # ndarray of per-class scores
conf = model._as_float(score)  # TypeError shape=(num_classes,)

# after
cls = int(labels[row])
conf = model._as_float(scores[row, cls])  # single element
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np
if isinstance(score, np.ndarray):
    assert score.size == 1, f'score must be scalar-like, got {score.shape}'

Type guard

import numpy as np

def is_scalar_score(value) -> bool:
    return not isinstance(value, np.ndarray) or value.size == 1

Prevention

When it happens

Trigger: A detection result's score field is an np.ndarray with size != 1 (e.g. a raw [1, N] or [N] logits/softmax slice) when it reaches score conversion.

Common situations: Custom model heads or post-processors returning per-class score vectors instead of the selected class score; shape regressions after changing batch post-processing code.

Related errors


AI-assisted analysis of docling-project/docling@61d76f1ff3 (2026-08-14). Data as JSON: /api/errors/8f004d9e61800d5b. Report an issue: GitHub.