kci-vec 0.2.16__py3-none-win_amd64.whl
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.
- kci_vec/__init__.py +666 -0
- kci_vec/hybrid.py +208 -0
- kci_vec/libkci_sparse.dll +0 -0
- kci_vec/libkci_vec_avx2.dll +0 -0
- kci_vec/sparse.py +349 -0
- kci_vec/text.py +617 -0
- kci_vec-0.2.16.dist-info/METADATA +54 -0
- kci_vec-0.2.16.dist-info/RECORD +11 -0
- kci_vec-0.2.16.dist-info/WHEEL +5 -0
- kci_vec-0.2.16.dist-info/licenses/LICENSE +21 -0
- kci_vec-0.2.16.dist-info/top_level.txt +1 -0
kci_vec/__init__.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
"""kci_vec — embedded Python binding for the kci_vec vector engine.
|
|
2
|
+
|
|
3
|
+
In-process, no server: this loads the kci_vec C shared library via ctypes and exposes a small Pythonic API.
|
|
4
|
+
Two ways to search (an int8 HNSW graph, and partitioned lists with 4-bit table lookup — the fast one), float /
|
|
5
|
+
int8 re-rank, metadata filtering, incremental update, and snapshots encrypted at rest (AES-256-CTR +
|
|
6
|
+
AES-256-CMAC) — all inside your process, no data leaving the machine.
|
|
7
|
+
|
|
8
|
+
from kci_vec import KciVec
|
|
9
|
+
import numpy as np
|
|
10
|
+
v = KciVec(dim=384, rerank=200) # keep floats for re-rank
|
|
11
|
+
v.add_many(ids, embeddings) # float32 [n, dim]
|
|
12
|
+
v.build_lists() # fast path (lists); or v.build() for the graph
|
|
13
|
+
for doc_id, score in v.search(query_vec, k=5):
|
|
14
|
+
...
|
|
15
|
+
ids, scores = v.search_many(queries, k=5) # [nq, k] arrays
|
|
16
|
+
v.search(query_vec, k=5, filter=lambda id: id in allowed) # metadata / ACL
|
|
17
|
+
v.save("index.kv", key=b"secret") # encrypted at rest
|
|
18
|
+
w = KciVec(dim=128, rerank=200, metric="l2") # Euclidean: scores are |q - x|^2, smallest first
|
|
19
|
+
u = KciVec(dim=128, rerank=400, metric="ip") # inner product: scores are q.x, largest first
|
|
20
|
+
v2 = KciVec.load("index.kv", key=b"secret")
|
|
21
|
+
|
|
22
|
+
Build the library first:
|
|
23
|
+
gcc -O3 -maes -mavx2 -mfma -shared -static -static-libgcc -o libkci_vec.dll kci_vec.c # Windows
|
|
24
|
+
sh build_kci_vec.sh # POSIX (libkci_vec.so/.dylib)
|
|
25
|
+
Set KCI_VEC_LIB to the .dll/.so/.dylib, or place it next to this file / repo root."""
|
|
26
|
+
import ctypes as C
|
|
27
|
+
import os
|
|
28
|
+
import sys
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
c_f32p = C.POINTER(C.c_float)
|
|
32
|
+
c_u64p = C.POINTER(C.c_uint64)
|
|
33
|
+
_FILTER = C.CFUNCTYPE(C.c_int, C.c_uint64, C.c_void_p) # int filt(uint64 id, void *ctx)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _IvfParams(C.Structure):
|
|
37
|
+
_fields_ = [("nlist", C.c_int), ("threads", C.c_int), ("soar", C.c_float), ("code_dims", C.c_int), ("lowrank", C.c_int)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _find_lib():
|
|
41
|
+
if os.environ.get("KCI_VEC_LIB"):
|
|
42
|
+
return os.environ["KCI_VEC_LIB"]
|
|
43
|
+
names = ["libkci_vec.dll", "libkci_vec.so", "libkci_vec.dylib"] if sys.platform == "win32" \
|
|
44
|
+
else ["libkci_vec.so", "libkci_vec.dylib", "libkci_vec.dll"]
|
|
45
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
46
|
+
# is compiled): libkci_vec_avx512.so needs AVX-512 BW + VNNI, libkci_vec_avx2.so needs AVX2 + FMA. Chosen by the
|
|
47
|
+
# CPU's flags; a plain libkci_vec.so next to this file (built for this machine) still wins when present.
|
|
48
|
+
if sys.platform.startswith("linux") and not os.path.exists(os.path.join(here, "libkci_vec.so")):
|
|
49
|
+
try:
|
|
50
|
+
flags = open("/proc/cpuinfo").read().split("flags")[1].split("\n")[0].split()
|
|
51
|
+
except Exception:
|
|
52
|
+
flags = []
|
|
53
|
+
for n, need in (("libkci_vec_avx512.so", ("avx512bw", "avx512_vnni")), ("libkci_vec_avx2.so", ("avx2", "fma"))):
|
|
54
|
+
p = os.path.join(here, n)
|
|
55
|
+
if os.path.exists(p) and all(f in flags for f in need):
|
|
56
|
+
return p
|
|
57
|
+
# The Windows wheel carries one library, libkci_vec_avx2.dll (AVX2 + FMA + AES, no other DLLs needed). A CPU
|
|
58
|
+
# without AVX2 would stop inside the DLL with an illegal instruction and no message, so the OS is asked first; a
|
|
59
|
+
# libkci_vec.dll next to this file (built for this machine: pip install . from the source) still wins.
|
|
60
|
+
# KCI_VEC_SKIP_CPU_CHECK=1 skips the question (an old Windows that does not know it answers no).
|
|
61
|
+
if sys.platform == "win32" and not os.path.exists(os.path.join(here, "libkci_vec.dll")):
|
|
62
|
+
p = os.path.join(here, "libkci_vec_avx2.dll")
|
|
63
|
+
if os.path.exists(p):
|
|
64
|
+
if not os.environ.get("KCI_VEC_SKIP_CPU_CHECK"):
|
|
65
|
+
try:
|
|
66
|
+
has = bool(C.windll.kernel32.IsProcessorFeaturePresent(40)) # PF_AVX2_INSTRUCTIONS_AVAILABLE
|
|
67
|
+
except Exception:
|
|
68
|
+
has = True
|
|
69
|
+
if not has:
|
|
70
|
+
raise RuntimeError("kci_vec: this CPU (or this Windows) does not report AVX2, which the distributed "
|
|
71
|
+
"library needs. Build from the source for this machine (pip install . in "
|
|
72
|
+
"clients/python), or set KCI_VEC_SKIP_CPU_CHECK=1 if the CPU does have AVX2.")
|
|
73
|
+
return p
|
|
74
|
+
# package dir first (pip-installed bundled lib), then repo root(s), then cwd
|
|
75
|
+
roots = [here, os.path.join(here, "..", ".."),
|
|
76
|
+
os.path.join(here, "..", "..", "..", ".."), os.getcwd()]
|
|
77
|
+
for r in roots:
|
|
78
|
+
for n in names:
|
|
79
|
+
p = os.path.abspath(os.path.join(r, n))
|
|
80
|
+
if os.path.exists(p):
|
|
81
|
+
return p
|
|
82
|
+
raise FileNotFoundError("libkci_vec not found; set KCI_VEC_LIB or build it (see module docstring)")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _bind(lib):
|
|
86
|
+
s = lib
|
|
87
|
+
s.kci_vec_new.restype = C.c_void_p; s.kci_vec_new.argtypes = [C.c_int, C.c_int, C.c_int]
|
|
88
|
+
s.kci_vec_free.argtypes = [C.c_void_p]
|
|
89
|
+
s.kci_vec_keep_float.argtypes = [C.c_void_p, C.c_int]
|
|
90
|
+
if hasattr(s, "kci_vec_half_floats"):
|
|
91
|
+
s.kci_vec_half_floats.restype = C.c_int; s.kci_vec_half_floats.argtypes = [C.c_void_p]
|
|
92
|
+
if hasattr(s, "kci_vec_build_qg_res"):
|
|
93
|
+
s.kci_vec_build_qg_res.restype = C.c_int; s.kci_vec_build_qg_res.argtypes = [C.c_void_p, C.c_int, C.c_int, C.c_int]
|
|
94
|
+
if hasattr(s, "kci_vec_search_only"):
|
|
95
|
+
s.kci_vec_search_only.restype = C.c_int; s.kci_vec_search_only.argtypes = [C.c_void_p]
|
|
96
|
+
s.kci_vec_reserve.argtypes = [C.c_void_p, C.c_uint32]
|
|
97
|
+
s.kci_vec_add.restype = C.c_int64; s.kci_vec_add.argtypes = [C.c_void_p, C.c_uint64, c_f32p]
|
|
98
|
+
s.kci_vec_build.argtypes = [C.c_void_p, C.c_int, C.POINTER(C.c_double)]
|
|
99
|
+
if hasattr(s, "kci_vec_build_fast"):
|
|
100
|
+
s.kci_vec_build_fast.restype = C.c_int; s.kci_vec_build_fast.argtypes = [C.c_void_p, C.c_int, C.POINTER(C.c_double)]
|
|
101
|
+
s.kci_vec_build_ivf_p.restype = C.c_int; s.kci_vec_build_ivf_p.argtypes = [C.c_void_p, C.POINTER(_IvfParams)]
|
|
102
|
+
s.kci_vec_searcher_new.restype = C.c_void_p; s.kci_vec_searcher_new.argtypes = [C.c_void_p]
|
|
103
|
+
s.kci_vec_searcher_free.argtypes = [C.c_void_p]
|
|
104
|
+
s.kci_vec_searcher_set_rerank_int8.argtypes = [C.c_void_p, C.c_int]
|
|
105
|
+
if hasattr(s, "kci_vec_searcher_set_probe_gap"):
|
|
106
|
+
s.kci_vec_searcher_set_probe_gap.restype = C.c_int
|
|
107
|
+
s.kci_vec_searcher_set_probe_gap.argtypes = [C.c_void_p, C.c_float, C.c_int]
|
|
108
|
+
if hasattr(s, "kci_vec_searcher_set_eps"):
|
|
109
|
+
s.kci_vec_searcher_set_eps.restype = C.c_int
|
|
110
|
+
s.kci_vec_searcher_set_eps.argtypes = [C.c_void_p, C.c_float]
|
|
111
|
+
if hasattr(s, "kci_vec_build_qg"):
|
|
112
|
+
s.kci_vec_build_qg.restype = C.c_int; s.kci_vec_build_qg.argtypes = [C.c_void_p, C.c_int, C.c_int]
|
|
113
|
+
s.kci_vec_qg_bytes.restype = C.c_int64; s.kci_vec_qg_bytes.argtypes = [C.c_void_p]
|
|
114
|
+
s.kci_vec_searcher_set_qg.restype = C.c_int; s.kci_vec_searcher_set_qg.argtypes = [C.c_void_p, C.c_int]
|
|
115
|
+
if hasattr(s, "kci_vec_build_qg_ex"):
|
|
116
|
+
s.kci_vec_build_qg_ex.restype = C.c_int; s.kci_vec_build_qg_ex.argtypes = [C.c_void_p, C.c_int, C.c_int, C.c_int]
|
|
117
|
+
if hasattr(s, "kci_vec_image_save"):
|
|
118
|
+
s.kci_vec_image_save.restype = C.c_int; s.kci_vec_image_save.argtypes = [C.c_void_p, C.c_char_p]
|
|
119
|
+
s.kci_vec_attach.restype = C.c_void_p; s.kci_vec_attach.argtypes = [C.c_char_p]
|
|
120
|
+
if hasattr(s, "kci_vec_build_qg_gate"):
|
|
121
|
+
s.kci_vec_build_qg_gate.restype = C.c_int; s.kci_vec_build_qg_gate.argtypes = [C.c_void_p, C.c_int, C.c_int, C.c_int, C.c_int]
|
|
122
|
+
if hasattr(s, "kci_vec_searcher_set_qg_exact"):
|
|
123
|
+
s.kci_vec_searcher_set_qg_exact.restype = C.c_int; s.kci_vec_searcher_set_qg_exact.argtypes = [C.c_void_p, C.c_int]
|
|
124
|
+
s.kci_vec_search_r.restype = C.c_int; s.kci_vec_search_r.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, c_u64p, c_f32p]
|
|
125
|
+
s.kci_vec_search_rerank.restype = C.c_int; s.kci_vec_search_rerank.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, C.c_int, c_u64p, c_f32p]
|
|
126
|
+
s.kci_vec_search_filtered.restype = C.c_int; s.kci_vec_search_filtered.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, C.c_int, _FILTER, C.c_void_p, c_u64p, c_f32p]
|
|
127
|
+
s.kci_vec_search_ivf.restype = C.c_int; s.kci_vec_search_ivf.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, C.c_int, c_u64p, c_f32p]
|
|
128
|
+
s.kci_vec_search_ivf_filtered.restype = C.c_int
|
|
129
|
+
s.kci_vec_search_ivf_filtered.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, C.c_int, _FILTER, C.c_void_p, c_u64p, c_f32p]
|
|
130
|
+
s.kci_vec_search_exact.restype = C.c_int; s.kci_vec_search_exact.argtypes = [C.c_void_p, c_f32p, C.c_int, C.c_int, c_u64p, c_f32p]
|
|
131
|
+
s.kci_vec_insert.restype = C.c_int64; s.kci_vec_insert.argtypes = [C.c_void_p, C.c_uint64, c_f32p]
|
|
132
|
+
s.kci_vec_delete.restype = C.c_int; s.kci_vec_delete.argtypes = [C.c_void_p, C.c_uint64]
|
|
133
|
+
s.kci_vec_compact.restype = C.c_uint32; s.kci_vec_compact.argtypes = [C.c_void_p]
|
|
134
|
+
s.kci_vec_float_mmap.restype = C.c_int; s.kci_vec_float_mmap.argtypes = [C.c_void_p, C.c_char_p]
|
|
135
|
+
s.kci_vec_save.restype = C.c_int; s.kci_vec_save.argtypes = [C.c_void_p, C.c_char_p, C.c_void_p, C.c_int]
|
|
136
|
+
s.kci_vec_load.restype = C.c_void_p; s.kci_vec_load.argtypes = [C.c_char_p, C.c_void_p, C.c_int]
|
|
137
|
+
s.kci_vec_count.restype = C.c_uint32; s.kci_vec_count.argtypes = [C.c_void_p]
|
|
138
|
+
if hasattr(s, "kci_vec_set_dedup"): # identical vectors kept once
|
|
139
|
+
s.kci_vec_set_dedup.restype = C.c_int; s.kci_vec_set_dedup.argtypes = [C.c_void_p, C.c_int]
|
|
140
|
+
s.kci_vec_searcher_set_unique.restype = C.c_int; s.kci_vec_searcher_set_unique.argtypes = [C.c_void_p, C.c_int]
|
|
141
|
+
if hasattr(s, "kci_vec_dup_stats"): # exact copies among the rows
|
|
142
|
+
s.kci_vec_dup_stats.restype = C.c_int; s.kci_vec_dup_stats.argtypes = [C.c_void_p, C.POINTER(C.c_uint64)]
|
|
143
|
+
if hasattr(s, "kci_vec_plain_bytes"):
|
|
144
|
+
s.kci_vec_plain_bytes.restype = C.c_int
|
|
145
|
+
s.kci_vec_plain_bytes.argtypes = [C.c_void_p, C.POINTER(C.c_uint64)]
|
|
146
|
+
s.kci_vec_dim.restype = C.c_int; s.kci_vec_dim.argtypes = [C.c_void_p]
|
|
147
|
+
if hasattr(s, "kci_vec_set_ivf_training"):
|
|
148
|
+
s.kci_vec_set_ivf_training.restype = C.c_int; s.kci_vec_set_ivf_training.argtypes = [C.c_void_p, C.c_int, C.c_uint32]
|
|
149
|
+
if hasattr(s, "kci_vec_set_ivf_codes"):
|
|
150
|
+
s.kci_vec_set_ivf_codes.restype = C.c_int; s.kci_vec_set_ivf_codes.argtypes = [C.c_void_p, C.c_int, C.c_float]
|
|
151
|
+
if hasattr(s, "kci_vec_new_l2"):
|
|
152
|
+
s.kci_vec_new_l2.restype = C.c_void_p; s.kci_vec_new_l2.argtypes = [C.c_int, C.c_int, C.c_int, C.c_float]
|
|
153
|
+
s.kci_vec_is_l2.restype = C.c_int; s.kci_vec_is_l2.argtypes = [C.c_void_p]
|
|
154
|
+
if hasattr(s, "kci_vec_new_ip"):
|
|
155
|
+
s.kci_vec_new_ip.restype = C.c_void_p; s.kci_vec_new_ip.argtypes = [C.c_int, C.c_int, C.c_int, C.c_float]
|
|
156
|
+
if hasattr(s, "kci_vec_learn"):
|
|
157
|
+
s.kci_vec_learn.restype = C.c_int
|
|
158
|
+
s.kci_vec_learn.argtypes = [C.c_void_p, C.c_void_p, C.c_uint32, C.c_void_p, C.c_int, C.c_int, C.c_int, C.c_int, C.POINTER(C.c_float)]
|
|
159
|
+
s.kci_vec_has_learned.restype = C.c_int; s.kci_vec_has_learned.argtypes = [C.c_void_p]
|
|
160
|
+
if hasattr(s, "kci_vec_learn_pack"):
|
|
161
|
+
s.kci_vec_learn_pack.restype = C.c_int; s.kci_vec_learn_pack.argtypes = [C.c_void_p]
|
|
162
|
+
for f in ("kci_vec_searcher_set_learned_seeds", "kci_vec_searcher_set_learned_pages", "kci_vec_searcher_set_learned_hot"):
|
|
163
|
+
if hasattr(s, f):
|
|
164
|
+
getattr(s, f).restype = C.c_int; getattr(s, f).argtypes = [C.c_void_p, C.c_int]
|
|
165
|
+
s.kci_vec_search_learned.restype = C.c_int
|
|
166
|
+
s.kci_vec_search_learned.argtypes = [C.c_void_p, C.c_void_p, C.c_int, C.c_int, C.c_int, C.c_int, C.c_void_p, C.c_void_p]
|
|
167
|
+
if hasattr(s, "kci_vec_set_ip_centre"):
|
|
168
|
+
s.kci_vec_set_ip_centre.restype = C.c_int; s.kci_vec_set_ip_centre.argtypes = [C.c_void_p, C.c_int]
|
|
169
|
+
if hasattr(s, "kci_vec_metric"):
|
|
170
|
+
s.kci_vec_metric.restype = C.c_int; s.kci_vec_metric.argtypes = [C.c_void_p]
|
|
171
|
+
s.kci_vec_is_built.restype = C.c_int; s.kci_vec_is_built.argtypes = [C.c_void_p]
|
|
172
|
+
return s
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
_LIB = None
|
|
176
|
+
def _lib():
|
|
177
|
+
global _LIB
|
|
178
|
+
if _LIB is None:
|
|
179
|
+
_LIB = _bind(C.CDLL(_find_lib()))
|
|
180
|
+
return _LIB
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _f32(a):
|
|
184
|
+
a = np.ascontiguousarray(a, dtype=np.float32)
|
|
185
|
+
return a, a.ctypes.data_as(c_f32p)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _make_filter(filt):
|
|
189
|
+
"""filt: None | callable(id) -> bool | a set / list / numpy array of allowed ids. Returns a C callback or None."""
|
|
190
|
+
if filt is None:
|
|
191
|
+
return None
|
|
192
|
+
if callable(filt):
|
|
193
|
+
return _FILTER(lambda i, _ctx: 1 if filt(int(i)) else 0)
|
|
194
|
+
allowed = filt if isinstance(filt, (set, frozenset)) else set(int(x) for x in np.asarray(filt).ravel())
|
|
195
|
+
return _FILTER(lambda i, _ctx: 1 if int(i) in allowed else 0)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class KciVec:
|
|
199
|
+
"""One index."""
|
|
200
|
+
|
|
201
|
+
def __init__(self, dim, M=16, efc=200, rerank=0, metric="cosine", max_norm=0.0, centre=False, _handle=None, dedup=False):
|
|
202
|
+
self.lib = _lib()
|
|
203
|
+
self._unique = False
|
|
204
|
+
self.dim = dim
|
|
205
|
+
self.rerank = rerank
|
|
206
|
+
if metric not in ("cosine", "l2", "ip"):
|
|
207
|
+
raise ValueError("metric must be 'cosine', 'l2' or 'ip'")
|
|
208
|
+
if _handle is not None:
|
|
209
|
+
self._v = _handle
|
|
210
|
+
if hasattr(self.lib, "kci_vec_metric"):
|
|
211
|
+
self.metric = ("cosine", "l2", "ip")[self.lib.kci_vec_metric(_handle)]
|
|
212
|
+
else:
|
|
213
|
+
self.metric = "l2" if hasattr(self.lib, "kci_vec_is_l2") and self.lib.kci_vec_is_l2(_handle) else "cosine"
|
|
214
|
+
else:
|
|
215
|
+
self.metric = metric
|
|
216
|
+
if metric == "l2":
|
|
217
|
+
if not hasattr(self.lib, "kci_vec_new_l2"):
|
|
218
|
+
raise RuntimeError("this libkci_vec has no L2 (a cosine-only build, or one from before 2026-11-08)")
|
|
219
|
+
self._v = self.lib.kci_vec_new_l2(dim, M, efc, float(max_norm))
|
|
220
|
+
elif metric == "ip":
|
|
221
|
+
if not hasattr(self.lib, "kci_vec_new_ip"):
|
|
222
|
+
raise RuntimeError("this libkci_vec has no inner product (a cosine-only build, or one from before 2026-11-16)")
|
|
223
|
+
self._v = self.lib.kci_vec_new_ip(dim, M, efc, float(max_norm))
|
|
224
|
+
if centre and self._v:
|
|
225
|
+
if not hasattr(self.lib, "kci_vec_set_ip_centre") or self.lib.kci_vec_set_ip_centre(self._v, 1) != 0:
|
|
226
|
+
raise RuntimeError("centre=True is not available in this libkci_vec")
|
|
227
|
+
else:
|
|
228
|
+
self._v = self.lib.kci_vec_new(dim, M, efc)
|
|
229
|
+
if not self._v:
|
|
230
|
+
raise RuntimeError("kci_vec_new failed (dim must be > 0; l2 / ip: max_norm >= 0)")
|
|
231
|
+
if rerank:
|
|
232
|
+
self.lib.kci_vec_keep_float(self._v, 1)
|
|
233
|
+
# dedup=True: identical vectors are kept once, their ids beside the row (kci_vec_set_dedup). For data with
|
|
234
|
+
# texts that repeat: see dup_stats(). Searches still answer with every id; .unique = True gives one id per
|
|
235
|
+
if dedup:
|
|
236
|
+
if not hasattr(self.lib, "kci_vec_set_dedup") or self.lib.kci_vec_set_dedup(self._v, 1) != 0:
|
|
237
|
+
raise RuntimeError("dedup=True is not available in this libkci_vec; rebuild it from the current kci_vec.c")
|
|
238
|
+
self._s = None
|
|
239
|
+
self._lists = False # lists built (fast path)?
|
|
240
|
+
self._dirty = False
|
|
241
|
+
self.nprobe = 32
|
|
242
|
+
self.rerank_mode = "float"
|
|
243
|
+
self.probe_gap = (0.0, 8)
|
|
244
|
+
self.eps = 0.0
|
|
245
|
+
self.qg_exact = False
|
|
246
|
+
self.qg = False
|
|
247
|
+
self.attached = False
|
|
248
|
+
self._ob = (C.c_uint64 * 4096)()
|
|
249
|
+
self._os = (C.c_float * 4096)()
|
|
250
|
+
|
|
251
|
+
# ---- ingest ----
|
|
252
|
+
def reserve(self, n): self.lib.kci_vec_reserve(self._v, int(n))
|
|
253
|
+
|
|
254
|
+
def add(self, id, vec):
|
|
255
|
+
_, p = _f32(np.reshape(vec, -1))
|
|
256
|
+
return self.lib.kci_vec_add(self._v, int(id), p)
|
|
257
|
+
|
|
258
|
+
def add_many(self, ids, mat):
|
|
259
|
+
mat = np.ascontiguousarray(mat, dtype=np.float32)
|
|
260
|
+
n, d = mat.shape
|
|
261
|
+
assert d == self.dim, f"dim mismatch {d} != {self.dim}"
|
|
262
|
+
self.reserve(n + 1)
|
|
263
|
+
base = mat.ctypes.data_as(C.c_void_p).value
|
|
264
|
+
for i, vid in enumerate(ids):
|
|
265
|
+
self.lib.kci_vec_add(self._v, int(vid), C.cast(base + i * d * 4, c_f32p))
|
|
266
|
+
|
|
267
|
+
def build(self, threads=0, fast=False):
|
|
268
|
+
"""Build the int8 HNSW graph."""
|
|
269
|
+
secs = C.c_double(0.0)
|
|
270
|
+
if fast and not hasattr(self.lib, "kci_vec_build_fast"):
|
|
271
|
+
raise RuntimeError("this libkci_vec has no kci_vec_build_fast (built before 2026-11-20); rebuild it, or use build()")
|
|
272
|
+
rc = (self.lib.kci_vec_build_fast if fast else self.lib.kci_vec_build)(self._v, threads, C.byref(secs))
|
|
273
|
+
if fast and rc != 0:
|
|
274
|
+
raise RuntimeError("kci_vec_build_fast failed (out of memory, or no vectors)")
|
|
275
|
+
self.qg = False # a rebuild drops the quantized graph
|
|
276
|
+
self._searcher(reset=True)
|
|
277
|
+
return secs.value
|
|
278
|
+
|
|
279
|
+
def build_qg(self, dims_per_code=1, threads=0, code_dims=0, gate_dims=0, residual=False):
|
|
280
|
+
"""Quantized graph lay layer 0 out as blocks of the neighbours' 4-bit codes, so a hop reads one block and scores
|
|
281
|
+
every neighbour with table lookups. Dropped by insert() / compact() / build(); call again after. Returns the
|
|
282
|
+
bytes it takes. code_dims > 0 the codes cover the top code_dims principal directions only (even, 8..dim-1), a
|
|
283
|
+
smaller block per node."""
|
|
284
|
+
if not hasattr(self.lib, "kci_vec_build_qg"):
|
|
285
|
+
raise RuntimeError("this libkci_vec has no kci_vec_build_qg (rebuild the library)")
|
|
286
|
+
if residual:
|
|
287
|
+
if not hasattr(self.lib, "kci_vec_build_qg_res"):
|
|
288
|
+
raise RuntimeError("this libkci_vec has no kci_vec_build_qg_res (rebuild the library)")
|
|
289
|
+
if self.lib.kci_vec_build_qg_res(self._v, int(code_dims), int(gate_dims), int(threads)) != 0:
|
|
290
|
+
raise RuntimeError("kci_vec_build_qg_res failed (no graph yet? code_dims must be even, 8..dim-1, gate_dims even, 8..code_dims; out of memory?)")
|
|
291
|
+
elif int(gate_dims):
|
|
292
|
+
if not hasattr(self.lib, "kci_vec_build_qg_gate"):
|
|
293
|
+
raise RuntimeError("this libkci_vec has no kci_vec_build_qg_gate (rebuild the library)")
|
|
294
|
+
if self.lib.kci_vec_build_qg_gate(self._v, int(dims_per_code), int(code_dims), int(gate_dims), int(threads)) != 0:
|
|
295
|
+
raise RuntimeError("kci_vec_build_qg_gate failed (no graph yet? gate_dims must be even, 8..code_dims; out of memory?)")
|
|
296
|
+
elif int(code_dims):
|
|
297
|
+
if not hasattr(self.lib, "kci_vec_build_qg_ex"):
|
|
298
|
+
raise RuntimeError("this libkci_vec has no kci_vec_build_qg_ex (rebuild the library)")
|
|
299
|
+
if self.lib.kci_vec_build_qg_ex(self._v, int(dims_per_code), int(code_dims), int(threads)) != 0:
|
|
300
|
+
raise RuntimeError("kci_vec_build_qg_ex failed (no graph yet? code_dims must be even, 8..dim-1; out of memory?)")
|
|
301
|
+
elif self.lib.kci_vec_build_qg(self._v, int(dims_per_code), int(threads)) != 0:
|
|
302
|
+
raise RuntimeError("kci_vec_build_qg failed (no graph yet? dims_per_code must be 1 or 2; out of memory?)")
|
|
303
|
+
self.qg = True
|
|
304
|
+
self._searcher(reset=True)
|
|
305
|
+
return int(self.lib.kci_vec_qg_bytes(self._v))
|
|
306
|
+
|
|
307
|
+
def build_lists(self, nlist=0, soar=0.0, threads=0, nprobe=None, dims_per_code=0, avq_threshold=0.0,
|
|
308
|
+
train_iters=0, train_sample=0):
|
|
309
|
+
"""Build the partitioned lists (4-bit table lookup) — the fast path. Build the graph first if you want both (the
|
|
310
|
+
graph build renumbers). dims_per_code / avq_threshold how the residuals are coded, 0 = by the dims (one dim
|
|
311
|
+
per code and 0.55 up to 32 dims, else pairs and 0.2); see kci_vec_set_ivf_codes. train_iters / train_sample
|
|
312
|
+
k-means iterations (0 = 10) and sample size (0 = 250,000; -1 = all vectors) for the centroids."""
|
|
313
|
+
if not self.rerank:
|
|
314
|
+
raise RuntimeError("build_lists needs rerank=... (retained floats)")
|
|
315
|
+
if dims_per_code or avq_threshold:
|
|
316
|
+
if not hasattr(self.lib, "kci_vec_set_ivf_codes"):
|
|
317
|
+
raise RuntimeError("this libkci_vec has no kci_vec_set_ivf_codes (built before 2026-11-08)")
|
|
318
|
+
if self.lib.kci_vec_set_ivf_codes(self._v, int(dims_per_code), float(avq_threshold)) != 0:
|
|
319
|
+
raise ValueError("dims_per_code must be 0, 1 or 2 and avq_threshold in [0, 0.98]")
|
|
320
|
+
if train_iters or train_sample:
|
|
321
|
+
if not hasattr(self.lib, "kci_vec_set_ivf_training"):
|
|
322
|
+
raise RuntimeError("this libkci_vec has no kci_vec_set_ivf_training (built before 2026-11-08)")
|
|
323
|
+
smp = 0xFFFFFFFF if train_sample < 0 else int(train_sample)
|
|
324
|
+
if self.lib.kci_vec_set_ivf_training(self._v, int(train_iters), smp) != 0:
|
|
325
|
+
raise ValueError("train_iters must be 0..1000")
|
|
326
|
+
p = _IvfParams(int(nlist), int(threads), float(soar), 0, 0)
|
|
327
|
+
if self.lib.kci_vec_build_ivf_p(self._v, C.byref(p)) != 0:
|
|
328
|
+
raise RuntimeError("kci_vec_build_ivf_p failed")
|
|
329
|
+
self._lists = True
|
|
330
|
+
if nprobe: self.nprobe = int(nprobe)
|
|
331
|
+
self._searcher(reset=True)
|
|
332
|
+
|
|
333
|
+
# ---- query ----
|
|
334
|
+
def set_rerank(self, mode):
|
|
335
|
+
"""'float' (exact, default) or 'int8' (1/4 of the bytes; fine for text embeddings at k=100, not for CLIP)."""
|
|
336
|
+
if mode not in ("float", "int8"):
|
|
337
|
+
raise ValueError("mode must be 'float' or 'int8'")
|
|
338
|
+
self.rerank_mode = mode
|
|
339
|
+
if self._s:
|
|
340
|
+
self.lib.kci_vec_searcher_set_rerank_int8(self._s, 1 if mode == "int8" else 0)
|
|
341
|
+
|
|
342
|
+
def set_probe_gap(self, gap, min_probe=8):
|
|
343
|
+
"""Lists: of the best nprobe, scan only those whose centroid score is within `gap` (cosine) of the nearest one's,
|
|
344
|
+
at least min_probe."""
|
|
345
|
+
if not hasattr(self.lib, "kci_vec_searcher_set_probe_gap"):
|
|
346
|
+
raise RuntimeError("this libkci_vec has no kci_vec_searcher_set_probe_gap (rebuild the library)")
|
|
347
|
+
self.probe_gap = (float(gap), int(min_probe))
|
|
348
|
+
if self._s:
|
|
349
|
+
self.lib.kci_vec_searcher_set_probe_gap(self._s, self.probe_gap[0], self.probe_gap[1])
|
|
350
|
+
|
|
351
|
+
def set_eps(self, eps):
|
|
352
|
+
"""Graph: exploration radius (NGT-qg's stop rule). eps > 0 keeps the result set at `ef` entries (use a small ef,
|
|
353
|
+
k..3k) and explores while the next candidate is within (1+eps) x the ef-th best cosine distance. Try
|
|
354
|
+
0.08-0.25."""
|
|
355
|
+
if not hasattr(self.lib, "kci_vec_searcher_set_eps"):
|
|
356
|
+
raise RuntimeError("this libkci_vec has no kci_vec_searcher_set_eps (rebuild the library)")
|
|
357
|
+
eps = float(eps)
|
|
358
|
+
if eps != eps:
|
|
359
|
+
raise ValueError("eps must be a number (NaN given)")
|
|
360
|
+
self.eps = eps if eps > 0 else 0.0
|
|
361
|
+
if self._s:
|
|
362
|
+
self.lib.kci_vec_searcher_set_eps(self._s, self.eps)
|
|
363
|
+
|
|
364
|
+
def set_qg_exact(self, on=True):
|
|
365
|
+
"""Worth trying at high dimensions with dims_per_code 2. Off by default. on=2: with build_qg(code_dims=...) score
|
|
366
|
+
them with short int8 rows (code_dims bytes) instead; less to read per hop, a little coarser, so search with a
|
|
367
|
+
wider rerank_n. Without code_dims the same as True."""
|
|
368
|
+
if not hasattr(self.lib, "kci_vec_searcher_set_qg_exact"):
|
|
369
|
+
raise RuntimeError("this libkci_vec has no kci_vec_searcher_set_qg_exact (rebuild the library)")
|
|
370
|
+
self.qg_exact = 2 if (on == 2 and on is not True) else (1 if on else 0)
|
|
371
|
+
if self._s:
|
|
372
|
+
self.lib.kci_vec_searcher_set_qg_exact(self._s, self.qg_exact)
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def unique(self):
|
|
376
|
+
"""With dedup=True: True = a search answers with one id per distinct vector (k results are k different
|
|
377
|
+
vectors); False (the default) = every id, the ids of one vector one after the other."""
|
|
378
|
+
return self._unique
|
|
379
|
+
@unique.setter
|
|
380
|
+
def unique(self, on):
|
|
381
|
+
self._unique = bool(on)
|
|
382
|
+
if getattr(self, "_s", None): self._searcher(reset=True)
|
|
383
|
+
|
|
384
|
+
def _searcher(self, reset=False):
|
|
385
|
+
if (reset or self._dirty) and self._s:
|
|
386
|
+
self.lib.kci_vec_searcher_free(self._s); self._s = None
|
|
387
|
+
self._dirty = False
|
|
388
|
+
if not self._s:
|
|
389
|
+
self._s = self.lib.kci_vec_searcher_new(self._v)
|
|
390
|
+
if self._unique and hasattr(self.lib, "kci_vec_searcher_set_unique"):
|
|
391
|
+
self.lib.kci_vec_searcher_set_unique(self._s, 1)
|
|
392
|
+
if self.rerank_mode == "int8":
|
|
393
|
+
self.lib.kci_vec_searcher_set_rerank_int8(self._s, 1)
|
|
394
|
+
if self.probe_gap[0] > 0:
|
|
395
|
+
self.lib.kci_vec_searcher_set_probe_gap(self._s, self.probe_gap[0], self.probe_gap[1])
|
|
396
|
+
if self.eps > 0:
|
|
397
|
+
self.lib.kci_vec_searcher_set_eps(self._s, self.eps)
|
|
398
|
+
if self.qg:
|
|
399
|
+
self.lib.kci_vec_searcher_set_qg(self._s, 1)
|
|
400
|
+
if self.qg_exact:
|
|
401
|
+
self.lib.kci_vec_searcher_set_qg_exact(self._s, int(self.qg_exact))
|
|
402
|
+
return self._s
|
|
403
|
+
|
|
404
|
+
def _query(self, q, k, ef, nprobe, rn, cb, method):
|
|
405
|
+
s = self._searcher()
|
|
406
|
+
use_lists = self._lists if method == "auto" else (method == "lists")
|
|
407
|
+
if use_lists:
|
|
408
|
+
if cb is not None:
|
|
409
|
+
return self.lib.kci_vec_search_ivf_filtered(s, q, k, nprobe, rn, cb, None, self._ob, self._os)
|
|
410
|
+
return self.lib.kci_vec_search_ivf(s, q, k, nprobe, rn, self._ob, self._os)
|
|
411
|
+
if cb is not None:
|
|
412
|
+
return self.lib.kci_vec_search_filtered(s, q, k, ef, rn, cb, None, self._ob, self._os)
|
|
413
|
+
if rn and rn > 0:
|
|
414
|
+
return self.lib.kci_vec_search_rerank(s, q, k, ef, rn, self._ob, self._os)
|
|
415
|
+
return self.lib.kci_vec_search_r(s, q, k, ef, self._ob, self._os)
|
|
416
|
+
|
|
417
|
+
def search(self, query, k=10, ef=None, nprobe=None, rerank_n=None, filter=None, method="auto"):
|
|
418
|
+
"""A selective filter needs a larger nprobe / rerank_n to find k matches."""
|
|
419
|
+
k = int(k); ef = ef or max(k, 100); nprobe = int(nprobe or self.nprobe)
|
|
420
|
+
rn = self.rerank if rerank_n is None else rerank_n
|
|
421
|
+
if method == "lists" or (method == "auto" and self._lists):
|
|
422
|
+
rn = max(int(rn or 0), 2 * k)
|
|
423
|
+
_, q = _f32(np.reshape(query, -1))
|
|
424
|
+
cb = _make_filter(filter)
|
|
425
|
+
n = self._query(q, k, ef, nprobe, int(rn or 0), cb, method)
|
|
426
|
+
return [(int(self._ob[i]), float(self._os[i])) for i in range(max(n, 0))]
|
|
427
|
+
|
|
428
|
+
def search_many(self, queries, k=10, **kw):
|
|
429
|
+
"""Many queries at once. Returns (ids, scores): int64 / float32 arrays [nq, k], -1 / -inf (l2: +inf) where fewer than k."""
|
|
430
|
+
Q = np.ascontiguousarray(queries, dtype=np.float32)
|
|
431
|
+
if Q.ndim == 1: Q = Q[None, :]
|
|
432
|
+
fill = np.inf if self.metric == "l2" else -np.inf
|
|
433
|
+
ids = np.full((len(Q), k), -1, dtype=np.int64); scores = np.full((len(Q), k), fill, dtype=np.float32)
|
|
434
|
+
for i, q in enumerate(Q):
|
|
435
|
+
for j, (vid, sc) in enumerate(self.search(q, k=k, **kw)):
|
|
436
|
+
ids[i, j] = vid; scores[i, j] = sc
|
|
437
|
+
return ids, scores
|
|
438
|
+
|
|
439
|
+
def learn(self, queries, answers, nclusters=0, list_cap=0, threads=0, pack=False):
|
|
440
|
+
"""Learn lists from a query sample, for data whose queries come from another distribution than the vectors and
|
|
441
|
+
whose answers concentrate on few vectors (e.g. the queries and keys of an attention head). queries: float32
|
|
442
|
+
[nq, dim]; answers: ids [nq, per_query], the (true or approximate) nearest of each query. Needs a built index
|
|
443
|
+
(build() or build_lists()) and rerank > 0."""
|
|
444
|
+
if not hasattr(self.lib, "kci_vec_learn"):
|
|
445
|
+
raise RuntimeError("this libkci_vec has no kci_vec_learn (from before 2026-11-16)")
|
|
446
|
+
Qs = np.ascontiguousarray(queries, dtype=np.float32); A = np.ascontiguousarray(answers, dtype=np.uint64)
|
|
447
|
+
if Qs.ndim != 2 or A.ndim != 2 or len(Qs) != len(A) or Qs.shape[1] != self.dim:
|
|
448
|
+
raise ValueError("queries must be [nq, dim] and answers [nq, per_query]")
|
|
449
|
+
top5 = C.c_float(0.0)
|
|
450
|
+
if self.lib.kci_vec_learn(self._v, Qs.ctypes.data, len(Qs), A.ctypes.data, A.shape[1], int(nclusters), int(list_cap),
|
|
451
|
+
int(threads), C.byref(top5)) != 0:
|
|
452
|
+
raise RuntimeError("kci_vec_learn failed (index not built? no answer id is in the index? out of memory?)")
|
|
453
|
+
if pack:
|
|
454
|
+
if not hasattr(self.lib, "kci_vec_learn_pack") or self.lib.kci_vec_learn_pack(self._v) != 0:
|
|
455
|
+
raise RuntimeError("kci_vec_learn_pack failed (out of memory, or a libkci_vec without it)")
|
|
456
|
+
return float(top5.value)
|
|
457
|
+
|
|
458
|
+
def search_learned(self, query, k=10, nclusters=4, per_list=1000, ef=0, seeds=0, pages=0, hot=0):
|
|
459
|
+
"""Top-k through the learned lists: the nclusters (1..64) nearest query clusters, the first per_list vectors of
|
|
460
|
+
each. ef = 0: those are scored exactly and the best k returned (fast; no fallback for a query unlike the sample).
|
|
461
|
+
ef > 0: they start the graph search (needs build()), which completes what the lists miss.
|
|
462
|
+
ef < 0 (after learn(pack=True)): the lists' int8 copies are scanned and only the -ef best (150 - 500) scored exactly.
|
|
463
|
+
seeds > 0 (ef > 0, packed): only the `seeds` best of the int8 scan start the graph (0: every vector of the prefixes).
|
|
464
|
+
pages > 0: the clusters are chosen in two stages, through the nearest `pages` groups of them (cheaper when
|
|
465
|
+
nclusters is small; 0: compare with every cluster).
|
|
466
|
+
hot > 0: also the first `hot` of the rows most often an answer over the whole sample (learn() keeps up to a
|
|
467
|
+
quarter of the index); for the last answers the nearest lists miss, when the answers are concentrated."""
|
|
468
|
+
_, q = _f32(np.reshape(query, -1))
|
|
469
|
+
for f, x in (("kci_vec_searcher_set_learned_seeds", seeds), ("kci_vec_searcher_set_learned_pages", pages),
|
|
470
|
+
("kci_vec_searcher_set_learned_hot", hot)):
|
|
471
|
+
if hasattr(self.lib, f):
|
|
472
|
+
if getattr(self.lib, f)(self._searcher(), int(x)) != 0:
|
|
473
|
+
raise ValueError(f + ": negative value")
|
|
474
|
+
elif x:
|
|
475
|
+
raise RuntimeError(f + ": this libkci_vec does not have it")
|
|
476
|
+
n = self.lib.kci_vec_search_learned(self._searcher(), q, int(k), int(nclusters), int(per_list), int(ef), self._ob, self._os)
|
|
477
|
+
if n == -2:
|
|
478
|
+
raise RuntimeError("nothing learned (call learn(); build() and compact() drop it; ef < 0 needs learn(pack=True))")
|
|
479
|
+
if n < 0:
|
|
480
|
+
raise RuntimeError("search_learned failed (rerank=... needed; ef > 0 needs build())")
|
|
481
|
+
return [(int(self._ob[i]), float(self._os[i])) for i in range(n)]
|
|
482
|
+
|
|
483
|
+
def vote_set(self, answers):
|
|
484
|
+
"""For data whose queries come from another distribution and whose answers are NOT concentrated (learn() returns
|
|
485
|
+
a low share): keep the answers of a query sample, answers = ids [nq, per_query], and an int8 copy of every
|
|
486
|
+
vector (dim bytes each). search_voted() then takes the numbers (0 .. nq-1) of the sample queries nearest to a
|
|
487
|
+
query, which the caller finds, for instance with a second KciVec holding the sample queries. Needs a built
|
|
488
|
+
index and rerank > 0. build() and compact() drop it; it is not saved."""
|
|
489
|
+
if not hasattr(self.lib, "kci_vec_vote_set"):
|
|
490
|
+
raise RuntimeError("this libkci_vec has no kci_vec_vote_set (from before 2026-11-17)")
|
|
491
|
+
A = np.ascontiguousarray(answers, dtype=np.uint64)
|
|
492
|
+
if A.ndim != 2:
|
|
493
|
+
raise ValueError("answers must be [nq, per_query]")
|
|
494
|
+
self.lib.kci_vec_vote_set.argtypes = [C.c_void_p, C.c_void_p, C.c_uint32, C.c_int]
|
|
495
|
+
if self.lib.kci_vec_vote_set(self._v, A.ctypes.data, A.shape[0], A.shape[1]) != 0:
|
|
496
|
+
raise RuntimeError("kci_vec_vote_set failed (index not built? rerank=... needed; out of memory?)")
|
|
497
|
+
|
|
498
|
+
def vote_short(self, ids, rows):
|
|
499
|
+
"""Optional, after vote_set(): one short vector per stored vector (rows float32 [count, sdim], in the order of
|
|
500
|
+
ids), chosen by the caller so that short query . short row orders the candidates like the score. Kept as int8;
|
|
501
|
+
search_voted(short_query=...) ranks the candidates by it first. For high dimensions."""
|
|
502
|
+
I = np.ascontiguousarray(ids, dtype=np.uint64); R = np.ascontiguousarray(rows, dtype=np.float32)
|
|
503
|
+
if R.ndim != 2 or I.ndim != 1 or len(I) != len(R):
|
|
504
|
+
raise ValueError("rows must be [count, sdim] and ids [count]")
|
|
505
|
+
if not hasattr(self.lib, "kci_vec_vote_short"):
|
|
506
|
+
raise RuntimeError("this libkci_vec has no kci_vec_vote_short (from before 2026-11-17)")
|
|
507
|
+
self.lib.kci_vec_vote_short.argtypes = [C.c_void_p, C.c_void_p, C.c_void_p, C.c_uint32, C.c_int]
|
|
508
|
+
if self.lib.kci_vec_vote_short(self._v, I.ctypes.data, R.ctypes.data, len(I), R.shape[1]) != 0:
|
|
509
|
+
raise RuntimeError("kci_vec_vote_short failed (vote_set() first; every id of the index exactly once; sdim 1..4096)")
|
|
510
|
+
self._vote_sdim = R.shape[1]
|
|
511
|
+
|
|
512
|
+
def search_voted(self, query, voters, k=10, rerank=200, short_query=None, keep=1000):
|
|
513
|
+
"""Top-k among the answers of the sample queries numbered in `voters` (see vote_set): the union is scanned on
|
|
514
|
+
int8 copies and the `rerank` best (at most 4096) are scored exactly. With short_query (after vote_short) the
|
|
515
|
+
union is ranked by the short codes first and only the `keep` best go on. No fallback for a query unlike the sample."""
|
|
516
|
+
_, q = _f32(np.reshape(query, -1))
|
|
517
|
+
V = np.ascontiguousarray(voters, dtype=np.uint32).reshape(-1)
|
|
518
|
+
if len(V) == 0:
|
|
519
|
+
return []
|
|
520
|
+
k = min(int(k), len(self._ob))
|
|
521
|
+
if short_query is None:
|
|
522
|
+
self.lib.kci_vec_search_voted.argtypes = [C.c_void_p, C.c_void_p, C.c_void_p, C.c_int, C.c_int, C.c_int, C.c_void_p, C.c_void_p]
|
|
523
|
+
n = self.lib.kci_vec_search_voted(self._searcher(), q, V.ctypes.data, len(V), k, int(rerank), self._ob, self._os)
|
|
524
|
+
else:
|
|
525
|
+
qs = np.ascontiguousarray(np.reshape(short_query, -1), dtype=np.float32)
|
|
526
|
+
if len(qs) != getattr(self, "_vote_sdim", -1):
|
|
527
|
+
raise ValueError("short_query must have the sdim given to vote_short()")
|
|
528
|
+
self.lib.kci_vec_search_voted_short.argtypes = [C.c_void_p, C.c_void_p, C.c_void_p, C.c_int, C.c_void_p, C.c_int, C.c_int, C.c_int, C.c_void_p, C.c_void_p]
|
|
529
|
+
n = self.lib.kci_vec_search_voted_short(self._searcher(), q, qs.ctypes.data, int(keep), V.ctypes.data, len(V), k, int(rerank), self._ob, self._os)
|
|
530
|
+
if n == -2:
|
|
531
|
+
raise RuntimeError("nothing set (call vote_set(); build() and compact() drop it; short_query needs vote_short())")
|
|
532
|
+
if n < 0:
|
|
533
|
+
raise RuntimeError("search_voted failed")
|
|
534
|
+
return [(int(self._ob[i]), float(self._os[i])) for i in range(n)]
|
|
535
|
+
|
|
536
|
+
def search_exact(self, query, k=10, threads=0):
|
|
537
|
+
"""Brute force (ground truth / tiny indexes)."""
|
|
538
|
+
_, q = _f32(np.reshape(query, -1))
|
|
539
|
+
n = self.lib.kci_vec_search_exact(self._v, q, int(k), int(threads), self._ob, self._os)
|
|
540
|
+
return [(int(self._ob[i]), float(self._os[i])) for i in range(max(n, 0))]
|
|
541
|
+
|
|
542
|
+
# ---- incremental update (single-writer) ----
|
|
543
|
+
def insert(self, id, vec):
|
|
544
|
+
_, p = _f32(np.reshape(vec, -1))
|
|
545
|
+
r = self.lib.kci_vec_insert(self._v, int(id), p)
|
|
546
|
+
if r == -2:
|
|
547
|
+
raise RuntimeError("insert requires rerank=… (retained floats)")
|
|
548
|
+
if r < 0:
|
|
549
|
+
raise RuntimeError("insert failed" + (" (l2: longer or much shorter than the vectors at the build?)" if self.metric == "l2" else
|
|
550
|
+
" (ip: longer than the longest vector at the build?)" if self.metric == "ip" else ""))
|
|
551
|
+
self._dirty = True
|
|
552
|
+
self.qg = False
|
|
553
|
+
return r
|
|
554
|
+
|
|
555
|
+
def delete(self, id): return self.lib.kci_vec_delete(self._v, int(id)) == 0
|
|
556
|
+
def compact(self):
|
|
557
|
+
n = self.lib.kci_vec_compact(self._v); self.qg = False; self._searcher(reset=True); return n
|
|
558
|
+
def float_mmap(self, path): return self.lib.kci_vec_float_mmap(self._v, path.encode()) == 0
|
|
559
|
+
|
|
560
|
+
# ---- persistence (encrypted at rest if key given: AES-256-CTR + AES-256-CMAC) ----
|
|
561
|
+
def save(self, path, key=None):
|
|
562
|
+
kp = (C.c_char_p(key), len(key)) if key else (None, 0)
|
|
563
|
+
return self.lib.kci_vec_save(self._v, path.encode(), kp[0], kp[1]) == 0
|
|
564
|
+
|
|
565
|
+
@classmethod
|
|
566
|
+
def load(cls, path, key=None, rerank=100):
|
|
567
|
+
"""(see the header for this function)"""
|
|
568
|
+
lib = _lib()
|
|
569
|
+
kp = (C.c_char_p(key), len(key)) if key else (None, 0)
|
|
570
|
+
h = lib.kci_vec_load(path.encode(), kp[0], kp[1])
|
|
571
|
+
if not h:
|
|
572
|
+
raise RuntimeError("load failed (wrong key, damaged file, or file missing)")
|
|
573
|
+
v = cls(lib.kci_vec_dim(h), _handle=h, rerank=rerank)
|
|
574
|
+
v.qg = hasattr(lib, "kci_vec_qg_bytes") and lib.kci_vec_qg_bytes(h) > 0
|
|
575
|
+
# the file carries the lists when they were built; a probe tells which path is available
|
|
576
|
+
try:
|
|
577
|
+
s = lib.kci_vec_searcher_new(h); z = np.zeros(v.dim, dtype=np.float32)
|
|
578
|
+
v._lists = lib.kci_vec_search_ivf(s, z.ctypes.data_as(c_f32p), 1, 1, 1, v._ob, v._os) >= 0
|
|
579
|
+
lib.kci_vec_searcher_free(s)
|
|
580
|
+
except Exception:
|
|
581
|
+
v._lists = False
|
|
582
|
+
return v
|
|
583
|
+
|
|
584
|
+
def save_image(self, path):
|
|
585
|
+
"""Write the index as a read-only image (kci_vec_image_save): a flat, plaintext file that KciVec.attach() opens
|
|
586
|
+
without parsing or copying. It carries the rows, the floats, the lists, and for an index with a graph the
|
|
587
|
+
graph, the quantized graph (build_qg) and the halves (half_floats). Not encrypted: for an encrypted file use
|
|
588
|
+
save(path, key). For the machine that wrote it (byte order). Returns True, or raises."""
|
|
589
|
+
if not hasattr(self.lib, "kci_vec_image_save"):
|
|
590
|
+
raise RuntimeError("this libkci_vec has no kci_vec_image_save (rebuild the library)")
|
|
591
|
+
if self.lib.kci_vec_image_save(self._v, os.fsencode(path)) != 0:
|
|
592
|
+
raise RuntimeError("kci_vec_image_save failed (cannot write the file, or the floats are mapped from a file)")
|
|
593
|
+
return True
|
|
594
|
+
|
|
595
|
+
@classmethod
|
|
596
|
+
def attach(cls, path, rerank=100):
|
|
597
|
+
"""Anything that writes (add, insert, delete, build, build_qg...) fails or is refused. rerank: the default
|
|
598
|
+
shortlist for search, as in load(). Missing, damaged or foreign file -> RuntimeError."""
|
|
599
|
+
lib = _lib()
|
|
600
|
+
if not hasattr(lib, "kci_vec_attach"):
|
|
601
|
+
raise RuntimeError("this libkci_vec has no kci_vec_attach (rebuild the library)")
|
|
602
|
+
h = lib.kci_vec_attach(os.fsencode(path))
|
|
603
|
+
if not h:
|
|
604
|
+
raise RuntimeError("attach failed (file missing, not an image, or damaged)")
|
|
605
|
+
v = cls(lib.kci_vec_dim(h), _handle=h, rerank=rerank)
|
|
606
|
+
v.attached = True
|
|
607
|
+
try:
|
|
608
|
+
s = lib.kci_vec_searcher_new(h); z = np.zeros(v.dim, dtype=np.float32)
|
|
609
|
+
v._lists = lib.kci_vec_search_ivf(s, z.ctypes.data_as(c_f32p), 1, 1, 1, v._ob, v._os) >= 0
|
|
610
|
+
lib.kci_vec_searcher_free(s)
|
|
611
|
+
except Exception:
|
|
612
|
+
v._lists = False
|
|
613
|
+
v.qg = hasattr(lib, "kci_vec_qg_bytes") and lib.kci_vec_qg_bytes(h) > 0
|
|
614
|
+
return v
|
|
615
|
+
|
|
616
|
+
def half_floats(self):
|
|
617
|
+
"""Turn the retained floats into 16-bit halves (kci_vec_half_floats): half the memory for them, and
|
|
618
|
+
search_rerank's float pass reads half as much (cosine scores within 1e-4 of the floats'; inner-product / L2
|
|
619
|
+
scores are off by the same relative amount). One way; afterwards the index is as one without floats for
|
|
620
|
+
everything but search_rerank (no insert, a save has no floats). Call after build() and build_qg()."""
|
|
621
|
+
if not hasattr(self.lib, "kci_vec_half_floats"):
|
|
622
|
+
raise RuntimeError("this libkci_vec has no kci_vec_half_floats (rebuild the library)")
|
|
623
|
+
if self.lib.kci_vec_half_floats(self._v) != 0:
|
|
624
|
+
raise RuntimeError("kci_vec_half_floats failed (needs a built index with floats kept in RAM)")
|
|
625
|
+
|
|
626
|
+
def search_only(self):
|
|
627
|
+
"""Give up what a quantized-graph search does not read — the int8 rows and the plain graph's layer-0 links
|
|
628
|
+
(kci_vec_search_only) — for an index that will only be searched. Needs build(), build_qg() and an exact pass
|
|
629
|
+
(half_floats(), or rerank > 0 at creation)."""
|
|
630
|
+
if not hasattr(self.lib, "kci_vec_search_only"):
|
|
631
|
+
raise RuntimeError("this libkci_vec has no kci_vec_search_only (rebuild the library)")
|
|
632
|
+
if self.lib.kci_vec_search_only(self._v) != 0:
|
|
633
|
+
raise RuntimeError("kci_vec_search_only failed (needs a built index with a quantized graph and halves or floats; no lists)")
|
|
634
|
+
self._searcher(reset=True)
|
|
635
|
+
|
|
636
|
+
def plain_bytes(self):
|
|
637
|
+
"""Plaintext bytes of the index in RAM, by kind (kci_vec_plain_bytes): codes, floats, derived (centroids,
|
|
638
|
+
codebooks), graph, ids, total. Allocated sizes; the last query in a searcher is not counted."""
|
|
639
|
+
out = (C.c_uint64 * 6)()
|
|
640
|
+
if not hasattr(self.lib, "kci_vec_plain_bytes") or self.lib.kci_vec_plain_bytes(self._v, out) != 0:
|
|
641
|
+
raise RuntimeError("kci_vec_plain_bytes not available")
|
|
642
|
+
return dict(zip(("codes", "floats", "derived", "graph", "ids", "total"), (int(x) for x in out)))
|
|
643
|
+
@property
|
|
644
|
+
def count(self): return self.lib.kci_vec_count(self._v)
|
|
645
|
+
|
|
646
|
+
def dup_stats(self):
|
|
647
|
+
"""How many rows are exact copies of another row (a built index; kci_vec_dup_stats): a dict with rows, groups (of
|
|
648
|
+
2 or more identical rows), rows_in_groups, largest, groups_over_m0 (larger than the layer-0 neighbour list)
|
|
649
|
+
and distinct."""
|
|
650
|
+
if not hasattr(self.lib, "kci_vec_dup_stats"):
|
|
651
|
+
raise RuntimeError("this libkci_vec has no kci_vec_dup_stats; rebuild it from the current kci_vec.c")
|
|
652
|
+
out = (C.c_uint64 * 8)()
|
|
653
|
+
if self.lib.kci_vec_dup_stats(self._v, out) != 0:
|
|
654
|
+
raise RuntimeError("dup_stats: the index is not built (or its int8 rows were given up: search_only)")
|
|
655
|
+
return dict(rows=out[0], groups=out[1], rows_in_groups=out[2], largest=out[3], groups_over_m0=out[4], distinct=out[5],
|
|
656
|
+
ids_beside_rows=out[6], rows_with_company=out[7]) # the last two: with dedup=True
|
|
657
|
+
def is_built(self): return self.lib.kci_vec_is_built(self._v) != 0
|
|
658
|
+
@property
|
|
659
|
+
def has_lists(self): return self._lists
|
|
660
|
+
|
|
661
|
+
def close(self):
|
|
662
|
+
if getattr(self, "_s", None): self.lib.kci_vec_searcher_free(self._s); self._s = None
|
|
663
|
+
if getattr(self, "_v", None): self.lib.kci_vec_free(self._v); self._v = None
|
|
664
|
+
def __del__(self):
|
|
665
|
+
try: self.close()
|
|
666
|
+
except Exception: pass
|