From: michaelbautin (@michaelbautin) <noreply+michaelbautin@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #769: Adding a precise formula to the README for estimating the amount of memory for HNSW indexing
Date: Tue, 28 Jan 2025 20:34:26 +0000
Message-ID: <gh-pgvector-pgvector-769@github.com> (raw)
The pull request https://github.com/pgvector/pgvector/pull/765 attempted to add functions for estimating the amount of memory needed for HNSW indexing, and was closed by @ankane with an explanation that was somewhat unclear to me. There exists a very precise formula for estimating the amount of memory for fast HNSW indexing in memory without spilling to disk, depending only on M, the number of vectors, and vector size in bytes. It depends on some internal structure sizes of the pgvector extension. If we are not allowed to have that formula as part of HSNW, we will need to implement it outside of pgvector, and expose some of the details mentioned in the following expression to that outside code, or hard-code them and keep them in sync.
```
return MAXALIGN(sizeof(HnswElementData)) +
(avgLevel + 1) * sizeof(HnswNeighborArrayPtr) +
(
MAXALIGN(HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, 0))) +
avgLevel * MAXALIGN(HNSW_NEIGHBOR_ARRAY_SIZE(m))
);
```
Estimating the amount of memory HNSW indexing takes is crucial for correctly configuring maintance_work_mem of the instance to avoid a dramatic drop in indexing performance. We have observed cases where indexing would take an extremely long time, with a high amount of disk I/O, just because of incorrect tuning of memory in relation to the dataset.
The comment https://github.com/pgvector/pgvector/pull/765#issuecomment-2617244649 mentions "actual data from different datasets and index options", but just to reiterate, precise estimation of the amount of memory needed only depends on M, the number of vectors, and vector size in bytes, assuming all vectors are of the same size, and does not depend on any other dataset parameters or index options.