pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] PR #946: add sample support. Usage
6+ messages / 3 participants
[nested] [flat]

* [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-11 07:22  "digoal (@digoal)" <noreply+digoal@github.com>
  0 siblings, 0 replies; 6+ messages in thread

From: digoal (@digoal) @ 2026-01-11 07:22 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

  Users can now create IVFFlat indexes with a fixed number of samples:

   1 CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops)
   2 WITH (lists = 100, samples = 20000);

  This allows maintaining 20,000 samples for k-means clustering regardless of the number of lists, ensuring consistent cluster center quality and recall performance.

  The implementation has been tested and verified to work correctly, with all existing regression tests passing.

inline patch 1: README.md, src/ivfbuild.c, src/ivfflat.c and 3 more (+211/-6 lines) download inline-1.patchdiff --git a/README.md b/README.md index 5f24eb92f..f4aafb789 100644 --- a/README.md +++ b/README.md @@ -331,11 +331,12 @@ The phases for HNSW are: An IVFFlat index divides vectors into lists, and then searches a subset of those lists that are closest to the query vector. It has faster build times and uses less memory than HNSW, but has lower query performance (in terms of speed-recall tradeoff). -Three keys to achieving good recall are: +Four keys to achieving good recall are: 1. Create the index *after* the table has some data 2. Choose an appropriate number of lists - a good place to start is `rows / 1000` for up to 1M rows and `sqrt(rows)` for over 1M rows 3. When querying, specify an appropriate number of [probes](#query-options) (higher is better for recall, lower is better for speed) - a good place to start is `sqrt(lists)` +4. Control the number of samples used for k-means clustering during index creation with the `samples` parameter - defaults to `lists * 50` with a minimum of 10,000 Add an index for each distance function you want to use. @@ -345,6 +346,12 @@ L2 distance CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100); ``` +You can also specify the number of samples to use for k-means clustering: + +```sql +CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100, samples = 20000); +``` + Note: Use `halfvec_l2_ops` for `halfvec` (and similar with the other distance functions) Inner product diff --git a/src/ivfbuild.c b/src/ivfbuild.c index d3f3c2415..2e4f3061b 100644 --- a/src/ivfbuild.c +++ b/src/ivfbuild.c @@ -417,14 +417,26 @@ static void ComputeCenters(IvfflatBuildState * buildstate) { int numSamples; + int userSpecifiedSamples; pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS); - /* Target 50 samples per list, with at least 10000 samples */ - /* The number of samples has a large effect on index build time */ - numSamples = buildstate->lists * 50; - if (numSamples < 10000) - numSamples = 10000; + /* Check if user specified a custom number of samples */ + userSpecifiedSamples = IvfflatGetSamples(buildstate->index); + + if (userSpecifiedSamples > 0) + { + /* Use user-specified number of samples */ + numSamples = userSpecifiedSamples; + } + else + { + /* Default behavior: Target 50 samples per list, with at least 10000 samples */ + /* The number of samples has a large effect on index build time */ + numSamples = buildstate->lists * 50; + if (numSamples < 10000) + numSamples = 10000; + } /* Skip samples for unlogged table */ if (buildstate->heap == NULL) diff --git a/src/ivfflat.c b/src/ivfflat.c index 49c14783f..641a87670 100644 --- a/src/ivfflat.c +++ b/src/ivfflat.c @@ -41,6 +41,8 @@ IvfflatInit(void) ivfflat_relopt_kind = add_reloption_kind(); add_int_reloption(ivfflat_relopt_kind, "lists", "Number of inverted lists", IVFFLAT_DEFAULT_LISTS, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, AccessExclusiveLock); + add_int_reloption(ivfflat_relopt_kind, "samples", "Number of samples for k-means clustering", + 0, 0, INT_MAX, AccessExclusiveLock); DefineCustomIntVariable("ivfflat.probes", "Sets the number of probes", "Valid range is 1..lists.", &ivfflat_probes, @@ -158,6 +160,7 @@ ivfflatoptions(Datum reloptions, bool validate) { static const relopt_parse_elt tab[] = { {"lists", RELOPT_TYPE_INT, offsetof(IvfflatOptions, lists)}, + {"samples", RELOPT_TYPE_INT, offsetof(IvfflatOptions, samples)}, }; return (bytea *) build_reloptions(reloptions, validate, @@ -166,6 +169,22 @@ ivfflatoptions(Datum reloptions, bool validate) tab, lengthof(tab)); } +/* + * Get the number of samples from index options + */ +int +IvfflatGetSamples(Relation index) +{ + IvfflatOptions *opts; + + opts = (IvfflatOptions *) index->rd_options; + if (opts && opts->samples != 0) + return opts->samples; + + /* Default behavior: use 50 samples per list, with minimum of 10000 */ + return 0; /* 0 means use default calculation */ +} + /* * Validate catalog entries for the specified operator class */ diff --git a/src/ivfflat.h b/src/ivfflat.h index 0d9601e03..a6eaeb4af 100644 --- a/src/ivfflat.h +++ b/src/ivfflat.h @@ -121,6 +121,7 @@ typedef struct IvfflatOptions { int32 vl_len_; /* varlena header (do not touch directly!) */ int lists; /* number of lists */ + int samples; /* number of samples for k-means */ } IvfflatOptions; typedef struct IvfflatSpool @@ -320,6 +321,7 @@ bool IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value); int IvfflatGetLists(Relation index); void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions); void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum); +int IvfflatGetSamples(Relation index); void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state); void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum); Buffer IvfflatNewBuffer(Relation index, ForkNumber forkNum); diff --git a/test/expected/ivfflat_samples.out b/test/expected/ivfflat_samples.out new file mode 100644 index 000000000..a4bf565fb --- /dev/null +++ b/test/expected/ivfflat_samples.out @@ -0,0 +1,92 @@ +-- Test the samples parameter for IVFFlat indexes +-- This tests the new functionality that allows specifying the number of samples for k-means clustering +-- Test setup +CREATE TABLE ivfflat_samples_test ( + id int4, + vec vector(3) +); +INSERT INTO ivfflat_samples_test VALUES + (1, '[1,0,0]'), + (2, '[0,1,0]'), + (3, '[0,0,1]'), + (4, '[1,1,0]'), + (5, '[1,0,1]'), + (6, '[0,1,1]'), + (7, '[1,1,1]'), + (8, '[0.5,0.5,0.5]'); +-- Test creating an IVFFlat index with the samples parameter +CREATE INDEX idx_ivfflat_samples ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 2, samples = 1000); +-- Test creating an IVFFlat index without the samples parameter (should use default) +CREATE INDEX idx_ivfflat_default ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 2); +-- Verify that both indexes were created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' ORDER BY indexname; + indexname +--------------------- + idx_ivfflat_default + idx_ivfflat_samples +(2 rows) + +-- Test that queries work with both indexes +SELECT id FROM ivfflat_samples_test +ORDER BY vec <-> '[0.1,0.1,0.1]' +LIMIT 1; + id +---- + 8 +(1 row) + +-- Test with different distance functions +CREATE INDEX idx_ivfflat_samples_ip ON ivfflat_samples_test +USING ivfflat (vec vector_ip_ops) +WITH (lists = 2, samples = 500); +CREATE INDEX idx_ivfflat_samples_cosine ON ivfflat_samples_test +USING ivfflat (vec vector_cosine_ops) +WITH (lists = 2, samples = 800); +-- Verify these indexes were also created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' AND indexname LIKE 'idx_ivfflat_samples%' ORDER BY indexname; + indexname +---------------------------- + idx_ivfflat_samples + idx_ivfflat_samples_cosine + idx_ivfflat_samples_ip +(3 rows) + +-- Test queries with different distance functions +SELECT id FROM ivfflat_samples_test +ORDER BY vec <#> '[0.1,0.1,0.1]' +LIMIT 1; + id +---- + 7 +(1 row) + +SELECT id FROM ivfflat_samples_test +ORDER BY vec <=> '[0.1,0.1,0.1]' +LIMIT 1; + id +---- + 7 +(1 row) + +-- Test with larger sample sizes +CREATE INDEX idx_ivfflat_samples_large ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 3, samples = 5000); +-- Verify the large samples index was created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' AND indexname = 'idx_ivfflat_samples_large'; + indexname +--------------------------- + idx_ivfflat_samples_large +(1 row) + +-- Clean up +DROP INDEX idx_ivfflat_samples; +DROP INDEX idx_ivfflat_default; +DROP INDEX idx_ivfflat_samples_ip; +DROP INDEX idx_ivfflat_samples_cosine; +DROP INDEX idx_ivfflat_samples_large; +DROP TABLE ivfflat_samples_test; diff --git a/test/sql/ivfflat_samples.sql b/test/sql/ivfflat_samples.sql new file mode 100644 index 000000000..79adb9646 --- /dev/null +++ b/test/sql/ivfflat_samples.sql @@ -0,0 +1,73 @@ +-- Test the samples parameter for IVFFlat indexes +-- This tests the new functionality that allows specifying the number of samples for k-means clustering + +-- Test setup +CREATE TABLE ivfflat_samples_test ( + id int4, + vec vector(3) +); + +INSERT INTO ivfflat_samples_test VALUES + (1, '[1,0,0]'), + (2, '[0,1,0]'), + (3, '[0,0,1]'), + (4, '[1,1,0]'), + (5, '[1,0,1]'), + (6, '[0,1,1]'), + (7, '[1,1,1]'), + (8, '[0.5,0.5,0.5]'); + +-- Test creating an IVFFlat index with the samples parameter +CREATE INDEX idx_ivfflat_samples ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 2, samples = 1000); + +-- Test creating an IVFFlat index without the samples parameter (should use default) +CREATE INDEX idx_ivfflat_default ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 2); + +-- Verify that both indexes were created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' ORDER BY indexname; + +-- Test that queries work with both indexes +SELECT id FROM ivfflat_samples_test +ORDER BY vec <-> '[0.1,0.1,0.1]' +LIMIT 1; + +-- Test with different distance functions +CREATE INDEX idx_ivfflat_samples_ip ON ivfflat_samples_test +USING ivfflat (vec vector_ip_ops) +WITH (lists = 2, samples = 500); + +CREATE INDEX idx_ivfflat_samples_cosine ON ivfflat_samples_test +USING ivfflat (vec vector_cosine_ops) +WITH (lists = 2, samples = 800); + +-- Verify these indexes were also created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' AND indexname LIKE 'idx_ivfflat_samples%' ORDER BY indexname; + +-- Test queries with different distance functions +SELECT id FROM ivfflat_samples_test +ORDER BY vec <#> '[0.1,0.1,0.1]' +LIMIT 1; + +SELECT id FROM ivfflat_samples_test +ORDER BY vec <=> '[0.1,0.1,0.1]' +LIMIT 1; + +-- Test with larger sample sizes +CREATE INDEX idx_ivfflat_samples_large ON ivfflat_samples_test +USING ivfflat (vec vector_l2_ops) +WITH (lists = 3, samples = 5000); + +-- Verify the large samples index was created +SELECT indexname FROM pg_indexes WHERE tablename = 'ivfflat_samples_test' AND indexname = 'idx_ivfflat_samples_large'; + +-- Clean up +DROP INDEX idx_ivfflat_samples; +DROP INDEX idx_ivfflat_default; +DROP INDEX idx_ivfflat_samples_ip; +DROP INDEX idx_ivfflat_samples_cosine; +DROP INDEX idx_ivfflat_samples_large; +DROP TABLE ivfflat_samples_test; \ No newline at end of file
^ permalink raw [nested|flat] 6+ messages in thread

* Re: [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-12 17:09  "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2026-01-12 17:09 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @digoal, thanks for the PR. However, I'm not sure it's common enough to add. What's the motivation for making it configurable? Are you seeing significantly higher recall with more samples?

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

* Re: [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-13 01:44  "digoal (@digoal)" <noreply+digoal@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: digoal (@digoal) @ 2026-01-13 01:44 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Thanks for the feedback. I understand the concern about commonality. The motivation comes from scenarios with large datasets: when lists is too small, the centroid calculation becomes less precise, leading to poor partitioning.

You can easily reproduce this with the following test:

Generate 1,000 random base vectors.

For each base vector, create 999 variants using Gaussian perturbation (total 1M vectors).

Build an IVFFlat index and compare lists=100 vs. lists=1000.

In my tests, at probe=1, the recall with lists=1000 is significantly higher than with lists=100. This flexibility allows users to optimize the Voronoi cells for specific data distributions.

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

* Re: [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-13 17:09  "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2026-01-13 17:09 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Thanks. It seems like the situation above can be solved by increasing the number of lists rather than the number of samples.

At this point, I don't think there's a strong enough case to make this configurable.

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

* Re: [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-13 17:09  "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2026-01-13 17:09 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

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

* Re: [pgvector/pgvector] PR #946: add sample support. Usage
@ 2026-01-13 17:17  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: jkatz (@jkatz) @ 2026-01-13 17:17 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Just for completeness, I had tested sampling several years ago to try to improve the performance/recall ratio, particularly on larger datasets, but I wasn't able to get much of a difference.

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


end of thread, other threads:[~2026-01-13 17:17 UTC | newest]

Thread overview: 6+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-01-11 07:22 [pgvector/pgvector] PR #946: add sample support. Usage "digoal (@digoal)" <noreply+digoal@github.com>
2026-01-12 17:09 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-01-13 01:44 ` "digoal (@digoal)" <noreply+digoal@github.com>
2026-01-13 17:09 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-01-13 17:09 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-01-13 17:17 ` "jkatz (@jkatz)" <noreply+jkatz@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