mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 03:57:34 +08:00
Compare commits
1 Commits
half-index
...
non-mvcc-s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb91de3332 |
10
.github/workflows/build.yml
vendored
10
.github/workflows/build.yml
vendored
@@ -8,8 +8,6 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- postgres: 17
|
||||
os: ubuntu-22.04
|
||||
- postgres: 16
|
||||
os: ubuntu-22.04
|
||||
- postgres: 15
|
||||
@@ -20,8 +18,10 @@ jobs:
|
||||
os: ubuntu-20.04
|
||||
- postgres: 12
|
||||
os: ubuntu-20.04
|
||||
- postgres: 11
|
||||
os: ubuntu-20.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: ${{ matrix.postgres }}
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
runs-on: macos-latest
|
||||
if: ${{ !startsWith(github.ref_name, 'windows') }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: 14
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
if: ${{ !startsWith(github.ref_name, 'mac') }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: 14
|
||||
|
||||
10
CHANGELOG.md
10
CHANGELOG.md
@@ -1,11 +1,7 @@
|
||||
## 0.5.2 (unreleased)
|
||||
## 0.5.1 (unreleased)
|
||||
|
||||
- Added support for on-disk parallel index builds for HNSW
|
||||
|
||||
## 0.5.1 (2023-10-10)
|
||||
|
||||
- Improved performance of HNSW index builds
|
||||
- Added check for MVCC-compliant snapshot for index scans
|
||||
- Improved performance of index scans for IVFFlat after updates and deletes
|
||||
- Fixed locking for index scans for HNSW
|
||||
|
||||
## 0.5.0 (2023-08-28)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "vector",
|
||||
"abstract": "Open-source vector similarity search for Postgres",
|
||||
"description": "Supports L2 distance, inner product, and cosine distance",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.0",
|
||||
"maintainer": [
|
||||
"Andrew Kane <andrew@ankane.org>"
|
||||
],
|
||||
@@ -20,7 +20,7 @@
|
||||
"vector": {
|
||||
"file": "sql/vector.sql",
|
||||
"docfile": "README.md",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.0",
|
||||
"abstract": "Open-source vector similarity search for Postgres"
|
||||
}
|
||||
},
|
||||
|
||||
6
Makefile
6
Makefile
@@ -1,10 +1,10 @@
|
||||
EXTENSION = vector
|
||||
EXTVERSION = 0.5.1
|
||||
EXTVERSION = 0.5.0
|
||||
|
||||
MODULE_big = vector
|
||||
DATA = $(wildcard sql/*--*.sql)
|
||||
OBJS = src/half.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
|
||||
HEADERS = src/half.h src/vector.h
|
||||
OBJS = 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
|
||||
HEADERS = src/vector.h
|
||||
|
||||
TESTS = $(wildcard test/sql/*.sql)
|
||||
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
EXTENSION = vector
|
||||
EXTVERSION = 0.5.1
|
||||
EXTVERSION = 0.5.0
|
||||
|
||||
OBJS = src\half.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
|
||||
HEADERS = src\half.h src\vector.h
|
||||
OBJS = 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
|
||||
HEADERS = src\vector.h
|
||||
|
||||
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
|
||||
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
||||
@@ -56,7 +56,7 @@ install:
|
||||
copy $(EXTENSION).control "$(SHAREDIR)\extension"
|
||||
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
|
||||
mkdir "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||
for %f in ($(HEADERS)) do copy %f "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||
copy $(HEADERS) "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||
|
||||
installcheck:
|
||||
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
|
||||
|
||||
117
README.md
117
README.md
@@ -10,7 +10,7 @@ Store your vectors with the rest of your data. Supports:
|
||||
|
||||
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
||||
|
||||
[](https://github.com/pgvector/pgvector/actions)
|
||||
[](https://github.com/pgvector/pgvector/actions)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -18,7 +18,7 @@ Compile and install the extension (supports Postgres 11+)
|
||||
|
||||
```sh
|
||||
cd /tmp
|
||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
make install # may need sudo
|
||||
@@ -26,7 +26,7 @@ make install # may need sudo
|
||||
|
||||
See the [installation notes](#installation-notes) if you run into issues
|
||||
|
||||
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres). There are also instructions for [GitHub Actions](https://github.com/pgvector/setup-pgvector).
|
||||
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres)
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -215,23 +215,6 @@ SELECT ...
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
### Indexing Progress
|
||||
|
||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||
|
||||
```sql
|
||||
SELECT phase, round(100.0 * tuples_done / nullif(tuples_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;
|
||||
```
|
||||
|
||||
The phases for IVFFlat are:
|
||||
|
||||
1. `initializing`
|
||||
2. `performing k-means`
|
||||
3. `assigning tuples`
|
||||
4. `loading tuples`
|
||||
|
||||
Note: `%` is only populated during the `loading tuples` phase
|
||||
|
||||
## HNSW
|
||||
|
||||
An HNSW index creates a multilayer graph. It has slower build times and uses more memory than IVFFlat, but has better query performance (in terms of speed-recall tradeoff). There’s no training step like IVFFlat, so the index can be created without any data in the table.
|
||||
@@ -269,8 +252,6 @@ Specify HNSW parameters
|
||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);
|
||||
```
|
||||
|
||||
A higher value of `ef_construction` provides better recall at the cost of index build time / insert speed.
|
||||
|
||||
### Query Options
|
||||
|
||||
Specify the size of the dynamic candidate list for search (40 by default)
|
||||
@@ -290,18 +271,22 @@ SELECT ...
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
### Indexing Progress
|
||||
## Indexing Progress
|
||||
|
||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||
|
||||
```sql
|
||||
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;
|
||||
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
|
||||
```
|
||||
|
||||
The phases for HNSW are:
|
||||
The phases are:
|
||||
|
||||
1. `initializing`
|
||||
2. `loading tuples`
|
||||
2. `performing k-means` - IVFFlat only
|
||||
3. `assigning tuples` - IVFFlat only
|
||||
4. `loading tuples`
|
||||
|
||||
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
|
||||
|
||||
## Filtering
|
||||
|
||||
@@ -332,15 +317,13 @@ CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(cate
|
||||
|
||||
## 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 ([Python example](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search.py)).
|
||||
|
||||
```sql
|
||||
SELECT id, content FROM items, plainto_tsquery('hello search') query
|
||||
WHERE textsearch @@ query ORDER BY ts_rank_cd(textsearch, query) DESC LIMIT 5;
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Performance
|
||||
|
||||
Use `EXPLAIN ANALYZE` to debug performance.
|
||||
@@ -377,21 +360,17 @@ Use pgvector from any language with a Postgres client. You can even generate and
|
||||
|
||||
Language | Libraries / Examples
|
||||
--- | ---
|
||||
C | [pgvector-c](https://github.com/pgvector/pgvector-c)
|
||||
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
|
||||
C#, F#, Visual Basic | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
|
||||
C# | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
|
||||
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
|
||||
Dart | [pgvector-dart](https://github.com/pgvector/pgvector-dart)
|
||||
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
|
||||
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
|
||||
Haskell | [pgvector-haskell](https://github.com/pgvector/pgvector-haskell)
|
||||
Java, Kotlin, Groovy, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
|
||||
JavaScript, TypeScript | [pgvector-node](https://github.com/pgvector/pgvector-node)
|
||||
Java, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
|
||||
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
|
||||
Lisp | [pgvector-lisp](https://github.com/pgvector/pgvector-lisp)
|
||||
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
|
||||
Nim | [pgvector-nim](https://github.com/pgvector/pgvector-nim)
|
||||
OCaml | [pgvector-ocaml](https://github.com/pgvector/pgvector-ocaml)
|
||||
Node.js | [pgvector-node](https://github.com/pgvector/pgvector-node)
|
||||
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
|
||||
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
|
||||
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
|
||||
@@ -399,7 +378,6 @@ R | [pgvector-r](https://github.com/pgvector/pgvector-r)
|
||||
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
|
||||
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
|
||||
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
|
||||
Zig | [pgvector-zig](https://github.com/pgvector/pgvector-zig)
|
||||
|
||||
## Frequently Asked Questions
|
||||
|
||||
@@ -415,63 +393,6 @@ Yes, pgvector uses the write-ahead log (WAL), which allows for replication and p
|
||||
|
||||
You’ll need to use [dimensionality reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction) at the moment.
|
||||
|
||||
#### Can I store vectors with different dimensions in the same column?
|
||||
|
||||
You can use `vector` as the type (instead of `vector(3)`).
|
||||
|
||||
```sql
|
||||
CREATE TABLE embeddings (model_id bigint, item_id bigint, embedding vector, PRIMARY KEY (model_id, item_id));
|
||||
```
|
||||
|
||||
However, you can only create indexes on rows with the same number of dimensions (using [expression](https://www.postgresql.org/docs/current/indexes-expressional.html) and [partial](https://www.postgresql.org/docs/current/indexes-partial.html) indexing):
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON embeddings USING hnsw ((embedding::vector(3)) vector_l2_ops) WHERE (model_id = 123);
|
||||
```
|
||||
|
||||
and query with:
|
||||
|
||||
```sql
|
||||
SELECT * FROM embeddings WHERE model_id = 123 ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
||||
```
|
||||
|
||||
#### Can I store vectors with more precision?
|
||||
|
||||
You can use the `double precision[]` or `numeric[]` type to store vectors with more precision.
|
||||
|
||||
```sql
|
||||
CREATE TABLE items (id bigserial PRIMARY KEY, embedding double precision[]);
|
||||
|
||||
-- use {} instead of [] for Postgres arrays
|
||||
INSERT INTO items (embedding) VALUES ('{1,2,3}'), ('{4,5,6}');
|
||||
```
|
||||
|
||||
Optionally, add a [check constraint](https://www.postgresql.org/docs/current/ddl-constraints.html) to ensure data can be converted to the `vector` type and has the expected dimensions.
|
||||
|
||||
```sql
|
||||
ALTER TABLE items ADD CHECK (vector_dims(embedding::vector) = 3);
|
||||
```
|
||||
|
||||
Use [expression indexing](https://www.postgresql.org/docs/current/indexes-expressional.html) to index (at a lower precision):
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON items USING hnsw ((embedding::vector(3)) vector_l2_ops);
|
||||
```
|
||||
|
||||
and query with:
|
||||
|
||||
```sql
|
||||
SELECT * FROM items ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
||||
```
|
||||
|
||||
#### 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:
|
||||
|
||||
```sql
|
||||
SELECT pg_size_pretty(pg_relation_size('index_name'));
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
#### Why isn’t a query using an index?
|
||||
@@ -485,8 +406,6 @@ SELECT ...
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
Also, if the table is small, a table scan may be faster.
|
||||
|
||||
#### Why isn’t a query using a parallel table scan?
|
||||
|
||||
The planner doesn’t consider [out-of-line storage](https://www.postgresql.org/docs/current/storage-toast.html) in cost estimates, which can make a serial scan look cheaper. You can reduce the cost of a parallel scan for a query with:
|
||||
@@ -590,7 +509,7 @@ Then use `nmake` to build:
|
||||
|
||||
```cmd
|
||||
set "PGROOT=C:\Program Files\PostgreSQL\15"
|
||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
nmake /F Makefile.win
|
||||
nmake /F Makefile.win install
|
||||
@@ -611,7 +530,7 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
||||
You can also build the image manually:
|
||||
|
||||
```sh
|
||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
docker build --build-arg PG_MAJOR=15 -t myuser/pgvector .
|
||||
```
|
||||
@@ -676,7 +595,7 @@ pgvector is available on [these providers](https://github.com/pgvector/pgvector/
|
||||
|
||||
## Upgrading
|
||||
|
||||
[Install](#installation) the latest version (use the same method as the original installation). Then in each database you want to upgrade, run:
|
||||
Install the latest version. Then in each database you want to upgrade, run:
|
||||
|
||||
```sql
|
||||
ALTER EXTENSION vector UPDATE;
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.5.1'" to load this file. \quit
|
||||
@@ -1,82 +0,0 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.6.0'" to load this file. \quit
|
||||
|
||||
CREATE TYPE half;
|
||||
|
||||
CREATE FUNCTION half_in(cstring, oid, integer) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_out(half) RETURNS cstring
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_recv(internal, oid, integer) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_send(half) RETURNS bytea
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE TYPE half (
|
||||
INPUT = half_in,
|
||||
OUTPUT = half_out,
|
||||
RECEIVE = half_recv,
|
||||
SEND = half_send,
|
||||
INTERNALLENGTH = 2,
|
||||
PASSEDBYVALUE,
|
||||
ALIGNMENT = int2
|
||||
);
|
||||
|
||||
CREATE FUNCTION l2_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION inner_product(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION cosine_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION l1_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_l2_squared_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_negative_inner_product(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION float4_to_half(real, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION integer_to_half(integer, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION numeric_to_half(numeric, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE CAST (real AS half)
|
||||
WITH FUNCTION float4_to_half(real, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (integer AS half)
|
||||
WITH FUNCTION integer_to_half(integer, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (numeric AS half)
|
||||
WITH FUNCTION numeric_to_half(numeric, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE OPERATOR <-> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = l2_distance,
|
||||
COMMUTATOR = '<->'
|
||||
);
|
||||
|
||||
CREATE OPERATOR <#> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = half_negative_inner_product,
|
||||
COMMUTATOR = '<#>'
|
||||
);
|
||||
|
||||
CREATE OPERATOR <=> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = cosine_distance,
|
||||
COMMUTATOR = '<=>'
|
||||
);
|
||||
|
||||
CREATE OPERATOR CLASS half_l2_ops
|
||||
FOR TYPE half[] USING hnsw AS
|
||||
OPERATOR 1 <-> (half[], half[]) FOR ORDER BY float_ops,
|
||||
FUNCTION 1 half_l2_squared_distance(half[], half[]);
|
||||
@@ -290,97 +290,3 @@ CREATE OPERATOR CLASS vector_cosine_ops
|
||||
OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,
|
||||
FUNCTION 1 vector_negative_inner_product(vector, vector),
|
||||
FUNCTION 2 vector_norm(vector);
|
||||
|
||||
-- half type
|
||||
|
||||
CREATE TYPE half;
|
||||
|
||||
CREATE FUNCTION half_in(cstring, oid, integer) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_out(half) RETURNS cstring
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_recv(internal, oid, integer) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_send(half) RETURNS bytea
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE TYPE half (
|
||||
INPUT = half_in,
|
||||
OUTPUT = half_out,
|
||||
RECEIVE = half_recv,
|
||||
SEND = half_send,
|
||||
INTERNALLENGTH = 2,
|
||||
PASSEDBYVALUE,
|
||||
ALIGNMENT = int2
|
||||
);
|
||||
|
||||
-- half functions
|
||||
|
||||
CREATE FUNCTION l2_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION inner_product(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION cosine_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION l1_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'half_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
-- half private functions
|
||||
|
||||
CREATE FUNCTION half_l2_squared_distance(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION half_negative_inner_product(half[], half[]) RETURNS float8
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
-- half cast functions
|
||||
|
||||
CREATE FUNCTION float4_to_half(real, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION integer_to_half(integer, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION numeric_to_half(numeric, integer, boolean) RETURNS half
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
-- half casts
|
||||
|
||||
CREATE CAST (real AS half)
|
||||
WITH FUNCTION float4_to_half(real, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (integer AS half)
|
||||
WITH FUNCTION integer_to_half(integer, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (numeric AS half)
|
||||
WITH FUNCTION numeric_to_half(numeric, integer, boolean) AS IMPLICIT;
|
||||
|
||||
-- half operators
|
||||
|
||||
CREATE OPERATOR <-> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = l2_distance,
|
||||
COMMUTATOR = '<->'
|
||||
);
|
||||
|
||||
CREATE OPERATOR <#> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = half_negative_inner_product,
|
||||
COMMUTATOR = '<#>'
|
||||
);
|
||||
|
||||
CREATE OPERATOR <=> (
|
||||
LEFTARG = half[], RIGHTARG = half[], PROCEDURE = cosine_distance,
|
||||
COMMUTATOR = '<=>'
|
||||
);
|
||||
|
||||
-- half opclasses
|
||||
|
||||
CREATE OPERATOR CLASS half_l2_ops
|
||||
FOR TYPE half[] USING hnsw AS
|
||||
OPERATOR 1 <-> (half[], half[]) FOR ORDER BY float_ops,
|
||||
FUNCTION 1 half_l2_squared_distance(half[], half[]);
|
||||
|
||||
599
src/half.c
599
src/half.c
@@ -1,599 +0,0 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "common/shortest_dec.h"
|
||||
#include "fmgr.h"
|
||||
#include "half.h"
|
||||
#include "lib/stringinfo.h"
|
||||
#include "libpq/pqformat.h"
|
||||
#include "utils/array.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/numeric.h"
|
||||
|
||||
#if PG_VERSION_NUM < 120003
|
||||
static pg_noinline void
|
||||
float_overflow_error(void)
|
||||
{
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||
errmsg("value out of range: overflow")));
|
||||
}
|
||||
|
||||
static pg_noinline void
|
||||
float_underflow_error(void)
|
||||
{
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||
errmsg("value out of range: underflow")));
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Check if array is a vector
|
||||
*/
|
||||
static void
|
||||
CheckArrayIsVector(ArrayType *array)
|
||||
{
|
||||
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")));
|
||||
}
|
||||
|
||||
/*
|
||||
* Check if dimensions are the same
|
||||
*/
|
||||
static int
|
||||
CheckDims(ArrayType *a, ArrayType *b)
|
||||
{
|
||||
int dima;
|
||||
int dimb;
|
||||
|
||||
CheckArrayIsVector(a);
|
||||
CheckArrayIsVector(b);
|
||||
|
||||
dima = ARR_DIMS(a)[0];
|
||||
dimb = ARR_DIMS(b)[0];
|
||||
|
||||
if (dima != dimb)
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||
errmsg("different dimensions %d and %d", dima, dimb)));
|
||||
|
||||
return dima;
|
||||
}
|
||||
|
||||
/*
|
||||
* Return the datum representation for a half
|
||||
*/
|
||||
static inline Datum
|
||||
HalfGetDatum(half X)
|
||||
{
|
||||
union
|
||||
{
|
||||
half value;
|
||||
int16 retval;
|
||||
} myunion;
|
||||
|
||||
myunion.value = X;
|
||||
return Int16GetDatum(myunion.retval);
|
||||
}
|
||||
|
||||
/*
|
||||
* Return the half value of a datum
|
||||
*/
|
||||
static inline half
|
||||
DatumGetHalf(Datum X)
|
||||
{
|
||||
union
|
||||
{
|
||||
int16 value;
|
||||
half retval;
|
||||
} myunion;
|
||||
|
||||
myunion.value = DatumGetInt16(X);
|
||||
return myunion.retval;
|
||||
}
|
||||
|
||||
/*
|
||||
* Append a half to a StringInfo buffer
|
||||
*/
|
||||
static half
|
||||
pq_getmsghalf(StringInfo msg)
|
||||
{
|
||||
union
|
||||
{
|
||||
half h;
|
||||
uint16 i;
|
||||
} swap;
|
||||
|
||||
/* TODO Likely use float4 for clients */
|
||||
swap.i = pq_getmsgint(msg, 2);
|
||||
return swap.h;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get a half from a message buffer
|
||||
*/
|
||||
static void
|
||||
pq_sendhalf(StringInfo buf, half h)
|
||||
{
|
||||
union
|
||||
{
|
||||
half h;
|
||||
uint16 i;
|
||||
} swap;
|
||||
|
||||
/* TODO Likely use float4 for clients */
|
||||
swap.h = h;
|
||||
pq_sendint16(buf, swap.i);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert a half to a float4
|
||||
*/
|
||||
static float
|
||||
HalfToFloat4(half num)
|
||||
{
|
||||
#ifdef FLT16_SUPPORT
|
||||
return (float) num;
|
||||
#else
|
||||
/* TODO Improve performance */
|
||||
/* TODO Check endianness */
|
||||
uint16 bin = *((uint16 *) &num);
|
||||
uint32 exponent = (bin & 0x7C00) >> 10;
|
||||
uint32 mantissa = bin & 0x03FF;
|
||||
|
||||
/* Sign */
|
||||
uint32 result = (bin & 0x8000) << 16;
|
||||
|
||||
if (exponent == 31)
|
||||
{
|
||||
if (mantissa == 0)
|
||||
{
|
||||
/* Infinite */
|
||||
result |= 0x7F800000;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* NaN */
|
||||
result |= 0x7FC00000;
|
||||
result |= mantissa << 13;
|
||||
}
|
||||
}
|
||||
else if (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;
|
||||
result |= mantissa << 13;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Normal */
|
||||
result |= (exponent - 15 + 127) << 23;
|
||||
result |= mantissa << 13;
|
||||
}
|
||||
|
||||
return *((float *) &result);
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert a float4 to a half
|
||||
*/
|
||||
static half
|
||||
Float4ToHalfUnchecked(float num)
|
||||
{
|
||||
#ifdef FLT16_SUPPORT
|
||||
return (_Float16) num;
|
||||
#else
|
||||
/* TODO Improve performance */
|
||||
/* TODO Check endianness */
|
||||
uint32 bin = *((uint32 *) &num);
|
||||
int exponent = (bin & 0x7F800000) >> 23;
|
||||
int mantissa = bin & 0x007FFFFF;
|
||||
|
||||
/* Sign */
|
||||
uint16 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;
|
||||
}
|
||||
}
|
||||
|
||||
return *((half *) & result);
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert a float4 to a half
|
||||
*/
|
||||
static half
|
||||
Float4ToHalf(float num)
|
||||
{
|
||||
half result = Float4ToHalfUnchecked(num);
|
||||
|
||||
/* TODO Perform checks without HalfToFloat4 */
|
||||
if (unlikely(isinf(HalfToFloat4(result))) && !isinf(num))
|
||||
float_overflow_error();
|
||||
if (unlikely(HalfToFloat4(result) == 0.0f) && num != 0.0)
|
||||
float_underflow_error();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert textual representation to internal representation
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_in);
|
||||
Datum
|
||||
half_in(PG_FUNCTION_ARGS)
|
||||
{
|
||||
char *num = PG_GETARG_CSTRING(0);
|
||||
char *orig_num;
|
||||
float val;
|
||||
char *endptr;
|
||||
|
||||
orig_num = num;
|
||||
|
||||
/* Skip leading whitespace */
|
||||
while (*num != '\0' && isspace((unsigned char) *num))
|
||||
num++;
|
||||
|
||||
/*
|
||||
* Check for an empty-string input to begin with, to avoid the vagaries of
|
||||
* strtof() on different platforms.
|
||||
*/
|
||||
if (*num == '\0')
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||
errmsg("invalid input syntax for type %s: \"%s\"",
|
||||
"half", orig_num)));
|
||||
|
||||
val = strtof(num, &endptr);
|
||||
|
||||
if (val < -HALF_MAX || val > HALF_MAX)
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||
errmsg("\"%s\" is out of range for type %s",
|
||||
orig_num, "half")));
|
||||
|
||||
/* Skip trailing whitespace */
|
||||
while (*endptr != '\0' && isspace((unsigned char) *endptr))
|
||||
endptr++;
|
||||
|
||||
/* If there is any junk left at the end of the string, bail out */
|
||||
if (*endptr != '\0')
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||
errmsg("invalid input syntax for type %s: \"%s\"",
|
||||
"half", orig_num)));
|
||||
|
||||
PG_RETURN_HALF(Float4ToHalf(val));
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert internal representation to textual representation
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_out);
|
||||
Datum
|
||||
half_out(PG_FUNCTION_ARGS)
|
||||
{
|
||||
float num = HalfToFloat4(PG_GETARG_HALF(0));
|
||||
char *ascii = (char *) palloc(32);
|
||||
int ndig = FLT_DIG + extra_float_digits;
|
||||
|
||||
if (extra_float_digits > 0)
|
||||
{
|
||||
float_to_shortest_decimal_buf(num, ascii);
|
||||
PG_RETURN_CSTRING(ascii);
|
||||
}
|
||||
|
||||
(void) pg_strfromd(ascii, 32, ndig, num);
|
||||
PG_RETURN_CSTRING(ascii);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert external binary representation to internal representation
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_recv);
|
||||
Datum
|
||||
half_recv(PG_FUNCTION_ARGS)
|
||||
{
|
||||
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
|
||||
|
||||
PG_RETURN_HALF(pq_getmsghalf(buf));
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert internal representation to the external binary representation
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_send);
|
||||
Datum
|
||||
half_send(PG_FUNCTION_ARGS)
|
||||
{
|
||||
half arg1 = PG_GETARG_HALF(0);
|
||||
StringInfoData buf;
|
||||
|
||||
pq_begintypsend(&buf);
|
||||
pq_sendhalf(&buf, arg1);
|
||||
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert integer to half
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(integer_to_half);
|
||||
Datum
|
||||
integer_to_half(PG_FUNCTION_ARGS)
|
||||
{
|
||||
int32 i = PG_GETARG_INT32(0);
|
||||
|
||||
/* TODO Figure out correct error */
|
||||
float f = (float) i;
|
||||
half h = Float4ToHalf(f);
|
||||
|
||||
PG_RETURN_HALF(h);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert numeric to half
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(numeric_to_half);
|
||||
Datum
|
||||
numeric_to_half(PG_FUNCTION_ARGS)
|
||||
{
|
||||
Numeric num = PG_GETARG_NUMERIC(0);
|
||||
float f = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(num)));
|
||||
half h = Float4ToHalf(f);
|
||||
|
||||
PG_RETURN_HALF(h);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert float4 to half
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(float4_to_half);
|
||||
Datum
|
||||
float4_to_half(PG_FUNCTION_ARGS)
|
||||
{
|
||||
float f = PG_GETARG_FLOAT4(0);
|
||||
half h = Float4ToHalf(f);
|
||||
|
||||
PG_RETURN_HALF(h);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the L2 distance between half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_l2_distance);
|
||||
Datum
|
||||
half_l2_distance(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < dim; i++)
|
||||
{
|
||||
float diff = HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]);
|
||||
|
||||
distance += diff * diff;
|
||||
}
|
||||
|
||||
PG_RETURN_FLOAT8(sqrt((double) distance));
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the L2 squared distance between half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_l2_squared_distance);
|
||||
Datum
|
||||
half_l2_squared_distance(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < dim; i++)
|
||||
{
|
||||
float diff = HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]);
|
||||
|
||||
distance += diff * diff;
|
||||
}
|
||||
|
||||
PG_RETURN_FLOAT8((double) distance);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the inner product of two half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_inner_product);
|
||||
Datum
|
||||
half_inner_product(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < dim; i++)
|
||||
distance += HalfToFloat4(ax[i]) * HalfToFloat4(bx[i]);
|
||||
|
||||
PG_RETURN_FLOAT8((double) distance);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the negative inner product of two half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_negative_inner_product);
|
||||
Datum
|
||||
half_negative_inner_product(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < dim; i++)
|
||||
distance += HalfToFloat4(ax[i]) * HalfToFloat4(bx[i]);
|
||||
|
||||
PG_RETURN_FLOAT8((double) distance * -1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the cosine distance between two half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_cosine_distance);
|
||||
Datum
|
||||
half_cosine_distance(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
float norma = 0.0;
|
||||
float normb = 0.0;
|
||||
double similarity;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < 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 L1 distance between two half arrays
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(half_l1_distance);
|
||||
Datum
|
||||
half_l1_distance(PG_FUNCTION_ARGS)
|
||||
{
|
||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||
half *ax = (half *) ARR_DATA_PTR(a);
|
||||
half *bx = (half *) ARR_DATA_PTR(b);
|
||||
float distance = 0.0;
|
||||
int dim = CheckDims(a, b);
|
||||
|
||||
/* Auto-vectorized */
|
||||
for (int i = 0; i < dim; i++)
|
||||
distance += fabsf(HalfToFloat4(ax[i]) - HalfToFloat4(bx[i]));
|
||||
|
||||
PG_RETURN_FLOAT8((double) distance);
|
||||
}
|
||||
28
src/half.h
28
src/half.h
@@ -1,28 +0,0 @@
|
||||
#ifndef HALF_H
|
||||
#define HALF_H
|
||||
|
||||
#define __STDC_WANT_IEC_60559_TYPES_EXT__
|
||||
|
||||
#include <float.h>
|
||||
|
||||
/* _Float16 and __fp16 are not supported on x86_64 with GCC 11 */
|
||||
#if defined(__is_identifier)
|
||||
#if __is_identifier(_Float16)
|
||||
#define FLT16_SUPPORT
|
||||
#endif
|
||||
#elif defined(FLT16_MAX)
|
||||
#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 PG_GETARG_HALF(n) DatumGetHalf(PG_GETARG_DATUM(n))
|
||||
#define PG_RETURN_HALF(x) return HalfGetDatum(x)
|
||||
|
||||
#endif
|
||||
@@ -14,7 +14,6 @@
|
||||
#endif
|
||||
|
||||
int hnsw_ef_search;
|
||||
bool hnsw_enable_parallel_build;
|
||||
static relopt_kind hnsw_relopt_kind;
|
||||
|
||||
/*
|
||||
@@ -40,11 +39,6 @@ HnswInit(void)
|
||||
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
|
||||
"Valid range is 1..1000.", &hnsw_ef_search,
|
||||
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
|
||||
/* Behind a variable for now since can be slower than building in memory */
|
||||
DefineCustomBoolVariable("hnsw.enable_parallel_build", "Enables or disables building indexes in parallel",
|
||||
NULL, &hnsw_enable_parallel_build,
|
||||
false, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
68
src/hnsw.h
68
src/hnsw.h
@@ -4,7 +4,6 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include "access/generic_xlog.h"
|
||||
#include "access/parallel.h"
|
||||
#include "access/reloptions.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "port.h" /* for random() */
|
||||
@@ -15,10 +14,6 @@
|
||||
#error "Requires PostgreSQL 11+"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM < 120000
|
||||
#include "access/relscan.h"
|
||||
#endif
|
||||
|
||||
#define HNSW_MAX_DIM 2000
|
||||
|
||||
/* Support functions */
|
||||
@@ -62,9 +57,7 @@
|
||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||
#define PROGRESS_HNSW_PHASE_LOAD 2
|
||||
|
||||
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
||||
|
||||
#define HNSW_ELEMENT_TUPLE_SIZE(size) MAXALIGN(offsetof(HnswElementTupleData, data) + (size))
|
||||
#define HNSW_ELEMENT_TUPLE_SIZE(_dim) MAXALIGN(offsetof(HnswElementTupleData, vec) + VECTOR_SIZE(_dim))
|
||||
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
||||
|
||||
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
||||
@@ -95,7 +88,6 @@
|
||||
|
||||
/* Variables */
|
||||
extern int hnsw_ef_search;
|
||||
extern bool hnsw_enable_parallel_build;
|
||||
|
||||
typedef struct HnswNeighborArray HnswNeighborArray;
|
||||
|
||||
@@ -109,7 +101,7 @@ typedef struct HnswElementData
|
||||
OffsetNumber offno;
|
||||
OffsetNumber neighborOffno;
|
||||
BlockNumber neighborPage;
|
||||
Datum value;
|
||||
Vector *vec;
|
||||
} HnswElementData;
|
||||
|
||||
typedef HnswElementData * HnswElement;
|
||||
@@ -118,13 +110,11 @@ typedef struct HnswCandidate
|
||||
{
|
||||
HnswElement element;
|
||||
float distance;
|
||||
bool closer;
|
||||
} HnswCandidate;
|
||||
|
||||
typedef struct HnswNeighborArray
|
||||
{
|
||||
int length;
|
||||
bool closerSet;
|
||||
HnswCandidate *items;
|
||||
} HnswNeighborArray;
|
||||
|
||||
@@ -142,49 +132,6 @@ typedef struct HnswOptions
|
||||
int efConstruction; /* size of dynamic candidate list */
|
||||
} HnswOptions;
|
||||
|
||||
typedef struct HnswSpool
|
||||
{
|
||||
Relation heap;
|
||||
Relation index;
|
||||
} HnswSpool;
|
||||
|
||||
typedef struct HnswShared
|
||||
{
|
||||
/* Immutable state */
|
||||
Oid heaprelid;
|
||||
Oid indexrelid;
|
||||
bool isconcurrent;
|
||||
int scantuplesortstates;
|
||||
|
||||
/* Worker progress */
|
||||
ConditionVariable workersdonecv;
|
||||
|
||||
/* Mutex for mutable state */
|
||||
slock_t mutex;
|
||||
|
||||
/* Mutable state */
|
||||
int nparticipantsdone;
|
||||
double reltuples;
|
||||
double indtuples;
|
||||
|
||||
#if PG_VERSION_NUM < 120000
|
||||
ParallelHeapScanDescData heapdesc; /* must come last */
|
||||
#endif
|
||||
} HnswShared;
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
#define ParallelTableScanFromHnswShared(shared) \
|
||||
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(HnswShared)))
|
||||
#endif
|
||||
|
||||
typedef struct HnswLeader
|
||||
{
|
||||
ParallelContext *pcxt;
|
||||
int nparticipanttuplesorts;
|
||||
HnswShared *hnswshared;
|
||||
Snapshot snapshot;
|
||||
} HnswLeader;
|
||||
|
||||
typedef struct HnswBuildState
|
||||
{
|
||||
/* Info */
|
||||
@@ -212,16 +159,12 @@ typedef struct HnswBuildState
|
||||
HnswElement entryPoint;
|
||||
double ml;
|
||||
int maxLevel;
|
||||
long memoryLeft;
|
||||
double maxInMemoryElements;
|
||||
bool flushed;
|
||||
Vector *normvec;
|
||||
|
||||
/* Memory */
|
||||
MemoryContext tmpCtx;
|
||||
|
||||
/* Parallel builds */
|
||||
HnswLeader *hnswleader;
|
||||
HnswShared *hnswshared;
|
||||
} HnswBuildState;
|
||||
|
||||
typedef struct HnswMetaPageData
|
||||
@@ -257,7 +200,7 @@ typedef struct HnswElementTupleData
|
||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
||||
ItemPointerData neighbortid;
|
||||
uint16 unused2;
|
||||
Vector data;
|
||||
Vector vec;
|
||||
} HnswElementTupleData;
|
||||
|
||||
typedef HnswElementTupleData * HnswElementTuple;
|
||||
@@ -315,7 +258,7 @@ typedef struct HnswVacuumState
|
||||
/* Methods */
|
||||
int HnswGetM(Relation index);
|
||||
int HnswGetEfConstruction(Relation index);
|
||||
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
||||
FmgrInfo *HnswOptionalProcInfo(Relation rel, uint16 procnum);
|
||||
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||
void HnswCommitBuffer(Buffer buf, GenericXLogState *state);
|
||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||
@@ -342,7 +285,6 @@ void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation i
|
||||
void HnswSetElementTuple(HnswElementTuple etup, HnswElement element);
|
||||
void HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
||||
void HnswLoadNeighbors(HnswElement element, Relation index, int m);
|
||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
||||
|
||||
/* Index access methods */
|
||||
IndexBuildResult *hnswbuild(Relation heap, Relation index, IndexInfo *indexInfo);
|
||||
|
||||
478
src/hnswbuild.c
478
src/hnswbuild.c
@@ -2,16 +2,12 @@
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "access/parallel.h"
|
||||
#include "access/xact.h"
|
||||
#include "catalog/index.h"
|
||||
#include "hnsw.h"
|
||||
#include "miscadmin.h"
|
||||
#include "lib/pairingheap.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "tcop/tcopprot.h"
|
||||
#include "utils/datum.h"
|
||||
#include "utils/memutils.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
@@ -39,23 +35,6 @@
|
||||
#define UpdateProgress(index, val) ((void)val)
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
#include "utils/backend_status.h"
|
||||
#include "utils/wait_event.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
#include "access/table.h"
|
||||
#include "optimizer/optimizer.h"
|
||||
#else
|
||||
#include "access/heapam.h"
|
||||
#include "optimizer/planner.h"
|
||||
#include "pgstat.h"
|
||||
#endif
|
||||
|
||||
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
||||
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000002)
|
||||
|
||||
/*
|
||||
* Create the metapage
|
||||
*/
|
||||
@@ -102,6 +81,7 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **
|
||||
HnswPageGetOpaque(*page)->nextblkno = BufferGetBlockNumber(newbuf);
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(*buf);
|
||||
GenericXLogFinish(*state);
|
||||
UnlockReleaseBuffer(*buf);
|
||||
|
||||
@@ -126,7 +106,8 @@ CreateElementPages(HnswBuildState * buildstate)
|
||||
{
|
||||
Relation index = buildstate->index;
|
||||
ForkNumber forkNum = buildstate->forkNum;
|
||||
Size etupAllocSize;
|
||||
int dimensions = buildstate->dimensions;
|
||||
Size etupSize;
|
||||
Size maxSize;
|
||||
HnswElementTuple etup;
|
||||
HnswNeighborTuple ntup;
|
||||
@@ -137,12 +118,12 @@ CreateElementPages(HnswBuildState * buildstate)
|
||||
ListCell *lc;
|
||||
|
||||
/* Calculate sizes */
|
||||
etupAllocSize = BLCKSZ;
|
||||
maxSize = HNSW_MAX_SIZE;
|
||||
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
||||
|
||||
/* Allocate once */
|
||||
etup = palloc0(etupAllocSize);
|
||||
ntup = palloc0(BLCKSZ);
|
||||
etup = palloc0(etupSize);
|
||||
ntup = palloc0(maxSize);
|
||||
|
||||
/* Prepare first page */
|
||||
buf = HnswNewBuffer(index, forkNum);
|
||||
@@ -153,24 +134,15 @@ CreateElementPages(HnswBuildState * buildstate)
|
||||
foreach(lc, buildstate->elements)
|
||||
{
|
||||
HnswElement element = lfirst(lc);
|
||||
Size etupSize;
|
||||
Size ntupSize;
|
||||
Size combinedSize;
|
||||
|
||||
/* Zero memory for each element */
|
||||
MemSet(etup, 0, etupAllocSize);
|
||||
HnswSetElementTuple(etup, element);
|
||||
|
||||
/* Calculate sizes */
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(DatumGetPointer(element->value)));
|
||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||
|
||||
/* Initial size check */
|
||||
if (etupSize > etupAllocSize)
|
||||
elog(ERROR, "index tuple too large");
|
||||
|
||||
HnswSetElementTuple(etup, element);
|
||||
|
||||
/* Keep element and neighbors on the same page if possible */
|
||||
if (PageGetFreeSpace(page) < etupSize || (combinedSize <= maxSize && PageGetFreeSpace(page) < combinedSize))
|
||||
HnswBuildAppendPage(index, &buf, &page, &state, forkNum);
|
||||
@@ -207,6 +179,7 @@ CreateElementPages(HnswBuildState * buildstate)
|
||||
insertPage = BufferGetBlockNumber(buf);
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
@@ -254,6 +227,7 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
@@ -293,14 +267,13 @@ FlushPages(HnswBuildState * buildstate)
|
||||
* Insert tuple
|
||||
*/
|
||||
static bool
|
||||
InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState * buildstate, HnswElement * dup, MemoryContext outerCtx)
|
||||
InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState * buildstate, HnswElement * dup)
|
||||
{
|
||||
FmgrInfo *procinfo = buildstate->procinfo;
|
||||
Oid collation = buildstate->collation;
|
||||
HnswElement entryPoint = buildstate->entryPoint;
|
||||
int efConstruction = buildstate->efConstruction;
|
||||
int m = buildstate->m;
|
||||
MemoryContext oldCtx;
|
||||
|
||||
/* Detoast once for all calls */
|
||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||
@@ -313,9 +286,7 @@ InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState *
|
||||
}
|
||||
|
||||
/* Copy value to element so accessible outside of memory context */
|
||||
oldCtx = MemoryContextSwitchTo(outerCtx);
|
||||
element->value = datumCopy(value, false, -1);
|
||||
MemoryContextSwitchTo(oldCtx);
|
||||
memcpy(element->vec, DatumGetVector(value), VECTOR_SIZE(buildstate->dimensions));
|
||||
|
||||
/* Insert element in graph */
|
||||
HnswInsertElement(element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
||||
@@ -345,21 +316,6 @@ InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState *
|
||||
return *dup == NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the memory used by an element
|
||||
*/
|
||||
static long
|
||||
HnswElementMemory(HnswElement e, int m)
|
||||
{
|
||||
long elementSize = sizeof(HnswElementData);
|
||||
|
||||
elementSize += sizeof(HnswNeighborArray) * (e->level + 1);
|
||||
elementSize += sizeof(HnswCandidate) * (m * (e->level + 2));
|
||||
elementSize += sizeof(ItemPointerData);
|
||||
elementSize += VARSIZE_ANY(DatumGetPointer(e->value));
|
||||
return elementSize;
|
||||
}
|
||||
|
||||
/*
|
||||
* Callback for table_index_build_scan
|
||||
*/
|
||||
@@ -381,7 +337,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
||||
if (isnull[0])
|
||||
return;
|
||||
|
||||
if (buildstate->memoryLeft <= 0)
|
||||
if (buildstate->indtuples >= buildstate->maxInMemoryElements)
|
||||
{
|
||||
if (!buildstate->flushed)
|
||||
{
|
||||
@@ -396,18 +352,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||
|
||||
if (HnswInsertTuple(buildstate->index, values, isnull, tid, buildstate->heap))
|
||||
{
|
||||
if (buildstate->hnswshared)
|
||||
{
|
||||
HnswShared *hnswshared = buildstate->hnswshared;
|
||||
|
||||
SpinLockAcquire(&hnswshared->mutex);
|
||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++hnswshared->indtuples);
|
||||
SpinLockRelease(&hnswshared->mutex);
|
||||
}
|
||||
else
|
||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
||||
}
|
||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
||||
|
||||
/* Reset memory context */
|
||||
MemoryContextSwitchTo(oldCtx);
|
||||
@@ -418,12 +363,13 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
||||
|
||||
/* Allocate necessary memory outside of memory context */
|
||||
element = HnswInitElement(tid, buildstate->m, buildstate->ml, buildstate->maxLevel);
|
||||
element->vec = palloc(VECTOR_SIZE(buildstate->dimensions));
|
||||
|
||||
/* Use memory context since detoast can allocate */
|
||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||
|
||||
/* Insert tuple */
|
||||
inserted = InsertTuple(index, values, element, buildstate, &dup, oldCtx);
|
||||
inserted = InsertTuple(index, values, element, buildstate, &dup);
|
||||
|
||||
/* Reset memory context */
|
||||
MemoryContextSwitchTo(oldCtx);
|
||||
@@ -431,21 +377,31 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
||||
|
||||
/* Add outside memory context */
|
||||
if (dup != NULL)
|
||||
{
|
||||
HnswAddHeapTid(dup, tid);
|
||||
buildstate->memoryLeft -= sizeof(ItemPointerData);
|
||||
}
|
||||
|
||||
/* Add to buildstate or free */
|
||||
if (inserted)
|
||||
{
|
||||
buildstate->elements = lappend(buildstate->elements, element);
|
||||
buildstate->memoryLeft -= HnswElementMemory(element, buildstate->m);
|
||||
}
|
||||
else
|
||||
HnswFreeElement(element);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the max number of elements that fit into maintenance_work_mem
|
||||
*/
|
||||
static double
|
||||
HnswGetMaxInMemoryElements(int m, double ml, int dimensions)
|
||||
{
|
||||
Size elementSize = sizeof(HnswElementData);
|
||||
double avgLevel = -log(0.5) * ml;
|
||||
|
||||
elementSize += sizeof(HnswNeighborArray) * (avgLevel + 1);
|
||||
elementSize += sizeof(HnswCandidate) * (m * (avgLevel + 2));
|
||||
elementSize += sizeof(ItemPointerData);
|
||||
elementSize += VECTOR_SIZE(dimensions);
|
||||
return (maintenance_work_mem * 1024L) / elementSize;
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize the build state
|
||||
*/
|
||||
@@ -462,8 +418,8 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
||||
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
||||
|
||||
/* Require column to have dimensions to be indexed */
|
||||
// if (buildstate->dimensions < 0)
|
||||
// elog(ERROR, "column does not have dimensions");
|
||||
if (buildstate->dimensions < 0)
|
||||
elog(ERROR, "column does not have dimensions");
|
||||
|
||||
if (buildstate->dimensions > HNSW_MAX_DIM)
|
||||
elog(ERROR, "column cannot have more than %d dimensions for hnsw index", HNSW_MAX_DIM);
|
||||
@@ -483,7 +439,7 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
||||
buildstate->entryPoint = NULL;
|
||||
buildstate->ml = HnswGetMl(buildstate->m);
|
||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||
buildstate->memoryLeft = maintenance_work_mem * 1024L;
|
||||
buildstate->maxInMemoryElements = HnswGetMaxInMemoryElements(buildstate->m, buildstate->ml, buildstate->dimensions);
|
||||
buildstate->flushed = false;
|
||||
|
||||
/* Reuse for each tuple */
|
||||
@@ -492,9 +448,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
||||
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||
"Hnsw build temporary context",
|
||||
ALLOCSET_DEFAULT_SIZES);
|
||||
|
||||
buildstate->hnswleader = NULL;
|
||||
buildstate->hnswshared = NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -507,374 +460,21 @@ FreeBuildState(HnswBuildState * buildstate)
|
||||
MemoryContextDelete(buildstate->tmpCtx);
|
||||
}
|
||||
|
||||
/*
|
||||
* Within leader, wait for end of heap scan
|
||||
*/
|
||||
static double
|
||||
ParallelHeapScan(HnswBuildState * buildstate)
|
||||
{
|
||||
HnswShared *hnswshared = buildstate->hnswleader->hnswshared;
|
||||
int nparticipanttuplesorts;
|
||||
double reltuples;
|
||||
|
||||
nparticipanttuplesorts = buildstate->hnswleader->nparticipanttuplesorts;
|
||||
for (;;)
|
||||
{
|
||||
SpinLockAcquire(&hnswshared->mutex);
|
||||
if (hnswshared->nparticipantsdone == nparticipanttuplesorts)
|
||||
{
|
||||
buildstate->indtuples = hnswshared->indtuples;
|
||||
reltuples = hnswshared->reltuples;
|
||||
SpinLockRelease(&hnswshared->mutex);
|
||||
break;
|
||||
}
|
||||
SpinLockRelease(&hnswshared->mutex);
|
||||
|
||||
ConditionVariableSleep(&hnswshared->workersdonecv,
|
||||
WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN);
|
||||
}
|
||||
|
||||
ConditionVariableCancelSleep();
|
||||
|
||||
return reltuples;
|
||||
}
|
||||
|
||||
/*
|
||||
* Perform a worker's portion of a parallel insert
|
||||
*/
|
||||
static void
|
||||
HnswParallelScanAndInsert(HnswSpool * hnswspool, HnswShared * hnswshared, bool progress)
|
||||
{
|
||||
HnswBuildState buildstate;
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
TableScanDesc scan;
|
||||
#else
|
||||
HeapScanDesc scan;
|
||||
#endif
|
||||
double reltuples;
|
||||
IndexInfo *indexInfo;
|
||||
|
||||
/* Join parallel scan */
|
||||
indexInfo = BuildIndexInfo(hnswspool->index);
|
||||
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
||||
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
||||
/* TODO Support in-memory builds */
|
||||
buildstate.memoryLeft = 0;
|
||||
buildstate.flushed = true;
|
||||
buildstate.hnswshared = hnswshared;
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
scan = table_beginscan_parallel(hnswspool->heap,
|
||||
ParallelTableScanFromHnswShared(hnswshared));
|
||||
reltuples = table_index_build_scan(hnswspool->heap, hnswspool->index, indexInfo,
|
||||
true, progress, BuildCallback,
|
||||
(void *) &buildstate, scan);
|
||||
#else
|
||||
scan = heap_beginscan_parallel(hnswspool->heap, &hnswshared->heapdesc);
|
||||
reltuples = IndexBuildHeapScan(hnswspool->heap, hnswspool->index, indexInfo,
|
||||
true, BuildCallback,
|
||||
(void *) &buildstate, scan);
|
||||
#endif
|
||||
|
||||
/* Record statistics */
|
||||
SpinLockAcquire(&hnswshared->mutex);
|
||||
hnswshared->nparticipantsdone++;
|
||||
hnswshared->reltuples += reltuples;
|
||||
SpinLockRelease(&hnswshared->mutex);
|
||||
|
||||
/* Log statistics */
|
||||
if (progress)
|
||||
ereport(DEBUG1, (errmsg("leader processed " INT64_FORMAT " tuples", (int64) reltuples)));
|
||||
else
|
||||
ereport(DEBUG1, (errmsg("worker processed " INT64_FORMAT " tuples", (int64) reltuples)));
|
||||
|
||||
/* Notify leader */
|
||||
ConditionVariableSignal(&hnswshared->workersdonecv);
|
||||
|
||||
FreeBuildState(&buildstate);
|
||||
}
|
||||
|
||||
/*
|
||||
* Perform work within a launched parallel process
|
||||
*/
|
||||
void
|
||||
HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
||||
{
|
||||
char *sharedquery;
|
||||
HnswSpool *hnswspool;
|
||||
HnswShared *hnswshared;
|
||||
Relation heapRel;
|
||||
Relation indexRel;
|
||||
LOCKMODE heapLockmode;
|
||||
LOCKMODE indexLockmode;
|
||||
|
||||
/* Set debug_query_string for individual workers first */
|
||||
sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
|
||||
debug_query_string = sharedquery;
|
||||
|
||||
/* Report the query string from leader */
|
||||
pgstat_report_activity(STATE_RUNNING, debug_query_string);
|
||||
|
||||
/* Look up shared state */
|
||||
hnswshared = shm_toc_lookup(toc, PARALLEL_KEY_HNSW_SHARED, false);
|
||||
|
||||
/* Open relations using lock modes known to be obtained by index.c */
|
||||
if (!hnswshared->isconcurrent)
|
||||
{
|
||||
heapLockmode = ShareLock;
|
||||
indexLockmode = AccessExclusiveLock;
|
||||
}
|
||||
else
|
||||
{
|
||||
heapLockmode = ShareUpdateExclusiveLock;
|
||||
indexLockmode = RowExclusiveLock;
|
||||
}
|
||||
|
||||
/* Open relations within worker */
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
heapRel = table_open(hnswshared->heaprelid, heapLockmode);
|
||||
#else
|
||||
heapRel = heap_open(hnswshared->heaprelid, heapLockmode);
|
||||
#endif
|
||||
indexRel = index_open(hnswshared->indexrelid, indexLockmode);
|
||||
|
||||
/* Initialize worker's own spool */
|
||||
hnswspool = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
||||
hnswspool->heap = heapRel;
|
||||
hnswspool->index = indexRel;
|
||||
|
||||
/* Perform inserts */
|
||||
HnswParallelScanAndInsert(hnswspool, hnswshared, false);
|
||||
|
||||
/* Close relations within worker */
|
||||
index_close(indexRel, indexLockmode);
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
table_close(heapRel, heapLockmode);
|
||||
#else
|
||||
heap_close(heapRel, heapLockmode);
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* End parallel build
|
||||
*/
|
||||
static void
|
||||
HnswEndParallel(HnswLeader * hnswleader)
|
||||
{
|
||||
/* Shutdown worker processes */
|
||||
WaitForParallelWorkersToFinish(hnswleader->pcxt);
|
||||
|
||||
/* Free last reference to MVCC snapshot, if one was used */
|
||||
if (IsMVCCSnapshot(hnswleader->snapshot))
|
||||
UnregisterSnapshot(hnswleader->snapshot);
|
||||
DestroyParallelContext(hnswleader->pcxt);
|
||||
ExitParallelMode();
|
||||
}
|
||||
|
||||
/*
|
||||
* Return size of shared memory required for parallel index build
|
||||
*/
|
||||
static Size
|
||||
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
||||
{
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
return add_size(BUFFERALIGN(sizeof(HnswShared)), table_parallelscan_estimate(heap, snapshot));
|
||||
#else
|
||||
if (!IsMVCCSnapshot(snapshot))
|
||||
{
|
||||
Assert(snapshot == SnapshotAny);
|
||||
return sizeof(HnswShared);
|
||||
}
|
||||
|
||||
return add_size(offsetof(HnswShared, heapdesc) +
|
||||
offsetof(ParallelHeapScanDescData, phs_snapshot_data),
|
||||
EstimateSnapshotSpace(snapshot));
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Within leader, participate as a parallel worker
|
||||
*/
|
||||
static void
|
||||
HnswLeaderParticipateAsWorker(HnswBuildState * buildstate)
|
||||
{
|
||||
HnswLeader *hnswleader = buildstate->hnswleader;
|
||||
HnswSpool *leaderworker;
|
||||
|
||||
/* Allocate memory and initialize private spool */
|
||||
leaderworker = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
||||
leaderworker->heap = buildstate->heap;
|
||||
leaderworker->index = buildstate->index;
|
||||
|
||||
/* Perform work common to all participants */
|
||||
HnswParallelScanAndInsert(leaderworker, hnswleader->hnswshared, true);
|
||||
}
|
||||
|
||||
/*
|
||||
* Begin parallel build
|
||||
*/
|
||||
static void
|
||||
HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
||||
{
|
||||
ParallelContext *pcxt;
|
||||
int scantuplesortstates;
|
||||
Snapshot snapshot;
|
||||
Size esthnswshared;
|
||||
HnswShared *hnswshared;
|
||||
HnswLeader *hnswleader = (HnswLeader *) palloc0(sizeof(HnswLeader));
|
||||
bool leaderparticipates = true;
|
||||
int querylen;
|
||||
|
||||
#ifdef DISABLE_LEADER_PARTICIPATION
|
||||
leaderparticipates = false;
|
||||
#endif
|
||||
|
||||
/* Enter parallel mode and create context */
|
||||
EnterParallelMode();
|
||||
Assert(request > 0);
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request);
|
||||
#else
|
||||
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request, true);
|
||||
#endif
|
||||
|
||||
scantuplesortstates = leaderparticipates ? request + 1 : request;
|
||||
|
||||
/* Get snapshot for table scan */
|
||||
if (!isconcurrent)
|
||||
snapshot = SnapshotAny;
|
||||
else
|
||||
snapshot = RegisterSnapshot(GetTransactionSnapshot());
|
||||
|
||||
/* Estimate size of workspaces */
|
||||
esthnswshared = ParallelEstimateShared(buildstate->heap, snapshot);
|
||||
shm_toc_estimate_chunk(&pcxt->estimator, esthnswshared);
|
||||
shm_toc_estimate_keys(&pcxt->estimator, 1);
|
||||
|
||||
/* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
|
||||
if (debug_query_string)
|
||||
{
|
||||
querylen = strlen(debug_query_string);
|
||||
shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
|
||||
shm_toc_estimate_keys(&pcxt->estimator, 1);
|
||||
}
|
||||
else
|
||||
querylen = 0; /* keep compiler quiet */
|
||||
|
||||
/* Everyone's had a chance to ask for space, so now create the DSM */
|
||||
InitializeParallelDSM(pcxt);
|
||||
|
||||
/* If no DSM segment was available, back out (do serial build) */
|
||||
if (pcxt->seg == NULL)
|
||||
{
|
||||
if (IsMVCCSnapshot(snapshot))
|
||||
UnregisterSnapshot(snapshot);
|
||||
DestroyParallelContext(pcxt);
|
||||
ExitParallelMode();
|
||||
return;
|
||||
}
|
||||
|
||||
/* Store shared build state, for which we reserved space */
|
||||
hnswshared = (HnswShared *) shm_toc_allocate(pcxt->toc, esthnswshared);
|
||||
/* Initialize immutable state */
|
||||
hnswshared->heaprelid = RelationGetRelid(buildstate->heap);
|
||||
hnswshared->indexrelid = RelationGetRelid(buildstate->index);
|
||||
hnswshared->isconcurrent = isconcurrent;
|
||||
hnswshared->scantuplesortstates = scantuplesortstates;
|
||||
ConditionVariableInit(&hnswshared->workersdonecv);
|
||||
SpinLockInit(&hnswshared->mutex);
|
||||
/* Initialize mutable state */
|
||||
hnswshared->nparticipantsdone = 0;
|
||||
hnswshared->reltuples = 0;
|
||||
hnswshared->indtuples = 0;
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
table_parallelscan_initialize(buildstate->heap,
|
||||
ParallelTableScanFromHnswShared(hnswshared),
|
||||
snapshot);
|
||||
#else
|
||||
heap_parallelscan_initialize(&hnswshared->heapdesc, buildstate->heap, snapshot);
|
||||
#endif
|
||||
|
||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_SHARED, hnswshared);
|
||||
|
||||
/* Store query string for workers */
|
||||
if (debug_query_string)
|
||||
{
|
||||
char *sharedquery;
|
||||
|
||||
sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
|
||||
memcpy(sharedquery, debug_query_string, querylen + 1);
|
||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
|
||||
}
|
||||
|
||||
/* Launch workers, saving status for leader/caller */
|
||||
LaunchParallelWorkers(pcxt);
|
||||
hnswleader->pcxt = pcxt;
|
||||
hnswleader->nparticipanttuplesorts = pcxt->nworkers_launched;
|
||||
if (leaderparticipates)
|
||||
hnswleader->nparticipanttuplesorts++;
|
||||
hnswleader->hnswshared = hnswshared;
|
||||
hnswleader->snapshot = snapshot;
|
||||
|
||||
/* If no workers were successfully launched, back out (do serial build) */
|
||||
if (pcxt->nworkers_launched == 0)
|
||||
{
|
||||
HnswEndParallel(hnswleader);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Log participants */
|
||||
ereport(DEBUG1, (errmsg("using %d parallel workers", pcxt->nworkers_launched)));
|
||||
|
||||
/* Save leader state now that it's clear build will be parallel */
|
||||
buildstate->hnswleader = hnswleader;
|
||||
|
||||
/* Join heap scan ourselves */
|
||||
if (leaderparticipates)
|
||||
HnswLeaderParticipateAsWorker(buildstate);
|
||||
|
||||
/* Wait for all launched workers */
|
||||
WaitForParallelWorkersToAttach(pcxt);
|
||||
}
|
||||
|
||||
/*
|
||||
* Build graph
|
||||
*/
|
||||
static void
|
||||
BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
||||
{
|
||||
int parallel_workers = 0;
|
||||
|
||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
||||
|
||||
/* Calculate parallel workers */
|
||||
if (hnsw_enable_parallel_build)
|
||||
parallel_workers = plan_create_index_workers(RelationGetRelid(buildstate->heap), RelationGetRelid(buildstate->index));
|
||||
|
||||
/* Attempt to launch parallel worker scan when required */
|
||||
if (parallel_workers > 0)
|
||||
{
|
||||
/* TODO Support in-memory builds */
|
||||
FlushPages(buildstate);
|
||||
HnswBeginParallel(buildstate, buildstate->indexInfo->ii_Concurrent, parallel_workers);
|
||||
}
|
||||
|
||||
/* Add tuples to sort */
|
||||
if (buildstate->hnswleader)
|
||||
buildstate->reltuples = ParallelHeapScan(buildstate);
|
||||
else
|
||||
{
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||
true, true, BuildCallback, (void *) buildstate, NULL);
|
||||
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||
true, true, BuildCallback, (void *) buildstate, NULL);
|
||||
#else
|
||||
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||
true, BuildCallback, (void *) buildstate, NULL);
|
||||
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||
true, BuildCallback, (void *) buildstate, NULL);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* End parallel build */
|
||||
if (buildstate->hnswleader)
|
||||
HnswEndParallel(buildstate->hnswleader);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -123,6 +123,7 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
||||
Size minCombinedSize;
|
||||
HnswElementTuple etup;
|
||||
BlockNumber currentPage = insertPage;
|
||||
int dimensions = e->vec->dim;
|
||||
HnswNeighborTuple ntup;
|
||||
Buffer nbuf;
|
||||
Page npage;
|
||||
@@ -131,10 +132,10 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||
|
||||
/* Calculate sizes */
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(DatumGetPointer(e->value)));
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||
maxSize = HNSW_MAX_SIZE;
|
||||
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||
minCombinedSize = etupSize + HNSW_NEIGHBOR_TUPLE_SIZE(0, m) + sizeof(ItemIdData);
|
||||
|
||||
/* Prepare element tuple */
|
||||
@@ -201,6 +202,8 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
||||
HnswInsertAppendPage(index, &newbuf, &newpage, state, page);
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(newbuf);
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
|
||||
/* Unlock previous buffer */
|
||||
@@ -267,6 +270,9 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
||||
}
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
if (nbuf != buf)
|
||||
MarkBufferDirty(nbuf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
if (nbuf != buf)
|
||||
@@ -385,6 +391,7 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
}
|
||||
else
|
||||
@@ -404,9 +411,8 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
||||
Buffer buf;
|
||||
Page page;
|
||||
GenericXLogState *state;
|
||||
ItemId itemid;
|
||||
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(dup->vec->dim);
|
||||
HnswElementTuple etup;
|
||||
Size etupSize;
|
||||
int i;
|
||||
|
||||
/* Read page */
|
||||
@@ -416,9 +422,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||
|
||||
/* Find space */
|
||||
itemid = PageGetItemId(page, dup->offno);
|
||||
etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||
etupSize = ItemIdGetLength(itemid);
|
||||
etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, dup->offno));
|
||||
for (i = 0; i < HNSW_HEAPTIDS; i++)
|
||||
{
|
||||
if (!ItemPointerIsValid(&etup->heaptids[i]))
|
||||
@@ -441,6 +445,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
@@ -517,7 +522,7 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
||||
|
||||
/* Create an element */
|
||||
element = HnswInitElement(heap_tid, m, HnswGetMl(m), HnswGetMaxLevel(m));
|
||||
element->value = value;
|
||||
element->vec = DatumGetVector(value);
|
||||
|
||||
/* Prevent concurrent inserts when likely updating entry point */
|
||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||
|
||||
@@ -113,6 +113,12 @@ hnswbeginscan(Relation index, int nkeys, int norderbys)
|
||||
|
||||
scan->opaque = so;
|
||||
|
||||
/*
|
||||
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
||||
* before marking tuples as deleted.
|
||||
*/
|
||||
LockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||
|
||||
return scan;
|
||||
}
|
||||
|
||||
@@ -160,25 +166,11 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
if (scan->orderByData == NULL)
|
||||
elog(ERROR, "cannot scan hnsw index without order");
|
||||
|
||||
/* Requires MVCC-compliant snapshot as not able to maintain a pin */
|
||||
/* https://www.postgresql.org/docs/current/index-locking.html */
|
||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
||||
elog(ERROR, "non-MVCC snapshots are not supported with hnsw");
|
||||
|
||||
/* Get scan value */
|
||||
value = GetScanValue(scan);
|
||||
|
||||
/*
|
||||
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
||||
* before marking tuples as deleted.
|
||||
*/
|
||||
LockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||
|
||||
so->w = GetScanItems(scan, value);
|
||||
|
||||
/* Release shared lock */
|
||||
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||
|
||||
so->first = false;
|
||||
}
|
||||
|
||||
@@ -206,6 +198,15 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
scan->xs_ctup.t_self = *heaptid;
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Typically, an index scan must maintain a pin on the index page
|
||||
* holding the item last returned by amgettuple. However, this is not
|
||||
* needed with the current vacuum strategy, which ensures scans do not
|
||||
* visit tuples in danger of being marked as deleted.
|
||||
*
|
||||
* https://www.postgresql.org/docs/current/index-locking.html
|
||||
*/
|
||||
|
||||
scan->xs_recheckorderby = false;
|
||||
return true;
|
||||
}
|
||||
@@ -222,6 +223,9 @@ hnswendscan(IndexScanDesc scan)
|
||||
{
|
||||
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
||||
|
||||
/* Release shared lock */
|
||||
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||
|
||||
MemoryContextDelete(so->tmpCtx);
|
||||
|
||||
pfree(so);
|
||||
|
||||
166
src/hnswutils.c
166
src/hnswutils.c
@@ -4,7 +4,6 @@
|
||||
|
||||
#include "hnsw.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "utils/datum.h"
|
||||
#include "vector.h"
|
||||
|
||||
/*
|
||||
@@ -39,12 +38,12 @@ HnswGetEfConstruction(Relation index)
|
||||
* Get proc
|
||||
*/
|
||||
FmgrInfo *
|
||||
HnswOptionalProcInfo(Relation index, uint16 procnum)
|
||||
HnswOptionalProcInfo(Relation rel, uint16 procnum)
|
||||
{
|
||||
if (!OidIsValid(index_getprocid(index, 1, procnum)))
|
||||
if (!OidIsValid(index_getprocid(rel, 1, procnum)))
|
||||
return NULL;
|
||||
|
||||
return index_getprocinfo(index, 1, procnum);
|
||||
return index_getprocinfo(rel, 1, procnum);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -118,6 +117,7 @@ HnswInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState *
|
||||
void
|
||||
HnswCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||
{
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
@@ -140,21 +140,9 @@ HnswInitNeighbors(HnswElement element, int m)
|
||||
a = &element->neighbors[lc];
|
||||
a->length = 0;
|
||||
a->items = palloc(sizeof(HnswCandidate) * lm);
|
||||
a->closerSet = false;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Free neighbors
|
||||
*/
|
||||
static void
|
||||
HnswFreeNeighbors(HnswElement element)
|
||||
{
|
||||
for (int lc = 0; lc <= element->level; lc++)
|
||||
pfree(element->neighbors[lc].items);
|
||||
pfree(element->neighbors);
|
||||
}
|
||||
|
||||
/*
|
||||
* Allocate an element
|
||||
*/
|
||||
@@ -177,8 +165,6 @@ HnswInitElement(ItemPointer heaptid, int m, double ml, int maxLevel)
|
||||
|
||||
HnswInitNeighbors(element, m);
|
||||
|
||||
element->value = PointerGetDatum(NULL);
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
@@ -188,10 +174,11 @@ HnswInitElement(ItemPointer heaptid, int m, double ml, int maxLevel)
|
||||
void
|
||||
HnswFreeElement(HnswElement element)
|
||||
{
|
||||
HnswFreeNeighbors(element);
|
||||
list_free_deep(element->heaptids);
|
||||
if (DatumGetPointer(element->value))
|
||||
pfree(DatumGetPointer(element->value));
|
||||
for (int lc = 0; lc <= element->level; lc++)
|
||||
pfree(element->neighbors[lc].items);
|
||||
pfree(element->neighbors);
|
||||
pfree(element->vec);
|
||||
pfree(element);
|
||||
}
|
||||
|
||||
@@ -218,7 +205,7 @@ HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno)
|
||||
element->blkno = blkno;
|
||||
element->offno = offno;
|
||||
element->neighbors = NULL;
|
||||
element->value = PointerGetDatum(NULL);
|
||||
element->vec = NULL;
|
||||
return element;
|
||||
}
|
||||
|
||||
@@ -328,7 +315,7 @@ HnswSetElementTuple(HnswElementTuple etup, HnswElement element)
|
||||
else
|
||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||
}
|
||||
memcpy(&etup->data, DatumGetPointer(element->value), VARSIZE_ANY(DatumGetPointer(element->value)));
|
||||
memcpy(&etup->vec, element->vec, VECTOR_SIZE(element->vec->dim));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -450,7 +437,10 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
||||
}
|
||||
|
||||
if (loadVec)
|
||||
element->value = datumCopy(PointerGetDatum(&etup->data), false, -1);
|
||||
{
|
||||
element->vec = palloc(VECTOR_SIZE(etup->vec.dim));
|
||||
memcpy(element->vec, &etup->vec, VECTOR_SIZE(etup->vec.dim));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -477,7 +467,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
||||
|
||||
/* Calculate distance */
|
||||
if (distance != NULL)
|
||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->data)));
|
||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->vec)));
|
||||
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
@@ -488,7 +478,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
||||
static float
|
||||
GetCandidateDistance(HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
||||
{
|
||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, hc->element->value));
|
||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, PointerGetDatum(hc->element->vec)));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -694,34 +684,6 @@ HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *pro
|
||||
return w;
|
||||
}
|
||||
|
||||
/*
|
||||
* Compare candidate distances
|
||||
*/
|
||||
static int
|
||||
#if PG_VERSION_NUM >= 130000
|
||||
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
||||
#else
|
||||
CompareCandidateDistances(const void *a, const void *b)
|
||||
#endif
|
||||
{
|
||||
HnswCandidate *hca = lfirst((ListCell *) a);
|
||||
HnswCandidate *hcb = lfirst((ListCell *) b);
|
||||
|
||||
if (hca->distance < hcb->distance)
|
||||
return 1;
|
||||
|
||||
if (hca->distance > hcb->distance)
|
||||
return -1;
|
||||
|
||||
if (hca->element < hcb->element)
|
||||
return 1;
|
||||
|
||||
if (hca->element > hcb->element)
|
||||
return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate the distance between elements
|
||||
*/
|
||||
@@ -751,7 +713,7 @@ HnswGetDistance(HnswElement a, HnswElement b, int lc, FmgrInfo *procinfo, Oid co
|
||||
}
|
||||
}
|
||||
|
||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, a->value, b->value));
|
||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(a->vec), PointerGetDatum(b->vec)));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -778,77 +740,33 @@ CheckElementCloser(HnswCandidate * e, List *r, int lc, FmgrInfo *procinfo, Oid c
|
||||
* Algorithm 4 from paper
|
||||
*/
|
||||
static List *
|
||||
SelectNeighbors(List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswElement e2, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
||||
SelectNeighbors(List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswCandidate * *pruned)
|
||||
{
|
||||
List *r = NIL;
|
||||
List *w = list_copy(c);
|
||||
pairingheap *wd;
|
||||
bool mustCalculate = !e2->neighbors[lc].closerSet;
|
||||
List *added = NIL;
|
||||
bool removedAny = false;
|
||||
|
||||
if (list_length(w) <= m)
|
||||
return w;
|
||||
|
||||
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||
|
||||
/* Ensure order of candidates is deterministic for closer caching */
|
||||
if (sortCandidates)
|
||||
list_sort(w, CompareCandidateDistances);
|
||||
|
||||
while (list_length(w) > 0 && list_length(r) < m)
|
||||
{
|
||||
/* Assumes w is already ordered desc */
|
||||
HnswCandidate *e = llast(w);
|
||||
bool closer;
|
||||
|
||||
w = list_delete_last(w);
|
||||
|
||||
/* Use previous state of r and wd to skip work when possible */
|
||||
if (mustCalculate)
|
||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
||||
else if (list_length(added) > 0)
|
||||
{
|
||||
/*
|
||||
* If the current candidate was closer, we only need to compare it
|
||||
* with the other candidates that we have added.
|
||||
*/
|
||||
if (e->closer)
|
||||
{
|
||||
e->closer = CheckElementCloser(e, added, lc, procinfo, collation);
|
||||
closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
||||
|
||||
if (!e->closer)
|
||||
removedAny = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
/*
|
||||
* If we have removed any candidates from closer, a candidate
|
||||
* that was not closer earlier might now be.
|
||||
*/
|
||||
if (removedAny)
|
||||
{
|
||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
||||
if (e->closer)
|
||||
added = lappend(added, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (e == newCandidate)
|
||||
{
|
||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
||||
if (e->closer)
|
||||
added = lappend(added, e);
|
||||
}
|
||||
|
||||
if (e->closer)
|
||||
if (closer)
|
||||
r = lappend(r, e);
|
||||
else
|
||||
pairingheap_add(wd, &(CreatePairingHeapNode(e)->ph_node));
|
||||
}
|
||||
|
||||
/* Cached value can only be used in future if sorted deterministically */
|
||||
e2->neighbors[lc].closerSet = sortCandidates;
|
||||
|
||||
/* Keep pruned connections */
|
||||
while (!pairingheap_is_empty(wd) && list_length(r) < m)
|
||||
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
||||
@@ -878,7 +796,7 @@ HnswFindDuplicate(HnswElement e)
|
||||
HnswCandidate *neighbor = &neighbors->items[i];
|
||||
|
||||
/* Exit early since ordered by distance */
|
||||
if (!datumIsEqual(e->value, neighbor->element->value, false, -1))
|
||||
if (vector_cmp_internal(e->vec, neighbor->element->vec) != 0)
|
||||
break;
|
||||
|
||||
/* Check for space */
|
||||
@@ -902,6 +820,28 @@ AddConnections(HnswElement element, List *neighbors, int m, int lc)
|
||||
a->items[a->length++] = *((HnswCandidate *) lfirst(lc2));
|
||||
}
|
||||
|
||||
/*
|
||||
* Compare candidate distances
|
||||
*/
|
||||
static int
|
||||
#if PG_VERSION_NUM >= 130000
|
||||
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
||||
#else
|
||||
CompareCandidateDistances(const void *a, const void *b)
|
||||
#endif
|
||||
{
|
||||
HnswCandidate *hca = lfirst((ListCell *) a);
|
||||
HnswCandidate *hcb = lfirst((ListCell *) b);
|
||||
|
||||
if (hca->distance < hcb->distance)
|
||||
return 1;
|
||||
|
||||
if (hca->distance > hcb->distance)
|
||||
return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Update connections
|
||||
*/
|
||||
@@ -931,13 +871,13 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
||||
/* Load elements on insert */
|
||||
if (index != NULL)
|
||||
{
|
||||
Datum q = hc->element->value;
|
||||
Datum q = PointerGetDatum(hc->element->vec);
|
||||
|
||||
for (int i = 0; i < currentNeighbors->length; i++)
|
||||
{
|
||||
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
||||
|
||||
if (DatumGetPointer(hc3->element->value) == NULL)
|
||||
if (hc3->element->vec == NULL)
|
||||
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
||||
else
|
||||
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
||||
@@ -955,12 +895,13 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
||||
{
|
||||
List *c = NIL;
|
||||
|
||||
/* Add candidates */
|
||||
/* Add and sort candidates */
|
||||
for (int i = 0; i < currentNeighbors->length; i++)
|
||||
c = lappend(c, ¤tNeighbors->items[i]);
|
||||
c = lappend(c, &hc2);
|
||||
list_sort(c, CompareCandidateDistances);
|
||||
|
||||
SelectNeighbors(c, m, lc, procinfo, collation, hc->element, &hc2, &pruned, true);
|
||||
SelectNeighbors(c, m, lc, procinfo, collation, &pruned);
|
||||
|
||||
/* Should not happen */
|
||||
if (pruned == NULL)
|
||||
@@ -1018,7 +959,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
||||
List *w;
|
||||
int level = element->level;
|
||||
int entryLevel;
|
||||
Datum q = element->value;
|
||||
Datum q = PointerGetDatum(element->vec);
|
||||
HnswElement skipElement = existing ? element : NULL;
|
||||
|
||||
/* No neighbors if no entry point */
|
||||
@@ -1059,12 +1000,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
||||
else
|
||||
lw = w;
|
||||
|
||||
/*
|
||||
* Candidates are sorted, but not deterministically. Could set
|
||||
* sortCandidates to true for in-memory builds to enable closer
|
||||
* caching, but there does not seem to be a difference in performance.
|
||||
*/
|
||||
neighbors = SelectNeighbors(lw, lm, lc, procinfo, collation, element, NULL, NULL, false);
|
||||
neighbors = SelectNeighbors(lw, lm, lc, procinfo, collation, NULL);
|
||||
|
||||
AddConnections(element, neighbors, lm, lc);
|
||||
|
||||
|
||||
@@ -62,8 +62,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
||||
/* Iterate over nodes */
|
||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||
{
|
||||
ItemId itemid = PageGetItemId(page, offno);
|
||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||
int idx = 0;
|
||||
bool itemUpdated = false;
|
||||
|
||||
@@ -94,7 +93,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
||||
|
||||
if (itemUpdated)
|
||||
{
|
||||
Size etupSize = ItemIdGetLength(itemid);
|
||||
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
||||
|
||||
/* Mark rest as invalid */
|
||||
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
||||
@@ -129,7 +128,10 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
||||
blkno = HnswPageGetOpaque(page)->nextblkno;
|
||||
|
||||
if (updated)
|
||||
{
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
}
|
||||
else
|
||||
GenericXLogAbort(state);
|
||||
|
||||
@@ -227,6 +229,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
@@ -478,8 +481,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
/* Update element and neighbors together */
|
||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||
{
|
||||
ItemId itemid = PageGetItemId(page, offno);
|
||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||
HnswNeighborTuple ntup;
|
||||
Size etupSize;
|
||||
Size ntupSize;
|
||||
@@ -507,7 +509,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
continue;
|
||||
|
||||
/* Calculate sizes */
|
||||
etupSize = ItemIdGetLength(itemid);
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
||||
|
||||
/* Get neighbor page */
|
||||
@@ -530,7 +532,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
|
||||
/* Overwrite element */
|
||||
etup->deleted = 1;
|
||||
MemSet(&etup->data, 0, VARSIZE_ANY(&etup->data));
|
||||
MemSet(&etup->vec.x, 0, etup->vec.dim * sizeof(float));
|
||||
|
||||
/* Overwrite neighbors */
|
||||
for (int i = 0; i < ntup->count; i++)
|
||||
@@ -545,6 +547,9 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(buf);
|
||||
if (nbuf != buf)
|
||||
MarkBufferDirty(nbuf);
|
||||
GenericXLogFinish(state);
|
||||
if (nbuf != buf)
|
||||
UnlockReleaseBuffer(nbuf);
|
||||
|
||||
@@ -506,30 +506,29 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
||||
Buffer buf;
|
||||
Page page;
|
||||
GenericXLogState *state;
|
||||
Size listSize;
|
||||
OffsetNumber offno;
|
||||
Size itemsz;
|
||||
IvfflatList list;
|
||||
|
||||
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
||||
list = palloc(listSize);
|
||||
itemsz = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
||||
list = palloc(itemsz);
|
||||
|
||||
buf = IvfflatNewBuffer(index, forkNum);
|
||||
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
||||
|
||||
for (int i = 0; i < lists; i++)
|
||||
{
|
||||
OffsetNumber offno;
|
||||
|
||||
/* Load list */
|
||||
list->startPage = InvalidBlockNumber;
|
||||
list->insertPage = InvalidBlockNumber;
|
||||
memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
|
||||
|
||||
/* Ensure free space */
|
||||
if (PageGetFreeSpace(page) < listSize)
|
||||
if (PageGetFreeSpace(page) < itemsz)
|
||||
IvfflatAppendPage(index, &buf, &page, &state, forkNum);
|
||||
|
||||
/* Add the item */
|
||||
offno = PageAddItem(page, (Item) list, listSize, InvalidOffsetNumber, false, false);
|
||||
offno = PageAddItem(page, (Item) list, itemsz, InvalidOffsetNumber, false, false);
|
||||
if (offno == InvalidOffsetNumber)
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
#define IVFFLAT_METAPAGE_BLKNO 0
|
||||
#define IVFFLAT_HEAD_BLKNO 1 /* first list page */
|
||||
|
||||
/* Must correspond to page numbers since page lock is used */
|
||||
#define IVFFLAT_SCAN_LOCK 0
|
||||
|
||||
/* IVFFlat parameters */
|
||||
#define IVFFLAT_DEFAULT_LISTS 100
|
||||
#define IVFFLAT_MIN_LISTS 1
|
||||
@@ -246,6 +249,9 @@ typedef struct IvfflatScanOpaqueData
|
||||
int probes;
|
||||
int dimensions;
|
||||
bool first;
|
||||
bool hasLock;
|
||||
Buffer buf;
|
||||
ItemPointerData heaptid;
|
||||
|
||||
/* Sorting */
|
||||
Tuplesortstate *sortstate;
|
||||
@@ -275,7 +281,7 @@ VectorArray VectorArrayInit(int maxlen, int dimensions);
|
||||
void VectorArrayFree(VectorArray arr);
|
||||
void PrintVectorArray(char *msg, VectorArray arr);
|
||||
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
||||
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
||||
FmgrInfo *IvfflatOptionalProcInfo(Relation rel, uint16 procnum);
|
||||
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||
int IvfflatGetLists(Relation index);
|
||||
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
||||
|
||||
@@ -11,37 +11,36 @@
|
||||
* Find the list that minimizes the distance function
|
||||
*/
|
||||
static void
|
||||
FindInsertPage(Relation index, Datum *values, BlockNumber *insertPage, ListInfo * listInfo)
|
||||
FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo * listInfo)
|
||||
{
|
||||
Buffer cbuf;
|
||||
Page cpage;
|
||||
IvfflatList list;
|
||||
double distance;
|
||||
double minDistance = DBL_MAX;
|
||||
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
||||
FmgrInfo *procinfo;
|
||||
Oid collation;
|
||||
OffsetNumber offno;
|
||||
OffsetNumber maxoffno;
|
||||
|
||||
/* Avoid compiler warning */
|
||||
listInfo->blkno = nextblkno;
|
||||
listInfo->offno = FirstOffsetNumber;
|
||||
|
||||
procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
|
||||
collation = index->rd_indcollation[0];
|
||||
procinfo = index_getprocinfo(rel, 1, IVFFLAT_DISTANCE_PROC);
|
||||
collation = rel->rd_indcollation[0];
|
||||
|
||||
/* Search all list pages */
|
||||
while (BlockNumberIsValid(nextblkno))
|
||||
{
|
||||
Buffer cbuf;
|
||||
Page cpage;
|
||||
OffsetNumber maxoffno;
|
||||
|
||||
cbuf = ReadBuffer(index, nextblkno);
|
||||
cbuf = ReadBuffer(rel, nextblkno);
|
||||
LockBuffer(cbuf, BUFFER_LOCK_SHARE);
|
||||
cpage = BufferGetPage(cbuf);
|
||||
maxoffno = PageGetMaxOffsetNumber(cpage);
|
||||
|
||||
for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||
{
|
||||
IvfflatList list;
|
||||
double distance;
|
||||
|
||||
list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
|
||||
distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum(&list->center)));
|
||||
|
||||
@@ -64,7 +63,7 @@ FindInsertPage(Relation index, Datum *values, BlockNumber *insertPage, ListInfo
|
||||
* Insert a tuple into the index
|
||||
*/
|
||||
static void
|
||||
InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
||||
InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
||||
{
|
||||
IndexTuple itup;
|
||||
Datum value;
|
||||
@@ -81,33 +80,33 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
||||
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||
|
||||
/* Normalize if needed */
|
||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
||||
normprocinfo = IvfflatOptionalProcInfo(rel, IVFFLAT_NORM_PROC);
|
||||
if (normprocinfo != NULL)
|
||||
{
|
||||
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, NULL))
|
||||
if (!IvfflatNormValue(normprocinfo, rel->rd_indcollation[0], &value, NULL))
|
||||
return;
|
||||
}
|
||||
|
||||
/* Find the insert page - sets the page and list info */
|
||||
FindInsertPage(index, values, &insertPage, &listInfo);
|
||||
FindInsertPage(rel, values, &insertPage, &listInfo);
|
||||
Assert(BlockNumberIsValid(insertPage));
|
||||
originalInsertPage = insertPage;
|
||||
|
||||
/* Form tuple */
|
||||
itup = index_form_tuple(RelationGetDescr(index), &value, isnull);
|
||||
itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
|
||||
itup->t_tid = *heap_tid;
|
||||
|
||||
/* Get tuple size */
|
||||
itemsz = MAXALIGN(IndexTupleSize(itup));
|
||||
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)) - sizeof(ItemIdData));
|
||||
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
|
||||
|
||||
/* Find a page to insert the item */
|
||||
for (;;)
|
||||
{
|
||||
buf = ReadBuffer(index, insertPage);
|
||||
buf = ReadBuffer(rel, insertPage);
|
||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||
|
||||
state = GenericXLogStart(index);
|
||||
state = GenericXLogStart(rel);
|
||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||
|
||||
if (PageGetFreeSpace(page) >= itemsz)
|
||||
@@ -127,9 +126,9 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
||||
Page newpage;
|
||||
|
||||
/* Add a new page */
|
||||
LockRelationForExtension(index, ExclusiveLock);
|
||||
newbuf = IvfflatNewBuffer(index, MAIN_FORKNUM);
|
||||
UnlockRelationForExtension(index, ExclusiveLock);
|
||||
LockRelationForExtension(rel, ExclusiveLock);
|
||||
newbuf = IvfflatNewBuffer(rel, MAIN_FORKNUM);
|
||||
UnlockRelationForExtension(rel, ExclusiveLock);
|
||||
|
||||
/* Init new page */
|
||||
newpage = GenericXLogRegisterBuffer(state, newbuf, GENERIC_XLOG_FULL_IMAGE);
|
||||
@@ -142,13 +141,15 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
||||
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(newbuf);
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
|
||||
/* Unlock previous buffer */
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
/* Prepare new buffer */
|
||||
state = GenericXLogStart(index);
|
||||
state = GenericXLogStart(rel);
|
||||
buf = newbuf;
|
||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||
break;
|
||||
@@ -157,13 +158,13 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
||||
|
||||
/* Add to next offset */
|
||||
if (PageAddItem(page, (Item) itup, itemsz, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(rel));
|
||||
|
||||
IvfflatCommitBuffer(buf, state);
|
||||
|
||||
/* Update the insert page */
|
||||
if (insertPage != originalInsertPage)
|
||||
IvfflatUpdateList(index, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
IvfflatUpdateList(rel, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -17,6 +17,10 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
||||
FmgrInfo *procinfo;
|
||||
Oid collation;
|
||||
int64 j;
|
||||
double distance;
|
||||
double sum;
|
||||
double choice;
|
||||
Vector *vec;
|
||||
float *weight = palloc(samples->length * sizeof(float));
|
||||
int numCenters = centers->maxlen;
|
||||
int numSamples = samples->length;
|
||||
@@ -29,21 +33,17 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
||||
centers->length++;
|
||||
|
||||
for (j = 0; j < numSamples; j++)
|
||||
weight[j] = FLT_MAX;
|
||||
weight[j] = DBL_MAX;
|
||||
|
||||
for (int i = 0; i < numCenters; i++)
|
||||
{
|
||||
double sum;
|
||||
double choice;
|
||||
|
||||
CHECK_FOR_INTERRUPTS();
|
||||
|
||||
sum = 0.0;
|
||||
|
||||
for (j = 0; j < numSamples; j++)
|
||||
{
|
||||
Vector *vec = VectorArrayGet(samples, j);
|
||||
double distance;
|
||||
vec = VectorArrayGet(samples, j);
|
||||
|
||||
/* Only need to compute distance for new center */
|
||||
/* TODO Use triangle inequality to reduce distance calculations */
|
||||
@@ -112,6 +112,7 @@ CompareVectors(const void *a, const void *b)
|
||||
static void
|
||||
QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
||||
{
|
||||
Vector *vec;
|
||||
int dimensions = centers->dim;
|
||||
Oid collation = index->rd_indcollation[0];
|
||||
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||
@@ -122,7 +123,7 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
||||
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
||||
for (int i = 0; i < samples->length; i++)
|
||||
{
|
||||
Vector *vec = VectorArrayGet(samples, i);
|
||||
vec = VectorArrayGet(samples, i);
|
||||
|
||||
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
||||
{
|
||||
@@ -135,7 +136,7 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
||||
/* Fill remaining with random data */
|
||||
while (centers->length < centers->maxlen)
|
||||
{
|
||||
Vector *vec = VectorArrayGet(centers, centers->length);
|
||||
vec = VectorArrayGet(centers, centers->length);
|
||||
|
||||
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
||||
vec->dim = dimensions;
|
||||
@@ -167,6 +168,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
Oid collation;
|
||||
Vector *vec;
|
||||
Vector *newCenter;
|
||||
int iteration;
|
||||
int64 j;
|
||||
int64 k;
|
||||
int dimensions = centers->dim;
|
||||
@@ -180,6 +182,14 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
float *s;
|
||||
float *halfcdist;
|
||||
float *newcdist;
|
||||
int changes;
|
||||
double minDistance;
|
||||
int closestCenter;
|
||||
double distance;
|
||||
bool rj;
|
||||
bool rjreset;
|
||||
double dxcx;
|
||||
double dxc;
|
||||
|
||||
/* Calculate allocation sizes */
|
||||
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
|
||||
@@ -237,14 +247,14 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
/* Assign each x to its closest initial center c(x) = argmin d(x,c) */
|
||||
for (j = 0; j < numSamples; j++)
|
||||
{
|
||||
float minDistance = FLT_MAX;
|
||||
int closestCenter = 0;
|
||||
minDistance = DBL_MAX;
|
||||
closestCenter = 0;
|
||||
|
||||
/* Find closest center */
|
||||
for (k = 0; k < numCenters; k++)
|
||||
{
|
||||
/* TODO Use Lemma 1 in k-means++ initialization */
|
||||
float distance = lowerBound[j * numCenters + k];
|
||||
distance = lowerBound[j * numCenters + k];
|
||||
|
||||
if (distance < minDistance)
|
||||
{
|
||||
@@ -258,14 +268,13 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
}
|
||||
|
||||
/* Give 500 iterations to converge */
|
||||
for (int iteration = 0; iteration < 500; iteration++)
|
||||
for (iteration = 0; iteration < 500; iteration++)
|
||||
{
|
||||
int changes = 0;
|
||||
bool rjreset;
|
||||
|
||||
/* Can take a while, so ensure we can interrupt */
|
||||
CHECK_FOR_INTERRUPTS();
|
||||
|
||||
changes = 0;
|
||||
|
||||
/* Step 1: For all centers, compute distance */
|
||||
for (j = 0; j < numCenters; j++)
|
||||
{
|
||||
@@ -273,8 +282,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
for (k = j + 1; k < numCenters; k++)
|
||||
{
|
||||
float distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||
|
||||
distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||
halfcdist[j * numCenters + k] = distance;
|
||||
halfcdist[k * numCenters + j] = distance;
|
||||
}
|
||||
@@ -283,12 +291,10 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
/* For all centers c, compute s(c) */
|
||||
for (j = 0; j < numCenters; j++)
|
||||
{
|
||||
float minDistance = FLT_MAX;
|
||||
minDistance = DBL_MAX;
|
||||
|
||||
for (k = 0; k < numCenters; k++)
|
||||
{
|
||||
float distance;
|
||||
|
||||
if (j == k)
|
||||
continue;
|
||||
|
||||
@@ -304,8 +310,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
for (j = 0; j < numSamples; j++)
|
||||
{
|
||||
bool rj;
|
||||
|
||||
/* Step 2: Identify all points x such that u(x) <= s(c(x)) */
|
||||
if (upperBound[j] <= s[closestCenters[j]])
|
||||
continue;
|
||||
@@ -314,8 +318,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
for (k = 0; k < numCenters; k++)
|
||||
{
|
||||
float dxcx;
|
||||
|
||||
/* Step 3: For all remaining points x and centers c */
|
||||
if (k == closestCenters[j])
|
||||
continue;
|
||||
@@ -345,7 +347,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
/* Step 3b */
|
||||
if (dxcx > lowerBound[j * numCenters + k] || dxcx > halfcdist[closestCenters[j] * numCenters + k])
|
||||
{
|
||||
float dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||
dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||
|
||||
/* d(x,c) calculated */
|
||||
lowerBound[j * numCenters + k] = dxc;
|
||||
@@ -359,6 +361,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
changes++;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -375,8 +378,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
for (j = 0; j < numSamples; j++)
|
||||
{
|
||||
int closestCenter;
|
||||
|
||||
vec = VectorArrayGet(samples, j);
|
||||
closestCenter = closestCenters[j];
|
||||
|
||||
@@ -425,7 +426,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
{
|
||||
for (k = 0; k < numCenters; k++)
|
||||
{
|
||||
float distance = lowerBound[j * numCenters + k] - newcdist[k];
|
||||
distance = lowerBound[j * numCenters + k] - newcdist[k];
|
||||
|
||||
if (distance < 0)
|
||||
distance = 0;
|
||||
@@ -441,7 +442,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
|
||||
/* Step 7 */
|
||||
for (j = 0; j < numCenters; j++)
|
||||
VectorArraySet(centers, j, VectorArrayGet(newCenters, j));
|
||||
memcpy(VectorArrayGet(centers, j), VectorArrayGet(newCenters, j), VECTOR_SIZE(dimensions));
|
||||
|
||||
if (changes == 0 && iteration != 0)
|
||||
break;
|
||||
@@ -464,6 +465,9 @@ static void
|
||||
CheckCenters(Relation index, VectorArray centers)
|
||||
{
|
||||
FmgrInfo *normprocinfo;
|
||||
Oid collation;
|
||||
Vector *vec;
|
||||
double norm;
|
||||
|
||||
if (centers->length != centers->maxlen)
|
||||
elog(ERROR, "Not enough centers. Please report a bug.");
|
||||
@@ -471,7 +475,7 @@ CheckCenters(Relation index, VectorArray centers)
|
||||
/* Ensure no NaN or infinite values */
|
||||
for (int i = 0; i < centers->length; i++)
|
||||
{
|
||||
Vector *vec = VectorArrayGet(centers, i);
|
||||
vec = VectorArrayGet(centers, i);
|
||||
|
||||
for (int j = 0; j < vec->dim; j++)
|
||||
{
|
||||
@@ -497,12 +501,11 @@ CheckCenters(Relation index, VectorArray centers)
|
||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
||||
if (normprocinfo != NULL)
|
||||
{
|
||||
Oid collation = index->rd_indcollation[0];
|
||||
collation = index->rd_indcollation[0];
|
||||
|
||||
for (int i = 0; i < centers->length; i++)
|
||||
{
|
||||
double norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, PointerGetDatum(VectorArrayGet(centers, i))));
|
||||
|
||||
norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, PointerGetDatum(VectorArrayGet(centers, i))));
|
||||
if (norm == 0)
|
||||
elog(ERROR, "Zero norm detected. Please report a bug.");
|
||||
}
|
||||
|
||||
105
src/ivfscan.c
105
src/ivfscan.c
@@ -9,6 +9,7 @@
|
||||
#include "miscadmin.h"
|
||||
#include "pgstat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
|
||||
/*
|
||||
* Compare list distances
|
||||
@@ -143,6 +144,10 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
||||
bool isnull;
|
||||
ItemId itemid = PageGetItemId(page, offno);
|
||||
|
||||
/* Skip dead tuples */
|
||||
if (scan->ignore_killed_tuples && ItemIdIsDead(itemid))
|
||||
continue;
|
||||
|
||||
itup = (IndexTuple) PageGetItem(page, itemid);
|
||||
datum = index_getattr(itup, 1, tupdesc, &isnull);
|
||||
|
||||
@@ -157,6 +162,8 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
||||
slot->tts_isnull[0] = false;
|
||||
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
|
||||
slot->tts_isnull[1] = false;
|
||||
slot->tts_values[2] = Int32GetDatum((int) searchPage);
|
||||
slot->tts_isnull[2] = false;
|
||||
ExecStoreVirtualTuple(slot);
|
||||
|
||||
tuplesort_puttupleslot(so->sortstate, slot);
|
||||
@@ -181,6 +188,55 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
||||
tuplesort_performsort(so->sortstate);
|
||||
}
|
||||
|
||||
/*
|
||||
* Mark prior tuple as dead
|
||||
*/
|
||||
static void
|
||||
MarkPriorTupleDead(IndexScanDesc scan)
|
||||
{
|
||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||
Buffer buf = so->buf;
|
||||
Page page;
|
||||
OffsetNumber maxoffno;
|
||||
|
||||
/* Safety check */
|
||||
if (!BufferIsValid(so->buf) || !ItemPointerIsValid(&so->heaptid))
|
||||
return;
|
||||
|
||||
/* Only a shared locked is needed for ItemIdMarkDead */
|
||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||
page = BufferGetPage(buf);
|
||||
maxoffno = PageGetMaxOffsetNumber(page);
|
||||
|
||||
for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||
{
|
||||
ItemId itemid = PageGetItemId(page, offno);
|
||||
IndexTuple itup = (IndexTuple) PageGetItem(page, itemid);
|
||||
|
||||
/*
|
||||
* Find tuple. Since buffer has been pinned, tuple cannot have been
|
||||
* vacuumed (and heap TID reused).
|
||||
*/
|
||||
if (ItemPointerEquals(&itup->t_tid, &so->heaptid))
|
||||
{
|
||||
/*
|
||||
* Make sure tuple has not already been marked dead to avoid extra
|
||||
* WAL if wal_log_hints or data checksums enabled
|
||||
*/
|
||||
if (!ItemIdIsDead(itemid))
|
||||
{
|
||||
ItemIdMarkDead(itemid);
|
||||
MarkBufferDirtyHint(buf, true);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Unlock buffer */
|
||||
LockBuffer(buf, BUFFER_LOCK_UNLOCK);
|
||||
}
|
||||
|
||||
/*
|
||||
* Prepare for an index scan
|
||||
*/
|
||||
@@ -206,7 +262,10 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
||||
probes = lists;
|
||||
|
||||
so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + probes * sizeof(IvfflatScanList));
|
||||
so->buf = InvalidBuffer;
|
||||
so->first = true;
|
||||
so->hasLock = false;
|
||||
ItemPointerSetInvalid(&so->heaptid);
|
||||
so->probes = probes;
|
||||
so->dimensions = dimensions;
|
||||
|
||||
@@ -217,12 +276,13 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
||||
|
||||
/* Create tuple description for sorting */
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
so->tupdesc = CreateTemplateTupleDesc(2);
|
||||
so->tupdesc = CreateTemplateTupleDesc(3);
|
||||
#else
|
||||
so->tupdesc = CreateTemplateTupleDesc(2, false);
|
||||
so->tupdesc = CreateTemplateTupleDesc(3, false);
|
||||
#endif
|
||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
|
||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
|
||||
|
||||
/* Prep sort */
|
||||
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
|
||||
@@ -254,6 +314,7 @@ ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int
|
||||
#endif
|
||||
|
||||
so->first = true;
|
||||
ItemPointerSetInvalid(&so->heaptid);
|
||||
pairingheap_reset(so->listQueue);
|
||||
|
||||
if (keys && scan->numberOfKeys > 0)
|
||||
@@ -288,10 +349,12 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
if (scan->orderByData == NULL)
|
||||
elog(ERROR, "cannot scan ivfflat index without order");
|
||||
|
||||
/* Requires MVCC-compliant snapshot as not able to pin during sorting */
|
||||
/* https://www.postgresql.org/docs/current/index-locking.html */
|
||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
||||
elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");
|
||||
/* Get a shared lock for non-MVCC snapshots */
|
||||
if (!so->hasLock && !IsMVCCSnapshot(scan->xs_snapshot))
|
||||
{
|
||||
so->hasLock = true;
|
||||
LockPage(scan->indexRelation, IVFFLAT_SCAN_LOCK, ShareLock);
|
||||
}
|
||||
|
||||
if (scan->orderByData->sk_flags & SK_ISNULL)
|
||||
value = PointerGetDatum(InitVector(so->dimensions));
|
||||
@@ -316,10 +379,17 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
if (value != scan->orderByData->sk_argument)
|
||||
pfree(DatumGetPointer(value));
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Mark prior tuple as dead */
|
||||
if (scan->kill_prior_tuple)
|
||||
MarkPriorTupleDead(scan);
|
||||
}
|
||||
|
||||
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL))
|
||||
{
|
||||
ItemPointer heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
|
||||
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
scan->xs_heaptid = *heaptid;
|
||||
@@ -327,6 +397,21 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
scan->xs_ctup.t_self = *heaptid;
|
||||
#endif
|
||||
|
||||
/* Keep track of info needed to mark tuple as dead */
|
||||
so->heaptid = *heaptid;
|
||||
|
||||
/* Unpin buffer */
|
||||
if (BufferIsValid(so->buf))
|
||||
ReleaseBuffer(so->buf);
|
||||
|
||||
/*
|
||||
* An index scan must maintain a pin on the index page holding the
|
||||
* item last returned by amgettuple
|
||||
*
|
||||
* https://www.postgresql.org/docs/current/index-locking.html
|
||||
*/
|
||||
so->buf = ReadBuffer(scan->indexRelation, indexblkno);
|
||||
|
||||
scan->xs_recheckorderby = false;
|
||||
return true;
|
||||
}
|
||||
@@ -342,6 +427,14 @@ ivfflatendscan(IndexScanDesc scan)
|
||||
{
|
||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||
|
||||
/* Release pin */
|
||||
if (BufferIsValid(so->buf))
|
||||
ReleaseBuffer(so->buf);
|
||||
|
||||
/* Release lock */
|
||||
if (so->hasLock)
|
||||
UnlockPage(scan->indexRelation, IVFFLAT_SCAN_LOCK, ShareLock);
|
||||
|
||||
pairingheap_free(so->listQueue);
|
||||
tuplesort_end(so->sortstate);
|
||||
|
||||
|
||||
@@ -57,12 +57,12 @@ IvfflatGetLists(Relation index)
|
||||
* Get proc
|
||||
*/
|
||||
FmgrInfo *
|
||||
IvfflatOptionalProcInfo(Relation index, uint16 procnum)
|
||||
IvfflatOptionalProcInfo(Relation rel, uint16 procnum)
|
||||
{
|
||||
if (!OidIsValid(index_getprocid(index, 1, procnum)))
|
||||
if (!OidIsValid(index_getprocid(rel, 1, procnum)))
|
||||
return NULL;
|
||||
|
||||
return index_getprocinfo(index, 1, procnum);
|
||||
return index_getprocinfo(rel, 1, procnum);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -136,6 +136,7 @@ IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogStat
|
||||
void
|
||||
IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||
{
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
@@ -159,6 +160,8 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
|
||||
IvfflatInitPage(newbuf, newpage);
|
||||
|
||||
/* Commit */
|
||||
MarkBufferDirty(*buf);
|
||||
MarkBufferDirty(newbuf);
|
||||
GenericXLogFinish(*state);
|
||||
|
||||
/* Unlock */
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "commands/vacuum.h"
|
||||
#include "ivfflat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
|
||||
/*
|
||||
* Bulk delete tuples from the index
|
||||
@@ -65,14 +66,10 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
|
||||
vacuum_delay_point();
|
||||
|
||||
buf = ReadBufferExtended(index, MAIN_FORKNUM, searchPage, RBM_NORMAL, bas);
|
||||
/* Ensure no in-flight index scans for non-MVCC snapshots */
|
||||
LockPage(index, IVFFLAT_SCAN_LOCK, ExclusiveLock);
|
||||
|
||||
/*
|
||||
* ambulkdelete cannot delete entries from pages that are
|
||||
* pinned by other backends
|
||||
*
|
||||
* https://www.postgresql.org/docs/current/index-locking.html
|
||||
*/
|
||||
buf = ReadBufferExtended(index, MAIN_FORKNUM, searchPage, RBM_NORMAL, bas);
|
||||
LockBufferForCleanup(buf);
|
||||
|
||||
state = GenericXLogStart(index);
|
||||
@@ -107,12 +104,15 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
{
|
||||
/* Delete tuples */
|
||||
PageIndexMultiDelete(page, deletable, ndeletable);
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
}
|
||||
else
|
||||
GenericXLogAbort(state);
|
||||
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
UnlockPage(index, IVFFLAT_SCAN_LOCK, ExclusiveLock);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
18
src/vector.c
18
src/vector.c
@@ -89,7 +89,7 @@ CheckDim(int dim)
|
||||
}
|
||||
|
||||
/*
|
||||
* Ensure finite element
|
||||
* Ensure finite elements
|
||||
*/
|
||||
static inline void
|
||||
CheckElement(float value)
|
||||
@@ -437,18 +437,17 @@ vector_send(PG_FUNCTION_ARGS)
|
||||
|
||||
/*
|
||||
* Convert vector to vector
|
||||
* This is needed to check the type modifier
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector);
|
||||
Datum
|
||||
vector(PG_FUNCTION_ARGS)
|
||||
{
|
||||
Vector *vec = PG_GETARG_VECTOR_P(0);
|
||||
Vector *arg = PG_GETARG_VECTOR_P(0);
|
||||
int32 typmod = PG_GETARG_INT32(1);
|
||||
|
||||
CheckExpectedDim(typmod, vec->dim);
|
||||
CheckExpectedDim(typmod, arg->dim);
|
||||
|
||||
PG_RETURN_POINTER(vec);
|
||||
PG_RETURN_POINTER(arg);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -465,6 +464,7 @@ array_to_vector(PG_FUNCTION_ARGS)
|
||||
bool typbyval;
|
||||
char typalign;
|
||||
Datum *elemsp;
|
||||
bool *nullsp;
|
||||
int nelemsp;
|
||||
|
||||
if (ARR_NDIM(array) > 1)
|
||||
@@ -478,7 +478,7 @@ array_to_vector(PG_FUNCTION_ARGS)
|
||||
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);
|
||||
deconstruct_array(array, ARR_ELEMTYPE(array), typlen, typbyval, typalign, &elemsp, &nullsp, &nelemsp);
|
||||
|
||||
CheckDim(nelemsp);
|
||||
CheckExpectedDim(typmod, nelemsp);
|
||||
@@ -512,12 +512,6 @@ array_to_vector(PG_FUNCTION_ARGS)
|
||||
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]);
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
CREATE TABLE t (val vector(3), val2 half[]);
|
||||
INSERT INTO t (val, val2) VALUES ('[0,0,0]', '{0,0,0}'), ('[1,2,3]', '{1,2,3}'), ('[1,1,1]', '{1,1,1}'), (NULL, NULL);
|
||||
CREATE TABLE t2 (val vector(3), val2 half[]);
|
||||
CREATE TABLE t (val vector(3));
|
||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||
CREATE TABLE t2 (val vector(3));
|
||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||
SELECT * FROM t2 ORDER BY val;
|
||||
val | val2
|
||||
---------+---------
|
||||
[0,0,0] | {0,0,0}
|
||||
[1,1,1] | {1,1,1}
|
||||
[1,2,3] | {1,2,3}
|
||||
|
|
||||
val
|
||||
---------
|
||||
[0,0,0]
|
||||
[1,1,1]
|
||||
[1,2,3]
|
||||
|
||||
(4 rows)
|
||||
|
||||
DROP TABLE t;
|
||||
|
||||
@@ -54,105 +54,105 @@ SELECT vector_norm('[3e37,4e37]')::real;
|
||||
5e+37
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('[0,0]'::vector, '[3,4]');
|
||||
SELECT l2_distance('[0,0]', '[3,4]');
|
||||
l2_distance
|
||||
-------------
|
||||
5
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('[0,0]'::vector, '[0,1]');
|
||||
SELECT l2_distance('[0,0]', '[0,1]');
|
||||
l2_distance
|
||||
-------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('[1,2]'::vector, '[3]');
|
||||
SELECT l2_distance('[1,2]', '[3]');
|
||||
ERROR: different vector dimensions 2 and 1
|
||||
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
||||
SELECT l2_distance('[3e38]', '[-3e38]');
|
||||
l2_distance
|
||||
-------------
|
||||
Infinity
|
||||
(1 row)
|
||||
|
||||
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
||||
SELECT inner_product('[1,2]', '[3,4]');
|
||||
inner_product
|
||||
---------------
|
||||
11
|
||||
(1 row)
|
||||
|
||||
SELECT inner_product('[1,2]'::vector, '[3]');
|
||||
SELECT inner_product('[1,2]', '[3]');
|
||||
ERROR: different vector dimensions 2 and 1
|
||||
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
||||
SELECT inner_product('[3e38]', '[3e38]');
|
||||
inner_product
|
||||
---------------
|
||||
Infinity
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
||||
SELECT cosine_distance('[1,2]', '[2,4]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
||||
SELECT cosine_distance('[1,2]', '[0,0]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
NaN
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
||||
SELECT cosine_distance('[1,1]', '[1,1]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
2
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
||||
SELECT cosine_distance('[1,2]', '[3]');
|
||||
ERROR: different vector dimensions 2 and 1
|
||||
SELECT cosine_distance('[1,1]'::vector, '[1.1,1.1]');
|
||||
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[1,1]'::vector, '[-1.1,-1.1]');
|
||||
SELECT cosine_distance('[1,1]', '[-1.1,-1.1]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
2
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
||||
SELECT cosine_distance('[3e38]', '[3e38]');
|
||||
cosine_distance
|
||||
-----------------
|
||||
NaN
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('[0,0]'::vector, '[3,4]');
|
||||
SELECT l1_distance('[0,0]', '[3,4]');
|
||||
l1_distance
|
||||
-------------
|
||||
7
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('[0,0]'::vector, '[0,1]');
|
||||
SELECT l1_distance('[0,0]', '[0,1]');
|
||||
l1_distance
|
||||
-------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('[1,2]'::vector, '[3]');
|
||||
SELECT l1_distance('[1,2]', '[3]');
|
||||
ERROR: different vector dimensions 2 and 1
|
||||
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
||||
SELECT l1_distance('[3e38]', '[-3e38]');
|
||||
l1_distance
|
||||
-------------
|
||||
Infinity
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
SELECT '1.5'::half;
|
||||
half
|
||||
------
|
||||
1.5
|
||||
(1 row)
|
||||
|
||||
SELECT '65504'::half;
|
||||
half
|
||||
-------
|
||||
65504
|
||||
(1 row)
|
||||
|
||||
SELECT '65505'::half;
|
||||
ERROR: "65505" is out of range for type half
|
||||
LINE 1: SELECT '65505'::half;
|
||||
^
|
||||
SELECT '-65504'::half;
|
||||
half
|
||||
--------
|
||||
-65504
|
||||
(1 row)
|
||||
|
||||
SELECT '-65505'::half;
|
||||
ERROR: "-65505" is out of range for type half
|
||||
LINE 1: SELECT '-65505'::half;
|
||||
^
|
||||
SELECT ''::half;
|
||||
ERROR: invalid input syntax for type half: ""
|
||||
LINE 1: SELECT ''::half;
|
||||
^
|
||||
SELECT ' '::half;
|
||||
ERROR: invalid input syntax for type half: " "
|
||||
LINE 1: SELECT ' '::half;
|
||||
^
|
||||
SELECT '-'::half;
|
||||
ERROR: invalid input syntax for type half: "-"
|
||||
LINE 1: SELECT '-'::half;
|
||||
^
|
||||
SELECT ' 1.5'::half;
|
||||
half
|
||||
------
|
||||
1.5
|
||||
(1 row)
|
||||
|
||||
SELECT '1.5 '::half;
|
||||
half
|
||||
------
|
||||
1.5
|
||||
(1 row)
|
||||
|
||||
SELECT '1.5a'::half;
|
||||
ERROR: invalid input syntax for type half: "1.5a"
|
||||
LINE 1: SELECT '1.5a'::half;
|
||||
^
|
||||
SELECT '{1,2,3}'::half[];
|
||||
half
|
||||
---------
|
||||
{1,2,3}
|
||||
(1 row)
|
||||
|
||||
SELECT '65505'::integer::half;
|
||||
half
|
||||
-------
|
||||
65504
|
||||
(1 row)
|
||||
|
||||
SELECT 'NaN'::real::half;
|
||||
half
|
||||
------
|
||||
NaN
|
||||
(1 row)
|
||||
|
||||
SELECT 'Infinity'::real::half;
|
||||
half
|
||||
----------
|
||||
Infinity
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('{0,0}'::half[], '{3,4}'::half[]);
|
||||
l2_distance
|
||||
-------------
|
||||
5
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('{0,0}'::half[], '{0,1}'::half[]);
|
||||
l2_distance
|
||||
-------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT l2_distance('{1,2}'::half[], '{3}'::half[]);
|
||||
ERROR: different dimensions 2 and 1
|
||||
SELECT '{0,0}'::half[] <-> '{3,4}'::half[];
|
||||
?column?
|
||||
----------
|
||||
5
|
||||
(1 row)
|
||||
|
||||
SELECT inner_product('{1,2}'::half[], '{3,4}'::half[]);
|
||||
inner_product
|
||||
---------------
|
||||
11
|
||||
(1 row)
|
||||
|
||||
SELECT inner_product('{1,2}'::half[], '{3}'::half[]);
|
||||
ERROR: different dimensions 2 and 1
|
||||
SELECT inner_product('{65504}'::half[], '{65504}'::half[]);
|
||||
inner_product
|
||||
---------------
|
||||
4290774016
|
||||
(1 row)
|
||||
|
||||
SELECT '{1,2}'::half[] <#> '{3,4}'::half[];
|
||||
?column?
|
||||
----------
|
||||
-11
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,2}'::half[], '{2,4}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,2}'::half[], '{0,0}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
NaN
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,1}'::half[], '{1,1}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,0}'::half[], '{0,2}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,1}'::half[], '{-1,-1}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
2
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,2}'::half[], '{3}'::half[]);
|
||||
ERROR: different dimensions 2 and 1
|
||||
SELECT cosine_distance('{1,1}'::half[], '{1.1,1.1}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT cosine_distance('{1,1}'::half[], '{-1.1,-1.1}'::half[]);
|
||||
cosine_distance
|
||||
-----------------
|
||||
2
|
||||
(1 row)
|
||||
|
||||
SELECT '{1,2}'::half[] <=> '{2,4}'::half[];
|
||||
?column?
|
||||
----------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('{0,0}'::half[], '{3,4}');
|
||||
l1_distance
|
||||
-------------
|
||||
7
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('{0,0}'::half[], '{0,1}');
|
||||
l1_distance
|
||||
-------------
|
||||
1
|
||||
(1 row)
|
||||
|
||||
SELECT l1_distance('{1,2}'::half[], '{3}');
|
||||
ERROR: different dimensions 2 and 1
|
||||
@@ -1,7 +1,7 @@
|
||||
CREATE TABLE t (val vector(3), val2 half[]);
|
||||
INSERT INTO t (val, val2) VALUES ('[0,0,0]', '{0,0,0}'), ('[1,2,3]', '{1,2,3}'), ('[1,1,1]', '{1,1,1}'), (NULL, NULL);
|
||||
CREATE TABLE t (val vector(3));
|
||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||
|
||||
CREATE TABLE t2 (val vector(3), val2 half[]);
|
||||
CREATE TABLE t2 (val vector(3));
|
||||
|
||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||
|
||||
@@ -13,29 +13,29 @@ SELECT vector_norm('[3,4]');
|
||||
SELECT vector_norm('[0,1]');
|
||||
SELECT vector_norm('[3e37,4e37]')::real;
|
||||
|
||||
SELECT l2_distance('[0,0]'::vector, '[3,4]');
|
||||
SELECT l2_distance('[0,0]'::vector, '[0,1]');
|
||||
SELECT l2_distance('[1,2]'::vector, '[3]');
|
||||
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
||||
SELECT l2_distance('[0,0]', '[3,4]');
|
||||
SELECT l2_distance('[0,0]', '[0,1]');
|
||||
SELECT l2_distance('[1,2]', '[3]');
|
||||
SELECT l2_distance('[3e38]', '[-3e38]');
|
||||
|
||||
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
||||
SELECT inner_product('[1,2]'::vector, '[3]');
|
||||
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
||||
SELECT inner_product('[1,2]', '[3,4]');
|
||||
SELECT inner_product('[1,2]', '[3]');
|
||||
SELECT inner_product('[3e38]', '[3e38]');
|
||||
|
||||
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
||||
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
||||
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
||||
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
||||
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
||||
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
||||
SELECT cosine_distance('[1,1]'::vector, '[1.1,1.1]');
|
||||
SELECT cosine_distance('[1,1]'::vector, '[-1.1,-1.1]');
|
||||
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
||||
SELECT cosine_distance('[1,2]', '[2,4]');
|
||||
SELECT cosine_distance('[1,2]', '[0,0]');
|
||||
SELECT cosine_distance('[1,1]', '[1,1]');
|
||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||
SELECT cosine_distance('[1,2]', '[3]');
|
||||
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
||||
SELECT cosine_distance('[1,1]', '[-1.1,-1.1]');
|
||||
SELECT cosine_distance('[3e38]', '[3e38]');
|
||||
|
||||
SELECT l1_distance('[0,0]'::vector, '[3,4]');
|
||||
SELECT l1_distance('[0,0]'::vector, '[0,1]');
|
||||
SELECT l1_distance('[1,2]'::vector, '[3]');
|
||||
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
||||
SELECT l1_distance('[0,0]', '[3,4]');
|
||||
SELECT l1_distance('[0,0]', '[0,1]');
|
||||
SELECT l1_distance('[1,2]', '[3]');
|
||||
SELECT l1_distance('[3e38]', '[-3e38]');
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
SELECT '1.5'::half;
|
||||
SELECT '65504'::half;
|
||||
SELECT '65505'::half;
|
||||
SELECT '-65504'::half;
|
||||
SELECT '-65505'::half;
|
||||
|
||||
SELECT ''::half;
|
||||
SELECT ' '::half;
|
||||
SELECT '-'::half;
|
||||
SELECT ' 1.5'::half;
|
||||
SELECT '1.5 '::half;
|
||||
SELECT '1.5a'::half;
|
||||
|
||||
SELECT '{1,2,3}'::half[];
|
||||
|
||||
SELECT '65505'::integer::half;
|
||||
SELECT 'NaN'::real::half;
|
||||
SELECT 'Infinity'::real::half;
|
||||
|
||||
SELECT l2_distance('{0,0}'::half[], '{3,4}'::half[]);
|
||||
SELECT l2_distance('{0,0}'::half[], '{0,1}'::half[]);
|
||||
SELECT l2_distance('{1,2}'::half[], '{3}'::half[]);
|
||||
SELECT '{0,0}'::half[] <-> '{3,4}'::half[];
|
||||
|
||||
SELECT inner_product('{1,2}'::half[], '{3,4}'::half[]);
|
||||
SELECT inner_product('{1,2}'::half[], '{3}'::half[]);
|
||||
SELECT inner_product('{65504}'::half[], '{65504}'::half[]);
|
||||
SELECT '{1,2}'::half[] <#> '{3,4}'::half[];
|
||||
|
||||
SELECT cosine_distance('{1,2}'::half[], '{2,4}'::half[]);
|
||||
SELECT cosine_distance('{1,2}'::half[], '{0,0}'::half[]);
|
||||
SELECT cosine_distance('{1,1}'::half[], '{1,1}'::half[]);
|
||||
SELECT cosine_distance('{1,0}'::half[], '{0,2}'::half[]);
|
||||
SELECT cosine_distance('{1,1}'::half[], '{-1,-1}'::half[]);
|
||||
SELECT cosine_distance('{1,2}'::half[], '{3}'::half[]);
|
||||
SELECT cosine_distance('{1,1}'::half[], '{1.1,1.1}'::half[]);
|
||||
SELECT cosine_distance('{1,1}'::half[], '{-1.1,-1.1}'::half[]);
|
||||
SELECT '{1,2}'::half[] <=> '{2,4}'::half[];
|
||||
|
||||
SELECT l1_distance('{0,0}'::half[], '{3,4}');
|
||||
SELECT l1_distance('{0,0}'::half[], '{0,1}');
|
||||
SELECT l1_distance('{1,2}'::half[], '{3}');
|
||||
@@ -83,32 +83,11 @@ for my $i (0 .. $#operators)
|
||||
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);
|
||||
));
|
||||
# Add index
|
||||
$node->safe_psql("postgres", "CREATE INDEX 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
|
||||
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||
SET client_min_messages = DEBUG;
|
||||
SET min_parallel_table_scan_size = 1;
|
||||
SET hnsw.enable_parallel_build = on;
|
||||
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;");
|
||||
}
|
||||
|
||||
done_testing();
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
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 half[3]);");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()]::numeric[]::half[] FROM generate_series(1, 10000) i;"
|
||||
);
|
||||
|
||||
# Generate queries
|
||||
for (1 .. 20)
|
||||
{
|
||||
my $r1 = rand();
|
||||
my $r2 = rand();
|
||||
my $r3 = rand();
|
||||
push(@queries, "{$r1,$r2,$r3}");
|
||||
}
|
||||
|
||||
# Check each index type
|
||||
my @operators = ("<->");
|
||||
my @opclasses = ("half_l2_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);
|
||||
}
|
||||
|
||||
# Add index
|
||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v $opclass);");
|
||||
|
||||
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||
test_recall($min, $operator);
|
||||
}
|
||||
|
||||
done_testing();
|
||||
@@ -1,4 +1,4 @@
|
||||
comment = 'vector data type and ivfflat and hnsw access methods'
|
||||
default_version = '0.5.1'
|
||||
default_version = '0.5.0'
|
||||
module_pathname = '$libdir/vector'
|
||||
relocatable = true
|
||||
|
||||
Reference in New Issue
Block a user