pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] PR #386: Optimize visiting neighbors
13+ messages / 4 participants
[nested] [flat]
* [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2023-12-22 14:39 "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
0 siblings, 0 replies; 13+ messages in thread
From: hlinnaka (@hlinnaka) @ 2023-12-22 14:39 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
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.patch
diff --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
*/
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2023-12-22 18:21 "jkatz (@jkatz)" <noreply+jkatz@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: jkatz (@jkatz) @ 2023-12-22 18:21 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
🚀 I still have on my TODO to run some serious benchmarks on these patches; I'll work to get those up and running to see how it performs under different contexts on some larger machines. Given they're focused on index building, my thought process is to test:
1. "Regression" tests using the ANN Benchmark suite to capture both performance/recall -- need to do two sets: with and without parallel build
2. Increasing concurrent building benchmarks (discussed [here][1])
3. Testing with the parallel build benchmark on different large data sets (10MM + 100MM) with a focus on timing
[1]: https://aws.amazon.com/blogs/database/accelerate-hnsw-indexing-and-searching-with-pgvector-on-amazon...
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-01-08 20:55 "ankane (@ankane)" <noreply+ankane@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: ankane (@ankane) @ 2024-01-08 20:55 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hey @hlinnaka, thanks for more PRs! I'm currently working on in-memory parallel index builds, but will dig into this and #388 once that's finished (as it may affect the impact on build time).
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-01-29 09:15 "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: hlinnaka (@hlinnaka) @ 2024-01-29 09:15 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Rebased this
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-06-11 08:43 "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: hlinnaka (@hlinnaka) @ 2024-06-11 08:43 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
I was reminded of this by https://www.postgresql.org/message-id/CA%2BhUKGJ_7NKd46nx1wbyXWriuZSNzsTfm%2BrhEuvU6nxZi3-KVw%40mail....
Rebased.
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-09-19 09:35 "ankane (@ankane)" <noreply+ankane@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: ankane (@ankane) @ 2024-09-19 09:35 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hey @hlinnaka, I incorporated some of this in 8dde14a7362e99a4f6b31fc355b96bfa0de5c3b4 as part of work to reduce memory usage for HNSW index scans.
(still planning to visit more of it, but want to get further along in that/filtering work before introducing more complexity)
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-09-21 22:53 "ankane (@ankane)" <noreply+ankane@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: ankane (@ankane) @ 2024-09-21 22:53 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Pushed a version of bulk hashing to the [bulk-hash branch](https://github.com/pgvector/pgvector/compare/bulk-hash), but seeing very little difference on Linux x86-64 and Mac arm64. Let me know if you're still seeing a difference (or if I messed something up with the code).
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-10-07 14:17 "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: hlinnaka (@hlinnaka) @ 2024-10-07 14:17 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
> Pushed a version of bulk hashing to the [bulk-hash branch](https://github.com/pgvector/pgvector/compare/bulk-hash), but seeing very little difference on Linux x86-64 and Mac arm64. Let me know if you're still seeing a difference (or if I messed something up with the code).
Thanks! I'm still seeing a modest ~4-5 % difference from the 'bulk-hash' patch. It feels smaller than what I saw before, but it's still measurable and repeatable.
(I got a new laptop since I wrote this, so I cannot compare on the same hardware anymore)
Rebased this again. The first commit is essentially the same as the bulk-hash branch.
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-10-08 05:17 "ankane (@ankane)" <noreply+ankane@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: ankane (@ankane) @ 2024-10-08 05:17 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@jkatz If you have a chance to test the bulk-hash branch vs its previous commit, I'd be curious to see what you find.
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-10-08 14:13 "jkatz (@jkatz)" <noreply+jkatz@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: jkatz (@jkatz) @ 2024-10-08 14:13 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane By previous commit do you mean what's currently on `master`? Happy to test. (Finishing up one comparing performance btw PG16 + PG17).
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-10-08 15:55 "ankane (@ankane)" <noreply+ankane@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: ankane (@ankane) @ 2024-10-08 15:55 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Cool, I meant the commit it was branched from (`d5e8fc9`), but `master` should work if you merge the latest changes into the branch (just want to make sure the single commit is the only difference).
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386: Optimize visiting neighbors
@ 2024-10-11 15:37 "jkatz (@jkatz)" <noreply+jkatz@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: jkatz (@jkatz) @ 2024-10-11 15:37 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane Understood. I'm working on this test now.
^ permalink raw [nested|flat] 13+ messages in thread
* Re: [pgvector/pgvector] PR #386 (changes requested): Optimize visiting neighbors
@ 2026-06-14 03:51 "sagitrs (@sagitrs)" <noreply+sagitrs@github.com>
11 siblings, 0 replies; 13+ messages in thread
From: sagitrs (@sagitrs) @ 2026-06-14 03:51 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
-
^ permalink raw [nested|flat] 13+ messages in thread
end of thread, other threads:[~2026-06-14 03:51 UTC | newest]
Thread overview: 13+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2023-12-22 14:39 [pgvector/pgvector] PR #386: Optimize visiting neighbors "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
2023-12-22 18:21 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-01-08 20:55 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-01-29 09:15 ` "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
2024-06-11 08:43 ` "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
2024-09-19 09:35 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-09-21 22:53 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-07 14:17 ` "hlinnaka (@hlinnaka)" <noreply+hlinnaka@github.com>
2024-10-08 05:17 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-08 14:13 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-10-08 15:55 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-11 15:37 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2026-06-14 03:51 ` Re: [pgvector/pgvector] PR #386 (changes requested): Optimize visiting neighbors "sagitrs (@sagitrs)" <noreply+sagitrs@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