pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
32+ messages / 6 participants
[nested] [flat]

* [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 14:28 "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  0 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-24 14:28 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

This PR adds implementations of halfvec distance functions based on the [AVX-512 FP16](https://networkbuilders.intel.com/solutionslibrary/intel-avx-512-fp16-instruction-set-for-intel-xeon...) instruction set. The instruction set was introduced with Intel 4th Gen Intel® Xeon® Scalable processors. It supports 32x FP16 operations per instruction with 512-bit registers.

Compiler support for the new instructions was added in [gcc-12](https://gcc.gnu.org/gcc-12/changes.html) and [clang-14](https://releases.llvm.org/14.0.0/tools/clang/docs/ReleaseNotes.html). Those versions are minimum requirements for the AVX-512 FP16 functions to be compiled (controlled by conditional compilation). Support for the instruction set is also detected at runtime using CPUID. If not supported, the existing default or F16c functions are used.

Building was tested with
- gcc-11/clang-13 (no AVX-512 FP16 support)
- gcc-12/gcc-13/clang-14 (with AVX-512 FP16 support)

Execution of a binary compiled with gcc-12 (which includes the AVX-512 FP16 functions) was tested on
- 4th Gen Intel® Xeon® Scalable processor (with AVX-512 FP16 support): AVX-512 FP16 functions are used
- 3rd Gen Intel® Xeon® Scalable processor (no AVX-512 FP16 support): existing F16c functions are used

inline patch 1: .github/workflows/build.yml, Makefile, src/halfutils.c and 6 more (+615/-2 lines) download inline-1.patchdiff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e58c3b56d..93cb37134 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,6 +39,38 @@ jobs: sudo apt-get update sudo apt-get install libipc-run-perl - run: make prove_installcheck + ubuntu_spr: + runs-on: ubuntu-24.04 + if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }} + steps: + - uses: actions/checkout@v4 + - name: Install Intel SDE + run: | + curl -o /tmp/sde.tar.xz https://downloadmirror.intel.com/831748/sde-external-9.44.0-2024-08-22-lin.tar.xz + mkdir /tmp/sde && tar -xvf /tmp/sde.tar.xz -C /tmp/sde/ + sudo mv /tmp/sde/* /opt/sde && sudo ln -s /opt/sde/sde64 /usr/bin/sde + - name: Install Postgres + run: | + sudo apt-get install postgresql-16 + sudo apt-get install postgresql-server-dev-16 + sudo systemctl stop postgresql + pgdir=$(pg_config --bindir) + pgdata=/tmp/postgres_data + mkdir $pgdata + $pgdir/initdb -D $pgdata --username=$USER + sudo chmod 777 /var/run/postgresql/ + sde -spr -mix -- $pgdir/pg_ctl -D $pgdata start + - run: make + env: + PG_CFLAGS: -DUSE_ASSERT_CHECKING -Wall -Wextra -Werror -Wno-unused-parameter -Wno-sign-compare + - run: | + export PG_CONFIG=`which pg_config` + sudo --preserve-env=PG_CONFIG make install + - run: sde -spr -mix -- make installcheck + - if: ${{ failure() }} + run: cat regression.diffs + - name: Report AVX512 FP16 FMA instruction count + run: cat sde*.txt | grep -E "FMA.*PH" mac: runs-on: ${{ matrix.os }} if: ${{ !startsWith(github.ref_name, 'windows') }} diff --git a/Makefile b/Makefile index 7a4b88caf..75d1330cc 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,9 @@ 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 +ifneq ($(USE_AVX512), 0) + OBJS += src/halfutils_avx512.o +endif HEADERS = src/halfvec.h src/sparsevec.h src/vector.h TESTS = $(wildcard test/sql/*.sql) @@ -31,6 +34,9 @@ endif # - GCC (needs -ftree-vectorize OR -O3) - https://gcc.gnu.org/projects/tree-ssa/vectorization.html # - Clang (could use pragma instead) - https://llvm.org/docs/Vectorizers.html PG_CFLAGS += $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math +ifneq ($(USE_AVX512), 0) + PG_CFLAGS += -DUSE_AVX512 +endif # Debug GCC auto-vectorization # PG_CFLAGS += -fopt-info-vec diff --git a/src/halfutils.c b/src/halfutils.c index d16909409..bdc370a19 100644 --- a/src/halfutils.c +++ b/src/halfutils.c @@ -5,6 +5,7 @@ #ifdef HALFVEC_DISPATCH #include <immintrin.h> +#include "halfutils_avx512.h" #if defined(USE__GET_CPUID) #include <cpuid.h> @@ -24,6 +25,8 @@ float (*HalfvecInnerProduct) (int dim, half * ax, half * bx); double (*HalfvecCosineSimilarity) (int dim, half * ax, half * bx); float (*HalfvecL1Distance) (int dim, half * ax, half * bx); +void (*Float4ToHalfVector) (Vector * vec, HalfVector * result); + static float HalfvecL2SquaredDistanceDefault(int dim, half * ax, half * bx) { @@ -237,6 +240,13 @@ HalfvecL1DistanceF16c(int dim, half * ax, half * bx) } #endif +static void +Float4ToHalfVectorDefault(Vector * vec, HalfVector * result) { + for (int i = 0; i < vec->dim; i++) + result->x[i] = Float4ToHalf(vec->x[i]); +} + + #ifdef HALFVEC_DISPATCH #define CPU_FEATURE_FMA (1 << 12) #define CPU_FEATURE_OSXSAVE (1 << 27) @@ -284,6 +294,7 @@ HalfvecInit(void) HalfvecInnerProduct = HalfvecInnerProductDefault; HalfvecCosineSimilarity = HalfvecCosineSimilarityDefault; HalfvecL1Distance = HalfvecL1DistanceDefault; + Float4ToHalfVector = Float4ToHalfVectorDefault; #ifdef HALFVEC_DISPATCH if (SupportsCpuFeature(CPU_FEATURE_AVX | CPU_FEATURE_F16C | CPU_FEATURE_FMA)) @@ -294,5 +305,16 @@ HalfvecInit(void) /* Does not require FMA, but keep logic simple */ HalfvecL1Distance = HalfvecL1DistanceF16c; } + +#if defined(USE_AVX512) && defined(HAVE_AVX512FP16) + if (SupportsAvx512Fp16()) + { + HalfvecL2SquaredDistance = HalfvecL2SquaredDistanceAvx512; + HalfvecInnerProduct = HalfvecInnerProductAvx512; + HalfvecCosineSimilarity = HalfvecCosineSimilarityAvx512; + HalfvecL1Distance = HalfvecL1DistanceAvx512; + Float4ToHalfVector = Float4ToHalfVectorAvx512; + } +#endif #endif } diff --git a/src/halfutils.h b/src/halfutils.h index c684f72d7..1a33d1748 100644 --- a/src/halfutils.h +++ b/src/halfutils.h @@ -5,6 +5,7 @@ #include "common/shortest_dec.h" #include "halfvec.h" +#include "vector.h" #ifdef F16C_SUPPORT #include <immintrin.h> @@ -15,6 +16,8 @@ extern float (*HalfvecInnerProduct) (int dim, half * ax, half * bx); extern double (*HalfvecCosineSimilarity) (int dim, half * ax, half * bx); extern float (*HalfvecL1Distance) (int dim, half * ax, half * bx); +extern void (*Float4ToHalfVector) (Vector * vec, HalfVector * result); + void HalfvecInit(void); /* diff --git a/src/halfutils_avx512.c b/src/halfutils_avx512.c new file mode 100644 index 000000000..27d907781 --- /dev/null +++ b/src/halfutils_avx512.c @@ -0,0 +1,449 @@ +#ifdef USE_AVX512 +#include "halfutils_avx512.h" + +#ifdef HAVE_AVX512FP16 +#include "common/shortest_dec.h" + +#include <immintrin.h> +#include <math.h> + +#if defined(USE__GET_CPUID) +#include <cpuid.h> +#else +#include <intrin.h> +#endif + +#ifdef _MSC_VER +#define TARGET_AVX512FP16 +#else +#define TARGET_AVX512FP16 __attribute__((target("avx512fp16,avx512f,avx512dq,avx512vl,avx512bw"))) +#endif + +TARGET_AVX512FP16 static inline bool +HasInfinity(__m512h val) { + /* Test for positive and negative infinity */ + __mmask32 mask = _mm512_fpclass_ph_mask(val, 0x08 + 0x10); + return mask != 0; +} + +TARGET_AVX512FP16 static inline __m512 +ConvertToFp32Sum(__m512h val) { + __m256h val_lower = _mm256_castsi256_ph(_mm512_extracti32x8_epi32(_mm512_castph_si512(val), 0)); + __m256h val_upper = _mm256_castsi256_ph(_mm512_extracti32x8_epi32(_mm512_castph_si512(val), 1)); + return _mm512_add_ps(_mm512_cvtxph_ps(val_lower), _mm512_cvtxph_ps(val_upper)); +} + +TARGET_AVX512FP16 float +HalfvecL2SquaredDistanceAvx512(int dim, half * ax, half * bx) +{ + float distance; + int i; + unsigned long mask; + + /* For FP16 computation */ + __m512h axi_512h; + __m512h bxi_512h; + __m512h diff_512h; + __m512h dist_512h = _mm512_setzero_ph(); + __m512h dist_512h_temp; + + /* For FP32 computation */ + __m256h axi_256h; + __m256h bxi_256h; + __m512 axi_512; + __m512 bxi_512; + __m512 diff_512; + __m512 dist_512; + + /* FP16 computation */ + for (i = 0; i < dim; i += 32) + { + if (dim - i < 32) + { + mask = (1 << (dim - i)) - 1; + axi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, ax + i)); + bxi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_512h = _mm512_loadu_ph(ax + i); + bxi_512h = _mm512_loadu_ph(bx + i); + } + diff_512h = _mm512_sub_ph(axi_512h, bxi_512h); + dist_512h_temp = _mm512_fmadd_ph(diff_512h, diff_512h, dist_512h); + + /* if overflow, continue with FP32 */ + if (HasInfinity(dist_512h_temp)) + break; + else + dist_512h = dist_512h_temp; + } + dist_512 = ConvertToFp32Sum(dist_512h); + + /* FP32 computation */ + for (; i < dim; i += 16) + { + if (dim - i < 16) + { + mask = (1 << (dim - i)) - 1; + axi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, ax + i)); + bxi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_256h = _mm256_loadu_ph(ax + i); + bxi_256h = _mm256_loadu_ph(bx + i); + } + axi_512 = _mm512_cvtxph_ps(axi_256h); + bxi_512 = _mm512_cvtxph_ps(bxi_256h); + diff_512 = _mm512_sub_ps(axi_512, bxi_512); + dist_512 = _mm512_fmadd_ps(diff_512, diff_512, dist_512); + } + + distance = _mm512_reduce_add_ps(dist_512); + return distance; +} + +TARGET_AVX512FP16 float +HalfvecInnerProductAvx512(int dim, half * ax, half * bx) +{ + float distance; + int i; + unsigned int mask; + + /* For FP16 computation */ + __m512h axi_512h; + __m512h bxi_512h; + __m512h dist_512h = _mm512_setzero_ph(); + __m512h dist_512h_temp; + + /* For FP32 computation */ + __m256h axi_256h; + __m256h bxi_256h; + __m512 axi_512; + __m512 bxi_512; + __m512 dist_512; + + /* FP16 computation */ + for (i = 0; i < dim; i += 32) + { + if (dim - i < 32) + { + mask = (1 << (dim - i)) - 1; + axi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, ax + i)); + bxi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_512h = _mm512_loadu_ph(ax + i); + bxi_512h = _mm512_loadu_ph(bx + i); + } + dist_512h_temp = _mm512_fmadd_ph(axi_512h, bxi_512h, dist_512h); + + /* if overflow, continue with FP32 */ + if (HasInfinity(dist_512h_temp)) + break; + else + dist_512h = dist_512h_temp; + } + dist_512 = ConvertToFp32Sum(dist_512h); + + /* FP32 computation */ + for (; i < dim; i += 16) + { + if (dim - i < 16) + { + mask = (1 << (dim - i)) - 1; + axi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, ax + i)); + bxi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_256h = _mm256_loadu_ph(ax + i); + bxi_256h = _mm256_loadu_ph(bx + i); + } + axi_512 = _mm512_cvtxph_ps(axi_256h); + bxi_512 = _mm512_cvtxph_ps(bxi_256h); + dist_512 = _mm512_fmadd_ps(axi_512, bxi_512, dist_512); + } + + distance = _mm512_reduce_add_ps(dist_512); + return distance; +} + +TARGET_AVX512FP16 double +HalfvecCosineSimilarityAvx512(int dim, half * ax, half * bx) +{ + float similarity; + float norma; + float normb; + int i; + unsigned int mask; + + /* For FP16 computation */ + __m512h axi_512h; + __m512h bxi_512h; + __m512h sim_512h = _mm512_setzero_ph(); + __m512h na_512h = _mm512_setzero_ph(); + __m512h nb_512h = _mm512_setzero_ph(); + __m512h sim_512h_temp; + __m512h na_512h_temp; + __m512h nb_512h_temp; + + /* For FP32 computation */ + __m256h axi_256h; + __m256h bxi_256h; + __m512 axi_512; + __m512 bxi_512; + __m512 sim_512; + __m512 na_512; + __m512 nb_512; + + /* FP16 computation */ + for (i = 0; i < dim; i += 32) + { + if (dim - i < 32) { + mask = (1 << (dim - i)) - 1; + axi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, ax + i)); + bxi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, bx + i)); + } + else { + axi_512h = _mm512_loadu_ph(ax + i); + bxi_512h = _mm512_loadu_ph(bx + i); + } + sim_512h_temp = _mm512_fmadd_ph(axi_512h, bxi_512h, sim_512h); + na_512h_temp = _mm512_fmadd_ph(axi_512h, axi_512h, na_512h); + nb_512h_temp = _mm512_fmadd_ph(bxi_512h, bxi_512h, nb_512h); + + /* if overflow, continue with FP32 */ + if (HasInfinity(sim_512h_temp) || + HasInfinity(na_512h_temp) || + HasInfinity(nb_512h_temp)) + break; + else + { + sim_512h = sim_512h_temp; + na_512h = na_512h_temp; + nb_512h = nb_512h_temp; + } + } + sim_512 = ConvertToFp32Sum(sim_512h); + na_512 = ConvertToFp32Sum(na_512h); + nb_512 = ConvertToFp32Sum(nb_512h); + + /* FP32 computation */ + for (; i < dim; i += 16) + { + if (dim - i < 16) + { + mask = (1 << (dim - i)) - 1; + axi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, ax + i)); + bxi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_256h = _mm256_loadu_ph(ax + i); + bxi_256h = _mm256_loadu_ph(bx + i); + } + axi_512 = _mm512_cvtxph_ps(axi_256h); + bxi_512 = _mm512_cvtxph_ps(bxi_256h); + sim_512 = _mm512_fmadd_ps(axi_512, bxi_512, sim_512); + na_512 = _mm512_fmadd_ps(axi_512, axi_512, na_512); + nb_512 = _mm512_fmadd_ps(bxi_512, bxi_512, nb_512); + } + + similarity = _mm512_reduce_add_ps(sim_512); + norma = _mm512_reduce_add_ps(na_512); + normb = _mm512_reduce_add_ps(nb_512); + + /* Use sqrt(a * b) over sqrt(a) * sqrt(b) */ + return (double) similarity / sqrt((double) norma * (double) normb); +} + +TARGET_AVX512FP16 float +HalfvecL1DistanceAvx512(int dim, half * ax, half * bx) +{ + float distance; + int i; + unsigned long mask; + + /* For FP16 computation */ + __m512h axi_512h; + __m512h bxi_512h; + __m512h dist_512h = _mm512_setzero_ph(); + __m512h dist_512h_temp; + + /* For FP32 computation */ + __m256h axi_256h; + __m256h bxi_256h; + __m512 axi_512; + __m512 bxi_512; + __m512 dist_512; + + /* FP16 computation */ + for (i = 0; i < dim; i += 32) + { + if (dim - i < 32) + { + mask = (1 << (dim - i)) - 1; + axi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, ax + i)); + bxi_512h = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_512h = _mm512_loadu_ph(ax + i); + bxi_512h = _mm512_loadu_ph(bx + i); + } + dist_512h_temp = _mm512_add_ph(dist_512h, _mm512_abs_ph(_mm512_sub_ph(axi_512h, bxi_512h))); + + /* if overflow, continue with FP32 */ + if (HasInfinity(dist_512h_temp)) + break; + else + dist_512h = dist_512h_temp; + } + dist_512 = ConvertToFp32Sum(dist_512h); + + /* FP32 computation */ + for (; i < dim; i += 16) + { + if (dim - i < 16) + { + mask = (1 << (dim - i)) - 1; + axi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, ax + i)); + bxi_256h = _mm256_castsi256_ph(_mm256_maskz_loadu_epi16(mask, bx + i)); + } + else + { + axi_256h = _mm256_loadu_ph(ax + i); + bxi_256h = _mm256_loadu_ph(bx + i); + } + axi_512 = _mm512_cvtxph_ps(axi_256h); + bxi_512 = _mm512_cvtxph_ps(bxi_256h); + dist_512 = _mm512_add_ps(dist_512, _mm512_abs_ps(_mm512_sub_ps(axi_512, bxi_512))); + } + + distance = _mm512_reduce_add_ps(dist_512); + + return distance; +} + +TARGET_AVX512FP16 void +Float4ToHalfVectorAvx512(Vector * vec, HalfVector * result) +{ + unsigned long mask; + __m512 vec_512; + __m256h vec_256h; + __mmask16 vec_512_inf; + __mmask16 vec_256h_inf; + + for (int i = 0; i < vec->dim; i += 16) + { + if (vec->dim - i < 16) + { + mask = (1 << (vec->dim - i)) - 1; + vec_512 = _mm512_maskz_loadu_ps(mask, vec->x + i); + vec_256h = _mm512_cvtxps_ph(vec_512); + _mm256_mask_storeu_epi16(result->x + i, mask, _mm256_castph_si256(vec_256h)); + } + else + { + vec_512 = _mm512_loadu_ps(vec->x + i); + vec_256h = _mm512_cvtxps_ph(vec_512); + _mm256_storeu_ph(result->x + i, vec_256h); + } + + /* Test for positive and negative infinity */ + vec_512_inf = _mm512_fpclass_ps_mask(vec_512, 0x08 + 0x10); + vec_256h_inf = _mm256_fpclass_ph_mask(vec_256h, 0x08 + 0x10); + if (unlikely(vec_512_inf != vec_256h_inf)) + { + float num; + char* buf; + + __mmask16 diff = _kxor_mask16(vec_512_inf, vec_256h_inf); + /* Find first element in vector to overflow after conversion (first bit set) */ + int count = 0; + while (diff % 2 == 0) { + diff >>= 1; + count++; + } + num = vec->x[i + count]; + + /* TODO Avoid duplicate code in Float4ToHalf */ + buf = palloc(FLOAT_SHORTEST_DECIMAL_LEN); + + float_to_shortest_decimal_buf(num, buf); + + ereport(ERROR, + (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), + errmsg("\"%s\" is out of range for type halfvec", buf))); + } + } +} + +#define CPU_FEATURE_OSXSAVE (1 << 27) +#define CPU_FEATURE_AVX512F (1 << 16) +#define CPU_FEATURE_AVX512DQ (1 << 17) +#define CPU_FEATURE_AVX512_FP16 (1 << 23) +#define CPU_FEATURE_AVX512BW (1 << 30) +#define CPU_FEATURE_AVX512VL (1 << 31) + +#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 bool +SupportsAvx512Fp16() +{ + unsigned int exx[4] = {0, 0, 0, 0}; + + /* AVX512 features required: + * AVX512F : sub/fma/add instructions + * AVX512DQ: _mm512_extracti32x8_epi32 + * AVX512VL: _mm256_loadu_ph + * AVX512BW: masked loads + */ + unsigned int features = CPU_FEATURE_AVX512F | + CPU_FEATURE_AVX512DQ | + CPU_FEATURE_AVX512VL | + CPU_FEATURE_AVX512BW; + + /* 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 + + if ((exx[1] & features) != features) + return false; + + return (exx[3] & CPU_FEATURE_AVX512_FP16) == CPU_FEATURE_AVX512_FP16; +} + +#endif +#endif diff --git a/src/halfutils_avx512.h b/src/halfutils_avx512.h new file mode 100644 index 000000000..9f94f11dc --- /dev/null +++ b/src/halfutils_avx512.h @@ -0,0 +1,25 @@ +#ifndef HALFUTILS_AVX512_H +#define HALFUTILS_AVX512_H + +#ifdef USE_AVX512 +#include "postgres.h" +#include "halfvec.h" +#include "vector.h" + +#if (defined(__GNUC__) && (__GNUC__ >= 12)) || \ + (defined(__clang__) && (__clang_major__ >= 16)) || \ + (defined __AVX512FP16__) +#define HAVE_AVX512FP16 +#endif + +#ifdef HAVE_AVX512FP16 +extern float HalfvecL2SquaredDistanceAvx512(int dim, half * ax, half * bx); +extern float HalfvecInnerProductAvx512(int dim, half * ax, half * bx); +extern double HalfvecCosineSimilarityAvx512(int dim, half * ax, half * bx); +extern float HalfvecL1DistanceAvx512(int dim, half * ax, half * bx); +extern void Float4ToHalfVectorAvx512(Vector * vec, HalfVector * result); + +extern bool SupportsAvx512Fp16(void); +#endif +#endif +#endif diff --git a/src/halfvec.c b/src/halfvec.c index aad320b1c..9b85ba741 100644 --- a/src/halfvec.c +++ b/src/halfvec.c @@ -533,8 +533,7 @@ vector_to_halfvec(PG_FUNCTION_ARGS) result = InitHalfVector(vec->dim); - for (int i = 0; i < vec->dim; i++) - result->x[i] = Float4ToHalf(vec->x[i]); + Float4ToHalfVector(vec, result); PG_RETURN_POINTER(result); } diff --git a/test/expected/halfvec.out b/test/expected/halfvec.out index a3ce8931f..867dd176b 100644 --- a/test/expected/halfvec.out +++ b/test/expected/halfvec.out @@ -378,6 +378,24 @@ SELECT '[0,0]'::halfvec <-> '[3,4]'; 5 (1 row) +SELECT l2_distance('[501]'::halfvec, '[1]'); + l2_distance +------------- + 500 +(1 row) + +SELECT l2_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + l2_distance +------------- + 0 +(1 row) + +SELECT l2_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + l2_distance +------------- + 6 +(1 row) + SELECT inner_product('[1,2]'::halfvec, '[3,4]'); inner_product --------------- @@ -404,6 +422,24 @@ SELECT '[1,2]'::halfvec <#> '[3,4]'; -11 (1 row) +SELECT inner_product('[50000,50000]'::halfvec, '[1,1]'); + inner_product +--------------- + 99968 +(1 row) + +SELECT inner_product('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + inner_product +--------------- + 36 +(1 row) + +SELECT inner_product('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + inner_product +--------------- + 72 +(1 row) + SELECT cosine_distance('[1,2]'::halfvec, '[2,4]'); cosine_distance ----------------- @@ -466,6 +502,24 @@ SELECT '[1,2]'::halfvec <=> '[2,4]'; 0 (1 row) +SELECT cosine_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + cosine_distance +----------------- + 0 +(1 row) + +SELECT cosine_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + cosine_distance +----------------- + 0 +(1 row) + +SELECT cosine_distance('[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]'::halfvec, '[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]'); + cosine_distance +----------------- + 1 +(1 row) + SELECT l1_distance('[0,0]'::halfvec, '[3,4]'); l1_distance ------------- @@ -498,6 +552,18 @@ SELECT '[0,0]'::halfvec <+> '[3,4]'; 7 (1 row) +SELECT l1_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + l1_distance +------------- + 0 +(1 row) + +SELECT l1_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); + l1_distance +------------- + 36 +(1 row) + SELECT l2_normalize('[3,4]'::halfvec); l2_normalize ------------------------ diff --git a/test/sql/halfvec.sql b/test/sql/halfvec.sql index 1a3fd1b82..d94518348 100644 --- a/test/sql/halfvec.sql +++ b/test/sql/halfvec.sql @@ -87,12 +87,18 @@ SELECT l2_distance('[0,0]'::halfvec, '[0,1]'); SELECT l2_distance('[1,2]'::halfvec, '[3]'); SELECT l2_distance('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,4,5]'); SELECT '[0,0]'::halfvec <-> '[3,4]'; +SELECT l2_distance('[501]'::halfvec, '[1]'); +SELECT l2_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); +SELECT l2_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); SELECT inner_product('[1,2]'::halfvec, '[3,4]'); SELECT inner_product('[1,2]'::halfvec, '[3]'); SELECT inner_product('[65504]'::halfvec, '[65504]'); SELECT inner_product('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,2,3,4,5,6,7,8,9]'); SELECT '[1,2]'::halfvec <#> '[3,4]'; +SELECT inner_product('[50000,50000]'::halfvec, '[1,1]'); +SELECT inner_product('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); +SELECT inner_product('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); SELECT cosine_distance('[1,2]'::halfvec, '[2,4]'); SELECT cosine_distance('[1,2]'::halfvec, '[0,0]'); @@ -105,6 +111,9 @@ SELECT cosine_distance('[1,1]'::halfvec, '[-1.1,-1.1]'); SELECT cosine_distance('[1,2,3,4,5,6,7,8,9]'::halfvec, '[1,2,3,4,5,6,7,8,9]'); SELECT cosine_distance('[1,2,3,4,5,6,7,8,9]'::halfvec, '[-1,-2,-3,-4,-5,-6,-7,-8,-9]'); SELECT '[1,2]'::halfvec <=> '[2,4]'; +SELECT cosine_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); +SELECT cosine_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); +SELECT cosine_distance('[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]'::halfvec, '[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]'); SELECT l1_distance('[0,0]'::halfvec, '[3,4]'); SELECT l1_distance('[0,0]'::halfvec, '[0,1]'); @@ -112,6 +121,8 @@ SELECT l1_distance('[1,2]'::halfvec, '[3]'); SELECT l1_distance('[1,2,3,4,5,6,7,8,9]'::halfvec, '[1,2,3,4,5,6,7,8,9]'); SELECT l1_distance('[1,2,3,4,5,6,7,8,9]'::halfvec, '[0,3,2,5,4,7,6,9,8]'); SELECT '[0,0]'::halfvec <+> '[3,4]'; +SELECT l1_distance('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); +SELECT l1_distance('[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]'::halfvec, '[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]'); SELECT l2_normalize('[3,4]'::halfvec); SELECT l2_normalize('[3,0]'::halfvec);
^ permalink raw [nested|flat] 32+ messages in thread

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 14:45 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: jkatz (@jkatz) @ 2024-04-24 14:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@nathan-bossart Would love your feedback on this one.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 16:28 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: nathan-bossart (@nathan-bossart) @ 2024-04-24 16:28 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

I think this is missing a couple steps, such as checking for osxsave and verifying the ZMM registers are enabled.  See `SupportsAvx512Popcount()` for an example.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 16:29 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: nathan-bossart (@nathan-bossart) @ 2024-04-24 16:29 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

Is this auto-vectorized?  (Same question for `HalfvecL2SquaredDistanceAvx512Fp16()`.)

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 16:32 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: nathan-bossart (@nathan-bossart) @ 2024-04-24 16:32 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

nitpick:  This might not need to be nested in the `HALFVEC_DISPATCH` block.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 16:35 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: nathan-bossart (@nathan-bossart) @ 2024-04-24 16:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Performance results will be shared soon.

Looking forward to these!

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 16:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: jkatz (@jkatz) @ 2024-04-24 16:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I'll kick off some local benchmark runs to see the diffs. I have a r7i at the ready.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-24 17:34 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: jkatz (@jkatz) @ 2024-04-24 17:34 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@lucagiac81 I'm having issues compiling on an EC2 r7i. This is using gcc12 and clang-15. Here is some truncated output:

```
/usr/bin/clang-15 -Wno-ignored-attributes -fno-strict-aliasing -fwrapv -Xclang -no-opaque-pointers -Wno-unused-command-line-argument -Wno-compound-token-split-by-macro -O2  -I. -I./ -I/usr/include/postgresql/16/server -I/usr/include/postgresql/internal  -Wdate-time -D_FORTIFY_SOURCE=2 -D_GNU_SOURCE -I/usr/include/libxml2  -flto=thin -emit-llvm -c -o src/halfutils.bc src/halfutils.c
src/halfutils.c:92:9: error: expected ';' after expression
        __m512h         dist = _mm512_setzero_ph();
               ^
               ;
src/halfutils.c:92:2: error: use of undeclared identifier '__m512h'
        __m512h         dist = _mm512_setzero_ph();
        ^
src/halfutils.c:92:11: error: use of undeclared identifier 'dist'
        __m512h         dist = _mm512_setzero_ph();
                        ^
src/halfutils.c:92:18: warning: call to undeclared function '_mm512_setzero_ph'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
        __m512h         dist = _mm512_setzero_ph();
                               ^
src/halfutils.c:95:10: error: expected ';' after expression
                __m512h axi = _mm512_loadu_ph(ax+i);
                       ^
                       ;
src/halfutils.c:95:3: error: use of undeclared identifier '__m512h'
                __m512h axi = _mm512_loadu_ph(ax+i);
                ^
src/halfutils.c:95:11: error: use of undeclared identifier 'axi'; did you mean 'ax'?
                __m512h axi = _mm512_loadu_ph(ax+i);
                        ^~~
                        ax
src/halfutils.c:87:52: note: 'ax' declared here
HalfvecL2SquaredDistanceAvx512Fp16(int dim, half * ax, half * bx)
```

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-25 00:56 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-25 00:56 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

Thanks for the reference. I'll add those checks (OSXSAVE and XCR0 control register).

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-25 01:00 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-25 01:00 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

You're right. Currently, it is taking advantage of the OSXSAVE check included with the other features, but I'll separate that.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-25 02:49 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-25 02:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz I think clang is not applying `__attribute__((target("avx512fp16")))`

I tested on an m7i instance (where `-march=native` includes `-mavx512fp16`) with clang-15
- Build pgvector with the default Makefile (which has` -march=native` in OPTFLAGS): no error
- Remove `-march=native` from Makefile: compilation errors (similar to your report)
- Replace `-march=native` with `-mavx512fp16` in Makefile: no error

With gcc-12.3, and I got no errors in all cases.

Can you try adding `-march=native` or `-mavx512fp16 `to your flags as a temporary solution?

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-25 19:54 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-25 19:54 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Rebased on latest master
Added checks for OSXSAVE and zmm registers enabled
Added L1 distance AVX512-FP16 implementation

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-25 20:01 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-04-25 20:01 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

I checked L2SquaredDistance and InnerProduct, and it is using AVX scalar instructions, at least with gcc-12. We'll try masked vector instructions to handle the loop remainder.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-26 23:52 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: akashsha1 (@akashsha1) @ 2024-04-26 23:52 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

nit. feature can be defined using #DEFINE CPU_FEATURE_AVX512FP16

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-26 23:54 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: akashsha1 (@akashsha1) @ 2024-04-26 23:54 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

nit. update comment to reflect OSXSAVE 

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-27 00:07 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: akashsha1 (@akashsha1) @ 2024-04-27 00:07 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

@nathan-bossart shouldn't this be _xgetbv(0) & 0xe6) **==** 0xe6 ? Similar comment on L187 in bitutils.c per the discussion [0]


[0] : https://www.postgresql.org/message-id/20240418210158.GA3776258%40nathanxps13


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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-04-29 20:52 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: nathan-bossart (@nathan-bossart) @ 2024-04-29 20:52 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

This looks alright as-is to me.  If this check fails, we return false, so `!=` looks correct.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-05-14 03:18 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-05-14 03:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

While collecting data with ANN benchmarks, we noticed a degradation in recall for some datasets (such as sift-128) when computing distances in half precision. Other datasets (such as gist-960) are not affected, and recall is matched to the existing distance functions. The existing functions (*F16c) first convert halfvec elements to single precision and execute the distance computation in single precision.

So, enabling the FP16 distance functions may not be desirable in all cases. The latest update to the PR provides two implementations of the distance functions with AVX-512: one using single precision and one using half precision.

- The single-precision functions are used by default, as they're the most generically applicable.
- The user can decide to use the half-precision functions by setting a variable (halfvec.use_fp16_compute). The decision should be based on recall vs performance tradeoff for a specific dataset (this implementation handles 2x the vector elements per iteration compared to the single-precision one). 

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-05-14 03:19 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-05-14 03:19 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

(on src/halfutils.c)

The latest update includes masked vector instructions for the loop remainder.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-05-14 15:30 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: jkatz (@jkatz) @ 2024-05-14 15:30 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@lucagiac81 Thanks for the continued work. Per @nathan-bossart comment earlier, it'd be helpful to see the actual performance results.

I'll try to get this to build again - last I checked I didn't have avx512fp16 available on my instance class.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-05-16 19:36 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-05-16 19:36 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Here are some initial results

- We made a few changes to ANN benchmarks to support halfvec (following your [post](https://jkatz05.com/post/postgres/pgvector-scalar-binary-quantization/)) and used the [default conditions](https://github.com/erikbern/ann-benchmarks/blob/main/ann_benchmarks/algorithms/pgvector/config.yml).
- The tests were run on an m7i.metal-24xl instance. pgvector is compiled with gcc-12.
- We measure query performance for the AVX-512 half-precision and single-precision distance implementations, and compare with the existing F16c implementation. To enable the half-precision functions, we use `SET halfvec.use_fp16_compute = true` in [set_query_arguments](https://github.com/erikbern/ann-benchmarks/blob/cc3a748305b2478838e84b8e625f9eb0beec993e/ann_benchma...), as described in the [previous comment](https://github.com/pgvector/pgvector/pull/531#issuecomment-2109199219).

With the gist-960-euclidean dataset, so far we observe

- qps increase of 9.6%-12.9% for half-precision and 1.4%-3.6% for single-precision
- p99 reduction of 8.3%-12.8% for half-precision and 0-4% for single-precision
- recall is matched to within +/-1% for both implementations

It'd be great if you could reproduce these numbers with your setup. Please let me know if you still run into compilation issues. We'd also like to collect data with dbpedia-openai-1000k-angular as well (higher dimensions, different distance metric) , but we're running into a 403 error when downloading the dataset (similar to this [report](https://github.com/erikbern/ann-benchmarks/issues/460)). Do you have any advice on how to run with that dataset?


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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-09-24 20:44 ` "ankane (@ankane)" <noreply+ankane@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: ankane (@ankane) @ 2024-09-24 20:44 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @lucagiac81, thanks for the PR, and sorry for the delay. Based on the numbers above, I'm not sure the benefit justifies the complexity.

For the `dbpedia-openai-1000k-angular` dataset, there's a `create_dataset.py` script in ann-benchmarks, fwiw.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-09-24 22:56 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-09-24 22:56 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Thanks @ankane. The issue with the dbpedia dataset was the inability to create the dataset locally. After updating the datasets package to v2.19.1, the issue is resolved. We'll share the results with that dataset as well.

Regarding the complexity, is the additional parameter to select the precision of the distance computation the main concern?

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-09-25 00:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: ankane (@ankane) @ 2024-09-25 00:06 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Sounds good.

The parameter doubles my concern, but there's still a lot of complexity without it. I'm not sure either choice is great based on the numbers above, since the single-precision version provides little performance benefit and while the half-precision provides some benefit but reduces precision and range.

For comparison, here are the f16c + fma numbers: https://github.com/pgvector/pgvector/pull/311#issuecomment-2043634797.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-10-21 22:15 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-10-21 22:15 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The latest update eliminates the need to manually enable FP16 computation. Computation starts with FP16 and switches to FP32 in case of overflow. 
With this approach, the recall degradation we observed with FP16 for certain datasets (sift-128-euclidean) is resolved. Datasets that performed well with FP16 computation (gist-960-euclidean) show similar performance as with FP16 enabled in the previous version of the code.
We will share a more detailed report, but this is a step towards reducing complexity (especially not exposing it to the end user).

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-11-12 20:48 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-11-12 20:48 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The latest update introduces an AVX512_FP16 implementation of vector_to_halfvec conversion (in separate commit), as that function has a noticeable contribution in VectorDBBench benchmarks. It is also rebased on pgvector v0.8.0. Sharing additional performance measurements with ANN-Benchmarks and VectorDBBench below.

For ANN-Benchmarks, we used a similar setup as for the [previously shared data](https://github.com/pgvector/pgvector/pull/531#issuecomment-2116043999). With the latest changes, the manual selection of FP16/FP32 computation is [removed](https://github.com/pgvector/pgvector/pull/531#issuecomment-2427840519). We also include measurements for index build time (with 8 parallel workers). Performance gains are relative to the existing F16c implementation.
For dbpedia-openai-1000k-angular dataset, we observe
- qps gain of 9.4%-14.2%
- p99 reduction of 9.0%-12.9%
- index build time reduction of 3.8% (m=16) and 11.6% (m=24)
- recall matched within +/-0.3%

For sift-128-euclidean, we observe 11-12% index build time reduction with recall matched within +/-0.1%, but no significant qps/p99 gain. This confirms that the recall degradation previously observed with FP16 computation is resolved and there are gains for certain metrics even at lower dimensions.

For VectorDBBench, we focused on larger datasets and varying search concurrency (1-40 range on an r7i.12xlarge instance). Below are initial results with two datasets:
- Performance1536D5M (OpenAI, 5M vectors, 1536 dimensions): 4-8% qps gain 
- Performance768D10M (Cohere, 10M vectors, 768 dimensions): 5-6% qps gain

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2024-11-21 22:33 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2024-11-21 22:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The last update fixes some issues reported by CI:
- Remove unnecessary variable initialization
- Add AVX512DQ check (required by one instruction)
- Increase clang minimum version requirement from 14 to 16. Version 16 solves the issue reported in a previous [comment](https://github.com/pgvector/pgvector/pull/531#issuecomment-2076257304). I'll keep checking for a solution with earlier versions.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2025-01-06 21:57 ` "greenhal (@greenhal)" <noreply+greenhal@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: greenhal (@greenhal) @ 2025-01-06 21:57 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@lucagiac81 

I tested the latest revision [a1e3ead](https://github.com/pgvector/pgvector/pull/531/commits/a1e3eadd0ed24092e7d93da32c6e183ae3efb210) using vectordbbench on a r7i.8xlarge instance and achieved qps improvements ranging from 7% to 23%, depending on the dataset.

|Dataset|qps|recall|with avx512 qps|qps improvement|with avx512 recall|recallimpact|
|-------|---|------|---|---------------|-------|-------|
|Performance1536D50K|10644.763|0.9691|12594.4903|18.32%|0.9626|-0.67%|
|Performance1536D5M|6810.1588|0.9338|7332.7366|7.67%|0.927|-0.73%|
|Performance768D10M|7916.9702|0.8975|9799.3695|23.78%|0.8949|-0.29%|
|Performance768D1M|9847.2079|0.926|11043.1437|12.14%|0.9262|0.02%|

Tests were performed using:

- ef_construction 128
- ef_search 128
- k 100
- full vector stored in the table 
- Amazon linux2
- gcc 12.4.0
- binutils 2.39 

_Note:  gcc >= 12 &  binutils >= 2.38 are required for this change to have any effect.   Upgrading gcc, without binutils can cause  pgvector's make to fail._



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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2025-01-06 23:09 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: akashsha1 (@akashsha1) @ 2025-01-06 23:09 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> @lucagiac81
> 
> I tested the latest revision [a1e3ead](https://github.com/pgvector/pgvector/pull/531/commits/a1e3eadd0ed24092e7d93da32c6e183ae3efb210) using vectordbbench on a r7i.8xlarge instance and achieved qps improvements ranging from 7% to 23%, depending on the dataset.
> 
> Dataset	qps	recall	with avx512 qps	qps improvement	with avx512 recall	recallimpact
> Performance1536D50K	10644.763	0.9691	12594.4903	18.32%	0.9626	-0.67%
> Performance1536D5M	6810.1588	0.9338	7332.7366	7.67%	0.927	-0.73%
> Performance768D10M	7916.9702	0.8975	9799.3695	23.78%	0.8949	-0.29%
> Performance768D1M	9847.2079	0.926	11043.1437	12.14%	0.9262	0.02%
> Tests were performed using:
> 
> * ef_construction 128
> * ef_search 128
> * k 100
> * full vector stored in the table
> * Amazon linux2
> * gcc 12.4.0
> * binutils 2.39
> 
> _Note: gcc >= 12 & binutils >= 2.38 are required for this change to have any effect. Upgrading gcc, without binutils can cause make to fail._

@greenhal thanks for sharing these. This is great improvements. 
@jkatz , @nathan-bossart , @ankane - 23% improvements seem like a solid improvement on AWS instances to consider. The PR has also been simplified to automatically take advantage of the new instructions in avx512. Would you be able to help provide any feedback here, and help merge this change?  

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2025-04-10 20:11 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: lucagiac81 (@lucagiac81) @ 2025-04-10 20:11 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

We'd like to propose a refactoring to make platform-specific optimizations easier to maintain.

In the latest update, AVX-512 functions are moved to separate files. The functions are also included by conditional compilation (enabled by default). In this way, AVX-512 implementations are all in one place, and they can be easily disabled in the build if desired. 
AVX-512 feature detection is currently in the same files. In the future, we could also move detection to a common location if duplication becomes a concern.

This approach is easily extended to future contributions and different architectures. This will allow pgvector to benefit from targeted optimizations while keeping the "core" code uncluttered. It will also clarify where particular expertise is needed for maintenance and improvements.

@ankane do you see this as a viable approach to integrate these optimizations? Please let us know your thoughts.

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2025-04-10 21:03 ` "ankane (@ankane)" <noreply+ankane@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: ankane (@ankane) @ 2025-04-10 21:03 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @lucagiac81, thanks again for the PR, but I don't think it's a good fit for pgvector. Changing the accumulation precision can reduce recall (as @greenhal's tests show), and there is already a separate lever for trading recall for speed (`ef_search`).

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

* Re: [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions
@ 2025-04-10 21:03 ` "ankane (@ankane)" <noreply+ankane@github.com>
  30 siblings, 0 replies; 32+ messages in thread

From: ankane (@ankane) @ 2025-04-10 21:03 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

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


end of thread, other threads:[~2025-04-10 21:03 UTC | newest]

Thread overview: 32+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-04-24 14:28 [pgvector/pgvector] PR #531: Add AVX-512 FP16 implementation of halfvec distance functions "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-24 14:45 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-04-24 16:28 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
2024-04-24 16:29 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
2024-04-24 16:32 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
2024-04-24 16:35 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
2024-04-24 16:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-04-24 17:34 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-04-25 00:56 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-25 01:00 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-25 02:49 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-25 19:54 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-25 20:01 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-04-26 23:52 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
2024-04-26 23:54 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
2024-04-27 00:07 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
2024-04-29 20:52 ` "nathan-bossart (@nathan-bossart)" <noreply+nathan-bossart@github.com>
2024-05-14 03:18 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-05-14 03:19 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-05-14 15:30 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-05-16 19:36 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-09-24 20:44 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-09-24 22:56 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-09-25 00:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-21 22:15 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-11-12 20:48 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2024-11-21 22:33 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2025-01-06 21:57 ` "greenhal (@greenhal)" <noreply+greenhal@github.com>
2025-01-06 23:09 ` "akashsha1 (@akashsha1)" <noreply+akashsha1@github.com>
2025-04-10 20:11 ` "lucagiac81 (@lucagiac81)" <noreply+lucagiac81@github.com>
2025-04-10 21:03 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-04-10 21:03 ` "ankane (@ankane)" <noreply+ankane@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