From: Ngalstyan4 (@Ngalstyan4) <noreply+Ngalstyan4@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #604: Add direct array to/from sparsevec casts
Date: Sun, 23 Jun 2024 09:16:30 +0000
Message-ID: <gh-pgvector-pgvector-604@github.com> (raw)
Hi all,
We ran into an issue when trying to use the `sparsevec` type at
Lantern with ~30K dimensional vectors (SPLADE) relevant commit message is below:
Before this commit the only ways to construct a sparse vector was to
cast one from vector/halfvec or create one from a literal.
Neither approach is suitable for construcitng sparse vectors that have
more than 16K dimensions, since intermediate ::vector cast disallows
such large vectors and writing down such large vector in literal format
is inconvenient.
This is a needless limitation since both the target sparsevec type and
the common source ARRAY type support larger dimensions.
This commit overcomes the limitation by implementing direct
ARRAY[]<->sparsevec casts
### Notes on the code
1. All current vector casts in pgvector disallow NULLs in ARRAYs that get cast to vectors. I followed that in the base commit. But also added a commit supporting NULL elements in array->sparsevec casts and treating NULLs as unset sparsevec elements
2. There is quite some repetition in `array_to_sparsevec` function when handling generic array to `float4` casts. There is similarly repeated code for [halfvec](https://github.com/pgvector/pgvector/blob/d1694a93afe4d23d0bc3ca6f9c85f06fb79a325c/src/halfvec.c#L47...) and [vector](https://github.com/pgvector/pgvector/blob/d1694a93afe4d23d0bc3ca6f9c85f06fb79a325c/src/vector.c#L482...) casts. I tried to reduce some of the repetition with the `PROCESS_ARRAY_ELEM ` macro
There is an alternative approach [here](https://github.com/pgvector/pgvector/commit/28282d0dcfdcaebe57a412477683c0606c25c813) where I factor out generic array element to float4 conversion to a function. The code is a lot cleaner there, but performance suffers. I benchmarked it with the query below:
`SELECT array_to_sparsevec(array_agg(0)::float4[], 16001000, false) FROM generate_series(1, 16001000) n;`
The version in this PR spends `60.0 +/- 1.2 ms` in the array extraction loop, while the linked version which uses a branch in each iteration of the loop takes `87.2 +/- 0.4 ms` on my 2019 Mac. Here is [the branch I used for the benchmarks](https://github.com/Ngalstyan4/pgvector/tree/array-to-sparsevec-benchmark).
I can probably combine something like the current `PROCESS_ARRAY_ELEM` with a macro-function similar to the static function from the benchmarking branch to reduce repetition with no performance hit. I am not sure the complexity is worth it
3. There is also a somewhat unrelated commit (8f2b7fec39a0ced45a76b97a932312dfceff3170) in the PR that changes one of the error messages to be closer to the error message [shown in the upstream](
https://github.com/search?q=repo%3Apostgres%2Fpostgres+%22array+must+be+one-dimensional%22&type=...) in similar situations
### NOT DONE:
1. [x] ~~Decide whether to support arrays containing NULLs to sparsevec casts (drop corresponding commit if not supporting)~~
1. [ ] Decide whether to simplify (at the cost of performance, or otherwise) the generic array to float4 conversion code
1. [x] ~~Decide whether sparsevec->array casts should contain zero values (current approach) or NULLs in place of `sparsevec`s empty slots in the returned ARRAY~~
1. [x] ~~Add update scripts introducing the functions and the casts~~
Happy to address any issues in this PR if you think it is useful to have it in pgvector
inline patch 1: sql/vector--0.7.2--0.7.3.sql, sql/vector.sql, src/halfvec.c and 5 more (+298/-15 lines) download inline-1.patchdiff --git a/sql/vector--0.7.2--0.7.3.sql b/sql/vector--0.7.2--0.7.3.sqlnew file mode 100644index 000000000..a31ee4df7--- /dev/null+++ b/sql/vector--0.7.2--0.7.3.sql@@ -0,0 +1,32 @@+-- complain if script is sourced in psql, rather than via CREATE EXTENSION+\echo Use "ALTER EXTENSION vector UPDATE TO '0.7.3'" to load this file. \quit+CREATE FUNCTION array_to_sparsevec(integer[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(real[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(double precision[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(numeric[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sparsevec_to_float4(sparsevec, integer, boolean) RETURNS real[]+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;+++CREATE CAST (sparsevec AS real[])+ WITH FUNCTION sparsevec_to_float4(sparsevec, integer, boolean) AS ASSIGNMENT;++CREATE CAST (integer[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(integer[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (real[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(real[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (double precision[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(double precision[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (numeric[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(numeric[], integer, boolean) AS ASSIGNMENT;diff --git a/sql/vector.sql b/sql/vector.sqlindex 32eb8345a..f48cb050b 100644--- a/sql/vector.sql+++ b/sql/vector.sql@@ -782,8 +782,38 @@ CREATE FUNCTION halfvec_to_sparsevec(halfvec, integer, boolean) RETURNS sparseve
CREATE FUNCTION sparsevec_to_halfvec(sparsevec, integer, boolean) RETURNS halfvec
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+CREATE FUNCTION array_to_sparsevec(integer[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(real[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(double precision[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION array_to_sparsevec(numeric[], integer, boolean) RETURNS sparsevec+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sparsevec_to_float4(sparsevec, integer, boolean) RETURNS real[]+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;+
-- sparsevec casts
+CREATE CAST (sparsevec AS real[])+ WITH FUNCTION sparsevec_to_float4(sparsevec, integer, boolean) AS ASSIGNMENT;++CREATE CAST (integer[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(integer[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (real[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(real[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (double precision[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(double precision[], integer, boolean) AS ASSIGNMENT;++CREATE CAST (numeric[] AS sparsevec)+ WITH FUNCTION array_to_sparsevec(numeric[], integer, boolean) AS ASSIGNMENT;+
CREATE CAST (sparsevec AS sparsevec)
WITH FUNCTION sparsevec(sparsevec, integer, boolean) AS IMPLICIT;
diff --git a/src/halfvec.c b/src/halfvec.cindex 2cb1127ff..94e98564a 100644--- a/src/halfvec.c+++ b/src/halfvec.c@@ -19,11 +19,6 @@
#include "utils/numeric.h"
#include "vector.h"
-#if PG_VERSION_NUM < 130000-#define TYPALIGN_DOUBLE 'd'-#define TYPALIGN_INT 'i'-#endif-
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
@@ -460,8 +455,8 @@ array_to_halfvec(PG_FUNCTION_ARGS)
if (ARR_NDIM(array) > 1)
ereport(ERROR,
- (errcode(ERRCODE_DATA_EXCEPTION),- errmsg("array must be 1-D")));+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),+ errmsg("array must be one-dimensional")));
if (ARR_HASNULL(array) && array_contains_nulls(array))
ereport(ERROR,
diff --git a/src/sparsevec.c b/src/sparsevec.cindex 4211fd8d5..1f142be61 100644--- a/src/sparsevec.c+++ b/src/sparsevec.c@@ -4,6 +4,7 @@
#include <math.h>
#include "common/string.h"
+#include "catalog/pg_type.h"
#include "fmgr.h"
#include "halfutils.h"
#include "halfvec.h"
@@ -11,6 +12,7 @@
#include "sparsevec.h"
#include "utils/array.h"
#include "utils/builtins.h"
+#include "utils/lsyscache.h"
#include "vector.h"
#if PG_VERSION_NUM >= 120000
@@ -627,6 +629,150 @@ vector_to_sparsevec(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*+ * Convert real array to sparse vector+ */+PGDLLEXPORT PG_FUNCTION_INFO_V1(array_to_sparsevec);+Datum+array_to_sparsevec(PG_FUNCTION_ARGS)+{+ ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);+ int32 typmod = PG_GETARG_INT32(1);+ SparseVector *result;+ int16 typlen;+ bool typbyval;+ char typalign;+ Datum *elemsp;+ int nelemsp;+ int nnz = 0;+ float *sparsevec_values;+ int j = 0;++ if (ARR_NDIM(array) > 1)+ ereport(ERROR,+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),+ errmsg("array must be one-dimensional")));++ 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);++ if (ARR_ELEMTYPE(array) == INT4OID)+ {+ for (int i = 0; i < nelemsp; i++)+ nnz += (DatumGetInt32(elemsp[i]) != 0);+ }+ else if (ARR_ELEMTYPE(array) == FLOAT8OID)+ {+ for (int i = 0; i < nelemsp; i++)+ nnz += (DatumGetFloat8(elemsp[i]) != 0);+ }+ else if (ARR_ELEMTYPE(array) == FLOAT4OID)+ {+ for (int i = 0; i < nelemsp; i++)+ nnz += (DatumGetFloat4(elemsp[i]) != 0);+ }+ else if (ARR_ELEMTYPE(array) == NUMERICOID)+ {+ for (int i = 0; i < nelemsp; i++)+ nnz += (DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i])) != 0);+ }+ else+ {+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("unsupported array type")));+ }++ CheckNnz(nnz, nelemsp);++ result = InitSparseVector(nelemsp, nnz);+ sparsevec_values = SPARSEVEC_VALUES(result);++#define PROCESS_ARRAY_ELEM(elem) \+ do { \+ if ((elem) != 0) { \+ /* Safety check */ \+ if (j >= result->nnz) \+ elog(ERROR, "safety check failed"); \+ result->indices[j] = i; \+ sparsevec_values[j] = (elem); \+ j++; \+ } \+ } while (0)++ if (ARR_ELEMTYPE(array) == INT4OID)+ {+ for (int i = 0; i < nelemsp; i++)+ PROCESS_ARRAY_ELEM(DatumGetInt32(elemsp[i]));+ }+ else if (ARR_ELEMTYPE(array) == FLOAT8OID)+ {+ for (int i = 0; i < nelemsp; i++)+ PROCESS_ARRAY_ELEM(DatumGetFloat8(elemsp[i]));+ }+ else if (ARR_ELEMTYPE(array) == FLOAT4OID)+ {+ for (int i = 0; i < nelemsp; i++)+ PROCESS_ARRAY_ELEM(DatumGetFloat4(elemsp[i]));+ }+ else if (ARR_ELEMTYPE(array) == NUMERICOID)+ {+ for (int i = 0; i < nelemsp; i++)+ PROCESS_ARRAY_ELEM(DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i])));+ }+ else+ {+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("unsupported array type")));+ }++#undef PROCESS_ARRAY_ELEM++ /*+ * Free allocation from deconstruct_array. Do not free individual elements+ * when pass-by-reference since they point to original array.+ */+ pfree(elemsp);++ PG_RETURN_POINTER(result);+}++/*+ * Convert sparse vector to float4[]+ */+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(sparsevec_to_float4);+Datum+sparsevec_to_float4(PG_FUNCTION_ARGS)+{+ SparseVector *svec = PG_GETARG_SPARSEVEC_P(0);+ ArrayType *result;+ Datum *datums;+ int dim = svec->dim;+ float *values = SPARSEVEC_VALUES(svec);++ CheckDim(dim);++ datums = (Datum *) palloc0(sizeof(Datum) * dim);++ for (int i = 0; i < svec->nnz; i++)+ datums[svec->indices[i]] = Float4GetDatum(values[i]);++ /* Use TYPALIGN_INT for float4 */+ result = construct_array(datums, dim, FLOAT4OID, sizeof(float4), true, TYPALIGN_INT);+ pfree(datums);++ PG_RETURN_POINTER(result);+}+
/*
* Convert half vector to sparse vector
*/
diff --git a/src/vector.c b/src/vector.cindex a0e2c3fb1..db6d4b444 100644--- a/src/vector.c+++ b/src/vector.c@@ -26,11 +26,6 @@
#include "varatt.h"
#endif
-#if PG_VERSION_NUM < 130000-#define TYPALIGN_DOUBLE 'd'-#define TYPALIGN_INT 'i'-#endif-
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
@@ -463,8 +458,8 @@ array_to_vector(PG_FUNCTION_ARGS)
if (ARR_NDIM(array) > 1)
ereport(ERROR,
- (errcode(ERRCODE_DATA_EXCEPTION),- errmsg("array must be 1-D")));+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),+ errmsg("array must be one-dimensional")));
if (ARR_HASNULL(array) && array_contains_nulls(array))
ereport(ERROR,
diff --git a/src/vector.h b/src/vector.hindex e29ccdc6a..7369ea076 100644--- a/src/vector.h+++ b/src/vector.h@@ -27,4 +27,9 @@ int vector_cmp_internal(Vector * a, Vector * b);
#define FUNCTION_PREFIX PGDLLEXPORT
#endif
+#if PG_VERSION_NUM < 130000+#define TYPALIGN_DOUBLE 'd'+#define TYPALIGN_INT 'i'+#endif+
#endif
diff --git a/test/expected/cast.out b/test/expected/cast.outindex 1aba43c73..ae908caa7 100644--- a/test/expected/cast.out+++ b/test/expected/cast.out@@ -59,7 +59,7 @@ ERROR: infinite value not allowed in vector
SELECT '{}'::real[]::vector;
ERROR: vector must have at least 1 dimension
SELECT '{{1}}'::real[]::vector;
-ERROR: array must be 1-D+ERROR: array must be one-dimensional
SELECT '{1,2,3}'::double precision[]::vector;
vector
---------
@@ -208,10 +208,74 @@ SELECT '{1:1e-8}/1'::sparsevec::halfvec;
[0]
(1 row)
+SELECT '{2:1.5,4:3.5}/5'::sparsevec::real[];+ float4 +-----------------+ {0,1.5,0,3.5,0}+(1 row)++SELECT array_length('{}/16001'::sparsevec::real[], 1);+ array_length +--------------+ 16001+(1 row)+
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
+SELECT ARRAY[NULL]::real[]::sparsevec;+ERROR: array must not contain nulls+SELECT ARRAY[NULL,1,2,3]::sparsevec;+ERROR: array must not contain nulls+SELECT ARRAY[1,2,3]::sparsevec;+ array +-----------------+ {1:1,2:2,3:3}/3+(1 row)++SELECT ARRAY[.1,2,3]::sparsevec;+ array +-------------------+ {1:0.1,2:2,3:3}/3+(1 row)++SELECT ARRAY[1,2,3]::float4[]::sparsevec;+ array +-----------------+ {1:1,2:2,3:3}/3+(1 row)++SELECT ARRAY[1,2,3]::float8[]::sparsevec;+ array +-----------------+ {1:1,2:2,3:3}/3+(1 row)++SELECT ARRAY[1,2,3]::numeric[]::sparsevec;+ array +-----------------+ {1:1,2:2,3:3}/3+(1 row)++SELECT ARRAY[1,2,0,3]::real[]::sparsevec(2);+ERROR: expected 2 dimensions, not 4+SELECT ARRAY[1,2,0,3]::real[]::sparsevec(4);+ array +-----------------+ {1:1,2:2,4:3}/4+(1 row)++SELECT ARRAY[1,2,0,3]::real[]::sparsevec(40);+ERROR: expected 40 dimensions, not 4+SELECT array_agg(n)::sparsevec FROM generate_series(1, 16001) n;+ERROR: sparsevec cannot have more than 16000 non-zero elements+SELECT ARRAY(SELECT (i % 307 = 0)::integer FROM generate_series(1, 40000) AS i)::sparsevec;+ array +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ {307:1,614:1,921:1,1228:1,1535:1,1842:1,2149:1,2456:1,2763:1,3070:1,3377:1,3684:1,3991:1,4298:1,4605:1,4912:1,5219:1,5526:1,5833:1,6140:1,6447:1,6754:1,7061:1,7368:1,7675:1,7982:1,8289:1,8596:1,8903:1,9210:1,9517:1,9824:1,10131:1,10438:1,10745:1,11052:1,11359:1,11666:1,11973:1,12280:1,12587:1,12894:1,13201:1,13508:1,13815:1,14122:1,14429:1,14736:1,15043:1,15350:1,15657:1,15964:1,16271:1,16578:1,16885:1,17192:1,17499:1,17806:1,18113:1,18420:1,18727:1,19034:1,19341:1,19648:1,19955:1,20262:1,20569:1,20876:1,21183:1,21490:1,21797:1,22104:1,22411:1,22718:1,23025:1,23332:1,23639:1,23946:1,24253:1,24560:1,24867:1,25174:1,25481:1,25788:1,26095:1,26402:1,26709:1,27016:1,27323:1,27630:1,27937:1,28244:1,28551:1,28858:1,29165:1,29472:1,29779:1,30086:1,30393:1,30700:1,31007:1,31314:1,31621:1,31928:1,32235:1,32542:1,32849:1,33156:1,33463:1,33770:1,34077:1,34384:1,34691:1,34998:1,35305:1,35612:1,35919:1,36226:1,36533:1,36840:1,37147:1,37454:1,37761:1,38068:1,38375:1,38682:1,38989:1,39296:1,39603:1,39910:1}/40000+(1 row)+
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
?column?
diff --git a/test/sql/cast.sql b/test/sql/cast.sqlindex cd2eb3cb0..e299126e8 100644--- a/test/sql/cast.sql+++ b/test/sql/cast.sql@@ -58,8 +58,24 @@ SELECT '{}/16001'::sparsevec::halfvec;
SELECT '{1:65520}/1'::sparsevec::halfvec;
SELECT '{1:1e-8}/1'::sparsevec::halfvec;
+SELECT '{2:1.5,4:3.5}/5'::sparsevec::real[];+SELECT array_length('{}/16001'::sparsevec::real[], 1);+
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
+SELECT ARRAY[NULL]::real[]::sparsevec;+SELECT ARRAY[NULL,1,2,3]::sparsevec;+SELECT ARRAY[1,2,3]::sparsevec;+SELECT ARRAY[.1,2,3]::sparsevec;+SELECT ARRAY[1,2,3]::float4[]::sparsevec;+SELECT ARRAY[1,2,3]::float8[]::sparsevec;+SELECT ARRAY[1,2,3]::numeric[]::sparsevec;+SELECT ARRAY[1,2,0,3]::real[]::sparsevec(2);+SELECT ARRAY[1,2,0,3]::real[]::sparsevec(4);+SELECT ARRAY[1,2,0,3]::real[]::sparsevec(40);+SELECT array_agg(n)::sparsevec FROM generate_series(1, 16001) n;+SELECT ARRAY(SELECT (i % 307 = 0)::integer FROM generate_series(1, 40000) AS i)::sparsevec;+
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];