pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
5+ messages / 2 participants
[nested] [flat]

* [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
@ 2025-08-15 20:37 "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  0 siblings, 0 replies; 5+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2025-08-15 20:37 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

This PR adds optimized implementations of binary_quantize. 

The first commit refactors the existing code to take advantage of autovectorization by the compiler (using an inner loop for each output byte). Generation of vectorized code has been confirmed with gcc-13, gcc-14, and clang-19.

The second commit adds optimized implementations using AVX-512 and GFNI instruction sets. 
There are two components:
- Vector element comparison using AVX-512F
- Bit order inversion using GFNI (invert the bit order of the results of the previous comparison to match the bit order required by pgvector). 

The GFNI instructions (Galois Field New Instructions) were introduced in the 3rd Gen Intel® Xeon® Scalable Processors.
Note that the GFNI-based component also requires AVX-512VL for some of the instructions. This is implied in the rest of the description.

The two components are enabled based on the features detected on the system at runtime:
- If neither AVX-512F or GFNI are present, the autovectorized binary_quantize implementation is used.
- If AVX-512F is present but not GFNI, the bit order inversion is done using a lookup table approach.

The AVX-512/GFNI implementation is placed in new files (vectorutils.h/c). This follows the same pattern used for halfvec and bit vector optimized implementations.

Both approaches (autovectorization and AVX-512/GFNI) are included in this PR to better show the full picture and the benefit introduced by each of them. However, if preferred, the two commits can be submitted as individual PRs.

### Results

Setup
- AWS r7i.metal-24xl (AVX-512 and GFNI supported), Ubuntu 24.04, kernel 6.8, gcc-13
- PostgreSQL 17.4
- pgvector
  - unmodified (trunk commit this PR is based on)
  - autovectorized implementation (use first commit in this PR)
  - AVX-512/GFNI implementation (use both commits in this PR)

Workload
- VectorDBBench v1.0.5
- Cases: Performance1536D500K and Performance1536D5M (OpenAI 500k and 5M vector datasets, 1536 dimensions)
- Parameters: k = 10, quantization = bit, reranking = enabled, query concurrency = 10
- HNSW parameters: m = 16, ef_construction = 128, ef_search = 128

Observed queries/second (qps) gains over unmodified pgvector:
- With 500k vector dataset: +20.5% (autovectorized vs unmodified), +28.5% (AVX-512/GFNI vs unmodified)
- With 5M vector dataset: +10.9% (autovectorized vs unmodified), +16.8% (AVX-512/GFNI vs unmodified)
 
Recall is matched for all cases, as expected (the quantization is the same in all implementation).

inline patch 1: Makefile, src/vector.c, src/vectorutils.c and 1 more (+213/-3 lines) download inline-1.patchdiff --git a/Makefile b/Makefile index 6fdede0ba..15e36160e 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ EXTVERSION = 0.8.0 MODULE_big = vector DATA = $(wildcard sql/*--*--*.sql) DATA_built = sql/$(EXTENSION)--$(EXTVERSION).sql -OBJS = src/bitutils.o src/bitvec.o src/halfutils.o src/halfvec.o src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/sparsevec.o src/vector.o +OBJS = src/bitutils.o src/bitvec.o src/halfutils.o src/halfvec.o src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/sparsevec.o src/vectorutils.o src/vector.o HEADERS = src/halfvec.h src/sparsevec.h src/vector.h TESTS = $(wildcard test/sql/*.sql) diff --git a/src/vector.c b/src/vector.c index 256d632a6..d8501ade6 100644 --- a/src/vector.c +++ b/src/vector.c @@ -21,6 +21,7 @@ #include "utils/lsyscache.h" #include "utils/numeric.h" #include "vector.h" +#include "vectorutils.h" #if PG_VERSION_NUM >= 160000 #include "varatt.h" @@ -48,6 +49,7 @@ PGDLLEXPORT void _PG_init(void); void _PG_init(void) { + VectorInit(); BitvecInit(); HalfvecInit(); HnswInit(); @@ -947,8 +949,7 @@ binary_quantize(PG_FUNCTION_ARGS) VarBit *result = InitBitVector(a->dim); unsigned char *rx = VARBITS(result); - for (int i = 0; i < a->dim; i++) - rx[i / 8] |= (ax[i] > 0) << (7 - (i % 8)); + BinaryQuantize(a->dim, ax, rx); PG_RETURN_VARBIT_P(result); } diff --git a/src/vectorutils.c b/src/vectorutils.c new file mode 100644 index 000000000..cc00c0532 --- /dev/null +++ b/src/vectorutils.c @@ -0,0 +1,201 @@ +#include "postgres.h" + +#include "vectorutils.h" +#include "halfvec.h" /* for USE_DISPATCH and USE_TARGET_CLONES */ + +#if defined(USE_DISPATCH) +#define VECTOR_DISPATCH +#endif + +#ifdef VECTOR_DISPATCH +#include <immintrin.h> + +#if defined(USE__GET_CPUID) +#include <cpuid.h> +#else +#include <intrin.h> +#endif + +#ifdef _MSC_VER +#define TARGET_AVX512 +#define TARGET_AVX512_GFNI +#else +#define TARGET_AVX512 __attribute__((target("avx512f"))) +#define TARGET_AVX512_GFNI __attribute__((target("avx512f,avx512vl,gfni"))) +#endif +#endif + +void (*BinaryQuantize) (int dim, float *ax, unsigned char *rx); + +static void +BinaryQuantizeDefault(int dim, float *ax, unsigned char *rx) { + int i; + int count = (dim / 8) * 8; + unsigned char result_byte; + + for (i = 0; i < count; i += 8) + { + result_byte = 0; + for (int j = 0; j < 8; j++) + result_byte |= (ax[i + j] > 0) << (7 - j); + rx[i / 8] = result_byte; + } + for (; i < dim; i++) + rx[i / 8] |= (ax[i] > 0) << (7 - (i % 8)); +} + +#ifdef VECTOR_DISPATCH +TARGET_AVX512 static inline void +BinaryQuantizeAvx512Compare(int dim, float *ax, unsigned char *rx) { + int rx_bytes = 0; + unsigned long mask; + __m512 axi_512; + __m512 zero_512 = _mm512_setzero_ps(); + __mmask16 cmp; + + for (int i = 0; i < dim; i += 16) + { + if (dim - i < 16) + { + mask = (1 << (dim - i)) - 1; + axi_512 = _mm512_maskz_loadu_ps(mask, ax + i); + cmp = _mm512_cmp_ps_mask(axi_512, zero_512, _CMP_GT_OQ); + if (dim - i > 8) + *((uint16_t*)(rx + rx_bytes)) = cmp; + else { + *((uint8_t*)(rx + rx_bytes)) = (uint8_t)(cmp & 0xFF); + } + } + else + { + axi_512 = _mm512_loadu_ps(ax + i); + cmp = _mm512_cmp_ps_mask(axi_512, zero_512, _CMP_GT_OQ); + *((uint16_t*)(rx + rx_bytes)) = cmp; + rx_bytes += 2; + } + } +} + +static const uint8_t bit_invert_lookup[16] = { + 0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE, + 0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF +}; + +TARGET_AVX512 static void +BinaryQuantizeAvx512(int dim, float *ax, unsigned char *rx) { + int rx_bytes = 0; + + BinaryQuantizeAvx512Compare(dim, ax, rx); + + rx_bytes = dim / 8; + if (dim % 8 > 0) + rx_bytes++; + for (int i = 0; i < rx_bytes; i++) + rx[i] = (bit_invert_lookup[rx[i] & 0b1111] << 4) | bit_invert_lookup[rx[i] >> 4]; +} + +/* For GFNI instructions to invert bit order refer to + * Galois Field New Instructions (GFNI) Technology Guide + * https://builders.intel.com/docs/networkbuilders/galois-field-new-instructions-gfni-technology-guide-... + */ +#define GFNI_REVBIT 0x8040201008040201 + +TARGET_AVX512_GFNI static void +BinaryQuantizeAvx512Gfni(int dim, float *ax, unsigned char *rx) { + int rx_bytes = 0; + __m128i revbit = _mm_set1_epi64x(GFNI_REVBIT); + __m128i rxi; + __m128i rxirev; + int count; + int i = 0; + + BinaryQuantizeAvx512Compare(dim, ax, rx); + + rx_bytes = dim / 8; + if (dim % 8 > 0) + rx_bytes++; + count = (rx_bytes/16)*16; + for (; i < count; i += 16) + { + rxi = _mm_loadu_epi64(rx + i); + rxirev = _mm_gf2p8affine_epi64_epi8(rxi, revbit, 0); + _mm_storeu_epi64(rx + i, rxirev); + } + for (; i < rx_bytes; i++) + rx[i] =(bit_invert_lookup[rx[i] & 0b1111] << 4) | bit_invert_lookup[rx[i] >> 4]; +} + +#define CPU_FEATURE_OSXSAVE (1 << 27) +#define CPU_FEATURE_AVX512F (1 << 16) +#define CPU_FEATURE_AVX512VL (1 << 31) +#define CPU_FEATURE_GFNI (1 << 8) + +#ifdef _MSC_VER +#define TARGET_XSAVE +#else +#define TARGET_XSAVE __attribute__((target("xsave"))) +#endif + +TARGET_XSAVE static bool +SupportsOsXsave() +{ + unsigned int exx[4] = {0, 0, 0, 0}; + +#if defined(HAVE__GET_CPUID) + __get_cpuid(1, &exx[0], &exx[1], &exx[2], &exx[3]); +#else + __cpuid(exx, 1); +#endif + + return (exx[2] & CPU_FEATURE_OSXSAVE) == CPU_FEATURE_OSXSAVE; +} + +TARGET_XSAVE static bool +SupportsAvx512(unsigned int feature) +{ + unsigned int exx[4] = {0, 0, 0, 0}; + + /* Check OS supports XSAVE */ + if (!SupportsOsXsave()) + return false; + + /* Check XMM, YMM, and ZMM registers are enabled */ + if ((_xgetbv(0) & 0xe6) != 0xe6) + return false; + +#if defined(HAVE__GET_CPUID) + __get_cpuid_count(7, 0, &exx[0], &exx[1], &exx[2], &exx[3]); +#elif defined(HAVE__CPUID) + __cpuid(exx, 7, 0); +#endif + + return (exx[1] & feature) == feature; +} + +TARGET_XSAVE static bool +SupportsGfni() +{ + unsigned int exx[4] = {0, 0, 0, 0}; + +#if defined(HAVE__GET_CPUID) + __get_cpuid_count(7, 0, &exx[0], &exx[1], &exx[2], &exx[3]); +#elif defined(HAVE__CPUID) + __cpuid(exx, 7, 0); +#endif + + return (exx[2] & CPU_FEATURE_GFNI) == CPU_FEATURE_GFNI; +} +#endif + +void +VectorInit(void) +{ + BinaryQuantize = BinaryQuantizeDefault; + +#ifdef VECTOR_DISPATCH + if (SupportsAvx512(CPU_FEATURE_AVX512F | CPU_FEATURE_AVX512VL) && SupportsGfni()) + BinaryQuantize = BinaryQuantizeAvx512Gfni; + else if (SupportsAvx512(CPU_FEATURE_AVX512F)) + BinaryQuantize = BinaryQuantizeAvx512; +#endif +} diff --git a/src/vectorutils.h b/src/vectorutils.h new file mode 100644 index 000000000..bfc332d3b --- /dev/null +++ b/src/vectorutils.h @@ -0,0 +1,8 @@ +#ifndef VECTORUTILS_H +#define VECTORUTILS_H + +extern void (*BinaryQuantize) (int dim, float *ax, unsigned char *rx); + +void VectorInit(void); + +#endif
^ permalink raw [nested|flat] 5+ messages in thread

* Re: [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
@ 2025-08-16 03:56 ` "ankane (@ankane)" <noreply+ankane@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: ankane (@ankane) @ 2025-08-16 03:56 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @lucagiac81, thanks for the PR. The auto-vectorized version seems like a good trade-off, so will do some testing.

The bigger issue is `binary_quantize` should only need to be called a single time for BQ w/ re-ranking queries (for the query vector).

```sql
SELECT * FROM (
    SELECT * FROM items ORDER BY binary_quantize(embedding)::bit(3) <~> binary_quantize('[1,-2,3]') LIMIT 20
) ORDER BY embedding <=> '[1,-2,3]' LIMIT 5;
```

However, it's called once for every row in the inner query as well (20 extra times in the example above) due to the [current behavior](https://www.postgresql.org/message-id/flat/2ca5865b-4693-40e5-8f78-f3b45d5378fb%40iki.fi) of the Postgres executor (which impacts all nearest neighbor queries).

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

* Re: [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
@ 2025-08-19 20:42 ` "ankane (@ankane)" <noreply+ankane@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: ankane (@ankane) @ 2025-08-19 20:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Merged auto-vectorization in 0c9070ba82fb4e6b6997cdd76b88442175a2f8ab.  Seeing a 5-10% improvement on Linux x86-64 and 10-20% on Mac arm64 in my testing.

Thanks @lucagiac81!

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

* Re: [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
@ 2025-08-19 20:42 ` "ankane (@ankane)" <noreply+ankane@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: ankane (@ankane) @ 2025-08-19 20:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

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

* Re: [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize
@ 2025-08-21 16:35 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  3 siblings, 0 replies; 5+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2025-08-21 16:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @ankane . Thank you very much for the fast review! If you plan to test the AVX-512/GFNI part as well, @asonje and @matt-welch can assist with any questions going forward.

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


end of thread, other threads:[~2025-08-21 16:35 UTC | newest]

Thread overview: 5+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-08-15 20:37 [pgvector/pgvector] PR #888: Add optimized implementations of binary_quantize "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2025-08-16 03:56 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-08-19 20:42 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-08-19 20:42 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-08-21 16:35 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@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