pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
8+ messages / 3 participants
[nested] [flat]
* [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-13 20:39 "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
0 siblings, 0 replies; 8+ messages in thread
From: tkreuder (@tkreuder) @ 2026-04-13 20:39 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Adds a new int8vec data type that stores vector dimensions as signed 8-bit integers (-128 to 127), providing 4x storage reduction vs vector and 2x vs halfvec .
This addresses #521 — the request for int8 vector support, useful for embeddings that are already quantized to int8 (e.g. from models with int8 output or post-training quantization).
### Features
• Type: int8vec(n) with [1,-2,3] integer format
• Distance functions: L2, inner product, cosine, L1
• Operators: <-> , <#> , <=> , <+> , + , - , * , ||
• Index support: IVFFlat (L2, IP, cosine) and HNSW (L2, IP, cosine, L1)
• Casts: to/from vector , halfvec , sparsevec , and arrays ( integer[] , real[] , double precision[] , numeric[] )
• Aggregates: avg() , sum()
• Functions: l2_norm , l2_normalize , binary_quantize , subvector , vector_dims
• Comparisons: full btree support ( < , <= , = , <> , >= , > )
### Design
• Follows the existing halfvec pattern exactly
• Integer parsing with range validation (rejects floats, NaN, out-of-range)
• Distance computations use int32 accumulators (no overflow for int8 range × 16000 dims)
• Arithmetic operations error on int8 overflow
### Files
• New: int8vec.h , int8utils.h , int8utils.c , int8vec.c
• Modified: Makefile , vector.sql , vector.c , halfvec.c , sparsevec.c , hnswutils.c , ivfutils.c
• Tests: int8vec.sql , hnsw_int8vec.sql , ivfflat_int8vec.sql
### Usage
sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding int8vec(3));
INSERT INTO items (embedding) VALUES ('[1,-2,3]'), ('[4,5,6]');
CREATE INDEX ON items USING hnsw (embedding int8vec_l2_ops);
SELECT * FROM items ORDER BY embedding <-> '[0,0,0]' LIMIT 5;
-- Cast from float vectors (rounds to nearest int8)
SELECT '[1.7,-2.3,4.9]'::vector::int8vec; -- [2,-2,5]
inline patch 1: Makefile, sql/vector.sql, src/halfvec.c and 14 more (+2804/-2 lines) download inline-1.patch
diff --git a/Makefile b/Makefile
index 8bedb890a..b221964c4 100644
--- a/Makefile
+++ b/Makefile
@@ -4,8 +4,8 @@ EXTVERSION = 0.8.2
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
-HEADERS = src/halfvec.h src/sparsevec.h src/vector.h
+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/int8utils.o src/int8vec.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
+HEADERS = src/halfvec.h src/int8vec.h src/sparsevec.h src/vector.h
TESTS = $(wildcard test/sql/*.sql)
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
diff --git a/sql/vector.sql b/sql/vector.sql
index 7fc36712b..746e51c0d 100644
--- a/sql/vector.sql
+++ b/sql/vector.sql
@@ -278,6 +278,12 @@ CREATE FUNCTION hnsw_bit_support(internal) RETURNS internal
CREATE FUNCTION hnsw_sparsevec_support(internal) RETURNS internal
AS 'MODULE_PATHNAME' LANGUAGE C;
+CREATE FUNCTION ivfflat_int8vec_support(internal) RETURNS internal
+ AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION hnsw_int8vec_support(internal) RETURNS internal
+ AS 'MODULE_PATHNAME' LANGUAGE C;
+
-- vector opclasses
CREATE OPERATOR CLASS vector_ops
@@ -647,6 +653,334 @@ CREATE OPERATOR CLASS halfvec_l1_ops
FUNCTION 1 l1_distance(halfvec, halfvec),
FUNCTION 3 hnsw_halfvec_support(internal);
+-- int8vec type
+
+CREATE TYPE int8vec;
+
+CREATE FUNCTION int8vec_in(cstring, oid, integer) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_out(int8vec) RETURNS cstring
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_typmod_in(cstring[]) RETURNS integer
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_recv(internal, oid, integer) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_send(int8vec) RETURNS bytea
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE TYPE int8vec (
+ INPUT = int8vec_in,
+ OUTPUT = int8vec_out,
+ TYPMOD_IN = int8vec_typmod_in,
+ RECEIVE = int8vec_recv,
+ SEND = int8vec_send,
+ STORAGE = external
+);
+
+-- int8vec functions
+
+CREATE FUNCTION l2_distance(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME', 'int8vec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION inner_product(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME', 'int8vec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION cosine_distance(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME', 'int8vec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION l1_distance(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME', 'int8vec_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION vector_dims(int8vec) RETURNS integer
+ AS 'MODULE_PATHNAME', 'int8vec_vector_dims' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION l2_norm(int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME', 'int8vec_l2_norm' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION l2_normalize(int8vec) RETURNS int8vec
+ AS 'MODULE_PATHNAME', 'int8vec_l2_normalize' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION binary_quantize(int8vec) RETURNS bit
+ AS 'MODULE_PATHNAME', 'int8vec_binary_quantize' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION subvector(int8vec, int, int) RETURNS int8vec
+ AS 'MODULE_PATHNAME', 'int8vec_subvector' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+-- int8vec private functions
+
+CREATE FUNCTION int8vec_add(int8vec, int8vec) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_sub(int8vec, int8vec) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_mul(int8vec, int8vec) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_concat(int8vec, int8vec) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_lt(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_le(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_eq(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_ne(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_ge(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_gt(int8vec, int8vec) RETURNS bool
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_cmp(int8vec, int8vec) RETURNS int4
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_l2_squared_distance(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_negative_inner_product(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_spherical_distance(int8vec, int8vec) RETURNS float8
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_accum(double precision[], int8vec) RETURNS double precision[]
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_avg(double precision[]) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_combine(double precision[], double precision[]) RETURNS double precision[]
+ AS 'MODULE_PATHNAME', 'vector_combine' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+-- int8vec aggregates
+
+CREATE AGGREGATE avg(int8vec) (
+ SFUNC = int8vec_accum,
+ STYPE = double precision[],
+ FINALFUNC = int8vec_avg,
+ COMBINEFUNC = int8vec_combine,
+ INITCOND = '{0}',
+ PARALLEL = SAFE
+);
+
+CREATE AGGREGATE sum(int8vec) (
+ SFUNC = int8vec_add,
+ STYPE = int8vec,
+ COMBINEFUNC = int8vec_add,
+ PARALLEL = SAFE
+);
+
+-- int8vec cast functions
+
+CREATE FUNCTION int8vec(int8vec, integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_to_vector(int8vec, integer, boolean) RETURNS vector
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION vector_to_int8vec(vector, integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_to_halfvec(int8vec, integer, boolean) RETURNS halfvec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION halfvec_to_int8vec(halfvec, integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION array_to_int8vec(integer[], integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION array_to_int8vec(real[], integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION array_to_int8vec(double precision[], integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION array_to_int8vec(numeric[], integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_to_float4(int8vec, integer, boolean) RETURNS real[]
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+-- int8vec casts
+
+CREATE CAST (int8vec AS int8vec)
+ WITH FUNCTION int8vec(int8vec, integer, boolean) AS IMPLICIT;
+
+CREATE CAST (int8vec AS vector)
+ WITH FUNCTION int8vec_to_vector(int8vec, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (vector AS int8vec)
+ WITH FUNCTION vector_to_int8vec(vector, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (int8vec AS halfvec)
+ WITH FUNCTION int8vec_to_halfvec(int8vec, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (halfvec AS int8vec)
+ WITH FUNCTION halfvec_to_int8vec(halfvec, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (int8vec AS real[])
+ WITH FUNCTION int8vec_to_float4(int8vec, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (integer[] AS int8vec)
+ WITH FUNCTION array_to_int8vec(integer[], integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (real[] AS int8vec)
+ WITH FUNCTION array_to_int8vec(real[], integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (double precision[] AS int8vec)
+ WITH FUNCTION array_to_int8vec(double precision[], integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (numeric[] AS int8vec)
+ WITH FUNCTION array_to_int8vec(numeric[], integer, boolean) AS ASSIGNMENT;
+
+-- int8vec operators
+
+CREATE OPERATOR <-> (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = l2_distance,
+ COMMUTATOR = '<->'
+);
+
+CREATE OPERATOR <#> (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_negative_inner_product,
+ COMMUTATOR = '<#>'
+);
+
+CREATE OPERATOR <=> (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = cosine_distance,
+ COMMUTATOR = '<=>'
+);
+
+CREATE OPERATOR <+> (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = l1_distance,
+ COMMUTATOR = '<+>'
+);
+
+CREATE OPERATOR + (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_add,
+ COMMUTATOR = +
+);
+
+CREATE OPERATOR - (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_sub
+);
+
+CREATE OPERATOR * (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_mul,
+ COMMUTATOR = *
+);
+
+CREATE OPERATOR || (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_concat
+);
+
+CREATE OPERATOR < (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_lt,
+ COMMUTATOR = > , NEGATOR = >= ,
+ RESTRICT = scalarltsel, JOIN = scalarltjoinsel
+);
+
+CREATE OPERATOR <= (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_le,
+ COMMUTATOR = >= , NEGATOR = > ,
+ RESTRICT = scalarlesel, JOIN = scalarlejoinsel
+);
+
+CREATE OPERATOR = (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_eq,
+ COMMUTATOR = = , NEGATOR = <> ,
+ RESTRICT = eqsel, JOIN = eqjoinsel
+);
+
+CREATE OPERATOR <> (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_ne,
+ COMMUTATOR = <> , NEGATOR = = ,
+ RESTRICT = eqsel, JOIN = eqjoinsel
+);
+
+CREATE OPERATOR >= (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_ge,
+ COMMUTATOR = <= , NEGATOR = < ,
+ RESTRICT = scalargesel, JOIN = scalargejoinsel
+);
+
+CREATE OPERATOR > (
+ LEFTARG = int8vec, RIGHTARG = int8vec, PROCEDURE = int8vec_gt,
+ COMMUTATOR = < , NEGATOR = <= ,
+ RESTRICT = scalargtsel, JOIN = scalargtjoinsel
+);
+
+-- int8vec opclasses
+
+CREATE OPERATOR CLASS int8vec_ops
+ DEFAULT FOR TYPE int8vec USING btree AS
+ OPERATOR 1 < ,
+ OPERATOR 2 <= ,
+ OPERATOR 3 = ,
+ OPERATOR 4 >= ,
+ OPERATOR 5 > ,
+ FUNCTION 1 int8vec_cmp(int8vec, int8vec);
+
+CREATE OPERATOR CLASS int8vec_l2_ops
+ FOR TYPE int8vec USING ivfflat AS
+ OPERATOR 1 <-> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_l2_squared_distance(int8vec, int8vec),
+ FUNCTION 3 l2_distance(int8vec, int8vec),
+ FUNCTION 5 ivfflat_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_ip_ops
+ FOR TYPE int8vec USING ivfflat AS
+ OPERATOR 1 <#> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_negative_inner_product(int8vec, int8vec),
+ FUNCTION 3 int8vec_spherical_distance(int8vec, int8vec),
+ FUNCTION 4 l2_norm(int8vec),
+ FUNCTION 5 ivfflat_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_cosine_ops
+ FOR TYPE int8vec USING ivfflat AS
+ OPERATOR 1 <=> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_negative_inner_product(int8vec, int8vec),
+ FUNCTION 2 l2_norm(int8vec),
+ FUNCTION 3 int8vec_spherical_distance(int8vec, int8vec),
+ FUNCTION 4 l2_norm(int8vec),
+ FUNCTION 5 ivfflat_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_l2_ops
+ FOR TYPE int8vec USING hnsw AS
+ OPERATOR 1 <-> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_l2_squared_distance(int8vec, int8vec),
+ FUNCTION 3 hnsw_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_ip_ops
+ FOR TYPE int8vec USING hnsw AS
+ OPERATOR 1 <#> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_negative_inner_product(int8vec, int8vec),
+ FUNCTION 3 hnsw_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_cosine_ops
+ FOR TYPE int8vec USING hnsw AS
+ OPERATOR 1 <=> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 int8vec_negative_inner_product(int8vec, int8vec),
+ FUNCTION 2 l2_norm(int8vec),
+ FUNCTION 3 hnsw_int8vec_support(internal);
+
+CREATE OPERATOR CLASS int8vec_l1_ops
+ FOR TYPE int8vec USING hnsw AS
+ OPERATOR 1 <+> (int8vec, int8vec) FOR ORDER BY float_ops,
+ FUNCTION 1 l1_distance(int8vec, int8vec),
+ FUNCTION 3 hnsw_int8vec_support(internal);
+
-- bit functions
CREATE FUNCTION hamming_distance(bit, bit) RETURNS float8
@@ -916,3 +1250,17 @@ 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);
+
+-- sparsevec <-> int8vec casts (after both types defined)
+
+CREATE FUNCTION sparsevec_to_int8vec(sparsevec, integer, boolean) RETURNS int8vec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE FUNCTION int8vec_to_sparsevec(int8vec, integer, boolean) RETURNS sparsevec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
+CREATE CAST (sparsevec AS int8vec)
+ WITH FUNCTION sparsevec_to_int8vec(sparsevec, integer, boolean) AS ASSIGNMENT;
+
+CREATE CAST (int8vec AS sparsevec)
+ WITH FUNCTION int8vec_to_sparsevec(int8vec, integer, boolean) AS ASSIGNMENT;
diff --git a/src/halfvec.c b/src/halfvec.c
index 377114692..19200d03c 100644
--- a/src/halfvec.c
+++ b/src/halfvec.c
@@ -8,6 +8,7 @@
#include "fmgr.h"
#include "halfutils.h"
#include "halfvec.h"
+#include "int8vec.h"
#include "lib/stringinfo.h"
#include "libpq/pqformat.h"
#include "port.h" /* for strtof() */
@@ -1209,3 +1210,25 @@ sparsevec_to_halfvec(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+
+/*
+ * Convert int8 vector to half vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_to_halfvec);
+Datum
+int8vec_to_halfvec(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ HalfVector *result;
+
+ CheckDim(vec->dim);
+ CheckExpectedDim(typmod, vec->dim);
+
+ result = InitHalfVector(vec->dim);
+
+ for (int i = 0; i < vec->dim; i++)
+ result->x[i] = Float4ToHalfUnchecked((float) vec->x[i]);
+
+ PG_RETURN_POINTER(result);
+}
diff --git a/src/hnswutils.c b/src/hnswutils.c
index f4e4d824b..b953574f4 100644
--- a/src/hnswutils.c
+++ b/src/hnswutils.c
@@ -7,6 +7,7 @@
#include "common/hashfn.h"
#include "fmgr.h"
#include "hnsw.h"
+#include "int8vec.h"
#include "lib/pairingheap.h"
#include "nodes/pg_list.h"
#include "port/atomics.h"
@@ -1354,6 +1355,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
PGDLLEXPORT Datum l2_normalize(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum halfvec_l2_normalize(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum sparsevec_l2_normalize(PG_FUNCTION_ARGS);
+PGDLLEXPORT Datum int8vec_l2_normalize(PG_FUNCTION_ARGS);
static void
SparsevecCheckValue(Pointer v)
@@ -1426,3 +1428,16 @@ hnsw_sparsevec_support(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(&typeInfo);
}
+
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(hnsw_int8vec_support);
+Datum
+hnsw_int8vec_support(PG_FUNCTION_ARGS)
+{
+ static const HnswTypeInfo typeInfo = {
+ .maxDimensions = HNSW_MAX_DIM * 4,
+ .normalize = int8vec_l2_normalize,
+ .checkValue = NULL
+ };
+
+ PG_RETURN_POINTER(&typeInfo);
+}
diff --git a/src/int8utils.c b/src/int8utils.c
new file mode 100644
index 000000000..e45fd814e
--- /dev/null
+++ b/src/int8utils.c
@@ -0,0 +1,86 @@
+#include "postgres.h"
+
+#include <math.h>
+
+#include "int8utils.h"
+#include "int8vec.h"
+
+float (*Int8vecL2SquaredDistance) (int dim, int8 *ax, int8 *bx);
+float (*Int8vecInnerProduct) (int dim, int8 *ax, int8 *bx);
+double (*Int8vecCosineSimilarity) (int dim, int8 *ax, int8 *bx);
+float (*Int8vecL1Distance) (int dim, int8 *ax, int8 *bx);
+
+static float
+Int8vecL2SquaredDistanceDefault(int dim, int8 *ax, int8 *bx)
+{
+ int32 distance = 0;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < dim; i++)
+ {
+ int32 diff = (int32) ax[i] - (int32) bx[i];
+
+ distance += diff * diff;
+ }
+
+ return (float) distance;
+}
+
+static float
+Int8vecInnerProductDefault(int dim, int8 *ax, int8 *bx)
+{
+ int32 distance = 0;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < dim; i++)
+ distance += (int32) ax[i] * (int32) bx[i];
+
+ return (float) distance;
+}
+
+static double
+Int8vecCosineSimilarityDefault(int dim, int8 *ax, int8 *bx)
+{
+ int32 similarity = 0;
+ int32 norma = 0;
+ int32 normb = 0;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < dim; i++)
+ {
+ int32 axi = (int32) ax[i];
+ int32 bxi = (int32) bx[i];
+
+ similarity += axi * bxi;
+ norma += axi * axi;
+ normb += bxi * bxi;
+ }
+
+ /* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
+ return (double) similarity / sqrt((double) norma * (double) normb);
+}
+
+static float
+Int8vecL1DistanceDefault(int dim, int8 *ax, int8 *bx)
+{
+ int32 distance = 0;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < dim; i++)
+ {
+ int32 diff = (int32) ax[i] - (int32) bx[i];
+
+ distance += (diff >= 0) ? diff : -diff;
+ }
+
+ return (float) distance;
+}
+
+void
+Int8vecInit(void)
+{
+ Int8vecL2SquaredDistance = Int8vecL2SquaredDistanceDefault;
+ Int8vecInnerProduct = Int8vecInnerProductDefault;
+ Int8vecCosineSimilarity = Int8vecCosineSimilarityDefault;
+ Int8vecL1Distance = Int8vecL1DistanceDefault;
+}
diff --git a/src/int8utils.h b/src/int8utils.h
new file mode 100644
index 000000000..e7727e0b5
--- /dev/null
+++ b/src/int8utils.h
@@ -0,0 +1,13 @@
+#ifndef INT8UTILS_H
+#define INT8UTILS_H
+
+#include "int8vec.h"
+
+extern float (*Int8vecL2SquaredDistance) (int dim, int8 *ax, int8 *bx);
+extern float (*Int8vecInnerProduct) (int dim, int8 *ax, int8 *bx);
+extern double (*Int8vecCosineSimilarity) (int dim, int8 *ax, int8 *bx);
+extern float (*Int8vecL1Distance) (int dim, int8 *ax, int8 *bx);
+
+void Int8vecInit(void);
+
+#endif
diff --git a/src/int8vec.c b/src/int8vec.c
new file mode 100644
index 000000000..7f638f294
--- /dev/null
+++ b/src/int8vec.c
@@ -0,0 +1,1215 @@
+#include "postgres.h"
+
+#include <math.h>
+
+#include "bitvec.h"
+#include "catalog/pg_type.h"
+#include "fmgr.h"
+#include "halfutils.h"
+#include "halfvec.h"
+#include "int8utils.h"
+#include "int8vec.h"
+#include "lib/stringinfo.h"
+#include "libpq/pqformat.h"
+#include "sparsevec.h"
+#include "utils/array.h"
+#include "utils/float.h"
+#include "utils/fmgrprotos.h"
+#include "utils/lsyscache.h"
+#include "utils/varbit.h"
+#include "vector.h"
+
+#if PG_VERSION_NUM >= 160000
+#include "varatt.h"
+#endif
+
+#if PG_VERSION_NUM >= 170000
+#include "parser/scansup.h"
+#endif
+
+#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
+#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
+
+/*
+ * Ensure same dimensions
+ */
+static inline void
+CheckDims(Int8Vector * a, Int8Vector * b)
+{
+ if (a->dim != b->dim)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("different int8vec dimensions %d and %d", a->dim, b->dim)));
+}
+
+/*
+ * Ensure expected dimensions
+ */
+static inline void
+CheckExpectedDim(int32 typmod, int dim)
+{
+ if (typmod != -1 && typmod != dim)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("expected %d dimensions, not %d", typmod, dim)));
+}
+
+/*
+ * Ensure valid dimensions
+ */
+static inline void
+CheckDim(int dim)
+{
+ if (dim < 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("int8vec must have at least 1 dimension")));
+
+ if (dim > INT8VEC_MAX_DIM)
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("int8vec cannot have more than %d dimensions", INT8VEC_MAX_DIM)));
+}
+
+/*
+ * Allocate and initialize a new int8 vector
+ */
+Int8Vector *
+InitInt8Vector(int dim)
+{
+ Int8Vector *result;
+ int size;
+
+ size = INT8VEC_SIZE(dim);
+ result = (Int8Vector *) palloc0(size);
+ SET_VARSIZE(result, size);
+ result->dim = dim;
+
+ return result;
+}
+
+#if PG_VERSION_NUM >= 170000
+#define int8vec_isspace(ch) scanner_isspace(ch)
+#else
+static inline bool
+int8vec_isspace(char ch)
+{
+ if (ch == ' ' ||
+ ch == '\t' ||
+ ch == '\n' ||
+ ch == '\r' ||
+ ch == '\v' ||
+ ch == '\f')
+ return true;
+ return false;
+}
+#endif
+
+/*
+ * Check state array
+ */
+static float8 *
+CheckStateArray(ArrayType *statearray, const char *caller)
+{
+ if (ARR_NDIM(statearray) != 1 ||
+ ARR_DIMS(statearray)[0] < 1 ||
+ ARR_HASNULL(statearray) ||
+ ARR_ELEMTYPE(statearray) != FLOAT8OID)
+ elog(ERROR, "%s: expected state array", caller);
+ return (float8 *) ARR_DATA_PTR(statearray);
+}
+
+/*
+ * Convert textual representation to internal representation
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_in);
+Datum
+int8vec_in(PG_FUNCTION_ARGS)
+{
+ char *lit = PG_GETARG_CSTRING(0);
+ int32 typmod = PG_GETARG_INT32(2);
+ int8 x[INT8VEC_MAX_DIM];
+ int dim = 0;
+ char *pt = lit;
+ Int8Vector *result;
+
+ while (int8vec_isspace(*pt))
+ pt++;
+
+ if (*pt != '[')
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit),
+ errdetail("Vector contents must start with \"[\".")));
+
+ pt++;
+
+ while (int8vec_isspace(*pt))
+ pt++;
+
+ if (*pt == ']')
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("int8vec must have at least 1 dimension")));
+
+ for (;;)
+ {
+ long val;
+ char *stringEnd;
+
+ if (dim == INT8VEC_MAX_DIM)
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("int8vec cannot have more than %d dimensions", INT8VEC_MAX_DIM)));
+
+ while (int8vec_isspace(*pt))
+ pt++;
+
+ /* Check for empty string */
+ if (*pt == '\0')
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit)));
+
+ errno = 0;
+ val = strtol(pt, &stringEnd, 10);
+
+ if (stringEnd == pt)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit)));
+
+ /* Reject non-integer input (no decimal point, no 'e') */
+ if (*stringEnd == '.' || *stringEnd == 'e' || *stringEnd == 'E')
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit),
+ errdetail("int8vec values must be integers.")));
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("\"%ld\" is out of range for type int8vec", val),
+ errdetail("int8vec values must be between -128 and 127.")));
+
+ x[dim] = (int8) val;
+ dim++;
+
+ pt = stringEnd;
+
+ while (int8vec_isspace(*pt))
+ pt++;
+
+ if (*pt == ',')
+ pt++;
+ else if (*pt == ']')
+ {
+ pt++;
+ break;
+ }
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit)));
+ }
+
+ /* Only whitespace is allowed after the closing brace */
+ while (int8vec_isspace(*pt))
+ pt++;
+
+ if (*pt != '\0')
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("invalid input syntax for type int8vec: \"%s\"", lit),
+ errdetail("Junk after closing right brace.")));
+
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ result = InitInt8Vector(dim);
+ for (int i = 0; i < dim; i++)
+ result->x[i] = x[i];
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert internal representation to textual representation
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_out);
+Datum
+int8vec_out(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vector = PG_GETARG_INT8VEC_P(0);
+ int dim = vector->dim;
+ char *buf;
+ char *ptr;
+
+ /*
+ * Need:
+ *
+ * dim * 4 bytes max for "-128"
+ *
+ * dim - 1 bytes for separator
+ *
+ * 3 bytes for [, ], and \0
+ */
+ buf = (char *) palloc(5 * dim + 2);
+ ptr = buf;
+
+ *ptr++ = '[';
+
+ for (int i = 0; i < dim; i++)
+ {
+ if (i > 0)
+ *ptr++ = ',';
+
+ ptr += sprintf(ptr, "%d", (int) vector->x[i]);
+ }
+
+ *ptr++ = ']';
+ *ptr = '\0';
+
+ PG_FREE_IF_COPY(vector, 0);
+ PG_RETURN_CSTRING(buf);
+}
+
+/*
+ * Convert type modifier
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_typmod_in);
+Datum
+int8vec_typmod_in(PG_FUNCTION_ARGS)
+{
+ ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
+ int32 *tl;
+ int n;
+
+ tl = ArrayGetIntegerTypmods(ta, &n);
+
+ if (n != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("invalid type modifier")));
+
+ if (*tl < 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("dimensions for type int8vec must be at least 1")));
+
+ if (*tl > INT8VEC_MAX_DIM)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("dimensions for type int8vec cannot exceed %d", INT8VEC_MAX_DIM)));
+
+ PG_RETURN_INT32(*tl);
+}
+
+/*
+ * Convert external binary representation to internal representation
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_recv);
+Datum
+int8vec_recv(PG_FUNCTION_ARGS)
+{
+ StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
+ int32 typmod = PG_GETARG_INT32(2);
+ Int8Vector *result;
+ int16 dim;
+ int16 unused;
+
+ dim = pq_getmsgint(buf, sizeof(int16));
+ unused = pq_getmsgint(buf, sizeof(int16));
+
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ if (unused != 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("expected unused to be 0, not %d", unused)));
+
+ result = InitInt8Vector(dim);
+ for (int i = 0; i < dim; i++)
+ result->x[i] = (int8) pq_getmsgint(buf, sizeof(int8));
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert internal representation to the external binary representation
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_send);
+Datum
+int8vec_send(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ StringInfoData buf;
+
+ pq_begintypsend(&buf);
+ pq_sendint(&buf, vec->dim, sizeof(int16));
+ pq_sendint(&buf, vec->unused, sizeof(int16));
+ for (int i = 0; i < vec->dim; i++)
+ pq_sendint(&buf, (uint8) vec->x[i], sizeof(int8));
+
+ PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
+}
+
+/*
+ * Convert int8vec to int8vec
+ * This is needed to check the type modifier
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec);
+Datum
+int8vec(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+
+ CheckExpectedDim(typmod, vec->dim);
+
+ PG_RETURN_POINTER(vec);
+}
+
+/*
+ * Convert array to int8vec
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(array_to_int8vec);
+Datum
+array_to_int8vec(PG_FUNCTION_ARGS)
+{
+ ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Int8Vector *result;
+ int16 typlen;
+ bool typbyval;
+ char typalign;
+ Datum *elemsp;
+ int nelemsp;
+
+ if (ARR_NDIM(array) > 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("array must be 1-D")));
+
+ if (ARR_HASNULL(array) && array_contains_nulls(array))
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("array must not contain nulls")));
+
+ get_typlenbyvalalign(ARR_ELEMTYPE(array), &typlen, &typbyval, &typalign);
+ deconstruct_array(array, ARR_ELEMTYPE(array), typlen, typbyval, typalign, &elemsp, NULL, &nelemsp);
+
+ CheckDim(nelemsp);
+ CheckExpectedDim(typmod, nelemsp);
+
+ result = InitInt8Vector(nelemsp);
+
+ if (ARR_ELEMTYPE(array) == INT4OID)
+ {
+ for (int i = 0; i < nelemsp; i++)
+ {
+ int32 val = DatumGetInt32(elemsp[i]);
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("\"%d\" is out of range for type int8vec", val)));
+ result->x[i] = (int8) val;
+ }
+ }
+ else if (ARR_ELEMTYPE(array) == FLOAT8OID)
+ {
+ for (int i = 0; i < nelemsp; i++)
+ {
+ float8 val = DatumGetFloat8(elemsp[i]);
+ int32 ival = (int32) round(val);
+
+ if (ival < -128 || ival > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[i] = (int8) ival;
+ }
+ }
+ else if (ARR_ELEMTYPE(array) == FLOAT4OID)
+ {
+ for (int i = 0; i < nelemsp; i++)
+ {
+ float4 val = DatumGetFloat4(elemsp[i]);
+ int32 ival = (int32) roundf(val);
+
+ if (ival < -128 || ival > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[i] = (int8) ival;
+ }
+ }
+ else if (ARR_ELEMTYPE(array) == NUMERICOID)
+ {
+ for (int i = 0; i < nelemsp; i++)
+ {
+ float4 val = DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i]));
+ int32 ival = (int32) roundf(val);
+
+ if (ival < -128 || ival > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[i] = (int8) ival;
+ }
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("unsupported array type")));
+ }
+
+ pfree(elemsp);
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert int8vec to float4[]
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_to_float4);
+Datum
+int8vec_to_float4(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ Datum *datums;
+ ArrayType *result;
+
+ datums = (Datum *) palloc(sizeof(Datum) * vec->dim);
+
+ for (int i = 0; i < vec->dim; i++)
+ datums[i] = Float4GetDatum((float4) vec->x[i]);
+
+ /* Use TYPALIGN_INT for float4 */
+ result = construct_array(datums, vec->dim, FLOAT4OID, sizeof(float4), true, TYPALIGN_INT);
+
+ pfree(datums);
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert vector to int8vec
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(vector_to_int8vec);
+Datum
+vector_to_int8vec(PG_FUNCTION_ARGS)
+{
+ Vector *vec = PG_GETARG_VECTOR_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Int8Vector *result;
+
+ CheckDim(vec->dim);
+ CheckExpectedDim(typmod, vec->dim);
+
+ result = InitInt8Vector(vec->dim);
+
+ for (int i = 0; i < vec->dim; i++)
+ {
+ int32 val = (int32) roundf(vec->x[i]);
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[i] = (int8) val;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert halfvec to int8vec
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(halfvec_to_int8vec);
+Datum
+halfvec_to_int8vec(PG_FUNCTION_ARGS)
+{
+ HalfVector *vec = PG_GETARG_HALFVEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Int8Vector *result;
+
+ CheckDim(vec->dim);
+ CheckExpectedDim(typmod, vec->dim);
+
+ result = InitInt8Vector(vec->dim);
+
+ for (int i = 0; i < vec->dim; i++)
+ {
+ float val = HalfToFloat4(vec->x[i]);
+ int32 ival = (int32) roundf(val);
+
+ if (ival < -128 || ival > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[i] = (int8) ival;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Get the L2 distance between int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_l2_distance);
+Datum
+int8vec_l2_distance(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ CheckDims(a, b);
+
+ PG_RETURN_FLOAT8(sqrt((double) Int8vecL2SquaredDistance(a->dim, a->x, b->x)));
+}
+
+/*
+ * Get the L2 squared distance between int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_l2_squared_distance);
+Datum
+int8vec_l2_squared_distance(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ CheckDims(a, b);
+
+ PG_RETURN_FLOAT8((double) Int8vecL2SquaredDistance(a->dim, a->x, b->x));
+}
+
+/*
+ * Get the inner product of two int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_inner_product);
+Datum
+int8vec_inner_product(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ CheckDims(a, b);
+
+ PG_RETURN_FLOAT8((double) Int8vecInnerProduct(a->dim, a->x, b->x));
+}
+
+/*
+ * Get the negative inner product of two int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_negative_inner_product);
+Datum
+int8vec_negative_inner_product(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ CheckDims(a, b);
+
+ PG_RETURN_FLOAT8((double) -Int8vecInnerProduct(a->dim, a->x, b->x));
+}
+
+/*
+ * Get the cosine distance between two int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_cosine_distance);
+Datum
+int8vec_cosine_distance(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ double similarity;
+
+ CheckDims(a, b);
+
+ similarity = Int8vecCosineSimilarity(a->dim, a->x, b->x);
+
+#ifdef _MSC_VER
+ /* /fp:fast may not propagate NaN */
+ if (isnan(similarity))
+ PG_RETURN_FLOAT8(NAN);
+#endif
+
+ /* Keep in range */
+ if (similarity > 1)
+ similarity = 1;
+ else if (similarity < -1)
+ similarity = -1;
+
+ PG_RETURN_FLOAT8(1 - similarity);
+}
+
+/*
+ * Get the distance for spherical k-means
+ * Currently uses angular distance since needs to satisfy triangle inequality
+ * Assumes inputs are unit vectors (skips norm)
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_spherical_distance);
+Datum
+int8vec_spherical_distance(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ double distance;
+
+ CheckDims(a, b);
+
+ distance = (double) Int8vecInnerProduct(a->dim, a->x, b->x);
+
+ /* Prevent NaN with acos with loss of precision */
+ if (distance > 1)
+ distance = 1;
+ else if (distance < -1)
+ distance = -1;
+
+ PG_RETURN_FLOAT8(acos(distance) / M_PI);
+}
+
+/*
+ * Get the L1 distance between two int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_l1_distance);
+Datum
+int8vec_l1_distance(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ CheckDims(a, b);
+
+ PG_RETURN_FLOAT8((double) Int8vecL1Distance(a->dim, a->x, b->x));
+}
+
+/*
+ * Get the dimensions of an int8 vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_vector_dims);
+Datum
+int8vec_vector_dims(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+
+ PG_RETURN_INT32(a->dim);
+}
+
+/*
+ * Get the L2 norm of an int8 vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_l2_norm);
+Datum
+int8vec_l2_norm(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ int8 *ax = a->x;
+ double norm = 0.0;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < a->dim; i++)
+ {
+ double axi = (double) ax[i];
+
+ norm += axi * axi;
+ }
+
+ PG_RETURN_FLOAT8(sqrt(norm));
+}
+
+/*
+ * Normalize an int8 vector with the L2 norm
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_l2_normalize);
+Datum
+int8vec_l2_normalize(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ int8 *ax = a->x;
+ double norm = 0;
+ Int8Vector *result;
+ int8 *rx;
+
+ result = InitInt8Vector(a->dim);
+ rx = result->x;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < a->dim; i++)
+ norm += (double) ax[i] * (double) ax[i];
+
+ norm = sqrt(norm);
+
+ /* Return zero vector for zero norm */
+ if (norm > 0)
+ {
+ for (int i = 0; i < a->dim; i++)
+ {
+ double val = ((double) ax[i] / norm) * 127.0;
+
+ /* Round to nearest int8 */
+ if (val >= 0)
+ rx[i] = (int8) (val + 0.5 > 127.0 ? 127 : (int32) (val + 0.5));
+ else
+ rx[i] = (int8) (val - 0.5 < -128.0 ? -128 : (int32) (val - 0.5));
+ }
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Add int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_add);
+Datum
+int8vec_add(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ int8 *ax = a->x;
+ int8 *bx = b->x;
+ Int8Vector *result;
+ int8 *rx;
+
+ CheckDims(a, b);
+
+ result = InitInt8Vector(a->dim);
+ rx = result->x;
+
+ for (int i = 0, imax = a->dim; i < imax; i++)
+ {
+ int32 val = (int32) ax[i] + (int32) bx[i];
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ rx[i] = (int8) val;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Subtract int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_sub);
+Datum
+int8vec_sub(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ int8 *ax = a->x;
+ int8 *bx = b->x;
+ Int8Vector *result;
+ int8 *rx;
+
+ CheckDims(a, b);
+
+ result = InitInt8Vector(a->dim);
+ rx = result->x;
+
+ for (int i = 0, imax = a->dim; i < imax; i++)
+ {
+ int32 val = (int32) ax[i] - (int32) bx[i];
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ rx[i] = (int8) val;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Multiply int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_mul);
+Datum
+int8vec_mul(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ int8 *ax = a->x;
+ int8 *bx = b->x;
+ Int8Vector *result;
+ int8 *rx;
+
+ CheckDims(a, b);
+
+ result = InitInt8Vector(a->dim);
+ rx = result->x;
+
+ for (int i = 0, imax = a->dim; i < imax; i++)
+ {
+ int32 val = (int32) ax[i] * (int32) bx[i];
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ rx[i] = (int8) val;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Concatenate int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_concat);
+Datum
+int8vec_concat(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+ Int8Vector *result;
+ int dim = a->dim + b->dim;
+
+ CheckDim(dim);
+ result = InitInt8Vector(dim);
+
+ for (int i = 0; i < a->dim; i++)
+ result->x[i] = a->x[i];
+
+ for (int i = 0; i < b->dim; i++)
+ result->x[i + a->dim] = b->x[i];
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Quantize an int8 vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_binary_quantize);
+Datum
+int8vec_binary_quantize(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ int8 *ax = a->x;
+ VarBit *result = InitBitVector(a->dim);
+ unsigned char *rx = VARBITS(result);
+ int i = 0;
+ int count = (a->dim / 8) * 8;
+
+ /* Auto-vectorized on aarch64 */
+ for (; i < count; i += 8)
+ {
+ unsigned char 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 < a->dim; i++)
+ rx[i / 8] |= (ax[i] > 0) << (7 - (i % 8));
+
+ PG_RETURN_VARBIT_P(result);
+}
+
+/*
+ * Get a subvector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_subvector);
+Datum
+int8vec_subvector(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ int32 start = PG_GETARG_INT32(1);
+ int32 count = PG_GETARG_INT32(2);
+ int32 end;
+ int8 *ax = a->x;
+ Int8Vector *result;
+ int32 dim;
+
+ if (count < 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("int8vec must have at least 1 dimension")));
+
+ /*
+ * Check if (start + count > a->dim), avoiding integer overflow. a->dim
+ * and count are both positive, so a->dim - count won't overflow.
+ */
+ if (start > a->dim - count)
+ end = a->dim + 1;
+ else
+ end = start + count;
+
+ /* Indexing starts at 1, like substring */
+ if (start < 1)
+ start = 1;
+ else if (start > a->dim)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("int8vec must have at least 1 dimension")));
+
+ dim = end - start;
+ CheckDim(dim);
+ result = InitInt8Vector(dim);
+
+ for (int i = 0; i < dim; i++)
+ result->x[i] = ax[start - 1 + i];
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Internal helper to compare int8 vectors
+ */
+static int
+int8vec_cmp_internal(Int8Vector * a, Int8Vector * b)
+{
+ int dim = Min(a->dim, b->dim);
+
+ /* Check values before dimensions to be consistent with Postgres arrays */
+ for (int i = 0; i < dim; i++)
+ {
+ if (a->x[i] < b->x[i])
+ return -1;
+
+ if (a->x[i] > b->x[i])
+ return 1;
+ }
+
+ if (a->dim < b->dim)
+ return -1;
+
+ if (a->dim > b->dim)
+ return 1;
+
+ return 0;
+}
+
+/*
+ * Less than
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_lt);
+Datum
+int8vec_lt(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) < 0);
+}
+
+/*
+ * Less than or equal
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_le);
+Datum
+int8vec_le(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) <= 0);
+}
+
+/*
+ * Equal
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_eq);
+Datum
+int8vec_eq(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) == 0);
+}
+
+/*
+ * Not equal
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_ne);
+Datum
+int8vec_ne(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) != 0);
+}
+
+/*
+ * Greater than or equal
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_ge);
+Datum
+int8vec_ge(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) >= 0);
+}
+
+/*
+ * Greater than
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_gt);
+Datum
+int8vec_gt(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_BOOL(int8vec_cmp_internal(a, b) > 0);
+}
+
+/*
+ * Compare int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_cmp);
+Datum
+int8vec_cmp(PG_FUNCTION_ARGS)
+{
+ Int8Vector *a = PG_GETARG_INT8VEC_P(0);
+ Int8Vector *b = PG_GETARG_INT8VEC_P(1);
+
+ PG_RETURN_INT32(int8vec_cmp_internal(a, b));
+}
+
+/*
+ * Accumulate int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_accum);
+Datum
+int8vec_accum(PG_FUNCTION_ARGS)
+{
+ ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
+ Int8Vector *newval = PG_GETARG_INT8VEC_P(1);
+ float8 *statevalues;
+ int16 dim;
+ bool newarr;
+ float8 n;
+ Datum *statedatums;
+ int8 *x = newval->x;
+ ArrayType *result;
+
+ /* Check array before using */
+ statevalues = CheckStateArray(statearray, "int8vec_accum");
+ dim = STATE_DIMS(statearray);
+ newarr = dim == 0;
+
+ if (newarr)
+ dim = newval->dim;
+ else
+ CheckExpectedDim(dim, newval->dim);
+
+ n = statevalues[0] + 1.0;
+
+ statedatums = CreateStateDatums(dim);
+ statedatums[0] = Float8GetDatum(n);
+
+ if (newarr)
+ {
+ for (int i = 0; i < dim; i++)
+ statedatums[i + 1] = Float8GetDatum((double) x[i]);
+ }
+ else
+ {
+ for (int i = 0; i < dim; i++)
+ {
+ double v = statevalues[i + 1] + (double) x[i];
+
+ /* Check for overflow */
+ if (isinf(v))
+ float_overflow_error();
+
+ statedatums[i + 1] = Float8GetDatum(v);
+ }
+ }
+
+ /* Use float8 array like float4_accum */
+ result = construct_array(statedatums, dim + 1,
+ FLOAT8OID,
+ sizeof(float8), FLOAT8PASSBYVAL, TYPALIGN_DOUBLE);
+
+ pfree(statedatums);
+
+ PG_RETURN_ARRAYTYPE_P(result);
+}
+
+/*
+ * Average int8 vectors
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_avg);
+Datum
+int8vec_avg(PG_FUNCTION_ARGS)
+{
+ ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
+ float8 *statevalues;
+ float8 n;
+ uint16 dim;
+ Int8Vector *result;
+
+ /* Check array before using */
+ statevalues = CheckStateArray(statearray, "int8vec_avg");
+ n = statevalues[0];
+
+ /* SQL defines AVG of no values to be NULL */
+ if (n == 0.0)
+ PG_RETURN_NULL();
+
+ /* Create int8 vector */
+ dim = STATE_DIMS(statearray);
+ CheckDim(dim);
+ result = InitInt8Vector(dim);
+ for (int i = 0; i < dim; i++)
+ {
+ double val = statevalues[i + 1] / n;
+ int32 ival = (int32) round(val);
+
+ if (ival < -128)
+ ival = -128;
+ else if (ival > 127)
+ ival = 127;
+
+ result->x[i] = (int8) ival;
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
+/*
+ * Convert sparse vector to int8 vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(sparsevec_to_int8vec);
+Datum
+sparsevec_to_int8vec(PG_FUNCTION_ARGS)
+{
+ SparseVector *svec = PG_GETARG_SPARSEVEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Int8Vector *result;
+ int dim = svec->dim;
+ float *values = SPARSEVEC_VALUES(svec);
+
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ result = InitInt8Vector(dim);
+ for (int i = 0; i < svec->nnz; i++)
+ {
+ int32 val = (int32) roundf(values[i]);
+
+ if (val < -128 || val > 127)
+ ereport(ERROR,
+ (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+ errmsg("value out of range for type int8vec")));
+ result->x[svec->indices[i]] = (int8) val;
+ }
+
+ PG_RETURN_POINTER(result);
+}
diff --git a/src/int8vec.h b/src/int8vec.h
new file mode 100644
index 000000000..89255b61b
--- /dev/null
+++ b/src/int8vec.h
@@ -0,0 +1,23 @@
+#ifndef INT8VEC_H
+#define INT8VEC_H
+
+#include "vector.h"
+
+#define INT8VEC_MAX_DIM 16000
+
+#define INT8VEC_SIZE(_dim) (offsetof(Int8Vector, x) + sizeof(int8)*(_dim))
+#define DatumGetInt8Vector(x) ((Int8Vector *) PG_DETOAST_DATUM(x))
+#define PG_GETARG_INT8VEC_P(x) DatumGetInt8Vector(PG_GETARG_DATUM(x))
+#define PG_RETURN_INT8VEC_P(x) PG_RETURN_POINTER(x)
+
+typedef struct Int8Vector
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int16 dim; /* number of dimensions */
+ int16 unused; /* reserved for future use, always zero */
+ int8 x[FLEXIBLE_ARRAY_MEMBER];
+} Int8Vector;
+
+Int8Vector *InitInt8Vector(int dim);
+
+#endif
diff --git a/src/ivfutils.c b/src/ivfutils.c
index f1586dd97..cedd92562 100644
--- a/src/ivfutils.c
+++ b/src/ivfutils.c
@@ -1,10 +1,13 @@
#include "postgres.h"
+#include <math.h>
+
#include "access/genam.h"
#include "access/generic_xlog.h"
#include "fmgr.h"
#include "halfutils.h"
#include "halfvec.h"
+#include "int8vec.h"
#include "ivfflat.h"
#include "storage/bufmgr.h"
#include "utils/relcache.h"
@@ -238,6 +241,7 @@ IvfflatUpdateList(Relation index, ListInfo listInfo,
PGDLLEXPORT Datum l2_normalize(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum halfvec_l2_normalize(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum sparsevec_l2_normalize(PG_FUNCTION_ARGS);
+PGDLLEXPORT Datum int8vec_l2_normalize(PG_FUNCTION_ARGS);
static Size
VectorItemSize(int dimensions)
@@ -328,6 +332,43 @@ BitSumCenter(Pointer v, float *x)
x[i] += (float) (((VARBITS(vec)[i / 8]) >> (7 - (i % 8))) & 0x01);
}
+static Size
+Int8vecItemSize(int dimensions)
+{
+ return INT8VEC_SIZE(dimensions);
+}
+
+static void
+Int8vecUpdateCenter(Pointer v, int dimensions, float *x)
+{
+ Int8Vector *vec = (Int8Vector *) v;
+
+ SET_VARSIZE(vec, INT8VEC_SIZE(dimensions));
+ vec->dim = dimensions;
+
+ for (int i = 0; i < dimensions; i++)
+ {
+ int32 val = (int32) roundf(x[i]);
+
+ if (val < -128)
+ val = -128;
+ else if (val > 127)
+ val = 127;
+ vec->x[i] = (int8) val;
+ }
+}
+
+static void
+Int8vecSumCenter(Pointer v, float *x)
+{
+ Int8Vector *vec = (Int8Vector *) v;
+ int dim = vec->dim;
+
+ /* Auto-vectorized */
+ for (int i = 0; i < dim; i++)
+ x[i] += (float) vec->x[i];
+}
+
/*
* Get type info
*/
@@ -381,3 +422,18 @@ ivfflat_bit_support(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(&typeInfo);
}
+
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(ivfflat_int8vec_support);
+Datum
+ivfflat_int8vec_support(PG_FUNCTION_ARGS)
+{
+ static const IvfflatTypeInfo typeInfo = {
+ .maxDimensions = IVFFLAT_MAX_DIM * 4,
+ .normalize = int8vec_l2_normalize,
+ .itemSize = Int8vecItemSize,
+ .updateCenter = Int8vecUpdateCenter,
+ .sumCenter = Int8vecSumCenter
+ };
+
+ PG_RETURN_POINTER(&typeInfo);
+}
diff --git a/src/sparsevec.c b/src/sparsevec.c
index d7811c75e..f992cdb91 100644
--- a/src/sparsevec.c
+++ b/src/sparsevec.c
@@ -8,6 +8,7 @@
#include "fmgr.h"
#include "halfutils.h"
#include "halfvec.h"
+#include "int8vec.h"
#include "lib/stringinfo.h"
#include "libpq/pqformat.h"
#include "sparsevec.h"
@@ -676,6 +677,49 @@ halfvec_to_sparsevec(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*
+ * Convert int8 vector to sparse vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_to_sparsevec);
+Datum
+int8vec_to_sparsevec(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ SparseVector *result;
+ int dim = vec->dim;
+ int nnz = 0;
+ float *values;
+ int j = 0;
+
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ for (int i = 0; i < dim; i++)
+ {
+ if (vec->x[i] != 0)
+ nnz++;
+ }
+
+ result = InitSparseVector(dim, nnz);
+ values = SPARSEVEC_VALUES(result);
+ for (int i = 0; i < dim; i++)
+ {
+ if (vec->x[i] != 0)
+ {
+ /* Safety check */
+ if (j >= result->nnz)
+ elog(ERROR, "safety check failed");
+
+ result->indices[j] = i;
+ values[j] = (float) vec->x[i];
+ j++;
+ }
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
/*
* Convert array to sparse vector
*/
diff --git a/src/vector.c b/src/vector.c
index b8c295395..ec9c2fdd1 100644
--- a/src/vector.c
+++ b/src/vector.c
@@ -9,6 +9,8 @@
#include "fmgr.h"
#include "halfutils.h"
#include "halfvec.h"
+#include "int8utils.h"
+#include "int8vec.h"
#include "hnsw.h"
#include "ivfflat.h"
#include "lib/stringinfo.h"
@@ -54,6 +56,7 @@ _PG_init(void)
{
BitvecInit();
HalfvecInit();
+ Int8vecInit();
HnswInit();
IvfflatInit();
}
@@ -551,6 +554,28 @@ halfvec_to_vector(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*
+ * Convert int8 vector to vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(int8vec_to_vector);
+Datum
+int8vec_to_vector(PG_FUNCTION_ARGS)
+{
+ Int8Vector *vec = PG_GETARG_INT8VEC_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Vector *result;
+
+ CheckDim(vec->dim);
+ CheckExpectedDim(typmod, vec->dim);
+
+ result = InitVector(vec->dim);
+
+ for (int i = 0; i < vec->dim; i++)
+ result->x[i] = (float) vec->x[i];
+
+ PG_RETURN_POINTER(result);
+}
+
VECTOR_TARGET_CLONES static float
VectorL2SquaredDistance(int dim, float *ax, float *bx)
{
diff --git a/test/expected/hnsw_int8vec.out b/test/expected/hnsw_int8vec.out
new file mode 100644
index 000000000..018acbb12
--- /dev/null
+++ b/test/expected/hnsw_int8vec.out
@@ -0,0 +1,102 @@
+SET enable_seqscan = off;
+-- L2
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_l2_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+---------
+ [1,2,3]
+ [1,2,4]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 4
+(1 row)
+
+SELECT COUNT(*) FROM t;
+ count
+-------
+ 5
+(1 row)
+
+TRUNCATE t;
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+-----
+(0 rows)
+
+DROP TABLE t;
+-- inner product
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_ip_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+ val
+---------
+ [1,2,4]
+ [1,2,3]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 4
+(1 row)
+
+DROP TABLE t;
+-- cosine
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_cosine_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+ val
+---------
+ [1,1,1]
+ [1,2,3]
+ [1,2,4]
+(3 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+ count
+-------
+ 3
+(1 row)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 3
+(1 row)
+
+DROP TABLE t;
+-- L1
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_l1_ops);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <+> '[3,3,3]';
+ val
+---------
+ [1,2,3]
+ [1,2,4]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <+> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 4
+(1 row)
+
+DROP TABLE t;
diff --git a/test/expected/int8vec.out b/test/expected/int8vec.out
new file mode 100644
index 000000000..91e684edc
--- /dev/null
+++ b/test/expected/int8vec.out
@@ -0,0 +1,529 @@
+-- I/O
+SELECT '[1,2,3]'::int8vec;
+ int8vec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[-1,-2,-3]'::int8vec;
+ int8vec
+------------
+ [-1,-2,-3]
+(1 row)
+
+SELECT '[-128,0,127]'::int8vec;
+ int8vec
+--------------
+ [-128,0,127]
+(1 row)
+
+SELECT ' [ 1, 2 , 3 ] '::int8vec;
+ int8vec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[hello,1]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[hello,1]"
+LINE 1: SELECT '[hello,1]'::int8vec;
+ ^
+SELECT '[1.5,2]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1.5,2]"
+LINE 1: SELECT '[1.5,2]'::int8vec;
+ ^
+DETAIL: int8vec values must be integers.
+SELECT '[129,0]'::int8vec;
+ERROR: "129" is out of range for type int8vec
+LINE 1: SELECT '[129,0]'::int8vec;
+ ^
+DETAIL: int8vec values must be between -128 and 127.
+SELECT '[-129,0]'::int8vec;
+ERROR: "-129" is out of range for type int8vec
+LINE 1: SELECT '[-129,0]'::int8vec;
+ ^
+DETAIL: int8vec values must be between -128 and 127.
+SELECT '[1,2,3'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1,2,3"
+LINE 1: SELECT '[1,2,3'::int8vec;
+ ^
+SELECT '[1,2,3]9'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1,2,3]9"
+LINE 1: SELECT '[1,2,3]9'::int8vec;
+ ^
+DETAIL: Junk after closing right brace.
+SELECT '1,2,3'::int8vec;
+ERROR: invalid input syntax for type int8vec: "1,2,3"
+LINE 1: SELECT '1,2,3'::int8vec;
+ ^
+DETAIL: Vector contents must start with "[".
+SELECT ''::int8vec;
+ERROR: invalid input syntax for type int8vec: ""
+LINE 1: SELECT ''::int8vec;
+ ^
+DETAIL: Vector contents must start with "[".
+SELECT '['::int8vec;
+ERROR: invalid input syntax for type int8vec: "["
+LINE 1: SELECT '['::int8vec;
+ ^
+SELECT '[ '::int8vec;
+ERROR: invalid input syntax for type int8vec: "[ "
+LINE 1: SELECT '[ '::int8vec;
+ ^
+SELECT '[,'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[,"
+LINE 1: SELECT '[,'::int8vec;
+ ^
+SELECT '[]'::int8vec;
+ERROR: int8vec must have at least 1 dimension
+LINE 1: SELECT '[]'::int8vec;
+ ^
+SELECT '[ ]'::int8vec;
+ERROR: int8vec must have at least 1 dimension
+LINE 1: SELECT '[ ]'::int8vec;
+ ^
+SELECT '[,]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[,]"
+LINE 1: SELECT '[,]'::int8vec;
+ ^
+SELECT '[1,]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1,]"
+LINE 1: SELECT '[1,]'::int8vec;
+ ^
+SELECT '[1a]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1a]"
+LINE 1: SELECT '[1a]'::int8vec;
+ ^
+SELECT '[1,,3]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1,,3]"
+LINE 1: SELECT '[1,,3]'::int8vec;
+ ^
+SELECT '[1, ,3]'::int8vec;
+ERROR: invalid input syntax for type int8vec: "[1, ,3]"
+LINE 1: SELECT '[1, ,3]'::int8vec;
+ ^
+-- typmod
+SELECT '[1,2,3]'::int8vec(3);
+ int8vec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1,2,3]'::int8vec(2);
+ERROR: expected 2 dimensions, not 3
+SELECT '[1,2,3]'::int8vec(3, 2);
+ERROR: invalid type modifier
+LINE 1: SELECT '[1,2,3]'::int8vec(3, 2);
+ ^
+SELECT '[1,2,3]'::int8vec('a');
+ERROR: invalid input syntax for type integer: "a"
+LINE 1: SELECT '[1,2,3]'::int8vec('a');
+ ^
+SELECT '[1,2,3]'::int8vec(0);
+ERROR: dimensions for type int8vec must be at least 1
+LINE 1: SELECT '[1,2,3]'::int8vec(0);
+ ^
+SELECT '[1,2,3]'::int8vec(16001);
+ERROR: dimensions for type int8vec cannot exceed 16000
+LINE 1: SELECT '[1,2,3]'::int8vec(16001);
+ ^
+-- array
+SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::int8vec[]);
+ unnest
+---------
+ [1,2,3]
+ [4,5,6]
+(2 rows)
+
+SELECT '{"[1,2,3]"}'::int8vec(2)[];
+ERROR: expected 2 dimensions, not 3
+-- arithmetic
+SELECT '[1,2,3]'::int8vec + '[4,5,6]';
+ ?column?
+----------
+ [5,7,9]
+(1 row)
+
+SELECT '[127]'::int8vec + '[1]';
+ERROR: value out of range for type int8vec
+SELECT '[1,2]'::int8vec + '[3]';
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[1,2,3]'::int8vec - '[4,5,6]';
+ ?column?
+------------
+ [-3,-3,-3]
+(1 row)
+
+SELECT '[-128]'::int8vec - '[1]';
+ERROR: value out of range for type int8vec
+SELECT '[1,2]'::int8vec - '[3]';
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[1,2,3]'::int8vec * '[4,5,6]';
+ ?column?
+-----------
+ [4,10,18]
+(1 row)
+
+SELECT '[127]'::int8vec * '[2]';
+ERROR: value out of range for type int8vec
+SELECT '[1,2]'::int8vec * '[3]';
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[1,2,3]'::int8vec || '[4,5]';
+ ?column?
+-------------
+ [1,2,3,4,5]
+(1 row)
+
+-- comparison
+SELECT '[1,2,3]'::int8vec < '[1,2,3]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec < '[1,2]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec <= '[1,2,3]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT '[1,2,3]'::int8vec <= '[1,2]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec = '[1,2,3]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT '[1,2,3]'::int8vec = '[1,2]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec != '[1,2,3]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec != '[1,2]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT '[1,2,3]'::int8vec >= '[1,2,3]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT '[1,2,3]'::int8vec >= '[1,2]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT '[1,2,3]'::int8vec > '[1,2,3]';
+ ?column?
+----------
+ f
+(1 row)
+
+SELECT '[1,2,3]'::int8vec > '[1,2]';
+ ?column?
+----------
+ t
+(1 row)
+
+SELECT int8vec_cmp('[1,2,3]', '[1,2,3]');
+ int8vec_cmp
+-------------
+ 0
+(1 row)
+
+SELECT int8vec_cmp('[1,2,3]', '[0,0,0]');
+ int8vec_cmp
+-------------
+ 1
+(1 row)
+
+SELECT int8vec_cmp('[0,0,0]', '[1,2,3]');
+ int8vec_cmp
+-------------
+ -1
+(1 row)
+
+SELECT int8vec_cmp('[1,2]', '[1,2,3]');
+ int8vec_cmp
+-------------
+ -1
+(1 row)
+
+SELECT int8vec_cmp('[1,2,3]', '[1,2]');
+ int8vec_cmp
+-------------
+ 1
+(1 row)
+
+SELECT int8vec_cmp('[1,2]', '[2,3,4]');
+ int8vec_cmp
+-------------
+ -1
+(1 row)
+
+SELECT int8vec_cmp('[2,3]', '[1,2,3]');
+ int8vec_cmp
+-------------
+ 1
+(1 row)
+
+-- dims
+SELECT vector_dims('[1,2,3]'::int8vec);
+ vector_dims
+-------------
+ 3
+(1 row)
+
+-- norm
+SELECT l2_norm('[3,4]'::int8vec);
+ l2_norm
+---------
+ 5
+(1 row)
+
+SELECT l2_norm('[0,1]'::int8vec);
+ l2_norm
+---------
+ 1
+(1 row)
+
+SELECT l2_norm('[0,0]'::int8vec);
+ l2_norm
+---------
+ 0
+(1 row)
+
+-- distance
+SELECT l2_distance('[0,0]'::int8vec, '[3,4]');
+ l2_distance
+-------------
+ 5
+(1 row)
+
+SELECT l2_distance('[0,0]'::int8vec, '[0,1]');
+ l2_distance
+-------------
+ 1
+(1 row)
+
+SELECT l2_distance('[1,2]'::int8vec, '[3]');
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[0,0]'::int8vec <-> '[3,4]';
+ ?column?
+----------
+ 5
+(1 row)
+
+SELECT inner_product('[1,2]'::int8vec, '[3,4]');
+ inner_product
+---------------
+ 11
+(1 row)
+
+SELECT inner_product('[1,2]'::int8vec, '[3]');
+ERROR: different int8vec dimensions 2 and 1
+SELECT inner_product('[127]'::int8vec, '[127]');
+ inner_product
+---------------
+ 16129
+(1 row)
+
+SELECT '[1,2]'::int8vec <#> '[3,4]';
+ ?column?
+----------
+ -11
+(1 row)
+
+SELECT cosine_distance('[1,2]'::int8vec, '[2,4]');
+ cosine_distance
+-----------------
+ 0
+(1 row)
+
+SELECT cosine_distance('[1,2]'::int8vec, '[0,0]');
+ cosine_distance
+-----------------
+ NaN
+(1 row)
+
+SELECT cosine_distance('[1,1]'::int8vec, '[1,1]');
+ cosine_distance
+-----------------
+ 0
+(1 row)
+
+SELECT cosine_distance('[1,0]'::int8vec, '[0,2]');
+ cosine_distance
+-----------------
+ 1
+(1 row)
+
+SELECT cosine_distance('[1,1]'::int8vec, '[-1,-1]');
+ cosine_distance
+-----------------
+ 2
+(1 row)
+
+SELECT cosine_distance('[1,2]'::int8vec, '[3]');
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[1,2]'::int8vec <=> '[2,4]';
+ ?column?
+----------
+ 0
+(1 row)
+
+SELECT l1_distance('[0,0]'::int8vec, '[3,4]');
+ l1_distance
+-------------
+ 7
+(1 row)
+
+SELECT l1_distance('[0,0]'::int8vec, '[0,1]');
+ l1_distance
+-------------
+ 1
+(1 row)
+
+SELECT l1_distance('[1,2]'::int8vec, '[3]');
+ERROR: different int8vec dimensions 2 and 1
+SELECT '[0,0]'::int8vec <+> '[3,4]';
+ ?column?
+----------
+ 7
+(1 row)
+
+-- normalize
+SELECT l2_normalize('[3,4,0]'::int8vec);
+ l2_normalize
+--------------
+ [76,102,0]
+(1 row)
+
+SELECT l2_normalize('[0,0,0]'::int8vec);
+ l2_normalize
+--------------
+ [0,0,0]
+(1 row)
+
+-- binary quantize
+SELECT binary_quantize('[1,0,-1]'::int8vec);
+ binary_quantize
+-----------------
+ 100
+(1 row)
+
+SELECT binary_quantize('[0,1,-2,-3,4,5,6,-7,8,-9,1]'::int8vec);
+ binary_quantize
+-----------------
+ 01001110101
+(1 row)
+
+-- subvector
+SELECT subvector('[1,2,3,4,5]'::int8vec, 1, 3);
+ subvector
+-----------
+ [1,2,3]
+(1 row)
+
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 2);
+ subvector
+-----------
+ [3,4]
+(1 row)
+
+SELECT subvector('[1,2,3,4,5]'::int8vec, -1, 3);
+ subvector
+-----------
+ [1]
+(1 row)
+
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 9);
+ subvector
+-----------
+ [3,4,5]
+(1 row)
+
+SELECT subvector('[1,2,3,4,5]'::int8vec, 1, 0);
+ERROR: int8vec must have at least 1 dimension
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, -1);
+ERROR: int8vec must have at least 1 dimension
+SELECT subvector('[1,2,3,4,5]'::int8vec, -1, 2);
+ERROR: int8vec must have at least 1 dimension
+SELECT subvector('[1,2,3,4,5]'::int8vec, 2147483647, 10);
+ERROR: int8vec must have at least 1 dimension
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 2147483647);
+ subvector
+-----------
+ [3,4,5]
+(1 row)
+
+SELECT subvector('[1,2,3,4,5]'::int8vec, -2147483644, 2147483647);
+ subvector
+-----------
+ [1,2]
+(1 row)
+
+-- aggregates
+SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,6,9]']) v;
+ avg
+---------
+ [2,4,6]
+(1 row)
+
+SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,6,9]', NULL]) v;
+ avg
+---------
+ [2,4,6]
+(1 row)
+
+SELECT avg(v) FROM unnest(ARRAY[]::int8vec[]) v;
+ avg
+-----
+
+(1 row)
+
+SELECT avg(v) FROM unnest(ARRAY['[1,2]'::int8vec, '[3]']) v;
+ERROR: expected 2 dimensions, not 1
+SELECT sum(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,5,7]']) v;
+ sum
+----------
+ [4,7,10]
+(1 row)
+
+SELECT sum(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,5,7]', NULL]) v;
+ sum
+----------
+ [4,7,10]
+(1 row)
+
+SELECT sum(v) FROM unnest(ARRAY[]::int8vec[]) v;
+ sum
+-----
+
+(1 row)
+
+SELECT sum(v) FROM unnest(ARRAY['[1,2]'::int8vec, '[3]']) v;
+ERROR: different int8vec dimensions 2 and 1
+SELECT sum(v) FROM unnest(ARRAY['[100,0]'::int8vec, '[100,0]']) v;
+ERROR: value out of range for type int8vec
diff --git a/test/expected/ivfflat_int8vec.out b/test/expected/ivfflat_int8vec.out
new file mode 100644
index 000000000..3cc600320
--- /dev/null
+++ b/test/expected/ivfflat_int8vec.out
@@ -0,0 +1,84 @@
+SET enable_seqscan = off;
+-- L2
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_l2_ops) WITH (lists = 1);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+---------
+ [1,2,3]
+ [1,2,4]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 4
+(1 row)
+
+SELECT COUNT(*) FROM t;
+ count
+-------
+ 5
+(1 row)
+
+TRUNCATE t;
+NOTICE: ivfflat index created with little data
+DETAIL: This will cause low recall.
+HINT: Drop the index until the table has more data.
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+ val
+-----
+(0 rows)
+
+DROP TABLE t;
+-- inner product
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_ip_ops) WITH (lists = 1);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+ val
+---------
+ [1,2,4]
+ [1,2,3]
+ [1,1,1]
+ [0,0,0]
+(4 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 4
+(1 row)
+
+DROP TABLE t;
+-- cosine
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_cosine_ops) WITH (lists = 1);
+INSERT INTO t (val) VALUES ('[1,2,4]');
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+ val
+---------
+ [1,1,1]
+ [1,2,3]
+ [1,2,4]
+(3 rows)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+ count
+-------
+ 3
+(1 row)
+
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::int8vec)) t2;
+ count
+-------
+ 3
+(1 row)
+
+DROP TABLE t;
diff --git a/test/sql/hnsw_int8vec.sql b/test/sql/hnsw_int8vec.sql
new file mode 100644
index 000000000..834d6b971
--- /dev/null
+++ b/test/sql/hnsw_int8vec.sql
@@ -0,0 +1,58 @@
+SET enable_seqscan = off;
+
+-- L2
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_l2_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::int8vec)) t2;
+SELECT COUNT(*) FROM t;
+
+TRUNCATE t;
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+
+DROP TABLE t;
+
+-- inner product
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_ip_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::int8vec)) t2;
+
+DROP TABLE t;
+
+-- cosine
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_cosine_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::int8vec)) t2;
+
+DROP TABLE t;
+
+-- L1
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING hnsw (val int8vec_l1_ops);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <+> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <+> (SELECT NULL::int8vec)) t2;
+
+DROP TABLE t;
diff --git a/test/sql/int8vec.sql b/test/sql/int8vec.sql
new file mode 100644
index 000000000..8e93b1c80
--- /dev/null
+++ b/test/sql/int8vec.sql
@@ -0,0 +1,136 @@
+-- I/O
+SELECT '[1,2,3]'::int8vec;
+SELECT '[-1,-2,-3]'::int8vec;
+SELECT '[-128,0,127]'::int8vec;
+SELECT ' [ 1, 2 , 3 ] '::int8vec;
+SELECT '[hello,1]'::int8vec;
+SELECT '[1.5,2]'::int8vec;
+SELECT '[129,0]'::int8vec;
+SELECT '[-129,0]'::int8vec;
+SELECT '[1,2,3'::int8vec;
+SELECT '[1,2,3]9'::int8vec;
+SELECT '1,2,3'::int8vec;
+SELECT ''::int8vec;
+SELECT '['::int8vec;
+SELECT '[ '::int8vec;
+SELECT '[,'::int8vec;
+SELECT '[]'::int8vec;
+SELECT '[ ]'::int8vec;
+SELECT '[,]'::int8vec;
+SELECT '[1,]'::int8vec;
+SELECT '[1a]'::int8vec;
+SELECT '[1,,3]'::int8vec;
+SELECT '[1, ,3]'::int8vec;
+
+-- typmod
+SELECT '[1,2,3]'::int8vec(3);
+SELECT '[1,2,3]'::int8vec(2);
+SELECT '[1,2,3]'::int8vec(3, 2);
+SELECT '[1,2,3]'::int8vec('a');
+SELECT '[1,2,3]'::int8vec(0);
+SELECT '[1,2,3]'::int8vec(16001);
+
+-- array
+SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::int8vec[]);
+SELECT '{"[1,2,3]"}'::int8vec(2)[];
+
+-- arithmetic
+SELECT '[1,2,3]'::int8vec + '[4,5,6]';
+SELECT '[127]'::int8vec + '[1]';
+SELECT '[1,2]'::int8vec + '[3]';
+
+SELECT '[1,2,3]'::int8vec - '[4,5,6]';
+SELECT '[-128]'::int8vec - '[1]';
+SELECT '[1,2]'::int8vec - '[3]';
+
+SELECT '[1,2,3]'::int8vec * '[4,5,6]';
+SELECT '[127]'::int8vec * '[2]';
+SELECT '[1,2]'::int8vec * '[3]';
+
+SELECT '[1,2,3]'::int8vec || '[4,5]';
+
+-- comparison
+SELECT '[1,2,3]'::int8vec < '[1,2,3]';
+SELECT '[1,2,3]'::int8vec < '[1,2]';
+SELECT '[1,2,3]'::int8vec <= '[1,2,3]';
+SELECT '[1,2,3]'::int8vec <= '[1,2]';
+SELECT '[1,2,3]'::int8vec = '[1,2,3]';
+SELECT '[1,2,3]'::int8vec = '[1,2]';
+SELECT '[1,2,3]'::int8vec != '[1,2,3]';
+SELECT '[1,2,3]'::int8vec != '[1,2]';
+SELECT '[1,2,3]'::int8vec >= '[1,2,3]';
+SELECT '[1,2,3]'::int8vec >= '[1,2]';
+SELECT '[1,2,3]'::int8vec > '[1,2,3]';
+SELECT '[1,2,3]'::int8vec > '[1,2]';
+
+SELECT int8vec_cmp('[1,2,3]', '[1,2,3]');
+SELECT int8vec_cmp('[1,2,3]', '[0,0,0]');
+SELECT int8vec_cmp('[0,0,0]', '[1,2,3]');
+SELECT int8vec_cmp('[1,2]', '[1,2,3]');
+SELECT int8vec_cmp('[1,2,3]', '[1,2]');
+SELECT int8vec_cmp('[1,2]', '[2,3,4]');
+SELECT int8vec_cmp('[2,3]', '[1,2,3]');
+
+-- dims
+SELECT vector_dims('[1,2,3]'::int8vec);
+
+-- norm
+SELECT l2_norm('[3,4]'::int8vec);
+SELECT l2_norm('[0,1]'::int8vec);
+SELECT l2_norm('[0,0]'::int8vec);
+
+-- distance
+SELECT l2_distance('[0,0]'::int8vec, '[3,4]');
+SELECT l2_distance('[0,0]'::int8vec, '[0,1]');
+SELECT l2_distance('[1,2]'::int8vec, '[3]');
+SELECT '[0,0]'::int8vec <-> '[3,4]';
+
+SELECT inner_product('[1,2]'::int8vec, '[3,4]');
+SELECT inner_product('[1,2]'::int8vec, '[3]');
+SELECT inner_product('[127]'::int8vec, '[127]');
+SELECT '[1,2]'::int8vec <#> '[3,4]';
+
+SELECT cosine_distance('[1,2]'::int8vec, '[2,4]');
+SELECT cosine_distance('[1,2]'::int8vec, '[0,0]');
+SELECT cosine_distance('[1,1]'::int8vec, '[1,1]');
+SELECT cosine_distance('[1,0]'::int8vec, '[0,2]');
+SELECT cosine_distance('[1,1]'::int8vec, '[-1,-1]');
+SELECT cosine_distance('[1,2]'::int8vec, '[3]');
+SELECT '[1,2]'::int8vec <=> '[2,4]';
+
+SELECT l1_distance('[0,0]'::int8vec, '[3,4]');
+SELECT l1_distance('[0,0]'::int8vec, '[0,1]');
+SELECT l1_distance('[1,2]'::int8vec, '[3]');
+SELECT '[0,0]'::int8vec <+> '[3,4]';
+
+-- normalize
+SELECT l2_normalize('[3,4,0]'::int8vec);
+SELECT l2_normalize('[0,0,0]'::int8vec);
+
+-- binary quantize
+SELECT binary_quantize('[1,0,-1]'::int8vec);
+SELECT binary_quantize('[0,1,-2,-3,4,5,6,-7,8,-9,1]'::int8vec);
+
+-- subvector
+SELECT subvector('[1,2,3,4,5]'::int8vec, 1, 3);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 2);
+SELECT subvector('[1,2,3,4,5]'::int8vec, -1, 3);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 9);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 1, 0);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, -1);
+SELECT subvector('[1,2,3,4,5]'::int8vec, -1, 2);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 2147483647, 10);
+SELECT subvector('[1,2,3,4,5]'::int8vec, 3, 2147483647);
+SELECT subvector('[1,2,3,4,5]'::int8vec, -2147483644, 2147483647);
+
+-- aggregates
+SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,6,9]']) v;
+SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,6,9]', NULL]) v;
+SELECT avg(v) FROM unnest(ARRAY[]::int8vec[]) v;
+SELECT avg(v) FROM unnest(ARRAY['[1,2]'::int8vec, '[3]']) v;
+
+SELECT sum(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,5,7]']) v;
+SELECT sum(v) FROM unnest(ARRAY['[1,2,3]'::int8vec, '[3,5,7]', NULL]) v;
+SELECT sum(v) FROM unnest(ARRAY[]::int8vec[]) v;
+SELECT sum(v) FROM unnest(ARRAY['[1,2]'::int8vec, '[3]']) v;
+SELECT sum(v) FROM unnest(ARRAY['[100,0]'::int8vec, '[100,0]']) v;
diff --git a/test/sql/ivfflat_int8vec.sql b/test/sql/ivfflat_int8vec.sql
new file mode 100644
index 000000000..f02baebcc
--- /dev/null
+++ b/test/sql/ivfflat_int8vec.sql
@@ -0,0 +1,45 @@
+SET enable_seqscan = off;
+
+-- L2
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_l2_ops) WITH (lists = 1);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::int8vec)) t2;
+SELECT COUNT(*) FROM t;
+
+TRUNCATE t;
+SELECT * FROM t ORDER BY val <-> '[3,3,3]';
+
+DROP TABLE t;
+
+-- inner product
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_ip_ops) WITH (lists = 1);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <#> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::int8vec)) t2;
+
+DROP TABLE t;
+
+-- cosine
+
+CREATE TABLE t (val int8vec(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX ON t USING ivfflat (val int8vec_cosine_ops) WITH (lists = 1);
+
+INSERT INTO t (val) VALUES ('[1,2,4]');
+
+SELECT * FROM t ORDER BY val <=> '[3,3,3]';
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
+SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::int8vec)) t2;
+
+DROP TABLE t;
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-13 20:43 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: tkreuder (@tkreuder) @ 2026-04-13 20:43 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Benchmark: 50k vectors, 128 dimensions, HNSW L2, Top-10
Table size
• vector: 28 MB
• halfvec: 15 MB
• int8vec: 8.5 MB
Index size
• vector: 40 MB
• halfvec: 27 MB
• int8vec: 21 MB
Index build
• vector: 3.1s
• halfvec: 2.7s
• int8vec: 2.8s
Search (exec)
• vector: 0.25 ms
• halfvec: 1.43 ms
• int8vec: 0.65 ms
PostgreSQL 17.9, macOS ARM (M-series), hnsw_ef_search = 40 (default).
int8vec achieves ~70% table storage reduction vs vector while maintaining sub-millisecond search latency. Notably faster than halfvec at search due to smaller data footprint (better cache utilization).
Distance functions currently cast int8→float for computation. Future optimization opportunity: pure integer arithmetic with SIMD could further improve search performance.
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-13 20:47 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: tkreuder (@tkreuder) @ 2026-04-13 20:47 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Recall@100 (20 queries, 50k×128d, HNSW, ef_search=200):
• vector: 66.7%
• halfvec: 66.4%
• int8vec: 66.8%
No recall degradation — relative distance ordering is preserved with int8 values.
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-15 00:41 ` "ankane (@ankane)" <noreply+ankane@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: ankane (@ankane) @ 2026-04-15 00:41 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hi @tkreuder, thanks for the PR, but there's already [a branch](https://github.com/pgvector/pgvector/compare/intvec) for this.
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-15 00:41 ` "ankane (@ankane)" <noreply+ankane@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: ankane (@ankane) @ 2026-04-15 00:41 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane closed this.
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-15 09:27 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: tkreuder (@tkreuder) @ 2026-04-15 09:27 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane can it be merged then? You are talking about: https://github.com/pgvector/pgvector/commit/b067b5f073e415f2f49e7c412205501dd94a736b ?
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-15 12:20 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: tkreuder (@tkreuder) @ 2026-04-15 12:20 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
I saw the intvec branch — great to see it landing in 0.8.0.
My implementation ( int8vec ) was built independently and goes a bit further in a few areas:
• IVFFlat support (not just HNSW)
• SIMD-ready distance functions via runtime-dispatched function pointers
• Utility functions like vector_dims() , l2_norm() , l2_normalize() , binary_quantize() , subvector()
• Arithmetic operators ( add , sub , mul , concat )
• Btree opclass for ORDER BY / DISTINCT / equality
• Sparsevec casts ( sparsevec <=> int8vec )
^ permalink raw [nested|flat] 8+ messages in thread
* Re: [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors
@ 2026-04-30 22:45 ` "areazus (@areazus)" <noreply+areazus@github.com>
6 siblings, 0 replies; 8+ messages in thread
From: areazus (@areazus) @ 2026-04-30 22:45 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
It wasn't landed in 0.8.0+
^ permalink raw [nested|flat] 8+ messages in thread
end of thread, other threads:[~2026-04-30 22:45 UTC | newest]
Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-13 20:39 [pgvector/pgvector] PR #977: Add int8vec type for 8-bit integer vectors "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
2026-04-13 20:43 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
2026-04-13 20:47 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
2026-04-15 00:41 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-04-15 00:41 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-04-15 09:27 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
2026-04-15 12:20 ` "tkreuder (@tkreuder)" <noreply+tkreuder@github.com>
2026-04-30 22:45 ` "areazus (@areazus)" <noreply+areazus@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