Skip to content

Cosine indexes use centroids from set_centroids without scaling them to unit length #259

Closed

Description

@gouyt13

IvfIndex and HnswIndex with metric="cosine" (new in 0.9, #212) scale data and queries to unit length, but set_centroids keeps the centroids as given. The codes are residuals against those centroids, so centroids far from the unit sphere ruin the estimates. An index that trains its own centroids (train or the first add) is fine, because it trains on the scaled data.

Anyone who runs their own k-means on unscaled vectors and passes the result with cluster_ids hits this, and nothing warns.

Reproduction (dev/0.9 at 5f27939, Python, Linux x86-64): 4000 points in 64 dimensions with norms around 100, 100 queries, 16 clusters, exact 1 - cos as reference, nprobe=16 / ef_search=200, one thread. The raw centroids are the cluster means of the unscaled data (norms 102–131).

Index nbits Centroids Recall@10 Median relative distance error
HNSW 5 raw 0.001 1.93
HNSW 5 scaled to unit length 0.943 0.005
HNSW 5 trained by the index 0.948 0.005
IVF (flat routing) 5 raw 0.001 1.92
IVF (flat routing) 5 scaled to unit length 0.950 0.005
IVF (flat routing) 1 raw 0.000 25.7
IVF (flat routing) 1 scaled to unit length 0.521 0.140

With smaller norms the damage is smaller but still large: centroids of norm 15–19 give a maximum relative error of 34% at 5 bits with HNSW, against 1.5% with unit centroids.

Options

  1. Scale centroids to unit length in set_centroids for cosine indexes, in IvfIndex and HnswIndex and the classes they wrap (ivf::IVF, hnsw::HierarchicalNSW). A zero centroid stays zero, as data does. The file stores the scaled centroids.
  2. Reject centroids that are not unit length.
  3. Document that cosine indexes need unit-length centroids.

Option 1 matches what the index already does to data and queries. Cosine indexes are new in 0.9, so no released file or caller depends on the current behavior; fixing it before 0.9 avoids changing results in a later release.

Activity

  1. added
    bug
    on Nov 20, 2026
  2. added this to the 0.9 milestone on Nov 20, 2026
  3. gouyt13 commented on Nov 20, 2026

    @gouyt13
    MemberAuthor

    Fixed by #260 (merged into dev/0.9 as 9f07dd5); ships in 0.9.0.

  4. added 2 commits that reference this issue on Nov 28, 2026
    3184948
    0c38beb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions