Skip to content

Fix IVFFlat cosine index builds when cluster centers become zero - #1076

Open
Waterpine wants to merge 1 commit into
pgvector:masterfrom
Waterpine:fix/f003-zero-centroid
Open

Waterpine wants to merge 1 commit into
pgvector:masterfrom
Waterpine:fix/f003-zero-centroid

Conversation

@Waterpine

Copy link
Copy Markdown
Contributor

Valid, nonzero input vectors can produce a zero cluster center when their contributions cancel. Floating-point quantization can also round a nonzero mean to zero. The resulting center cannot be normalized, causing IVFFlat cosine index creation to fail with:

ERROR: Zero norm detected. Please report a bug.

Retain the corresponding previous valid center whenever an updated center has zero norm. Apply this fallback before computing center-movement distances and updating Elkan bounds. Final center validation remains enabled.

Example

Two opposite vectors are sufficient to reproduce the failure:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE tst (id int PRIMARY KEY, v vector(2));

INSERT INTO tst VALUES
    (1, '[1,0]'),
    (2, '[-1,0]');

CREATE INDEX tst_idx
ON tst USING ivfflat (v vector_cosine_ops)
WITH (lists = 1);

Both input vectors have nonzero norms, but their mean is [0,0].

  • Before the fix: index creation fails with the zero-norm error.
  • After the fix: index creation succeeds by retaining the previous valid center.

The regression test also covers means that round to zero for both vector and halfvec.

The complete reproducer is included in test/t/049_f003_regression.pl.

Validation

  • Added 16 regression assertions covering exact cancellation and underflow for vector and halfvec.
  • Verified query results after index creation, REINDEX, VACUUM FULL, and CLUSTER using the primary-key
    index.
  • Confirmed that the unmodified baseline fails on the opposite-vector example.
  • Passed 14 SQL regression tests, the new regression test, and existing IVFFlat center and build-recall
    tests on PostgreSQL 17.

Keep the previous valid center when cancellation or quantization yields
a zero center, before updating center movement bounds. Cover opposite
and underflowing vector and halfvec inputs, builds, and table rewrites.

Audit finding: F003
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant