mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
149 Commits
concat-v2
...
target-clo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
665b3dfa1c | ||
|
|
ce597f770d | ||
|
|
1234fffcb0 | ||
|
|
e70a47c154 | ||
|
|
0c9ad67a1c | ||
|
|
8a4845b52e | ||
|
|
e14fdba8b3 | ||
|
|
5abf83c415 | ||
|
|
96b30fd25d | ||
|
|
1c791480ff | ||
|
|
545ae30057 | ||
|
|
20fb2e0797 | ||
|
|
89629abc08 | ||
|
|
db112862a5 | ||
|
|
bb84d69e57 | ||
|
|
7ea1590ea3 | ||
|
|
d98eb0a28d | ||
|
|
72eee91d00 | ||
|
|
f5e6e58359 | ||
|
|
8f93d02c71 | ||
|
|
c5c82bafda | ||
|
|
f627e69c5f | ||
|
|
23944302fe | ||
|
|
9957ba6817 | ||
|
|
aed463dbad | ||
|
|
f64abe3aae | ||
|
|
06d90fdc76 | ||
|
|
cc4b01bd49 | ||
|
|
3621a84ef8 | ||
|
|
b9d5269547 | ||
|
|
fbc96bb488 | ||
|
|
5510ae5b8c | ||
|
|
70eee06e83 | ||
|
|
f2bffff460 | ||
|
|
af7d9b74a9 | ||
|
|
f1a71524f0 | ||
|
|
7710cc8c28 | ||
|
|
fea2eb262e | ||
|
|
1bc6f954f4 | ||
|
|
6fd6b0bd5f | ||
|
|
546006b7ca | ||
|
|
cca0edf458 | ||
|
|
8d9400bae3 | ||
|
|
a4531ca51f | ||
|
|
94ee6b13c3 | ||
|
|
e6a591275a | ||
|
|
7fddd296ee | ||
|
|
c581db9f98 | ||
|
|
626bc053e5 | ||
|
|
66a29dbdf3 | ||
|
|
1c26da6ef5 | ||
|
|
000cc13c29 | ||
|
|
bbfe1e8b61 | ||
|
|
7e8be16e37 | ||
|
|
17c2f9c0b6 | ||
|
|
bd52ed29e0 | ||
|
|
245bac5e8e | ||
|
|
d84fc303ee | ||
|
|
4ff36af67e | ||
|
|
5834b58c5a | ||
|
|
381216a956 | ||
|
|
c3c6af8a84 | ||
|
|
d45f561d75 | ||
|
|
e1647473c9 | ||
|
|
e8bd7cd2f5 | ||
|
|
bed40ec0b5 | ||
|
|
d64295dfd7 | ||
|
|
8178a902ce | ||
|
|
f9f53b64e8 | ||
|
|
fc83cd8d12 | ||
|
|
1e41ed6f15 | ||
|
|
e6ca831f3d | ||
|
|
a824af42fb | ||
|
|
8a29bf4619 | ||
|
|
33369e0744 | ||
|
|
34b09cc062 | ||
|
|
d8f3e18db6 | ||
|
|
e6e7d7c1bc | ||
|
|
bf355792b2 | ||
|
|
12f4a34708 | ||
|
|
f6becf01aa | ||
|
|
dd5b856f68 | ||
|
|
9c96164f2c | ||
|
|
b583803b2c | ||
|
|
a04bf7fce2 | ||
|
|
62b411f94c | ||
|
|
82a17b81f5 | ||
|
|
3b2ca7df7a | ||
|
|
21d125abed | ||
|
|
f42ccd451d | ||
|
|
85345e3f8c | ||
|
|
05ce20990c | ||
|
|
f3477cf28d | ||
|
|
434f3f5e88 | ||
|
|
bd6fdb73eb | ||
|
|
ab382a2053 | ||
|
|
191c8e1cca | ||
|
|
3eba34e5e3 | ||
|
|
862f17c1de | ||
|
|
21bcff6722 | ||
|
|
60b4bb2ad1 | ||
|
|
c27363fbf7 | ||
|
|
06309f5d07 | ||
|
|
39b8bd1816 | ||
|
|
925aa4e048 | ||
|
|
9ed39cee67 | ||
|
|
494087222f | ||
|
|
4c0b10451f | ||
|
|
3bd67fef54 | ||
|
|
d861a0304e | ||
|
|
d8719d59a3 | ||
|
|
98d4b1a364 | ||
|
|
33daf87fcb | ||
|
|
faa33c32d9 | ||
|
|
0df30c12a7 | ||
|
|
8d7e0e693c | ||
|
|
457adcbbdb | ||
|
|
bada41484f | ||
|
|
60104264d5 | ||
|
|
53c4faaf72 | ||
|
|
5fa3da5400 | ||
|
|
4450029bdc | ||
|
|
aec853dc68 | ||
|
|
2d24d65f1c | ||
|
|
abd9963e66 | ||
|
|
7e5df3c9fe | ||
|
|
61e803a4dc | ||
|
|
2e5cbf611a | ||
|
|
d28b2cfccf | ||
|
|
6c4a115ebf | ||
|
|
c421dc6483 | ||
|
|
8961de6179 | ||
|
|
9f61dcff5d | ||
|
|
7667abe9a0 | ||
|
|
3219a30290 | ||
|
|
483e42b9c4 | ||
|
|
41b4bf79ba | ||
|
|
fc1aeee62c | ||
|
|
35d0fe88b9 | ||
|
|
aaa2d644ce | ||
|
|
253acbccf4 | ||
|
|
060d299e4b | ||
|
|
d7354a86a8 | ||
|
|
daba71694b | ||
|
|
506dd2b44a | ||
|
|
bcf41f5f66 | ||
|
|
abac7a3f77 | ||
|
|
32a502c838 | ||
|
|
1134e52762 |
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
@@ -123,6 +123,6 @@ jobs:
|
|||||||
- uses: ankane/setup-postgres-valgrind@v1
|
- uses: ankane/setup-postgres-valgrind@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: 16
|
postgres-version: 16
|
||||||
- run: make
|
- run: make OPTFLAGS=""
|
||||||
- run: sudo --preserve-env=PG_CONFIG make install
|
- run: sudo --preserve-env=PG_CONFIG make install
|
||||||
- run: make installcheck
|
- run: make installcheck
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
## 0.7.0 (unreleased)
|
## 0.7.0 (unreleased)
|
||||||
|
|
||||||
- Added support for bit vectors to HNSW
|
- Added `halfvec` type
|
||||||
|
- Added `sparsevec` type
|
||||||
|
- Added support for `bit` vectors to HNSW
|
||||||
- Added `hamming_distance` function
|
- Added `hamming_distance` function
|
||||||
- Added `jaccard_distance` function
|
- Added `jaccard_distance` function
|
||||||
- Added `quantize_binary` function
|
- Added `quantize_binary` function
|
||||||
- Added `subvector` function
|
- Added `subvector` function
|
||||||
- Added concatenate operator for vectors
|
- Added CPU dispatching for distance functions on Linux x86-64
|
||||||
- Updated comparison operators to support vectors with different dimensions
|
- Updated comparison operators to support vectors with different dimensions
|
||||||
|
|
||||||
## 0.6.2 (2024-03-18)
|
## 0.6.2 (2024-03-18)
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -3,8 +3,8 @@ EXTVERSION = 0.6.2
|
|||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
OBJS = src/bitvector.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/vector.o
|
OBJS = src/bitvector.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/vector.h
|
HEADERS = src/halfvec.h src/sparsevec.h src/vector.h
|
||||||
|
|
||||||
TESTS = $(wildcard test/sql/*.sql)
|
TESTS = $(wildcard test/sql/*.sql)
|
||||||
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.2
|
EXTVERSION = 0.6.2
|
||||||
|
|
||||||
OBJS = src\bitvector.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
|
OBJS = src\bitvector.obj src\halfutils.obj src\halfvec.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\sparsevec.obj src\vector.obj
|
||||||
HEADERS = src\vector.h
|
HEADERS = src\halfvec.h src\sparsevec.h src\vector.h
|
||||||
|
|
||||||
REGRESS = bit_functions btree cast copy hnsw_cosine hnsw_hamming hnsw_ip hnsw_jaccard hnsw_l2 hnsw_options hnsw_unlogged ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged vector_functions vector_input
|
REGRESS = bit_functions btree cast copy halfvec_functions halfvec_input hnsw_bit_hamming hnsw_bit_jaccard hnsw_halfvec_cosine hnsw_halfvec_ip hnsw_halfvec_l2 hnsw_options hnsw_sparsevec_cosine hnsw_sparsevec_ip hnsw_sparsevec_l2 hnsw_unlogged hnsw_vector_cosine hnsw_vector_ip hnsw_vector_l2 ivfflat_options ivfflat_unlogged ivfflat_vector_cosine ivfflat_vector_ip ivfflat_vector_l2 sparsevec_functions sparsevec_input vector_functions vector_input
|
||||||
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
||||||
|
|
||||||
# For /arch flags
|
# For /arch flags
|
||||||
|
|||||||
194
README.md
194
README.md
@@ -233,7 +233,12 @@ Jaccard distance - unreleased
|
|||||||
CREATE INDEX ON items USING hnsw (embedding bit_jaccard_ops);
|
CREATE INDEX ON items USING hnsw (embedding bit_jaccard_ops);
|
||||||
```
|
```
|
||||||
|
|
||||||
Vectors with up to 2,000 dimensions can be indexed, or bit vectors with up to 64,000 dimensions.
|
Supported types are:
|
||||||
|
|
||||||
|
- `vector` - up to 2,000 dimensions
|
||||||
|
- `halfvec` - up to 4,000 dimensions (unreleased)
|
||||||
|
- `bit` - up to 64,000 dimensions (unreleased)
|
||||||
|
- `sparsevec` - up to 1,000 non-zero elements (unreleased)
|
||||||
|
|
||||||
### Index Options
|
### Index Options
|
||||||
|
|
||||||
@@ -338,7 +343,10 @@ Cosine distance
|
|||||||
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
|
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
|
||||||
```
|
```
|
||||||
|
|
||||||
Vectors with up to 2,000 dimensions can be indexed.
|
Supported types are:
|
||||||
|
|
||||||
|
- `vector` - up to 2,000 dimensions
|
||||||
|
- `halfvec` - up to 4,000 dimensions (unreleased)
|
||||||
|
|
||||||
### Query Options
|
### Query Options
|
||||||
|
|
||||||
@@ -412,6 +420,103 @@ Use [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html
|
|||||||
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
|
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Half Vectors
|
||||||
|
|
||||||
|
*Unreleased*
|
||||||
|
|
||||||
|
Use the `halfvec` type to store half-precision vectors
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE items (id bigserial PRIMARY KEY, embedding halfvec(3));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Half Indexing
|
||||||
|
|
||||||
|
*Unreleased*
|
||||||
|
|
||||||
|
Index vectors at half precision for smaller indexes and faster build times
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw ((embedding::halfvec(3)) halfvec_l2_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
Get the nearest neighbors
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY embedding::halfvec(3) <-> '[1,2,3]' LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Binary Vectors
|
||||||
|
|
||||||
|
Use the `bit` type to store binary vectors ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/hash_image_search.py))
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE items (id bigserial PRIMARY KEY, embedding bit(3));
|
||||||
|
INSERT INTO items (embedding) VALUES ('000'), ('111');
|
||||||
|
```
|
||||||
|
|
||||||
|
Get the nearest neighbors by Hamming distance
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY bit_count(embedding # '101') LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
Or (unreleased)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY embedding <~> '101' LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
Also supports Jaccard distance (`<%>`)
|
||||||
|
|
||||||
|
## Binary Quantization
|
||||||
|
|
||||||
|
*Unreleased*
|
||||||
|
|
||||||
|
Use expression indexing for binary quantization
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw ((quantize_binary(embedding)::bit(3)) bit_hamming_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
Get the nearest neighbors by Hamming distance
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY quantize_binary(embedding)::bit(3) <~> quantize_binary('[1,-2,3]') LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
Re-rank by the original vectors for better recall
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM (
|
||||||
|
SELECT * FROM items ORDER BY quantize_binary(embedding)::bit(3) <~> quantize_binary('[1,-2,3]') LIMIT 20
|
||||||
|
) ORDER BY embedding <=> '[1,-2,3]' LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sparse Vectors
|
||||||
|
|
||||||
|
*Unreleased*
|
||||||
|
|
||||||
|
Use the `sparsevec` type to store sparse vectors
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE items (id bigserial PRIMARY KEY, embedding sparsevec(5));
|
||||||
|
```
|
||||||
|
|
||||||
|
Insert vectors
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO items (embedding) VALUES ('{1:1,3:2,5:3}/5'), ('{1:4,3:5,5:6}/5');
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: The format is `{index1:value1,index2:value2,...}/dimensions` and indices start at 1 like SQL arrays
|
||||||
|
|
||||||
|
Get the nearest neighbors by L2 distance
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY embedding <-> '{1:3,3:1,5:2}/5' LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
## Hybrid Search
|
## Hybrid Search
|
||||||
|
|
||||||
Use together with Postgres [full-text search](https://www.postgresql.org/docs/current/textsearch-intro.html) for hybrid search.
|
Use together with Postgres [full-text search](https://www.postgresql.org/docs/current/textsearch-intro.html) for hybrid search.
|
||||||
@@ -423,6 +528,30 @@ SELECT id, content FROM items, plainto_tsquery('hello search') query
|
|||||||
|
|
||||||
You can use [Reciprocal Rank Fusion](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search_rrf.py) or a [cross-encoder](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search.py) to combine results.
|
You can use [Reciprocal Rank Fusion](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search_rrf.py) or a [cross-encoder](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search.py) to combine results.
|
||||||
|
|
||||||
|
## Subvector Indexing
|
||||||
|
|
||||||
|
*Unreleased*
|
||||||
|
|
||||||
|
Use expression indexing to index subvectors
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw ((subvector(embedding, 1, 3)::vector(3)) vector_cosine_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
Get the nearest neighbors by cosine distance
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM items ORDER BY subvector(embedding, 1, 3)::vector(3) <=> subvector('[1,2,3,4,5]'::vector, 1, 3) LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
Re-rank by the full vectors for better recall
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM (
|
||||||
|
SELECT * FROM items ORDER BY subvector(embedding, 1, 3)::vector(3) <=> subvector('[1,2,3,4,5]'::vector, 1, 3) LIMIT 20
|
||||||
|
) ORDER BY embedding <=> '[1,2,3,4,5]' LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
### Tuning
|
### Tuning
|
||||||
@@ -628,18 +757,6 @@ and query with:
|
|||||||
SELECT * FROM items ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
SELECT * FROM items ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Are binary vectors supported?
|
|
||||||
|
|
||||||
You can store binary vectors and perform exact nearest neighbor search by Hamming distance in Postgres without an extension ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/hash_image_search.py)).
|
|
||||||
|
|
||||||
```tsql
|
|
||||||
CREATE TABLE items (id bigserial PRIMARY KEY, embedding bit(3));
|
|
||||||
INSERT INTO items (embedding) VALUES (B'000'), (B'111');
|
|
||||||
SELECT * FROM items ORDER BY bit_count(embedding # B'101') LIMIT 5;
|
|
||||||
```
|
|
||||||
|
|
||||||
Indexing is not currently supported.
|
|
||||||
|
|
||||||
#### Do indexes need to fit into memory?
|
#### Do indexes need to fit into memory?
|
||||||
|
|
||||||
No, but like other index types, you’ll likely see better performance if they do. You can get the size of an index with:
|
No, but like other index types, you’ll likely see better performance if they do. You can get the size of an index with:
|
||||||
@@ -712,7 +829,9 @@ Also, note that `NULL` vectors are not indexed (as well as zero vectors for cosi
|
|||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
- [Vector](#vector-type)
|
- [Vector](#vector-type)
|
||||||
|
- [Halfvec](#halfvec-type)
|
||||||
- [Bit](#bit-type)
|
- [Bit](#bit-type)
|
||||||
|
- [Sparsevec](#sparsevec-type)
|
||||||
|
|
||||||
### Vector Type
|
### Vector Type
|
||||||
|
|
||||||
@@ -725,7 +844,6 @@ Operator | Description | Added
|
|||||||
\+ | element-wise addition |
|
\+ | element-wise addition |
|
||||||
\- | element-wise subtraction |
|
\- | element-wise subtraction |
|
||||||
\* | element-wise multiplication | 0.5.0
|
\* | element-wise multiplication | 0.5.0
|
||||||
\|\| | concatenate | unreleased
|
|
||||||
<-> | Euclidean distance |
|
<-> | Euclidean distance |
|
||||||
<#> | negative inner product |
|
<#> | negative inner product |
|
||||||
<=> | cosine distance |
|
<=> | cosine distance |
|
||||||
@@ -750,9 +868,32 @@ Function | Description | Added
|
|||||||
avg(vector) → vector | average |
|
avg(vector) → vector | average |
|
||||||
sum(vector) → vector | sum | 0.5.0
|
sum(vector) → vector | sum | 0.5.0
|
||||||
|
|
||||||
|
### Halfvec Type
|
||||||
|
|
||||||
|
Each half vector takes `2 * dimensions + 8` bytes of storage. Each element is a half-precision floating-point number, and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Half vectors can have up to 16,000 dimensions.
|
||||||
|
|
||||||
|
### Halfvec Operators
|
||||||
|
|
||||||
|
Operator | Description | Added
|
||||||
|
--- | --- | ---
|
||||||
|
<-> | Euclidean distance | unreleased
|
||||||
|
<#> | negative inner product | unreleased
|
||||||
|
<=> | cosine distance | unreleased
|
||||||
|
|
||||||
|
### Halfvec Functions
|
||||||
|
|
||||||
|
Function | Description | Added
|
||||||
|
--- | --- | ---
|
||||||
|
cosine_distance(halfvec, halfvec) → double precision | cosine distance | unreleased
|
||||||
|
inner_product(halfvec, halfvec) → double precision | inner product | unreleased
|
||||||
|
l2_distance(halfvec, halfvec) → double precision | Euclidean distance | unreleased
|
||||||
|
l1_distance(halfvec, halfvec) → double precision | taxicab distance | unreleased
|
||||||
|
quantize_binary(halfvec) → bit | quantize | unreleased
|
||||||
|
subvector(halfvec, integer, integer) → halfvec | subvector | unreleased
|
||||||
|
|
||||||
### Bit Type
|
### Bit Type
|
||||||
|
|
||||||
Each bit vector takes `dimensions / 8 + (5 or 8)` bytes of storage. See the [Postgres docs](https://www.postgresql.org/docs/current/datatype-bit.html) for more info.
|
Each bit vector takes `dimensions / 8 + 8` bytes of storage. See the [Postgres docs](https://www.postgresql.org/docs/current/datatype-bit.html) for more info.
|
||||||
|
|
||||||
### Bit Operators
|
### Bit Operators
|
||||||
|
|
||||||
@@ -768,6 +909,27 @@ Function | Description | Added
|
|||||||
hamming_distance(bit, bit) → double precision | Hamming distance | unreleased
|
hamming_distance(bit, bit) → double precision | Hamming distance | unreleased
|
||||||
jaccard_distance(bit, bit) → double precision | Jaccard distance | unreleased
|
jaccard_distance(bit, bit) → double precision | Jaccard distance | unreleased
|
||||||
|
|
||||||
|
### Sparsevec Type
|
||||||
|
|
||||||
|
Each sparse vector takes `8 * non-zero elements + 16` bytes of storage. Each element is a single-precision floating-point number, and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Sparse vectors can have up to 16,000 non-zero elements.
|
||||||
|
|
||||||
|
### Sparsevec Operators
|
||||||
|
|
||||||
|
Operator | Description | Added
|
||||||
|
--- | --- | ---
|
||||||
|
<-> | Euclidean distance | unreleased
|
||||||
|
<#> | negative inner product | unreleased
|
||||||
|
<=> | cosine distance | unreleased
|
||||||
|
|
||||||
|
### Sparsevec Functions
|
||||||
|
|
||||||
|
Function | Description | Added
|
||||||
|
--- | --- | ---
|
||||||
|
cosine_distance(sparsevec, sparsevec) → double precision | cosine distance | unreleased
|
||||||
|
inner_product(sparsevec, sparsevec) → double precision | inner product | unreleased
|
||||||
|
l2_distance(sparsevec, sparsevec) → double precision | Euclidean distance | unreleased
|
||||||
|
l1_distance(sparsevec, sparsevec) → double precision | taxicab distance | unreleased
|
||||||
|
|
||||||
## Installation Notes - Linux and Mac
|
## Installation Notes - Linux and Mac
|
||||||
|
|
||||||
### Postgres Location
|
### Postgres Location
|
||||||
|
|||||||
@@ -7,13 +7,6 @@ CREATE FUNCTION quantize_binary(vector) RETURNS bit
|
|||||||
CREATE FUNCTION subvector(vector, int, int) RETURNS vector
|
CREATE FUNCTION subvector(vector, int, int) RETURNS vector
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION vector_concat(vector, vector) RETURNS vector
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE OPERATOR || (
|
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_concat
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE FUNCTION hamming_distance(bit, bit) RETURNS float8
|
CREATE FUNCTION hamming_distance(bit, bit) RETURNS float8
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
@@ -39,3 +32,252 @@ CREATE OPERATOR CLASS bit_jaccard_ops
|
|||||||
FOR TYPE bit USING hnsw AS
|
FOR TYPE bit USING hnsw AS
|
||||||
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
||||||
FUNCTION 1 jaccard_distance(bit, bit);
|
FUNCTION 1 jaccard_distance(bit, bit);
|
||||||
|
|
||||||
|
CREATE TYPE halfvec;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_in(cstring, oid, integer) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_out(halfvec) RETURNS cstring
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_typmod_in(cstring[]) RETURNS integer
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_recv(internal, oid, integer) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_send(halfvec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE halfvec (
|
||||||
|
INPUT = halfvec_in,
|
||||||
|
OUTPUT = halfvec_out,
|
||||||
|
TYPMOD_IN = halfvec_typmod_in,
|
||||||
|
RECEIVE = halfvec_recv,
|
||||||
|
SEND = halfvec_send,
|
||||||
|
STORAGE = external
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION inner_product(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l1_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_norm(halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION quantize_binary(halfvec) RETURNS bit
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_quantize_binary' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION subvector(halfvec, int, int) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_subvector' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_l2_squared_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_negative_inner_product(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_spherical_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec(halfvec, integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(integer[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(real[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(double precision[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(numeric[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_to_float4(halfvec, integer, boolean) RETURNS real[]
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS halfvec)
|
||||||
|
WITH FUNCTION halfvec(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS real[])
|
||||||
|
WITH FUNCTION halfvec_to_float4(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (integer[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(integer[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (real[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(real[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (double precision[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(double precision[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (numeric[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(numeric[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <#> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = halfvec_negative_inner_product,
|
||||||
|
COMMUTATOR = '<#>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <=> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = cosine_distance,
|
||||||
|
COMMUTATOR = '<=>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_l2_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <-> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_l2_squared_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 3 l2_distance(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_ip_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <#> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 3 halfvec_spherical_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 4 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_cosine_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <=> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 2 halfvec_norm(halfvec),
|
||||||
|
FUNCTION 3 halfvec_spherical_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 4 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_l2_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_l2_squared_distance(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_ip_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_cosine_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 2 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_to_vector(halfvec, integer, boolean) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_to_halfvec(vector, integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS vector)
|
||||||
|
WITH FUNCTION halfvec_to_vector(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (vector AS halfvec)
|
||||||
|
WITH FUNCTION vector_to_halfvec(vector, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE TYPE sparsevec;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_in(cstring, oid, integer) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_out(sparsevec) RETURNS cstring
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_typmod_in(cstring[]) RETURNS integer
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_recv(internal, oid, integer) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_send(sparsevec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE sparsevec (
|
||||||
|
INPUT = sparsevec_in,
|
||||||
|
OUTPUT = sparsevec_out,
|
||||||
|
TYPMOD_IN = sparsevec_typmod_in,
|
||||||
|
RECEIVE = sparsevec_recv,
|
||||||
|
SEND = sparsevec_send,
|
||||||
|
STORAGE = external
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION inner_product(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_norm(sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_l2_squared_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_negative_inner_product(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec(sparsevec, integer, boolean) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_to_sparsevec(vector, integer, boolean) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_to_vector(sparsevec, integer, boolean) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE CAST (sparsevec AS sparsevec)
|
||||||
|
WITH FUNCTION sparsevec(sparsevec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (sparsevec AS vector)
|
||||||
|
WITH FUNCTION sparsevec_to_vector(sparsevec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (vector AS sparsevec)
|
||||||
|
WITH FUNCTION vector_to_sparsevec(vector, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <#> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = sparsevec_negative_inner_product,
|
||||||
|
COMMUTATOR = '<#>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <=> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = cosine_distance,
|
||||||
|
COMMUTATOR = '<=>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_l2_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_l2_squared_distance(sparsevec, sparsevec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_ip_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_negative_inner_product(sparsevec, sparsevec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_cosine_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_negative_inner_product(sparsevec, sparsevec),
|
||||||
|
FUNCTION 2 sparsevec_norm(sparsevec);
|
||||||
|
|||||||
286
sql/vector.sql
286
sql/vector.sql
@@ -105,9 +105,6 @@ CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
|
|||||||
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
|
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION vector_concat(vector, vector) RETURNS vector
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
-- vector aggregates
|
-- vector aggregates
|
||||||
|
|
||||||
CREATE AGGREGATE avg(vector) (
|
CREATE AGGREGATE avg(vector) (
|
||||||
@@ -197,10 +194,6 @@ CREATE OPERATOR * (
|
|||||||
COMMUTATOR = *
|
COMMUTATOR = *
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR || (
|
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_concat
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE OPERATOR < (
|
CREATE OPERATOR < (
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_lt,
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_lt,
|
||||||
COMMUTATOR = > , NEGATOR = >= ,
|
COMMUTATOR = > , NEGATOR = >= ,
|
||||||
@@ -328,3 +321,282 @@ CREATE OPERATOR CLASS bit_jaccard_ops
|
|||||||
FOR TYPE bit USING hnsw AS
|
FOR TYPE bit USING hnsw AS
|
||||||
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
||||||
FUNCTION 1 jaccard_distance(bit, bit);
|
FUNCTION 1 jaccard_distance(bit, bit);
|
||||||
|
|
||||||
|
-- halfvec type
|
||||||
|
|
||||||
|
CREATE TYPE halfvec;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_in(cstring, oid, integer) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_out(halfvec) RETURNS cstring
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_typmod_in(cstring[]) RETURNS integer
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_recv(internal, oid, integer) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_send(halfvec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE halfvec (
|
||||||
|
INPUT = halfvec_in,
|
||||||
|
OUTPUT = halfvec_out,
|
||||||
|
TYPMOD_IN = halfvec_typmod_in,
|
||||||
|
RECEIVE = halfvec_recv,
|
||||||
|
SEND = halfvec_send,
|
||||||
|
STORAGE = external
|
||||||
|
);
|
||||||
|
|
||||||
|
-- halfvec functions
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION inner_product(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l1_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_norm(halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION quantize_binary(halfvec) RETURNS bit
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_quantize_binary' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION subvector(halfvec, int, int) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME', 'halfvec_subvector' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- halfvec private functions
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_l2_squared_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_negative_inner_product(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_spherical_distance(halfvec, halfvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- halfvec cast functions
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec(halfvec, integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(integer[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(real[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(double precision[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_halfvec(numeric[], integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_to_float4(halfvec, integer, boolean) RETURNS real[]
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- halfvec casts
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS halfvec)
|
||||||
|
WITH FUNCTION halfvec(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS real[])
|
||||||
|
WITH FUNCTION halfvec_to_float4(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (integer[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(integer[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (real[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(real[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (double precision[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(double precision[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE CAST (numeric[] AS halfvec)
|
||||||
|
WITH FUNCTION array_to_halfvec(numeric[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
-- halfvec operators
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <#> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = halfvec_negative_inner_product,
|
||||||
|
COMMUTATOR = '<#>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <=> (
|
||||||
|
LEFTARG = halfvec, RIGHTARG = halfvec, PROCEDURE = cosine_distance,
|
||||||
|
COMMUTATOR = '<=>'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- halfvec opclasses
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_l2_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <-> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_l2_squared_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 3 l2_distance(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_ip_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <#> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 3 halfvec_spherical_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 4 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_cosine_ops
|
||||||
|
FOR TYPE halfvec USING ivfflat AS
|
||||||
|
OPERATOR 1 <=> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 2 halfvec_norm(halfvec),
|
||||||
|
FUNCTION 3 halfvec_spherical_distance(halfvec, halfvec),
|
||||||
|
FUNCTION 4 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_l2_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_l2_squared_distance(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_ip_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS halfvec_cosine_ops
|
||||||
|
FOR TYPE halfvec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (halfvec, halfvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 halfvec_negative_inner_product(halfvec, halfvec),
|
||||||
|
FUNCTION 2 halfvec_norm(halfvec);
|
||||||
|
|
||||||
|
-- extension casts
|
||||||
|
|
||||||
|
CREATE FUNCTION halfvec_to_vector(halfvec, integer, boolean) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_to_halfvec(vector, integer, boolean) RETURNS halfvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE CAST (halfvec AS vector)
|
||||||
|
WITH FUNCTION halfvec_to_vector(halfvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (vector AS halfvec)
|
||||||
|
WITH FUNCTION vector_to_halfvec(vector, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
--- sparsevec type
|
||||||
|
|
||||||
|
CREATE TYPE sparsevec;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_in(cstring, oid, integer) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_out(sparsevec) RETURNS cstring
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_typmod_in(cstring[]) RETURNS integer
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_recv(internal, oid, integer) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_send(sparsevec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE sparsevec (
|
||||||
|
INPUT = sparsevec_in,
|
||||||
|
OUTPUT = sparsevec_out,
|
||||||
|
TYPMOD_IN = sparsevec_typmod_in,
|
||||||
|
RECEIVE = sparsevec_recv,
|
||||||
|
SEND = sparsevec_send,
|
||||||
|
STORAGE = external
|
||||||
|
);
|
||||||
|
|
||||||
|
-- sparsevec functions
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION inner_product(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'sparsevec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_norm(sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- sparsevec private functions
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_l2_squared_distance(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_negative_inner_product(sparsevec, sparsevec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- sparsevec cast functions
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec(sparsevec, integer, boolean) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_to_sparsevec(vector, integer, boolean) RETURNS sparsevec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION sparsevec_to_vector(sparsevec, integer, boolean) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- sparsevec casts
|
||||||
|
|
||||||
|
CREATE CAST (sparsevec AS sparsevec)
|
||||||
|
WITH FUNCTION sparsevec(sparsevec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (sparsevec AS vector)
|
||||||
|
WITH FUNCTION sparsevec_to_vector(sparsevec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (vector AS sparsevec)
|
||||||
|
WITH FUNCTION vector_to_sparsevec(vector, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
-- sparsevec operators
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <#> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = sparsevec_negative_inner_product,
|
||||||
|
COMMUTATOR = '<#>'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <=> (
|
||||||
|
LEFTARG = sparsevec, RIGHTARG = sparsevec, PROCEDURE = cosine_distance,
|
||||||
|
COMMUTATOR = '<=>'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- sparsevec opclasses
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_l2_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_l2_squared_distance(sparsevec, sparsevec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_ip_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_negative_inner_product(sparsevec, sparsevec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS sparsevec_cosine_ops
|
||||||
|
FOR TYPE sparsevec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 sparsevec_negative_inner_product(sparsevec, sparsevec),
|
||||||
|
FUNCTION 2 sparsevec_norm(sparsevec);
|
||||||
|
|||||||
156
src/halfutils.c
Normal file
156
src/halfutils.c
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
|
|
||||||
|
#ifdef HALFVEC_DISPATCH
|
||||||
|
#include <immintrin.h>
|
||||||
|
|
||||||
|
#if defined(HAVE__GET_CPUID)
|
||||||
|
#include <cpuid.h>
|
||||||
|
#elif defined(HAVE__CPUID)
|
||||||
|
#include <intrin.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
#define TARGET_F16C_FMA
|
||||||
|
#else
|
||||||
|
#define TARGET_F16C_FMA __attribute__((target("f16c,fma")))
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
float (*HalfvecL2SquaredDistance) (int dim, half * ax, half * bx);
|
||||||
|
float (*HalfvecInnerProduct) (int dim, half * ax, half * bx);
|
||||||
|
|
||||||
|
static float
|
||||||
|
HalfvecL2SquaredDistanceDefault(int dim, half * ax, half * bx)
|
||||||
|
{
|
||||||
|
float distance = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
float diff = HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]);
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef HALFVEC_DISPATCH
|
||||||
|
TARGET_F16C_FMA static float
|
||||||
|
HalfvecL2SquaredDistanceF16cFma(int dim, half * ax, half * bx)
|
||||||
|
{
|
||||||
|
float distance;
|
||||||
|
int i;
|
||||||
|
float s[8];
|
||||||
|
int count = (dim / 8) * 8;
|
||||||
|
__m256 dist = _mm256_setzero_ps();
|
||||||
|
|
||||||
|
for (i = 0; i < count; i += 8)
|
||||||
|
{
|
||||||
|
__m128i axi = _mm_loadu_si128((__m128i *) (ax + i));
|
||||||
|
__m128i bxi = _mm_loadu_si128((__m128i *) (bx + i));
|
||||||
|
__m256 axs = _mm256_cvtph_ps(axi);
|
||||||
|
__m256 bxs = _mm256_cvtph_ps(bxi);
|
||||||
|
__m256 diff = _mm256_sub_ps(axs, bxs);
|
||||||
|
|
||||||
|
dist = _mm256_fmadd_ps(diff, diff, dist);
|
||||||
|
}
|
||||||
|
|
||||||
|
_mm256_storeu_ps(s, dist);
|
||||||
|
|
||||||
|
distance = s[0] + s[1] + s[2] + s[3] + s[4] + s[5] + s[6] + s[7];
|
||||||
|
|
||||||
|
for (; i < dim; i++)
|
||||||
|
{
|
||||||
|
float diff = HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]);
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static float
|
||||||
|
HalfvecInnerProductDefault(int dim, half * ax, half * bx)
|
||||||
|
{
|
||||||
|
float distance = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
distance += HalfToFloat4(ax[i]) * HalfToFloat4(bx[i]);
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef HALFVEC_DISPATCH
|
||||||
|
TARGET_F16C_FMA static float
|
||||||
|
HalfvecInnerProductF16cFma(int dim, half * ax, half * bx)
|
||||||
|
{
|
||||||
|
float distance;
|
||||||
|
int i;
|
||||||
|
float s[8];
|
||||||
|
int count = (dim / 8) * 8;
|
||||||
|
__m256 dist = _mm256_setzero_ps();
|
||||||
|
|
||||||
|
for (i = 0; i < count; i += 8)
|
||||||
|
{
|
||||||
|
__m128i axi = _mm_loadu_si128((__m128i *) (ax + i));
|
||||||
|
__m128i bxi = _mm_loadu_si128((__m128i *) (bx + i));
|
||||||
|
__m256 axs = _mm256_cvtph_ps(axi);
|
||||||
|
__m256 bxs = _mm256_cvtph_ps(bxi);
|
||||||
|
|
||||||
|
dist = _mm256_fmadd_ps(axs, bxs, dist);
|
||||||
|
}
|
||||||
|
|
||||||
|
_mm256_storeu_ps(s, dist);
|
||||||
|
|
||||||
|
distance = s[0] + s[1] + s[2] + s[3] + s[4] + s[5] + s[6] + s[7];
|
||||||
|
|
||||||
|
for (; i < dim; i++)
|
||||||
|
distance += HalfToFloat4(ax[i]) * HalfToFloat4(bx[i]);
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef HALFVEC_DISPATCH
|
||||||
|
#define CPU_FEATURE_FMA (1 << 12)
|
||||||
|
#define CPU_FEATURE_F16C (1 << 29)
|
||||||
|
|
||||||
|
static bool
|
||||||
|
SupportsCpuFeature(unsigned int feature)
|
||||||
|
{
|
||||||
|
unsigned int exx[4] = {0, 0, 0, 0};
|
||||||
|
|
||||||
|
#if defined(HAVE__GET_CPUID)
|
||||||
|
__get_cpuid(1, &exx[0], &exx[1], &exx[2], &exx[3]);
|
||||||
|
#elif defined(HAVE__CPUID)
|
||||||
|
__cpuid(exx, 1);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return (exx[2] & feature) == feature;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void
|
||||||
|
HalfvecInit(void)
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* Could skip pointer when single function, but no difference in
|
||||||
|
* performance
|
||||||
|
*/
|
||||||
|
HalfvecL2SquaredDistance = HalfvecL2SquaredDistanceDefault;
|
||||||
|
HalfvecInnerProduct = HalfvecInnerProductDefault;
|
||||||
|
|
||||||
|
#ifdef HALFVEC_DISPATCH
|
||||||
|
if (SupportsCpuFeature(CPU_FEATURE_FMA | CPU_FEATURE_F16C))
|
||||||
|
{
|
||||||
|
HalfvecL2SquaredDistance = HalfvecL2SquaredDistanceF16cFma;
|
||||||
|
HalfvecInnerProduct = HalfvecInnerProductF16cFma;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
254
src/halfutils.h
Normal file
254
src/halfutils.h
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
#ifndef HALFUTILS_H
|
||||||
|
#define HALFUTILS_H
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "common/shortest_dec.h"
|
||||||
|
#include "halfvec.h"
|
||||||
|
|
||||||
|
#ifdef F16C_SUPPORT
|
||||||
|
#include <immintrin.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
extern float (*HalfvecL2SquaredDistance) (int dim, half * ax, half * bx);
|
||||||
|
extern float (*HalfvecInnerProduct) (int dim, half * ax, half * bx);
|
||||||
|
|
||||||
|
void HalfvecInit(void);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check if half is NaN
|
||||||
|
*/
|
||||||
|
static inline bool
|
||||||
|
HalfIsNan(half num)
|
||||||
|
{
|
||||||
|
#ifdef FLT16_SUPPORT
|
||||||
|
return isnan(num);
|
||||||
|
#else
|
||||||
|
return (num & 0x7C00) == 0x7C00 && (num & 0x7FFF) != 0x7C00;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check if half is infinite
|
||||||
|
*/
|
||||||
|
static inline bool
|
||||||
|
HalfIsInf(half num)
|
||||||
|
{
|
||||||
|
#ifdef FLT16_SUPPORT
|
||||||
|
return isinf(num);
|
||||||
|
#else
|
||||||
|
return (num & 0x7FFF) == 0x7C00;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert a half to a float4
|
||||||
|
*/
|
||||||
|
static inline float
|
||||||
|
HalfToFloat4(half num)
|
||||||
|
{
|
||||||
|
#if defined(F16C_SUPPORT)
|
||||||
|
return _cvtsh_ss(num);
|
||||||
|
#elif defined(FLT16_SUPPORT)
|
||||||
|
return (float) num;
|
||||||
|
#else
|
||||||
|
/* TODO Improve performance */
|
||||||
|
|
||||||
|
/* Assumes same endianness for floats and integers */
|
||||||
|
union
|
||||||
|
{
|
||||||
|
float f;
|
||||||
|
uint32 i;
|
||||||
|
} swapfloat;
|
||||||
|
|
||||||
|
union
|
||||||
|
{
|
||||||
|
half h;
|
||||||
|
uint16 i;
|
||||||
|
} swaphalf;
|
||||||
|
|
||||||
|
uint16 bin;
|
||||||
|
uint32 exponent;
|
||||||
|
uint32 mantissa;
|
||||||
|
uint32 result;
|
||||||
|
|
||||||
|
swaphalf.h = num;
|
||||||
|
bin = swaphalf.i;
|
||||||
|
exponent = (bin & 0x7C00) >> 10;
|
||||||
|
mantissa = bin & 0x03FF;
|
||||||
|
|
||||||
|
/* Sign */
|
||||||
|
result = (bin & 0x8000) << 16;
|
||||||
|
|
||||||
|
if (unlikely(exponent == 31))
|
||||||
|
{
|
||||||
|
if (mantissa == 0)
|
||||||
|
{
|
||||||
|
/* Infinite */
|
||||||
|
result |= 0x7F800000;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* NaN */
|
||||||
|
result |= 0x7FC00000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (unlikely(exponent == 0))
|
||||||
|
{
|
||||||
|
/* Subnormal */
|
||||||
|
if (mantissa != 0)
|
||||||
|
{
|
||||||
|
exponent = -14;
|
||||||
|
|
||||||
|
for (int i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
mantissa <<= 1;
|
||||||
|
exponent -= 1;
|
||||||
|
|
||||||
|
if ((mantissa >> 10) % 2 == 1)
|
||||||
|
{
|
||||||
|
mantissa &= 0x03ff;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result |= (exponent + 127) << 23;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Normal */
|
||||||
|
result |= (exponent - 15 + 127) << 23;
|
||||||
|
}
|
||||||
|
|
||||||
|
result |= mantissa << 13;
|
||||||
|
|
||||||
|
swapfloat.i = result;
|
||||||
|
return swapfloat.f;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert a float4 to a half
|
||||||
|
*/
|
||||||
|
static inline half
|
||||||
|
Float4ToHalfUnchecked(float num)
|
||||||
|
{
|
||||||
|
#if defined(F16C_SUPPORT)
|
||||||
|
return _cvtss_sh(num, 0);
|
||||||
|
#elif defined(FLT16_SUPPORT)
|
||||||
|
return (_Float16) num;
|
||||||
|
#else
|
||||||
|
/* TODO Improve performance */
|
||||||
|
|
||||||
|
/* Assumes same endianness for floats and integers */
|
||||||
|
union
|
||||||
|
{
|
||||||
|
float f;
|
||||||
|
uint32 i;
|
||||||
|
} swapfloat;
|
||||||
|
|
||||||
|
union
|
||||||
|
{
|
||||||
|
half h;
|
||||||
|
uint16 i;
|
||||||
|
} swaphalf;
|
||||||
|
|
||||||
|
uint32 bin;
|
||||||
|
int exponent;
|
||||||
|
int mantissa;
|
||||||
|
uint16 result;
|
||||||
|
|
||||||
|
swapfloat.f = num;
|
||||||
|
bin = swapfloat.i;
|
||||||
|
exponent = (bin & 0x7F800000) >> 23;
|
||||||
|
mantissa = bin & 0x007FFFFF;
|
||||||
|
|
||||||
|
/* Sign */
|
||||||
|
result = (bin & 0x80000000) >> 16;
|
||||||
|
|
||||||
|
if (isinf(num))
|
||||||
|
{
|
||||||
|
/* Infinite */
|
||||||
|
result |= 0x7C00;
|
||||||
|
}
|
||||||
|
else if (isnan(num))
|
||||||
|
{
|
||||||
|
/* NaN */
|
||||||
|
result |= 0x7E00;
|
||||||
|
result |= mantissa >> 13;
|
||||||
|
}
|
||||||
|
else if (exponent > 98)
|
||||||
|
{
|
||||||
|
int m;
|
||||||
|
int gr;
|
||||||
|
int s;
|
||||||
|
|
||||||
|
exponent -= 127;
|
||||||
|
s = mantissa & 0x00000FFF;
|
||||||
|
|
||||||
|
/* Subnormal */
|
||||||
|
if (exponent < -14)
|
||||||
|
{
|
||||||
|
int diff = -exponent - 14;
|
||||||
|
|
||||||
|
mantissa >>= diff;
|
||||||
|
mantissa += 1 << (23 - diff);
|
||||||
|
s |= mantissa & 0x00000FFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
m = mantissa >> 13;
|
||||||
|
|
||||||
|
/* Round */
|
||||||
|
gr = (mantissa >> 12) % 4;
|
||||||
|
if (gr == 3 || (gr == 1 && s != 0))
|
||||||
|
m += 1;
|
||||||
|
|
||||||
|
if (m == 1024)
|
||||||
|
{
|
||||||
|
m = 0;
|
||||||
|
exponent += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exponent > 15)
|
||||||
|
{
|
||||||
|
/* Infinite */
|
||||||
|
result |= 0x7C00;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (exponent >= -14)
|
||||||
|
result |= (exponent + 15) << 10;
|
||||||
|
|
||||||
|
result |= m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
swaphalf.i = result;
|
||||||
|
return swaphalf.h;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert a float4 to a half
|
||||||
|
*/
|
||||||
|
static inline half
|
||||||
|
Float4ToHalf(float num)
|
||||||
|
{
|
||||||
|
half result = Float4ToHalfUnchecked(num);
|
||||||
|
|
||||||
|
if (unlikely(HalfIsInf(result)) && !isinf(num))
|
||||||
|
{
|
||||||
|
char *buf = palloc(FLOAT_SHORTEST_DECIMAL_LEN);
|
||||||
|
|
||||||
|
float_to_shortest_decimal_buf(num, buf);
|
||||||
|
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("\"%s\" is out of range for type halfvec", buf)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
777
src/halfvec.c
Normal file
777
src/halfvec.c
Normal file
@@ -0,0 +1,777 @@
|
|||||||
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "bitvector.h"
|
||||||
|
#include "catalog/pg_type.h"
|
||||||
|
#include "common/shortest_dec.h"
|
||||||
|
#include "fmgr.h"
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
|
#include "lib/stringinfo.h"
|
||||||
|
#include "libpq/pqformat.h"
|
||||||
|
#include "port.h" /* for strtof() */
|
||||||
|
#include "utils/array.h"
|
||||||
|
#include "utils/builtins.h"
|
||||||
|
#include "utils/float.h"
|
||||||
|
#include "utils/lsyscache.h"
|
||||||
|
#include "utils/numeric.h"
|
||||||
|
#include "vector.h"
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 130000
|
||||||
|
#define TYPALIGN_DOUBLE 'd'
|
||||||
|
#define TYPALIGN_INT 'i'
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get a half from a message buffer
|
||||||
|
*/
|
||||||
|
static half
|
||||||
|
pq_getmsghalf(StringInfo msg)
|
||||||
|
{
|
||||||
|
union
|
||||||
|
{
|
||||||
|
half h;
|
||||||
|
uint16 i;
|
||||||
|
} swap;
|
||||||
|
|
||||||
|
swap.i = pq_getmsgint(msg, 2);
|
||||||
|
return swap.h;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Append a half to a StringInfo buffer
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
pq_sendhalf(StringInfo buf, half h)
|
||||||
|
{
|
||||||
|
union
|
||||||
|
{
|
||||||
|
half h;
|
||||||
|
uint16 i;
|
||||||
|
} swap;
|
||||||
|
|
||||||
|
swap.h = h;
|
||||||
|
pq_sendint16(buf, swap.i);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure same dimensions
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckDims(HalfVector * a, HalfVector * b)
|
||||||
|
{
|
||||||
|
if (a->dim != b->dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("different halfvec 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("halfvec must have at least 1 dimension")));
|
||||||
|
|
||||||
|
if (dim > HALFVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("halfvec cannot have more than %d dimensions", HALFVEC_MAX_DIM)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure finite element
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckElement(half value)
|
||||||
|
{
|
||||||
|
if (HalfIsNan(value))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("NaN not allowed in halfvec")));
|
||||||
|
|
||||||
|
if (HalfIsInf(value))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("infinite value not allowed in halfvec")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Allocate and initialize a new half vector
|
||||||
|
*/
|
||||||
|
HalfVector *
|
||||||
|
InitHalfVector(int dim)
|
||||||
|
{
|
||||||
|
HalfVector *result;
|
||||||
|
int size;
|
||||||
|
|
||||||
|
size = HALFVEC_SIZE(dim);
|
||||||
|
result = (HalfVector *) palloc0(size);
|
||||||
|
SET_VARSIZE(result, size);
|
||||||
|
result->dim = dim;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check for whitespace, since array_isspace() is static
|
||||||
|
*/
|
||||||
|
static inline bool
|
||||||
|
halfvec_isspace(char ch)
|
||||||
|
{
|
||||||
|
if (ch == ' ' ||
|
||||||
|
ch == '\t' ||
|
||||||
|
ch == '\n' ||
|
||||||
|
ch == '\r' ||
|
||||||
|
ch == '\v' ||
|
||||||
|
ch == '\f')
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert textual representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_in);
|
||||||
|
Datum
|
||||||
|
halfvec_in(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
char *lit = PG_GETARG_CSTRING(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
half x[HALFVEC_MAX_DIM];
|
||||||
|
int dim = 0;
|
||||||
|
char *pt = lit;
|
||||||
|
HalfVector *result;
|
||||||
|
|
||||||
|
while (halfvec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != '[')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type halfvec: \"%s\"", lit),
|
||||||
|
errdetail("Vector contents must start with \"[\".")));
|
||||||
|
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
while (halfvec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt == ']')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("halfvec must have at least 1 dimension")));
|
||||||
|
|
||||||
|
for (;;)
|
||||||
|
{
|
||||||
|
float val;
|
||||||
|
char *stringEnd;
|
||||||
|
|
||||||
|
if (dim == HALFVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("halfvec cannot have more than %d dimensions", HALFVEC_MAX_DIM)));
|
||||||
|
|
||||||
|
while (halfvec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
/* Check for empty string like float4in */
|
||||||
|
if (*pt == '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type halfvec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
errno = 0;
|
||||||
|
|
||||||
|
/* Postgres sets LC_NUMERIC to C on startup */
|
||||||
|
val = strtof(pt, &stringEnd);
|
||||||
|
|
||||||
|
if (stringEnd == pt)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type halfvec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
x[dim] = Float4ToHalfUnchecked(val);
|
||||||
|
|
||||||
|
/* Check for range error like float4in */
|
||||||
|
if ((errno == ERANGE && isinf(val)) || (HalfIsInf(x[dim]) && !isinf(val)))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("\"%s\" is out of range for type halfvec", pnstrdup(pt, stringEnd - pt))));
|
||||||
|
|
||||||
|
CheckElement(x[dim]);
|
||||||
|
dim++;
|
||||||
|
|
||||||
|
pt = stringEnd;
|
||||||
|
|
||||||
|
while (halfvec_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 halfvec: \"%s\"", lit)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Only whitespace is allowed after the closing brace */
|
||||||
|
while (halfvec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type halfvec: \"%s\"", lit),
|
||||||
|
errdetail("Junk after closing right brace.")));
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
result = InitHalfVector(dim);
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
result->x[i] = x[i];
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#define AppendChar(ptr, c) (*(ptr)++ = (c))
|
||||||
|
#define AppendFloat(ptr, f) ((ptr) += float_to_shortest_decimal_bufn((f), (ptr)))
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to textual representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_out);
|
||||||
|
Datum
|
||||||
|
halfvec_out(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *vector = PG_GETARG_HALFVEC_P(0);
|
||||||
|
int dim = vector->dim;
|
||||||
|
char *buf;
|
||||||
|
char *ptr;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Need:
|
||||||
|
*
|
||||||
|
* dim * (FLOAT_SHORTEST_DECIMAL_LEN - 1) bytes for
|
||||||
|
* float_to_shortest_decimal_bufn
|
||||||
|
*
|
||||||
|
* dim - 1 bytes for separator
|
||||||
|
*
|
||||||
|
* 3 bytes for [, ], and \0
|
||||||
|
*/
|
||||||
|
buf = (char *) palloc(FLOAT_SHORTEST_DECIMAL_LEN * dim + 2);
|
||||||
|
ptr = buf;
|
||||||
|
|
||||||
|
AppendChar(ptr, '[');
|
||||||
|
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
AppendChar(ptr, ',');
|
||||||
|
|
||||||
|
AppendFloat(ptr, HalfToFloat4(vector->x[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
AppendChar(ptr, ']');
|
||||||
|
*ptr = '\0';
|
||||||
|
|
||||||
|
PG_FREE_IF_COPY(vector, 0);
|
||||||
|
PG_RETURN_CSTRING(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_typmod_in);
|
||||||
|
Datum
|
||||||
|
halfvec_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 halfvec must be at least 1")));
|
||||||
|
|
||||||
|
if (*tl > HALFVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
||||||
|
errmsg("dimensions for type halfvec cannot exceed %d", HALFVEC_MAX_DIM)));
|
||||||
|
|
||||||
|
PG_RETURN_INT32(*tl);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert external binary representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_recv);
|
||||||
|
Datum
|
||||||
|
halfvec_recv(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
HalfVector *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 = InitHalfVector(dim);
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
result->x[i] = pq_getmsghalf(buf);
|
||||||
|
CheckElement(result->x[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to the external binary representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_send);
|
||||||
|
Datum
|
||||||
|
halfvec_send(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *vec = PG_GETARG_HALFVEC_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_sendhalf(&buf, vec->x[i]);
|
||||||
|
|
||||||
|
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert half vector to half vector
|
||||||
|
* This is needed to check the type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec);
|
||||||
|
Datum
|
||||||
|
halfvec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *vec = PG_GETARG_HALFVEC_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
|
||||||
|
CheckExpectedDim(typmod, vec->dim);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(vec);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert array to half vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(array_to_halfvec);
|
||||||
|
Datum
|
||||||
|
array_to_halfvec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
HalfVector *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 = InitHalfVector(nelemsp);
|
||||||
|
|
||||||
|
if (ARR_ELEMTYPE(array) == INT4OID)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nelemsp; i++)
|
||||||
|
result->x[i] = Float4ToHalf(DatumGetInt32(elemsp[i]));
|
||||||
|
}
|
||||||
|
else if (ARR_ELEMTYPE(array) == FLOAT8OID)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nelemsp; i++)
|
||||||
|
result->x[i] = Float4ToHalf(DatumGetFloat8(elemsp[i]));
|
||||||
|
}
|
||||||
|
else if (ARR_ELEMTYPE(array) == FLOAT4OID)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nelemsp; i++)
|
||||||
|
result->x[i] = Float4ToHalf(DatumGetFloat4(elemsp[i]));
|
||||||
|
}
|
||||||
|
else if (ARR_ELEMTYPE(array) == NUMERICOID)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nelemsp; i++)
|
||||||
|
result->x[i] = Float4ToHalf(DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i])));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("unsupported array type")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Free allocation from deconstruct_array. Do not free individual elements
|
||||||
|
* when pass-by-reference since they point to original array.
|
||||||
|
*/
|
||||||
|
pfree(elemsp);
|
||||||
|
|
||||||
|
/* Check elements */
|
||||||
|
for (int i = 0; i < result->dim; i++)
|
||||||
|
CheckElement(result->x[i]);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert half vector to float4[]
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_to_float4);
|
||||||
|
Datum
|
||||||
|
halfvec_to_float4(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *vec = PG_GETARG_HALFVEC_P(0);
|
||||||
|
Datum *datums;
|
||||||
|
ArrayType *result;
|
||||||
|
|
||||||
|
datums = (Datum *) palloc(sizeof(Datum) * vec->dim);
|
||||||
|
|
||||||
|
for (int i = 0; i < vec->dim; i++)
|
||||||
|
datums[i] = Float4GetDatum(HalfToFloat4(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 half vec
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_to_halfvec);
|
||||||
|
Datum
|
||||||
|
vector_to_halfvec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
Vector *vec = PG_GETARG_VECTOR_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] = Float4ToHalf(vec->x[i]);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 distance between half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_l2_distance);
|
||||||
|
Datum
|
||||||
|
halfvec_l2_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt((double) HalfvecL2SquaredDistance(a->dim, a->x, b->x)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 squared distance between half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_l2_squared_distance);
|
||||||
|
Datum
|
||||||
|
halfvec_l2_squared_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) HalfvecL2SquaredDistance(a->dim, a->x, b->x));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the inner product of two half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_inner_product);
|
||||||
|
Datum
|
||||||
|
halfvec_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) HalfvecInnerProduct(a->dim, a->x, b->x));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the negative inner product of two half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_negative_inner_product);
|
||||||
|
Datum
|
||||||
|
halfvec_negative_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) -HalfvecInnerProduct(a->dim, a->x, b->x));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the cosine distance between two half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_cosine_distance);
|
||||||
|
Datum
|
||||||
|
halfvec_cosine_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
half *ax = a->x;
|
||||||
|
half *bx = b->x;
|
||||||
|
float distance = 0.0;
|
||||||
|
float norma = 0.0;
|
||||||
|
float normb = 0.0;
|
||||||
|
double similarity;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
{
|
||||||
|
float axi = HalfToFloat4(ax[i]);
|
||||||
|
float bxi = HalfToFloat4(bx[i]);
|
||||||
|
|
||||||
|
distance += axi * bxi;
|
||||||
|
norma += axi * axi;
|
||||||
|
normb += bxi * bxi;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
|
||||||
|
similarity = (double) distance / sqrt((double) norma * (double) normb);
|
||||||
|
|
||||||
|
#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)
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_spherical_distance);
|
||||||
|
Datum
|
||||||
|
halfvec_spherical_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
double distance;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
distance = (double) HalfvecInnerProduct(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 half vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_l1_distance);
|
||||||
|
Datum
|
||||||
|
halfvec_l1_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
HalfVector *b = PG_GETARG_HALFVEC_P(1);
|
||||||
|
half *ax = a->x;
|
||||||
|
half *bx = b->x;
|
||||||
|
float distance = 0.0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
distance += fabsf(HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]));
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 norm of a half vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_norm);
|
||||||
|
Datum
|
||||||
|
halfvec_norm(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
half *ax = a->x;
|
||||||
|
double norm = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
{
|
||||||
|
double axi = (double) HalfToFloat4(ax[i]);
|
||||||
|
|
||||||
|
norm += axi * axi;
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt(norm));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Quantize a half vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_quantize_binary);
|
||||||
|
Datum
|
||||||
|
halfvec_quantize_binary(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
half *ax = a->x;
|
||||||
|
VarBit *result = InitBitVector(a->dim);
|
||||||
|
unsigned char *rx = VARBITS(result);
|
||||||
|
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
rx[i / 8] |= (HalfToFloat4(ax[i]) > 0) << (7 - (i % 8));
|
||||||
|
|
||||||
|
PG_RETURN_VARBIT_P(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get a subvector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_subvector);
|
||||||
|
Datum
|
||||||
|
halfvec_subvector(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *a = PG_GETARG_HALFVEC_P(0);
|
||||||
|
int32 start = PG_GETARG_INT32(1);
|
||||||
|
int32 count = PG_GETARG_INT32(2);
|
||||||
|
int32 end = start + count;
|
||||||
|
half *ax = a->x;
|
||||||
|
HalfVector *result;
|
||||||
|
int dim;
|
||||||
|
|
||||||
|
/* Indexing starts at 1, like substring */
|
||||||
|
if (start < 1)
|
||||||
|
start = 1;
|
||||||
|
|
||||||
|
if (end > a->dim)
|
||||||
|
end = a->dim + 1;
|
||||||
|
|
||||||
|
dim = end - start;
|
||||||
|
CheckDim(dim);
|
||||||
|
result = InitHalfVector(dim);
|
||||||
|
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
result->x[i] = ax[start - 1 + i];
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Internal helper to compare half vectors
|
||||||
|
*/
|
||||||
|
int
|
||||||
|
halfvec_cmp_internal(HalfVector * a, HalfVector * 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 (HalfToFloat4(a->x[i]) < HalfToFloat4(b->x[i]))
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
if (HalfToFloat4(a->x[i]) > HalfToFloat4(b->x[i]))
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (a->dim < b->dim)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
if (a->dim > b->dim)
|
||||||
|
return 1;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
47
src/halfvec.h
Normal file
47
src/halfvec.h
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
#ifndef HALFVEC_H
|
||||||
|
#define HALFVEC_H
|
||||||
|
|
||||||
|
#define __STDC_WANT_IEC_60559_TYPES_EXT__
|
||||||
|
|
||||||
|
#include <float.h>
|
||||||
|
|
||||||
|
#include "vector.h"
|
||||||
|
|
||||||
|
#if defined(__x86_64__) || defined(_M_AMD64)
|
||||||
|
#define HALFVEC_DISPATCH
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* F16C has better performance than _Float16 (on x86-64) */
|
||||||
|
#if defined(__F16C__)
|
||||||
|
#define F16C_SUPPORT
|
||||||
|
#elif defined(__FLT16_MAX__) && !defined(HALFVEC_DISPATCH)
|
||||||
|
#define FLT16_SUPPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef FLT16_SUPPORT
|
||||||
|
#define half _Float16
|
||||||
|
#define HALF_MAX FLT16_MAX
|
||||||
|
#else
|
||||||
|
#define half uint16
|
||||||
|
#define HALF_MAX 65504
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define HALFVEC_MAX_DIM VECTOR_MAX_DIM
|
||||||
|
|
||||||
|
#define HALFVEC_SIZE(_dim) (offsetof(HalfVector, x) + sizeof(half)*(_dim))
|
||||||
|
#define DatumGetHalfVector(x) ((HalfVector *) PG_DETOAST_DATUM(x))
|
||||||
|
#define PG_GETARG_HALFVEC_P(x) DatumGetHalfVector(PG_GETARG_DATUM(x))
|
||||||
|
#define PG_RETURN_HALFVEC_P(x) PG_RETURN_POINTER(x)
|
||||||
|
|
||||||
|
typedef struct HalfVector
|
||||||
|
{
|
||||||
|
int32 vl_len_; /* varlena header (do not touch directly!) */
|
||||||
|
int16 dim; /* number of dimensions */
|
||||||
|
int16 unused;
|
||||||
|
half x[FLEXIBLE_ARRAY_MEMBER];
|
||||||
|
} HalfVector;
|
||||||
|
|
||||||
|
HalfVector *InitHalfVector(int dim);
|
||||||
|
int halfvec_cmp_internal(HalfVector * a, HalfVector * b);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define HNSW_MAX_DIM 2000
|
#define HNSW_MAX_DIM 2000
|
||||||
|
#define HNSW_MAX_NNZ 1000
|
||||||
|
|
||||||
/* Support functions */
|
/* Support functions */
|
||||||
#define HNSW_DISTANCE_PROC 1
|
#define HNSW_DISTANCE_PROC 1
|
||||||
@@ -58,7 +59,9 @@
|
|||||||
typedef enum HnswType
|
typedef enum HnswType
|
||||||
{
|
{
|
||||||
HNSW_TYPE_VECTOR,
|
HNSW_TYPE_VECTOR,
|
||||||
HNSW_TYPE_BIT
|
HNSW_TYPE_HALFVEC,
|
||||||
|
HNSW_TYPE_BIT,
|
||||||
|
HNSW_TYPE_SPARSEVEC
|
||||||
} HnswType;
|
} HnswType;
|
||||||
|
|
||||||
/* Build phases */
|
/* Build phases */
|
||||||
@@ -375,6 +378,7 @@ int HnswGetEfConstruction(Relation index);
|
|||||||
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
HnswType HnswGetType(Relation index);
|
HnswType HnswGetType(Relation index);
|
||||||
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type);
|
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type);
|
||||||
|
void HnswCheckValue(Datum value, HnswType type);
|
||||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||||
void HnswInitPage(Buffer buf, Page page);
|
void HnswInitPage(Buffer buf, Page page);
|
||||||
void HnswInit(void);
|
void HnswInit(void);
|
||||||
|
|||||||
@@ -487,6 +487,9 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
|
|
||||||
|
/* Check value */
|
||||||
|
HnswCheckValue(value, buildstate->type);
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
@@ -674,8 +677,12 @@ GetMaxDimensions(HnswType type)
|
|||||||
{
|
{
|
||||||
int maxDimensions = HNSW_MAX_DIM;
|
int maxDimensions = HNSW_MAX_DIM;
|
||||||
|
|
||||||
if (type == HNSW_TYPE_BIT)
|
if (type == HNSW_TYPE_HALFVEC)
|
||||||
|
maxDimensions *= 2;
|
||||||
|
else if (type == HNSW_TYPE_BIT)
|
||||||
maxDimensions *= 32;
|
maxDimensions *= 32;
|
||||||
|
else if (type == HNSW_TYPE_SPARSEVEC)
|
||||||
|
maxDimensions = INT_MAX;
|
||||||
|
|
||||||
return maxDimensions;
|
return maxDimensions;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -614,15 +614,19 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
Datum value;
|
Datum value;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
Oid collation = index->rd_indcollation[0];
|
Oid collation = index->rd_indcollation[0];
|
||||||
|
HnswType type = HnswGetType(index);
|
||||||
|
|
||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
|
|
||||||
|
/* Check value */
|
||||||
|
HnswCheckValue(value, type);
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(normprocinfo, collation, &value, HnswGetType(index)))
|
if (!HnswNormValue(normprocinfo, collation, &value, type))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/relscan.h"
|
#include "access/relscan.h"
|
||||||
#include "bitvector.h"
|
|
||||||
#include "catalog/pg_type_d.h"
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "pgstat.h"
|
#include "pgstat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
@@ -160,6 +158,10 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||||
|
|
||||||
so->first = false;
|
so->first = false;
|
||||||
|
|
||||||
|
#if defined(HNSW_MEMORY) && PG_VERSION_NUM >= 130000
|
||||||
|
elog(INFO, "memory: %zu MB", MemoryContextMemAllocated(so->tmpCtx, false) / (1024 * 1024));
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
while (list_length(so->w) > 0)
|
while (list_length(so->w) > 0)
|
||||||
|
|||||||
@@ -3,13 +3,18 @@
|
|||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
|
#include "catalog/pg_type.h"
|
||||||
#include "catalog/pg_type_d.h"
|
#include "catalog/pg_type_d.h"
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "lib/pairingheap.h"
|
||||||
|
#include "sparsevec.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "utils/datum.h"
|
#include "utils/datum.h"
|
||||||
#include "utils/memdebug.h"
|
#include "utils/memdebug.h"
|
||||||
#include "utils/rel.h"
|
#include "utils/rel.h"
|
||||||
|
#include "utils/syscache.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
@@ -157,11 +162,33 @@ HnswType
|
|||||||
HnswGetType(Relation index)
|
HnswGetType(Relation index)
|
||||||
{
|
{
|
||||||
Oid typid = TupleDescAttr(index->rd_att, 0)->atttypid;
|
Oid typid = TupleDescAttr(index->rd_att, 0)->atttypid;
|
||||||
|
HeapTuple tuple;
|
||||||
|
Form_pg_type type;
|
||||||
|
HnswType result;
|
||||||
|
|
||||||
if (typid == BITOID || typid == VARBITOID)
|
if (typid == BITOID)
|
||||||
return HNSW_TYPE_BIT;
|
return HNSW_TYPE_BIT;
|
||||||
|
|
||||||
return HNSW_TYPE_VECTOR;
|
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
|
||||||
|
if (!HeapTupleIsValid(tuple))
|
||||||
|
elog(ERROR, "cache lookup failed for type %u", typid);
|
||||||
|
|
||||||
|
type = (Form_pg_type) GETSTRUCT(tuple);
|
||||||
|
if (strcmp(NameStr(type->typname), "vector") == 0)
|
||||||
|
result = HNSW_TYPE_VECTOR;
|
||||||
|
else if (strcmp(NameStr(type->typname), "halfvec") == 0)
|
||||||
|
result = HNSW_TYPE_HALFVEC;
|
||||||
|
else if (strcmp(NameStr(type->typname), "sparsevec") == 0)
|
||||||
|
result = HNSW_TYPE_SPARSEVEC;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ReleaseSysCache(tuple);
|
||||||
|
elog(ERROR, "type not supported for hnsw index");
|
||||||
|
}
|
||||||
|
|
||||||
|
ReleaseSysCache(tuple);
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -190,6 +217,31 @@ HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type)
|
|||||||
|
|
||||||
*value = PointerGetDatum(result);
|
*value = PointerGetDatum(result);
|
||||||
}
|
}
|
||||||
|
else if (type == HNSW_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
HalfVector *v = DatumGetHalfVector(*value);
|
||||||
|
HalfVector *result = InitHalfVector(v->dim);
|
||||||
|
|
||||||
|
for (int i = 0; i < v->dim; i++)
|
||||||
|
result->x[i] = Float4ToHalfUnchecked(HalfToFloat4(v->x[i]) / norm);
|
||||||
|
|
||||||
|
*value = PointerGetDatum(result);
|
||||||
|
}
|
||||||
|
else if (type == HNSW_TYPE_SPARSEVEC)
|
||||||
|
{
|
||||||
|
SparseVector *v = DatumGetSparseVector(*value);
|
||||||
|
SparseVector *result = InitSparseVector(v->dim, v->nnz);
|
||||||
|
float *vx = SPARSEVEC_VALUES(v);
|
||||||
|
float *rx = SPARSEVEC_VALUES(result);
|
||||||
|
|
||||||
|
for (int i = 0; i < v->nnz; i++)
|
||||||
|
{
|
||||||
|
result->indices[i] = v->indices[i];
|
||||||
|
rx[i] = vx[i] / norm;
|
||||||
|
}
|
||||||
|
|
||||||
|
*value = PointerGetDatum(result);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
elog(ERROR, "Unsupported type");
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
@@ -199,6 +251,21 @@ HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check if a value can be indexed
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
HnswCheckValue(Datum value, HnswType type)
|
||||||
|
{
|
||||||
|
if (type == HNSW_TYPE_SPARSEVEC)
|
||||||
|
{
|
||||||
|
SparseVector *vec = DatumGetSparseVector(value);
|
||||||
|
|
||||||
|
if (vec->nnz > HNSW_MAX_NNZ)
|
||||||
|
elog(ERROR, "sparsevec cannot have more than %d non-zero elements for hnsw index", HNSW_MAX_NNZ);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* New buffer
|
* New buffer
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -10,12 +10,14 @@
|
|||||||
#include "catalog/pg_operator_d.h"
|
#include "catalog/pg_operator_d.h"
|
||||||
#include "catalog/pg_type_d.h"
|
#include "catalog/pg_type_d.h"
|
||||||
#include "commands/progress.h"
|
#include "commands/progress.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "optimizer/optimizer.h"
|
#include "optimizer/optimizer.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
#include "tcop/tcopprot.h"
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
#include "vector.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_progress.h"
|
#include "utils/backend_progress.h"
|
||||||
@@ -57,13 +59,13 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
|||||||
*/
|
*/
|
||||||
if (buildstate->kmeansnormprocinfo != NULL)
|
if (buildstate->kmeansnormprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(buildstate->kmeansnormprocinfo, buildstate->collation, &value))
|
if (!IvfflatNormValue(buildstate->kmeansnormprocinfo, buildstate->collation, &value, buildstate->type))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (samples->length < targsamples)
|
if (samples->length < targsamples)
|
||||||
{
|
{
|
||||||
VectorArraySet(samples, samples->length, DatumGetVector(value));
|
VectorArraySet(samples, samples->length, DatumGetPointer(value));
|
||||||
samples->length++;
|
samples->length++;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -80,7 +82,7 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
Assert(k >= 0 && k < targsamples);
|
Assert(k >= 0 && k < targsamples);
|
||||||
VectorArraySet(samples, k, DatumGetVector(value));
|
VectorArraySet(samples, k, DatumGetPointer(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
buildstate->rowstoskip -= 1;
|
buildstate->rowstoskip -= 1;
|
||||||
@@ -153,7 +155,7 @@ AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState
|
|||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(buildstate->normprocinfo, buildstate->collation, &value))
|
if (!IvfflatNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->type))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,25 +314,58 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get max dimensions
|
||||||
|
*/
|
||||||
|
static int
|
||||||
|
GetMaxDimensions(IvfflatType type)
|
||||||
|
{
|
||||||
|
int maxDimensions = IVFFLAT_MAX_DIM;
|
||||||
|
|
||||||
|
if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
maxDimensions *= 2;
|
||||||
|
|
||||||
|
return maxDimensions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get item size
|
||||||
|
*/
|
||||||
|
static Size
|
||||||
|
GetItemSize(IvfflatType type, int dimensions)
|
||||||
|
{
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
return VECTOR_SIZE(dimensions);
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
return HALFVEC_SIZE(dimensions);
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Initialize the build state
|
* Initialize the build state
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, IndexInfo *indexInfo)
|
InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, IndexInfo *indexInfo)
|
||||||
{
|
{
|
||||||
|
int maxDimensions;
|
||||||
|
|
||||||
buildstate->heap = heap;
|
buildstate->heap = heap;
|
||||||
buildstate->index = index;
|
buildstate->index = index;
|
||||||
buildstate->indexInfo = indexInfo;
|
buildstate->indexInfo = indexInfo;
|
||||||
|
buildstate->type = IvfflatGetType(index);
|
||||||
|
|
||||||
buildstate->lists = IvfflatGetLists(index);
|
buildstate->lists = IvfflatGetLists(index);
|
||||||
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
||||||
|
|
||||||
|
maxDimensions = GetMaxDimensions(buildstate->type);
|
||||||
|
|
||||||
/* Require column to have dimensions to be indexed */
|
/* Require column to have dimensions to be indexed */
|
||||||
if (buildstate->dimensions < 0)
|
if (buildstate->dimensions < 0)
|
||||||
elog(ERROR, "column does not have dimensions");
|
elog(ERROR, "column does not have dimensions");
|
||||||
|
|
||||||
if (buildstate->dimensions > IVFFLAT_MAX_DIM)
|
if (buildstate->dimensions > maxDimensions)
|
||||||
elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", IVFFLAT_MAX_DIM);
|
elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", maxDimensions);
|
||||||
|
|
||||||
buildstate->reltuples = 0;
|
buildstate->reltuples = 0;
|
||||||
buildstate->indtuples = 0;
|
buildstate->indtuples = 0;
|
||||||
@@ -353,7 +388,7 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
|||||||
|
|
||||||
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
|
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
|
||||||
|
|
||||||
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions);
|
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions, GetItemSize(buildstate->type, buildstate->dimensions));
|
||||||
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
||||||
|
|
||||||
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
@@ -408,7 +443,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
|
|
||||||
/* Sample rows */
|
/* Sample rows */
|
||||||
/* TODO Ensure within maintenance_work_mem */
|
/* TODO Ensure within maintenance_work_mem */
|
||||||
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions);
|
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions, buildstate->centers->itemsize);
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
{
|
{
|
||||||
SampleRows(buildstate);
|
SampleRows(buildstate);
|
||||||
@@ -423,7 +458,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Calculate centers */
|
/* Calculate centers */
|
||||||
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers));
|
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers, buildstate->type));
|
||||||
|
|
||||||
/* Free samples before we allocate more memory */
|
/* Free samples before we allocate more memory */
|
||||||
VectorArrayFree(buildstate->samples);
|
VectorArrayFree(buildstate->samples);
|
||||||
@@ -468,7 +503,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
Size listSize;
|
Size listSize;
|
||||||
IvfflatList list;
|
IvfflatList list;
|
||||||
|
|
||||||
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(centers->itemsize));
|
||||||
list = palloc0(listSize);
|
list = palloc0(listSize);
|
||||||
|
|
||||||
buf = IvfflatNewBuffer(index, forkNum);
|
buf = IvfflatNewBuffer(index, forkNum);
|
||||||
@@ -481,7 +516,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
/* Load list */
|
/* Load list */
|
||||||
list->startPage = InvalidBlockNumber;
|
list->startPage = InvalidBlockNumber;
|
||||||
list->insertPage = InvalidBlockNumber;
|
list->insertPage = InvalidBlockNumber;
|
||||||
memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
|
memcpy(&list->center, VectorArrayGet(centers, i), centers->itemsize);
|
||||||
|
|
||||||
/* Ensure free space */
|
/* Ensure free space */
|
||||||
if (PageGetFreeSpace(page) < listSize)
|
if (PageGetFreeSpace(page) < listSize)
|
||||||
@@ -586,7 +621,7 @@ ParallelHeapScan(IvfflatBuildState * buildstate)
|
|||||||
* Perform a worker's portion of a parallel sort
|
* Perform a worker's portion of a parallel sort
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, Sharedsort *sharedsort, Vector * ivfcenters, int sortmem, bool progress)
|
IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, Sharedsort *sharedsort, char *ivfcenters, int sortmem, bool progress)
|
||||||
{
|
{
|
||||||
SortCoordinate coordinate;
|
SortCoordinate coordinate;
|
||||||
IvfflatBuildState buildstate;
|
IvfflatBuildState buildstate;
|
||||||
@@ -610,7 +645,7 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
|
|||||||
indexInfo = BuildIndexInfo(ivfspool->index);
|
indexInfo = BuildIndexInfo(ivfspool->index);
|
||||||
indexInfo->ii_Concurrent = ivfshared->isconcurrent;
|
indexInfo->ii_Concurrent = ivfshared->isconcurrent;
|
||||||
InitBuildState(&buildstate, ivfspool->heap, ivfspool->index, indexInfo);
|
InitBuildState(&buildstate, ivfspool->heap, ivfspool->index, indexInfo);
|
||||||
memcpy(buildstate.centers->items, ivfcenters, VECTOR_SIZE(buildstate.centers->dim) * buildstate.centers->maxlen);
|
memcpy(buildstate.centers->items, ivfcenters, buildstate.centers->itemsize * buildstate.centers->maxlen);
|
||||||
buildstate.centers->length = buildstate.centers->maxlen;
|
buildstate.centers->length = buildstate.centers->maxlen;
|
||||||
ivfspool->sortstate = tuplesort_begin_heap(buildstate.tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, sortmem, coordinate, false);
|
ivfspool->sortstate = tuplesort_begin_heap(buildstate.tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, sortmem, coordinate, false);
|
||||||
buildstate.sortstate = ivfspool->sortstate;
|
buildstate.sortstate = ivfspool->sortstate;
|
||||||
@@ -658,7 +693,7 @@ IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
|||||||
IvfflatSpool *ivfspool;
|
IvfflatSpool *ivfspool;
|
||||||
IvfflatShared *ivfshared;
|
IvfflatShared *ivfshared;
|
||||||
Sharedsort *sharedsort;
|
Sharedsort *sharedsort;
|
||||||
Vector *ivfcenters;
|
char *ivfcenters;
|
||||||
Relation heapRel;
|
Relation heapRel;
|
||||||
Relation indexRel;
|
Relation indexRel;
|
||||||
LOCKMODE heapLockmode;
|
LOCKMODE heapLockmode;
|
||||||
@@ -772,7 +807,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
|
|||||||
Size estcenters;
|
Size estcenters;
|
||||||
IvfflatShared *ivfshared;
|
IvfflatShared *ivfshared;
|
||||||
Sharedsort *sharedsort;
|
Sharedsort *sharedsort;
|
||||||
Vector *ivfcenters;
|
char *ivfcenters;
|
||||||
IvfflatLeader *ivfleader = (IvfflatLeader *) palloc0(sizeof(IvfflatLeader));
|
IvfflatLeader *ivfleader = (IvfflatLeader *) palloc0(sizeof(IvfflatLeader));
|
||||||
bool leaderparticipates = true;
|
bool leaderparticipates = true;
|
||||||
int querylen;
|
int querylen;
|
||||||
@@ -799,7 +834,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
|
|||||||
shm_toc_estimate_chunk(&pcxt->estimator, estivfshared);
|
shm_toc_estimate_chunk(&pcxt->estimator, estivfshared);
|
||||||
estsort = tuplesort_estimate_shared(scantuplesortstates);
|
estsort = tuplesort_estimate_shared(scantuplesortstates);
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, estsort);
|
shm_toc_estimate_chunk(&pcxt->estimator, estsort);
|
||||||
estcenters = VECTOR_SIZE(buildstate->dimensions) * buildstate->lists;
|
estcenters = buildstate->centers->itemsize * buildstate->centers->maxlen;
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, estcenters);
|
shm_toc_estimate_chunk(&pcxt->estimator, estcenters);
|
||||||
shm_toc_estimate_keys(&pcxt->estimator, 3);
|
shm_toc_estimate_keys(&pcxt->estimator, 3);
|
||||||
|
|
||||||
@@ -851,7 +886,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
|
|||||||
tuplesort_initialize_shared(sharedsort, scantuplesortstates,
|
tuplesort_initialize_shared(sharedsort, scantuplesortstates,
|
||||||
pcxt->seg);
|
pcxt->seg);
|
||||||
|
|
||||||
ivfcenters = (Vector *) shm_toc_allocate(pcxt->toc, estcenters);
|
ivfcenters = shm_toc_allocate(pcxt->toc, estcenters);
|
||||||
memcpy(ivfcenters, buildstate->centers->items, estcenters);
|
memcpy(ivfcenters, buildstate->centers->items, estcenters);
|
||||||
|
|
||||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_IVFFLAT_SHARED, ivfshared);
|
shm_toc_insert(pcxt->toc, PARALLEL_KEY_IVFFLAT_SHARED, ivfshared);
|
||||||
|
|||||||
@@ -43,13 +43,19 @@
|
|||||||
#define IVFFLAT_MAX_LISTS 32768
|
#define IVFFLAT_MAX_LISTS 32768
|
||||||
#define IVFFLAT_DEFAULT_PROBES 1
|
#define IVFFLAT_DEFAULT_PROBES 1
|
||||||
|
|
||||||
|
typedef enum IvfflatType
|
||||||
|
{
|
||||||
|
IVFFLAT_TYPE_VECTOR,
|
||||||
|
IVFFLAT_TYPE_HALFVEC
|
||||||
|
} IvfflatType;
|
||||||
|
|
||||||
/* Build phases */
|
/* Build phases */
|
||||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||||
#define PROGRESS_IVFFLAT_PHASE_KMEANS 2
|
#define PROGRESS_IVFFLAT_PHASE_KMEANS 2
|
||||||
#define PROGRESS_IVFFLAT_PHASE_ASSIGN 3
|
#define PROGRESS_IVFFLAT_PHASE_ASSIGN 3
|
||||||
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
|
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
|
||||||
|
|
||||||
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
|
#define IVFFLAT_LIST_SIZE(size) (offsetof(IvfflatListData, center) + size)
|
||||||
|
|
||||||
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
|
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
|
||||||
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
|
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
|
||||||
@@ -85,7 +91,8 @@ typedef struct VectorArrayData
|
|||||||
int length;
|
int length;
|
||||||
int maxlen;
|
int maxlen;
|
||||||
int dim;
|
int dim;
|
||||||
Vector *items;
|
Size itemsize;
|
||||||
|
char *items;
|
||||||
} VectorArrayData;
|
} VectorArrayData;
|
||||||
|
|
||||||
typedef VectorArrayData * VectorArray;
|
typedef VectorArrayData * VectorArray;
|
||||||
@@ -144,7 +151,7 @@ typedef struct IvfflatLeader
|
|||||||
IvfflatShared *ivfshared;
|
IvfflatShared *ivfshared;
|
||||||
Sharedsort *sharedsort;
|
Sharedsort *sharedsort;
|
||||||
Snapshot snapshot;
|
Snapshot snapshot;
|
||||||
Vector *ivfcenters;
|
char *ivfcenters;
|
||||||
} IvfflatLeader;
|
} IvfflatLeader;
|
||||||
|
|
||||||
typedef struct IvfflatBuildState
|
typedef struct IvfflatBuildState
|
||||||
@@ -153,6 +160,7 @@ typedef struct IvfflatBuildState
|
|||||||
Relation heap;
|
Relation heap;
|
||||||
Relation index;
|
Relation index;
|
||||||
IndexInfo *indexInfo;
|
IndexInfo *indexInfo;
|
||||||
|
IvfflatType type;
|
||||||
|
|
||||||
/* Settings */
|
/* Settings */
|
||||||
int dimensions;
|
int dimensions;
|
||||||
@@ -255,18 +263,18 @@ typedef struct IvfflatScanOpaqueData
|
|||||||
|
|
||||||
typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
|
typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
|
||||||
|
|
||||||
#define VECTOR_ARRAY_SIZE(_length, _dim) (sizeof(VectorArrayData) + (_length) * VECTOR_SIZE(_dim))
|
#define VECTOR_ARRAY_SIZE(_length, _size) (sizeof(VectorArrayData) + (_length) * _size)
|
||||||
#define VECTOR_ARRAY_OFFSET(_arr, _offset) ((char*) (_arr)->items + (_offset) * VECTOR_SIZE((_arr)->dim))
|
#define VECTOR_ARRAY_OFFSET(_arr, _offset) ((char*) (_arr)->items + (_offset) * (_arr)->itemsize)
|
||||||
#define VectorArrayGet(_arr, _offset) ((Vector *) VECTOR_ARRAY_OFFSET(_arr, _offset))
|
#define VectorArrayGet(_arr, _offset) VECTOR_ARRAY_OFFSET(_arr, _offset)
|
||||||
#define VectorArraySet(_arr, _offset, _val) memcpy(VECTOR_ARRAY_OFFSET(_arr, _offset), _val, VECTOR_SIZE((_arr)->dim))
|
#define VectorArraySet(_arr, _offset, _val) memcpy(VECTOR_ARRAY_OFFSET(_arr, _offset), _val, (_arr)->itemsize)
|
||||||
|
|
||||||
/* Methods */
|
/* Methods */
|
||||||
VectorArray VectorArrayInit(int maxlen, int dimensions);
|
VectorArray VectorArrayInit(int maxlen, int dimensions, Size itemsize);
|
||||||
void VectorArrayFree(VectorArray arr);
|
void VectorArrayFree(VectorArray arr);
|
||||||
void PrintVectorArray(char *msg, VectorArray arr);
|
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, IvfflatType type);
|
||||||
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
|
||||||
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value);
|
IvfflatType IvfflatGetType(Relation index);
|
||||||
|
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, IvfflatType type);
|
||||||
int IvfflatGetLists(Relation index);
|
int IvfflatGetLists(Relation index);
|
||||||
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
||||||
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value))
|
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, IvfflatGetType(index)))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
376
src/ivfkmeans.c
376
src/ivfkmeans.c
@@ -3,12 +3,13 @@
|
|||||||
#include <float.h>
|
#include <float.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
|
#include "utils/datum.h"
|
||||||
#ifdef IVFFLAT_MEMORY
|
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
#endif
|
#include "vector.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Initialize with kmeans++
|
* Initialize with kmeans++
|
||||||
@@ -46,12 +47,12 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
|||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(samples, j);
|
Datum vec = PointerGetDatum(VectorArrayGet(samples, j));
|
||||||
double distance;
|
double distance;
|
||||||
|
|
||||||
/* Only need to compute distance for new center */
|
/* Only need to compute distance for new center */
|
||||||
/* TODO Use triangle inequality to reduce distance calculations */
|
/* TODO Use triangle inequality to reduce distance calculations */
|
||||||
distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, i))));
|
distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, vec, PointerGetDatum(VectorArrayGet(centers, i))));
|
||||||
|
|
||||||
/* Set lower bound */
|
/* Set lower bound */
|
||||||
lowerBound[j * numCenters + i] = distance;
|
lowerBound[j * numCenters + i] = distance;
|
||||||
@@ -89,16 +90,30 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
|||||||
* Apply norm to vector
|
* Apply norm to vector
|
||||||
*/
|
*/
|
||||||
static inline void
|
static inline void
|
||||||
ApplyNorm(FmgrInfo *normprocinfo, Oid collation, Vector * vec)
|
ApplyNorm(FmgrInfo *normprocinfo, Oid collation, Datum value, IvfflatType type)
|
||||||
{
|
{
|
||||||
double norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, PointerGetDatum(vec)));
|
double norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, value));
|
||||||
|
|
||||||
/* TODO Handle zero norm */
|
/* TODO Handle zero norm */
|
||||||
if (norm > 0)
|
if (norm > 0)
|
||||||
{
|
{
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
{
|
||||||
|
Vector *vec = DatumGetVector(value);
|
||||||
|
|
||||||
for (int i = 0; i < vec->dim; i++)
|
for (int i = 0; i < vec->dim; i++)
|
||||||
vec->x[i] /= norm;
|
vec->x[i] /= norm;
|
||||||
}
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
HalfVector *vec = DatumGetHalfVector(value);
|
||||||
|
|
||||||
|
for (int i = 0; i < vec->dim; i++)
|
||||||
|
vec->x[i] = Float4ToHalfUnchecked(HalfToFloat4(vec->x[i]) / norm);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -110,11 +125,20 @@ CompareVectors(const void *a, const void *b)
|
|||||||
return vector_cmp_internal((Vector *) a, (Vector *) b);
|
return vector_cmp_internal((Vector *) a, (Vector *) b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Compare half vectors
|
||||||
|
*/
|
||||||
|
static int
|
||||||
|
CompareHalfVectors(const void *a, const void *b)
|
||||||
|
{
|
||||||
|
return halfvec_cmp_internal((HalfVector *) a, (HalfVector *) b);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Quick approach if we have little data
|
* Quick approach if we have little data
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
QuickCenters(Relation index, VectorArray samples, VectorArray centers, IvfflatType type)
|
||||||
{
|
{
|
||||||
int dimensions = centers->dim;
|
int dimensions = centers->dim;
|
||||||
Oid collation = index->rd_indcollation[0];
|
Oid collation = index->rd_indcollation[0];
|
||||||
@@ -123,14 +147,20 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* Copy existing vectors while avoiding duplicates */
|
/* Copy existing vectors while avoiding duplicates */
|
||||||
if (samples->length > 0)
|
if (samples->length > 0)
|
||||||
{
|
{
|
||||||
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
qsort(samples->items, samples->length, samples->itemsize, CompareVectors);
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
qsort(samples->items, samples->length, samples->itemsize, CompareHalfVectors);
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
for (int i = 0; i < samples->length; i++)
|
for (int i = 0; i < samples->length; i++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(samples, i);
|
Datum vec = PointerGetDatum(VectorArrayGet(samples, i));
|
||||||
|
|
||||||
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
if (i == 0 || !datumIsEqual(vec, PointerGetDatum(VectorArrayGet(samples, i - 1)), false, -1))
|
||||||
{
|
{
|
||||||
VectorArraySet(centers, centers->length, vec);
|
VectorArraySet(centers, centers->length, DatumGetPointer(vec));
|
||||||
centers->length++;
|
centers->length++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,17 +169,34 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* Fill remaining with random data */
|
/* Fill remaining with random data */
|
||||||
while (centers->length < centers->maxlen)
|
while (centers->length < centers->maxlen)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(centers, centers->length);
|
Datum center = PointerGetDatum(VectorArrayGet(centers, centers->length));
|
||||||
|
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
{
|
||||||
|
Vector *vec = DatumGetVector(center);
|
||||||
|
|
||||||
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
||||||
vec->dim = dimensions;
|
vec->dim = dimensions;
|
||||||
|
|
||||||
for (int j = 0; j < dimensions; j++)
|
for (int j = 0; j < dimensions; j++)
|
||||||
vec->x[j] = RandomDouble();
|
vec->x[j] = RandomDouble();
|
||||||
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
HalfVector *vec = DatumGetHalfVector(center);
|
||||||
|
|
||||||
|
SET_VARSIZE(vec, HALFVEC_SIZE(dimensions));
|
||||||
|
vec->dim = dimensions;
|
||||||
|
|
||||||
|
for (int j = 0; j < dimensions; j++)
|
||||||
|
vec->x[j] = Float4ToHalfUnchecked((float) RandomDouble());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
/* Normalize if needed (only needed for random centers) */
|
/* Normalize if needed (only needed for random centers) */
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
ApplyNorm(normprocinfo, collation, vec);
|
ApplyNorm(normprocinfo, collation, center, type);
|
||||||
|
|
||||||
centers->length++;
|
centers->length++;
|
||||||
}
|
}
|
||||||
@@ -160,18 +207,120 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
* Show memory usage
|
* Show memory usage
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
ShowMemoryUsage(Size estimatedSize)
|
ShowMemoryUsage(MemoryContext context, Size estimatedSize)
|
||||||
{
|
{
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
elog(INFO, "total memory: %zu MB",
|
elog(INFO, "total memory: %zu MB",
|
||||||
MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024));
|
MemoryContextMemAllocated(context, true) / (1024 * 1024));
|
||||||
#else
|
#else
|
||||||
MemoryContextStats(CurrentMemoryContext);
|
MemoryContextStats(context);
|
||||||
#endif
|
#endif
|
||||||
elog(INFO, "estimated memory: %zu MB", estimatedSize / (1024 * 1024));
|
elog(INFO, "estimated memory: %zu MB", estimatedSize / (1024 * 1024));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Compute new centers
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
ComputeNewCenters(VectorArray samples, VectorArray aggCenters, VectorArray newCenters, int *centerCounts, int *closestCenters, FmgrInfo *normprocinfo, Oid collation, IvfflatType type)
|
||||||
|
{
|
||||||
|
int dimensions = aggCenters->dim;
|
||||||
|
int numCenters = aggCenters->maxlen;
|
||||||
|
int numSamples = samples->length;
|
||||||
|
|
||||||
|
/* Reset sum and count */
|
||||||
|
for (int j = 0; j < numCenters; j++)
|
||||||
|
{
|
||||||
|
Vector *vec = (Vector *) VectorArrayGet(aggCenters, j);
|
||||||
|
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
vec->x[k] = 0.0;
|
||||||
|
|
||||||
|
centerCounts[j] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Increment sum of closest center */
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < numSamples; j++)
|
||||||
|
{
|
||||||
|
Vector *aggCenter = (Vector *) VectorArrayGet(aggCenters, closestCenters[j]);
|
||||||
|
Vector *vec = (Vector *) VectorArrayGet(samples, j);
|
||||||
|
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
aggCenter->x[k] += vec->x[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < numSamples; j++)
|
||||||
|
{
|
||||||
|
Vector *aggCenter = (Vector *) VectorArrayGet(aggCenters, closestCenters[j]);
|
||||||
|
HalfVector *vec = (HalfVector *) VectorArrayGet(samples, j);
|
||||||
|
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
aggCenter->x[k] += HalfToFloat4(vec->x[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
|
/* Increment count of closest center */
|
||||||
|
for (int j = 0; j < numSamples; j++)
|
||||||
|
centerCounts[closestCenters[j]] += 1;
|
||||||
|
|
||||||
|
/* Divide sum by count */
|
||||||
|
for (int j = 0; j < numCenters; j++)
|
||||||
|
{
|
||||||
|
Vector *vec = (Vector *) VectorArrayGet(aggCenters, j);
|
||||||
|
|
||||||
|
if (centerCounts[j] > 0)
|
||||||
|
{
|
||||||
|
/* Double avoids overflow, but requires more memory */
|
||||||
|
/* TODO Update bounds */
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
{
|
||||||
|
if (isinf(vec->x[k]))
|
||||||
|
vec->x[k] = vec->x[k] > 0 ? FLT_MAX : -FLT_MAX;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
vec->x[k] /= centerCounts[j];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* TODO Handle empty centers properly */
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
vec->x[k] = RandomDouble();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Set new centers if different from agg centers */
|
||||||
|
if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < numCenters; j++)
|
||||||
|
{
|
||||||
|
Vector *aggCenter = (Vector *) VectorArrayGet(aggCenters, j);
|
||||||
|
HalfVector *newCenter = (HalfVector *) VectorArrayGet(newCenters, j);
|
||||||
|
|
||||||
|
for (int k = 0; k < dimensions; k++)
|
||||||
|
newCenter->x[k] = Float4ToHalfUnchecked(aggCenter->x[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Normalize if needed */
|
||||||
|
if (normprocinfo != NULL)
|
||||||
|
{
|
||||||
|
for (int j = 0; j < numCenters; j++)
|
||||||
|
{
|
||||||
|
Datum newCenter = PointerGetDatum(VectorArrayGet(newCenters, j));
|
||||||
|
|
||||||
|
ApplyNorm(normprocinfo, collation, newCenter, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Use Elkan for performance. This requires distance function to satisfy triangle inequality.
|
* Use Elkan for performance. This requires distance function to satisfy triangle inequality.
|
||||||
*
|
*
|
||||||
@@ -181,19 +330,16 @@ ShowMemoryUsage(Size estimatedSize)
|
|||||||
* https://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf
|
* https://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
ElkanKmeans(Relation index, VectorArray samples, VectorArray centers, IvfflatType type)
|
||||||
{
|
{
|
||||||
FmgrInfo *procinfo;
|
FmgrInfo *procinfo;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
Oid collation;
|
Oid collation;
|
||||||
Vector *vec;
|
|
||||||
Vector *newCenter;
|
|
||||||
int64 j;
|
|
||||||
int64 k;
|
|
||||||
int dimensions = centers->dim;
|
int dimensions = centers->dim;
|
||||||
int numCenters = centers->maxlen;
|
int numCenters = centers->maxlen;
|
||||||
int numSamples = samples->length;
|
int numSamples = samples->length;
|
||||||
VectorArray newCenters;
|
VectorArray newCenters;
|
||||||
|
VectorArray aggCenters;
|
||||||
int *centerCounts;
|
int *centerCounts;
|
||||||
int *closestCenters;
|
int *closestCenters;
|
||||||
float *lowerBound;
|
float *lowerBound;
|
||||||
@@ -201,11 +347,14 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
float *s;
|
float *s;
|
||||||
float *halfcdist;
|
float *halfcdist;
|
||||||
float *newcdist;
|
float *newcdist;
|
||||||
|
MemoryContext kmeansCtx;
|
||||||
|
MemoryContext oldCtx;
|
||||||
|
|
||||||
/* Calculate allocation sizes */
|
/* Calculate allocation sizes */
|
||||||
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
|
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->itemsize);
|
||||||
Size centersSize = VECTOR_ARRAY_SIZE(centers->maxlen, centers->dim);
|
Size centersSize = VECTOR_ARRAY_SIZE(centers->maxlen, centers->itemsize);
|
||||||
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, dimensions);
|
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, centers->itemsize);
|
||||||
|
Size aggCentersSize = type == IVFFLAT_TYPE_VECTOR ? 0 : VECTOR_ARRAY_SIZE(numCenters, VECTOR_SIZE(dimensions));
|
||||||
Size centerCountsSize = sizeof(int) * numCenters;
|
Size centerCountsSize = sizeof(int) * numCenters;
|
||||||
Size closestCentersSize = sizeof(int) * numSamples;
|
Size closestCentersSize = sizeof(int) * numSamples;
|
||||||
Size lowerBoundSize = sizeof(float) * numSamples * numCenters;
|
Size lowerBoundSize = sizeof(float) * numSamples * numCenters;
|
||||||
@@ -215,7 +364,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
Size newcdistSize = sizeof(float) * numCenters;
|
Size newcdistSize = sizeof(float) * numCenters;
|
||||||
|
|
||||||
/* Calculate total size */
|
/* Calculate total size */
|
||||||
Size totalSize = samplesSize + centersSize + newCentersSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
|
Size totalSize = samplesSize + centersSize + newCentersSize + aggCentersSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
|
||||||
|
|
||||||
/* Check memory requirements */
|
/* Check memory requirements */
|
||||||
/* Add one to error message to ceil */
|
/* Add one to error message to ceil */
|
||||||
@@ -234,6 +383,12 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||||
collation = index->rd_indcollation[0];
|
collation = index->rd_indcollation[0];
|
||||||
|
|
||||||
|
/* Use memory context */
|
||||||
|
kmeansCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
|
"Ivfflat kmeans temporary context",
|
||||||
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
|
oldCtx = MemoryContextSwitchTo(kmeansCtx);
|
||||||
|
|
||||||
/* Allocate space */
|
/* Allocate space */
|
||||||
/* Use float instead of double to save memory */
|
/* Use float instead of double to save memory */
|
||||||
centerCounts = palloc(centerCountsSize);
|
centerCounts = palloc(centerCountsSize);
|
||||||
@@ -244,29 +399,50 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
halfcdist = palloc_extended(halfcdistSize, MCXT_ALLOC_HUGE);
|
halfcdist = palloc_extended(halfcdistSize, MCXT_ALLOC_HUGE);
|
||||||
newcdist = palloc(newcdistSize);
|
newcdist = palloc(newcdistSize);
|
||||||
|
|
||||||
newCenters = VectorArrayInit(numCenters, dimensions);
|
aggCenters = VectorArrayInit(numCenters, dimensions, VECTOR_SIZE(dimensions));
|
||||||
for (j = 0; j < numCenters; j++)
|
for (int j = 0; j < numCenters; j++)
|
||||||
{
|
{
|
||||||
vec = VectorArrayGet(newCenters, j);
|
Vector *vec = (Vector *) VectorArrayGet(aggCenters, j);
|
||||||
|
|
||||||
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
||||||
vec->dim = dimensions;
|
vec->dim = dimensions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
{
|
||||||
|
/* Use same centers to save memory */
|
||||||
|
newCenters = aggCenters;
|
||||||
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
newCenters = VectorArrayInit(numCenters, dimensions, centers->itemsize);
|
||||||
|
|
||||||
|
for (int j = 0; j < numCenters; j++)
|
||||||
|
{
|
||||||
|
HalfVector *vec = (HalfVector *) VectorArrayGet(newCenters, j);
|
||||||
|
|
||||||
|
SET_VARSIZE(vec, HALFVEC_SIZE(dimensions));
|
||||||
|
vec->dim = dimensions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
#ifdef IVFFLAT_MEMORY
|
#ifdef IVFFLAT_MEMORY
|
||||||
ShowMemoryUsage(totalSize);
|
ShowMemoryUsage(oldCtx, totalSize);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/* Pick initial centers */
|
/* Pick initial centers */
|
||||||
InitCenters(index, samples, centers, lowerBound);
|
InitCenters(index, samples, centers, lowerBound);
|
||||||
|
|
||||||
/* Assign each x to its closest initial center c(x) = argmin d(x,c) */
|
/* Assign each x to its closest initial center c(x) = argmin d(x,c) */
|
||||||
for (j = 0; j < numSamples; j++)
|
for (int64 j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
float minDistance = FLT_MAX;
|
float minDistance = FLT_MAX;
|
||||||
int closestCenter = 0;
|
int closestCenter = 0;
|
||||||
|
|
||||||
/* Find closest center */
|
/* Find closest center */
|
||||||
for (k = 0; k < numCenters; k++)
|
for (int64 k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
/* TODO Use Lemma 1 in k-means++ initialization */
|
/* TODO Use Lemma 1 in k-means++ initialization */
|
||||||
float distance = lowerBound[j * numCenters + k];
|
float distance = lowerBound[j * numCenters + k];
|
||||||
@@ -292,13 +468,13 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
CHECK_FOR_INTERRUPTS();
|
CHECK_FOR_INTERRUPTS();
|
||||||
|
|
||||||
/* Step 1: For all centers, compute distance */
|
/* Step 1: For all centers, compute distance */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (int64 j = 0; j < numCenters; j++)
|
||||||
{
|
{
|
||||||
vec = VectorArrayGet(centers, j);
|
Datum vec = PointerGetDatum(VectorArrayGet(centers, j));
|
||||||
|
|
||||||
for (k = j + 1; k < numCenters; k++)
|
for (int64 k = j + 1; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
float distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, vec, PointerGetDatum(VectorArrayGet(centers, k))));
|
||||||
|
|
||||||
halfcdist[j * numCenters + k] = distance;
|
halfcdist[j * numCenters + k] = distance;
|
||||||
halfcdist[k * numCenters + j] = distance;
|
halfcdist[k * numCenters + j] = distance;
|
||||||
@@ -306,11 +482,11 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* For all centers c, compute s(c) */
|
/* For all centers c, compute s(c) */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (int64 j = 0; j < numCenters; j++)
|
||||||
{
|
{
|
||||||
float minDistance = FLT_MAX;
|
float minDistance = FLT_MAX;
|
||||||
|
|
||||||
for (k = 0; k < numCenters; k++)
|
for (int64 k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance;
|
float distance;
|
||||||
|
|
||||||
@@ -327,7 +503,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
rjreset = iteration != 0;
|
rjreset = iteration != 0;
|
||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (int64 j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
bool rj;
|
bool rj;
|
||||||
|
|
||||||
@@ -337,8 +513,9 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
rj = rjreset;
|
rj = rjreset;
|
||||||
|
|
||||||
for (k = 0; k < numCenters; k++)
|
for (int64 k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
|
Datum vec;
|
||||||
float dxcx;
|
float dxcx;
|
||||||
|
|
||||||
/* Step 3: For all remaining points x and centers c */
|
/* Step 3: For all remaining points x and centers c */
|
||||||
@@ -351,12 +528,12 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
if (upperBound[j] <= halfcdist[closestCenters[j] * numCenters + k])
|
if (upperBound[j] <= halfcdist[closestCenters[j] * numCenters + k])
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
vec = VectorArrayGet(samples, j);
|
vec = PointerGetDatum(VectorArrayGet(samples, j));
|
||||||
|
|
||||||
/* Step 3a */
|
/* Step 3a */
|
||||||
if (rj)
|
if (rj)
|
||||||
{
|
{
|
||||||
dxcx = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, closestCenters[j]))));
|
dxcx = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, vec, PointerGetDatum(VectorArrayGet(centers, closestCenters[j]))));
|
||||||
|
|
||||||
/* d(x,c(x)) computed, which is a form of d(x,c) */
|
/* d(x,c(x)) computed, which is a form of d(x,c) */
|
||||||
lowerBound[j * numCenters + closestCenters[j]] = dxcx;
|
lowerBound[j * numCenters + closestCenters[j]] = dxcx;
|
||||||
@@ -370,7 +547,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* Step 3b */
|
/* Step 3b */
|
||||||
if (dxcx > lowerBound[j * numCenters + k] || dxcx > halfcdist[closestCenters[j] * numCenters + k])
|
if (dxcx > lowerBound[j * numCenters + k] || dxcx > halfcdist[closestCenters[j] * numCenters + k])
|
||||||
{
|
{
|
||||||
float dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
float dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, vec, PointerGetDatum(VectorArrayGet(centers, k))));
|
||||||
|
|
||||||
/* d(x,c) calculated */
|
/* d(x,c) calculated */
|
||||||
lowerBound[j * numCenters + k] = dxc;
|
lowerBound[j * numCenters + k] = dxc;
|
||||||
@@ -389,66 +566,15 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Step 4: For each center c, let m(c) be mean of all points assigned */
|
/* Step 4: For each center c, let m(c) be mean of all points assigned */
|
||||||
for (j = 0; j < numCenters; j++)
|
ComputeNewCenters(samples, aggCenters, newCenters, centerCounts, closestCenters, normprocinfo, collation, type);
|
||||||
{
|
|
||||||
vec = VectorArrayGet(newCenters, j);
|
|
||||||
for (k = 0; k < dimensions; k++)
|
|
||||||
vec->x[k] = 0.0;
|
|
||||||
|
|
||||||
centerCounts[j] = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
|
||||||
{
|
|
||||||
int closestCenter;
|
|
||||||
|
|
||||||
vec = VectorArrayGet(samples, j);
|
|
||||||
closestCenter = closestCenters[j];
|
|
||||||
|
|
||||||
/* Increment sum and count of closest center */
|
|
||||||
newCenter = VectorArrayGet(newCenters, closestCenter);
|
|
||||||
for (k = 0; k < dimensions; k++)
|
|
||||||
newCenter->x[k] += vec->x[k];
|
|
||||||
|
|
||||||
centerCounts[closestCenter] += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (j = 0; j < numCenters; j++)
|
|
||||||
{
|
|
||||||
vec = VectorArrayGet(newCenters, j);
|
|
||||||
|
|
||||||
if (centerCounts[j] > 0)
|
|
||||||
{
|
|
||||||
/* Double avoids overflow, but requires more memory */
|
|
||||||
/* TODO Update bounds */
|
|
||||||
for (k = 0; k < dimensions; k++)
|
|
||||||
{
|
|
||||||
if (isinf(vec->x[k]))
|
|
||||||
vec->x[k] = vec->x[k] > 0 ? FLT_MAX : -FLT_MAX;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (k = 0; k < dimensions; k++)
|
|
||||||
vec->x[k] /= centerCounts[j];
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
/* TODO Handle empty centers properly */
|
|
||||||
for (k = 0; k < dimensions; k++)
|
|
||||||
vec->x[k] = RandomDouble();
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Normalize if needed */
|
|
||||||
if (normprocinfo != NULL)
|
|
||||||
ApplyNorm(normprocinfo, collation, vec);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Step 5 */
|
/* Step 5 */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (int j = 0; j < numCenters; j++)
|
||||||
newcdist[j] = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(VectorArrayGet(centers, j)), PointerGetDatum(VectorArrayGet(newCenters, j))));
|
newcdist[j] = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(VectorArrayGet(centers, j)), PointerGetDatum(VectorArrayGet(newCenters, j))));
|
||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (int64 j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
for (k = 0; k < numCenters; k++)
|
for (int64 k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance = lowerBound[j * numCenters + k] - newcdist[k];
|
float distance = lowerBound[j * numCenters + k] - newcdist[k];
|
||||||
|
|
||||||
@@ -461,32 +587,26 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
/* Step 6 */
|
/* Step 6 */
|
||||||
/* We reset r(x) before Step 3 in the next iteration */
|
/* We reset r(x) before Step 3 in the next iteration */
|
||||||
for (j = 0; j < numSamples; j++)
|
for (int j = 0; j < numSamples; j++)
|
||||||
upperBound[j] += newcdist[closestCenters[j]];
|
upperBound[j] += newcdist[closestCenters[j]];
|
||||||
|
|
||||||
/* Step 7 */
|
/* Step 7 */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (int j = 0; j < numCenters; j++)
|
||||||
VectorArraySet(centers, j, VectorArrayGet(newCenters, j));
|
VectorArraySet(centers, j, VectorArrayGet(newCenters, j));
|
||||||
|
|
||||||
if (changes == 0 && iteration != 0)
|
if (changes == 0 && iteration != 0)
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
VectorArrayFree(newCenters);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
pfree(centerCounts);
|
MemoryContextDelete(kmeansCtx);
|
||||||
pfree(closestCenters);
|
|
||||||
pfree(lowerBound);
|
|
||||||
pfree(upperBound);
|
|
||||||
pfree(s);
|
|
||||||
pfree(halfcdist);
|
|
||||||
pfree(newcdist);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Detect issues with centers
|
* Detect issues with centers
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
CheckCenters(Relation index, VectorArray centers)
|
CheckCenters(Relation index, VectorArray centers, IvfflatType type)
|
||||||
{
|
{
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
|
|
||||||
@@ -496,7 +616,9 @@ CheckCenters(Relation index, VectorArray centers)
|
|||||||
/* Ensure no NaN or infinite values */
|
/* Ensure no NaN or infinite values */
|
||||||
for (int i = 0; i < centers->length; i++)
|
for (int i = 0; i < centers->length; i++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(centers, i);
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
{
|
||||||
|
Vector *vec = (Vector *) VectorArrayGet(centers, i);
|
||||||
|
|
||||||
for (int j = 0; j < vec->dim; j++)
|
for (int j = 0; j < vec->dim; j++)
|
||||||
{
|
{
|
||||||
@@ -507,13 +629,35 @@ CheckCenters(Relation index, VectorArray centers)
|
|||||||
elog(ERROR, "Infinite value detected. Please report a bug.");
|
elog(ERROR, "Infinite value detected. Please report a bug.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
HalfVector *vec = (HalfVector *) VectorArrayGet(centers, i);
|
||||||
|
|
||||||
|
for (int j = 0; j < vec->dim; j++)
|
||||||
|
{
|
||||||
|
if (HalfIsNan(vec->x[j]))
|
||||||
|
elog(ERROR, "NaN detected. Please report a bug.");
|
||||||
|
|
||||||
|
if (HalfIsInf(vec->x[j]))
|
||||||
|
elog(ERROR, "Infinite value detected. Please report a bug.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
}
|
||||||
|
|
||||||
/* Ensure no duplicate centers */
|
/* Ensure no duplicate centers */
|
||||||
/* Fine to sort in-place */
|
/* Fine to sort in-place */
|
||||||
qsort(centers->items, centers->length, VECTOR_SIZE(centers->dim), CompareVectors);
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
qsort(centers->items, centers->length, centers->itemsize, CompareVectors);
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
qsort(centers->items, centers->length, centers->itemsize, CompareHalfVectors);
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
for (int i = 1; i < centers->length; i++)
|
for (int i = 1; i < centers->length; i++)
|
||||||
{
|
{
|
||||||
if (CompareVectors(VectorArrayGet(centers, i), VectorArrayGet(centers, i - 1)) == 0)
|
if (datumIsEqual(PointerGetDatum(VectorArrayGet(centers, i)), PointerGetDatum(VectorArrayGet(centers, i - 1)), false, -1))
|
||||||
elog(ERROR, "Duplicate centers detected. Please report a bug.");
|
elog(ERROR, "Duplicate centers detected. Please report a bug.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -539,12 +683,12 @@ CheckCenters(Relation index, VectorArray centers)
|
|||||||
* We use spherical k-means for inner product and cosine
|
* We use spherical k-means for inner product and cosine
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers)
|
IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, IvfflatType type)
|
||||||
{
|
{
|
||||||
if (samples->length <= centers->maxlen)
|
if (samples->length <= centers->maxlen)
|
||||||
QuickCenters(index, samples, centers);
|
QuickCenters(index, samples, centers, type);
|
||||||
else
|
else
|
||||||
ElkanKmeans(index, samples, centers);
|
ElkanKmeans(index, samples, centers, type);
|
||||||
|
|
||||||
CheckCenters(index, centers);
|
CheckCenters(index, centers, type);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
#include "access/relscan.h"
|
#include "access/relscan.h"
|
||||||
#include "catalog/pg_operator_d.h"
|
#include "catalog/pg_operator_d.h"
|
||||||
#include "catalog/pg_type_d.h"
|
#include "catalog/pg_type_d.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "lib/pairingheap.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
@@ -177,6 +178,42 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
tuplesort_performsort(so->sortstate);
|
tuplesort_performsort(so->sortstate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get scan value
|
||||||
|
*/
|
||||||
|
static Datum
|
||||||
|
GetScanValue(IndexScanDesc scan)
|
||||||
|
{
|
||||||
|
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||||
|
Datum value;
|
||||||
|
|
||||||
|
if (scan->orderByData->sk_flags & SK_ISNULL)
|
||||||
|
{
|
||||||
|
IvfflatType type = IvfflatGetType(scan->indexRelation);
|
||||||
|
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
|
value = PointerGetDatum(InitVector(so->dimensions));
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
value = PointerGetDatum(InitHalfVector(so->dimensions));
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
value = scan->orderByData->sk_argument;
|
||||||
|
|
||||||
|
/* Value should not be compressed or toasted */
|
||||||
|
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
|
||||||
|
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
|
||||||
|
|
||||||
|
/* Fine if normalization fails */
|
||||||
|
if (so->normprocinfo != NULL)
|
||||||
|
IvfflatNormValue(so->normprocinfo, so->collation, &value, IvfflatGetType(scan->indexRelation));
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Prepare for an index scan
|
* Prepare for an index scan
|
||||||
*/
|
*/
|
||||||
@@ -281,21 +318,7 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
||||||
elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");
|
elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");
|
||||||
|
|
||||||
if (scan->orderByData->sk_flags & SK_ISNULL)
|
value = GetScanValue(scan);
|
||||||
value = PointerGetDatum(InitVector(so->dimensions));
|
|
||||||
else
|
|
||||||
{
|
|
||||||
value = scan->orderByData->sk_argument;
|
|
||||||
|
|
||||||
/* Value should not be compressed or toasted */
|
|
||||||
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
|
|
||||||
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
|
|
||||||
|
|
||||||
/* Fine if normalization fails */
|
|
||||||
if (so->normprocinfo != NULL)
|
|
||||||
IvfflatNormValue(so->normprocinfo, so->collation, &value);
|
|
||||||
}
|
|
||||||
|
|
||||||
IvfflatBench("GetScanLists", GetScanLists(scan, value));
|
IvfflatBench("GetScanLists", GetScanLists(scan, value));
|
||||||
IvfflatBench("GetScanItems", GetScanItems(scan, value));
|
IvfflatBench("GetScanItems", GetScanItems(scan, value));
|
||||||
so->first = false;
|
so->first = false;
|
||||||
|
|||||||
@@ -1,22 +1,27 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
|
#include "catalog/pg_type.h"
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
#include "utils/syscache.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Allocate a vector array
|
* Allocate a vector array
|
||||||
*/
|
*/
|
||||||
VectorArray
|
VectorArray
|
||||||
VectorArrayInit(int maxlen, int dimensions)
|
VectorArrayInit(int maxlen, int dimensions, Size itemsize)
|
||||||
{
|
{
|
||||||
VectorArray res = palloc(sizeof(VectorArrayData));
|
VectorArray res = palloc(sizeof(VectorArrayData));
|
||||||
|
|
||||||
res->length = 0;
|
res->length = 0;
|
||||||
res->maxlen = maxlen;
|
res->maxlen = maxlen;
|
||||||
res->dim = dimensions;
|
res->dim = dimensions;
|
||||||
res->items = palloc_extended(maxlen * VECTOR_SIZE(dimensions), MCXT_ALLOC_ZERO | MCXT_ALLOC_HUGE);
|
res->itemsize = itemsize;
|
||||||
|
res->items = palloc_extended(maxlen * itemsize, MCXT_ALLOC_ZERO | MCXT_ALLOC_HUGE);
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,16 +35,6 @@ VectorArrayFree(VectorArray arr)
|
|||||||
pfree(arr);
|
pfree(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Print vector array - useful for debugging
|
|
||||||
*/
|
|
||||||
void
|
|
||||||
PrintVectorArray(char *msg, VectorArray arr)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < arr->length; i++)
|
|
||||||
PrintVector(msg, VectorArrayGet(arr, i));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the number of lists in the index
|
* Get the number of lists in the index
|
||||||
*/
|
*/
|
||||||
@@ -66,6 +61,37 @@ IvfflatOptionalProcInfo(Relation index, uint16 procnum)
|
|||||||
return index_getprocinfo(index, 1, procnum);
|
return index_getprocinfo(index, 1, procnum);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get type
|
||||||
|
*/
|
||||||
|
IvfflatType
|
||||||
|
IvfflatGetType(Relation index)
|
||||||
|
{
|
||||||
|
Oid typid = TupleDescAttr(index->rd_att, 0)->atttypid;
|
||||||
|
HeapTuple tuple;
|
||||||
|
Form_pg_type type;
|
||||||
|
IvfflatType result;
|
||||||
|
|
||||||
|
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
|
||||||
|
if (!HeapTupleIsValid(tuple))
|
||||||
|
elog(ERROR, "cache lookup failed for type %u", typid);
|
||||||
|
|
||||||
|
type = (Form_pg_type) GETSTRUCT(tuple);
|
||||||
|
if (strcmp(NameStr(type->typname), "vector") == 0)
|
||||||
|
result = IVFFLAT_TYPE_VECTOR;
|
||||||
|
else if (strcmp(NameStr(type->typname), "halfvec") == 0)
|
||||||
|
result = IVFFLAT_TYPE_HALFVEC;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ReleaseSysCache(tuple);
|
||||||
|
elog(ERROR, "type not supported for ivfflat index");
|
||||||
|
}
|
||||||
|
|
||||||
|
ReleaseSysCache(tuple);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Divide by the norm
|
* Divide by the norm
|
||||||
*
|
*
|
||||||
@@ -75,11 +101,13 @@ IvfflatOptionalProcInfo(Relation index, uint16 procnum)
|
|||||||
* if it's different than the original value
|
* if it's different than the original value
|
||||||
*/
|
*/
|
||||||
bool
|
bool
|
||||||
IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value)
|
IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, IvfflatType type)
|
||||||
{
|
{
|
||||||
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
||||||
|
|
||||||
if (norm > 0)
|
if (norm > 0)
|
||||||
|
{
|
||||||
|
if (type == IVFFLAT_TYPE_VECTOR)
|
||||||
{
|
{
|
||||||
Vector *v = DatumGetVector(*value);
|
Vector *v = DatumGetVector(*value);
|
||||||
Vector *result = InitVector(v->dim);
|
Vector *result = InitVector(v->dim);
|
||||||
@@ -88,6 +116,19 @@ IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value)
|
|||||||
result->x[i] = v->x[i] / norm;
|
result->x[i] = v->x[i] / norm;
|
||||||
|
|
||||||
*value = PointerGetDatum(result);
|
*value = PointerGetDatum(result);
|
||||||
|
}
|
||||||
|
else if (type == IVFFLAT_TYPE_HALFVEC)
|
||||||
|
{
|
||||||
|
HalfVector *v = DatumGetHalfVector(*value);
|
||||||
|
HalfVector *result = InitHalfVector(v->dim);
|
||||||
|
|
||||||
|
for (int i = 0; i < v->dim; i++)
|
||||||
|
result->x[i] = Float4ToHalfUnchecked(HalfToFloat4(v->x[i]) / norm);
|
||||||
|
|
||||||
|
*value = PointerGetDatum(result);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
800
src/sparsevec.c
Normal file
800
src/sparsevec.c
Normal file
@@ -0,0 +1,800 @@
|
|||||||
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "fmgr.h"
|
||||||
|
#include "libpq/pqformat.h"
|
||||||
|
#include "sparsevec.h"
|
||||||
|
#include "utils/array.h"
|
||||||
|
#include "utils/builtins.h"
|
||||||
|
#include "vector.h"
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "common/shortest_dec.h"
|
||||||
|
#include "utils/float.h"
|
||||||
|
#else
|
||||||
|
#include <float.h>
|
||||||
|
#include "utils/builtins.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure same dimensions
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckDims(SparseVector * a, SparseVector * b)
|
||||||
|
{
|
||||||
|
if (a->dim != b->dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("different sparsevec 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("sparsevec must have at least 1 dimension")));
|
||||||
|
|
||||||
|
if (dim > SPARSEVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("sparsevec cannot have more than %d dimensions", SPARSEVEC_MAX_DIM)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure valid nnz
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckNnz(int nnz, int dim)
|
||||||
|
{
|
||||||
|
if (nnz < 0)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("sparsevec cannot have negative number of elements")));
|
||||||
|
|
||||||
|
if (nnz > SPARSEVEC_MAX_NNZ)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("sparsevec cannot have more than %d non-zero elements", SPARSEVEC_MAX_NNZ)));
|
||||||
|
|
||||||
|
if (nnz > dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("sparsevec cannot have more elements than dimensions")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure valid index
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckIndex(int32 *indices, int i, int dim)
|
||||||
|
{
|
||||||
|
int32 index = indices[i];
|
||||||
|
|
||||||
|
if (index < 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("index must be greater than zero")));
|
||||||
|
|
||||||
|
if (index > dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("index must be less than or equal to dimensions")));
|
||||||
|
|
||||||
|
if (i > 0)
|
||||||
|
{
|
||||||
|
if (index < indices[i - 1])
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("indexes must be in ascending order")));
|
||||||
|
|
||||||
|
if (index == indices[i - 1])
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("indexes must not contain duplicates")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure finite element
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckElement(float value)
|
||||||
|
{
|
||||||
|
if (isnan(value))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("NaN not allowed in sparsevec")));
|
||||||
|
|
||||||
|
if (isinf(value))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("infinite value not allowed in sparsevec")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Allocate and initialize a new sparse vector
|
||||||
|
*/
|
||||||
|
SparseVector *
|
||||||
|
InitSparseVector(int dim, int nnz)
|
||||||
|
{
|
||||||
|
SparseVector *result;
|
||||||
|
int size;
|
||||||
|
|
||||||
|
size = SPARSEVEC_SIZE(nnz);
|
||||||
|
result = (SparseVector *) palloc0(size);
|
||||||
|
SET_VARSIZE(result, size);
|
||||||
|
result->dim = dim;
|
||||||
|
result->nnz = nnz;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check for whitespace, since array_isspace() is static
|
||||||
|
*/
|
||||||
|
static inline bool
|
||||||
|
sparsevec_isspace(char ch)
|
||||||
|
{
|
||||||
|
if (ch == ' ' ||
|
||||||
|
ch == '\t' ||
|
||||||
|
ch == '\n' ||
|
||||||
|
ch == '\r' ||
|
||||||
|
ch == '\v' ||
|
||||||
|
ch == '\f')
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert textual representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_in);
|
||||||
|
Datum
|
||||||
|
sparsevec_in(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
char *lit = PG_GETARG_CSTRING(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
int dim;
|
||||||
|
char *pt = lit;
|
||||||
|
char *stringEnd;
|
||||||
|
SparseVector *result;
|
||||||
|
float *rvalues;
|
||||||
|
int32 *indices;
|
||||||
|
float *values;
|
||||||
|
int maxNnz;
|
||||||
|
int nnz = 0;
|
||||||
|
|
||||||
|
maxNnz = 1;
|
||||||
|
while (*pt != '\0')
|
||||||
|
{
|
||||||
|
if (*pt == ',')
|
||||||
|
maxNnz++;
|
||||||
|
|
||||||
|
pt++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxNnz > SPARSEVEC_MAX_NNZ)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("sparsevec cannot have more than %d non-zero elements", SPARSEVEC_MAX_NNZ)));
|
||||||
|
|
||||||
|
indices = palloc(maxNnz * sizeof(int32));
|
||||||
|
values = palloc(maxNnz * sizeof(float));
|
||||||
|
|
||||||
|
pt = lit;
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != '{')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit),
|
||||||
|
errdetail("Vector contents must start with \"{\".")));
|
||||||
|
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt == '}')
|
||||||
|
pt++;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (;;)
|
||||||
|
{
|
||||||
|
long index;
|
||||||
|
float value;
|
||||||
|
|
||||||
|
/* TODO Better error */
|
||||||
|
if (nnz == maxNnz)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("ran out of buffer: \"%s\"", lit)));
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
/* Check for empty string like float4in */
|
||||||
|
if (*pt == '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
/* Use similar logic as int2vectorin */
|
||||||
|
errno = 0;
|
||||||
|
index = strtol(pt, &stringEnd, 10);
|
||||||
|
|
||||||
|
if (stringEnd == pt)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
if (errno == ERANGE || index < 1 || index > INT_MAX)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("index \"%ld\" is out of range for type sparsevec", index)));
|
||||||
|
|
||||||
|
pt = stringEnd;
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != ':')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
errno = 0;
|
||||||
|
|
||||||
|
/* Use strtof like float4in to avoid a double-rounding problem */
|
||||||
|
/* Postgres sets LC_NUMERIC to C on startup */
|
||||||
|
value = strtof(pt, &stringEnd);
|
||||||
|
|
||||||
|
if (stringEnd == pt)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
/* Check for range error like float4in */
|
||||||
|
if (errno == ERANGE && (value == 0 || isinf(value)))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("\"%s\" is out of range for type sparsevec", pnstrdup(pt, stringEnd - pt))));
|
||||||
|
|
||||||
|
CheckElement(value);
|
||||||
|
|
||||||
|
/* Do not store zero values */
|
||||||
|
if (value != 0)
|
||||||
|
{
|
||||||
|
indices[nnz] = index;
|
||||||
|
values[nnz] = value;
|
||||||
|
nnz++;
|
||||||
|
}
|
||||||
|
|
||||||
|
pt = stringEnd;
|
||||||
|
|
||||||
|
while (sparsevec_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 sparsevec: \"%s\"", lit)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != '/')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit),
|
||||||
|
errdetail("Unexpected end of input.")));
|
||||||
|
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
/* Use similar logic as int2vectorin */
|
||||||
|
errno = 0;
|
||||||
|
dim = strtol(pt, &stringEnd, 10);
|
||||||
|
|
||||||
|
if (stringEnd == pt)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
pt = stringEnd;
|
||||||
|
|
||||||
|
/* Only whitespace is allowed after the closing brace */
|
||||||
|
while (sparsevec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt != '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type sparsevec: \"%s\"", lit),
|
||||||
|
errdetail("Junk after closing.")));
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
result = InitSparseVector(dim, nnz);
|
||||||
|
rvalues = SPARSEVEC_VALUES(result);
|
||||||
|
for (int i = 0; i < nnz; i++)
|
||||||
|
{
|
||||||
|
result->indices[i] = indices[i];
|
||||||
|
rvalues[i] = values[i];
|
||||||
|
|
||||||
|
CheckIndex(result->indices, i, dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#define AppendChar(ptr, c) (*(ptr)++ = (c))
|
||||||
|
#define AppendFloat(ptr, f) ((ptr) += float_to_shortest_decimal_bufn((f), (ptr)))
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 140000
|
||||||
|
#define AppendInt(ptr, i) ((ptr) += pg_ltoa((i), (ptr)))
|
||||||
|
#else
|
||||||
|
#define AppendInt(ptr, i) \
|
||||||
|
do { \
|
||||||
|
pg_ltoa(i, ptr); \
|
||||||
|
while (*ptr != '\0') \
|
||||||
|
ptr++; \
|
||||||
|
} while (0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to textual representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_out);
|
||||||
|
Datum
|
||||||
|
sparsevec_out(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *sparsevec = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
float *values = SPARSEVEC_VALUES(sparsevec);
|
||||||
|
char *buf;
|
||||||
|
char *ptr;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Need:
|
||||||
|
*
|
||||||
|
* nnz * 10 bytes for index (positive integer)
|
||||||
|
*
|
||||||
|
* nnz bytes for :
|
||||||
|
*
|
||||||
|
* nnz * (FLOAT_SHORTEST_DECIMAL_LEN - 1) bytes for
|
||||||
|
* float_to_shortest_decimal_bufn
|
||||||
|
*
|
||||||
|
* nnz - 1 bytes for ,
|
||||||
|
*
|
||||||
|
* 10 bytes for dimensions
|
||||||
|
*
|
||||||
|
* 4 bytes for {, }, /, and \0
|
||||||
|
*/
|
||||||
|
buf = (char *) palloc((11 + FLOAT_SHORTEST_DECIMAL_LEN) * sparsevec->nnz + 13);
|
||||||
|
ptr = buf;
|
||||||
|
|
||||||
|
AppendChar(ptr, '{');
|
||||||
|
|
||||||
|
for (int i = 0; i < sparsevec->nnz; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
AppendChar(ptr, ',');
|
||||||
|
|
||||||
|
AppendInt(ptr, sparsevec->indices[i]);
|
||||||
|
AppendChar(ptr, ':');
|
||||||
|
AppendFloat(ptr, values[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
AppendChar(ptr, '}');
|
||||||
|
AppendChar(ptr, '/');
|
||||||
|
AppendInt(ptr, sparsevec->dim);
|
||||||
|
*ptr = '\0';
|
||||||
|
|
||||||
|
PG_FREE_IF_COPY(sparsevec, 0);
|
||||||
|
PG_RETURN_CSTRING(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_typmod_in);
|
||||||
|
Datum
|
||||||
|
sparsevec_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 sparsevec must be at least 1")));
|
||||||
|
|
||||||
|
if (*tl > SPARSEVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
||||||
|
errmsg("dimensions for type sparsevec cannot exceed %d", SPARSEVEC_MAX_DIM)));
|
||||||
|
|
||||||
|
PG_RETURN_INT32(*tl);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert external binary representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_recv);
|
||||||
|
Datum
|
||||||
|
sparsevec_recv(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
SparseVector *result;
|
||||||
|
int32 dim;
|
||||||
|
int32 nnz;
|
||||||
|
int32 unused;
|
||||||
|
float *values;
|
||||||
|
|
||||||
|
dim = pq_getmsgint(buf, sizeof(int32));
|
||||||
|
nnz = pq_getmsgint(buf, sizeof(int32));
|
||||||
|
unused = pq_getmsgint(buf, sizeof(int32));
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
CheckNnz(nnz, dim);
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
if (unused != 0)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("expected unused to be 0, not %d", unused)));
|
||||||
|
|
||||||
|
result = InitSparseVector(dim, nnz);
|
||||||
|
values = SPARSEVEC_VALUES(result);
|
||||||
|
|
||||||
|
for (int i = 0; i < nnz; i++)
|
||||||
|
{
|
||||||
|
result->indices[i] = pq_getmsgint(buf, sizeof(int32));
|
||||||
|
CheckIndex(result->indices, i, dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < nnz; i++)
|
||||||
|
{
|
||||||
|
values[i] = pq_getmsgfloat4(buf);
|
||||||
|
CheckElement(values[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to the external binary representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_send);
|
||||||
|
Datum
|
||||||
|
sparsevec_send(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *svec = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
float *values = SPARSEVEC_VALUES(svec);
|
||||||
|
StringInfoData buf;
|
||||||
|
|
||||||
|
pq_begintypsend(&buf);
|
||||||
|
pq_sendint(&buf, svec->dim, sizeof(int32));
|
||||||
|
pq_sendint(&buf, svec->nnz, sizeof(int32));
|
||||||
|
pq_sendint(&buf, svec->unused, sizeof(int32));
|
||||||
|
for (int i = 0; i < svec->nnz; i++)
|
||||||
|
pq_sendint(&buf, svec->indices[i], sizeof(int32));
|
||||||
|
for (int i = 0; i < svec->nnz; i++)
|
||||||
|
pq_sendfloat4(&buf, values[i]);
|
||||||
|
|
||||||
|
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert sparse vector to sparse vector
|
||||||
|
* This is needed to check the type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec);
|
||||||
|
Datum
|
||||||
|
sparsevec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *svec = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
|
||||||
|
CheckExpectedDim(typmod, svec->dim);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(svec);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert dense vector to sparse vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_to_sparsevec);
|
||||||
|
Datum
|
||||||
|
vector_to_sparsevec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
Vector *vec = PG_GETARG_VECTOR_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 == nnz)
|
||||||
|
elog(ERROR, "safety check failed");
|
||||||
|
|
||||||
|
result->indices[j] = i + 1;
|
||||||
|
values[j] = vec->x[i];
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 squared distance between sparse vectors
|
||||||
|
*/
|
||||||
|
static double
|
||||||
|
SparsevecL2SquaredDistance(SparseVector * a, SparseVector * b)
|
||||||
|
{
|
||||||
|
float *ax = SPARSEVEC_VALUES(a);
|
||||||
|
float *bx = SPARSEVEC_VALUES(b);
|
||||||
|
double distance = 0.0;
|
||||||
|
int bpos = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < a->nnz; i++)
|
||||||
|
{
|
||||||
|
int ai = a->indices[i];
|
||||||
|
int bi = -1;
|
||||||
|
|
||||||
|
for (int j = bpos; j < b->nnz; j++)
|
||||||
|
{
|
||||||
|
bi = b->indices[j];
|
||||||
|
|
||||||
|
if (ai == bi)
|
||||||
|
{
|
||||||
|
double diff = ax[i] - bx[j];
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
else if (ai > bi)
|
||||||
|
distance += bx[j] * bx[j];
|
||||||
|
|
||||||
|
/* Update start for next iteration */
|
||||||
|
if (ai >= bi)
|
||||||
|
bpos = j + 1;
|
||||||
|
|
||||||
|
/* Found or passed it */
|
||||||
|
if (bi >= ai)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ai != bi)
|
||||||
|
distance += ax[i] * ax[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int j = bpos; j < b->nnz; j++)
|
||||||
|
distance += bx[j] * bx[j];
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 distance between sparse vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_l2_distance);
|
||||||
|
Datum
|
||||||
|
sparsevec_l2_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
SparseVector *b = PG_GETARG_SPARSEVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt(SparsevecL2SquaredDistance(a, b)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 squared distance between sparse vectors
|
||||||
|
* This saves a sqrt calculation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_l2_squared_distance);
|
||||||
|
Datum
|
||||||
|
sparsevec_l2_squared_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
SparseVector *b = PG_GETARG_SPARSEVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(SparsevecL2SquaredDistance(a, b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the inner product of two sparse vectors
|
||||||
|
*/
|
||||||
|
static double
|
||||||
|
SparsevecInnerProduct(SparseVector * a, SparseVector * b)
|
||||||
|
{
|
||||||
|
float *ax = SPARSEVEC_VALUES(a);
|
||||||
|
float *bx = SPARSEVEC_VALUES(b);
|
||||||
|
double distance = 0.0;
|
||||||
|
int bpos = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < a->nnz; i++)
|
||||||
|
{
|
||||||
|
int ai = a->indices[i];
|
||||||
|
|
||||||
|
for (int j = bpos; j < b->nnz; j++)
|
||||||
|
{
|
||||||
|
int bi = b->indices[j];
|
||||||
|
|
||||||
|
/* Only update when the same index */
|
||||||
|
if (ai == bi)
|
||||||
|
distance += ax[i] * bx[j];
|
||||||
|
|
||||||
|
/* Update start for next iteration */
|
||||||
|
if (ai >= bi)
|
||||||
|
bpos = j + 1;
|
||||||
|
|
||||||
|
/* Found or passed it */
|
||||||
|
if (bi >= ai)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the inner product of two sparse vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_inner_product);
|
||||||
|
Datum
|
||||||
|
sparsevec_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
SparseVector *b = PG_GETARG_SPARSEVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(SparsevecInnerProduct(a, b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the negative inner product of two sparse vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_negative_inner_product);
|
||||||
|
Datum
|
||||||
|
sparsevec_negative_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
SparseVector *b = PG_GETARG_SPARSEVEC_P(1);
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(-SparsevecInnerProduct(a, b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the cosine distance between two sparse vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_cosine_distance);
|
||||||
|
Datum
|
||||||
|
sparsevec_cosine_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
SparseVector *b = PG_GETARG_SPARSEVEC_P(1);
|
||||||
|
float *ax = SPARSEVEC_VALUES(a);
|
||||||
|
float *bx = SPARSEVEC_VALUES(b);
|
||||||
|
float norma = 0.0;
|
||||||
|
float normb = 0.0;
|
||||||
|
double similarity;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
similarity = SparsevecInnerProduct(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->nnz; i++)
|
||||||
|
norma += ax[i] * ax[i];
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < b->nnz; i++)
|
||||||
|
normb += bx[i] * bx[i];
|
||||||
|
|
||||||
|
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
|
||||||
|
similarity /= sqrt((double) norma * (double) normb);
|
||||||
|
|
||||||
|
#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.0;
|
||||||
|
else if (similarity < -1)
|
||||||
|
similarity = -1.0;
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(1.0 - similarity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 norm of a sparse vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_norm);
|
||||||
|
Datum
|
||||||
|
sparsevec_norm(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *a = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
float *ax = SPARSEVEC_VALUES(a);
|
||||||
|
double norm = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->nnz; i++)
|
||||||
|
norm += (double) ax[i] * (double) ax[i];
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt(norm));
|
||||||
|
}
|
||||||
25
src/sparsevec.h
Normal file
25
src/sparsevec.h
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
#ifndef SPARSEVEC_H
|
||||||
|
#define SPARSEVEC_H
|
||||||
|
|
||||||
|
#define SPARSEVEC_MAX_DIM 100000
|
||||||
|
#define SPARSEVEC_MAX_NNZ 16000
|
||||||
|
|
||||||
|
/* Ensure values are aligned */
|
||||||
|
#define SPARSEVEC_SIZE(_nnz) (offsetof(SparseVector, indices) + MAXALIGN((_nnz) * sizeof(int32)) + (_nnz * sizeof(float)))
|
||||||
|
#define SPARSEVEC_VALUES(x) ((float *) (((char *) (x)) + offsetof(SparseVector, indices) + MAXALIGN((x)->nnz * sizeof(int32))))
|
||||||
|
#define DatumGetSparseVector(x) ((SparseVector *) PG_DETOAST_DATUM(x))
|
||||||
|
#define PG_GETARG_SPARSEVEC_P(x) DatumGetSparseVector(PG_GETARG_DATUM(x))
|
||||||
|
#define PG_RETURN_SPARSEVEC_P(x) PG_RETURN_POINTER(x)
|
||||||
|
|
||||||
|
typedef struct SparseVector
|
||||||
|
{
|
||||||
|
int32 vl_len_; /* varlena header (do not touch directly!) */
|
||||||
|
int32 dim; /* number of dimensions */
|
||||||
|
int32 nnz;
|
||||||
|
int32 unused;
|
||||||
|
int32 indices[FLEXIBLE_ARRAY_MEMBER];
|
||||||
|
} SparseVector;
|
||||||
|
|
||||||
|
SparseVector *InitSparseVector(int dim, int nnz);
|
||||||
|
|
||||||
|
#endif
|
||||||
253
src/vector.c
253
src/vector.c
@@ -6,11 +6,14 @@
|
|||||||
#include "catalog/pg_type.h"
|
#include "catalog/pg_type.h"
|
||||||
#include "common/shortest_dec.h"
|
#include "common/shortest_dec.h"
|
||||||
#include "fmgr.h"
|
#include "fmgr.h"
|
||||||
|
#include "halfutils.h"
|
||||||
|
#include "halfvec.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "lib/stringinfo.h"
|
#include "lib/stringinfo.h"
|
||||||
#include "libpq/pqformat.h"
|
#include "libpq/pqformat.h"
|
||||||
#include "port.h" /* for strtof() */
|
#include "port.h" /* for strtof() */
|
||||||
|
#include "sparsevec.h"
|
||||||
#include "utils/array.h"
|
#include "utils/array.h"
|
||||||
#include "utils/builtins.h"
|
#include "utils/builtins.h"
|
||||||
#include "utils/float.h"
|
#include "utils/float.h"
|
||||||
@@ -30,6 +33,13 @@
|
|||||||
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
|
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
|
||||||
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
|
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
|
||||||
|
|
||||||
|
/* target_clones requires glibc */
|
||||||
|
#if defined(__x86_64__) && defined(__gnu_linux__) && defined(__has_attribute) && __has_attribute(target_clones) && !defined(__FMA__)
|
||||||
|
#define VECTOR_DISPATCH __attribute__((target_clones("default", "fma")))
|
||||||
|
#else
|
||||||
|
#define VECTOR_DISPATCH
|
||||||
|
#endif
|
||||||
|
|
||||||
PG_MODULE_MAGIC;
|
PG_MODULE_MAGIC;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -39,6 +49,7 @@ PGDLLEXPORT void _PG_init(void);
|
|||||||
void
|
void
|
||||||
_PG_init(void)
|
_PG_init(void)
|
||||||
{
|
{
|
||||||
|
HalfvecInit();
|
||||||
HnswInit();
|
HnswInit();
|
||||||
IvfflatInit();
|
IvfflatInit();
|
||||||
}
|
}
|
||||||
@@ -177,27 +188,33 @@ vector_in(PG_FUNCTION_ARGS)
|
|||||||
int32 typmod = PG_GETARG_INT32(2);
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
float x[VECTOR_MAX_DIM];
|
float x[VECTOR_MAX_DIM];
|
||||||
int dim = 0;
|
int dim = 0;
|
||||||
char *pt;
|
char *pt = lit;
|
||||||
char *stringEnd;
|
|
||||||
Vector *result;
|
Vector *result;
|
||||||
char *litcopy = pstrdup(lit);
|
|
||||||
char *str = litcopy;
|
|
||||||
|
|
||||||
while (vector_isspace(*str))
|
while (vector_isspace(*pt))
|
||||||
str++;
|
pt++;
|
||||||
|
|
||||||
if (*str != '[')
|
if (*pt != '[')
|
||||||
ereport(ERROR,
|
ereport(ERROR,
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
errmsg("malformed vector literal: \"%s\"", lit),
|
errmsg("invalid input syntax for type vector: \"%s\"", lit),
|
||||||
errdetail("Vector contents must start with \"[\".")));
|
errdetail("Vector contents must start with \"[\".")));
|
||||||
|
|
||||||
str++;
|
pt++;
|
||||||
pt = strtok(str, ",");
|
|
||||||
stringEnd = pt;
|
|
||||||
|
|
||||||
while (pt != NULL && *stringEnd != ']')
|
while (vector_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt == ']')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("vector must have at least 1 dimension")));
|
||||||
|
|
||||||
|
for (;;)
|
||||||
{
|
{
|
||||||
|
float val;
|
||||||
|
char *stringEnd;
|
||||||
|
|
||||||
if (dim == VECTOR_MAX_DIM)
|
if (dim == VECTOR_MAX_DIM)
|
||||||
ereport(ERROR,
|
ereport(ERROR,
|
||||||
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
@@ -212,61 +229,55 @@ vector_in(PG_FUNCTION_ARGS)
|
|||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
||||||
|
|
||||||
|
errno = 0;
|
||||||
|
|
||||||
/* Use strtof like float4in to avoid a double-rounding problem */
|
/* Use strtof like float4in to avoid a double-rounding problem */
|
||||||
x[dim] = strtof(pt, &stringEnd);
|
/* Postgres sets LC_NUMERIC to C on startup */
|
||||||
CheckElement(x[dim]);
|
val = strtof(pt, &stringEnd);
|
||||||
dim++;
|
|
||||||
|
|
||||||
if (stringEnd == pt)
|
if (stringEnd == pt)
|
||||||
ereport(ERROR,
|
ereport(ERROR,
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
||||||
|
|
||||||
while (vector_isspace(*stringEnd))
|
/* Check for range error like float4in */
|
||||||
stringEnd++;
|
if (errno == ERANGE && isinf(val))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("\"%s\" is out of range for type vector", pnstrdup(pt, stringEnd - pt))));
|
||||||
|
|
||||||
if (*stringEnd != '\0' && *stringEnd != ']')
|
CheckElement(val);
|
||||||
|
x[dim++] = val;
|
||||||
|
|
||||||
|
pt = stringEnd;
|
||||||
|
|
||||||
|
while (vector_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
if (*pt == ',')
|
||||||
|
pt++;
|
||||||
|
else if (*pt == ']')
|
||||||
|
{
|
||||||
|
pt++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else
|
||||||
ereport(ERROR,
|
ereport(ERROR,
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
errmsg("invalid input syntax for type vector: \"%s\"", lit)));
|
||||||
|
|
||||||
pt = strtok(NULL, ",");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (stringEnd == NULL || *stringEnd != ']')
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
|
||||||
errmsg("malformed vector literal: \"%s\"", lit),
|
|
||||||
errdetail("Unexpected end of input.")));
|
|
||||||
|
|
||||||
stringEnd++;
|
|
||||||
|
|
||||||
/* Only whitespace is allowed after the closing brace */
|
/* Only whitespace is allowed after the closing brace */
|
||||||
while (vector_isspace(*stringEnd))
|
while (vector_isspace(*pt))
|
||||||
stringEnd++;
|
pt++;
|
||||||
|
|
||||||
if (*stringEnd != '\0')
|
if (*pt != '\0')
|
||||||
ereport(ERROR,
|
ereport(ERROR,
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
errmsg("malformed vector literal: \"%s\"", lit),
|
errmsg("invalid input syntax for type vector: \"%s\"", lit),
|
||||||
errdetail("Junk after closing right brace.")));
|
errdetail("Junk after closing right brace.")));
|
||||||
|
|
||||||
/* Ensure no consecutive delimiters since strtok skips */
|
CheckDim(dim);
|
||||||
for (pt = lit + 1; *pt != '\0'; pt++)
|
|
||||||
{
|
|
||||||
if (pt[-1] == ',' && *pt == ',')
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
|
||||||
errmsg("malformed vector literal: \"%s\"", lit)));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dim < 1)
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
|
||||||
errmsg("vector must have at least 1 dimension")));
|
|
||||||
|
|
||||||
pfree(litcopy);
|
|
||||||
|
|
||||||
CheckExpectedDim(typmod, dim);
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
result = InitVector(dim);
|
result = InitVector(dim);
|
||||||
@@ -531,6 +542,44 @@ vector_to_float4(PG_FUNCTION_ARGS)
|
|||||||
PG_RETURN_POINTER(result);
|
PG_RETURN_POINTER(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert half vector to vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(halfvec_to_vector);
|
||||||
|
Datum
|
||||||
|
halfvec_to_vector(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
HalfVector *vec = PG_GETARG_HALFVEC_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] = HalfToFloat4(vec->x[i]);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
VECTOR_DISPATCH static float
|
||||||
|
VectorL2SquaredDistance(int dim, float *ax, float *bx)
|
||||||
|
{
|
||||||
|
float distance = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
float diff = ax[i] - bx[i];
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the L2 distance between vectors
|
* Get the L2 distance between vectors
|
||||||
*/
|
*/
|
||||||
@@ -540,21 +589,10 @@ l2_distance(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float distance = 0.0;
|
|
||||||
float diff;
|
|
||||||
|
|
||||||
CheckDims(a, b);
|
CheckDims(a, b);
|
||||||
|
|
||||||
/* Auto-vectorized */
|
PG_RETURN_FLOAT8(sqrt((double) VectorL2SquaredDistance(a->dim, a->x, b->x)));
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
{
|
|
||||||
diff = ax[i] - bx[i];
|
|
||||||
distance += diff * diff;
|
|
||||||
}
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8(sqrt((double) distance));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -567,21 +605,22 @@ vector_l2_squared_distance(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float distance = 0.0;
|
|
||||||
float diff;
|
|
||||||
|
|
||||||
CheckDims(a, b);
|
CheckDims(a, b);
|
||||||
|
|
||||||
/* Auto-vectorized */
|
PG_RETURN_FLOAT8((double) VectorL2SquaredDistance(a->dim, a->x, b->x));
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
{
|
|
||||||
diff = ax[i] - bx[i];
|
|
||||||
distance += diff * diff;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
PG_RETURN_FLOAT8((double) distance);
|
VECTOR_DISPATCH static float
|
||||||
|
VectorInnerProduct(int dim, float *ax, float *bx)
|
||||||
|
{
|
||||||
|
float distance = 0.0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
distance += ax[i] * bx[i];
|
||||||
|
|
||||||
|
return distance;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -593,17 +632,10 @@ inner_product(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float distance = 0.0;
|
|
||||||
|
|
||||||
CheckDims(a, b);
|
CheckDims(a, b);
|
||||||
|
|
||||||
/* Auto-vectorized */
|
PG_RETURN_FLOAT8((double) VectorInnerProduct(a->dim, a->x, b->x));
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
distance += ax[i] * bx[i];
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8((double) distance);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -615,17 +647,10 @@ vector_negative_inner_product(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float distance = 0.0;
|
|
||||||
|
|
||||||
CheckDims(a, b);
|
CheckDims(a, b);
|
||||||
|
|
||||||
/* Auto-vectorized */
|
PG_RETURN_FLOAT8((double) -VectorInnerProduct(a->dim, a->x, b->x));
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
distance += ax[i] * bx[i];
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8((double) distance * -1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -683,18 +708,11 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float dp = 0.0;
|
|
||||||
double distance;
|
double distance;
|
||||||
|
|
||||||
CheckDims(a, b);
|
CheckDims(a, b);
|
||||||
|
|
||||||
/* Auto-vectorized */
|
distance = (double) VectorInnerProduct(a->dim, a->x, b->x);
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
dp += ax[i] * bx[i];
|
|
||||||
|
|
||||||
distance = (double) dp;
|
|
||||||
|
|
||||||
/* Prevent NaN with acos with loss of precision */
|
/* Prevent NaN with acos with loss of precision */
|
||||||
if (distance > 1)
|
if (distance > 1)
|
||||||
@@ -909,30 +927,6 @@ subvector(PG_FUNCTION_ARGS)
|
|||||||
PG_RETURN_POINTER(result);
|
PG_RETURN_POINTER(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Concatenate vectors
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_concat);
|
|
||||||
Datum
|
|
||||||
vector_concat(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
|
||||||
Vector *result;
|
|
||||||
int dim = a->dim + b->dim;
|
|
||||||
|
|
||||||
CheckDim(dim);
|
|
||||||
result = InitVector(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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Internal helper to compare vectors
|
* Internal helper to compare vectors
|
||||||
*/
|
*/
|
||||||
@@ -1215,3 +1209,26 @@ vector_avg(PG_FUNCTION_ARGS)
|
|||||||
|
|
||||||
PG_RETURN_POINTER(result);
|
PG_RETURN_POINTER(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert sparse vector to dense vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(sparsevec_to_vector);
|
||||||
|
Datum
|
||||||
|
sparsevec_to_vector(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
SparseVector *svec = PG_GETARG_SPARSEVEC_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
Vector *result;
|
||||||
|
int dim = svec->dim;
|
||||||
|
float *values = SPARSEVEC_VALUES(svec);
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
result = InitVector(dim);
|
||||||
|
for (int i = 0; i < svec->nnz; i++)
|
||||||
|
result->x[svec->indices[i] - 1] = values[i];
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,64 +1,104 @@
|
|||||||
SELECT hamming_distance(B'111', B'111');
|
SELECT hamming_distance('111', '111');
|
||||||
hamming_distance
|
hamming_distance
|
||||||
------------------
|
------------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'110');
|
SELECT hamming_distance('111', '110');
|
||||||
hamming_distance
|
hamming_distance
|
||||||
------------------
|
------------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'100');
|
SELECT hamming_distance('111', '100');
|
||||||
hamming_distance
|
hamming_distance
|
||||||
------------------
|
------------------
|
||||||
2
|
2
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'000');
|
SELECT hamming_distance('111', '000');
|
||||||
hamming_distance
|
hamming_distance
|
||||||
------------------
|
------------------
|
||||||
3
|
3
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'00');
|
SELECT hamming_distance('10101010101010101010', '01010101010101010101');
|
||||||
|
hamming_distance
|
||||||
|
------------------
|
||||||
|
20
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT hamming_distance('', '');
|
||||||
|
hamming_distance
|
||||||
|
------------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT hamming_distance('111', '00');
|
||||||
ERROR: different bit lengths 3 and 2
|
ERROR: different bit lengths 3 and 2
|
||||||
SELECT jaccard_distance(B'1111', B'1111');
|
SELECT hamming_distance('111', '000'::varbit(4));
|
||||||
|
hamming_distance
|
||||||
|
------------------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT hamming_distance('111', '0000'::varbit(4));
|
||||||
|
ERROR: different bit lengths 3 and 4
|
||||||
|
SELECT jaccard_distance('1111', '1111');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1110');
|
SELECT jaccard_distance('1111', '1110');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
0.25
|
0.25
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1100');
|
SELECT jaccard_distance('1111', '1100');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
0.5
|
0.5
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1000');
|
SELECT jaccard_distance('1111', '1000');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
0.75
|
0.75
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'0000');
|
SELECT jaccard_distance('1111', '0000');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1100', B'1000');
|
SELECT jaccard_distance('1100', '1000');
|
||||||
jaccard_distance
|
jaccard_distance
|
||||||
------------------
|
------------------
|
||||||
0.5
|
0.5
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'000');
|
SELECT jaccard_distance('10101010101010101010', '01010101010101010101');
|
||||||
|
jaccard_distance
|
||||||
|
------------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT jaccard_distance('', '');
|
||||||
|
jaccard_distance
|
||||||
|
------------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT jaccard_distance('1111', '000');
|
||||||
ERROR: different bit lengths 4 and 3
|
ERROR: different bit lengths 4 and 3
|
||||||
|
SELECT jaccard_distance('1111', '0000'::varbit(5));
|
||||||
|
jaccard_distance
|
||||||
|
------------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT jaccard_distance('1111', '00000'::varbit(5));
|
||||||
|
ERROR: different bit lengths 4 and 5
|
||||||
|
|||||||
@@ -28,6 +28,26 @@ SELECT ARRAY[1,2,3]::numeric[]::vector;
|
|||||||
[1,2,3]
|
[1,2,3]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::real[];
|
||||||
|
float4
|
||||||
|
---------
|
||||||
|
{1,2,3}
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::vector;
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::vector(3);
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::vector(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
SELECT '{NULL}'::real[]::vector;
|
SELECT '{NULL}'::real[]::vector;
|
||||||
ERROR: array must not contain nulls
|
ERROR: array must not contain nulls
|
||||||
SELECT '{NaN}'::real[]::vector;
|
SELECT '{NaN}'::real[]::vector;
|
||||||
@@ -40,12 +60,116 @@ SELECT '{}'::real[]::vector;
|
|||||||
ERROR: vector must have at least 1 dimension
|
ERROR: vector must have at least 1 dimension
|
||||||
SELECT '{{1}}'::real[]::vector;
|
SELECT '{{1}}'::real[]::vector;
|
||||||
ERROR: array must be 1-D
|
ERROR: array must be 1-D
|
||||||
SELECT '[1,2,3]'::vector::real[];
|
SELECT '{1,2,3}'::double precision[]::vector;
|
||||||
float4
|
vector
|
||||||
---------
|
---------
|
||||||
{1,2,3}
|
[1,2,3]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::double precision[]::vector(3);
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::double precision[]::vector(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '{4e38,-4e38}'::double precision[]::vector;
|
||||||
|
ERROR: infinite value not allowed in vector
|
||||||
|
SELECT '{1e-46,-1e-46}'::double precision[]::vector;
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[0,-0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec(3);
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '[65520]'::vector::halfvec;
|
||||||
|
ERROR: "65520" is out of range for type halfvec
|
||||||
|
SELECT '[1e-8]'::vector::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector;
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector(3);
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec(3);
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '{65520,-65520}'::real[]::halfvec;
|
||||||
|
ERROR: "65520" is out of range for type halfvec
|
||||||
|
SELECT '{1e-8,-1e-8}'::real[]::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[0,-0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------------
|
||||||
|
{2:1.5,4:3.5}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec(5);
|
||||||
|
sparsevec
|
||||||
|
-----------------
|
||||||
|
{2:1.5,4:3.5}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec(4);
|
||||||
|
ERROR: expected 4 dimensions, not 5
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector;
|
||||||
|
vector
|
||||||
|
-----------------
|
||||||
|
[0,1.5,0,3.5,0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector(5);
|
||||||
|
vector
|
||||||
|
-----------------
|
||||||
|
[0,1.5,0,3.5,0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector(4);
|
||||||
|
ERROR: expected 4 dimensions, not 5
|
||||||
|
SELECT '{}/16001'::sparsevec::vector;
|
||||||
|
ERROR: vector cannot have more than 16000 dimensions
|
||||||
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
|
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
|
||||||
ERROR: vector cannot have more than 16000 dimensions
|
ERROR: vector cannot have more than 16000 dimensions
|
||||||
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
|
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
CREATE TABLE t (val vector(3));
|
CREATE TABLE t (val vector(3), val2 halfvec(3), val3 sparsevec(3));
|
||||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
INSERT INTO t (val, val2, val3) VALUES ('[0,0,0]', '[0,0,0]', '{}/3'), ('[1,2,3]', '[1,2,3]', '{1:1,2:2,3:3}/3'), ('[1,1,1]', '[1,1,1]', '{1:1,2:1,3:1}/3'), (NULL, NULL, NULL);
|
||||||
CREATE TABLE t2 (val vector(3));
|
CREATE TABLE t2 (val vector(3), val2 halfvec(3), val3 sparsevec(3));
|
||||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||||
SELECT * FROM t2 ORDER BY val;
|
SELECT * FROM t2 ORDER BY val;
|
||||||
val
|
val | val2 | val3
|
||||||
---------
|
---------+---------+-----------------
|
||||||
[0,0,0]
|
[0,0,0] | [0,0,0] | {}/3
|
||||||
[1,1,1]
|
[1,1,1] | [1,1,1] | {1:1,2:1,3:1}/3
|
||||||
[1,2,3]
|
[1,2,3] | [1,2,3] | {1:1,2:2,3:3}/3
|
||||||
|
| |
|
||||||
(4 rows)
|
(4 rows)
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|||||||
176
test/expected/halfvec_functions.out
Normal file
176
test/expected/halfvec_functions.out
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
SELECT round(halfvec_norm('[1,1]')::numeric, 5);
|
||||||
|
round
|
||||||
|
---------
|
||||||
|
1.41421
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT halfvec_norm('[3,4]');
|
||||||
|
halfvec_norm
|
||||||
|
--------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT halfvec_norm('[0,1]');
|
||||||
|
halfvec_norm
|
||||||
|
--------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('[0,0]'::halfvec, '[3,4]');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('[0,0]'::halfvec, '[0,1]');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
ERROR: different halfvec dimensions 2 and 1
|
||||||
|
SELECT l2_distance('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,4,5]');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[0,0]'::halfvec <-> '[3,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::halfvec, '[3,4]');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
11
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::halfvec, '[3]');
|
||||||
|
ERROR: different halfvec dimensions 2 and 1
|
||||||
|
SELECT inner_product('[65504]'::halfvec, '[65504]');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
4290774016
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,2,3,4,5,6,7,8,9]');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
45
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2]'::halfvec <#> '[3,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
-11
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[2,4]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[0,0]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
NaN
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[1,1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,0]'::halfvec, '[0,2]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[-1,-1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
ERROR: different halfvec dimensions 2 and 1
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[1.1,1.1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[-1.1,-1.1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2]'::halfvec <=> '[2,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::halfvec, '[3,4]');
|
||||||
|
l1_distance
|
||||||
|
-------------
|
||||||
|
7
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::halfvec, '[0,1]');
|
||||||
|
l1_distance
|
||||||
|
-------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
ERROR: different halfvec dimensions 2 and 1
|
||||||
|
SELECT quantize_binary('[1,0,-1]'::halfvec);
|
||||||
|
quantize_binary
|
||||||
|
-----------------
|
||||||
|
100
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]'::halfvec);
|
||||||
|
quantize_binary
|
||||||
|
-----------------
|
||||||
|
01001110101
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 1, 3);
|
||||||
|
subvector
|
||||||
|
-----------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, 2);
|
||||||
|
subvector
|
||||||
|
-----------
|
||||||
|
[3,4]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, -1, 3);
|
||||||
|
subvector
|
||||||
|
-----------
|
||||||
|
[1]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, 9);
|
||||||
|
subvector
|
||||||
|
-----------
|
||||||
|
[3,4,5]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 1, 0);
|
||||||
|
ERROR: halfvec must have at least 1 dimension
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, -1);
|
||||||
|
ERROR: halfvec must have at least 1 dimension
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, -1, 2);
|
||||||
|
ERROR: halfvec must have at least 1 dimension
|
||||||
164
test/expected/halfvec_input.out
Normal file
164
test/expected/halfvec_input.out
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
SELECT '[1,2,3]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[-1,-2,-3]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
------------
|
||||||
|
[-1,-2,-3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1.,2.,3.]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ' [ 1, 2 , 3 ] '::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1.23456]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
------------
|
||||||
|
[1.234375]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[hello,1]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[hello,1]"
|
||||||
|
LINE 1: SELECT '[hello,1]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[NaN,1]'::halfvec;
|
||||||
|
ERROR: NaN not allowed in halfvec
|
||||||
|
LINE 1: SELECT '[NaN,1]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[Infinity,1]'::halfvec;
|
||||||
|
ERROR: infinite value not allowed in halfvec
|
||||||
|
LINE 1: SELECT '[Infinity,1]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[-Infinity,1]'::halfvec;
|
||||||
|
ERROR: infinite value not allowed in halfvec
|
||||||
|
LINE 1: SELECT '[-Infinity,1]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[65519,-65519]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
----------------
|
||||||
|
[65504,-65504]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[65520,-65520]'::halfvec;
|
||||||
|
ERROR: "65520" is out of range for type halfvec
|
||||||
|
LINE 1: SELECT '[65520,-65520]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1e-8,-1e-8]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[0,-0]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[4e38,1]'::halfvec;
|
||||||
|
ERROR: "4e38" is out of range for type halfvec
|
||||||
|
LINE 1: SELECT '[4e38,1]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1e-46,1]'::halfvec;
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[0,1]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1,2,3"
|
||||||
|
LINE 1: SELECT '[1,2,3'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]9'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1,2,3]9"
|
||||||
|
LINE 1: SELECT '[1,2,3]9'::halfvec;
|
||||||
|
^
|
||||||
|
DETAIL: Junk after closing right brace.
|
||||||
|
SELECT '1,2,3'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "1,2,3"
|
||||||
|
LINE 1: SELECT '1,2,3'::halfvec;
|
||||||
|
^
|
||||||
|
DETAIL: Vector contents must start with "[".
|
||||||
|
SELECT ''::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: ""
|
||||||
|
LINE 1: SELECT ''::halfvec;
|
||||||
|
^
|
||||||
|
DETAIL: Vector contents must start with "[".
|
||||||
|
SELECT '['::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "["
|
||||||
|
LINE 1: SELECT '['::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[ '::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[ "
|
||||||
|
LINE 1: SELECT '[ '::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[,'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[,"
|
||||||
|
LINE 1: SELECT '[,'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[]'::halfvec;
|
||||||
|
ERROR: halfvec must have at least 1 dimension
|
||||||
|
LINE 1: SELECT '[]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[ ]'::halfvec;
|
||||||
|
ERROR: halfvec must have at least 1 dimension
|
||||||
|
LINE 1: SELECT '[ ]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[,]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[,]"
|
||||||
|
LINE 1: SELECT '[,]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1,]"
|
||||||
|
LINE 1: SELECT '[1,]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1a]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1a]"
|
||||||
|
LINE 1: SELECT '[1a]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,,3]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1,,3]"
|
||||||
|
LINE 1: SELECT '[1,,3]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1, ,3]'::halfvec;
|
||||||
|
ERROR: invalid input syntax for type halfvec: "[1, ,3]"
|
||||||
|
LINE 1: SELECT '[1, ,3]'::halfvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::halfvec(3);
|
||||||
|
halfvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '[1,2,3]'::halfvec(3, 2);
|
||||||
|
ERROR: invalid type modifier
|
||||||
|
LINE 1: SELECT '[1,2,3]'::halfvec(3, 2);
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::halfvec('a');
|
||||||
|
ERROR: invalid input syntax for type integer: "a"
|
||||||
|
LINE 1: SELECT '[1,2,3]'::halfvec('a');
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::halfvec(0);
|
||||||
|
ERROR: dimensions for type halfvec must be at least 1
|
||||||
|
LINE 1: SELECT '[1,2,3]'::halfvec(0);
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::halfvec(16001);
|
||||||
|
ERROR: dimensions for type halfvec cannot exceed 16000
|
||||||
|
LINE 1: SELECT '[1,2,3]'::halfvec(16001);
|
||||||
|
^
|
||||||
|
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::halfvec[]);
|
||||||
|
unnest
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
[4,5,6]
|
||||||
|
(2 rows)
|
||||||
|
|
||||||
|
SELECT '{"[1,2,3]"}'::halfvec(2)[];
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
@@ -19,3 +19,11 @@ SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <~> (SELECT NULL::bit)) t2;
|
|||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
-- TODO move
|
||||||
|
CREATE TABLE t (val varbit(3));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
ERROR: type not supported for hnsw index
|
||||||
|
CREATE INDEX ON t USING hnsw ((val::bit(3)) bit_hamming_ops);
|
||||||
|
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
||||||
|
ERROR: column cannot have more than 64000 dimensions for hnsw index
|
||||||
|
DROP TABLE t;
|
||||||
26
test/expected/hnsw_halfvec_cosine.out
Normal file
26
test/expected/hnsw_halfvec_cosine.out
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
21
test/expected/hnsw_halfvec_ip.out
Normal file
21
test/expected/hnsw_halfvec_ip.out
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
33
test/expected/hnsw_halfvec_l2.out
Normal file
33
test/expected/hnsw_halfvec_l2.out
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) 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;
|
||||||
26
test/expected/hnsw_sparsevec_cosine.out
Normal file
26
test/expected/hnsw_sparsevec_cosine.out
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_cosine_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
SELECT * FROM t ORDER BY val <=> '{1:3,2:3,3:3}/3';
|
||||||
|
val
|
||||||
|
-----------------
|
||||||
|
{1:1,2:1,3:1}/3
|
||||||
|
{1:1,2:2,3:3}/3
|
||||||
|
{1:1,2:2,3:4}/3
|
||||||
|
(3 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '{}/3') t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::sparsevec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
21
test/expected/hnsw_sparsevec_ip.out
Normal file
21
test/expected/hnsw_sparsevec_ip.out
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_ip_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
SELECT * FROM t ORDER BY val <#> '{1:3,2:3,3:3}/3';
|
||||||
|
val
|
||||||
|
-----------------
|
||||||
|
{1:1,2:2,3:4}/3
|
||||||
|
{1:1,2:2,3:3}/3
|
||||||
|
{1:1,2:1,3:1}/3
|
||||||
|
{}/3
|
||||||
|
(4 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::sparsevec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
43
test/expected/hnsw_sparsevec_l2.out
Normal file
43
test/expected/hnsw_sparsevec_l2.out
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
SELECT * FROM t ORDER BY val <-> '{1:3,2:3,3:3}/3';
|
||||||
|
val
|
||||||
|
-----------------
|
||||||
|
{1:1,2:2,3:3}/3
|
||||||
|
{1:1,2:2,3:4}/3
|
||||||
|
{1:1,2:1,3:1}/3
|
||||||
|
{}/3
|
||||||
|
(4 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::sparsevec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '{1:3,2:3,3:3}/3';
|
||||||
|
val
|
||||||
|
-----
|
||||||
|
(0 rows)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
|
-- TODO move
|
||||||
|
CREATE TABLE t (val sparsevec(1001));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(1, ARRAY[1001])::vector::sparsevec);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
ERROR: sparsevec cannot have more than 1000 non-zero elements for hnsw index
|
||||||
|
TRUNCATE t;
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(1, ARRAY[1001])::vector::sparsevec);
|
||||||
|
ERROR: sparsevec cannot have more than 1000 non-zero elements for hnsw index
|
||||||
|
DROP TABLE t;
|
||||||
26
test/expected/ivfflat_halfvec_cosine.out
Normal file
26
test/expected/ivfflat_halfvec_cosine.out
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
21
test/expected/ivfflat_halfvec_ip.out
Normal file
21
test/expected/ivfflat_halfvec_ip.out
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
36
test/expected/ivfflat_halfvec_l2.out
Normal file
36
test/expected/ivfflat_halfvec_l2.out
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) 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;
|
||||||
@@ -12,14 +12,11 @@ SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
|||||||
[0,0,0]
|
[0,0,0]
|
||||||
(4 rows)
|
(4 rows)
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
|
||||||
val
|
count
|
||||||
---------
|
-------
|
||||||
[0,0,0]
|
4
|
||||||
[1,1,1]
|
(1 row)
|
||||||
[1,2,3]
|
|
||||||
[1,2,4]
|
|
||||||
(4 rows)
|
|
||||||
|
|
||||||
SELECT COUNT(*) FROM t;
|
SELECT COUNT(*) FROM t;
|
||||||
count
|
count
|
||||||
86
test/expected/sparsevec_functions.out
Normal file
86
test/expected/sparsevec_functions.out
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
SELECT round(sparsevec_norm('{1:1,2:1}/2')::numeric, 5);
|
||||||
|
round
|
||||||
|
---------
|
||||||
|
1.41421
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT sparsevec_norm('{1:3,2:4}/2');
|
||||||
|
sparsevec_norm
|
||||||
|
----------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT sparsevec_norm('{2:1}/2');
|
||||||
|
sparsevec_norm
|
||||||
|
----------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT sparsevec_norm('{1:3e37,2:4e37}/2')::real;
|
||||||
|
sparsevec_norm
|
||||||
|
----------------
|
||||||
|
5e+37
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('{}/2'::sparsevec, '{1:3,2:4}/2');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('{}/2'::sparsevec, '{2:1}/2');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{}/2'::sparsevec <-> '{1:3,2:4}/2';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('{1:1,2:2}/2'::sparsevec, '{1:2,2:4}/2');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
10
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT sparsevec_negative_inner_product('{1:1,2:2}/2', '{1:2,2:4}/2');
|
||||||
|
sparsevec_negative_inner_product
|
||||||
|
----------------------------------
|
||||||
|
-10
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:1,2:2}/2'::sparsevec, '{1:2,2:4}/2');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:1,2:2}/2'::sparsevec, '{}/2');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
NaN
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:1,2:1}/2'::sparsevec, '{1:-1,2:-1}/2');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:2}/2'::sparsevec, '{2:2}/2');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{}/1'::sparsevec, '{}/1');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
NaN
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:2}/2'::sparsevec, '{1:1}/3');
|
||||||
|
ERROR: different sparsevec dimensions 2 and 3
|
||||||
215
test/expected/sparsevec_input.out
Normal file
215
test/expected/sparsevec_input.out
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
SELECT '{1:1.5,3:3.5}/5'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------------
|
||||||
|
{1:1.5,3:3.5}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:-2,3:-4}/5'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
---------------
|
||||||
|
{1:-2,3:-4}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:2.,3:4.}/5'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-------------
|
||||||
|
{1:2,3:4}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ' { 1 : 1.5 , 3 : 3.5 } / 5 '::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------------
|
||||||
|
{1:1.5,3:3.5}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:1.23456}/1'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
---------------
|
||||||
|
{1:1.23456}/1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:hello,2:1}/2'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1:hello,2:1}/2"
|
||||||
|
LINE 1: SELECT '{1:hello,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:NaN,2:1}/2'::sparsevec;
|
||||||
|
ERROR: NaN not allowed in sparsevec
|
||||||
|
LINE 1: SELECT '{1:NaN,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:Infinity,2:1}/2'::sparsevec;
|
||||||
|
ERROR: infinite value not allowed in sparsevec
|
||||||
|
LINE 1: SELECT '{1:Infinity,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:-Infinity,2:1}/2'::sparsevec;
|
||||||
|
ERROR: infinite value not allowed in sparsevec
|
||||||
|
LINE 1: SELECT '{1:-Infinity,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:1.5e38,2:-1.5e38}/2'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
--------------------------
|
||||||
|
{1:1.5e+38,2:-1.5e+38}/2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:1.5e+38,2:-1.5e+38}/2'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
--------------------------
|
||||||
|
{1:1.5e+38,2:-1.5e+38}/2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:1.5e-38,2:-1.5e-38}/2'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
--------------------------
|
||||||
|
{1:1.5e-38,2:-1.5e-38}/2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{1:4e38,2:1}/2'::sparsevec;
|
||||||
|
ERROR: "4e38" is out of range for type sparsevec
|
||||||
|
LINE 1: SELECT '{1:4e38,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:-4e38,2:1}/2'::sparsevec;
|
||||||
|
ERROR: "-4e38" is out of range for type sparsevec
|
||||||
|
LINE 1: SELECT '{1:-4e38,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:1e-46,2:1}/2'::sparsevec;
|
||||||
|
ERROR: "1e-46" is out of range for type sparsevec
|
||||||
|
LINE 1: SELECT '{1:1e-46,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:-1e-46,2:1}/2'::sparsevec;
|
||||||
|
ERROR: "-1e-46" is out of range for type sparsevec
|
||||||
|
LINE 1: SELECT '{1:-1e-46,2:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT ''::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: ""
|
||||||
|
LINE 1: SELECT ''::sparsevec;
|
||||||
|
^
|
||||||
|
DETAIL: Vector contents must start with "{".
|
||||||
|
SELECT '{'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{"
|
||||||
|
LINE 1: SELECT '{'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{ '::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{ "
|
||||||
|
LINE 1: SELECT '{ '::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{:'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{:"
|
||||||
|
LINE 1: SELECT '{:'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{,'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{,"
|
||||||
|
LINE 1: SELECT '{,'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{}'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{}"
|
||||||
|
LINE 1: SELECT '{}'::sparsevec;
|
||||||
|
^
|
||||||
|
DETAIL: Unexpected end of input.
|
||||||
|
SELECT '{}/'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{}/"
|
||||||
|
LINE 1: SELECT '{}/'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{}/1'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------
|
||||||
|
{}/1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{}/1a'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{}/1a"
|
||||||
|
LINE 1: SELECT '{}/1a'::sparsevec;
|
||||||
|
^
|
||||||
|
DETAIL: Junk after closing.
|
||||||
|
SELECT '{ }/1'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------
|
||||||
|
{}/1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{:}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{:}/1"
|
||||||
|
LINE 1: SELECT '{:}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{,}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{,}/1"
|
||||||
|
LINE 1: SELECT '{,}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1,}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1,}/1"
|
||||||
|
LINE 1: SELECT '{1,}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{:1}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{:1}/1"
|
||||||
|
LINE 1: SELECT '{:1}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1:}/1"
|
||||||
|
LINE 1: SELECT '{1:}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1a:1}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1a:1}/1"
|
||||||
|
LINE 1: SELECT '{1a:1}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:1a}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1:1a}/1"
|
||||||
|
LINE 1: SELECT '{1:1a}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:1,}/1'::sparsevec;
|
||||||
|
ERROR: invalid input syntax for type sparsevec: "{1:1,}/1"
|
||||||
|
LINE 1: SELECT '{1:1,}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{1:0,2:1,3:0}/3'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------
|
||||||
|
{2:1}/3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{2:1,1:1}/2'::sparsevec;
|
||||||
|
ERROR: indexes must be in ascending order
|
||||||
|
LINE 1: SELECT '{2:1,1:1}/2'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{}/5'::sparsevec;
|
||||||
|
sparsevec
|
||||||
|
-----------
|
||||||
|
{}/5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{}/-1'::sparsevec;
|
||||||
|
ERROR: sparsevec must have at least 1 dimension
|
||||||
|
LINE 1: SELECT '{}/-1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{}/100001'::sparsevec;
|
||||||
|
ERROR: sparsevec cannot have more than 100000 dimensions
|
||||||
|
LINE 1: SELECT '{}/100001'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{0:1}/1'::sparsevec;
|
||||||
|
ERROR: index "0" is out of range for type sparsevec
|
||||||
|
LINE 1: SELECT '{0:1}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{2:1}/1'::sparsevec;
|
||||||
|
ERROR: index must be less than or equal to dimensions
|
||||||
|
LINE 1: SELECT '{2:1}/1'::sparsevec;
|
||||||
|
^
|
||||||
|
SELECT '{}/3'::sparsevec(3);
|
||||||
|
sparsevec
|
||||||
|
-----------
|
||||||
|
{}/3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '{}/3'::sparsevec(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '{}/3'::sparsevec(3, 2);
|
||||||
|
ERROR: invalid type modifier
|
||||||
|
LINE 1: SELECT '{}/3'::sparsevec(3, 2);
|
||||||
|
^
|
||||||
|
SELECT '{}/3'::sparsevec('a');
|
||||||
|
ERROR: invalid input syntax for type integer: "a"
|
||||||
|
LINE 1: SELECT '{}/3'::sparsevec('a');
|
||||||
|
^
|
||||||
|
SELECT '{}/3'::sparsevec(0);
|
||||||
|
ERROR: dimensions for type sparsevec must be at least 1
|
||||||
|
LINE 1: SELECT '{}/3'::sparsevec(0);
|
||||||
|
^
|
||||||
|
SELECT '{}/3'::sparsevec(100001);
|
||||||
|
ERROR: dimensions for type sparsevec cannot exceed 100000
|
||||||
|
LINE 1: SELECT '{}/3'::sparsevec(100001);
|
||||||
|
^
|
||||||
@@ -24,14 +24,6 @@ SELECT '[1e37]'::vector * '[1e37]';
|
|||||||
ERROR: value out of range: overflow
|
ERROR: value out of range: overflow
|
||||||
SELECT '[1e-37]'::vector * '[1e-37]';
|
SELECT '[1e-37]'::vector * '[1e-37]';
|
||||||
ERROR: value out of range: underflow
|
ERROR: value out of range: underflow
|
||||||
SELECT '[1,2,3]'::vector || '[4,5]'::vector;
|
|
||||||
?column?
|
|
||||||
-------------
|
|
||||||
[1,2,3,4,5]
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT array_fill(0, ARRAY[16000])::vector || '[1]'::vector;
|
|
||||||
ERROR: vector cannot have more than 16000 dimensions
|
|
||||||
SELECT '[1,2,3]'::vector < '[1,2,3]';
|
SELECT '[1,2,3]'::vector < '[1,2,3]';
|
||||||
?column?
|
?column?
|
||||||
----------
|
----------
|
||||||
@@ -280,47 +272,47 @@ SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
|||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT quantize_binary('[1,0,-1]');
|
SELECT quantize_binary('[1,0,-1]'::vector);
|
||||||
quantize_binary
|
quantize_binary
|
||||||
-----------------
|
-----------------
|
||||||
100
|
100
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]');
|
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]'::vector);
|
||||||
quantize_binary
|
quantize_binary
|
||||||
-----------------
|
-----------------
|
||||||
01001110101
|
01001110101
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', 1, 3);
|
SELECT subvector('[1,2,3,4,5]'::vector, 1, 3);
|
||||||
subvector
|
subvector
|
||||||
-----------
|
-----------
|
||||||
[1,2,3]
|
[1,2,3]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, 2);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, 2);
|
||||||
subvector
|
subvector
|
||||||
-----------
|
-----------
|
||||||
[3,4]
|
[3,4]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', -1, 3);
|
SELECT subvector('[1,2,3,4,5]'::vector, -1, 3);
|
||||||
subvector
|
subvector
|
||||||
-----------
|
-----------
|
||||||
[1]
|
[1]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, 9);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, 9);
|
||||||
subvector
|
subvector
|
||||||
-----------
|
-----------
|
||||||
[3,4,5]
|
[3,4,5]
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', 1, 0);
|
SELECT subvector('[1,2,3,4,5]'::vector, 1, 0);
|
||||||
ERROR: vector must have at least 1 dimension
|
ERROR: vector must have at least 1 dimension
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, -1);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, -1);
|
||||||
ERROR: vector must have at least 1 dimension
|
ERROR: vector must have at least 1 dimension
|
||||||
SELECT subvector('[1,2,3,4,5]', -1, 2);
|
SELECT subvector('[1,2,3,4,5]'::vector, -1, 2);
|
||||||
ERROR: vector must have at least 1 dimension
|
ERROR: vector must have at least 1 dimension
|
||||||
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
|
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
|
||||||
avg
|
avg
|
||||||
|
|||||||
@@ -63,11 +63,11 @@ SELECT '[1.5e-38,-1.5e-38]'::vector;
|
|||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT '[4e38,1]'::vector;
|
SELECT '[4e38,1]'::vector;
|
||||||
ERROR: infinite value not allowed in vector
|
ERROR: "4e38" is out of range for type vector
|
||||||
LINE 1: SELECT '[4e38,1]'::vector;
|
LINE 1: SELECT '[4e38,1]'::vector;
|
||||||
^
|
^
|
||||||
SELECT '[-4e38,1]'::vector;
|
SELECT '[-4e38,1]'::vector;
|
||||||
ERROR: infinite value not allowed in vector
|
ERROR: "-4e38" is out of range for type vector
|
||||||
LINE 1: SELECT '[-4e38,1]'::vector;
|
LINE 1: SELECT '[-4e38,1]'::vector;
|
||||||
^
|
^
|
||||||
SELECT '[1e-46,1]'::vector;
|
SELECT '[1e-46,1]'::vector;
|
||||||
@@ -83,39 +83,48 @@ SELECT '[-1e-46,1]'::vector;
|
|||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT '[1,2,3'::vector;
|
SELECT '[1,2,3'::vector;
|
||||||
ERROR: malformed vector literal: "[1,2,3"
|
ERROR: invalid input syntax for type vector: "[1,2,3"
|
||||||
LINE 1: SELECT '[1,2,3'::vector;
|
LINE 1: SELECT '[1,2,3'::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Unexpected end of input.
|
|
||||||
SELECT '[1,2,3]9'::vector;
|
SELECT '[1,2,3]9'::vector;
|
||||||
ERROR: malformed vector literal: "[1,2,3]9"
|
ERROR: invalid input syntax for type vector: "[1,2,3]9"
|
||||||
LINE 1: SELECT '[1,2,3]9'::vector;
|
LINE 1: SELECT '[1,2,3]9'::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Junk after closing right brace.
|
DETAIL: Junk after closing right brace.
|
||||||
SELECT '1,2,3'::vector;
|
SELECT '1,2,3'::vector;
|
||||||
ERROR: malformed vector literal: "1,2,3"
|
ERROR: invalid input syntax for type vector: "1,2,3"
|
||||||
LINE 1: SELECT '1,2,3'::vector;
|
LINE 1: SELECT '1,2,3'::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Vector contents must start with "[".
|
DETAIL: Vector contents must start with "[".
|
||||||
SELECT ''::vector;
|
SELECT ''::vector;
|
||||||
ERROR: malformed vector literal: ""
|
ERROR: invalid input syntax for type vector: ""
|
||||||
LINE 1: SELECT ''::vector;
|
LINE 1: SELECT ''::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Vector contents must start with "[".
|
DETAIL: Vector contents must start with "[".
|
||||||
SELECT '['::vector;
|
SELECT '['::vector;
|
||||||
ERROR: malformed vector literal: "["
|
ERROR: invalid input syntax for type vector: "["
|
||||||
|
LINE 1: SELECT '['::vector;
|
||||||
|
^
|
||||||
|
SELECT '[ '::vector;
|
||||||
|
ERROR: invalid input syntax for type vector: "[ "
|
||||||
LINE 1: SELECT '[ '::vector;
|
LINE 1: SELECT '[ '::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Unexpected end of input.
|
|
||||||
SELECT '[,'::vector;
|
SELECT '[,'::vector;
|
||||||
ERROR: malformed vector literal: "[,"
|
ERROR: invalid input syntax for type vector: "[,"
|
||||||
LINE 1: SELECT '[,'::vector;
|
LINE 1: SELECT '[,'::vector;
|
||||||
^
|
^
|
||||||
DETAIL: Unexpected end of input.
|
|
||||||
SELECT '[]'::vector;
|
SELECT '[]'::vector;
|
||||||
ERROR: vector must have at least 1 dimension
|
ERROR: vector must have at least 1 dimension
|
||||||
LINE 1: SELECT '[]'::vector;
|
LINE 1: SELECT '[]'::vector;
|
||||||
^
|
^
|
||||||
|
SELECT '[ ]'::vector;
|
||||||
|
ERROR: vector must have at least 1 dimension
|
||||||
|
LINE 1: SELECT '[ ]'::vector;
|
||||||
|
^
|
||||||
|
SELECT '[,]'::vector;
|
||||||
|
ERROR: invalid input syntax for type vector: "[,]"
|
||||||
|
LINE 1: SELECT '[,]'::vector;
|
||||||
|
^
|
||||||
SELECT '[1,]'::vector;
|
SELECT '[1,]'::vector;
|
||||||
ERROR: invalid input syntax for type vector: "[1,]"
|
ERROR: invalid input syntax for type vector: "[1,]"
|
||||||
LINE 1: SELECT '[1,]'::vector;
|
LINE 1: SELECT '[1,]'::vector;
|
||||||
@@ -125,7 +134,7 @@ ERROR: invalid input syntax for type vector: "[1a]"
|
|||||||
LINE 1: SELECT '[1a]'::vector;
|
LINE 1: SELECT '[1a]'::vector;
|
||||||
^
|
^
|
||||||
SELECT '[1,,3]'::vector;
|
SELECT '[1,,3]'::vector;
|
||||||
ERROR: malformed vector literal: "[1,,3]"
|
ERROR: invalid input syntax for type vector: "[1,,3]"
|
||||||
LINE 1: SELECT '[1,,3]'::vector;
|
LINE 1: SELECT '[1,,3]'::vector;
|
||||||
^
|
^
|
||||||
SELECT '[1, ,3]'::vector;
|
SELECT '[1, ,3]'::vector;
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
SELECT hamming_distance(B'111', B'111');
|
SELECT hamming_distance('111', '111');
|
||||||
SELECT hamming_distance(B'111', B'110');
|
SELECT hamming_distance('111', '110');
|
||||||
SELECT hamming_distance(B'111', B'100');
|
SELECT hamming_distance('111', '100');
|
||||||
SELECT hamming_distance(B'111', B'000');
|
SELECT hamming_distance('111', '000');
|
||||||
SELECT hamming_distance(B'111', B'00');
|
SELECT hamming_distance('10101010101010101010', '01010101010101010101');
|
||||||
|
SELECT hamming_distance('', '');
|
||||||
|
SELECT hamming_distance('111', '00');
|
||||||
|
SELECT hamming_distance('111', '000'::varbit(4));
|
||||||
|
SELECT hamming_distance('111', '0000'::varbit(4));
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1111');
|
SELECT jaccard_distance('1111', '1111');
|
||||||
SELECT jaccard_distance(B'1111', B'1110');
|
SELECT jaccard_distance('1111', '1110');
|
||||||
SELECT jaccard_distance(B'1111', B'1100');
|
SELECT jaccard_distance('1111', '1100');
|
||||||
SELECT jaccard_distance(B'1111', B'1000');
|
SELECT jaccard_distance('1111', '1000');
|
||||||
SELECT jaccard_distance(B'1111', B'0000');
|
SELECT jaccard_distance('1111', '0000');
|
||||||
SELECT jaccard_distance(B'1100', B'1000');
|
SELECT jaccard_distance('1100', '1000');
|
||||||
SELECT jaccard_distance(B'1111', B'000');
|
SELECT jaccard_distance('10101010101010101010', '01010101010101010101');
|
||||||
|
SELECT jaccard_distance('', '');
|
||||||
|
SELECT jaccard_distance('1111', '000');
|
||||||
|
SELECT jaccard_distance('1111', '0000'::varbit(5));
|
||||||
|
SELECT jaccard_distance('1111', '00000'::varbit(5));
|
||||||
|
|||||||
@@ -3,13 +3,50 @@ SELECT ARRAY[1.0,2.0,3.0]::vector;
|
|||||||
SELECT ARRAY[1,2,3]::float4[]::vector;
|
SELECT ARRAY[1,2,3]::float4[]::vector;
|
||||||
SELECT ARRAY[1,2,3]::float8[]::vector;
|
SELECT ARRAY[1,2,3]::float8[]::vector;
|
||||||
SELECT ARRAY[1,2,3]::numeric[]::vector;
|
SELECT ARRAY[1,2,3]::numeric[]::vector;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::real[];
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::vector;
|
||||||
|
SELECT '{1,2,3}'::real[]::vector(3);
|
||||||
|
SELECT '{1,2,3}'::real[]::vector(2);
|
||||||
SELECT '{NULL}'::real[]::vector;
|
SELECT '{NULL}'::real[]::vector;
|
||||||
SELECT '{NaN}'::real[]::vector;
|
SELECT '{NaN}'::real[]::vector;
|
||||||
SELECT '{Infinity}'::real[]::vector;
|
SELECT '{Infinity}'::real[]::vector;
|
||||||
SELECT '{-Infinity}'::real[]::vector;
|
SELECT '{-Infinity}'::real[]::vector;
|
||||||
SELECT '{}'::real[]::vector;
|
SELECT '{}'::real[]::vector;
|
||||||
SELECT '{{1}}'::real[]::vector;
|
SELECT '{{1}}'::real[]::vector;
|
||||||
SELECT '[1,2,3]'::vector::real[];
|
|
||||||
|
SELECT '{1,2,3}'::double precision[]::vector;
|
||||||
|
SELECT '{1,2,3}'::double precision[]::vector(3);
|
||||||
|
SELECT '{1,2,3}'::double precision[]::vector(2);
|
||||||
|
SELECT '{4e38,-4e38}'::double precision[]::vector;
|
||||||
|
SELECT '{1e-46,-1e-46}'::double precision[]::vector;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec;
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec(3);
|
||||||
|
SELECT '[1,2,3]'::vector::halfvec(2);
|
||||||
|
SELECT '[65520]'::vector::halfvec;
|
||||||
|
SELECT '[1e-8]'::vector::halfvec;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector;
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector(3);
|
||||||
|
SELECT '[1,2,3]'::halfvec::vector(2);
|
||||||
|
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec;
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec(3);
|
||||||
|
SELECT '{1,2,3}'::real[]::halfvec(2);
|
||||||
|
SELECT '{65520,-65520}'::real[]::halfvec;
|
||||||
|
SELECT '{1e-8,-1e-8}'::real[]::halfvec;
|
||||||
|
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec;
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec(5);
|
||||||
|
SELECT '[0,1.5,0,3.5,0]'::vector::sparsevec(4);
|
||||||
|
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector;
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector(5);
|
||||||
|
SELECT '{2:1.5,4:3.5}/5'::sparsevec::vector(4);
|
||||||
|
SELECT '{}/16001'::sparsevec::vector;
|
||||||
|
|
||||||
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
|
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_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
CREATE TABLE t (val vector(3));
|
CREATE TABLE t (val vector(3), val2 halfvec(3), val3 sparsevec(3));
|
||||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
INSERT INTO t (val, val2, val3) VALUES ('[0,0,0]', '[0,0,0]', '{}/3'), ('[1,2,3]', '[1,2,3]', '{1:1,2:2,3:3}/3'), ('[1,1,1]', '[1,1,1]', '{1:1,2:1,3:1}/3'), (NULL, NULL, NULL);
|
||||||
|
|
||||||
CREATE TABLE t2 (val vector(3));
|
CREATE TABLE t2 (val vector(3), val2 halfvec(3), val3 sparsevec(3));
|
||||||
|
|
||||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||||
|
|||||||
40
test/sql/halfvec_functions.sql
Normal file
40
test/sql/halfvec_functions.sql
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
SELECT round(halfvec_norm('[1,1]')::numeric, 5);
|
||||||
|
SELECT halfvec_norm('[3,4]');
|
||||||
|
SELECT halfvec_norm('[0,1]');
|
||||||
|
|
||||||
|
SELECT l2_distance('[0,0]'::halfvec, '[3,4]');
|
||||||
|
SELECT l2_distance('[0,0]'::halfvec, '[0,1]');
|
||||||
|
SELECT l2_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
SELECT l2_distance('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,1,1,1,1,1,1,4,5]');
|
||||||
|
SELECT '[0,0]'::halfvec <-> '[3,4]';
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::halfvec, '[3,4]');
|
||||||
|
SELECT inner_product('[1,2]'::halfvec, '[3]');
|
||||||
|
SELECT inner_product('[65504]'::halfvec, '[65504]');
|
||||||
|
SELECT inner_product('[1,1,1,1,1,1,1,1,1]'::halfvec, '[1,2,3,4,5,6,7,8,9]');
|
||||||
|
SELECT '[1,2]'::halfvec <#> '[3,4]';
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[2,4]');
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[0,0]');
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[1,1]');
|
||||||
|
SELECT cosine_distance('[1,0]'::halfvec, '[0,2]');
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[-1,-1]');
|
||||||
|
SELECT cosine_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[1.1,1.1]');
|
||||||
|
SELECT cosine_distance('[1,1]'::halfvec, '[-1.1,-1.1]');
|
||||||
|
SELECT '[1,2]'::halfvec <=> '[2,4]';
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::halfvec, '[3,4]');
|
||||||
|
SELECT l1_distance('[0,0]'::halfvec, '[0,1]');
|
||||||
|
SELECT l1_distance('[1,2]'::halfvec, '[3]');
|
||||||
|
|
||||||
|
SELECT quantize_binary('[1,0,-1]'::halfvec);
|
||||||
|
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]'::halfvec);
|
||||||
|
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 1, 3);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, 2);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, -1, 3);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, 9);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 1, 0);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, 3, -1);
|
||||||
|
SELECT subvector('[1,2,3,4,5]'::halfvec, -1, 2);
|
||||||
38
test/sql/halfvec_input.sql
Normal file
38
test/sql/halfvec_input.sql
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
SELECT '[1,2,3]'::halfvec;
|
||||||
|
SELECT '[-1,-2,-3]'::halfvec;
|
||||||
|
SELECT '[1.,2.,3.]'::halfvec;
|
||||||
|
SELECT ' [ 1, 2 , 3 ] '::halfvec;
|
||||||
|
SELECT '[1.23456]'::halfvec;
|
||||||
|
SELECT '[hello,1]'::halfvec;
|
||||||
|
SELECT '[NaN,1]'::halfvec;
|
||||||
|
SELECT '[Infinity,1]'::halfvec;
|
||||||
|
SELECT '[-Infinity,1]'::halfvec;
|
||||||
|
SELECT '[65519,-65519]'::halfvec;
|
||||||
|
SELECT '[65520,-65520]'::halfvec;
|
||||||
|
SELECT '[1e-8,-1e-8]'::halfvec;
|
||||||
|
SELECT '[4e38,1]'::halfvec;
|
||||||
|
SELECT '[1e-46,1]'::halfvec;
|
||||||
|
SELECT '[1,2,3'::halfvec;
|
||||||
|
SELECT '[1,2,3]9'::halfvec;
|
||||||
|
SELECT '1,2,3'::halfvec;
|
||||||
|
SELECT ''::halfvec;
|
||||||
|
SELECT '['::halfvec;
|
||||||
|
SELECT '[ '::halfvec;
|
||||||
|
SELECT '[,'::halfvec;
|
||||||
|
SELECT '[]'::halfvec;
|
||||||
|
SELECT '[ ]'::halfvec;
|
||||||
|
SELECT '[,]'::halfvec;
|
||||||
|
SELECT '[1,]'::halfvec;
|
||||||
|
SELECT '[1a]'::halfvec;
|
||||||
|
SELECT '[1,,3]'::halfvec;
|
||||||
|
SELECT '[1, ,3]'::halfvec;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::halfvec(3);
|
||||||
|
SELECT '[1,2,3]'::halfvec(2);
|
||||||
|
SELECT '[1,2,3]'::halfvec(3, 2);
|
||||||
|
SELECT '[1,2,3]'::halfvec('a');
|
||||||
|
SELECT '[1,2,3]'::halfvec(0);
|
||||||
|
SELECT '[1,2,3]'::halfvec(16001);
|
||||||
|
|
||||||
|
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::halfvec[]);
|
||||||
|
SELECT '{"[1,2,3]"}'::halfvec(2)[];
|
||||||
@@ -10,3 +10,10 @@ SELECT * FROM t ORDER BY val <~> B'111';
|
|||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <~> (SELECT NULL::bit)) t2;
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <~> (SELECT NULL::bit)) t2;
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- TODO move
|
||||||
|
CREATE TABLE t (val varbit(3));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
CREATE INDEX ON t USING hnsw ((val::bit(3)) bit_hamming_ops);
|
||||||
|
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
13
test/sql/hnsw_halfvec_cosine.sql
Normal file
13
test/sql/hnsw_halfvec_cosine.sql
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
12
test/sql/hnsw_halfvec_ip.sql
Normal file
12
test/sql/hnsw_halfvec_ip.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
16
test/sql/hnsw_halfvec_l2.sql
Normal file
16
test/sql/hnsw_halfvec_l2.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_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::halfvec)) t2;
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
13
test/sql/hnsw_sparsevec_cosine.sql
Normal file
13
test/sql/hnsw_sparsevec_cosine.sql
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_cosine_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <=> '{1:3,2:3,3:3}/3';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '{}/3') t2;
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::sparsevec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
12
test/sql/hnsw_sparsevec_ip.sql
Normal file
12
test/sql/hnsw_sparsevec_ip.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_ip_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <#> '{1:3,2:3,3:3}/3';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::sparsevec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
25
test/sql/hnsw_sparsevec_l2.sql
Normal file
25
test/sql/hnsw_sparsevec_l2.sql
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val sparsevec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('{}/3'), ('{1:1,2:2,3:3}/3'), ('{1:1,2:1,3:1}/3'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('{1:1,2:2,3:4}/3');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <-> '{1:3,2:3,3:3}/3';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::sparsevec)) t2;
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '{1:3,2:3,3:3}/3';
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- TODO move
|
||||||
|
CREATE TABLE t (val sparsevec(1001));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(1, ARRAY[1001])::vector::sparsevec);
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
TRUNCATE t;
|
||||||
|
CREATE INDEX ON t USING hnsw (val sparsevec_l2_ops);
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(1, ARRAY[1001])::vector::sparsevec);
|
||||||
|
DROP TABLE t;
|
||||||
13
test/sql/ivfflat_halfvec_cosine.sql
Normal file
13
test/sql/ivfflat_halfvec_cosine.sql
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
12
test/sql/ivfflat_halfvec_ip.sql
Normal file
12
test/sql/ivfflat_halfvec_ip.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
16
test/sql/ivfflat_halfvec_l2.sql
Normal file
16
test/sql/ivfflat_halfvec_l2.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_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::halfvec)) t2;
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
@@ -7,7 +7,7 @@ CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 1);
|
|||||||
INSERT INTO t (val) VALUES ('[1,2,4]');
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
|
||||||
SELECT COUNT(*) FROM t;
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
TRUNCATE t;
|
TRUNCATE t;
|
||||||
18
test/sql/sparsevec_functions.sql
Normal file
18
test/sql/sparsevec_functions.sql
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
SELECT round(sparsevec_norm('{1:1,2:1}/2')::numeric, 5);
|
||||||
|
SELECT sparsevec_norm('{1:3,2:4}/2');
|
||||||
|
SELECT sparsevec_norm('{2:1}/2');
|
||||||
|
SELECT sparsevec_norm('{1:3e37,2:4e37}/2')::real;
|
||||||
|
|
||||||
|
SELECT l2_distance('{}/2'::sparsevec, '{1:3,2:4}/2');
|
||||||
|
SELECT l2_distance('{}/2'::sparsevec, '{2:1}/2');
|
||||||
|
SELECT '{}/2'::sparsevec <-> '{1:3,2:4}/2';
|
||||||
|
|
||||||
|
SELECT inner_product('{1:1,2:2}/2'::sparsevec, '{1:2,2:4}/2');
|
||||||
|
SELECT sparsevec_negative_inner_product('{1:1,2:2}/2', '{1:2,2:4}/2');
|
||||||
|
|
||||||
|
SELECT cosine_distance('{1:1,2:2}/2'::sparsevec, '{1:2,2:4}/2');
|
||||||
|
SELECT cosine_distance('{1:1,2:2}/2'::sparsevec, '{}/2');
|
||||||
|
SELECT cosine_distance('{1:1,2:1}/2'::sparsevec, '{1:-1,2:-1}/2');
|
||||||
|
SELECT cosine_distance('{1:2}/2'::sparsevec, '{2:2}/2');
|
||||||
|
SELECT cosine_distance('{}/1'::sparsevec, '{}/1');
|
||||||
|
SELECT cosine_distance('{1:2}/2'::sparsevec, '{1:1}/3');
|
||||||
48
test/sql/sparsevec_input.sql
Normal file
48
test/sql/sparsevec_input.sql
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
SELECT '{1:1.5,3:3.5}/5'::sparsevec;
|
||||||
|
SELECT '{1:-2,3:-4}/5'::sparsevec;
|
||||||
|
SELECT '{1:2.,3:4.}/5'::sparsevec;
|
||||||
|
SELECT ' { 1 : 1.5 , 3 : 3.5 } / 5 '::sparsevec;
|
||||||
|
SELECT '{1:1.23456}/1'::sparsevec;
|
||||||
|
SELECT '{1:hello,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:NaN,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:Infinity,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:-Infinity,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:1.5e38,2:-1.5e38}/2'::sparsevec;
|
||||||
|
SELECT '{1:1.5e+38,2:-1.5e+38}/2'::sparsevec;
|
||||||
|
SELECT '{1:1.5e-38,2:-1.5e-38}/2'::sparsevec;
|
||||||
|
SELECT '{1:4e38,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:-4e38,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:1e-46,2:1}/2'::sparsevec;
|
||||||
|
SELECT '{1:-1e-46,2:1}/2'::sparsevec;
|
||||||
|
SELECT ''::sparsevec;
|
||||||
|
SELECT '{'::sparsevec;
|
||||||
|
SELECT '{ '::sparsevec;
|
||||||
|
SELECT '{:'::sparsevec;
|
||||||
|
SELECT '{,'::sparsevec;
|
||||||
|
SELECT '{}'::sparsevec;
|
||||||
|
SELECT '{}/'::sparsevec;
|
||||||
|
SELECT '{}/1'::sparsevec;
|
||||||
|
SELECT '{}/1a'::sparsevec;
|
||||||
|
SELECT '{ }/1'::sparsevec;
|
||||||
|
SELECT '{:}/1'::sparsevec;
|
||||||
|
SELECT '{,}/1'::sparsevec;
|
||||||
|
SELECT '{1,}/1'::sparsevec;
|
||||||
|
SELECT '{:1}/1'::sparsevec;
|
||||||
|
SELECT '{1:}/1'::sparsevec;
|
||||||
|
SELECT '{1a:1}/1'::sparsevec;
|
||||||
|
SELECT '{1:1a}/1'::sparsevec;
|
||||||
|
SELECT '{1:1,}/1'::sparsevec;
|
||||||
|
SELECT '{1:0,2:1,3:0}/3'::sparsevec;
|
||||||
|
SELECT '{2:1,1:1}/2'::sparsevec;
|
||||||
|
SELECT '{}/5'::sparsevec;
|
||||||
|
SELECT '{}/-1'::sparsevec;
|
||||||
|
SELECT '{}/100001'::sparsevec;
|
||||||
|
SELECT '{0:1}/1'::sparsevec;
|
||||||
|
SELECT '{2:1}/1'::sparsevec;
|
||||||
|
|
||||||
|
SELECT '{}/3'::sparsevec(3);
|
||||||
|
SELECT '{}/3'::sparsevec(2);
|
||||||
|
SELECT '{}/3'::sparsevec(3, 2);
|
||||||
|
SELECT '{}/3'::sparsevec('a');
|
||||||
|
SELECT '{}/3'::sparsevec(0);
|
||||||
|
SELECT '{}/3'::sparsevec(100001);
|
||||||
@@ -6,9 +6,6 @@ SELECT '[1,2,3]'::vector * '[4,5,6]';
|
|||||||
SELECT '[1e37]'::vector * '[1e37]';
|
SELECT '[1e37]'::vector * '[1e37]';
|
||||||
SELECT '[1e-37]'::vector * '[1e-37]';
|
SELECT '[1e-37]'::vector * '[1e-37]';
|
||||||
|
|
||||||
SELECT '[1,2,3]'::vector || '[4,5]'::vector;
|
|
||||||
SELECT array_fill(0, ARRAY[16000])::vector || '[1]'::vector;
|
|
||||||
|
|
||||||
SELECT '[1,2,3]'::vector < '[1,2,3]';
|
SELECT '[1,2,3]'::vector < '[1,2,3]';
|
||||||
SELECT '[1,2,3]'::vector < '[1,2]';
|
SELECT '[1,2,3]'::vector < '[1,2]';
|
||||||
SELECT '[1,2,3]'::vector <= '[1,2,3]';
|
SELECT '[1,2,3]'::vector <= '[1,2,3]';
|
||||||
@@ -61,16 +58,16 @@ SELECT l1_distance('[0,0]'::vector, '[0,1]');
|
|||||||
SELECT l1_distance('[1,2]'::vector, '[3]');
|
SELECT l1_distance('[1,2]'::vector, '[3]');
|
||||||
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
||||||
|
|
||||||
SELECT quantize_binary('[1,0,-1]');
|
SELECT quantize_binary('[1,0,-1]'::vector);
|
||||||
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]');
|
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]'::vector);
|
||||||
|
|
||||||
SELECT subvector('[1,2,3,4,5]', 1, 3);
|
SELECT subvector('[1,2,3,4,5]'::vector, 1, 3);
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, 2);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, 2);
|
||||||
SELECT subvector('[1,2,3,4,5]', -1, 3);
|
SELECT subvector('[1,2,3,4,5]'::vector, -1, 3);
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, 9);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, 9);
|
||||||
SELECT subvector('[1,2,3,4,5]', 1, 0);
|
SELECT subvector('[1,2,3,4,5]'::vector, 1, 0);
|
||||||
SELECT subvector('[1,2,3,4,5]', 3, -1);
|
SELECT subvector('[1,2,3,4,5]'::vector, 3, -1);
|
||||||
SELECT subvector('[1,2,3,4,5]', -1, 2);
|
SELECT subvector('[1,2,3,4,5]'::vector, -1, 2);
|
||||||
|
|
||||||
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
|
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
|
||||||
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
|
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
|
||||||
|
|||||||
@@ -19,8 +19,11 @@ SELECT '[1,2,3]9'::vector;
|
|||||||
SELECT '1,2,3'::vector;
|
SELECT '1,2,3'::vector;
|
||||||
SELECT ''::vector;
|
SELECT ''::vector;
|
||||||
SELECT '['::vector;
|
SELECT '['::vector;
|
||||||
|
SELECT '[ '::vector;
|
||||||
SELECT '[,'::vector;
|
SELECT '[,'::vector;
|
||||||
SELECT '[]'::vector;
|
SELECT '[]'::vector;
|
||||||
|
SELECT '[ ]'::vector;
|
||||||
|
SELECT '[,]'::vector;
|
||||||
SELECT '[1,]'::vector;
|
SELECT '[1,]'::vector;
|
||||||
SELECT '[1a]'::vector;
|
SELECT '[1a]'::vector;
|
||||||
SELECT '[1,,3]'::vector;
|
SELECT '[1,,3]'::vector;
|
||||||
|
|||||||
@@ -30,18 +30,19 @@ sub test_recall
|
|||||||
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
));
|
));
|
||||||
my @actual_ids = split("\n", $actual);
|
my @actual_ids = split("\n", $actual);
|
||||||
my %actual_set = map { $_ => 1 } @actual_ids;
|
|
||||||
|
|
||||||
my @expected_ids = split("\n", $expected[$i]);
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
my %expected_set = map { $_ => 1 } @expected_ids;
|
||||||
|
|
||||||
foreach (@expected_ids)
|
foreach (@actual_ids)
|
||||||
{
|
{
|
||||||
if (exists($actual_set{$_}))
|
if (exists($expected_set{$_}))
|
||||||
{
|
{
|
||||||
$correct++;
|
$correct++;
|
||||||
}
|
}
|
||||||
$total++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$total += $limit;
|
||||||
}
|
}
|
||||||
|
|
||||||
cmp_ok($correct / $total, ">=", $min, $operator);
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
@@ -81,7 +82,12 @@ for my $i (0 .. $#operators)
|
|||||||
@expected = ();
|
@expected = ();
|
||||||
foreach (@queries)
|
foreach (@queries)
|
||||||
{
|
{
|
||||||
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
WITH top AS (
|
||||||
|
SELECT v $operator '$_' AS distance FROM tst ORDER BY distance LIMIT $limit
|
||||||
|
)
|
||||||
|
SELECT i FROM tst WHERE (v $operator '$_') <= (SELECT MAX(distance) FROM top)
|
||||||
|
));
|
||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,8 +104,16 @@ for my $i (0 .. $#operators)
|
|||||||
test_recall(1, 0.71, $operator);
|
test_recall(1, 0.71, $operator);
|
||||||
test_recall(10, 0.95, $operator);
|
test_recall(10, 0.95, $operator);
|
||||||
}
|
}
|
||||||
# Account for equal distances
|
|
||||||
|
# Test probes equals lists
|
||||||
|
if ($operator eq "<=>")
|
||||||
|
{
|
||||||
test_recall(100, 0.9925, $operator);
|
test_recall(100, 0.9925, $operator);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
test_recall(100, 1.00, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
@@ -119,8 +133,16 @@ for my $i (0 .. $#operators)
|
|||||||
test_recall(1, 0.71, $operator);
|
test_recall(1, 0.71, $operator);
|
||||||
test_recall(10, 0.95, $operator);
|
test_recall(10, 0.95, $operator);
|
||||||
}
|
}
|
||||||
# Account for equal distances
|
|
||||||
|
# Test probes equals lists
|
||||||
|
if ($operator eq "<=>")
|
||||||
|
{
|
||||||
test_recall(100, 0.9925, $operator);
|
test_recall(100, 0.9925, $operator);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
test_recall(100, 1.00, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ for my $i (0 .. $#operators)
|
|||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
test_recall($min, $operator);
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ foreach (@queries)
|
|||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
test_recall(0.19, $limit, "before vacuum");
|
test_recall(0.18, $limit, "before vacuum");
|
||||||
test_recall(0.95, 100, "before vacuum");
|
test_recall(0.95, 100, "before vacuum");
|
||||||
|
|
||||||
# TODO Test concurrent inserts with vacuum
|
# TODO Test concurrent inserts with vacuum
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ for my $i (0 .. $#operators)
|
|||||||
# Handle ties
|
# Handle ties
|
||||||
my $res = $node->safe_psql("postgres", qq(
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
WITH top AS (
|
WITH top AS (
|
||||||
SELECT v $operator $_ AS distance FROM tst ORDER BY v $operator $_ LIMIT $limit
|
SELECT v $operator $_ AS distance FROM tst ORDER BY distance LIMIT $limit
|
||||||
)
|
)
|
||||||
SELECT i FROM tst WHERE (v $operator $_) <= (SELECT MAX(distance) FROM top)
|
SELECT i FROM tst WHERE (v $operator $_) <= (SELECT MAX(distance) FROM top)
|
||||||
));
|
));
|
||||||
@@ -99,7 +99,7 @@ for my $i (0 .. $#operators)
|
|||||||
));
|
));
|
||||||
|
|
||||||
# Test approximate results
|
# Test approximate results
|
||||||
my $min = $operator eq "<\%>" ? 0.96 : 0.98;
|
my $min = $operator eq "<\%>" ? 0.95 : 0.98;
|
||||||
test_recall($min, $operator);
|
test_recall($min, $operator);
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|||||||
132
test/t/021_hnsw_halfvec_build_recall.pl
Normal file
132
test/t/021_hnsw_halfvec_build_recall.pl
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
my $dim = 10;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v halfvec($dim));");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my @r = ();
|
||||||
|
for (1 .. $dim)
|
||||||
|
{
|
||||||
|
push(@r, rand());
|
||||||
|
}
|
||||||
|
push(@queries, "[" . join(",", @r) . "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
|
my @opclasses = ("halfvec_l2_ops", "halfvec_ip_ops", "halfvec_cosine_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build index serially
|
||||||
|
$node->safe_psql("postgres", qq(
|
||||||
|
SET max_parallel_maintenance_workers = 0;
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
));
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
my $min = $operator eq "<#>" ? 0.93 : 0.98;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
|
# Build index in parallel in memory
|
||||||
|
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
|
SET client_min_messages = DEBUG;
|
||||||
|
SET min_parallel_table_scan_size = 1;
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
));
|
||||||
|
is($ret, 0, $stderr);
|
||||||
|
like($stderr, qr/using \d+ parallel workers/);
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
|
# Build index in parallel on disk
|
||||||
|
# Set parallel_workers on table to use workers with low maintenance_work_mem
|
||||||
|
($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
|
ALTER TABLE tst SET (parallel_workers = 2);
|
||||||
|
SET client_min_messages = DEBUG;
|
||||||
|
SET maintenance_work_mem = '4MB';
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
ALTER TABLE tst RESET (parallel_workers);
|
||||||
|
));
|
||||||
|
is($ret, 0, $stderr);
|
||||||
|
like($stderr, qr/using \d+ parallel workers/);
|
||||||
|
like($stderr, qr/hnsw graph no longer fits into maintenance_work_mem/);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
128
test/t/022_hnsw_sparsevec_build_recall.pl
Normal file
128
test/t/022_hnsw_sparsevec_build_recall.pl
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v sparsevec(3));");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()]::vector::sparsevec FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "{1:$r1,2:$r2,3:$r3}/3");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
|
my @opclasses = ("sparsevec_l2_ops", "sparsevec_ip_ops", "sparsevec_cosine_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build index serially
|
||||||
|
$node->safe_psql("postgres", qq(
|
||||||
|
SET max_parallel_maintenance_workers = 0;
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
));
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
|
# Build index in parallel in memory
|
||||||
|
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
|
SET client_min_messages = DEBUG;
|
||||||
|
SET min_parallel_table_scan_size = 1;
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
));
|
||||||
|
is($ret, 0, $stderr);
|
||||||
|
like($stderr, qr/using \d+ parallel workers/);
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
|
# Build index in parallel on disk
|
||||||
|
# Set parallel_workers on table to use workers with low maintenance_work_mem
|
||||||
|
($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
|
ALTER TABLE tst SET (parallel_workers = 2);
|
||||||
|
SET client_min_messages = DEBUG;
|
||||||
|
SET maintenance_work_mem = '4MB';
|
||||||
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
|
ALTER TABLE tst RESET (parallel_workers);
|
||||||
|
));
|
||||||
|
is($ret, 0, $stderr);
|
||||||
|
like($stderr, qr/using \d+ parallel workers/);
|
||||||
|
like($stderr, qr/hnsw graph no longer fits into maintenance_work_mem/);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
116
test/t/023_hnsw_bit_insert_recall.pl
Normal file
116
test/t/023_hnsw_bit_insert_recall.pl
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
my $dim = 52;
|
||||||
|
my $max = 2**$dim;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = 100;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator $queries[0] LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = 100;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator $queries[$i] LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
my %expected_set = map { $_ => 1 } @expected_ids;
|
||||||
|
|
||||||
|
foreach (@actual_ids)
|
||||||
|
{
|
||||||
|
if (exists($expected_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$total += $limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v bit($dim));");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r = int(rand() * $max);
|
||||||
|
push(@queries, "${r}::bigint::bit($dim)");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<~>", "<\%>");
|
||||||
|
my @opclasses = ("bit_hamming_ops", "bit_jaccard_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v $opclass);");
|
||||||
|
|
||||||
|
# Use concurrent inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=10 --transactions=1000",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"023_hnsw_bit_insert_recall_$opclass" => "INSERT INTO tst (v) VALUES ((random() * $max)::bigint::bit($dim));"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
# Handle ties
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
WITH top AS (
|
||||||
|
SELECT v $operator $_ AS distance FROM tst ORDER BY distance LIMIT $limit
|
||||||
|
)
|
||||||
|
SELECT i FROM tst WHERE (v $operator $_) <= (SELECT MAX(distance) FROM top)
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
my $min = $operator eq "<\%>" ? 0.95 : 0.98;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
113
test/t/024_hnsw_halfvec_insert_recall.pl
Normal file
113
test/t/024_hnsw_halfvec_insert_recall.pl
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
my $dim = 10;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v halfvec($dim));");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my @r = ();
|
||||||
|
for (1 .. $dim)
|
||||||
|
{
|
||||||
|
push(@r, rand());
|
||||||
|
}
|
||||||
|
push(@queries, "[" . join(",", @r) . "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
|
my @opclasses = ("halfvec_l2_ops", "halfvec_ip_ops", "halfvec_cosine_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v $opclass);");
|
||||||
|
|
||||||
|
# Use concurrent inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=10 --transactions=1000",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"024_hnsw_halfvec_insert_recall_$opclass" => "INSERT INTO tst (v) VALUES (ARRAY[$array_sql]);"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
my $min = $operator eq "<#>" ? 0.94 : 0.98;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
109
test/t/025_hnsw_sparsevec_insert_recall.pl
Normal file
109
test/t/025_hnsw_sparsevec_insert_recall.pl
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v sparsevec(3));");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "{1:$r1,2:$r2,3:$r3}/3");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
|
my @opclasses = ("sparsevec_l2_ops", "sparsevec_ip_ops", "sparsevec_cosine_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v $opclass);");
|
||||||
|
|
||||||
|
# Use concurrent inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=10 --transactions=1000",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"025_hnsw_sparsevec_insert_recall_$opclass" => "INSERT INTO tst (v) VALUES (ARRAY[random(), random(), random()]::vector::sparsevec);"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
58
test/t/026_hnsw_bit_duplicates.pl
Normal file
58
test/t/026_hnsw_bit_duplicates.pl
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (v bit(3));");
|
||||||
|
|
||||||
|
sub insert_vectors
|
||||||
|
{
|
||||||
|
for my $i (1 .. 20)
|
||||||
|
{
|
||||||
|
$node->safe_psql("postgres", "INSERT INTO tst VALUES ('111');");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub test_duplicates
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = 1;
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM tst ORDER BY v <~> '111') t;
|
||||||
|
));
|
||||||
|
is($res, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test duplicates with build
|
||||||
|
insert_vectors();
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v bit_hamming_ops);");
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Reset
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
|
||||||
|
# Test duplicates with inserts
|
||||||
|
insert_vectors();
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Test fallback path for inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=100",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"026_hnsw_bit_duplicates" => "INSERT INTO tst VALUES ('111');"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
58
test/t/027_hnsw_halfvec_duplicates.pl
Normal file
58
test/t/027_hnsw_halfvec_duplicates.pl
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (v halfvec(3));");
|
||||||
|
|
||||||
|
sub insert_vectors
|
||||||
|
{
|
||||||
|
for my $i (1 .. 20)
|
||||||
|
{
|
||||||
|
$node->safe_psql("postgres", "INSERT INTO tst VALUES ('[1,1,1]');");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub test_duplicates
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = 1;
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM tst ORDER BY v <-> '[1,1,1]') t;
|
||||||
|
));
|
||||||
|
is($res, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test duplicates with build
|
||||||
|
insert_vectors();
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v halfvec_l2_ops);");
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Reset
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
|
||||||
|
# Test duplicates with inserts
|
||||||
|
insert_vectors();
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Test fallback path for inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=100",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"027_hnsw_halfvec_duplicates" => "INSERT INTO tst VALUES ('[1,1,1]');"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
58
test/t/028_hnsw_sparsevec_duplicates.pl
Normal file
58
test/t/028_hnsw_sparsevec_duplicates.pl
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (v sparsevec(3));");
|
||||||
|
|
||||||
|
sub insert_vectors
|
||||||
|
{
|
||||||
|
for my $i (1 .. 20)
|
||||||
|
{
|
||||||
|
$node->safe_psql("postgres", "INSERT INTO tst VALUES ('{1:1,2:1,3:1}/3');");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub test_duplicates
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = 1;
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM tst ORDER BY v <-> '{1:1,2:1,3:1}/3') t;
|
||||||
|
));
|
||||||
|
is($res, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test duplicates with build
|
||||||
|
insert_vectors();
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v sparsevec_l2_ops);");
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Reset
|
||||||
|
$node->safe_psql("postgres", "TRUNCATE tst;");
|
||||||
|
|
||||||
|
# Test duplicates with inserts
|
||||||
|
insert_vectors();
|
||||||
|
test_duplicates();
|
||||||
|
|
||||||
|
# Test fallback path for inserts
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=100",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs",
|
||||||
|
{
|
||||||
|
"028_hnsw_sparsevec_duplicates" => "INSERT INTO tst VALUES ('{1:1,2:1,3:1}/3');"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
100
test/t/029_hnsw_bit_vacuum_recall.pl
Normal file
100
test/t/029_hnsw_bit_vacuum_recall.pl
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
my $dim = 52;
|
||||||
|
my $max = 2**$dim;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $ef_search, $test_name) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v <~> $queries[0] LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
SELECT i FROM tst ORDER BY v <~> $queries[$i] LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
my %expected_set = map { $_ => 1 } @expected_ids;
|
||||||
|
|
||||||
|
foreach (@actual_ids)
|
||||||
|
{
|
||||||
|
if (exists($expected_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$total += $limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $test_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v bit($dim));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, (random() * $max)::bigint::bit($dim) FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v bit_hamming_ops) WITH (m = 4, ef_construction = 8);");
|
||||||
|
|
||||||
|
# Delete data
|
||||||
|
$node->safe_psql("postgres", "DELETE FROM tst WHERE i > 2500;");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r = int(rand() * $max);
|
||||||
|
push(@queries, "${r}::bigint::bit($dim)");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
WITH top AS (
|
||||||
|
SELECT v <~> $_ AS distance FROM tst ORDER BY distance LIMIT $limit
|
||||||
|
)
|
||||||
|
SELECT i FROM tst WHERE (v <~> $_) <= (SELECT MAX(distance) FROM top)
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
test_recall(0.35, 100, "before vacuum");
|
||||||
|
|
||||||
|
# TODO Test concurrent inserts with vacuum
|
||||||
|
$node->safe_psql("postgres", "VACUUM tst;");
|
||||||
|
|
||||||
|
test_recall(0.80, 100, "after vacuum");
|
||||||
|
|
||||||
|
done_testing();
|
||||||
97
test/t/030_hnsw_halfvec_vacuum_recall.pl
Normal file
97
test/t/030_hnsw_halfvec_vacuum_recall.pl
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $ef_search, $test_name) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v <-> '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $test_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v halfvec(3));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v halfvec_l2_ops) WITH (m = 4, ef_construction = 8);");
|
||||||
|
|
||||||
|
# Delete data
|
||||||
|
$node->safe_psql("postgres", "DELETE FROM tst WHERE i > 2500;");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "[$r1,$r2,$r3]");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '$_' LIMIT $limit;
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
test_recall(0.18, $limit, "before vacuum");
|
||||||
|
test_recall(0.95, 100, "before vacuum");
|
||||||
|
|
||||||
|
# TODO Test concurrent inserts with vacuum
|
||||||
|
$node->safe_psql("postgres", "VACUUM tst;");
|
||||||
|
|
||||||
|
test_recall(0.95, $limit, "after vacuum");
|
||||||
|
|
||||||
|
done_testing();
|
||||||
97
test/t/031_hnsw_sparsevec_vacuum_recall.pl
Normal file
97
test/t/031_hnsw_sparsevec_vacuum_recall.pl
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $ef_search, $test_name) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v <-> '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET hnsw.ef_search = $ef_search;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $test_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v sparsevec(3));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()]::vector::sparsevec(3) FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v sparsevec_l2_ops) WITH (m = 4, ef_construction = 8);");
|
||||||
|
|
||||||
|
# Delete data
|
||||||
|
$node->safe_psql("postgres", "DELETE FROM tst WHERE i > 2500;");
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "{1:$r1,2:$r2,3:$r3}/3");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '$_' LIMIT $limit;
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
test_recall(0.18, $limit, "before vacuum");
|
||||||
|
test_recall(0.95, 100, "before vacuum");
|
||||||
|
|
||||||
|
# TODO Test concurrent inserts with vacuum
|
||||||
|
$node->safe_psql("postgres", "VACUUM tst;");
|
||||||
|
|
||||||
|
test_recall(0.95, $limit, "after vacuum");
|
||||||
|
|
||||||
|
done_testing();
|
||||||
154
test/t/032_ivfflat_halfvec_build_recall.pl
Normal file
154
test/t/032_ivfflat_halfvec_build_recall.pl
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
my $dim = 10;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($probes, $min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET ivfflat.probes = $probes;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan using idx on tst/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET ivfflat.probes = $probes;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
my %expected_set = map { $_ => 1 } @expected_ids;
|
||||||
|
|
||||||
|
foreach (@actual_ids)
|
||||||
|
{
|
||||||
|
if (exists($expected_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$total += $limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v halfvec($dim));");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my @r = ();
|
||||||
|
for (1 .. $dim)
|
||||||
|
{
|
||||||
|
push(@r, rand());
|
||||||
|
}
|
||||||
|
push(@queries, "[" . join(",", @r) . "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
|
my @opclasses = ("halfvec_l2_ops", "halfvec_ip_ops", "halfvec_cosine_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
WITH top AS (
|
||||||
|
SELECT v $operator '$_' AS distance FROM tst ORDER BY distance LIMIT $limit
|
||||||
|
)
|
||||||
|
SELECT i FROM tst WHERE (v $operator '$_') <= (SELECT MAX(distance) FROM top)
|
||||||
|
));
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build index serially
|
||||||
|
$node->safe_psql("postgres", qq(
|
||||||
|
SET max_parallel_maintenance_workers = 0;
|
||||||
|
CREATE INDEX idx ON tst USING ivfflat (v $opclass);
|
||||||
|
));
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
if ($operator ne "<#>")
|
||||||
|
{
|
||||||
|
# TODO Fix test (uniform random vectors all have similar inner product)
|
||||||
|
test_recall(1, 0.35, $operator);
|
||||||
|
test_recall(10, 0.95, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test probes equals lists
|
||||||
|
if ($operator eq "<=>")
|
||||||
|
{
|
||||||
|
test_recall(100, 0.98, $operator);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
test_recall(100, 1.00, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
|
||||||
|
# Build index in parallel
|
||||||
|
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
|
SET client_min_messages = DEBUG;
|
||||||
|
SET min_parallel_table_scan_size = 1;
|
||||||
|
CREATE INDEX idx ON tst USING ivfflat (v $opclass);
|
||||||
|
));
|
||||||
|
is($ret, 0, $stderr);
|
||||||
|
like($stderr, qr/using \d+ parallel workers/);
|
||||||
|
|
||||||
|
# Test approximate results
|
||||||
|
if ($operator ne "<#>")
|
||||||
|
{
|
||||||
|
# TODO Fix test (uniform random vectors all have similar inner product)
|
||||||
|
test_recall(1, 0.35, $operator);
|
||||||
|
test_recall(10, 0.95, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test probes equals lists
|
||||||
|
if ($operator eq "<=>")
|
||||||
|
{
|
||||||
|
test_recall(100, 0.98, $operator);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
test_recall(100, 1.00, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
Reference in New Issue
Block a user