pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: zthhhhh (@zthhhhh) <noreply+zthhhhh@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #991: Optimize zero-vector detection in vector_norm with early exit
Date: Wed, 24 Jun 2026 16:35:13 +0000
Message-ID: <gh-pgvector-pgvector-991@github.com> (raw)

The `vector_norm`function computes the full Euclidean norm:
https://github.com/pgvector/pgvector/blob/master/src/vector.c#L763

In practice, `vector_norm ` is used as the NORM_PROC in HNSW and IVF operator classes (e.g. vector_cosine_ops) to detect all-zero vectors so they can be skipped during index building and insertion.  For example, HnswCheckNorm and IvfflatCheckNorm both check vector_norm(...) > 0 , they only care whether the vector is zero, not the actual norm value.

Because of this, vector_norm always iterates through every element (computing squares and sqrt), even if the first element is already non-zero.  This is wasteful when the only goal is zero detection.

A simple early-exit optimization can reduce the loop cost for non-zero vectors (the vast majority in practice):
```
for (int i = 0; i < a->dim; i++)
{
    if (ax[i] != 0)
    {
        norm = 1.0;
        break;
    }
}
```

I'd like to propose adding a lightweight zero-check function (or optimizing the NORM_PROC usage) so that the index build/insert hot path doesn't pay the cost of a full Euclidean norm when only zero-detection is needed.

view thread (3+ messages)  latest in thread

Message-ID: <gh-pgvector-pgvector-991@github.com>
Permalink:  ../gh-pgvector-pgvector-991@github.com/

 · 


This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox