epzero 0.5.0__tar.gz → 0.6.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {epzero-0.5.0 → epzero-0.6.0}/CHANGELOG.md +84 -0
- {epzero-0.5.0 → epzero-0.6.0}/PKG-INFO +22 -3
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/auto.h +21 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/database.h +4 -1
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/distance.h +11 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/hnsw.h +40 -5
- {epzero-0.5.0 → epzero-0.6.0}/pyproject.toml +1 -1
- {epzero-0.5.0 → epzero-0.6.0}/python/README.md +21 -2
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/auto.py +11 -2
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/ir.py +36 -14
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero_py.cpp +106 -35
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_auto.py +9 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_epzero.py +58 -2
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_ir.py +33 -1
- {epzero-0.5.0 → epzero-0.6.0}/src/auto.cpp +252 -8
- {epzero-0.5.0 → epzero-0.6.0}/src/database.cpp +17 -4
- {epzero-0.5.0 → epzero-0.6.0}/src/distance.cpp +62 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_avx2.cpp +34 -0
- epzero-0.6.0/src/distance_avx512vnni.cpp +72 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_avxvnni.cpp +27 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_f16c.cpp +7 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_neon.cpp +37 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_scalar.cpp +21 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/hnsw.cpp +162 -28
- {epzero-0.5.0 → epzero-0.6.0}/src/kernels.h +10 -0
- epzero-0.6.0/src/sq4.h +49 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/auto_test.cpp +108 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/database_test.cpp +32 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/distance_test.cpp +32 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/half_test.cpp +25 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/hnsw_test.cpp +196 -0
- epzero-0.5.0/src/distance_avx512vnni.cpp +0 -34
- {epzero-0.5.0 → epzero-0.6.0}/CMakeLists.txt +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_adaptive.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_churn.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_distance.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_filter.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_guard.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/bench_recall.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/bench/regression.json +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/common.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/fuzz_graph.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/fuzz_metadata.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/fuzz_snapshot.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/fuzz_text.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/fuzz_wal.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/make_seeds.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/regressions/graph-empty-with-entry-point +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/regressions/graph-entry-level-overflow +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/regressions/graph-upper-link-to-base-node +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/regressions/snapshot-empty-with-entry-point +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/fuzz/regressions/snapshot-huge-capacity +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/brute_force.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/dataset.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/metadata.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/parallel.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/recall.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/include/epzero/text.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/__init__.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/haystack.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/langchain.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/epzero/llamaindex.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_haystack.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_langchain.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_llamaindex.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/python/tests/test_metadata.py +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/server/node_main.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/brute_force.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/dataset.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_avx512.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/distance_wasm.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/half.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/metadata.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/pca.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/platform.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/porter.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/rabitq.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/recall.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/text.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/src/visited_pool.h +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/data/v4-from-0.4.0.epzero +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/dataset_test.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/metadata_test.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/recall_test.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tests/text_test.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/tools/export_graph.cpp +0 -0
- {epzero-0.5.0 → epzero-0.6.0}/wasm/epzero_wasm.cpp +0 -0
|
@@ -1,5 +1,89 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
Indexes that keep growing without leaving their newest vectors behind; 4-bit codes; walks on principal
|
|
6
|
+
directions chosen by measurement (opt-in); faster builds; a deeper re-rank at k = 100; and a library that
|
|
7
|
+
refuses the usual first-time mistakes with a clear message. Files written by 0.5 load unchanged.
|
|
8
|
+
|
|
9
|
+
**Indexes that keep growing.** A vector inserted late has had no time to gain incoming links from
|
|
10
|
+
later arrivals, so the newest vectors of a grown index are found less often than in a rebuild.
|
|
11
|
+
|
|
12
|
+
- `extra_backlinks` (Python: `Index(..., extra_backlinks=8)`, `epzero.build(..., extra_backlinks=8)`;
|
|
13
|
+
C++: `HnswParams::extra_backlinks`): each insertion also asks that many of its closest construction
|
|
14
|
+
candidates that it did not choose to link to it. Off by default; not saved with the index, so
|
|
15
|
+
`index.set_extra_backlinks(n)` sets it again after `load()`.
|
|
16
|
+
- `index.refine_links(ef=..., first=n)`: reconnects only the vectors inserted from position `n` on, for
|
|
17
|
+
a checkpoint after a batch of additions. It returns the number of vectors refined. `around=True` also
|
|
18
|
+
refines the older vectors those link to, so that they can choose the new ones beside them.
|
|
19
|
+
- Both are opt-in. A one-off build doesn't change. Together (8 extra links, each batch refined at a beam
|
|
20
|
+
of 100) they removed the newest vectors' extra misses on a growing collection for about 9% more
|
|
21
|
+
insertion work.
|
|
22
|
+
|
|
23
|
+
**4-bit codes.** The graph walk can score 4-bit codes instead of 8-bit ones: half the bytes per scored
|
|
24
|
+
node, on the same per-dimension ranges at 16 levels, with the full vectors re-ranking more of the beam.
|
|
25
|
+
|
|
26
|
+
- `epzero.build(..., code_bits=4)` builds the graph on 8-bit codes as before and walks it on 4-bit ones.
|
|
27
|
+
They were 25-43% faster on GooAQ and Yahoo (walks over every dimension) and slower on most walks on
|
|
28
|
+
principal directions and on CLIP and ALIGN image vectors (Xeon Gold 6226), so the default stays 8 bits.
|
|
29
|
+
- `measure_code_bits=True` calibrates and times the walk at both widths on the same graph and keeps 4 bits
|
|
30
|
+
only where they reach the recall target at least 3% faster (`index.plan.reasons["code_bits"]` gives both
|
|
31
|
+
timings). Opt-in: its choice was within 3% of the better one on 9 of 12 datasets, but 24% slower on GooAQ
|
|
32
|
+
at k = 10, where the two tied at calibration. Below 128 codes per vector it keeps 8 bits without trying.
|
|
33
|
+
- `index.set_code_bits(4)` (C++: `HnswIndex::set_code_bits`) converts a built index in place, keeping
|
|
34
|
+
the graph, and back with `set_code_bits(8)`. 4-bit codes need the full vectors (the default).
|
|
35
|
+
- Integer kernels for AVX2, AVX-VNNI, AVX-512 VNNI and NEON (base ARMv8, no dot-product extension needed);
|
|
36
|
+
WebAssembly uses a scalar kernel for 4-bit codes, so there the planner's timing keeps 8 bits.
|
|
37
|
+
- Saved with the index as a storage flag; builds before this one refuse such a file instead of misreading it.
|
|
38
|
+
|
|
39
|
+
**Walking on the right directions, chosen by measurement (opt-in).**
|
|
40
|
+
|
|
41
|
+
- `check_walk=True`: with your own `queries=`, if they look unlike the data (as `check_queries` judges, on a
|
|
42
|
+
sample before the build), the build times the variance rule's walk on principal directions against no walk,
|
|
43
|
+
on 50,000 rows, and keeps the faster. On COCO (text queries against image vectors) the rule's 128-direction
|
|
44
|
+
walk never reached recall 0.95 (beam width 4096); with the check, no walk reached it at 128, for 26% more build
|
|
45
|
+
time on a laptop. On the full set on a Xeon Gold 6226 the highest recall rose from 0.76-0.82 to 0.996, for 1.5x
|
|
46
|
+
the build time (25 to 38 s). Queries like the data skip the trial (AG News: build time unchanged).
|
|
47
|
+
- `measure_nav=True`: the number of directions itself by trial indexes on 100,000 rows (none, 128-512 and the
|
|
48
|
+
rule's), timed on your queries or on held-out rows. On eight datasets it chose the count that was fastest on
|
|
49
|
+
the full data, or within 5% of it, 15 times out of 16 (Xeon Gold 6226, round 14), but it costs 2-3.5x the build
|
|
50
|
+
time, so it stays opt-in.
|
|
51
|
+
|
|
52
|
+
**Searching deeper at k = 100.** With the walk on principal directions, the early-stopping re-rank with
|
|
53
|
+
full vectors now scores up to max(`rerank`, `ef`) candidates instead of `rerank`: at k = 100 a wide beam
|
|
54
|
+
holds true neighbours past the first 300. Highest recall at k = 100 rose from 0.987 to 0.999 on AG News,
|
|
55
|
+
0.970 to 0.999 on arXiv and 0.910 to 0.995 on GIST1M; at k = 10 the early stop ends the re-rank first,
|
|
56
|
+
and speed is unchanged within 1-2%.
|
|
57
|
+
|
|
58
|
+
**Faster builds.**
|
|
59
|
+
|
|
60
|
+
- Building with 16-bit full vectors (`half_vectors=True`) and no walk on principal directions widened each
|
|
61
|
+
stored vector to floats one value at a time for every pair the build compared; it now uses F16C or NEON.
|
|
62
|
+
Such a build took 2.6x as long as an 8-bit one on 300,000 AG News vectors (1.7x on GooAQ, 24 cores); now 1.01x,
|
|
63
|
+
and 0.68-1.02x on nine datasets on a Xeon Gold 6226 (GooAQ 0.82x). 16-bit vectors stay opt-in: they cost up to
|
|
64
|
+
0.006 recall at 10 neighbours on some text embeddings.
|
|
65
|
+
- A build that also times 4-bit codes computes its calibration queries' exact neighbours once, not twice.
|
|
66
|
+
- `refine_ef=` sets the refine pass's beam width (by default efConstruction with a walk on directions, half
|
|
67
|
+
of it without).
|
|
68
|
+
|
|
69
|
+
**Friendlier for a first-time user** (found by installing from PyPI and trying the usual mistakes):
|
|
70
|
+
|
|
71
|
+
- Vectors or queries holding a NaN or an infinity are refused with the row and column (`ValueError: row 42
|
|
72
|
+
contains NaN (column 5)`). Before, such data built an index that calibrated to its widest beam and returned
|
|
73
|
+
noise. C++: `HnswIndex::add` throws `std::invalid_argument`, and `Database` refuses them before they reach
|
|
74
|
+
its log. A log written by an older version that holds such a vector still opens: the vector is skipped
|
|
75
|
+
and counted in `recovery()["skipped"]`, on a replica too.
|
|
76
|
+
- Metric names other libraries use are accepted, in any case: `"euclidean"` and `"l2sq"` for `"l2"`, `"dot"`,
|
|
77
|
+
`"inner_product"` and `"mips"` for `"ip"`, `"angular"` and `"cos"` for `"cosine"`.
|
|
78
|
+
- `save`, `load` and `Database.open` take any path-like object (`pathlib.Path`), not only strings.
|
|
79
|
+
- A negative `k`, `ef` or `rerank` gets `ValueError: k must be 0 or more` instead of a pybind11 cast error.
|
|
80
|
+
- `search` documents what fills a short result: label -1 and distance inf.
|
|
81
|
+
|
|
82
|
+
**Retrieval evaluation** (`epzero.ir`): run files keep full score precision; qrels with a non-integer or
|
|
83
|
+
non-finite grade, or a duplicate judgment, are refused with the file and the offending value; `evaluate(...,
|
|
84
|
+
population=...)` chooses which queries count (`"positive"`, the default and the earlier behaviour, `"judged"`,
|
|
85
|
+
or `"explicit"` with `query_ids=`), and a query missing from the run scores 0.
|
|
86
|
+
|
|
3
87
|
## 0.5.0
|
|
4
88
|
|
|
5
89
|
An index that stays accurate as its data changes, fixed in place; metadata and keyword search in the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: epzero
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: A fast HNSW vector database in C++20 that configures itself: SIMD search, filtered search, recall monitoring, crash-safe storage
|
|
5
5
|
Keywords: vector database,hnsw,ann,nearest neighbor,embeddings,rag,langchain
|
|
6
6
|
Author: Lajat
|
|
@@ -132,6 +132,26 @@ the graph links chosen for them suffer: in a synthetic test with a 4 sd drift, t
|
|
|
132
132
|
for recall 0.95 went from 12 to 200. `requantize()` refits the codes and reconnects the graph in about half a rebuild's
|
|
133
133
|
time, back to 12.
|
|
134
134
|
|
|
135
|
+
**An index that keeps growing.** In a graph index, a vector inserted early keeps gaining incoming links
|
|
136
|
+
from everything added near it later, and one inserted late has had no time to. So the newest vectors are
|
|
137
|
+
found less often than in a fresh build of the same data. Two options make an index grown in batches
|
|
138
|
+
behave like a rebuild:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
index = epzero.build(vectors, extra_backlinks=8) # each insertion is also linked from 8 nearby nodes
|
|
142
|
+
...
|
|
143
|
+
first = len(index) # before a batch (nothing removed since)
|
|
144
|
+
index.add(batch, labels=batch_labels)
|
|
145
|
+
index.refine_links(ef=100, first=first) # at a checkpoint: reconnect the batch, all cores
|
|
146
|
+
|
|
147
|
+
index = epzero.Index.load(path)
|
|
148
|
+
index.set_extra_backlinks(8) # not saved with the index: set it again after load
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Both are off by default. A one-off build gains nothing from them; they are for indexes that keep
|
|
152
|
+
growing. The checkpoint refine visits only the vectors added since `first`, so it takes a small
|
|
153
|
+
fraction of a rebuild's time.
|
|
154
|
+
|
|
135
155
|
## Configured by hand
|
|
136
156
|
|
|
137
157
|
```python
|
|
@@ -236,7 +256,6 @@ saves to a folder.
|
|
|
236
256
|
|
|
237
257
|
## Platforms
|
|
238
258
|
|
|
239
|
-
Wheels for Linux (x86-64 and ARM64, glibc 2.28+), macOS (Apple silicon and Intel) and, from
|
|
240
|
-
Windows (x64), Python 3.10 to 3.13. Elsewhere, `pip install epzero` builds from source (CMake 3.20+, a C++20 compiler).
|
|
259
|
+
Wheels for Linux (x86-64 and ARM64, glibc 2.28+), macOS (Apple silicon and Intel) and Windows (x64), Python 3.10 to 3.13. Elsewhere, `pip install epzero` builds from source (CMake 3.20+, a C++20 compiler).
|
|
241
260
|
|
|
242
261
|
Live demo, benchmarks and design notes: https://epzero.dev/ · MIT license.
|
|
@@ -32,12 +32,15 @@ struct AutoFixed {
|
|
|
32
32
|
std::optional<std::size_t> nav_dim;
|
|
33
33
|
std::optional<bool> fast_build;
|
|
34
34
|
std::optional<bool> refine; // refine_links() after the build
|
|
35
|
+
std::optional<std::size_t> refine_ef; // that pass's beam (default: efConstruction with directions, half without)
|
|
35
36
|
std::optional<bool> fill_after; // fill_free_links() after the build
|
|
36
37
|
std::optional<std::size_t> rerank;
|
|
37
38
|
std::optional<float> rerank_z;
|
|
38
39
|
std::optional<std::size_t> ef; // skips calibration
|
|
39
40
|
std::optional<std::pair<std::size_t, std::size_t>> prefetch; // (depth, lines); skips timing
|
|
40
41
|
std::optional<bool> half_vectors; // 16-bit full vectors: half their memory (never chosen automatically)
|
|
42
|
+
std::optional<std::size_t> extra_backlinks; // HnswParams::extra_backlinks (0 unless set)
|
|
43
|
+
std::optional<std::size_t> code_bits; // 8 or 4 (otherwise 8, or the faster of the two with measure_code_bits)
|
|
41
44
|
};
|
|
42
45
|
|
|
43
46
|
struct AutoOptions {
|
|
@@ -54,6 +57,20 @@ struct AutoOptions {
|
|
|
54
57
|
const float* queries = nullptr;
|
|
55
58
|
std::size_t query_count = 0;
|
|
56
59
|
AutoFixed fixed;
|
|
60
|
+
// Choose the number of principal directions to walk on by measurement instead of the variance rule
|
|
61
|
+
// (unless nav_dim is fixed): a trial index on a sample of the data for each candidate count (none,
|
|
62
|
+
// 128-512, and the rule's), calibrated to the recall target and timed on one thread, on `queries` when
|
|
63
|
+
// given and on rows held out of the sample otherwise; the fastest that reaches the target is built.
|
|
64
|
+
// Opt-in until measured on every dataset (docs/performance.md).
|
|
65
|
+
bool measure_nav = false;
|
|
66
|
+
// With your own `queries`, whether to walk on principal directions at all: the variance rule's walk and
|
|
67
|
+
// none, each built on a sample and timed on them, so that queries unlike the data (text against images)
|
|
68
|
+
// don't walk on the data's directions when that is slower. Cheaper than measure_nav: two small trials.
|
|
69
|
+
bool check_walk = false;
|
|
70
|
+
// Unless code_bits is fixed: time the walk on 8-bit and on 4-bit codes of the same graph and keep 4 bits
|
|
71
|
+
// only if at least 3% faster at the recall target. Opt-in: on the Gold 6226 the choice was within 3% of the
|
|
72
|
+
// better one on 9 of 12 datasets, and 24% slower on GooAQ (round 14, docs/performance.md).
|
|
73
|
+
bool measure_code_bits = false;
|
|
57
74
|
};
|
|
58
75
|
|
|
59
76
|
struct AutoPlan {
|
|
@@ -61,6 +78,10 @@ struct AutoPlan {
|
|
|
61
78
|
IndexProfile profile; // ef is 0 while it still has to be calibrated
|
|
62
79
|
bool calibrate = true; // build_auto will calibrate ef
|
|
63
80
|
bool tune = true; // build_auto will time prefetch settings
|
|
81
|
+
// The graph is always built on 8-bit codes (params.code_bits stays 8); build_auto then walks it on
|
|
82
|
+
// `code_bits`, or, with measure_code_bits, on whichever of 8 and 4 bits is faster at the recall target.
|
|
83
|
+
std::size_t code_bits = 8;
|
|
84
|
+
bool measure_code_bits = false;
|
|
64
85
|
};
|
|
65
86
|
|
|
66
87
|
// What build_auto() would do with `data` (n rows of dim floats), without building.
|
|
@@ -41,6 +41,7 @@ struct RecoveryInfo {
|
|
|
41
41
|
std::uint64_t snapshot_lsn = 0;
|
|
42
42
|
std::size_t replayed = 0; // WAL records applied on top of the snapshot
|
|
43
43
|
std::size_t truncated_bytes = 0; // torn or corrupt tail removed from the WAL
|
|
44
|
+
std::size_t skipped = 0; // logged vectors with a NaN or infinity (older versions accepted them), not applied
|
|
44
45
|
};
|
|
45
46
|
|
|
46
47
|
// A durable vector collection: an HnswIndex plus a write-ahead log in a directory.
|
|
@@ -107,9 +108,11 @@ class Database {
|
|
|
107
108
|
private:
|
|
108
109
|
Database(std::string dir, const HnswParams& params, const DatabaseOptions& options);
|
|
109
110
|
void recover();
|
|
110
|
-
void check_upserts(const std::uint64_t* labels, std::size_t n) const;
|
|
111
|
+
void check_upserts(const std::uint64_t* labels, const float* vectors, std::size_t n) const;
|
|
111
112
|
void append(const std::vector<std::uint8_t>& bytes, bool sync);
|
|
112
113
|
void apply_upsert(std::uint64_t label, const float* vector);
|
|
114
|
+
// Applies a logged record; an upsert whose vector holds a NaN or an infinity (logged by an older version)
|
|
115
|
+
// is skipped and counted in recovery().skipped instead, so neither recovery nor a replica can fail on it.
|
|
113
116
|
void apply_record(const LogRecord& record);
|
|
114
117
|
void write_checkpoint_file(std::uint64_t lsn);
|
|
115
118
|
void maybe_checkpoint();
|
|
@@ -43,6 +43,9 @@ DistanceFn get_distance_fn(Metric metric) noexcept;
|
|
|
43
43
|
// the CPU has them.
|
|
44
44
|
using HalfDistanceFn = float (*)(const float* query, const std::uint16_t* v, std::size_t dim) noexcept;
|
|
45
45
|
HalfDistanceFn get_half_distance_fn(Metric metric, SimdLevel level) noexcept;
|
|
46
|
+
// Widens `n` half floats to floats (F16C or NEON where present, exact scalar code otherwise).
|
|
47
|
+
using HalfToFloatFn = void (*)(const std::uint16_t* in, float* out, std::size_t n) noexcept;
|
|
48
|
+
HalfToFloatFn get_half_to_float_fn(SimdLevel level) noexcept;
|
|
46
49
|
|
|
47
50
|
// Asymmetric-distance kernel for 8-bit scalar quantization: returns sum_i w[i] * codes[i].
|
|
48
51
|
// The quantizer folds its per-dimension scales and offsets into `w` once per query, so scoring a
|
|
@@ -65,6 +68,14 @@ Sq8IntDotFn get_sq8_int_dot_fn(SimdLevel level, std::size_t dim = 0) noexcept;
|
|
|
65
68
|
// Every integer kernel this CPU can run, by name (for tests and benchmarks).
|
|
66
69
|
std::vector<std::pair<std::string_view, Sq8IntDotFn>> sq8_int_dot_variants();
|
|
67
70
|
|
|
71
|
+
// 4-bit codes (HnswParams::code_bits = 4): the same integer dot product against codes packed two to a byte
|
|
72
|
+
// (src/sq4.h), with `dim` padded to a multiple of 32. Codes are at most 15, so weights may use the
|
|
73
|
+
// whole int8 range (2 x 15 x 127 stays inside the AVX2 kernel's 16-bit pair sums). Always available: a
|
|
74
|
+
// scalar kernel where the CPU has no faster one, as 4-bit codes have no float path.
|
|
75
|
+
inline constexpr int kSq4IntWeightMax = 127;
|
|
76
|
+
Sq8IntDotFn get_sq4_int_dot_fn(SimdLevel level, std::size_t dim = 0) noexcept;
|
|
77
|
+
std::vector<std::pair<std::string_view, Sq8IntDotFn>> sq4_int_dot_variants();
|
|
78
|
+
|
|
68
79
|
// RaBitQ kernel: sum over j < 4 of 2^j * popcount(bits & planes[j]), with `planes` the four bit
|
|
69
80
|
// planes of a 4-bit query (`words` 64-bit words each). See src/rabitq.h.
|
|
70
81
|
using RabitqIpFn = std::uint32_t (*)(const std::uint64_t* bits, const std::uint64_t* planes, std::size_t words) noexcept;
|
|
@@ -56,6 +56,17 @@ struct HnswParams {
|
|
|
56
56
|
// index. They are read only to build the graph and to re-rank, where three significant digits are
|
|
57
57
|
// enough (recall identical to four decimals on GIST1M and OpenAI embeddings). Saved with the index.
|
|
58
58
|
bool half_vectors = false;
|
|
59
|
+
// SQ8 with keep_vectors: bits per code, 8 or 4. Four halves the codes each scored node reads (two to a
|
|
60
|
+
// byte, on the same per-dimension ranges at 16 levels instead of 256), so the walk ranks less exactly
|
|
61
|
+
// and the re-rank with full vectors does more of the work. Saved with the index; set_code_bits()
|
|
62
|
+
// changes it on a built index, keeping the graph.
|
|
63
|
+
std::size_t code_bits = 8;
|
|
64
|
+
// Building: old nodes keep receiving incoming links from every later arrival near them, so late
|
|
65
|
+
// insertions have fewer and are found less often. With this set, each insertion also asks this many
|
|
66
|
+
// of its closest construction candidates that it did not choose as neighbours to link to it at the
|
|
67
|
+
// base layer (a full candidate gives up its farthest link), standing in for the later arrivals a
|
|
68
|
+
// new node has not had yet. 0 keeps the standard behaviour. Not saved with the index.
|
|
69
|
+
std::size_t extra_backlinks = 0;
|
|
59
70
|
};
|
|
60
71
|
|
|
61
72
|
struct SearchResult {
|
|
@@ -132,7 +143,9 @@ struct SearchOptions {
|
|
|
132
143
|
std::size_t rerank = 0;
|
|
133
144
|
// Stops the re-rank early (0 = off): candidates are scored in blocks, and scoring ends once the
|
|
134
145
|
// next one, placed by this query's gap between estimated and exact distances, is more than this
|
|
135
|
-
// many standard deviations past the k-th best.
|
|
146
|
+
// many standard deviations past the k-th best. The cap is then max(`rerank`, `ef`): a wider beam
|
|
147
|
+
// holds more true neighbours past a fixed cap, and the early stop ends the re-rank well before it
|
|
148
|
+
// when they are found (at k = 100 a fixed 300 held recall at 0.988 from ef 400 on). 3 is a safe value.
|
|
136
149
|
float rerank_z = 0.0f;
|
|
137
150
|
SearchStats* stats = nullptr; // optional
|
|
138
151
|
SearchTrace* trace = nullptr; // optional; costs nothing when null
|
|
@@ -254,8 +267,16 @@ class HnswIndex {
|
|
|
254
267
|
|
|
255
268
|
// Once the index is built: every node searches the finished graph and reconnects, as its first
|
|
256
269
|
// neighbours were chosen from a sparser one. Must not run concurrently with add() or remove().
|
|
257
|
-
// `exact` searches and prunes on full vectors even on an index built with fast_build.
|
|
258
|
-
|
|
270
|
+
// `exact` searches and prunes on full vectors even on an index built with fast_build. `first`: only
|
|
271
|
+
// the nodes inserted from that position on (0 = all), e.g. those added since the last refine, so
|
|
272
|
+
// that later insertions are refined like the bulk-built ones. `around`: also the older nodes those
|
|
273
|
+
// link to on layer 0, so that they can choose the new nodes beside them. Returns the nodes refined.
|
|
274
|
+
std::size_t refine_links(std::size_t threads = 0, std::size_t ef = 0, bool exact = false,
|
|
275
|
+
std::size_t first = 0, bool around = false); // ef 0: ef_construction
|
|
276
|
+
|
|
277
|
+
// HnswParams::extra_backlinks for the insertions from now on. It is not saved with the index, so an
|
|
278
|
+
// index that keeps growing sets it again after load(). Must not run concurrently with add().
|
|
279
|
+
void set_extra_backlinks(std::size_t count) { params_.extra_backlinks = count; }
|
|
259
280
|
|
|
260
281
|
// SQ8: the share of the vectors' variance (in code space, up to `sample` live vectors) that their
|
|
261
282
|
// 8-bit codes miss. Rounding alone loses about 1e-4; a vector added outside the ranges train() saw is
|
|
@@ -267,6 +288,11 @@ class HnswIndex {
|
|
|
267
288
|
// Not thread-safe: nothing else may use the index meanwhile.
|
|
268
289
|
void requantize(std::size_t threads = 0);
|
|
269
290
|
|
|
291
|
+
// SQ8 with full vectors: re-encodes every node's codes at `bits` (8 or 4) from its full vector, keeping
|
|
292
|
+
// the graph and the code ranges, so a graph built on 8-bit codes can be walked on 4-bit ones (or back).
|
|
293
|
+
// Not thread-safe: nothing else may use the index meanwhile, as its memory moves.
|
|
294
|
+
void set_code_bits(std::size_t bits, std::size_t threads = 0);
|
|
295
|
+
|
|
270
296
|
void save(const std::string& path) const;
|
|
271
297
|
// Loads a snapshot; corrupt or truncated files throw. With max_bytes, a snapshot whose index
|
|
272
298
|
// would allocate more than that is refused before allocating (for untrusted files).
|
|
@@ -362,8 +388,13 @@ class HnswIndex {
|
|
|
362
388
|
// Node `id`'s full vector as floats: in place, or decoded from halves into `scratch`.
|
|
363
389
|
const float* full_floats(id_t id, std::vector<float>& scratch) const;
|
|
364
390
|
bool has_full_vectors() const noexcept { return !quantized() || params_.keep_vectors; }
|
|
365
|
-
//
|
|
391
|
+
// Codes per node, and the projection onto the walk's directions (nav_dim only).
|
|
366
392
|
std::size_t code_dim() const noexcept { return params_.nav_dim != 0 ? params_.nav_dim : params_.dim; }
|
|
393
|
+
bool four_bit() const noexcept { return params_.code_bits == 4; }
|
|
394
|
+
// Bytes of code per node: one per code, or two codes to a byte padded to 32 codes (src/sq4.h).
|
|
395
|
+
std::size_t code_bytes() const noexcept { return four_bit() ? (code_dim() + 31) / 32 * 16 : code_dim(); }
|
|
396
|
+
float max_code() const noexcept { return four_bit() ? 15.0f : 255.0f; }
|
|
397
|
+
std::uint8_t code_at(const std::uint8_t* codes, std::size_t i) const noexcept;
|
|
367
398
|
void project(const float* v, float* out) const noexcept;
|
|
368
399
|
void project_query(const float* query, float* out) const;
|
|
369
400
|
void prepare_query_projection();
|
|
@@ -416,6 +447,7 @@ class HnswIndex {
|
|
|
416
447
|
// diverse directions, which is what makes the graph navigable across clusters.
|
|
417
448
|
std::vector<Candidate> select_neighbors(std::vector<Candidate> candidates, std::size_t max_count) const;
|
|
418
449
|
void connect(id_t id, const std::vector<Candidate>& neighbors, int layer);
|
|
450
|
+
void add_extra_backlinks(id_t id, const std::vector<Candidate>& candidates, const std::vector<Candidate>& chosen);
|
|
419
451
|
|
|
420
452
|
HnswParams params_;
|
|
421
453
|
SimdLevel simd_level_;
|
|
@@ -423,6 +455,7 @@ class HnswIndex {
|
|
|
423
455
|
Sq8DotFn sq8_dot_;
|
|
424
456
|
// SQ8 in integers (int8 per-query weights), where the CPU has a kernel faster than the float one.
|
|
425
457
|
Sq8IntDotFn sq8_int_dot_;
|
|
458
|
+
Sq8IntDotFn sq4_int_dot_; // 4-bit codes: always set (a scalar kernel at worst)
|
|
426
459
|
RabitqIpFn rabitq_ip_;
|
|
427
460
|
std::size_t max_links0_;
|
|
428
461
|
double level_mult_;
|
|
@@ -438,7 +471,8 @@ class HnswIndex {
|
|
|
438
471
|
std::unique_ptr<std::byte[], AlignedFree> allocate_level0() const;
|
|
439
472
|
std::unique_ptr<std::byte[], AlignedFree> level0_;
|
|
440
473
|
|
|
441
|
-
// SQ8: per-dimension x = min + code * scale,
|
|
474
|
+
// SQ8: per-dimension x = min + code * scale (scale = range / 255, or / 15 with 4-bit codes), and the
|
|
475
|
+
// kept full-precision vectors.
|
|
442
476
|
std::vector<float> sq8_min_;
|
|
443
477
|
std::vector<float> sq8_scale_;
|
|
444
478
|
bool walk_full_ = false;
|
|
@@ -453,6 +487,7 @@ class HnswIndex {
|
|
|
453
487
|
std::unique_ptr<float[], AlignedFree> full_;
|
|
454
488
|
std::unique_ptr<std::uint16_t[], AlignedFree> half_; // instead of full_, with half_vectors
|
|
455
489
|
HalfDistanceFn dist_half_ = nullptr;
|
|
490
|
+
HalfToFloatFn half_to_float_ = nullptr; // widens a whole 16-bit vector (full_floats)
|
|
456
491
|
|
|
457
492
|
// RaBitQ: the centroid, the rotation's random signs, and the padded (power of two) dimension.
|
|
458
493
|
std::vector<float> rbq_center_;
|
|
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "epzero"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.6.0"
|
|
8
8
|
description = "A fast HNSW vector database in C++20 that configures itself: SIMD search, filtered search, recall monitoring, crash-safe storage"
|
|
9
9
|
readme = "python/README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -96,6 +96,26 @@ the graph links chosen for them suffer: in a synthetic test with a 4 sd drift, t
|
|
|
96
96
|
for recall 0.95 went from 12 to 200. `requantize()` refits the codes and reconnects the graph in about half a rebuild's
|
|
97
97
|
time, back to 12.
|
|
98
98
|
|
|
99
|
+
**An index that keeps growing.** In a graph index, a vector inserted early keeps gaining incoming links
|
|
100
|
+
from everything added near it later, and one inserted late has had no time to. So the newest vectors are
|
|
101
|
+
found less often than in a fresh build of the same data. Two options make an index grown in batches
|
|
102
|
+
behave like a rebuild:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
index = epzero.build(vectors, extra_backlinks=8) # each insertion is also linked from 8 nearby nodes
|
|
106
|
+
...
|
|
107
|
+
first = len(index) # before a batch (nothing removed since)
|
|
108
|
+
index.add(batch, labels=batch_labels)
|
|
109
|
+
index.refine_links(ef=100, first=first) # at a checkpoint: reconnect the batch, all cores
|
|
110
|
+
|
|
111
|
+
index = epzero.Index.load(path)
|
|
112
|
+
index.set_extra_backlinks(8) # not saved with the index: set it again after load
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Both are off by default. A one-off build gains nothing from them; they are for indexes that keep
|
|
116
|
+
growing. The checkpoint refine visits only the vectors added since `first`, so it takes a small
|
|
117
|
+
fraction of a rebuild's time.
|
|
118
|
+
|
|
99
119
|
## Configured by hand
|
|
100
120
|
|
|
101
121
|
```python
|
|
@@ -200,7 +220,6 @@ saves to a folder.
|
|
|
200
220
|
|
|
201
221
|
## Platforms
|
|
202
222
|
|
|
203
|
-
Wheels for Linux (x86-64 and ARM64, glibc 2.28+), macOS (Apple silicon and Intel) and, from
|
|
204
|
-
Windows (x64), Python 3.10 to 3.13. Elsewhere, `pip install epzero` builds from source (CMake 3.20+, a C++20 compiler).
|
|
223
|
+
Wheels for Linux (x86-64 and ARM64, glibc 2.28+), macOS (Apple silicon and Intel) and Windows (x64), Python 3.10 to 3.13. Elsewhere, `pip install epzero` builds from source (CMake 3.20+, a C++20 compiler).
|
|
205
224
|
|
|
206
225
|
Live demo, benchmarks and design notes: https://epzero.dev/ · MIT license.
|
|
@@ -30,7 +30,8 @@ from ._core import Index, _build_auto, _plan_auto
|
|
|
30
30
|
|
|
31
31
|
# Settings the C++ planner decides, which a caller can fix instead.
|
|
32
32
|
_DECIDED = ("quantization", "nav_dim", "fast_build", "refine", "fill_after", "rerank", "rerank_z", "ef", "prefetch",
|
|
33
|
-
"half_vectors"
|
|
33
|
+
"half_vectors", "extra_backlinks", "code_bits", "measure_nav", "check_walk", "refine_ef",
|
|
34
|
+
"measure_code_bits")
|
|
34
35
|
|
|
35
36
|
|
|
36
37
|
@dataclasses.dataclass(frozen=True)
|
|
@@ -44,8 +45,14 @@ class Plan:
|
|
|
44
45
|
nav_dim: int = 0 # walk on 8-bit codes of this many principal directions (0: off)
|
|
45
46
|
fast_build: bool = True # build on the 8-bit codes
|
|
46
47
|
refine: bool = True # a second pass: every node searches the finished graph and reconnects
|
|
48
|
+
refine_ef: int | None = None # that pass's beam width; None: efConstruction with directions, half without
|
|
47
49
|
fill_after: bool = False # give free link slots to the closest two-hop neighbours
|
|
48
50
|
half_vectors: bool = False # keep the full vectors as 16-bit floats: half their memory, a little speed and recall
|
|
51
|
+
extra_backlinks: int = 0 # each insertion is also linked from this many nearby nodes it did not choose
|
|
52
|
+
code_bits: int | None = None # 8 or 4 bits per code; None: 8, or the faster of the two with measure_code_bits
|
|
53
|
+
measure_code_bits: bool = False # time 8- and 4-bit walks of the same graph, keep the faster (opt-in)
|
|
54
|
+
measure_nav: bool = False # choose nav_dim by trial indexes on a sample, timed on your queries (opt-in)
|
|
55
|
+
check_walk: bool = False # with your queries: walk on directions only if faster for them (opt-in)
|
|
49
56
|
rerank: int = 0 # candidates re-scored with full vectors (0: twice k)
|
|
50
57
|
rerank_z: float = 0.0 # stop the re-rank early at this many standard deviations (0: off)
|
|
51
58
|
recall: float = 0.95 # the target the beam width is calibrated for
|
|
@@ -93,6 +100,8 @@ def _from_core(params, profile, recall, threads, seed, built):
|
|
|
93
100
|
ef_construction=params["ef_construction"], nav_dim=params["nav_dim"],
|
|
94
101
|
fast_build=profile["fast_build"] if built else params["fast_build"],
|
|
95
102
|
refine=profile["refine"], fill_after=profile["fill_after"], half_vectors=params["half_vectors"],
|
|
103
|
+
extra_backlinks=params.get("extra_backlinks", 0),
|
|
104
|
+
code_bits=params.get("code_bits", 8) if built else None,
|
|
96
105
|
rerank=profile["rerank"],
|
|
97
106
|
rerank_z=round(float(profile["rerank_z"]), 4), recall=round(float(profile["recall_target"] or recall), 4),
|
|
98
107
|
k=profile["k"], ef=profile["ef"] or None, prefetch=tuple(profile["prefetch"]) if built else None,
|
|
@@ -114,7 +123,7 @@ def plan(data, metric="l2", queries=None, **settings):
|
|
|
114
123
|
queries is not None, p.fixed())
|
|
115
124
|
out = _from_core(core["params"], core["profile"], p.recall, p.threads, p.seed, built=False)
|
|
116
125
|
# The planner records your settings as "set by you"; keep the measured ones you fixed too.
|
|
117
|
-
return dataclasses.replace(out, **{name: getattr(p, name) for name in ("ef", "prefetch") if name in p.fixed()})
|
|
126
|
+
return dataclasses.replace(out, **{name: getattr(p, name) for name in ("ef", "prefetch", "code_bits", "refine_ef", "measure_nav", "check_walk", "measure_code_bits") if name in p.fixed()})
|
|
118
127
|
|
|
119
128
|
|
|
120
129
|
def build(data, metric="l2", labels=None, plan=None, capacity=None, queries=None, **settings):
|
|
@@ -8,9 +8,9 @@ retrieval, TREC run files, relevance judgements and the standard measures.
|
|
|
8
8
|
ir.write_run(run, "run.txt", tag="epzero-hybrid") # TREC format, for CLEF, TREC or BEIR
|
|
9
9
|
print(ir.evaluate(run, ir.read_qrels("qrels.txt"))) # nDCG@10, R@100, MAP, MRR@10
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
from the run scores 0.
|
|
11
|
+
Runs are ranked by score (ties by document id, descending) and nDCG uses linear gains. By default,
|
|
12
|
+
every query with at least one relevant judgment is scored; evaluate also supports judged and explicit
|
|
13
|
+
query populations. A query missing from the run scores 0.
|
|
14
14
|
"""
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
@@ -152,13 +152,13 @@ class Collection:
|
|
|
152
152
|
# ---- TREC files ----
|
|
153
153
|
|
|
154
154
|
def write_run(run: Run, path: str, tag: str = "epzero") -> None:
|
|
155
|
-
"""A TREC run file
|
|
155
|
+
"""A TREC run file, preserving binary64 scores through a text round trip."""
|
|
156
156
|
if any(c.isspace() for c in tag):
|
|
157
157
|
raise ValueError("the run tag must not contain whitespace")
|
|
158
158
|
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
|
159
159
|
for qid, ranked in run.items():
|
|
160
160
|
for rank, (doc_id, score) in enumerate(ranked, start=1):
|
|
161
|
-
f.write(f"{qid} Q0 {doc_id} {rank} {score:.
|
|
161
|
+
f.write(f"{qid} Q0 {doc_id} {rank} {score:.17g} {tag}\n")
|
|
162
162
|
|
|
163
163
|
|
|
164
164
|
def read_run(path: str) -> Run:
|
|
@@ -176,7 +176,7 @@ def read_run(path: str) -> Run:
|
|
|
176
176
|
|
|
177
177
|
def read_qrels(path: str) -> Qrels:
|
|
178
178
|
"""Reads relevance judgements: TREC (`query 0 document relevance`) or BEIR's TSV with a header
|
|
179
|
-
(`query-id corpus-id score`)."""
|
|
179
|
+
(`query-id corpus-id score`). Rejects fractional/nonfinite labels and duplicate judgments."""
|
|
180
180
|
qrels: Qrels = {}
|
|
181
181
|
with open(path, encoding="utf-8") as f:
|
|
182
182
|
for line in f:
|
|
@@ -189,7 +189,12 @@ def read_qrels(path: str) -> Qrels:
|
|
|
189
189
|
qid, doc_id, rel = parts
|
|
190
190
|
else:
|
|
191
191
|
raise ValueError(f"{path}: unexpected line {line.strip()!r}")
|
|
192
|
-
|
|
192
|
+
value = float(rel)
|
|
193
|
+
if not math.isfinite(value) or not value.is_integer():
|
|
194
|
+
raise ValueError(f"{path}: relevance must be a finite integer, got {rel!r}")
|
|
195
|
+
if doc_id in qrels.get(qid, {}):
|
|
196
|
+
raise ValueError(f"{path}: duplicate judgment for {qid!r}, {doc_id!r}")
|
|
197
|
+
qrels.setdefault(qid, {})[doc_id] = int(value)
|
|
193
198
|
return qrels
|
|
194
199
|
|
|
195
200
|
|
|
@@ -206,7 +211,7 @@ def _measure(name: str, ranked: list[str], judged: dict[str, int]) -> float:
|
|
|
206
211
|
idcg = sum(r / math.log2(i + 2) for i, r in enumerate(ideal))
|
|
207
212
|
return dcg / idcg if idcg > 0 else 0.0
|
|
208
213
|
if base == "R":
|
|
209
|
-
return sum(1 for d in top if d in relevant) / len(relevant)
|
|
214
|
+
return sum(1 for d in top if d in relevant) / len(relevant) if relevant else 0.0
|
|
210
215
|
if base == "P":
|
|
211
216
|
return sum(1 for d in top if d in relevant) / depth
|
|
212
217
|
if base == "MAP":
|
|
@@ -215,22 +220,39 @@ def _measure(name: str, ranked: list[str], judged: dict[str, int]) -> float:
|
|
|
215
220
|
if d in relevant:
|
|
216
221
|
hits += 1
|
|
217
222
|
total += hits / (i + 1)
|
|
218
|
-
return total / len(relevant)
|
|
223
|
+
return total / len(relevant) if relevant else 0.0
|
|
219
224
|
if base in ("MRR", "RR"):
|
|
220
225
|
return next((1.0 / (i + 1) for i, d in enumerate(top) if d in relevant), 0.0)
|
|
221
226
|
raise ValueError(f"unknown measure {name}: use nDCG@k, R@k, P@k, MAP or MRR@k")
|
|
222
227
|
|
|
223
228
|
|
|
224
|
-
def evaluate(run: Run, qrels: Qrels, measures: Sequence[str] = DEFAULT_MEASURES, per_query: bool = False
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
229
|
+
def evaluate(run: Run, qrels: Qrels, measures: Sequence[str] = DEFAULT_MEASURES, per_query: bool = False,
|
|
230
|
+
*, population: str = "positive", query_ids: Sequence[str] | None = None):
|
|
231
|
+
"""Mean measures, or {measure: {query: value}} with per_query.
|
|
232
|
+
|
|
233
|
+
population='positive' preserves the historical positive-judgment cohort. 'judged' includes
|
|
234
|
+
every qrels query, and 'explicit' uses query_ids (including unjudged queries). Missing runs and
|
|
235
|
+
zero-IDCG queries score zero. These policies are explicit choices, not a claim of official
|
|
236
|
+
benchmark compatibility.
|
|
237
|
+
"""
|
|
238
|
+
if population not in ("positive", "judged", "explicit"):
|
|
239
|
+
raise ValueError("population must be positive, judged or explicit")
|
|
240
|
+
if (query_ids is not None) != (population == "explicit"):
|
|
241
|
+
raise ValueError("query_ids must be supplied exactly for population='explicit'")
|
|
242
|
+
if population == "explicit":
|
|
243
|
+
queries = list(query_ids)
|
|
244
|
+
if len(queries) != len(set(queries)):
|
|
245
|
+
raise ValueError("query_ids must be unique")
|
|
246
|
+
elif population == "judged":
|
|
247
|
+
queries = list(qrels)
|
|
248
|
+
else:
|
|
249
|
+
queries = [q for q, judged in qrels.items() if any(r > 0 for r in judged.values())]
|
|
228
250
|
values = {m: {} for m in measures}
|
|
229
251
|
for qid in queries:
|
|
230
252
|
# trec_eval's order, whatever the run's: by score, ties by document id, both descending.
|
|
231
253
|
ranked = [d for d, _ in sorted(run.get(qid, []), key=lambda p: (p[1], p[0]), reverse=True)]
|
|
232
254
|
for m in measures:
|
|
233
|
-
values[m][qid] = _measure(m, ranked, qrels
|
|
255
|
+
values[m][qid] = _measure(m, ranked, qrels.get(qid, {}))
|
|
234
256
|
if per_query:
|
|
235
257
|
return values
|
|
236
258
|
return {m: (sum(v.values()) / len(v) if v else 0.0) for m, v in values.items()}
|