pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: hlinnaka (@hlinnaka) <noreply+hlinnaka@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #386: Optimize visiting neighbors
Date: Fri, 22 Dec 2023 14:39:30 +0000
Message-ID: <gh-pgvector-pgvector-386@github.com> (raw)

Here are two more micro-optimizations of HnswSearchLayer, for HNSW index build

## 1st Commit: Add a bulk-variant of AddToVisited

The idea is to move code around so that we collect all the 'hash' values to an array in a tight loop, before performing the hash table lookups. This codepath causes a lot of CPU cache misses, as the elements are scattered around memory, and performing all the fetches upfront allows the CPU to schedule fetching those cachelines sooner. That's my theory of why this works, anyway :-).

This gives a 5%-10% speedup on my laptop, on HNSW index build of a subset of the 'angular-100' dataset (same test I used on my previous PRs). I'd love to hear how this performs on other systems, as this could be very dependent on CPU details.

## 2nd & 3rd commits: Calculate 4 neighbor distances at a time in HNSW search

This is just a proof of concept at this stage, but shows promising results. The idea is to have a variant of the distance function that calculates the distance from one point 'q' to 4 other points in one call. That gives the vectorized loop in the distance function more work to do in each iteration. If you think this is worthwhile, I can spend more time polishing this, adding these array-variants as proper AM support functions, etc.

This gives another 10% speedup on the same test on my laptop. It could possibly be optimized further, by providing variants with different array sizes, or a variable-length version and let the function itself vectorize it in the optimal way. With some refactoring, I think we could also use this in CheckElementCloser(). This might also work well together with PR #311, but I haven't tested that.

inline patch 1: src/hnswutils.c, src/vector.c (+162/-8 lines) download inline-1.patchdiff --git a/src/hnswutils.c b/src/hnswutils.c index 3d0b48409..c44fa99e0 100644 --- a/src/hnswutils.c +++ b/src/hnswutils.c @@ -542,6 +542,62 @@ GetElementDistance(char *base, HnswElement element, Datum q, FmgrInfo *procinfo, return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, value)); } + +extern Datum vector_negative_inner_product(PG_FUNCTION_ARGS); +extern Datum vector_negative_inner_product4(PG_FUNCTION_ARGS); + +/* + * Fill in the 'distance' field in an array of candidates, with the distance + * of each candidate from 'q'. + */ +static void +CalculateCandidateDistances(char *base, HnswUnvisited *unvisited, int unvisitedLength, Datum q, + FmgrInfo *procinfo, Oid collation, + double *distances) +{ + int i; + + /* + * Fast-path: Calculate 4 distances in one call + * + * XXX: I only implemented an array version for + * vector_negative_inner_product(). For a proper implementation, this + * ought to be defined as an extra support function. Or perhaps + * something like btree sortsupport machinery + */ + i = 0; + if (procinfo->fn_addr == vector_negative_inner_product) + { + for (; i < unvisitedLength - 4; i += 4) + { + HnswElement e[4]; + double result[4]; + + e[0] = unvisited[i].element; + e[1] = unvisited[i + 1].element; + e[2] = unvisited[i + 2].element; + e[3] = unvisited[i + 3].element; + DirectFunctionCall6Coll(vector_negative_inner_product4, + collation, + q, + HnswGetValue(base, e[0]), + HnswGetValue(base, e[1]), + HnswGetValue(base, e[2]), + HnswGetValue(base, e[3]), + PointerGetDatum(result)); + distances[i] = result[0]; + distances[i + 1] = result[1]; + distances[i + 2] = result[2]; + distances[i + 3] = result[3]; + } + } + + /* Process the remaining elements one by one */ + for (; i < unvisitedLength; i++) + distances[i] = GetElementDistance(base, unvisited[i].element, q, procinfo, collation); +} + + /* * Create a candidate for the entry point */ @@ -659,24 +715,74 @@ HnswLoadUnvisitedFromMemory(char *base, HnswElement element, HnswUnvisited * unv { /* Get the neighborhood at layer lc */ HnswNeighborArray *neighborhood = HnswGetNeighbors(base, element, lc); + int localNeighborhoodLen; + uint32 hashes[HNSW_MAX_M * 2]; + int num_tovisit; /* Copy neighborhood to local memory */ LWLockAcquire(&element->lock, LW_SHARED); memcpy(localNeighborhood, neighborhood, neighborhoodSize); LWLockRelease(&element->lock); + localNeighborhoodLen = localNeighborhood->length; + + /* + * Fetch the hashes of all the neighbors first. Accessing the hashes + * causes a lot of cache misses, and by initiating them all now, the CPU + * pipeline can look ahead and perform them in parallel. + * + * Alternatively, we could recalculate the hashes from the pointer values, + * and avoid the cache misses from following the pointers. However, that + * just kicks the can down the road: all the unvisited elements need to be + * accessed anyway and the visited elements are already in cache, so we + * will just suffer the cache misses slightly later. It's better to start + * fetching them into the cache now in bulk. + */ +#if PG_VERSION_NUM >= 130000 + Assert(localNeighborhoodLen <= HNSW_MAX_M * 2); + for (int i = 0; i < localNeighborhoodLen; i++) + { + HnswElement hce = HnswPtrAccess(base, localNeighborhood->items[i].element); - *unvisitedLength = 0; + hashes[i] = hce->hash; + } +#endif - for (int i = 0; i < localNeighborhood->length; i++) + num_tovisit = 0; + if (base != NULL) { - HnswCandidate *hc = &localNeighborhood->items[i]; - bool found; + for (int i = 0; i < localNeighborhoodLen; i++) + { + HnswElementPtr hep = localNeighborhood->items[i].element; + bool found; - AddToVisited(base, v, hc->element, NULL, &found); +#if PG_VERSION_NUM >= 130000 + offsethash_insert_hash(v->offsets, HnswPtrOffset(hep), hashes[i], &found); +#else + offsethash_insert(v->offsets, HnswPtrOffset(hep), &found); +#endif - if (!found) - unvisited[(*unvisitedLength)++].element = HnswPtrAccess(base, hc->element); + if (!found) + unvisited[num_tovisit++].element = HnswPtrAccess(base, hep); + } } + else + { + for (int i = 0; i < localNeighborhoodLen; i++) + { + HnswElementPtr hep = localNeighborhood->items[i].element; + bool found; + +#if PG_VERSION_NUM >= 130000 + pointerhash_insert_hash(v->pointers, (uintptr_t) HnswPtrPointer(hep), hashes[i], &found); +#else + pointerhash_insert(v->pointers, (uintptr_t) HnswPtrPointer(hep), &found); +#endif + + if (!found) + unvisited[num_tovisit++].element = HnswPtrAccess(base, hep); + } + } + *unvisitedLength = num_tovisit; } /* @@ -755,6 +861,7 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F Size neighborhoodSize = 0; int lm = HnswGetLayerM(m, lc); HnswUnvisited *unvisited = palloc(lm * sizeof(HnswUnvisited)); + double *unvisitedDistances = palloc(lm * sizeof(double)); int unvisitedLength; InitVisited(base, &v, index, ef, m); @@ -802,6 +909,10 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F else HnswLoadUnvisitedFromDisk(cElement, unvisited, &unvisitedLength, &v, index, m, lm, lc); + if (index == NULL) + CalculateCandidateDistances(base, unvisited, unvisitedLength, q, + procinfo, collation, unvisitedDistances); + for (int i = 0; i < unvisitedLength; i++) { HnswElement eElement; @@ -814,7 +925,7 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F if (index == NULL) { eElement = unvisited[i].element; - eDistance = GetElementDistance(base, eElement, q, procinfo, collation); + eDistance = unvisitedDistances[i]; } else { diff --git a/src/vector.c b/src/vector.c index a5b2aac36..daa9eac45 100644 --- a/src/vector.c +++ b/src/vector.c @@ -650,6 +650,49 @@ VectorCosineSimilarity(int dim, float *ax, float *bx) return (double) similarity / sqrt((double) norma * (double) normb); } +/* + * Compute the distances from 'q' to four other vectors in one function + * call. This is equivalent to calling vector_negative_inner_product + * four times with the same 'q' argument, but faster. + */ +PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_negative_inner_product4); +Datum +vector_negative_inner_product4(PG_FUNCTION_ARGS) +{ + Vector *q = PG_GETARG_VECTOR_P(0); + Vector *a = PG_GETARG_VECTOR_P(1); + Vector *b = PG_GETARG_VECTOR_P(2); + Vector *c = PG_GETARG_VECTOR_P(3); + Vector *d = PG_GETARG_VECTOR_P(4); + double *results = (double *) PG_GETARG_POINTER(5); + float *qx = q->x; + float *ax = a->x; + float *bx = b->x; + float *cx = c->x; + float *dx = d->x; + float distance[4] = { 0.0, 0.0, 0.0, 0.0 }; + + CheckDims(q, a); + CheckDims(q, b); + CheckDims(q, c); + CheckDims(q, d); + + /* Auto-vectorized */ + for (int i = 0; i < q->dim; i++) + { + distance[0] += qx[i] * ax[i]; + distance[1] += qx[i] * bx[i]; + distance[2] += qx[i] * cx[i]; + distance[3] += qx[i] * dx[i]; + } + results[0] = (double) distance[0] * -1; + results[1] = (double) distance[1] * -1; + results[2] = (double) distance[2] * -1; + results[3] = (double) distance[3] * -1; + + PG_RETURN_VOID(); +} + /* * Get the cosine distance between two vectors */

view thread (13+ messages)  latest in thread

Message-ID: <gh-pgvector-pgvector-386@github.com>
Permalink:  ../gh-pgvector-pgvector-386@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