compute_count_vector counts explicit sparse zeros as nonzero values

Author: HuaTNACreated Sep 23, 2026Updated Sep 30, 2026

compute_count_vector counts stored sparse COO entries even when their values are zero. This makes its output depend on whether the same embeddings are represented densely or sparsely, and can inflate the counts used by sparse retrieval evaluation.

Reproduction on main (sentence-transformers 6.2.0.dev0), Python 3.13.13, PyTorch 2.14.0, macOS arm64:

python
import torch
from sentence_transformers.util import compute_count_vector

x = torch.sparse_coo_tensor(
    [[0, 0, 1, 1], [0, 1, 1, 2]],
    [0.0, 2.0, 0.0, 3.0],
    (2, 3),
)
print(compute_count_vector(x.to_dense()).tolist())  # [0, 1, 1]
print(compute_count_vector(x).tolist())             # [1, 2, 1]

Expected: both return [0, 1, 1], counting samples with nonzero values as documented. Coalescing alone does not remove explicit zeros, including zeros produced by duplicate entries cancelling each other.

A small fix and regression tests are ready: filter the coalesced indices by nonzero values before counting. Tests cover 1D and 2D embeddings, explicit zeros, duplicate cancellation, and all-zero embeddings. All four new cases fail before the fix; the full tensor utility module passes afterward (23 tests).

AI assistance was used for the investigation, patch, and local tests. No models or remote datasets were downloaded for the tests.

Source: huggingface/sentence-transformers