pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: kirito632 (@kirito632) <noreply+kirito632@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #1028: Speed up IVFFlat scans with direct kernel calls and candidate array
Date: Sat, 12 Sep 2026 13:04:22 +0000
Message-ID: <gh-pgvector-pgvector-1028@github.com> (raw)



## Motivation

Profiling an IVFFlat index scan at moderate `probes` shows that the distance
computation itself is only a small fraction of scan CPU. Most time goes to
per-tuple machinery in `GetScanItems`:

1. **fmgr dispatch per candidate row** — the opclass distance function is
   called through `FunctionCallInvoke` for every candidate, paying full
   argument marshalling (each `Vector *` re-validated, `dim` re-checked).
2. **Tuple slot + tuplesort per batch** — every candidate is stored in a
   heap tuple and run through `tuplesort`, even though only the top
   `k` (bounded by `work_mem`) can survive.

Both costs scale with the number of scanned candidates (probes x cluster
size), not with result size, so they dominate exactly when recall settings
are aggressive.

## What this PR changes

- `ivfflatbeginscan` resolves the opclass distance proc (`FUNCTION 1`) to
  one of three exported C kernels — `vector_l2_squared_distance`,
  `vector_negative_inner_product` (shared by `ip_ops` and `cosine_ops`) —
  and stores the function pointer on the scan. Kernels take
  `(int dim, const float *ax, const float *bx)`.
- `IvfflatVectorParts()` resolves both varlena header layouts inline:
  index tuples for `dim <= 30` use a 1-byte short header, and the previous
  direct `(Vector *)` cast was only valid for 4-byte headers. (This was the
  source of out-of-bounds reads on small-`dim` data — see Testing.)
- `GetScanItems` fast path accumulates `{distance, tid}` pairs into a
  `work_mem`-bounded candidate array, sorted once per batch. Ties are
  broken by TID.
- **Fallbacks are preserved**: capacity overflow, dimension mismatch, or an
  unrecognized opclass proc all revert to the original slot + tuplesort
  path. NULL order-by values keep using the original path.

## Benchmark

Frozen configuration: deterministic clustered-Gaussian synthetic data, N=100k, dim=128, 1,000 queries,
P2 matrix (3 operators x 14 lists/probes cells), R=5 repetitions per arm,
same-machine A/B (OpenTenBase / PostgreSQL 19beta3, gcc 13.3, x86_64).
Recall = mean Recall@10 per cell; QPS = 1,000 queries / freeze-robust mean wall seconds (concurrency=1); wall time = median of repetitions with
freeze outliers (>5x median) excluded.

- Recall: unchanged on every acceptance cell — worst |delta| = 0.0011
  against a 0.02 tolerance.
- Wall time: **mean 1.43x / median 1.44x faster** across the 42-cell grid;
  largest single-cell gain 2.93x (trend cells at low lists).
- pgvector regression suite: **15/15** (14 existing + 1 new).

## Testing

- New `test/sql/ivfflat_fastscan.sql` covers both varlena header forms
  (dim 8 short-header, dim 64 4-byte-header) for L2/IP/cosine, the
  `work_mem` overflow fallback, and lateral rescans. The dim<=30 short
  header case is a regression guard: the naive `(Vector *)` cast reads a
  garbage `dim` there and crashes.
- Adversarial smoke tests outside the suite additionally verified
  full-probes equality with exact scans (diff = 0) on both header forms.
- One behavioral note for reviewers: the fast path breaks distance ties by
  TID, whereas the tuplesort path's tie order is unspecified. The new test
  pins the fallback query with a secondary sort key where ties occur.

## Notes

- No user-visible defaults or GUCs change; the fast path is transparent.
- The kernels are also the natural seam for future SIMD work (the current
  build already auto-vectorizes the inner loops with AVX2).


inline patch 1: src/ivfflat.h, src/ivfscan.c, src/vector.c and 3 more (+665/-18 lines) download inline-1.patchdiff --git a/src/ivfflat.h b/src/ivfflat.h index 31071b773..672b8aa85 100644 --- a/src/ivfflat.h +++ b/src/ivfflat.h @@ -10,6 +10,7 @@ #include "nodes/execnodes.h" #include "port.h" /* for random() */ #include "storage/condition_variable.h" +#include "storage/itemptr.h" #include "utils/sampling.h" #include "utils/tuplesort.h" #include "vector.h" @@ -283,6 +284,19 @@ typedef struct IvfflatScanList double distance; } IvfflatScanList; +/* + * Task 2 O2: scan candidate for the fast path. Lightweight replacement for + * the per-tuple TupleTableSlot + tuplesort machinery: one double plus the + * heap TID, 16 bytes. + */ +typedef struct IvfflatCandData +{ + double distance; + ItemPointerData tid; +} IvfflatCandData; + +typedef IvfflatCandData * IvfflatCand; + typedef struct IvfflatScanOpaqueData { const IvfflatTypeInfo *typeInfo; @@ -306,6 +320,27 @@ typedef struct IvfflatScanOpaqueData Oid collation; Datum (*distfunc) (FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2); + /* Task 2 fast path: kernel dispatch + candidate array */ + bool fastPath; + + /* + * The kernel takes (dim, ax, bx) rather than (Vector *, Vector *) because + * index tuples store small vectors with a 1-byte short varlena header, so + * the Vector struct layout cannot be assumed for index entries. See + * IvfflatVectorParts() in src/ivfscan.c. + */ + double (*kernel) (int dim, const float *ax, const float *bx); + + /* Scan (query) vector parts, resolved once per scan in GetScanValue */ + int qdim; + const float *qx; + + IvfflatCand cands; + int candCount; + int candCapacity; + int candMax; + int emitIndex; + /* Lists */ pairingheap *listQueue; BlockNumber *listPages; diff --git a/src/ivfscan.c b/src/ivfscan.c index 27cb48fb5..6e6a99351 100644 --- a/src/ivfscan.c +++ b/src/ivfscan.c @@ -23,9 +23,171 @@ #include "varatt.h" #endif +#include "vector.h" + +/* + * Distance support functions of the vector opclasses, defined in + * src/vector.c via PG_FUNCTION_INFO_V1. Declared here for the fn_addr + * dispatch in ivfflatbeginscan (Task 2 O1). + * + * These are the FUNCTION 1 (IVFFLAT_DISTANCE_PROC) entries of the ivfflat + * opclasses in sql/vector--*.sql: + * vector_l2_ops -> vector_l2_squared_distance + * vector_ip_ops -> vector_negative_inner_product + * vector_cosine_ops -> vector_negative_inner_product (inputs normalized + * by the FUNCTION 2 norm proc) + */ +extern Datum vector_l2_squared_distance(PG_FUNCTION_ARGS); +extern Datum vector_negative_inner_product(PG_FUNCTION_ARGS); + +/* + * Task 2 O1: extract (dim, values) from a vector Datum without detoasting. + * + * Index tuples store small vectors with a 1-byte SHORT varlena header + * (see VARATT_CAN_MAKE_SHORT). Such a datum has the layout + * [1B header][int16 dim][int16 unused][float x[dim]] + * while a 4-byte-header datum has + * [4B header][int16 dim][int16 unused][float x[dim]]. + * Casting a short-header datum to Vector * reads dim out of the first + * float, which produced garbage dimensions, NaN distances and, for large + * garbage dims, out-of-bounds reads (reproduced as a segfault on the + * cosine opclass with dim 8). The fmgr path hides this because + * PG_GETARG_VECTOR_P detoasts. + * + * Returns false for header forms we do not handle inline (external or + * compressed), in which case the caller must use the fmgr path. + */ +static inline bool +IvfflatVectorParts(Datum d, int *dim, const float **x) +{ + struct varlena *vl = (struct varlena *) DatumGetPointer(d); + + if (VARATT_IS_4B_U(vl)) + { + Vector *v = (Vector *) vl; + + *dim = v->dim; + *x = v->x; + return true; + } + else if (VARATT_IS_1B(vl) && !VARATT_IS_1B_E(vl)) + { + unsigned char *p = (unsigned char *) vl; + int16 rawDim; + + /* Copy the unaligned int16 instead of dereferencing it directly. */ + memcpy(&rawDim, p + 1, sizeof(int16)); + + *dim = (int) rawDim; + *x = (const float *) (p + 5); + return true; + } + + return false; +} + #define GetScanList(ptr) pairingheap_container(IvfflatScanList, ph_node, ptr) #define GetScanListConst(ptr) pairingheap_const_container(IvfflatScanList, ph_node, ptr) +/* + * Task 2 O2: comparator for the candidate array. Distance ascending; + * exact ties are broken by TID (block, then offset) so the emitted order + * is fully deterministic across runs. + */ +static int +CompareCands(const void *a, const void *b) +{ + const IvfflatCandData *x = (const IvfflatCandData *) a; + const IvfflatCandData *y = (const IvfflatCandData *) b; + BlockNumber xb; + BlockNumber yb; + + if (x->distance < y->distance) + return -1; + if (x->distance > y->distance) + return 1; + + xb = ItemPointerGetBlockNumber(&x->tid); + yb = ItemPointerGetBlockNumber(&y->tid); + if (xb != yb) + return (xb < yb) ? -1 : 1; + + { + OffsetNumber xo = ItemPointerGetOffsetNumber(&x->tid); + OffsetNumber yo = ItemPointerGetOffsetNumber(&y->tid); + + return (xo < yo) ? -1 : (xo > yo) ? 1 : 0; + } +} + +static void +SortCands(IvfflatScanOpaque so) +{ + if (so->candCount > 1) + qsort(so->cands, so->candCount, sizeof(IvfflatCandData), CompareCands); +} + +/* + * Task 2 O2: append a candidate to the array. Returns false when the + * work_mem-derived capacity is reached and the scan must fall back to + * the original tuplesort path. + */ +static bool +AppendCand(IvfflatScanOpaque so, double distance, ItemPointer tid) +{ + if (so->candCount >= so->candCapacity) + { + int newcap; + + if (so->candCapacity >= so->candMax) + return false; + + newcap = (so->candCapacity > 0) ? so->candCapacity * 2 : Min(1024, so->candMax); + if (newcap > so->candMax) + newcap = so->candMax; + + if (so->cands == NULL) + so->cands = (IvfflatCand) palloc((Size) newcap * sizeof(IvfflatCandData)); + else + so->cands = (IvfflatCand) repalloc(so->cands, (Size) newcap * sizeof(IvfflatCandData)); + so->candCapacity = newcap; + } + + so->cands[so->candCount].distance = distance; + so->cands[so->candCount].tid = *tid; + so->candCount++; + return true; +} + +/* + * Task 2 O2 fallback: move already-collected candidates into the tuplesort + * and switch this scan to the original code path. The caller keeps + * appending through the tuplesort afterwards; performsort is deferred to + * the end of GetScanItems. + */ +static void +FallbackToSort(IvfflatScanOpaque so) +{ + TupleTableSlot *slot = so->vslot; + + tuplesort_reset(so->sortstate); + + for (int i = 0; i < so->candCount; i++) + { + ExecClearTuple(slot); + slot->tts_values[0] = Float8GetDatum(so->cands[i].distance); + slot->tts_isnull[0] = false; + slot->tts_values[1] = PointerGetDatum(&so->cands[i].tid); + slot->tts_isnull[1] = false; + ExecStoreVirtualTuple(slot); + + tuplesort_puttupleslot(so->sortstate, slot); + } + + so->candCount = 0; + so->fastPath = false; +} + /* * Compare list distances */ @@ -70,8 +232,28 @@ GetScanLists(IndexScanDesc scan, Datum value) IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno)); double distance; - /* Use procinfo from the index instead of scan key for performance */ - distance = DatumGetFloat8(so->distfunc(so->procinfo, so->collation, PointerGetDatum(&list->center), value)); + /* Use procinfo from the index instead of scan key for performance */ + if (so->fastPath) + { + /* Task 2 O1: bypass fmgr for list-center distances */ + int cdim; + const float *cx; + + /* + * List centers are embedded Vectors with a regular 4-byte + * header, but fall back to fmgr if that ever changes. + */ + if (IvfflatVectorParts(PointerGetDatum(&list->center), &cdim, &cx) && + cdim == so->qdim) + distance = so->kernel(cdim, cx, so->qx); + else + distance = DatumGetFloat8(so->distfunc(so->procinfo, so->collation, + PointerGetDatum(&list->center), value)); + } + else + { + distance = DatumGetFloat8(so->distfunc(so->procinfo, so->collation, PointerGetDatum(&list->center), value)); + } if (listCount < so->maxProbes) { @@ -127,8 +309,19 @@ GetScanItems(IndexScanDesc scan, Datum value) TupleDesc tupdesc = RelationGetDescr(scan->indexRelation); TupleTableSlot *slot = so->vslot; int batchProbes = 0; + MemoryContext oldCtx = CurrentMemoryContext; - tuplesort_reset(so->sortstate); + if (so->fastPath) + { + /* Task 2 O2: candidate array replaces the tuplesort batch */ + so->candCount = 0; + so->emitIndex = 0; + oldCtx = MemoryContextSwitchTo(so->tmpCtx); + } + else + { + tuplesort_reset(so->sortstate); + } /* Search closest probes lists */ while (so->listIndex < so->maxProbes && (++batchProbes) <= so->probes) @@ -157,20 +350,56 @@ GetScanItems(IndexScanDesc scan, Datum value) itup = (IndexTuple) PageGetItem(page, itemid); datum = index_getattr(itup, 1, tupdesc, &isnull); - /* - * Add virtual tuple - * - * Use procinfo from the index instead of scan key for - * performance - */ - ExecClearTuple(slot); - slot->tts_values[0] = so->distfunc(so->procinfo, so->collation, datum, value); - slot->tts_isnull[0] = false; - slot->tts_values[1] = PointerGetDatum(&itup->t_tid); - slot->tts_isnull[1] = false; - ExecStoreVirtualTuple(slot); - - tuplesort_puttupleslot(so->sortstate, slot); + if (so->fastPath) + { + /* + * Task 2 O1/O2: direct C kernel + candidate array, no + * fmgr dispatch and no slot machinery per tuple. + */ + int edim; + const float *ex; + + /* + * Any entry whose header form or dimension we cannot + * handle inline falls back: the candidates collected so + * far are flushed into the tuplesort and this tuple is + * appended below by the original path. + */ + if (!IvfflatVectorParts(datum, &edim, &ex) || edim != so->qdim) + FallbackToSort(so); + else + { + double distance = so->kernel(edim, ex, so->qx); + + if (!AppendCand(so, distance, &itup->t_tid)) + { + /* + * Capacity reached: flush collected candidates + * into the tuplesort and continue on the original + * path for the rest of this scan. + */ + FallbackToSort(so); + } + } + } + + if (!so->fastPath) + { + /* + * Add virtual tuple + * + * Use procinfo from the index instead of scan key for + * performance + */ + ExecClearTuple(slot); + slot->tts_values[0] = so->distfunc(so->procinfo, so->collation, datum, value); + slot->tts_isnull[0] = false; + slot->tts_values[1] = PointerGetDatum(&itup->t_tid); + slot->tts_isnull[1] = false; + ExecStoreVirtualTuple(slot); + + tuplesort_puttupleslot(so->sortstate, slot); + } } searchPage = IvfflatPageGetOpaque(page)->nextblkno; @@ -179,7 +408,11 @@ GetScanItems(IndexScanDesc scan, Datum value) } } - tuplesort_performsort(so->sortstate); + if (oldCtx != CurrentMemoryContext) + MemoryContextSwitchTo(oldCtx); + + if (!so->fastPath) + tuplesort_performsort(so->sortstate); #if defined(IVFFLAT_MEMORY) elog(INFO, "memory: %zu MB", MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024)); @@ -208,6 +441,9 @@ GetScanValue(IndexScanDesc scan) { value = PointerGetDatum(NULL); so->distfunc = ZeroDistance; + + /* Task 2: no kernel on NULL order-by value */ + so->fastPath = false; } else { @@ -227,6 +463,17 @@ GetScanValue(IndexScanDesc scan) MemoryContextSwitchTo(oldCtx); } + + /* + * Task 2: enable the fast path when a kernel was resolved and the + * scan value can be read without detoasting. The parts are resolved + * once per scan (after normalization) and reused for every entry. + */ + so->qdim = 0; + so->qx = NULL; + so->fastPath = (so->kernel != NULL) && + IvfflatVectorParts(value, &so->qdim, &so->qx) && + so->qdim == so->dimensions; } return value; @@ -289,6 +536,37 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys) so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC); so->collation = index->rd_indcollation[0]; + /* + * Task 2 O1: resolve the C-level distance kernel for this index by + * comparing fn_addr. Both the support function and the kernels come + * from this extension's shared library, so the addresses are + * comparable within a single loaded .so. + * + * The mapping follows IVFFLAT_DISTANCE_PROC (FUNCTION 1) of each + * opclass - see the extern declarations at the top of this file. Note + * that ip_ops and cosine_ops share vector_negative_inner_product: for + * cosine the norm proc normalizes the entries and the scan value, so + * -dot orders the same as cosine distance and one kernel serves both. + * + * Anything unrecognised leaves kernel = NULL, which keeps the scan on + * the original fmgr path. + */ + so->kernel = NULL; + if (so->procinfo->fn_addr == vector_l2_squared_distance) + so->kernel = IvfflatFastL2SquaredDistance; + else if (so->procinfo->fn_addr == vector_negative_inner_product) + so->kernel = IvfflatFastNegInnerProduct; + + /* Enabled per scan in GetScanValue once the order-by value is known */ + so->fastPath = false; + + /* Task 2 O2: candidate array state, bounded by work_mem */ + so->cands = NULL; + so->candCount = 0; + so->candCapacity = 0; + so->emitIndex = 0; + so->candMax = (int) Min((double) work_mem * 1024 / sizeof(IvfflatCandData), (double) INT_MAX); + so->tmpCtx = AllocSetContextCreate(CurrentMemoryContext, "Ivfflat scan temporary context", ALLOCSET_DEFAULT_SIZES); @@ -393,10 +671,40 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir) value = GetScanValue(scan); IvfflatBench("GetScanLists", GetScanLists(scan, value)); IvfflatBench("GetScanItems", GetScanItems(scan, value)); + if (so->fastPath) + SortCands(so); so->first = false; so->value = value; } + if (so->fastPath) + { + /* + * Task 2 O2: emit directly from the sorted candidate array. + */ + while (true) + { + if (so->emitIndex < so->candCount) + { + scan->xs_heaptid = so->cands[so->emitIndex].tid; + scan->xs_recheck = false; + scan->xs_recheckorderby = false; + so->emitIndex++; + return true; + } + + if (so->listIndex == so->maxProbes) + return false; + + IvfflatBench("GetScanItems", GetScanItems(scan, so->value)); + + if (so->fastPath) + SortCands(so); + else + break; /* fell back to the tuplesort mid-batch */ + } + } + while (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL)) { if (so->listIndex == so->maxProbes) diff --git a/src/vector.c b/src/vector.c index e1100ecd8..7c2e0de1d 100644 --- a/src/vector.c +++ b/src/vector.c @@ -646,6 +646,37 @@ vector_negative_inner_product(PG_FUNCTION_ARGS) PG_RETURN_FLOAT8((double) -VectorInnerProduct(a->dim, a->x, b->x)); } +/* + * Task 2 O1: C-level kernels exported for the Ivfflat scan fast path. + * + * These bypass fmgr (FunctionCall2Coll), argument Datum packaging, NULL + * checks and per-tuple detoasting for the hot scan loop. They take + * (dim, ax, bx) rather than (Vector *, Vector *) because index tuples store + * small vectors with a 1-byte short varlena header - the caller resolves + * the parts with IvfflatVectorParts() in src/ivfscan.c. + * + * Result semantics (must match the opclass distance proc exactly): + * - ivfflat l2_ops: FUNCTION 1 is vector_l2_squared_distance, so the + * sort key is the SQUARED L2 distance. sqrt() is monotonic, so + * skipping it preserves the ordering and saves one sqrt per tuple. + * - ivfflat ip_ops: FUNCTION 1 is vector_negative_inner_product. + * - ivfflat cosine_ops: FUNCTION 1 is also vector_negative_inner_product; + * the norm proc normalizes both the indexed entries and the scan value, + * so -dot orders identically to cosine distance 1 - dot. One kernel + * therefore serves both opclasses bit-for-bit identically to fmgr. + */ +FUNCTION_PREFIX double +IvfflatFastL2SquaredDistance(int dim, const float *ax, const float *bx) +{ + return (double) VectorL2SquaredDistance(dim, (float *) ax, (float *) bx); +} + +FUNCTION_PREFIX double +IvfflatFastNegInnerProduct(int dim, const float *ax, const float *bx) +{ + return (double) -VectorInnerProduct(dim, (float *) ax, (float *) bx); +} + VECTOR_TARGET_CLONES static double VectorCosineSimilarity(int dim, float *ax, float *bx) { diff --git a/src/vector.h b/src/vector.h index 7dbca7502..5fd3c0693 100644 --- a/src/vector.h +++ b/src/vector.h @@ -27,6 +27,24 @@ Vector *InitVector(int dim); void PrintVector(char *msg, Vector * vector); int vector_cmp_internal(Vector * a, Vector * b); +/* + * Task 2 O1: C-level distance kernels exported for the Ivfflat scan fast + * path (src/ivfscan.c). + * + * They take (dim, ax, bx) instead of (Vector *, Vector *) because index + * tuples store small vectors with a 1-byte short varlena header, so the + * 4-byte-header Vector layout cannot be assumed for index entries. The + * caller resolves the parts with IvfflatVectorParts() and guarantees equal + * dimensions (enforced by the index typmod at insert time; the scan falls + * back to the fmgr path if dimensions ever disagree). + * + * IvfflatFastL2SquaredDistance returns the SQUARED L2 distance: the opclass + * distance proc is vector_l2_squared_distance and sqrt() is monotonic, so + * the ordering is identical while one sqrt per tuple is saved. + */ +extern double IvfflatFastL2SquaredDistance(int dim, const float *ax, const float *bx); +extern double IvfflatFastNegInnerProduct(int dim, const float *ax, const float *bx); + /* TODO Move to better place */ #if PG_VERSION_NUM >= 160000 #define FUNCTION_PREFIX diff --git a/test/expected/ivfflat_fastscan.out b/test/expected/ivfflat_fastscan.out new file mode 100644 index 000000000..8f0fa4814 --- /dev/null +++ b/test/expected/ivfflat_fastscan.out @@ -0,0 +1,150 @@ +SET enable_seqscan = off; +-- Fast-path correctness for the direct-call IVFFlat scan. +-- +-- Index tuples for vectors with 1 + 4 + 4*dim <= 127 (dim <= 30) use a +-- 1-byte short varlena header; larger dimensions use the standard 4-byte +-- header. Both layouts must produce the same ordering as the original +-- fmgr path. The generators below use primes larger than the row count, +-- so every vector is distinct. +-- L2, short header (dim = 8) +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 37 + d * 11) % 211)::numeric / 8), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); +SET ivfflat.probes = 5; +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8]' LIMIT 10; + id | round +-----+----------- + 23 | 10.145812 + 177 | 10.145812 + 80 | 10.158125 + 120 | 10.158125 + 63 | 10.182706 + 137 | 10.182706 + 6 | 10.219467 + 194 | 10.219467 + 40 | 10.268276 + 160 | 10.268276 +(10 rows) + +RESET ivfflat.probes; +DROP TABLE t; +-- inner product, short header (dim = 8) +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 41 + d * 7) % 211)::numeric / 7), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; +CREATE INDEX ON t USING ivfflat (val vector_ip_ops) WITH (lists = 5); +SET ivfflat.probes = 5; +SELECT id, ROUND((val <#> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <#> '[3,7,1,9,2,11,5,8]' LIMIT 10; + id | round +-----+-------------- + 112 | -1243.000000 + 148 | -1236.421997 + 184 | -1229.843994 + 9 | -1223.265991 + 45 | -1216.734009 + 81 | -1210.156006 + 117 | -1203.578003 + 153 | -1197.000000 + 189 | -1190.421997 + 14 | -1183.843994 +(10 rows) + +RESET ivfflat.probes; +DROP TABLE t; +-- cosine, short header (dim = 8) +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 43 + d * 13) % 211)::numeric / 6), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; +CREATE INDEX ON t USING ivfflat (val vector_cosine_ops) WITH (lists = 5); +SET ivfflat.probes = 5; +SELECT id, ROUND((val <=> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <=> '[3,7,1,9,2,11,5,8]' LIMIT 10; + id | round +-----+---------- + 159 | 0.113481 + 2 | 0.113481 + 105 | 0.113484 + 56 | 0.113485 + 51 | 0.113488 + 110 | 0.113489 + 164 | 0.113497 + 154 | 0.113505 + 7 | 0.113506 + 61 | 0.113517 +(10 rows) + +-- lateral rescan keeps the fast path +SELECT t.id, l.id FROM t CROSS JOIN LATERAL (SELECT id FROM t t2 WHERE t2.id != t.id ORDER BY t2.val <=> t.val LIMIT 1) l ORDER BY t.id LIMIT 5; + id | id +----+----- + 1 | 55 + 2 | 159 + 3 | 57 + 4 | 58 + 5 | 59 +(5 rows) + +RESET ivfflat.probes; +DROP TABLE t; +-- candidate-array overflow falls back to the tuplesort path +-- (work_mem = 64kB caps the candidate array at 4096 entries) +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 37 + d * 11) % 9973)::numeric / 8), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 5000) g, generate_series(0, 7) d +GROUP BY g; +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); +SET ivfflat.probes = 5; +SET work_mem = '64kB'; +-- exact distance ties exist in this data set; the fast path breaks ties by +-- TID, but the tuplesort fallback does not guarantee a tie order, so order +-- by id as a secondary key to keep the snapshot deterministic +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8]', id LIMIT 10; + id | round +------+----------- + 1887 | 10.145812 + 2426 | 10.182706 + 4852 | 10.182706 + 1348 | 10.219467 + 2965 | 10.328964 + 4313 | 10.328964 + 809 | 10.401322 + 3774 | 10.580052 + 270 | 10.685855 + 3235 | 10.928746 +(10 rows) + +RESET work_mem; +RESET ivfflat.probes; +DROP TABLE t; +-- 4-byte varlena header (dim = 64) +CREATE TABLE t (id serial, val vector(64)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 31 + d * 17) % 311)::numeric / 9), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 300) g, generate_series(0, 63) d +GROUP BY g; +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); +SET ivfflat.probes = 5; +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9]' LIMIT 10; + id | round +-----+------------ + 132 | 109.696786 + 161 | 110.240420 + 122 | 110.332890 + 151 | 110.838997 + 112 | 110.972675 + 211 | 111.018289 + 182 | 111.240818 + 91 | 111.365521 + 141 | 111.441452 + 201 | 111.611754 +(10 rows) + +RESET ivfflat.probes; +DROP TABLE t; diff --git a/test/sql/ivfflat_fastscan.sql b/test/sql/ivfflat_fastscan.sql new file mode 100644 index 000000000..e03d4a9f9 --- /dev/null +++ b/test/sql/ivfflat_fastscan.sql @@ -0,0 +1,105 @@ +SET enable_seqscan = off; + +-- Fast-path correctness for the direct-call IVFFlat scan. +-- +-- Index tuples for vectors with 1 + 4 + 4*dim <= 127 (dim <= 30) use a +-- 1-byte short varlena header; larger dimensions use the standard 4-byte +-- header. Both layouts must produce the same ordering as the original +-- fmgr path. The generators below use primes larger than the row count, +-- so every vector is distinct. + +-- L2, short header (dim = 8) + +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 37 + d * 11) % 211)::numeric / 8), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; + +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); + +SET ivfflat.probes = 5; + +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8]' LIMIT 10; + +RESET ivfflat.probes; +DROP TABLE t; + +-- inner product, short header (dim = 8) + +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 41 + d * 7) % 211)::numeric / 7), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; + +CREATE INDEX ON t USING ivfflat (val vector_ip_ops) WITH (lists = 5); + +SET ivfflat.probes = 5; + +SELECT id, ROUND((val <#> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <#> '[3,7,1,9,2,11,5,8]' LIMIT 10; + +RESET ivfflat.probes; +DROP TABLE t; + +-- cosine, short header (dim = 8) + +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 43 + d * 13) % 211)::numeric / 6), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 200) g, generate_series(0, 7) d +GROUP BY g; + +CREATE INDEX ON t USING ivfflat (val vector_cosine_ops) WITH (lists = 5); + +SET ivfflat.probes = 5; + +SELECT id, ROUND((val <=> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <=> '[3,7,1,9,2,11,5,8]' LIMIT 10; + +-- lateral rescan keeps the fast path + +SELECT t.id, l.id FROM t CROSS JOIN LATERAL (SELECT id FROM t t2 WHERE t2.id != t.id ORDER BY t2.val <=> t.val LIMIT 1) l ORDER BY t.id LIMIT 5; + +RESET ivfflat.probes; +DROP TABLE t; + +-- candidate-array overflow falls back to the tuplesort path +-- (work_mem = 64kB caps the candidate array at 4096 entries) + +CREATE TABLE t (id serial, val vector(8)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 37 + d * 11) % 9973)::numeric / 8), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 5000) g, generate_series(0, 7) d +GROUP BY g; + +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); + +SET ivfflat.probes = 5; +SET work_mem = '64kB'; + +-- exact distance ties exist in this data set; the fast path breaks ties by +-- TID, but the tuplesort fallback does not guarantee a tie order, so order +-- by id as a secondary key to keep the snapshot deterministic + +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8]', id LIMIT 10; + +RESET work_mem; +RESET ivfflat.probes; +DROP TABLE t; + +-- 4-byte varlena header (dim = 64) + +CREATE TABLE t (id serial, val vector(64)); +INSERT INTO t (val) +SELECT ('[' || string_agg(ROUND((((g * 31 + d * 17) % 311)::numeric / 9), 3)::text, ',' ORDER BY d) || ']')::vector +FROM generate_series(1, 300) g, generate_series(0, 63) d +GROUP BY g; + +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 5); + +SET ivfflat.probes = 5; + +SELECT id, ROUND((val <-> '[3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9]')::numeric, 6) FROM t ORDER BY val <-> '[3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9,3,7,1,9,2,11,5,8,4,6,10,2,12,1,15,9]' LIMIT 10; + +RESET ivfflat.probes; +DROP TABLE t;

view thread (3+ messages)  latest in thread

Message-ID: <gh-pgvector-pgvector-1028@github.com>
Permalink:  ../gh-pgvector-pgvector-1028@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