From: zthhhhh (@zthhhhh) <noreply+zthhhhh@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #927: Support sq16 in hnsw access method with vector_cosine_ops
Date: Wed, 19 Nov 2025 07:05:27 +0000
Message-ID: <gh-pgvector-pgvector-927@github.com> (raw)
Hi pgvector teams,
In this pull request, I would like to add a new operator class family for hnsw access method, and it is used to enhance the performance when conducting vector search based on cosine distance.
# Theory
In the calculation of vector cosine distance, what we focus on is the direction of each vector. That is to say, If a coefficient is multiplied in each dimension of the vector, this will not lead to the final calculation result of the cosine distance, without considering the loss of accuracy. So we can use an int16 to represent the value of each dimension and use the avx512 instruction to optimize the distance calculation function.
This has already been supported and verified to be feasible in some open-source databases, such as mariadb mhnsw index.
relevant code:
https://github.com/MariaDB/server/blob/main/sql/vector_mhnsw.cc#L898
# Performance
I run ann-benchmark in my test machine with 'dbpedia-openai-1000k-angular' dataset, setup enough large `shared_buffers` and `maintenance_work_mem` to eliminate the impact of disk I/O during index building and vector search phase, and it shows promising results. Under the same recall rate, we achieved a higher qps.
<img width="979" height="646" alt="image" src="https://github.com/user-attachments/assets/3d6223b4-7a2a-427b-a50c-408891faa32a"; />
Moreover, the construction time has been increased from 1517.7 seconds to 936.4 seconds, using the same index build parameter.
In addition, I noticed that hnsw will have a significant performance regression when memory is limited, there are some solutions for this question, such as PQ. Would the pgvector team like have plans to support them?
inline patch 1: Makefile, sql/vector.sql, src/vector.c and 3 more (+223/-0 lines) download inline-1.patchdiff --git a/Makefile b/Makefileindex d98d73b8c..9a2a9209f 100644--- a/Makefile+++ b/Makefile@@ -32,6 +32,12 @@ endif
# - Clang (could use pragma instead) - https://llvm.org/docs/Vectorizers.html
PG_CFLAGS += $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math
+ARCH := $(shell uname -m)+ifeq ($(ARCH),x86_64)+PG_CFLAGS += -mavx512f -mavx512dq -mavx512vnni+COMPILE.c.bc = $(CLANG) -Wno-ignored-attributes $(BITCODE_CFLAGS) $(CPPFLAGS) -flto=thin -emit-llvm -c -mavx512f -mavx512dq -mavx512vnni -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math+endif+
# Debug GCC auto-vectorization
# PG_CFLAGS += -fopt-info-vec
diff --git a/sql/vector.sql b/sql/vector.sqlindex 7fc36712b..eb1c8887d 100644--- a/sql/vector.sql+++ b/sql/vector.sql@@ -916,3 +916,25 @@ CREATE OPERATOR CLASS sparsevec_l1_ops
OPERATOR 1 <+> (sparsevec, sparsevec) FOR ORDER BY float_ops,
FUNCTION 1 l1_distance(sparsevec, sparsevec),
FUNCTION 3 hnsw_sparsevec_support(internal);
++-- TODO:+-- 1. Move these code into upgrade sql file.+-- 2. More appropriate location in vector.sql+CREATE FUNCTION vector_negative_inner_product_avx512(internal, internal) RETURNS float8+ AS 'MODULE_PATHNAME' LANGUAGE C;++CREATE FUNCTION vector_should_insert_hnsw(vector) RETURNS float8+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION vec_normalize_i16(internal) RETURNS internal+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sq16_hnsw_vec_support(internal) RETURNS internal+ AS 'MODULE_PATHNAME' LANGUAGE C;++CREATE OPERATOR CLASS sq16_vector_cosine_ops+ FOR TYPE vector USING hnsw AS+ OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,+ FUNCTION 1 vector_negative_inner_product_avx512(internal, internal),+ FUNCTION 2 vector_should_insert_hnsw(vector),+ FUNCTION 3 sq16_hnsw_vec_support(internal);diff --git a/src/vector.c b/src/vector.cindex 03f70d601..765619a1c 100644--- a/src/vector.c+++ b/src/vector.c@@ -22,6 +22,10 @@
#include "utils/numeric.h"
#include "vector.h"
+#if defined(__x86_64__)+#include <immintrin.h>+#endif+
#if PG_VERSION_NUM >= 160000
#include "varatt.h"
#endif
@@ -54,6 +58,65 @@ _PG_init(void)
IvfflatInit();
}
+#if defined(__x86_64__)+static inline int64+VectorNegativeProduct_avx512_vnni(int16 n, const int16 *a, const int16 *b)+{+ __m512i sum32_0 = _mm512_setzero_si512();+ __m512i sum32_1 = _mm512_setzero_si512();+ __m512i sum32_2 = _mm512_setzero_si512();+ __m512i sum32_3 = _mm512_setzero_si512();++ __m512i sum32;+ __m512i acc_lo;+ __m512i acc_hi;+ int64 total = 0;++ int16 i = 0;++ for (; i + 127 < n; i += 128)+ {+ __m512i a0 = _mm512_loadu_si512((const __m512i *)(a + i));+ __m512i a1 = _mm512_loadu_si512((const __m512i *)(a + i + 32));+ __m512i a2 = _mm512_loadu_si512((const __m512i *)(a + i + 64));+ __m512i a3 = _mm512_loadu_si512((const __m512i *)(a + i + 96));++ __m512i b0 = _mm512_loadu_si512((const __m512i *)(b + i));+ __m512i b1 = _mm512_loadu_si512((const __m512i *)(b + i + 32));+ __m512i b2 = _mm512_loadu_si512((const __m512i *)(b + i + 64));+ __m512i b3 = _mm512_loadu_si512((const __m512i *)(b + i + 96));++ sum32_0 = _mm512_dpwssd_epi32(sum32_0, a0, b0);+ sum32_1 = _mm512_dpwssd_epi32(sum32_1, a1, b1);+ sum32_2 = _mm512_dpwssd_epi32(sum32_2, a2, b2);+ sum32_3 = _mm512_dpwssd_epi32(sum32_3, a3, b3);+ }++ for (; i + 31 < n; i += 32)+ {+ __m512i a_vec = _mm512_loadu_si512((const __m512i *)(a + i));+ __m512i b_vec = _mm512_loadu_si512((const __m512i *)(b + i));++ sum32_0 = _mm512_dpwssd_epi32(sum32_0, a_vec, b_vec);+ }++ sum32 = _mm512_add_epi32(_mm512_add_epi32(sum32_0, sum32_1),+ _mm512_add_epi32(sum32_2, sum32_3));++ acc_lo = _mm512_cvtepi32_epi64(_mm512_extracti32x8_epi32(sum32, 0));+ acc_hi = _mm512_cvtepi32_epi64(_mm512_extracti32x8_epi32(sum32, 1));++ total = _mm512_reduce_add_epi64(acc_lo) + _mm512_reduce_add_epi64(acc_hi);++ for (; i < n; i++)+ {+ total += (int32)a[i] * (int32)b[i];+ }++ return -total;+}+#endif+
/*
* Ensure same dimensions
*/
@@ -129,6 +192,20 @@ InitVector(int dim)
return result;
}
+VectorI16 *+InitVectorI16(int dim)+{+ VectorI16 *result = NULL;+ int size;++ size = VECTOR_SIZE_I16(dim);+ result = (VectorI16 *) palloc(size);+ SET_VARSIZE(result, size);+ result->dim = dim;++ return result;+}+
/*
* Check for whitespace, since array_isspace() is static
*/
@@ -807,6 +884,88 @@ l2_normalize(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(vector_negative_inner_product_avx512);+Datum+vector_negative_inner_product_avx512(PG_FUNCTION_ARGS)+{+ VectorI16 *a = PG_GETARG_VECTORI16_P(0);+ VectorI16 *b = PG_GETARG_VECTORI16_P(1);+ int64 negative_product = 0;++#if defined(__x86_64__)+ negative_product = VectorNegativeProduct_avx512_vnni(a->dim, (int16 *) a->x, (int16 *) b->x);+#else+ elog(ERROR, "Operator class sq16_vector_cosine_ops is not supprted in arm")+#endif++ PG_RETURN_FLOAT8((double) negative_product / (a->dot_product * b->dot_product));+}++FUNCTION_PREFIX PG_FUNCTION_INFO_V1(vector_should_insert_hnsw);+Datum+vector_should_insert_hnsw(PG_FUNCTION_ARGS)+{+ Vector *a = PG_GETARG_VECTOR_P(0);+ float *ax = a->x;+ float ret = 0.0;+++ for (int i = 0, imax = a->dim; i < imax; i++)+ {+ if (ax[i] != 0)+ {+ ret = 1.0;+ break;+ }+ }++ PG_RETURN_FLOAT8(ret);+}++FUNCTION_PREFIX PG_FUNCTION_INFO_V1(vec_normalize_i16);+Datum+vec_normalize_i16(PG_FUNCTION_ARGS)+{+ Vector *a = PG_GETARG_VECTOR_P(0);+ VectorI16 *result = NULL;+ int16 *rx = NULL;+ double dot_product = 0;+ float max_element = 0;+ double scale = 0;+ + result = InitVectorI16(a->dim);+ rx = (int16 *) result->x;+ + for (int i = 0; i < a->dim; ++i)+ max_element = Max(fabs(a->x[i]), max_element);+ + scale = max_element / INT16_MAX;+ + for (int i = 0; i < a->dim; ++i)+ {+ rx[i] = (int16) round(a->x[i] / scale);+ dot_product += rx[i] * rx[i];+ }+ + result->dot_product = sqrt(dot_product);+ + PG_RETURN_POINTER(result);+}++FUNCTION_PREFIX PG_FUNCTION_INFO_V1(sq16_hnsw_vec_support);+Datum+sq16_hnsw_vec_support(PG_FUNCTION_ARGS)+{+ static const HnswTypeInfo typeInfo =+ {+ .maxDimensions = HNSW_MAX_DIM,+ .normalize = vec_normalize_i16,+ .checkValue = NULL+ };++ PG_RETURN_POINTER(&typeInfo);+};+
/*
* Add vectors
*/
diff --git a/src/vector.h b/src/vector.hindex e29ccdc6a..ec17ad70c 100644--- a/src/vector.h+++ b/src/vector.h@@ -1,6 +1,8 @@
#ifndef VECTOR_H
#define VECTOR_H
+#include <stdalign.h>+
#define VECTOR_MAX_DIM 16000
#define VECTOR_SIZE(_dim) (offsetof(Vector, x) + sizeof(float)*(_dim))
@@ -20,6 +22,22 @@ Vector *InitVector(int dim);
void PrintVector(char *msg, Vector * vector);
int vector_cmp_internal(Vector * a, Vector * b);
+#define VECTOR_SIZE_I16(_dim) (offsetof(VectorI16, x) + sizeof(int16) * (_dim))+#define DatumGetVectorI16(x) ((VectorI16 *) PG_DETOAST_DATUM(x))+#define PG_GETARG_VECTORI16_P(x) DatumGetVectorI16(PG_GETARG_DATUM(x))+#define PG_RETURN_VECTORI16_P(x) PG_RETURN_POINTER(x)++typedef struct VectorI16+{+ int32 vl_len_;+ int16 dim;+ int16 unused;+ double dot_product;+ alignas(64) int16 x[FLEXIBLE_ARRAY_MEMBER];+} VectorI16;++VectorI16 *InitVectorI16(int dim);+
/* TODO Move to better place */
#if PG_VERSION_NUM >= 160000
#define FUNCTION_PREFIX
diff --git a/test/t/012_hnsw_vector_build_recall.pl b/test/t/012_hnsw_vector_build_recall.plindex 9358874aa..011787b4d 100644--- a/test/t/012_hnsw_vector_build_recall.pl+++ b/test/t/012_hnsw_vector_build_recall.pl@@ -3,12 +3,14 @@
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
+use Config;
my $node;
my @queries = ();
my @expected;
my $limit = 20;
my $array_sql = join(",", ('random() * random()') x 3);
+my $arch = $Config{archname};
sub test_recall
{
@@ -71,6 +73,13 @@ sub test_recall
my @operators = ("<->", "<#>", "<=>", "<+>");
my @opclasses = ("vector_l2_ops", "vector_ip_ops", "vector_cosine_ops", "vector_l1_ops");
+if ($arch =~ /x86/)+{+ print "x86 arch, run test case for sq16_vector_cosine_ops\n";+ push(@operators, "<=>");+ push(@opclasses, "sq16_vector_cosine_ops");+}+
for my $i (0 .. $#operators)
{
my $operator = $operators[$i];
diff --git a/test/t/013_hnsw_vector_insert_recall.pl b/test/t/013_hnsw_vector_insert_recall.plindex d2dfc01e7..11ec305d0 100644--- a/test/t/013_hnsw_vector_insert_recall.pl+++ b/test/t/013_hnsw_vector_insert_recall.pl@@ -3,12 +3,14 @@
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
+use Config;
my $node;
my @queries = ();
my @expected;
my $limit = 20;
my $array_sql = join(",", ('random() * random()') x 3);
+my $arch = $Config{archname};
sub test_recall
{
@@ -68,6 +70,13 @@ sub test_recall
my @operators = ("<->", "<#>", "<=>", "<+>");
my @opclasses = ("vector_l2_ops", "vector_ip_ops", "vector_cosine_ops", "vector_l1_ops");
+if ($arch =~ /x86/)+{+ print "x86 arch, run test case for sq16_vector_cosine_ops\n";+ push(@operators, "<=>");+ push(@opclasses, "sq16_vector_cosine_ops");+}+
for my $i (0 .. $#operators)
{
my $operator = $operators[$i];