diff --git a/CHANGELOG.md b/CHANGELOG.md index 67de8321..0b93e3b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ - Added asynchronous I/O for indexes - Added vacuuming progress for indexes - Added `vector_dims` function for `sparsevec` +- Improved performance of IVFFlat index scans - Improved performance of HNSW inserts with `sparsevec` - Improved `amvalidate` for indexes - Improved property testing for indexes diff --git a/src/ivfflat.h b/src/ivfflat.h index 46d3911f..00891a55 100644 --- a/src/ivfflat.h +++ b/src/ivfflat.h @@ -92,9 +92,11 @@ typedef Pointer Item; #if PG_VERSION_NUM >= 190000 #define palloc_array_checked(type, count) palloc_array(type, count) #define palloc0_array_checked(type, count) palloc0_array(type, count) +#define repalloc_array_checked(pointer, type, count) repalloc_array(pointer, type, count) #else #define palloc_array_checked(type, count) ((type *) palloc(mul_size(sizeof(type), count))) #define palloc0_array_checked(type, count) ((type *) palloc0(mul_size(sizeof(type), count))) +#define repalloc_array_checked(pointer, type, count) ((type *) repalloc(pointer, mul_size(sizeof(type), count))) #endif /* Variables */ @@ -283,6 +285,19 @@ typedef struct IvfflatScanList double distance; } IvfflatScanList; +typedef struct IvfflatBinaryNode +{ + ItemPointerData heaptid; + double distance; +} IvfflatBinaryNode; + +typedef struct IvfflatBinaryHeap +{ + IvfflatBinaryNode *nodes; + int length; + int capacity; +} IvfflatBinaryHeap; + typedef struct IvfflatScanOpaqueData { const IvfflatTypeInfo *typeInfo; @@ -313,6 +328,9 @@ typedef struct IvfflatScanOpaqueData pairingheap *listsHeap; /* Items */ + bool useHeap; + int maxHeapItems; + IvfflatBinaryHeap itemsHeap; Tuplesortstate *sortstate; TupleDesc tupdesc; TupleTableSlot *vslot; diff --git a/src/ivfscan.c b/src/ivfscan.c index e7ab8954..9b6e3c00 100644 --- a/src/ivfscan.c +++ b/src/ivfscan.c @@ -1,3 +1,7 @@ +/* + * Binary heap based on Postgres implementation + */ + #include "postgres.h" #include @@ -27,6 +31,8 @@ #include "varatt.h" #endif +#define IVFFLAT_SORT_MEMORY (64 * 1024) + #define GetScanList(ptr) pairingheap_container(IvfflatScanList, ph_node, ptr) #define GetScanListConst(ptr) pairingheap_const_container(IvfflatScanList, ph_node, ptr) @@ -60,6 +66,107 @@ CompareListsSort(const void *a, const void *b) return 0; } +/* + * Initialize binary heap + */ +static void +BinaryHeapInit(IvfflatBinaryHeap * heap, int capacity) +{ + heap->nodes = palloc_array_checked(IvfflatBinaryNode, capacity); + heap->length = 0; + heap->capacity = capacity; +} + +/* + * Add unordered - O(1) + */ +static void +BinaryHeapAddUnordered(IvfflatBinaryHeap * heap, IvfflatBinaryNode node) +{ + /* Safety check */ + if (heap->length >= heap->capacity) + elog(ERROR, "heap full"); + + heap->nodes[heap->length++] = node; +} + +/* + * Grow binary heap + */ +static void +BinaryHeapGrow(IvfflatBinaryHeap * heap, int newCapacity) +{ + if (newCapacity > heap->capacity) + { + heap->nodes = repalloc_array_checked(heap->nodes, IvfflatBinaryNode, newCapacity); + heap->capacity = newCapacity; + } +} + +/* + * Sift down - O(log n) + */ +static void +BinaryHeapSiftDown(IvfflatBinaryHeap * heap, int offset) +{ + IvfflatBinaryNode node = heap->nodes[offset]; + + for (;;) + { + int left = 2 * offset + 1; + int right = 2 * offset + 2; + int swap = left; + + if (right < heap->length && heap->nodes[left].distance >= heap->nodes[right].distance) + swap = right; + + if (left >= heap->length || node.distance < heap->nodes[swap].distance) + break; + + heap->nodes[offset] = heap->nodes[swap]; + offset = swap; + } + + heap->nodes[offset] = node; +} + +/* + * Build binary heap - O(n) + */ +static void +BinaryHeapBuild(IvfflatBinaryHeap * heap) +{ + for (int i = heap->length / 2 - 1; i >= 0; i--) + BinaryHeapSiftDown(heap, i); +} + +/* + * Remove first from binary heap - O(log n) + */ +static IvfflatBinaryNode +BinaryHeapRemoveFirst(IvfflatBinaryHeap * heap) +{ + IvfflatBinaryNode node; + + /* Safety check */ + if (heap->length < 1) + elog(ERROR, "heap empty"); + + node = heap->nodes[0]; + heap->nodes[0] = heap->nodes[--heap->length]; + BinaryHeapSiftDown(heap, 0); + return node; +} + +/* + * Reset binary heap + */ +static void +BinaryHeapReset(IvfflatBinaryHeap * heap) +{ + heap->length = 0; +} + /* * Get lists and sort by distance */ @@ -141,10 +248,10 @@ GetScanLists(IndexScanDesc scan, Datum value) } /* - * Add scan item + * Add sort item */ static inline void -AddScanItem(IvfflatScanOpaque so, double distance, ItemPointer heaptid) +AddSortItem(IvfflatScanOpaque so, double distance, ItemPointer heaptid) { TupleTableSlot *slot = so->vslot; @@ -159,6 +266,46 @@ AddScanItem(IvfflatScanOpaque so, double distance, ItemPointer heaptid) tuplesort_puttupleslot(so->sortstate, slot); } +/* + * Add scan item + */ +static void +AddScanItem(IvfflatScanOpaque so, double distance, ItemPointer heaptid) +{ + IvfflatBinaryHeap *heap = &so->itemsHeap; + + if (so->useHeap) + { + if (heap->length < heap->capacity) + { + IvfflatBinaryNode node = {*heaptid, distance}; + + BinaryHeapAddUnordered(heap, node); + } + else if (heap->capacity < so->maxHeapItems) + { + IvfflatBinaryNode node = {*heaptid, distance}; + + /* Avoid overflow */ + int newCapacity = heap->capacity < so->maxHeapItems / 2 ? heap->capacity * 2 : so->maxHeapItems; + + BinaryHeapGrow(heap, newCapacity); + BinaryHeapAddUnordered(heap, node); + } + else + { + /* Move items to sort */ + for (int i = 0; i < heap->length; i++) + AddSortItem(so, heap->nodes[i].distance, &heap->nodes[i].heaptid); + + AddSortItem(so, distance, heaptid); + so->useHeap = false; + } + } + else + AddSortItem(so, distance, heaptid); +} + /* * Get page items */ @@ -197,6 +344,8 @@ GetScanItems(IndexScanDesc scan, Datum value) IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque; int batchProbes = 0; + so->useHeap = true; + BinaryHeapReset(&so->itemsHeap); tuplesort_reset(so->sortstate); /* Search closest probes lists */ @@ -257,7 +406,10 @@ GetScanItems(IndexScanDesc scan, Datum value) } } - tuplesort_performsort(so->sortstate); + if (so->useHeap) + BinaryHeapBuild(&so->itemsHeap); + else + tuplesort_performsort(so->sortstate); #if defined(IVFFLAT_MEMORY) elog(INFO, "memory: %zu MB", MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024)); @@ -333,13 +485,32 @@ InitScanSortState(IvfflatScanOpaque so) #endif /* Prep sort */ - so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, TUPLESORT_NONE); + so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, IVFFLAT_SORT_MEMORY / 1024, NULL, TUPLESORT_NONE); /* Need separate slots for puttuple and gettuple */ so->vslot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual); so->mslot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple); } +/* + * Compute max heap items + */ +static int +ComputeMaxHeapItems(Size memory) +{ + Size maxItems; + + if (memory < IVFFLAT_SORT_MEMORY) + return 1; + + maxItems = Min(memory - IVFFLAT_SORT_MEMORY, MaxAllocSize) / sizeof(IvfflatBinaryNode); + + if (maxItems < 1) + return 1; + + return Min(maxItems, INT_MAX); +} + #ifdef IVFFLAT_USE_READ_STREAM /* * Get next block number for read stream @@ -368,13 +539,26 @@ IvfflatReadStreamNextBlock(ReadStream *stream, void *callback_private_data, void static inline bool IvfflatNextScanItem(IvfflatScanOpaque so, ItemPointerData *heaptid) { - bool isnull; + if (so->useHeap) + { + IvfflatBinaryHeap *heap = &so->itemsHeap; - if (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL)) - return false; + if (heap->length < 1) + return false; - *heaptid = *((ItemPointer) DatumGetPointer(slot_getattr(so->mslot, 2, &isnull))); - return true; + *heaptid = BinaryHeapRemoveFirst(heap).heaptid; + return true; + } + else + { + bool isnull; + + if (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL)) + return false; + + *heaptid = *((ItemPointer) DatumGetPointer(slot_getattr(so->mslot, 2, &isnull))); + return true; + } } /* @@ -431,6 +615,9 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys) so->listsVisited = 0; so->listsHeap = pairingheap_allocate(CompareLists, NULL); + so->useHeap = true; + so->maxHeapItems = ComputeMaxHeapItems(mul_size(work_mem, 1024)); + BinaryHeapInit(&so->itemsHeap, Min(32 * 1024, so->maxHeapItems)); InitScanSortState(so); #ifdef IVFFLAT_USE_READ_STREAM diff --git a/test/expected/ivfflat_vector.out b/test/expected/ivfflat_vector.out index ec3f778b..073cf20b 100644 --- a/test/expected/ivfflat_vector.out +++ b/test/expected/ivfflat_vector.out @@ -247,3 +247,18 @@ SELECT pg_index_column_has_property('idx'::regclass, 1, 'search_nulls'); (1 row) DROP TABLE t; +-- work memory +SET work_mem = '64kB'; +CREATE TABLE t (val vector(3)); +INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'); +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 1); +SELECT * FROM t ORDER BY val <-> '[3,3,3]'; + val +--------- + [1,2,3] + [1,1,1] + [0,0,0] +(3 rows) + +DROP TABLE t; +RESET work_mem; diff --git a/test/sql/ivfflat_vector.sql b/test/sql/ivfflat_vector.sql index 7c8537cf..594edb80 100644 --- a/test/sql/ivfflat_vector.sql +++ b/test/sql/ivfflat_vector.sql @@ -133,3 +133,13 @@ SELECT pg_index_column_has_property('idx'::regclass, 2, 'distance_orderable'); SELECT pg_index_column_has_property('idx'::regclass, 1, 'search_nulls'); DROP TABLE t; + +-- work memory + +SET work_mem = '64kB'; +CREATE TABLE t (val vector(3)); +INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'); +CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 1); +SELECT * FROM t ORDER BY val <-> '[3,3,3]'; +DROP TABLE t; +RESET work_mem;