You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi all, support for in-memory, parallel index builds is now available in the hnsw-fast-build branch 🎉
A few benchmarks from my local machine with the SIFT 1M dataset (128 dimensions):
code version
processes
build time
0.5.1
1
415 sec
master
1
309 sec
branch
2
184 sec
branch
4
107 sec
branch
8
83 sec
A few useful settings are:
SET max_parallel_maintenance_workers =3; -- plus leader (default is 2)SET maintenance_work_mem ='8GB'; -- memory to useSET client_min_messages = DEBUG; -- prints worker information
For a high number of workers, you may also need to increase max_parallel_workers (default is 8).
Please test it out (in a non-production environment) and share any feedback. Aiming for a release (0.5.2) at the end of January if all goes well.
Reacted by Jonathan S. Katz, Pavel Borisov, lin72h, K-Dog (Kevin), James Yao, Mais Alheraki, Brecht Carnewal and Wahaj Ali
Reacted by Pierre Dulac, lin72h, Mais Alheraki, Brecht Carnewal and Wahaj Ali
When I checked in on master, it was about 16% completed. However, when looking pg_stat_progress_create_index, hnsw-fast-bulid-branch was outpacing master by about 10x.
hnsw-fast-bulid-branch was indexing at about 6,565 tps, which was more than 6x faster than the concurrent insert method on a similar data set...and the other data set had ef_construction at 64!
This looks really promising! There are a few more tests I plan to run:
"Regression" tests against ANN Benchmark to ensure recall is not skewed.
Running with different values of max_parallel_maintenance_workers to understand the performance profile
A few tests with different vector sizes. At least 128 and 1536, but I'd like to also try 384 and 768.
Anyway, this looks awesome!
Reacted by Andrew Kane, Pavel Borisov, Oliver Rice, Heikki Linnakangas, Pierre Dulac, DANNI WEI and Max Feinberg
Running into an issue with Docker if anyone has ideas.
Docker has a default shared memory limit of 64 MB (shm_size). When trying to allocate more shared memory, CREATE INDEX fails with ERROR: could not resize shared memory segment. Ideally, it would fallback to a serial build, but I'm having trouble getting this to happen.
It initially fails on the InitializeParallelDSM call. One way around this is to create a minimal DSA, then try to allocate from that (hnsw-fast-build-dsa branch). However, it fails with the same error on dsa_allocate_extended, even when DSA_ALLOC_NO_OOM is set.
Script to repro
CREATE EXTENSION vector;
CREATETABLEtst (i int4, v vector(3));
INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 10000) i;
SET client_min_messages = DEBUG;
SET maintenance_work_mem ='128MB';
SET min_parallel_table_scan_size =1;
CREATEINDEXidxON tst USING hnsw (v vector_l2_ops);
I did testing on a set of OpenAI embeddings (900K embeddings, 1536 dimensions). The results are really impressive: for construction ef=100 I have 20 times speedup for 64 workers (including leader) compared to building in one process and 27 times speedup compared to version 5.1.0!
On a second plot the same results in log scale. Here I also added (inverse) linear build time in a dotted line which is a theoretical maximum of parallelizing with no concurrency overhead.
Testing was on c7g.metal with settings:
shared_buffers = 50000MB
maintenance_work_mem = 30000MB
max_parallel_maintenance_workers = {0-63}
wal_level=minimal
max_wal_size = 10GB
autovacuum = off
full_page_writes = off
fsync = off
create unlogged table emb (id serial, vector vector(1536), primary key (id));
alter table emb alter column vector set storage plain;
CREATE INDEX emb_hnsw ON emb USING hnsw (vector vector_ip_ops) WITH (m = 16, ef_construction = {32,64,100})
I can't wait when the branch is merged into the release. A killer feature indeed!
Reacted by Andrew Kane, Jonathan S. Katz, Copple and egor
I've been running tests on my random 10MM 1536-dim dataset. It's taking some time (I didn't automate it well), but here's roughly where I'm at (same settings as #409 (comment)):
Workers
master (min)
hnsw-fast-build (min)
Speedup
2
243
4
130
8
524
74
7.13
16
279
46
6.11
32
201
30
6.72
64
188
25
7.39
I think the win is pretty demonstrable, even if there's still room for improvement. I'm going to pivot to run the ANN Benchmarks on the 64 worker load to check for any recall regressions.
Cool, thanks for the testing @jkatz! I wonder what's the bottleneck that prevents it from scaling linearly as you add worker. Would it be possible to run perf record --call-graph=lbr -p <pid of one of the worker processes> while the test is running with >= 64 workers? Running it for a short duration like 10 s - 20 s should be enough.
@hlinnaka Actually, I can't do that on my current instance as I'm using a Graviton 3 (ARM) processor. I can set up an instance with an Intel processor in the interim.
Docker has a default shared memory limit of 64 MB (shm_size). When trying to allocate more shared memory, CREATE INDEX fails with ERROR: could not resize shared memory segment. Ideally, it would fallback to a serial build, but I'm having trouble getting this to happen.
Yeah, that's unfortunate. AFAICS there is no equivalent of MCXT_ALLOC_NO_OOM for the shared memory allocation.
The HNSW build isn't doing anything special, this is a general Postgres issue. Most parallel operations in Postgres need only a small amount of memory for coordinating the workers, but e.g. with parallel vacuum:
postgres=# create table foo (i int) with (fillfactor=10);
CREATE TABLE
postgres=# insert into foo select g from generate_series(1, 10000000) g;
INSERT 0 10000000
postgres=# create index foo_idx_1 on foo(i);
CREATE INDEX
postgres=# create index foo_idx_2 on foo(i);
CREATE INDEX
postgres=# delete from foo where i <= 1000;
DELETE 1000
postgres=# vacuum (parallel 2) foo;
ERROR: could not resize shared memory segment "/PostgreSQL.3249931004" to 67128640 bytes: No space left on device
The hc->element->hash access is very often a cache miss. That's pretty much unavoidable, I'm afraid. The HNSW algorithm is very heavy on random memory access, and when expanding the search through the graph, this line happens to be the first access of the each neighbor.
We could avoid that access here by recalculating the hash, instead of reading it from hc->element->hash. But it doesn't help: you then suffer the same CPU cache the next time you follow the pointer, right after AddToVisited.
I spent some time on this at #386. The first commit there helps a little, by reorganizing the code around AddToVisited so that CPU cache prefetching is more effective for those memory accesses.
I ran an ANN Benchmark run I did overnight. I'll likely add details over a series of comments.
First and most importantly (IMV) is recall impact. Overall, it's negligible, and any swings over 1% were positive(!). For this test, I had two machines running at the commits mentioned in the table, with the following setup:
shared_buffers: 128GB
work_mem: 64MB
maintenance_work_mem: 128GB
max_parallel_maintenance_workers: 63 (with leader, so this will be 64)
max_wal_size: 20GB
wal_compression: zstd
Here is the run below. (Note the sort is lexical, so you'll see the ef_search in odd orders; this is due to me hacking this up in Excel, I'll work to make it nicer).
Due to not wanting to break Docker on a patch release (users who have increased maintenance_work_mem will need to either increase shm_size or set max_parallel_maintenance_workers to 0 for index builds to work), I'm leaning towards making this 0.6.0 instead of 0.5.2.
A few other items that could also be included:
change vector storage to EXTERNAL - external branch
(maybe) include vectors with zero norm in indexes for cosine distance - index-zero-norm branch
drop support for Postgres 11 (EOL)
Another option is to place this behind SET hnsw.enable_parallel_build = on; (then default to on in 0.6.0), but think it's better for users to make it the default earlier and not introduce a new GUC variable.
Huge thanks @hlinnaka for reviewing and the code contributions (especially around locking and documenting the build process) and @jkatz and @pashkinelfe for benchmarking, testing, and profiling.
The current plan is to release 0.6.0 early next week.
@ankane don't you think of something like MAIN storage to use out-of-line (i.e. TOAST) storage only as a last resort? Unfortunately, it will try to compress vectors inline, but maybe this will not add much burden (I haven't checked yet).
@ankane yes, that's it. My main line of thinking is to avoid TOASTing rows with vectors if their size is between 2 and 8 Kb. The user could avoid this setting TOAST_TUPLE_THRESHOLD to 8Kb but this could not be made default for type vector. Maybe at best setting TOAST_TUPLE_THRESHOLD value could be mentioned in readme as a performance-tuning action.
Trying to get an exclusive lock on entryLock can cause the process to wait for a bit when there are a lot of shared locks. This shows up in pg_stat_activity and uneven tuple counts between processes.
So the problem was that LWLocks are not fair. If there's a constant stream of processes acquiring and releasing the lock in shared mode, one process that's waiting to acquire it in exclusive mode might never get it. By briefly acquiring another lock in exclusive mode, you force the shared-lockers to pause when there's an exclusive-locker waiting. I see.
Activity
jkatz commentedon Jan 16, 2024
@ankane Awesome!
I'm running a series of tests, but I waned to share a very early result. Here is my test info:
Dataset: 10MM 1,536-dim randomly generated normalized vectors
Instance: r7gd.16xlarge (64 vCPU, 512GB RAM)
Storage: NVMe
Build parameters:
m: 16ef_construction: 100PostgreSQL configuration of relevance:
shared_buffers: 128GBmaintenance_work_mem: 128GBmax_parallel_maintenance_workers: 63 (with leader, so this will be 64)max_wal_size: 20GBwal_compression: zstdResults:
master, it was about 16% completed. However, when lookingpg_stat_progress_create_index, hnsw-fast-bulid-branch was outpacingmasterby about 10x.ef_constructionat64!This looks really promising! There are a few more tests I plan to run:
max_parallel_maintenance_workersto understand the performance profileAnyway, this looks awesome!
jkatz commentedon Jan 16, 2024
For completeness, the second test finished in 3h7m35s (11255652.916 ms). So for this run,
hnsw-fast-build-branchshowed a 7.39x speedup!ankane commentedon Jan 17, 2024
Running into an issue with Docker if anyone has ideas.
Docker has a default shared memory limit of 64 MB (
shm_size). When trying to allocate more shared memory,CREATE INDEXfails withERROR: could not resize shared memory segment. Ideally, it would fallback to a serial build, but I'm having trouble getting this to happen.It initially fails on the
InitializeParallelDSMcall. One way around this is to create a minimal DSA, then try to allocate from that (hnsw-fast-build-dsa branch). However, it fails with the same error ondsa_allocate_extended, even whenDSA_ALLOC_NO_OOMis set.Script to repro
pashkinelfe commentedon Jan 17, 2024
I did testing on a set of OpenAI embeddings (900K embeddings, 1536 dimensions). The results are really impressive: for construction ef=100 I have 20 times speedup for 64 workers (including leader) compared to building in one process and 27 times speedup compared to version 5.1.0!

On a second plot the same results in log scale. Here I also added (inverse) linear build time in a dotted line which is a theoretical maximum of parallelizing with no concurrency overhead.
Testing was on c7g.metal with settings:
I can't wait when the branch is merged into the release. A killer feature indeed!
jkatz commentedon Jan 17, 2024
I've been running tests on my random 10MM 1536-dim dataset. It's taking some time (I didn't automate it well), but here's roughly where I'm at (same settings as #409 (comment)):
master(min)hnsw-fast-build(min)I think the win is pretty demonstrable, even if there's still room for improvement. I'm going to pivot to run the ANN Benchmarks on the 64 worker load to check for any recall regressions.
hlinnaka commentedon Jan 17, 2024
Cool, thanks for the testing @jkatz! I wonder what's the bottleneck that prevents it from scaling linearly as you add worker. Would it be possible to run
perf record --call-graph=lbr -p <pid of one of the worker processes>while the test is running with >= 64 workers? Running it for a short duration like 10 s - 20 s should be enough.jkatz commentedon Jan 17, 2024
@hlinnaka I can do that. I'll get a few: 64 and 96 workers.
jkatz commentedon Jan 18, 2024
@hlinnaka Actually, I can't do that on my current instance as I'm using a Graviton 3 (ARM) processor. I can set up an instance with an Intel processor in the interim.
From the Graviton, here's the dwarf:
And here's the fp:
jkatz commentedon Jan 18, 2024
@hlinnaka Hm, turns out I can't get lbr either from the r7i. Does this give you enough info, or do you want me to try on a different machine?
hlinnaka commentedon Jan 18, 2024
Yeah that's good, thanks @jkatz.
I don't see a smoking gun in the profile, it looks similar to what I'm seeing without parallelism. Doesn't seem to be lock contention.
hlinnaka commentedon Jan 18, 2024
Yeah, that's unfortunate. AFAICS there is no equivalent of MCXT_ALLOC_NO_OOM for the shared memory allocation.
The HNSW build isn't doing anything special, this is a general Postgres issue. Most parallel operations in Postgres need only a small amount of memory for coordinating the workers, but e.g. with parallel vacuum:
pashkinelfe commentedon Jan 18, 2024
@hlinnaka The graphs for time spent in calls for building index with ef=100 in 61 processes (including leader) on 64-core Graviton3 (c7g.metal). Gathered by interrupting and recording gdb stacks (using https://github.com/jasonrohrer/wallClockProfiler).
My attention came to AddToVisited. There should be some locks inside hash inserts.


Worker:
Leader:
Non-recompressed svg's (clickable call graph) pgvector-60-time-in-calls.zip
hlinnaka commentedon Jan 18, 2024
Cool, thanks! This profile also looks similar to what I'm seeing on a non-parallel build.
The hash table is local to the search, so it doesn't need locking.
AddToVisited shows up as a hot spot in a single-process build too. It's because of CPU cache misses coming from this line:
The
hc->element->hashaccess is very often a cache miss. That's pretty much unavoidable, I'm afraid. The HNSW algorithm is very heavy on random memory access, and when expanding the search through the graph, this line happens to be the first access of the each neighbor.We could avoid that access here by recalculating the hash, instead of reading it from
hc->element->hash. But it doesn't help: you then suffer the same CPU cache the next time you follow the pointer, right after AddToVisited.I spent some time on this at #386. The first commit there helps a little, by reorganizing the code around AddToVisited so that CPU cache prefetching is more effective for those memory accesses.
jkatz commentedon Jan 18, 2024
I ran an ANN Benchmark run I did overnight. I'll likely add details over a series of comments.
First and most importantly (IMV) is recall impact. Overall, it's negligible, and any swings over 1% were positive(!). For this test, I had two machines running at the commits mentioned in the table, with the following setup:
shared_buffers: 128GBwork_mem: 64MBmaintenance_work_mem: 128GBmax_parallel_maintenance_workers: 63 (with leader, so this will be 64)max_wal_size: 20GBwal_compression: zstdHere is the run below. (Note the sort is lexical, so you'll see the ef_search in odd orders; this is due to me hacking this up in Excel, I'll work to make it nicer).
ankane commentedon Jan 19, 2024
Due to not wanting to break Docker on a patch release (users who have increased
maintenance_work_memwill need to either increaseshm_sizeor setmax_parallel_maintenance_workersto 0 for index builds to work), I'm leaning towards making this 0.6.0 instead of 0.5.2.A few other items that could also be included:
vectorstorage toEXTERNAL-externalbranchindex-zero-normbranchAnother option is to place this behind
SET hnsw.enable_parallel_build = on;(then default toonin 0.6.0), but think it's better for users to make it the default earlier and not introduce a new GUC variable.ankane commentedon Jan 23, 2024
Hi all, this is now merged 🎉
Huge thanks @hlinnaka for reviewing and the code contributions (especially around locking and documenting the build process) and @jkatz and @pashkinelfe for benchmarking, testing, and profiling.
The current plan is to release 0.6.0 early next week.
pashkinelfe commentedon Jan 23, 2024
@ankane don't you think of something like MAIN storage to use out-of-line (i.e. TOAST) storage only as a last resort? Unfortunately, it will try to compress vectors inline, but maybe this will not add much burden (I haven't checked yet).
ankane commentedon Jan 23, 2024
Vectors don't really compress well (unless they have duplicate elements), so I think it's best to skip compression and just TOAST when needed.
(
externalstill stores inline if less thanTOAST_TUPLE_THRESHOLD)pashkinelfe commentedon Jan 23, 2024
@ankane yes, that's it. My main line of thinking is to avoid TOASTing rows with vectors if their size is between 2 and 8 Kb. The user could avoid this setting TOAST_TUPLE_THRESHOLD to 8Kb but this could not be made default for type vector. Maybe at best setting TOAST_TUPLE_THRESHOLD value could be mentioned in readme as a performance-tuning action.
ankane commentedon Jan 24, 2024
@pashkinelfe The easiest way to make sure it's stored inline is to set:
It'd be good to benchmark the difference between that and
EXTERNALbefore adding to the readme.pashkinelfe commentedon Jan 26, 2024
I propose mentioning toast_tuple_target in documentation: #437
ankane commentedon Mar 12, 2024
Just fyi: found an issue with lock contention that was impacting performance for higher numbers of parallel workers (thanks @jkatz). Fixed in 3ea2ce8.
hlinnaka commentedon Mar 12, 2024
Can you give some more details on the issue?
ankane commentedon Mar 12, 2024
Trying to get an exclusive lock on
entryLockcan cause the process to wait for a bit when there are a lot of shared locks. This shows up inpg_stat_activityand uneven tuple counts between processes.Before
After
hlinnaka commentedon Mar 12, 2024
So the problem was that LWLocks are not fair. If there's a constant stream of processes acquiring and releasing the lock in shared mode, one process that's waiting to acquire it in exclusive mode might never get it. By briefly acquiring another lock in exclusive mode, you force the shared-lockers to pause when there's an exclusive-locker waiting. I see.
ankane commentedon Mar 12, 2024
Yeah, exactly. We want
entryLockto be write-preferring.feat(pgvector): tune specifically for pgvector workloads