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/hybrid.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Hybrid search: word matching (BM25) fused with the vector search, all in-process.
|
|
2
|
+
|
|
3
|
+
Embeddings miss exact things — product codes, names, numbers, rare words. A small BM25 index over the same
|
|
4
|
+
chunks catches them; the two rankings are fused by reciprocal rank (RRF), which needs no score scaling.
|
|
5
|
+
|
|
6
|
+
from kci_vec import KciVec
|
|
7
|
+
from kci_vec.hybrid import BM25Index, hybrid_search
|
|
8
|
+
bm = BM25Index()
|
|
9
|
+
bm.add(0, "Annual leave: 20 paid days ...") # same ids as the vectors
|
|
10
|
+
...
|
|
11
|
+
hits = hybrid_search(vec_index, bm, query_vec, "paid leave days", k=5) # [(id, fused, vec_rank, bm25_rank)]
|
|
12
|
+
bm.save("index.bm25.json"); bm = BM25Index.load("index.bm25.json")
|
|
13
|
+
|
|
14
|
+
Tokens: Latin / digit runs lower-cased as words; runs of CJK characters (Japanese, Chinese, Korean) as character
|
|
15
|
+
bigrams (plus the single character for 1-char runs), so no morphological analyser is needed. Pure Python / numpy;
|
|
16
|
+
tens of thousands of chunks search in milliseconds. The text index is stored as plain JSON — keep it beside the
|
|
17
|
+
encrypted vector snapshot inside your own encrypted store when the text is sensitive.
|
|
18
|
+
"""
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
import unicodedata
|
|
23
|
+
from collections import defaultdict
|
|
24
|
+
|
|
25
|
+
_WORD = re.compile(r"[0-9A-Za-z_][0-9A-Za-z_\-\.]*|[-ヿ㐀-鿿豈-ヲ-゚]+")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def tokenize(text):
|
|
29
|
+
"""Lower-cased words for Latin / digits; character bigrams for CJK runs."""
|
|
30
|
+
out = []
|
|
31
|
+
for m in _WORD.finditer(unicodedata.normalize("NFKC", text)):
|
|
32
|
+
t = m.group(0)
|
|
33
|
+
if ord(t[0]) < 0x3000:
|
|
34
|
+
out.append(t.lower().strip(".-"))
|
|
35
|
+
elif len(t) == 1:
|
|
36
|
+
out.append(t)
|
|
37
|
+
else:
|
|
38
|
+
out.extend(t[i:i + 2] for i in range(len(t) - 1))
|
|
39
|
+
return [t for t in out if t]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class BM25Index:
|
|
43
|
+
"""BM25 (k1, b) over tokenized texts keyed by your ids (the same ids as the vectors)."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, k1=1.5, b=0.75):
|
|
46
|
+
self.k1, self.b = k1, b
|
|
47
|
+
self.post = defaultdict(dict) # token -> {id: tf}
|
|
48
|
+
self.dl = {} # id -> token count
|
|
49
|
+
self.avgdl = 0.0
|
|
50
|
+
|
|
51
|
+
def add(self, id, text):
|
|
52
|
+
id = int(id)
|
|
53
|
+
if id in self.dl:
|
|
54
|
+
self.remove(id)
|
|
55
|
+
toks = tokenize(text)
|
|
56
|
+
self.dl[id] = len(toks)
|
|
57
|
+
for t in toks:
|
|
58
|
+
self.post[t][id] = self.post[t].get(id, 0) + 1
|
|
59
|
+
self.avgdl = sum(self.dl.values()) / max(1, len(self.dl))
|
|
60
|
+
|
|
61
|
+
def remove(self, id):
|
|
62
|
+
id = int(id)
|
|
63
|
+
if id not in self.dl:
|
|
64
|
+
return False
|
|
65
|
+
for t in list(self.post):
|
|
66
|
+
self.post[t].pop(id, None)
|
|
67
|
+
if not self.post[t]:
|
|
68
|
+
del self.post[t]
|
|
69
|
+
del self.dl[id]
|
|
70
|
+
self.avgdl = sum(self.dl.values()) / max(1, len(self.dl))
|
|
71
|
+
return True
|
|
72
|
+
|
|
73
|
+
def __len__(self):
|
|
74
|
+
return len(self.dl)
|
|
75
|
+
|
|
76
|
+
def search(self, text, k=10, allowed=None):
|
|
77
|
+
"""[(id, bm25 score)], best first. allowed: optional set of ids to restrict to."""
|
|
78
|
+
N = len(self.dl)
|
|
79
|
+
if N == 0:
|
|
80
|
+
return []
|
|
81
|
+
scores = defaultdict(float)
|
|
82
|
+
for t in set(tokenize(text)):
|
|
83
|
+
plist = self.post.get(t)
|
|
84
|
+
if not plist:
|
|
85
|
+
continue
|
|
86
|
+
idf = math.log(1.0 + (N - len(plist) + 0.5) / (len(plist) + 0.5))
|
|
87
|
+
for id, tf in plist.items():
|
|
88
|
+
if allowed is not None and id not in allowed:
|
|
89
|
+
continue
|
|
90
|
+
dl = self.dl[id]
|
|
91
|
+
scores[id] += idf * tf * (self.k1 + 1) / (tf + self.k1 * (1 - self.b + self.b * dl / self.avgdl))
|
|
92
|
+
top = sorted(scores.items(), key=lambda x: -x[1])[:k]
|
|
93
|
+
return [(id, float(s)) for id, s in top]
|
|
94
|
+
|
|
95
|
+
def save(self, path):
|
|
96
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
97
|
+
json.dump({"k1": self.k1, "b": self.b, "dl": self.dl,
|
|
98
|
+
"post": {t: p for t, p in self.post.items()}}, f, ensure_ascii=False)
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def load(cls, path):
|
|
102
|
+
with open(path, encoding="utf-8") as f:
|
|
103
|
+
d = json.load(f)
|
|
104
|
+
bm = cls(d.get("k1", 1.5), d.get("b", 0.75))
|
|
105
|
+
bm.dl = {int(k): v for k, v in d["dl"].items()}
|
|
106
|
+
for t, p in d["post"].items():
|
|
107
|
+
bm.post[t] = {int(k): v for k, v in p.items()}
|
|
108
|
+
bm.avgdl = sum(bm.dl.values()) / max(1, len(bm.dl))
|
|
109
|
+
return bm
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def rrf(rankings, k=10, c=60.0, weights=None):
|
|
113
|
+
"""Reciprocal rank fusion of several [(id, score)] lists: fused(id) = sum_i w_i / (c + rank_i(id)).
|
|
114
|
+
Returns [(id, fused, [rank_i or None ...])], best first."""
|
|
115
|
+
weights = weights or [1.0] * len(rankings)
|
|
116
|
+
fused, ranks = defaultdict(float), defaultdict(lambda: [None] * len(rankings))
|
|
117
|
+
for i, (lst, w) in enumerate(zip(rankings, weights)):
|
|
118
|
+
for r, (id, _) in enumerate(lst):
|
|
119
|
+
fused[id] += w / (c + r + 1)
|
|
120
|
+
ranks[id][i] = r + 1
|
|
121
|
+
top = sorted(fused.items(), key=lambda x: -x[1])[:k]
|
|
122
|
+
return [(id, float(s), ranks[id]) for id, s in top]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def mix(rankings, k=10, weights=None):
|
|
126
|
+
"""Merge several [(id, score)] lists (best first) by score: fused(id) = sum_i w_i * s_i(id), where s_i is list
|
|
127
|
+
i's score stretched so that its first row is 1 and its last row is 0 (0 when list i does not hold id). The
|
|
128
|
+
same as kci_hybrid_mix in kci_sparse.h . Unlike rrf it uses how far apart the scores are. When one side is
|
|
129
|
+
much weaker than the other give it a small weight (see choose_weight); equal weights can then do worse than
|
|
130
|
+
the strong side alone. Returns [(id, fused, [rank_i or None ...])], best first."""
|
|
131
|
+
weights = weights or [1.0] * len(rankings)
|
|
132
|
+
fused, ranks = defaultdict(float), defaultdict(lambda: [None] * len(rankings))
|
|
133
|
+
for i, (lst, w) in enumerate(zip(rankings, weights)):
|
|
134
|
+
if not lst:
|
|
135
|
+
continue
|
|
136
|
+
hi, lo = lst[0][1], lst[-1][1]
|
|
137
|
+
span = hi - lo
|
|
138
|
+
for r, (id, s) in enumerate(lst):
|
|
139
|
+
if ranks[id][i] is not None:
|
|
140
|
+
continue
|
|
141
|
+
v = (s - lo) / span if span != 0 else 1.0
|
|
142
|
+
fused[id] += w * min(1.0, max(0.0, v))
|
|
143
|
+
ranks[id][i] = r + 1
|
|
144
|
+
top = sorted(fused.items(), key=lambda x: (-x[1], x[0]))[:k]
|
|
145
|
+
return [(id, float(s), ranks[id]) for id, s in top]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def ndcg_at(ids, gains, k=10):
|
|
149
|
+
"""(see the header for this function)"""
|
|
150
|
+
dcg = sum(gains.get(i, 0) / math.log2(r + 2) for r, i in enumerate(ids[:k]))
|
|
151
|
+
ideal = sorted((g for g in gains.values() if g > 0), reverse=True)[:k]
|
|
152
|
+
idcg = sum(g / math.log2(r + 2) for r, g in enumerate(ideal))
|
|
153
|
+
return dcg / idcg if idcg > 0 else 0.0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def choose_weight(lists_a, lists_b, answers, k=10, method="mix", steps=10, prefer=None):
|
|
157
|
+
"""Pick the weight of side a (side b gets 1 - weight) from a few queries whose right answers are known.
|
|
158
|
+
|
|
159
|
+
lists_a[q], lists_b[q]: the two [(id, score)] lists of query q (e.g. dense and sparse, the depth you will
|
|
160
|
+
use). answers[q]: the right ids of query q, a set / list or {id: grade}. method: "mix" (by score) or "rrf" (by
|
|
161
|
+
rank).
|
|
162
|
+
|
|
163
|
+
prefer=None: the weight with the highest mean (of equally good ones the middle one)."""
|
|
164
|
+
if len(lists_a) != len(lists_b) or len(lists_a) != len(answers) or not lists_a:
|
|
165
|
+
raise ValueError("choose_weight: the three inputs must have one entry per query (at least one)")
|
|
166
|
+
if method not in ("mix", "rrf"):
|
|
167
|
+
raise ValueError("choose_weight: method must be 'mix' or 'rrf'")
|
|
168
|
+
if prefer is not None and not 0.0 <= prefer <= 1.0:
|
|
169
|
+
raise ValueError("choose_weight: prefer must be between 0 and 1")
|
|
170
|
+
fuse = mix if method == "mix" else rrf
|
|
171
|
+
gains = [a if isinstance(a, dict) else {i: 1 for i in a} for a in answers]
|
|
172
|
+
ws = [s / steps for s in range(steps + 1)]
|
|
173
|
+
per = [] # per[weight][query]
|
|
174
|
+
for w in ws:
|
|
175
|
+
row = []
|
|
176
|
+
for la, lb, g in zip(lists_a, lists_b, gains):
|
|
177
|
+
if w == 0: ids = [i for i, _ in lb[:k]]
|
|
178
|
+
elif w == 1: ids = [i for i, _ in la[:k]]
|
|
179
|
+
else: ids = [i for i, _, _ in fuse([la, lb], k=k, weights=[w, 1 - w])]
|
|
180
|
+
row.append(ndcg_at(ids, g, k))
|
|
181
|
+
per.append(row)
|
|
182
|
+
n = len(gains)
|
|
183
|
+
table = [(w, sum(r) / n) for w, r in zip(ws, per)]
|
|
184
|
+
best = max(v for _, v in table)
|
|
185
|
+
if prefer is None:
|
|
186
|
+
good = [w for w, v in table if v >= best - 1e-12]
|
|
187
|
+
return good[len(good) // 2], table
|
|
188
|
+
bi = max(range(len(ws)), key=lambda i: table[i][1])
|
|
189
|
+
ok = []
|
|
190
|
+
for i in range(len(ws)):
|
|
191
|
+
d = [x - y for x, y in zip(per[bi], per[i])]
|
|
192
|
+
m = sum(d) / n
|
|
193
|
+
se = math.sqrt(sum((x - m) ** 2 for x in d) / (n - 1) / n) if n > 1 else 0.0
|
|
194
|
+
if m <= se: ok.append(ws[i]) # not clearly worse than the best
|
|
195
|
+
return min(ok, key=lambda w: (abs(w - prefer), w)), table
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def hybrid_search(vec, bm25, query_vec, query_text, k=10, depth=None, filter=None, w_vec=1.0, w_text=1.0, **search_kw):
|
|
199
|
+
"""Vector search (kci_vec.KciVec) + BM25 fused by RRF. depth: candidates taken from each side (default 4k).
|
|
200
|
+
filter: a set of allowed ids (applied to both sides) or a callable id -> bool (vector side; BM25 filtered after).
|
|
201
|
+
Returns [(id, fused_score, vec_rank, bm25_rank)], best first; a rank is None when that side did not return the id."""
|
|
202
|
+
depth = depth or 4 * k
|
|
203
|
+
vhits = vec.search(query_vec, k=depth, filter=filter, **search_kw)
|
|
204
|
+
allowed = filter if isinstance(filter, (set, frozenset)) else None
|
|
205
|
+
thits = bm25.search(query_text, k=depth, allowed=allowed)
|
|
206
|
+
if callable(filter):
|
|
207
|
+
thits = [(i, s) for i, s in thits if filter(i)]
|
|
208
|
+
return [(id, s, r[0], r[1]) for id, s, r in rrf([vhits, thits], k=k, weights=[w_vec, w_text])]
|
|
Binary file
|
|
Binary file
|
kci_vec/sparse.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Sparse vectors (word weights: SPLADE, BM25 and the like) and hybrid search with the dense index.
|
|
2
|
+
|
|
3
|
+
A sparse vector is given as two arrays: the dimension numbers that are present and their weights. Similarity
|
|
4
|
+
is the inner product. Use the same id for the same document as in the dense KciVec.
|
|
5
|
+
|
|
6
|
+
Needs the library libkci_sparse (built from kci_sparse.c by build_kci_vec.sh, or by pip from the repo tree).
|
|
7
|
+
Set KCI_SPARSE_LIB to the .dll/.so/.dylib, or place it next to this file / the repo root. A KciSparse is not
|
|
8
|
+
for use from several threads at once (it holds one search context). New. No save / load yet."""
|
|
9
|
+
import ctypes as C
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from .hybrid import rrf, mix, choose_weight
|
|
15
|
+
|
|
16
|
+
c_f32p = C.POINTER(C.c_float)
|
|
17
|
+
c_u32p = C.POINTER(C.c_uint32)
|
|
18
|
+
c_u64p = C.POINTER(C.c_uint64)
|
|
19
|
+
_FILTER = C.CFUNCTYPE(C.c_int, C.c_uint64, C.c_void_p) # int filt(uint64 id, void *ctx)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _make_filter(filt):
|
|
23
|
+
"""filt: None | callable(id) -> bool | a set / list / numpy array of allowed ids. Returns a C callback or None."""
|
|
24
|
+
if filt is None:
|
|
25
|
+
return None
|
|
26
|
+
if callable(filt):
|
|
27
|
+
return _FILTER(lambda i, _ctx: 1 if filt(int(i)) else 0)
|
|
28
|
+
allowed = filt if isinstance(filt, (set, frozenset)) else set(int(x) for x in np.asarray(filt).ravel())
|
|
29
|
+
return _FILTER(lambda i, _ctx: 1 if int(i) in allowed else 0)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _BlockParams(C.Structure):
|
|
33
|
+
_fields_ = [("struct_size", C.c_uint), ("list_len", C.c_int), ("block_size", C.c_int), ("summary_mass", C.c_float), ("threads", C.c_int),
|
|
34
|
+
("cluster_terms", C.c_int), ("centre_terms", C.c_int), ("head_mass", C.c_float), ("global_cut", C.c_int)]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _find_lib():
|
|
38
|
+
if os.environ.get("KCI_SPARSE_LIB"):
|
|
39
|
+
return os.environ["KCI_SPARSE_LIB"]
|
|
40
|
+
names = ["libkci_sparse.dll", "libkci_sparse.so", "libkci_sparse.dylib"] if sys.platform == "win32" \
|
|
41
|
+
else ["libkci_sparse.so", "libkci_sparse.dylib", "libkci_sparse.dll"]
|
|
42
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
43
|
+
for r in (here, os.path.join(here, "..", ".."), os.path.join(here, "..", "..", "..", ".."), os.getcwd()):
|
|
44
|
+
for n in names:
|
|
45
|
+
p = os.path.abspath(os.path.join(r, n))
|
|
46
|
+
if os.path.exists(p):
|
|
47
|
+
return p
|
|
48
|
+
raise FileNotFoundError("libkci_sparse not found; set KCI_SPARSE_LIB or build it (see module docstring)")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_LIB = None
|
|
52
|
+
def _lib():
|
|
53
|
+
global _LIB
|
|
54
|
+
if _LIB is None:
|
|
55
|
+
s = C.CDLL(_find_lib())
|
|
56
|
+
s.kci_sparse_new.restype = C.c_void_p; s.kci_sparse_new.argtypes = [C.c_uint32]
|
|
57
|
+
s.kci_sparse_free.restype = None; s.kci_sparse_free.argtypes = [C.c_void_p]
|
|
58
|
+
s.kci_sparse_add.restype = C.c_int64; s.kci_sparse_add.argtypes = [C.c_void_p, C.c_uint64, c_u32p, c_f32p, C.c_int]
|
|
59
|
+
s.kci_sparse_insert.restype = C.c_int64; s.kci_sparse_insert.argtypes = [C.c_void_p, C.c_uint64, c_u32p, c_f32p, C.c_int]
|
|
60
|
+
s.kci_sparse_pending.restype = C.c_uint32; s.kci_sparse_pending.argtypes = [C.c_void_p]
|
|
61
|
+
s.kci_sparse_delete.restype = C.c_int; s.kci_sparse_delete.argtypes = [C.c_void_p, C.c_uint64]
|
|
62
|
+
s.kci_sparse_build.restype = C.c_int; s.kci_sparse_build.argtypes = [C.c_void_p, C.c_int, C.POINTER(C.c_double)]
|
|
63
|
+
s.kci_sparse_searcher_new.restype = C.c_void_p; s.kci_sparse_searcher_new.argtypes = [C.c_void_p]
|
|
64
|
+
s.kci_sparse_searcher_free.restype = None; s.kci_sparse_searcher_free.argtypes = [C.c_void_p]
|
|
65
|
+
s.kci_sparse_search.restype = C.c_int
|
|
66
|
+
s.kci_sparse_search.argtypes = [C.c_void_p, c_u32p, c_f32p, C.c_int, C.c_int, C.c_uint32, C.c_int, c_u64p, c_f32p]
|
|
67
|
+
s.kci_sparse_build_blocks.restype = C.c_int
|
|
68
|
+
s.kci_sparse_build_blocks.argtypes = [C.c_void_p, C.POINTER(_BlockParams), C.POINTER(C.c_double)]
|
|
69
|
+
s.kci_sparse_build_knn.restype = C.c_int
|
|
70
|
+
s.kci_sparse_build_knn.argtypes = [C.c_void_p, C.c_int, C.c_int, C.c_float, C.c_int, C.POINTER(C.c_double)]
|
|
71
|
+
s.kci_sparse_drop_lists.restype = C.c_int; s.kci_sparse_drop_lists.argtypes = [C.c_void_p]
|
|
72
|
+
s.kci_sparse_has_blocks.restype = C.c_int; s.kci_sparse_has_blocks.argtypes = [C.c_void_p]
|
|
73
|
+
s.kci_sparse_drop_rows.restype = C.c_int; s.kci_sparse_drop_rows.argtypes = [C.c_void_p]
|
|
74
|
+
s.kci_sparse_has_rows.restype = C.c_int; s.kci_sparse_has_rows.argtypes = [C.c_void_p]
|
|
75
|
+
s.kci_sparse_knn.restype = C.c_int; s.kci_sparse_knn.argtypes = [C.c_void_p]
|
|
76
|
+
s.kci_sparse_search_blocks.restype = C.c_int
|
|
77
|
+
s.kci_sparse_search_blocks.argtypes = [C.c_void_p, c_u32p, c_f32p, C.c_int, C.c_int, C.c_int, C.c_float, C.c_int, c_u64p, c_f32p]
|
|
78
|
+
s.kci_sparse_searcher_set_filter.restype = None
|
|
79
|
+
s.kci_sparse_searcher_set_filter.argtypes = [C.c_void_p, C.c_void_p, C.c_void_p]
|
|
80
|
+
s.kci_sparse_count.restype = C.c_uint32; s.kci_sparse_count.argtypes = [C.c_void_p]
|
|
81
|
+
s.kci_sparse_is_built.restype = C.c_int; s.kci_sparse_is_built.argtypes = [C.c_void_p]
|
|
82
|
+
s.kci_sparse_bytes.restype = C.c_int64; s.kci_sparse_bytes.argtypes = [C.c_void_p]
|
|
83
|
+
s.kci_sparse_dim.restype = C.c_uint32; s.kci_sparse_dim.argtypes = [C.c_void_p]
|
|
84
|
+
s.kci_sparse_save.restype = C.c_int; s.kci_sparse_save.argtypes = [C.c_void_p, C.c_char_p, C.c_char_p, C.c_int]
|
|
85
|
+
s.kci_sparse_load.restype = C.c_void_p; s.kci_sparse_load.argtypes = [C.c_char_p, C.c_char_p, C.c_int]
|
|
86
|
+
_LIB = s
|
|
87
|
+
return _LIB
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _pairs(indices, values, dim):
|
|
91
|
+
"""Check one sparse vector and return it as contiguous uint32 / float32 arrays."""
|
|
92
|
+
idx = np.asarray(indices)
|
|
93
|
+
val = np.ascontiguousarray(values, dtype=np.float32)
|
|
94
|
+
if idx.ndim != 1 or val.ndim != 1 or len(idx) != len(val):
|
|
95
|
+
raise ValueError("indices and values must be two 1-d arrays of the same length")
|
|
96
|
+
if len(idx):
|
|
97
|
+
if idx.dtype.kind not in "iu":
|
|
98
|
+
raise ValueError("indices must be integers")
|
|
99
|
+
if int(idx.min()) < 0 or int(idx.max()) >= dim:
|
|
100
|
+
raise ValueError(f"a dimension number is outside 0..{dim - 1}")
|
|
101
|
+
if not np.isfinite(val).all():
|
|
102
|
+
raise ValueError("a weight is NaN or infinite")
|
|
103
|
+
return np.ascontiguousarray(idx, dtype=np.uint32), val
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class KciSparse:
|
|
107
|
+
"""One sparse index over a vocabulary of `dim` dimensions."""
|
|
108
|
+
|
|
109
|
+
def __init__(self, dim):
|
|
110
|
+
self.lib = _lib()
|
|
111
|
+
if not (0 < int(dim) < 2 ** 32):
|
|
112
|
+
raise ValueError("dim must be between 1 and 2^32 - 1")
|
|
113
|
+
self.dim = int(dim)
|
|
114
|
+
self._s = self.lib.kci_sparse_new(self.dim)
|
|
115
|
+
if not self._s:
|
|
116
|
+
raise MemoryError("kci_sparse_new failed")
|
|
117
|
+
self._searcher = None
|
|
118
|
+
|
|
119
|
+
def close(self):
|
|
120
|
+
if getattr(self, "_searcher", None):
|
|
121
|
+
self.lib.kci_sparse_searcher_free(self._searcher)
|
|
122
|
+
self._searcher = None
|
|
123
|
+
if getattr(self, "_s", None):
|
|
124
|
+
self.lib.kci_sparse_free(self._s)
|
|
125
|
+
self._s = None
|
|
126
|
+
|
|
127
|
+
def __del__(self):
|
|
128
|
+
try:
|
|
129
|
+
self.close()
|
|
130
|
+
except Exception:
|
|
131
|
+
pass
|
|
132
|
+
|
|
133
|
+
def __len__(self):
|
|
134
|
+
return int(self.lib.kci_sparse_count(self._s))
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def nbytes(self):
|
|
138
|
+
return int(self.lib.kci_sparse_bytes(self._s))
|
|
139
|
+
|
|
140
|
+
def add(self, id, indices, values):
|
|
141
|
+
"""Add one row. A dimension given twice is summed."""
|
|
142
|
+
idx, val = _pairs(indices, values, self.dim)
|
|
143
|
+
r = self.lib.kci_sparse_add(self._s, int(id), idx.ctypes.data_as(c_u32p), val.ctypes.data_as(c_f32p), len(idx))
|
|
144
|
+
if r < 0:
|
|
145
|
+
raise RuntimeError("kci_sparse_add failed")
|
|
146
|
+
return int(r)
|
|
147
|
+
|
|
148
|
+
def insert(self, id, indices, values):
|
|
149
|
+
"""Add one row to a built index without rebuilding; searches find it at once. Every search scores all
|
|
150
|
+
rows inserted since the last build, so call build() again once `pending` is in the thousands."""
|
|
151
|
+
idx, val = _pairs(indices, values, self.dim)
|
|
152
|
+
r = self.lib.kci_sparse_insert(self._s, int(id), idx.ctypes.data_as(c_u32p), val.ctypes.data_as(c_f32p), len(idx))
|
|
153
|
+
if r < 0:
|
|
154
|
+
raise RuntimeError("kci_sparse_insert failed (call build() first)")
|
|
155
|
+
return int(r)
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def pending(self):
|
|
159
|
+
"""Rows inserted since the last build."""
|
|
160
|
+
return int(self.lib.kci_sparse_pending(self._s))
|
|
161
|
+
|
|
162
|
+
def add_csr(self, ids, indptr, indices, data):
|
|
163
|
+
"""Add many rows held in CSR form (as in scipy.sparse.csr_matrix: m.indptr, m.indices, m.data).
|
|
164
|
+
Row i is ids[i] with pairs indptr[i] .. indptr[i+1]. Nothing is added if the input is refused."""
|
|
165
|
+
ids = np.asarray(ids)
|
|
166
|
+
indptr = np.asarray(indptr, dtype=np.int64)
|
|
167
|
+
if ids.ndim != 1 or len(indptr) != len(ids) + 1:
|
|
168
|
+
raise ValueError("indptr must have len(ids) + 1 entries")
|
|
169
|
+
idx, val = _pairs(indices, data, self.dim)
|
|
170
|
+
if len(indptr) and (indptr[0] != 0 or indptr[-1] != len(idx) or (np.diff(indptr) < 0).any()):
|
|
171
|
+
raise ValueError("indptr does not describe indices / data")
|
|
172
|
+
pi, pv = idx.ctypes.data, val.ctypes.data
|
|
173
|
+
add, s = self.lib.kci_sparse_add, self._s
|
|
174
|
+
for i in range(len(ids)):
|
|
175
|
+
a, n = int(indptr[i]), int(indptr[i + 1] - indptr[i])
|
|
176
|
+
if add(s, int(ids[i]), C.cast(pi + 4 * a, c_u32p), C.cast(pv + 4 * a, c_f32p), n) < 0:
|
|
177
|
+
raise RuntimeError(f"kci_sparse_add failed at row {i} (rows before it were added)")
|
|
178
|
+
return len(self)
|
|
179
|
+
|
|
180
|
+
def delete(self, id):
|
|
181
|
+
"""Remove the row(s) added under this id. No rebuild needed. Returns how many were removed."""
|
|
182
|
+
r = self.lib.kci_sparse_delete(self._s, int(id))
|
|
183
|
+
if r < 0:
|
|
184
|
+
raise RuntimeError("kci_sparse_delete failed")
|
|
185
|
+
return int(r)
|
|
186
|
+
|
|
187
|
+
def save(self, path, key=None):
|
|
188
|
+
"""Write the index to `path` with everything built so far, so load() needs no build. key: bytes or None."""
|
|
189
|
+
kp = (bytes(key), len(key)) if key else (None, 0)
|
|
190
|
+
if self.lib.kci_sparse_save(self._s, os.fsencode(path), *kp) != 0:
|
|
191
|
+
raise RuntimeError("kci_sparse_save failed")
|
|
192
|
+
|
|
193
|
+
@classmethod
|
|
194
|
+
def load(cls, path, key=None):
|
|
195
|
+
"""Read an index written by save(). Wrong key, damaged or altered file, a file saved without a key when
|
|
196
|
+
one is given (or the other way round) -> RuntimeError."""
|
|
197
|
+
lib = _lib()
|
|
198
|
+
kp = (bytes(key), len(key)) if key else (None, 0)
|
|
199
|
+
p = lib.kci_sparse_load(os.fsencode(path), *kp)
|
|
200
|
+
if not p:
|
|
201
|
+
raise RuntimeError("load failed (wrong key, damaged file, or file missing)")
|
|
202
|
+
self = cls.__new__(cls)
|
|
203
|
+
self.lib = lib
|
|
204
|
+
self._s = p
|
|
205
|
+
self._searcher = None
|
|
206
|
+
self.dim = int(lib.kci_sparse_dim(p))
|
|
207
|
+
return self
|
|
208
|
+
|
|
209
|
+
def build(self, threads=0):
|
|
210
|
+
"""Build the search structure over everything added. Returns the seconds it took."""
|
|
211
|
+
if self._searcher:
|
|
212
|
+
self.lib.kci_sparse_searcher_free(self._searcher)
|
|
213
|
+
self._searcher = None
|
|
214
|
+
secs = C.c_double(0)
|
|
215
|
+
if self.lib.kci_sparse_build(self._s, int(threads), C.byref(secs)) != 0:
|
|
216
|
+
raise MemoryError("kci_sparse_build failed")
|
|
217
|
+
return secs.value
|
|
218
|
+
|
|
219
|
+
def _with_filter(self, filter, call):
|
|
220
|
+
"""Run one search with the filter set on the searcher, and take it off again whatever happens."""
|
|
221
|
+
cb = _make_filter(filter)
|
|
222
|
+
if cb is None:
|
|
223
|
+
return call()
|
|
224
|
+
self.lib.kci_sparse_searcher_set_filter(self._searcher, C.cast(cb, C.c_void_p), None)
|
|
225
|
+
try:
|
|
226
|
+
return call()
|
|
227
|
+
finally:
|
|
228
|
+
self.lib.kci_sparse_searcher_set_filter(self._searcher, None, None)
|
|
229
|
+
|
|
230
|
+
def search(self, indices, values, k=10, budget=0, rerank=None, filter=None):
|
|
231
|
+
"""Top k by inner product, as [(id, score)], best first. budget 0 = exact; a positive budget caps the work
|
|
232
|
+
per query (larger = closer to exact) and the best `rerank` rows found (default 3k) are scored exactly.
|
|
233
|
+
filter: a set / list of allowed ids or a callable id -> bool; only those rows are returned."""
|
|
234
|
+
if not self.lib.kci_sparse_is_built(self._s):
|
|
235
|
+
raise RuntimeError("call build() first (rows were added since the last build)")
|
|
236
|
+
if k <= 0 or budget < 0:
|
|
237
|
+
raise ValueError("k must be positive and budget must not be negative")
|
|
238
|
+
if self._searcher is None:
|
|
239
|
+
self._searcher = self.lib.kci_sparse_searcher_new(self._s)
|
|
240
|
+
if not self._searcher:
|
|
241
|
+
raise MemoryError("kci_sparse_searcher_new failed")
|
|
242
|
+
idx, val = _pairs(indices, values, self.dim)
|
|
243
|
+
ids = np.empty(k, dtype=np.uint64)
|
|
244
|
+
sc = np.empty(k, dtype=np.float32)
|
|
245
|
+
n = self._with_filter(filter, lambda: self.lib.kci_sparse_search(
|
|
246
|
+
self._searcher, idx.ctypes.data_as(c_u32p), val.ctypes.data_as(c_f32p), len(idx),
|
|
247
|
+
int(k), int(min(budget, 2 ** 32 - 1)), int(rerank if rerank is not None else 3 * k),
|
|
248
|
+
ids.ctypes.data_as(c_u64p), sc.ctypes.data_as(c_f32p)))
|
|
249
|
+
if n < 0:
|
|
250
|
+
raise RuntimeError("kci_sparse_search failed")
|
|
251
|
+
return [(int(ids[i]), float(sc[i])) for i in range(n)]
|
|
252
|
+
|
|
253
|
+
def build_blocks(self, list_len=0, block_size=0, summary_mass=0.0, threads=0, cluster_terms=0, centre_terms=0, head_mass=0.0, global_cut=False):
|
|
254
|
+
"""The structure search_blocks needs (call build() first). 0 = the default of each setting; see
|
|
255
|
+
KciSparseBlockParams in kci_sparse.h. global_cut is experimental (very slow builds on large data): leave it
|
|
256
|
+
False. Returns the seconds it took."""
|
|
257
|
+
p = _BlockParams(C.sizeof(_BlockParams), int(list_len), int(block_size), float(summary_mass), int(threads), int(cluster_terms),
|
|
258
|
+
int(centre_terms), float(head_mass), 1 if global_cut else 0)
|
|
259
|
+
secs = C.c_double(0)
|
|
260
|
+
if self.lib.kci_sparse_build_blocks(self._s, C.byref(p), C.byref(secs)) != 0:
|
|
261
|
+
raise RuntimeError("kci_sparse_build_blocks failed (not built, a bad setting, or out of memory)")
|
|
262
|
+
return secs.value
|
|
263
|
+
|
|
264
|
+
def build_neighbours(self, knn=20, query_terms=0, heap_factor=0.0, threads=0):
|
|
265
|
+
"""For every row, its knn most similar rows (call build_blocks() first). One block search per row, so minutes on
|
|
266
|
+
millions of rows. Returns the seconds it took."""
|
|
267
|
+
secs = C.c_double(0)
|
|
268
|
+
if self.lib.kci_sparse_build_knn(self._s, int(knn), int(query_terms), float(heap_factor), int(threads), C.byref(secs)) != 0:
|
|
269
|
+
raise RuntimeError("kci_sparse_build_knn failed (no blocks, a bad setting, or out of memory)")
|
|
270
|
+
return secs.value
|
|
271
|
+
|
|
272
|
+
def drop_lists(self):
|
|
273
|
+
"""Free the memory search() needs once the blocks are built; search() is then refused until the next build()."""
|
|
274
|
+
if self.lib.kci_sparse_drop_lists(self._s) != 0:
|
|
275
|
+
raise RuntimeError("kci_sparse_drop_lists failed (call build_blocks() first)")
|
|
276
|
+
|
|
277
|
+
def drop_rows(self):
|
|
278
|
+
"""For a finished index: also free the full rows (and the lists). search_blocks() goes on working, with scores
|
|
279
|
+
from the 16-bit copy of the rows (within about 1e-4 of the exact ones); add(), insert(), build(), build_blocks(),
|
|
280
|
+
build_neighbours() and search() are refused from then on. delete(), save() and load() work."""
|
|
281
|
+
if self.lib.kci_sparse_drop_rows(self._s) != 0:
|
|
282
|
+
raise RuntimeError("kci_sparse_drop_rows failed (needs build_blocks(), no inserted rows waiting, dimension below 65536)")
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def has_rows(self):
|
|
286
|
+
"""False after drop_rows() (also for an index loaded from a file saved in that state)."""
|
|
287
|
+
return bool(self.lib.kci_sparse_has_rows(self._s))
|
|
288
|
+
|
|
289
|
+
def search_blocks(self, indices, values, k=10, query_terms=8, heap_factor=1.0, neighbours=0, filter=None):
|
|
290
|
+
"""(see the header for this function)"""
|
|
291
|
+
if not self.lib.kci_sparse_is_built(self._s):
|
|
292
|
+
raise RuntimeError("call build() first (rows were added since the last build)")
|
|
293
|
+
if not self.lib.kci_sparse_has_blocks(self._s):
|
|
294
|
+
raise RuntimeError("call build_blocks() first")
|
|
295
|
+
if k <= 0 or neighbours < 0 or not (0 < heap_factor <= 4):
|
|
296
|
+
raise ValueError("k must be positive, neighbours not negative, heap_factor in (0, 4]")
|
|
297
|
+
if self._searcher is None:
|
|
298
|
+
self._searcher = self.lib.kci_sparse_searcher_new(self._s)
|
|
299
|
+
if not self._searcher:
|
|
300
|
+
raise MemoryError("kci_sparse_searcher_new failed")
|
|
301
|
+
idx, val = _pairs(indices, values, self.dim)
|
|
302
|
+
ids = np.empty(k, dtype=np.uint64)
|
|
303
|
+
sc = np.empty(k, dtype=np.float32)
|
|
304
|
+
n = self._with_filter(filter, lambda: self.lib.kci_sparse_search_blocks(
|
|
305
|
+
self._searcher, idx.ctypes.data_as(c_u32p), val.ctypes.data_as(c_f32p), len(idx),
|
|
306
|
+
int(k), int(query_terms), float(heap_factor), int(neighbours),
|
|
307
|
+
ids.ctypes.data_as(c_u64p), sc.ctypes.data_as(c_f32p)))
|
|
308
|
+
if n < 0:
|
|
309
|
+
raise RuntimeError("kci_sparse_search_blocks failed")
|
|
310
|
+
return [(int(ids[i]), float(sc[i])) for i in range(n)]
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def seal(data, key):
|
|
314
|
+
"""Encrypt bytes with a passphrase (kci_seal: PBKDF2-HMAC-SHA256, AES-256-CTR, AES-256-CMAC). -> bytes, 40 longer."""
|
|
315
|
+
data, key = bytes(data), (key.encode("utf-8") if isinstance(key, str) else bytes(key))
|
|
316
|
+
if not key: raise ValueError("seal: empty key")
|
|
317
|
+
lib = _lib(); out = C.create_string_buffer(len(data) + 40)
|
|
318
|
+
lib.kci_seal.restype = C.c_int64; lib.kci_seal.argtypes = [C.c_char_p, C.c_uint64, C.c_char_p, C.c_int, C.c_char_p]
|
|
319
|
+
n = lib.kci_seal(data, len(data), key, len(key), out)
|
|
320
|
+
if n != len(data) + 40: raise RuntimeError("kci_seal failed")
|
|
321
|
+
return out.raw
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def unseal(blob, key):
|
|
325
|
+
"""The bytes back from seal(). Wrong key, a changed or missing byte -> RuntimeError (nothing is returned)."""
|
|
326
|
+
blob, key = bytes(blob), (key.encode("utf-8") if isinstance(key, str) else bytes(key))
|
|
327
|
+
if not key: raise ValueError("unseal: empty key")
|
|
328
|
+
lib = _lib(); out = C.create_string_buffer(max(1, len(blob) - 40))
|
|
329
|
+
lib.kci_unseal.restype = C.c_int64; lib.kci_unseal.argtypes = [C.c_char_p, C.c_uint64, C.c_char_p, C.c_int, C.c_char_p]
|
|
330
|
+
n = lib.kci_unseal(blob, len(blob), key, len(key), out)
|
|
331
|
+
if n < 0: raise RuntimeError("unseal failed (wrong key, or the data was changed or cut off)")
|
|
332
|
+
return out.raw[:n]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def hybrid_search_sparse(vec, sparse, query_vec, q_indices, q_values, k=10, depth=None, w_vec=1.0, w_sparse=1.0,
|
|
336
|
+
budget=0, rerank=None, filter=None, method="rrf", **search_kw):
|
|
337
|
+
"""Dense search (kci_vec.KciVec) + sparse search (KciSparse) merged by reciprocal rank (RRF). method="mix" merges
|
|
338
|
+
by score instead (hybrid.mix); weights from hybrid.choose_weight. depth: candidates taken from each side
|
|
339
|
+
(default 4k). Taking many more than that lets rows that only one side cares about rise; tune w_vec / w_sparse
|
|
340
|
+
first. filter: a set / list of allowed ids or a callable id -> bool, applied to both sides. search_kw goes to
|
|
341
|
+
vec.search. Returns [(id, fused_score, vec_rank, sparse_rank)], best first; a rank is None when that side did
|
|
342
|
+
not return the id."""
|
|
343
|
+
depth = depth or 4 * k
|
|
344
|
+
vhits = vec.search(query_vec, k=depth, filter=filter, **search_kw)
|
|
345
|
+
shits = sparse.search(q_indices, q_values, k=depth, budget=budget, rerank=rerank, filter=filter)
|
|
346
|
+
if method not in ("rrf", "mix"):
|
|
347
|
+
raise ValueError("method must be 'rrf' or 'mix'")
|
|
348
|
+
fuse = mix if method == "mix" else rrf
|
|
349
|
+
return [(id, s, r[0], r[1]) for id, s, r in fuse([vhits, shits], k=k, weights=[w_vec, w_sparse])]
|