pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
5+ messages / 2 participants
[nested] [flat]

* [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
@ 2025-01-24 09:13 "michaelbautin (@michaelbautin)" <noreply+michaelbautin@github.com>
  0 siblings, 0 replies; 5+ messages in thread

From: michaelbautin (@michaelbautin) @ 2025-01-24 09:13 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

This will allow users to verify if they can build an HNSW index fully in memory, which is frequently necessary to avoid unacceptable performance degradation, and to compute the appropriate value of maintenance_work_mem.

I am planning to expand this pull request with validation that the estimated memory usage is indeed correct during index build.

Fixes: #745

Related issues: #500

inline patch 1: sql/vector.sql, src/hnswbuild.c (+109/-0 lines) download inline-1.patchdiff --git a/sql/vector.sql b/sql/vector.sql index 7fc36712b..6fbcb5aaa 100644 --- a/sql/vector.sql +++ b/sql/vector.sql @@ -916,3 +916,11 @@ CREATE OPERATOR CLASS sparsevec_l1_ops OPERATOR 1 <+> (sparsevec, sparsevec) FOR ORDER BY float_ops, FUNCTION 1 l1_distance(sparsevec, sparsevec), FUNCTION 3 hnsw_sparsevec_support(internal); + +CREATE FUNCTION hnsw_build_memory_bytes_per_vector(integer, integer) + RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION hnsw_build_memory_bytes_per_halfvec(integer, integer) + RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; diff --git a/src/hnswbuild.c b/src/hnswbuild.c index b667478b6..ae6428c02 100644 --- a/src/hnswbuild.c +++ b/src/hnswbuild.c @@ -53,6 +53,8 @@ #include "tcop/tcopprot.h" #include "utils/datum.h" #include "utils/memutils.h" +#include "fmgr.h" +#include "halfvec.h" #if PG_VERSION_NUM >= 140000 #include "utils/backend_progress.h" @@ -1050,6 +1052,80 @@ ComputeParallelWorkers(Relation heap, Relation index) return max_parallel_maintenance_workers; } +static double +HnswMemoryBytesPerElementExcludingValue(int m, double ml) { + double geometricP = 1 - exp(-1 / ml); + + /* + * Average level of a node. We subtract 1 because we number levels starting + * from 0. On average, a node is present at (avgLevel + 1) levels. + */ + double avgLevel = 1 / geometricP - 1; + + /* + * For each element we store: + * - HnswElementData struct + * - An array of pointers to neighbor arrays, as many as the number of + * levels where the element is present. + * - The neighbor arrays themselves. We need to take into account that the + * lowest level has a different number of neighbors per node than higher + * levels. But it also helps that every node is present at the lowest + * level. + */ + return MAXALIGN(sizeof(HnswElementData)) + + (avgLevel + 1) * sizeof(HnswNeighborArrayPtr) + + ( + MAXALIGN(HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, 0))) + + avgLevel * MAXALIGN(HNSW_NEIGHBOR_ARRAY_SIZE(m)) + ); +} + +/* + * Returns the number of bytes used by a single element on average, excluding + * the vector value itself. The vector value size depends on the vector data + * type and the number of dimensions. + */ +static double +HnswMemoryBytesPerElementExcludingValueForM(int m) +{ + return HnswMemoryBytesPerElementExcludingValue(m, HnswGetMl(m)); +} + +/* + * Validate our memory usage estimation formula to ensure that users have a + * good way to provision sufficient memory for an HNSW build. This assumes that + * the graph was built fully in memory. + */ +static void ValidateMemoryUsageEstimation(HnswBuildState * buildstate) +{ + HnswGraph * graph = buildstate->graph; + Size actualMemoryUsage = graph->memoryUsed; + double numTuples = graph->indtuples; + if (numTuples < 1) { + return; + } + double actualMemoryUsagePerTuple = actualMemoryUsage / numTuples; + + /* TODO: use the actual vector size, do not assume float vectors. */ + double estimatedMemoryUsagePerTuple = + HnswMemoryBytesPerElementExcludingValue(buildstate->m, buildstate->ml) + + VECTOR_SIZE(buildstate->dimensions); + + double estimationError = + (estimatedMemoryUsagePerTuple - actualMemoryUsagePerTuple) / + actualMemoryUsagePerTuple; + elog( + NOTICE, + "Tuples indexed in memory: %.0f, " + "bytes used per tuple: %.3f, " + "estimated bytes per tuple: %.3f, " + "estimation error: %.6f%%", + numTuples, + actualMemoryUsagePerTuple, + estimatedMemoryUsagePerTuple, + estimationError * 100); +} + /* * Build graph */ @@ -1082,7 +1158,10 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum) /* Flush pages */ if (!buildstate->graph->flushed) + { FlushPages(buildstate); + ValidateMemoryUsageEstimation(buildstate); + } /* End parallel build */ if (buildstate->hnswleader) @@ -1139,3 +1218,25 @@ hnswbuildempty(Relation index) BuildIndex(NULL, index, indexInfo, &buildstate, INIT_FORKNUM); } + +FUNCTION_PREFIX PG_FUNCTION_INFO_V1(hnsw_build_memory_bytes_per_vector); +Datum +hnsw_build_memory_bytes_per_vector(PG_FUNCTION_ARGS) +{ + int dimensions = PG_GETARG_INT32(0); + int m = PG_GETARG_INT32(1); + + PG_RETURN_FLOAT8(HnswMemoryBytesPerElementExcludingValueForM(m) + + VECTOR_SIZE(dimensions)); +} + +FUNCTION_PREFIX PG_FUNCTION_INFO_V1(hnsw_build_memory_bytes_per_halfvec); +Datum +hnsw_build_memory_bytes_per_halfvec(PG_FUNCTION_ARGS) +{ + int dimensions = PG_GETARG_INT32(0); + int m = PG_GETARG_INT32(1); + + PG_RETURN_FLOAT8(HnswMemoryBytesPerElementExcludingValueForM(m) + + HALFVEC_SIZE(dimensions)); +}
^ permalink raw [nested|flat] 5+ messages in thread

* Re: [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
@ 2025-01-28 00:18 ` "ankane (@ankane)" <noreply+ankane@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: ankane (@ankane) @ 2025-01-28 00:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @michaelbautin, thanks for the PR. If someone comes up with an approximate formula based on actual data from different datasets and index options, I may be open to including it in the readme, but don't want to add a function for it.

^ permalink  raw  [nested|flat] 5+ messages in thread

* Re: [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
@ 2025-01-28 00:18 ` "ankane (@ankane)" <noreply+ankane@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: ankane (@ankane) @ 2025-01-28 00:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

^ permalink  raw  [nested|flat] 5+ messages in thread

* Re: [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
@ 2025-01-28 02:14 ` "michaelbautin (@michaelbautin)" <noreply+michaelbautin@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: michaelbautin (@michaelbautin) @ 2025-01-28 02:14 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane The formulas in this PR are very precise (less than 0.01% error in my experiments), as long as we know the vector sizes. For sparse vectors, where the vector size might vary, this would be more complicated. But to compute the same formulas outside of the pgvector code, we would have to know various sizeof values of internal data structures. So any memory sizing automation code would have to know these internal details.

^ permalink  raw  [nested|flat] 5+ messages in thread

* Re: [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index
@ 2025-01-28 02:23 ` "michaelbautin (@michaelbautin)" <noreply+michaelbautin@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: michaelbautin (@michaelbautin) @ 2025-01-28 02:23 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane 
>  If someone comes up with an approximate formula based on actual data from different datasets and index options

I am not sure what you mean by "formula based on actual data". The only parameters influencing the HNSW build memory  consumption are M (given that mL is computed based on M), the number of vectors, and per-vector memory usage, assuming it is the same for all vector, which covers a lot of use cases. Given those parameters, the memory usage can be estimated with a very high precision and there is no need for any additional data collection from different datsets.

^ permalink  raw  [nested|flat] 5+ messages in thread


end of thread, other threads:[~2025-01-28 02:23 UTC | newest]

Thread overview: 5+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-01-24 09:13 [pgvector/pgvector] PR #765: Functions to estimate the amount of memory for building an HNSW index "michaelbautin (@michaelbautin)" <noreply+michaelbautin@github.com>
2025-01-28 00:18 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-01-28 00:18 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-01-28 02:14 ` "michaelbautin (@michaelbautin)" <noreply+michaelbautin@github.com>
2025-01-28 02:23 ` "michaelbautin (@michaelbautin)" <noreply+michaelbautin@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