llama-index-vector-stores-rabitqlib 0.1.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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ .coverage
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.5
2
+ Name: llama-index-vector-stores-rabitqlib
3
+ Version: 0.1.0
4
+ Summary: LlamaIndex vector store backed by RaBitQ-quantized HNSW (rabitqlib)
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: <4.0,>=3.10
8
+ Requires-Dist: llama-index-core<0.15,>=0.13.0
9
+ Requires-Dist: numpy>=1.24
10
+ Requires-Dist: rabitqlib<0.9,>=0.8.3
11
+ Description-Content-Type: text/markdown
12
+
13
+ # llama-index-vector-stores-rabitqlib
14
+
15
+ A [LlamaIndex](https://github.com/run-llama/llama_index) vector store backed by [RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library)-quantized HNSW (`rabitqlib.HnswIndex`). It's a local, in-process index, a drop-in for `SimpleVectorStore` or `FaissVectorStore`, and stores compressed vectors (default 7 bits per dimension).
16
+
17
+ Status: v0.1, not yet published to PyPI.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install -e . # from this folder; pulls llama-index-core and rabitqlib>=0.8.3
23
+ ```
24
+
25
+ ## Quickstart
26
+
27
+ ```python
28
+ from llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage
29
+ from llama_index.vector_stores.rabitqlib import RabitqHnswVectorStore
30
+
31
+ vector_store = RabitqHnswVectorStore(dim=1536) # your embedding model's dimension
32
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
33
+ index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
34
+
35
+ nodes = index.as_retriever(similarity_top_k=5).retrieve("my question")
36
+ index.delete_ref_doc("some-doc-id", delete_from_docstore=True)
37
+
38
+ # Persist and reload. The vector store has to be loaded explicitly, because
39
+ # StorageContext.from_defaults(persist_dir=...) alone would load SimpleVectorStore.
40
+ index.storage_context.persist(persist_dir="./storage")
41
+ vector_store = RabitqHnswVectorStore.from_persist_dir("./storage")
42
+ storage_context = StorageContext.from_defaults(
43
+ vector_store=vector_store, persist_dir="./storage"
44
+ )
45
+ index = load_index_from_storage(storage_context)
46
+ ```
47
+
48
+ `examples/quickstart.py` is a runnable offline version that uses a toy embedding and no LLM. It passes `min_train_size=1` so its three documents go into the HNSW index. With the default of 1024, a store that small is answered by an exact scan of the buffer and never reaches RaBitQ (see "Training is deferred" below).
49
+
50
+ ## Options
51
+
52
+ | Option | Default | Meaning |
53
+ |---|---|---|
54
+ | `dim` | required | Embedding dimension, 64 to 65536. |
55
+ | `metric` | `"cosine"` | `"cosine"` (normalizes vectors, then uses inner product), `"ip"`, or `"l2"`. |
56
+ | `nbits` | 7 | RaBitQ bits per dimension, 1 to 9. Fewer bits means less memory and lower recall. |
57
+ | `M`, `ef_construction` | 16, 200 | HNSW graph parameters. |
58
+ | `num_clusters` | 16 | RaBitQ centroids, trained once. |
59
+ | `seed` | 100 | Graph, rotation and clustering seed. |
60
+ | `ef` | `max(k, 64)` | Search breadth; always raised to at least `similarity_top_k`. Can be changed at any time (`store.ef = 128`). |
61
+ | `num_threads` | library default | Threads for add, train and search; `0` means all CPUs. With more than one thread the graph is built in a nondeterministic order, so results can differ slightly between runs. Use `1` for a reproducible graph. |
62
+ | `min_train_size` | 1024 | Embeddings buffered before the index is trained (see below). |
63
+ | `train_vectors` / `centroids` | none | Train up front instead of buffering. Centroids are used as given. |
64
+
65
+ ## How it works
66
+
67
+ - **Text lives in LlamaIndex's docstore** (`stores_text = False`), as with FAISS. The store keeps only embeddings plus a node-ID ↔ index-ID map and a ref-doc ↔ node map.
68
+ - **Training is deferred.** RaBitQ trains its centroids once, on the first vectors it gets, and can't retrain afterwards. Training on a handful of vectors would hurt every later query. So until `min_train_size` embeddings have arrived they're kept in a float32 buffer and searched exactly. When the threshold is reached, the whole buffer is added to a new `HnswIndex` in one call, which trains on it. Pass `train_vectors=` or `centroids=` to skip the buffer.
69
+ - **Adds are batched.** Each `add(nodes)` makes one `HnswIndex.add` call. Re-adding an existing node ID replaces its embedding.
70
+ - **Scores are higher-is-better**, computed from RaBitQ distance *estimates*. They're close to exact at `nbits=7`, but not exact:
71
+ - `cosine`: cosine similarity, clipped to [-1, 1];
72
+ - `ip`: inner product (unbounded);
73
+ - `l2`: `1 / (1 + squared_l2)`, in (0, 1].
74
+ - **Persistence.** `persist(path)` writes JSON metadata to `path` (for example `default__vector_store.json`). Alongside it go `path.hnsw` (the index), `path.buffer.npy` (vectors still buffered) or `path.train.npy` (training data not yet used). The JSON has a `format_version`. Only the local filesystem is supported.
75
+ - **Thread safety.** Queries and `persist` run concurrently with each other, though two `persist` calls run one at a time. Add, delete and clear are exclusive. Waiting writers don't block new queries, so a continuous stream of overlapping queries can hold an add back indefinitely. That's unlikely with RAG-style traffic.
76
+
77
+ ## Limitations (v0.1)
78
+
79
+ - **No metadata filters.** A query with `filters`, or `delete_nodes(filters=...)`, raises `ValueError`, and so does a query restricted to `doc_ids`. Only the default query mode is supported, so no MMR, hybrid or sparse search.
80
+ - **`node_ids` on a query is ignored**, as in `FaissVectorStore`, so `index.as_retriever(node_ids=subset)` searches every node. `as_retriever()` always passes the node IDs it knew about when it was created. Honouring that list would break long-lived retrievers after an insert, and would cost O(n) per query.
81
+ - **Deletes don't reclaim memory.** Deleted nodes are excluded from results but stay in storage. To reclaim it, rebuild from your documents.
82
+ - **Accuracy is bounded by quantization.** Recall can plateau below 1.0 however large `ef` is (see below). Raise `nbits` for higher accuracy.
83
+ - **No compaction or retraining.** Centroids are fixed after the first training. If your data drifts a lot, rebuild.
84
+
85
+ ## Measured recall
86
+
87
+ Run with `examples/recall.py`. Setup: 10,000 base and 200 query vectors, dim 128, drawn from 50 Gaussian clusters (seed 0); default `M=16`, `ef_construction=200`, `num_clusters=16`; graph built with `num_threads=1`, so runs are reproducible; top-10 compared against an exact NumPy scan. Machine: 96-core Linux, rabitqlib 0.8.3, llama-index-core 0.14.25. With multi-threaded builds, expect differences of about ±0.002.
88
+
89
+ | metric | nbits | ef=64 | ef=128 | ef=256 |
90
+ |---|---|---|---|---|
91
+ | cosine | 4 | 0.7335 | 0.7335 | 0.7335 |
92
+ | cosine | 7 | 0.9510 | 0.9510 | 0.9510 |
93
+ | l2 | 4 | 0.7685 | 0.7680 | 0.7680 |
94
+ | l2 | 7 | 0.9680 | 0.9685 | 0.9685 |
95
+
96
+ On this dataset, recall is limited by the quantized distance estimates, not by graph search: calling `rabitqlib.HnswIndex` directly gives the same numbers, and they level off from about `ef=64`. `HnswIndex` has no exact re-ranking step, so raising `ef` can't push recall past this ceiling; only a higher `nbits` can. This is one synthetic dataset, so measure on your own embeddings.
97
+
98
+ ## Development
99
+
100
+ ```bash
101
+ python -m pytest --cov=llama_index.vector_stores.rabitqlib
102
+ ruff check . && ruff format --check .
103
+ mypy llama_index tests
104
+ ```
105
+
106
+ ## License
107
+
108
+ Apache-2.0, the same as RaBitQ-Library.
@@ -0,0 +1,96 @@
1
+ # llama-index-vector-stores-rabitqlib
2
+
3
+ A [LlamaIndex](https://github.com/run-llama/llama_index) vector store backed by [RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library)-quantized HNSW (`rabitqlib.HnswIndex`). It's a local, in-process index, a drop-in for `SimpleVectorStore` or `FaissVectorStore`, and stores compressed vectors (default 7 bits per dimension).
4
+
5
+ Status: v0.1, not yet published to PyPI.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install -e . # from this folder; pulls llama-index-core and rabitqlib>=0.8.3
11
+ ```
12
+
13
+ ## Quickstart
14
+
15
+ ```python
16
+ from llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage
17
+ from llama_index.vector_stores.rabitqlib import RabitqHnswVectorStore
18
+
19
+ vector_store = RabitqHnswVectorStore(dim=1536) # your embedding model's dimension
20
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
21
+ index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
22
+
23
+ nodes = index.as_retriever(similarity_top_k=5).retrieve("my question")
24
+ index.delete_ref_doc("some-doc-id", delete_from_docstore=True)
25
+
26
+ # Persist and reload. The vector store has to be loaded explicitly, because
27
+ # StorageContext.from_defaults(persist_dir=...) alone would load SimpleVectorStore.
28
+ index.storage_context.persist(persist_dir="./storage")
29
+ vector_store = RabitqHnswVectorStore.from_persist_dir("./storage")
30
+ storage_context = StorageContext.from_defaults(
31
+ vector_store=vector_store, persist_dir="./storage"
32
+ )
33
+ index = load_index_from_storage(storage_context)
34
+ ```
35
+
36
+ `examples/quickstart.py` is a runnable offline version that uses a toy embedding and no LLM. It passes `min_train_size=1` so its three documents go into the HNSW index. With the default of 1024, a store that small is answered by an exact scan of the buffer and never reaches RaBitQ (see "Training is deferred" below).
37
+
38
+ ## Options
39
+
40
+ | Option | Default | Meaning |
41
+ |---|---|---|
42
+ | `dim` | required | Embedding dimension, 64 to 65536. |
43
+ | `metric` | `"cosine"` | `"cosine"` (normalizes vectors, then uses inner product), `"ip"`, or `"l2"`. |
44
+ | `nbits` | 7 | RaBitQ bits per dimension, 1 to 9. Fewer bits means less memory and lower recall. |
45
+ | `M`, `ef_construction` | 16, 200 | HNSW graph parameters. |
46
+ | `num_clusters` | 16 | RaBitQ centroids, trained once. |
47
+ | `seed` | 100 | Graph, rotation and clustering seed. |
48
+ | `ef` | `max(k, 64)` | Search breadth; always raised to at least `similarity_top_k`. Can be changed at any time (`store.ef = 128`). |
49
+ | `num_threads` | library default | Threads for add, train and search; `0` means all CPUs. With more than one thread the graph is built in a nondeterministic order, so results can differ slightly between runs. Use `1` for a reproducible graph. |
50
+ | `min_train_size` | 1024 | Embeddings buffered before the index is trained (see below). |
51
+ | `train_vectors` / `centroids` | none | Train up front instead of buffering. Centroids are used as given. |
52
+
53
+ ## How it works
54
+
55
+ - **Text lives in LlamaIndex's docstore** (`stores_text = False`), as with FAISS. The store keeps only embeddings plus a node-ID ↔ index-ID map and a ref-doc ↔ node map.
56
+ - **Training is deferred.** RaBitQ trains its centroids once, on the first vectors it gets, and can't retrain afterwards. Training on a handful of vectors would hurt every later query. So until `min_train_size` embeddings have arrived they're kept in a float32 buffer and searched exactly. When the threshold is reached, the whole buffer is added to a new `HnswIndex` in one call, which trains on it. Pass `train_vectors=` or `centroids=` to skip the buffer.
57
+ - **Adds are batched.** Each `add(nodes)` makes one `HnswIndex.add` call. Re-adding an existing node ID replaces its embedding.
58
+ - **Scores are higher-is-better**, computed from RaBitQ distance *estimates*. They're close to exact at `nbits=7`, but not exact:
59
+ - `cosine`: cosine similarity, clipped to [-1, 1];
60
+ - `ip`: inner product (unbounded);
61
+ - `l2`: `1 / (1 + squared_l2)`, in (0, 1].
62
+ - **Persistence.** `persist(path)` writes JSON metadata to `path` (for example `default__vector_store.json`). Alongside it go `path.hnsw` (the index), `path.buffer.npy` (vectors still buffered) or `path.train.npy` (training data not yet used). The JSON has a `format_version`. Only the local filesystem is supported.
63
+ - **Thread safety.** Queries and `persist` run concurrently with each other, though two `persist` calls run one at a time. Add, delete and clear are exclusive. Waiting writers don't block new queries, so a continuous stream of overlapping queries can hold an add back indefinitely. That's unlikely with RAG-style traffic.
64
+
65
+ ## Limitations (v0.1)
66
+
67
+ - **No metadata filters.** A query with `filters`, or `delete_nodes(filters=...)`, raises `ValueError`, and so does a query restricted to `doc_ids`. Only the default query mode is supported, so no MMR, hybrid or sparse search.
68
+ - **`node_ids` on a query is ignored**, as in `FaissVectorStore`, so `index.as_retriever(node_ids=subset)` searches every node. `as_retriever()` always passes the node IDs it knew about when it was created. Honouring that list would break long-lived retrievers after an insert, and would cost O(n) per query.
69
+ - **Deletes don't reclaim memory.** Deleted nodes are excluded from results but stay in storage. To reclaim it, rebuild from your documents.
70
+ - **Accuracy is bounded by quantization.** Recall can plateau below 1.0 however large `ef` is (see below). Raise `nbits` for higher accuracy.
71
+ - **No compaction or retraining.** Centroids are fixed after the first training. If your data drifts a lot, rebuild.
72
+
73
+ ## Measured recall
74
+
75
+ Run with `examples/recall.py`. Setup: 10,000 base and 200 query vectors, dim 128, drawn from 50 Gaussian clusters (seed 0); default `M=16`, `ef_construction=200`, `num_clusters=16`; graph built with `num_threads=1`, so runs are reproducible; top-10 compared against an exact NumPy scan. Machine: 96-core Linux, rabitqlib 0.8.3, llama-index-core 0.14.25. With multi-threaded builds, expect differences of about ±0.002.
76
+
77
+ | metric | nbits | ef=64 | ef=128 | ef=256 |
78
+ |---|---|---|---|---|
79
+ | cosine | 4 | 0.7335 | 0.7335 | 0.7335 |
80
+ | cosine | 7 | 0.9510 | 0.9510 | 0.9510 |
81
+ | l2 | 4 | 0.7685 | 0.7680 | 0.7680 |
82
+ | l2 | 7 | 0.9680 | 0.9685 | 0.9685 |
83
+
84
+ On this dataset, recall is limited by the quantized distance estimates, not by graph search: calling `rabitqlib.HnswIndex` directly gives the same numbers, and they level off from about `ef=64`. `HnswIndex` has no exact re-ranking step, so raising `ef` can't push recall past this ceiling; only a higher `nbits` can. This is one synthetic dataset, so measure on your own embeddings.
85
+
86
+ ## Development
87
+
88
+ ```bash
89
+ python -m pytest --cov=llama_index.vector_stores.rabitqlib
90
+ ruff check . && ruff format --check .
91
+ mypy llama_index tests
92
+ ```
93
+
94
+ ## License
95
+
96
+ Apache-2.0, the same as RaBitQ-Library.
@@ -0,0 +1,3 @@
1
+ from llama_index.vector_stores.rabitqlib.base import RabitqHnswVectorStore
2
+
3
+ __all__ = ["RabitqHnswVectorStore"]
@@ -0,0 +1,625 @@
1
+ """LlamaIndex vector store backed by ``rabitqlib.HnswIndex``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ import threading
9
+ from collections.abc import Iterator, Sequence
10
+ from contextlib import contextmanager
11
+ from typing import Any, Literal
12
+
13
+ import fsspec
14
+ import numpy as np
15
+ import numpy.typing as npt
16
+ from fsspec.implementations.local import LocalFileSystem
17
+ from llama_index.core.bridge.pydantic import Field, PrivateAttr
18
+ from llama_index.core.schema import BaseNode
19
+ from llama_index.core.vector_stores.simple import DEFAULT_VECTOR_STORE, NAMESPACE_SEP
20
+ from llama_index.core.vector_stores.types import (
21
+ DEFAULT_PERSIST_DIR,
22
+ DEFAULT_PERSIST_FNAME,
23
+ BasePydanticVectorStore,
24
+ MetadataFilters,
25
+ VectorStoreQuery,
26
+ VectorStoreQueryMode,
27
+ VectorStoreQueryResult,
28
+ )
29
+ from rabitqlib import HnswIndex
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ FORMAT_VERSION = 1
34
+ DEFAULT_PERSIST_PATH = os.path.join(
35
+ DEFAULT_PERSIST_DIR, f"{DEFAULT_VECTOR_STORE}{NAMESPACE_SEP}{DEFAULT_PERSIST_FNAME}"
36
+ )
37
+ _MISSING_ID = 0xFFFFFFFF
38
+ _HNSW_SUFFIX = ".hnsw"
39
+ _BUFFER_SUFFIX = ".buffer.npy"
40
+ _TRAIN_SUFFIX = ".train.npy"
41
+
42
+ Metric = Literal["cosine", "l2", "ip"]
43
+ FloatArray = npt.NDArray[np.float32]
44
+
45
+
46
+ class _RWLock:
47
+ """
48
+ Many concurrent readers or one writer (not reentrant).
49
+
50
+ Readers are not blocked by a waiting writer, so a continuous stream of
51
+ overlapping queries can delay an add or delete indefinitely. That is
52
+ unlikely with RAG-style traffic, where queries have gaps between them.
53
+ """
54
+
55
+ def __init__(self) -> None:
56
+ self._cond = threading.Condition()
57
+ self._readers = 0
58
+ self._writer = False
59
+
60
+ @contextmanager
61
+ def read(self) -> Iterator[None]:
62
+ with self._cond:
63
+ while self._writer:
64
+ self._cond.wait()
65
+ self._readers += 1
66
+ try:
67
+ yield
68
+ finally:
69
+ with self._cond:
70
+ self._readers -= 1
71
+ if self._readers == 0:
72
+ self._cond.notify_all()
73
+
74
+ @contextmanager
75
+ def write(self) -> Iterator[None]:
76
+ with self._cond:
77
+ while self._writer or self._readers:
78
+ self._cond.wait()
79
+ self._writer = True
80
+ try:
81
+ yield
82
+ finally:
83
+ with self._cond:
84
+ self._writer = False
85
+ self._cond.notify_all()
86
+
87
+
88
+ def _check_local_fs(fs: fsspec.AbstractFileSystem | None) -> None:
89
+ if fs is not None and not isinstance(fs, LocalFileSystem):
90
+ raise NotImplementedError(
91
+ "RabitqHnswVectorStore only supports the local filesystem."
92
+ )
93
+
94
+
95
+ class RabitqHnswVectorStore(BasePydanticVectorStore):
96
+ """
97
+ Vector store backed by a RaBitQ-quantized HNSW graph (``rabitqlib.HnswIndex``).
98
+
99
+ Only embeddings are stored (``stores_text = False``); LlamaIndex keeps node
100
+ text and metadata in its docstore. Metadata filters are not supported, and
101
+ ``VectorStoreQuery.node_ids`` is ignored (as in ``FaissVectorStore``), so
102
+ ``as_retriever(node_ids=subset)`` does not restrict results.
103
+
104
+ Until ``min_train_size`` embeddings have been added, they are buffered and
105
+ queried by exact search. Once the threshold is reached the whole buffer is
106
+ added to a new ``HnswIndex`` in one call, which trains its centroids on it.
107
+ Pass ``train_vectors`` or ``centroids`` to skip buffering.
108
+
109
+ Similarity scores are computed from RaBitQ distance estimates (close to
110
+ exact at the default ``nbits=7``, but not exact) and are higher-is-better:
111
+
112
+ - ``cosine``: cosine similarity in ``[-1, 1]``.
113
+ - ``ip``: inner product (unbounded).
114
+ - ``l2``: ``1 / (1 + squared_l2)`` in ``(0, 1]``.
115
+
116
+ Deleting nodes hides them from results but does not reclaim storage.
117
+
118
+ Examples:
119
+ ```python
120
+ from llama_index.core import StorageContext, VectorStoreIndex
121
+ from llama_index.vector_stores.rabitqlib import RabitqHnswVectorStore
122
+
123
+ vector_store = RabitqHnswVectorStore(dim=1536)
124
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
125
+ index = VectorStoreIndex.from_documents(
126
+ documents, storage_context=storage_context
127
+ )
128
+ ```
129
+
130
+ """
131
+
132
+ stores_text: bool = False
133
+
134
+ dim: int = Field(ge=64, le=65536, description="Embedding dimension.")
135
+ metric: Metric = Field(default="cosine", description="cosine, l2 or ip.")
136
+ nbits: int = Field(default=7, ge=1, le=9, description="RaBitQ bits per dim.")
137
+ M: int = Field(default=16, ge=2, description="HNSW graph connectivity.")
138
+ ef_construction: int = Field(default=200, ge=1)
139
+ num_clusters: int = Field(default=16, ge=1)
140
+ seed: int = Field(default=100, description="Graph and rotation seed.")
141
+ ef: int | None = Field(
142
+ default=None, ge=1, description="Search breadth; default max(k, 64)."
143
+ )
144
+ num_threads: int | None = Field(
145
+ default=None, ge=0, description="Threads for add and search; 0 = all CPUs."
146
+ )
147
+ min_train_size: int = Field(
148
+ default=1024, ge=1, description="Embeddings buffered before training."
149
+ )
150
+
151
+ _index: HnswIndex | None = PrivateAttr(default=None)
152
+ _node_to_label: dict[str, int] = PrivateAttr(default_factory=dict)
153
+ _label_to_node: dict[int, str] = PrivateAttr(default_factory=dict)
154
+ _node_to_ref: dict[str, str] = PrivateAttr(default_factory=dict)
155
+ _ref_to_nodes: dict[str, set[str]] = PrivateAttr(default_factory=dict)
156
+ _buf_vecs: Any = PrivateAttr(default=None)
157
+ _buf_ids: list[str] = PrivateAttr(default_factory=list)
158
+ _pending_train: tuple[str, Any] | None = PrivateAttr(default=None)
159
+ _lock: _RWLock = PrivateAttr(default_factory=_RWLock)
160
+ # Serializes persist() calls; they share temp-file names.
161
+ _persist_lock: Any = PrivateAttr(default_factory=threading.Lock)
162
+
163
+ def __init__(
164
+ self,
165
+ dim: int,
166
+ *,
167
+ metric: Metric = "cosine",
168
+ nbits: int = 7,
169
+ M: int = 16,
170
+ ef_construction: int = 200,
171
+ num_clusters: int = 16,
172
+ seed: int = 100,
173
+ ef: int | None = None,
174
+ num_threads: int | None = None,
175
+ min_train_size: int = 1024,
176
+ train_vectors: npt.ArrayLike | None = None,
177
+ centroids: npt.ArrayLike | None = None,
178
+ ) -> None:
179
+ """
180
+ Create an empty store.
181
+
182
+ Args:
183
+ dim: Embedding dimension, 64 through 65536.
184
+ metric: ``"cosine"`` (default), ``"l2"`` or ``"ip"``.
185
+ nbits: RaBitQ quantization bits, 1 through 9.
186
+ M: HNSW connectivity.
187
+ ef_construction: HNSW construction breadth.
188
+ num_clusters: Number of RaBitQ centroids to train.
189
+ seed: Graph, rotation and clustering seed.
190
+ ef: Search breadth. Defaults to ``max(k, 64)`` and is raised to ``k``.
191
+ num_threads: Threads for add, train and search (library default if None).
192
+ min_train_size: Embeddings to buffer before training the index.
193
+ train_vectors: Optional sample to train centroids on; disables buffering.
194
+ centroids: Optional ``(num_clusters, dim)`` centroids, used as given;
195
+ disables buffering. Overrides ``num_clusters``.
196
+
197
+ """
198
+ pending: tuple[str, FloatArray] | None = None
199
+ if train_vectors is not None and centroids is not None:
200
+ raise ValueError("Pass at most one of train_vectors and centroids.")
201
+ if centroids is not None:
202
+ c = self._as_matrix(centroids, dim, "centroids")
203
+ num_clusters = c.shape[0]
204
+ pending = ("centroids", c)
205
+ elif train_vectors is not None:
206
+ t = self._as_matrix(train_vectors, dim, "train_vectors")
207
+ if metric == "cosine":
208
+ t = self._normalize(t)
209
+ pending = ("train", t)
210
+
211
+ super().__init__(
212
+ stores_text=False,
213
+ dim=dim,
214
+ metric=metric,
215
+ nbits=nbits,
216
+ M=M,
217
+ ef_construction=ef_construction,
218
+ num_clusters=num_clusters,
219
+ seed=seed,
220
+ ef=ef,
221
+ num_threads=num_threads,
222
+ min_train_size=min_train_size,
223
+ )
224
+ self._buf_vecs = np.empty((0, dim), dtype=np.float32)
225
+ self._pending_train = pending
226
+
227
+ @classmethod
228
+ def class_name(cls) -> str:
229
+ return "RabitqHnswVectorStore"
230
+
231
+ @property
232
+ def client(self) -> HnswIndex | None:
233
+ """The underlying ``HnswIndex``, or ``None`` while the store is buffering."""
234
+ return self._index
235
+
236
+ # No __len__: StorageContext.from_defaults tests `if vector_store:`, and an
237
+ # empty store must not be falsy or it is silently replaced.
238
+ @property
239
+ def num_nodes(self) -> int:
240
+ """Number of live (searchable) nodes."""
241
+ with self._lock.read():
242
+ return len(self._buf_ids) + len(self._node_to_label)
243
+
244
+ # ------------------------------------------------------------------ helpers
245
+
246
+ @staticmethod
247
+ def _as_matrix(data: npt.ArrayLike, dim: int, what: str) -> FloatArray:
248
+ arr = np.ascontiguousarray(data, dtype=np.float32)
249
+ if arr.ndim != 2 or arr.shape[1] != dim or arr.shape[0] == 0:
250
+ raise ValueError(f"{what} must have shape (n, {dim}) with n >= 1.")
251
+ if not np.all(np.isfinite(arr)):
252
+ raise ValueError(f"{what} must contain only finite values.")
253
+ return arr
254
+
255
+ @staticmethod
256
+ def _normalize(x: FloatArray) -> FloatArray:
257
+ norms = np.linalg.norm(x, axis=1, keepdims=True)
258
+ if np.any(norms == 0):
259
+ raise ValueError("Cannot use zero vectors with the cosine metric.")
260
+ return np.ascontiguousarray(x / norms, dtype=np.float32)
261
+
262
+ def _prepare(self, x: npt.ArrayLike, what: str) -> FloatArray:
263
+ arr = self._as_matrix(x, self.dim, what)
264
+ return self._normalize(arr) if self.metric == "cosine" else arr
265
+
266
+ def _hnsw_metric(self) -> Literal["l2", "ip"]:
267
+ return "l2" if self.metric == "l2" else "ip"
268
+
269
+ def _new_index(self) -> HnswIndex:
270
+ index = HnswIndex(
271
+ self.dim,
272
+ nbits=self.nbits,
273
+ num_clusters=self.num_clusters,
274
+ M=self.M,
275
+ ef_construction=self.ef_construction,
276
+ metric=self._hnsw_metric(),
277
+ seed=self.seed,
278
+ )
279
+ if self._pending_train is not None:
280
+ kind, data = self._pending_train
281
+ if kind == "centroids":
282
+ index.set_centroids(data)
283
+ else:
284
+ index.train(data, num_threads=self.num_threads)
285
+ return index
286
+
287
+ def _to_similarity(self, d: FloatArray) -> list[float]:
288
+ d = d.astype(np.float64)
289
+ if self.metric == "cosine":
290
+ sims = np.clip(1.0 - d, -1.0, 1.0)
291
+ elif self.metric == "ip":
292
+ sims = 1.0 - d
293
+ else:
294
+ sims = 1.0 / (1.0 + np.maximum(d, 0.0))
295
+ return [float(s) for s in sims]
296
+
297
+ def _exact_distances(self, x: FloatArray, q: FloatArray) -> FloatArray:
298
+ if self.metric == "l2":
299
+ diff = x - q
300
+ return np.einsum("ij,ij->i", diff, diff).astype(np.float32)
301
+ return (1.0 - x @ q).astype(np.float32)
302
+
303
+ def _unlink_ref(self, node_id: str) -> None:
304
+ ref = self._node_to_ref.pop(node_id, None)
305
+ if ref is not None:
306
+ members = self._ref_to_nodes.get(ref)
307
+ if members is not None:
308
+ members.discard(node_id)
309
+ if not members:
310
+ del self._ref_to_nodes[ref]
311
+
312
+ def _remove_unlocked(self, node_ids: Sequence[str]) -> None:
313
+ targets = set(node_ids)
314
+ if not targets:
315
+ return
316
+ if self._buf_ids:
317
+ keep = [i for i, nid in enumerate(self._buf_ids) if nid not in targets]
318
+ if len(keep) != len(self._buf_ids):
319
+ self._buf_vecs = self._buf_vecs[keep]
320
+ self._buf_ids = [self._buf_ids[i] for i in keep]
321
+ labels = [self._node_to_label[n] for n in targets if n in self._node_to_label]
322
+ if labels and self._index is not None:
323
+ self._index.remove(np.asarray(labels, dtype=np.int64))
324
+ for label in labels:
325
+ del self._node_to_label[self._label_to_node.pop(label)]
326
+ for nid in targets:
327
+ self._unlink_ref(nid)
328
+
329
+ # --------------------------------------------------------------- interface
330
+
331
+ def add(self, nodes: Sequence[BaseNode], **add_kwargs: Any) -> list[str]:
332
+ """
333
+ Add nodes with embeddings; returns their node IDs.
334
+
335
+ Re-adding an existing node ID replaces its embedding.
336
+ """
337
+ if not nodes:
338
+ return []
339
+ last: dict[str, int] = {}
340
+ for i, node in enumerate(nodes):
341
+ last[node.node_id] = i
342
+ unique = [nodes[i] for i in sorted(last.values())]
343
+ rows = []
344
+ for node in unique:
345
+ if node.embedding is None:
346
+ raise ValueError(f"Node {node.node_id} has no embedding.")
347
+ if len(node.embedding) != self.dim:
348
+ raise ValueError(
349
+ f"Node {node.node_id} embedding has dimension "
350
+ f"{len(node.embedding)}, expected {self.dim}."
351
+ )
352
+ rows.append(node.embedding)
353
+ vecs = self._prepare(rows, "embeddings")
354
+ ids = [node.node_id for node in unique]
355
+ new_set = set(ids)
356
+
357
+ with self._lock.write():
358
+ if self._index is None:
359
+ keep = [i for i, nid in enumerate(self._buf_ids) if nid not in new_set]
360
+ buf_vecs = self._buf_vecs[keep]
361
+ buf_ids = [self._buf_ids[i] for i in keep]
362
+ all_vecs = np.ascontiguousarray(np.vstack([buf_vecs, vecs]))
363
+ all_ids = buf_ids + ids
364
+ if self._pending_train is None and len(all_ids) < self.min_train_size:
365
+ self._buf_vecs, self._buf_ids = all_vecs, all_ids
366
+ else:
367
+ index = self._new_index()
368
+ labels = index.add(all_vecs, num_threads=self.num_threads)
369
+ self._index = index
370
+ self._pending_train = None
371
+ self._buf_vecs = np.empty((0, self.dim), dtype=np.float32)
372
+ self._buf_ids = []
373
+ for nid, label in zip(all_ids, labels.tolist(), strict=True):
374
+ self._node_to_label[nid] = label
375
+ self._label_to_node[label] = nid
376
+ else:
377
+ labels = self._index.add(vecs, num_threads=self.num_threads)
378
+ old = [self._node_to_label[n] for n in ids if n in self._node_to_label]
379
+ if old:
380
+ self._index.remove(np.asarray(old, dtype=np.int64))
381
+ for label in old:
382
+ del self._label_to_node[label]
383
+ for nid, label in zip(ids, labels.tolist(), strict=True):
384
+ self._node_to_label[nid] = label
385
+ self._label_to_node[label] = nid
386
+ for node in unique:
387
+ self._unlink_ref(node.node_id)
388
+ ref = node.ref_doc_id
389
+ if ref is not None:
390
+ self._node_to_ref[node.node_id] = ref
391
+ self._ref_to_nodes.setdefault(ref, set()).add(node.node_id)
392
+ return [node.node_id for node in nodes]
393
+
394
+ def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
395
+ """Delete every node that belongs to ``ref_doc_id``."""
396
+ with self._lock.write():
397
+ node_ids = list(self._ref_to_nodes.get(ref_doc_id, ()))
398
+ self._remove_unlocked(node_ids)
399
+
400
+ def delete_nodes(
401
+ self,
402
+ node_ids: list[str] | None = None,
403
+ filters: MetadataFilters | None = None,
404
+ **delete_kwargs: Any,
405
+ ) -> None:
406
+ """Delete nodes by ID. Metadata filters are not supported."""
407
+ if filters is not None:
408
+ raise ValueError("Metadata filters are not supported.")
409
+ if not node_ids:
410
+ return
411
+ with self._lock.write():
412
+ self._remove_unlocked(node_ids)
413
+
414
+ def clear(self) -> None:
415
+ """
416
+ Remove everything and return to the empty, buffering state.
417
+
418
+ Any ``train_vectors`` or ``centroids`` given at construction are not kept.
419
+ """
420
+ with self._lock.write():
421
+ self._index = None
422
+ self._pending_train = None
423
+ self._node_to_label = {}
424
+ self._label_to_node = {}
425
+ self._node_to_ref = {}
426
+ self._ref_to_nodes = {}
427
+ self._buf_vecs = np.empty((0, self.dim), dtype=np.float32)
428
+ self._buf_ids = []
429
+
430
+ def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
431
+ """Return the ``similarity_top_k`` nearest node IDs and similarities."""
432
+ if query.filters is not None:
433
+ raise ValueError("Metadata filters are not supported.")
434
+ if query.doc_ids:
435
+ raise ValueError("Restricting queries by doc_ids is not supported.")
436
+ if query.mode != VectorStoreQueryMode.DEFAULT:
437
+ raise ValueError(f"Query mode {query.mode!r} is not supported.")
438
+ if query.query_embedding is None:
439
+ raise ValueError("query_embedding is required.")
440
+ if len(query.query_embedding) != self.dim:
441
+ raise ValueError(
442
+ f"Query embedding has dimension {len(query.query_embedding)}, "
443
+ f"expected {self.dim}."
444
+ )
445
+ q = self._prepare([query.query_embedding], "query_embedding")
446
+ k = query.similarity_top_k
447
+
448
+ ids: list[str] = []
449
+ dists = np.empty(0, dtype=np.float32)
450
+ # query.node_ids is deliberately ignored: VectorIndexRetriever always
451
+ # passes every node ID it knew of when it was created, which goes stale
452
+ # after an insert, and checking it would cost O(n) per query.
453
+ with self._lock.read():
454
+ if k < 1:
455
+ pass
456
+ elif self._index is None:
457
+ n = len(self._buf_ids)
458
+ if n:
459
+ d = self._exact_distances(self._buf_vecs, q[0])
460
+ order = np.argsort(d, kind="stable")[: min(k, n)]
461
+ ids = [self._buf_ids[i] for i in order.tolist()]
462
+ dists = d[order]
463
+ elif len(self._node_to_label):
464
+ kk = min(k, len(self._node_to_label))
465
+ ef = max(self.ef if self.ef is not None else max(kk, 64), kk)
466
+ labels, d = self._index.search(
467
+ q, kk, ef=ef, num_threads=self.num_threads
468
+ )
469
+ keep = [
470
+ j
471
+ for j, (label, dist) in enumerate(
472
+ zip(labels[0].tolist(), d[0], strict=True)
473
+ )
474
+ if label != _MISSING_ID
475
+ and np.isfinite(dist)
476
+ and label in self._label_to_node
477
+ ]
478
+ ids = [self._label_to_node[int(labels[0][j])] for j in keep]
479
+ dists = d[0][keep]
480
+ return VectorStoreQueryResult(
481
+ nodes=None, similarities=self._to_similarity(dists), ids=ids
482
+ )
483
+
484
+ # ------------------------------------------------------------- persistence
485
+
486
+ def persist(
487
+ self,
488
+ persist_path: str = DEFAULT_PERSIST_PATH,
489
+ fs: fsspec.AbstractFileSystem | None = None,
490
+ ) -> None:
491
+ """
492
+ Save the store.
493
+
494
+ Writes JSON metadata to ``persist_path`` and, as needed, the index to
495
+ ``<persist_path>.hnsw``, the buffer to ``<persist_path>.buffer.npy`` and
496
+ pending training data to ``<persist_path>.train.npy``.
497
+
498
+ Queries keep running while saving; adds and deletes wait for it.
499
+ """
500
+ _check_local_fs(fs)
501
+ dirpath = os.path.dirname(persist_path)
502
+ if dirpath:
503
+ os.makedirs(dirpath, exist_ok=True)
504
+
505
+ with self._persist_lock, self._lock.read():
506
+ files: dict[str, str] = {}
507
+ if self._index is not None:
508
+ files["hnsw"] = persist_path + _HNSW_SUFFIX
509
+ tmp = files["hnsw"] + ".tmp"
510
+ self._index.save(tmp)
511
+ os.replace(tmp, files["hnsw"])
512
+ if self._buf_ids:
513
+ files["buffer"] = persist_path + _BUFFER_SUFFIX
514
+ self._save_npy(files["buffer"], self._buf_vecs)
515
+ pending_kind = None
516
+ if self._pending_train is not None:
517
+ pending_kind, data = self._pending_train
518
+ files["train"] = persist_path + _TRAIN_SUFFIX
519
+ self._save_npy(files["train"], data)
520
+
521
+ meta = {
522
+ "format_version": FORMAT_VERSION,
523
+ "config": self._config(),
524
+ "pending_train": pending_kind,
525
+ "files": {k: os.path.basename(v) for k, v in files.items()},
526
+ "labels": [[n, lbl] for n, lbl in self._node_to_label.items()],
527
+ "buffer_ids": list(self._buf_ids),
528
+ "refs": dict(self._node_to_ref),
529
+ }
530
+ tmp = persist_path + ".tmp"
531
+ with open(tmp, "w", encoding="utf-8") as f:
532
+ json.dump(meta, f)
533
+ os.replace(tmp, persist_path)
534
+
535
+ for suffix in (_HNSW_SUFFIX, _BUFFER_SUFFIX, _TRAIN_SUFFIX):
536
+ stale = persist_path + suffix
537
+ if stale not in files.values() and os.path.exists(stale):
538
+ os.remove(stale)
539
+
540
+ def _config(self) -> dict[str, Any]:
541
+ return {
542
+ "dim": self.dim,
543
+ "metric": self.metric,
544
+ "nbits": self.nbits,
545
+ "M": self.M,
546
+ "ef_construction": self.ef_construction,
547
+ "num_clusters": self.num_clusters,
548
+ "seed": self.seed,
549
+ "ef": self.ef,
550
+ "num_threads": self.num_threads,
551
+ "min_train_size": self.min_train_size,
552
+ }
553
+
554
+ @staticmethod
555
+ def _save_npy(path: str, arr: Any) -> None:
556
+ tmp = path + ".tmp"
557
+ with open(tmp, "wb") as f:
558
+ np.save(f, np.asarray(arr, dtype=np.float32), allow_pickle=False)
559
+ os.replace(tmp, path)
560
+
561
+ @classmethod
562
+ def from_persist_path(
563
+ cls,
564
+ persist_path: str,
565
+ fs: fsspec.AbstractFileSystem | None = None,
566
+ **overrides: Any,
567
+ ) -> RabitqHnswVectorStore:
568
+ """
569
+ Load a store saved by :meth:`persist`.
570
+
571
+ ``overrides`` may set the search-time options ``ef`` and ``num_threads``.
572
+ """
573
+ _check_local_fs(fs)
574
+ if not os.path.exists(persist_path):
575
+ raise ValueError(f"No RabitqHnswVectorStore found at {persist_path}.")
576
+ with open(persist_path, encoding="utf-8") as f:
577
+ meta = json.load(f)
578
+ version = meta.get("format_version")
579
+ if version != FORMAT_VERSION:
580
+ raise ValueError(
581
+ f"Unsupported format_version {version!r}; expected {FORMAT_VERSION}."
582
+ )
583
+ unknown = set(overrides) - {"ef", "num_threads"}
584
+ if unknown:
585
+ raise TypeError(f"Unexpected overrides: {sorted(unknown)}")
586
+ config = {**meta["config"], **overrides}
587
+ store = cls(**config)
588
+ base = os.path.dirname(persist_path)
589
+ files = meta["files"]
590
+
591
+ if "hnsw" in files:
592
+ index = HnswIndex.load(os.path.join(base, files["hnsw"]))
593
+ if index.dim != store.dim or index.metric != store._hnsw_metric():
594
+ raise ValueError("Saved index does not match the saved config.")
595
+ store._index = index
596
+ for nid, label in meta["labels"]:
597
+ store._node_to_label[nid] = int(label)
598
+ store._label_to_node[int(label)] = nid
599
+ if "buffer" in files:
600
+ buf = np.load(os.path.join(base, files["buffer"]), allow_pickle=False)
601
+ store._buf_vecs = np.ascontiguousarray(buf, dtype=np.float32)
602
+ store._buf_ids = list(meta["buffer_ids"])
603
+ if store._buf_vecs.shape != (len(store._buf_ids), store.dim):
604
+ raise ValueError("Saved buffer does not match its IDs.")
605
+ if "train" in files:
606
+ data = np.load(os.path.join(base, files["train"]), allow_pickle=False)
607
+ store._pending_train = (meta["pending_train"], data)
608
+ for nid, ref in meta["refs"].items():
609
+ store._node_to_ref[nid] = ref
610
+ store._ref_to_nodes.setdefault(ref, set()).add(nid)
611
+ return store
612
+
613
+ @classmethod
614
+ def from_persist_dir(
615
+ cls,
616
+ persist_dir: str = DEFAULT_PERSIST_DIR,
617
+ fs: fsspec.AbstractFileSystem | None = None,
618
+ **overrides: Any,
619
+ ) -> RabitqHnswVectorStore:
620
+ """Load the default-namespace store saved by ``StorageContext.persist``."""
621
+ _check_local_fs(fs)
622
+ persist_path = os.path.join(
623
+ persist_dir, f"{DEFAULT_VECTOR_STORE}{NAMESPACE_SEP}{DEFAULT_PERSIST_FNAME}"
624
+ )
625
+ return cls.from_persist_path(persist_path, **overrides)
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "llama-index-vector-stores-rabitqlib"
7
+ version = "0.1.0"
8
+ description = "LlamaIndex vector store backed by RaBitQ-quantized HNSW (rabitqlib)"
9
+ requires-python = ">=3.10,<4.0"
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ dependencies = [
13
+ "llama-index-core>=0.13.0,<0.15",
14
+ "rabitqlib>=0.8.3,<0.9",
15
+ "numpy>=1.24",
16
+ ]
17
+
18
+ [dependency-groups]
19
+ dev = ["pytest", "pytest-cov", "ruff", "mypy"]
20
+ bench = ["faiss-cpu", "llama-index-vector-stores-faiss"]
21
+
22
+ [tool.hatch.build.targets.sdist]
23
+ include = ["llama_index/"]
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ include = ["llama_index/"]
27
+
28
+ [tool.llamahub]
29
+ contains_example = false
30
+ import_path = "llama_index.vector_stores.rabitqlib"
31
+
32
+ [tool.llamahub.class_authors]
33
+ RabitqHnswVectorStore = "rabitq"
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+
38
+ [tool.ruff]
39
+ line-length = 88
40
+ target-version = "py310"
41
+
42
+ [tool.ruff.lint]
43
+ select = ["E", "F", "I", "B", "UP"]
44
+
45
+ [tool.ruff.lint.isort]
46
+ known-third-party = ["rabitqlib"]
47
+
48
+ [tool.mypy]
49
+ disallow_untyped_defs = true
50
+ ignore_missing_imports = true
51
+ python_version = "3.10"
52
+ exclude = ["examples", ".venv"]
53
+ explicit_package_bases = true
54
+ namespace_packages = true
55
+ plugins = ["pydantic.mypy"]