kci-vec 0.0.0-stage → 0.2.30

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,208 @@
1
+ /*
2
+ * kci_sparse.h — sparse-vector index (public API), the companion of kci_vec
3
+ *
4
+ * A sparse vector is a short list of (dimension, weight) pairs out of a very
5
+ * large vocabulary: learned sparse embeddings (SPLADE and the like), BM25 /
6
+ * TF-IDF term weights. Similarity is the inner product.
7
+ * - Exact top-k, and an approximate search with a work budget.
8
+ * - Reusable per-thread searchers; many may search one built index at once.
9
+ * - kci_hybrid_rrf: merge the ranking of this index with the ranking of a
10
+ * dense kci_vec index (or any other ranking) into one.
11
+ *
12
+ * New file. kci_vec.c stays a one-file dense index; this file does
13
+ * not include it and needs nothing from it. Ids are opaque u64 keys chosen by
14
+ * the caller — use the same id for the same document on both sides.
15
+ *
16
+ * Thread-safety: single-writer. Do not call _add or _build concurrently with
17
+ * searches on the same handle.
18
+ */
19
+ #ifndef KCI_SPARSE_H
20
+ #define KCI_SPARSE_H
21
+
22
+ #include <stdint.h>
23
+ #include <stddef.h>
24
+
25
+ #ifdef __cplusplus
26
+ extern "C" {
27
+ #endif
28
+
29
+ typedef struct KciSparse KciSparse;
30
+
31
+ /* Create an empty index. `dim` is the vocabulary size: every dimension number
32
+ * must be < dim (SPLADE with the BERT vocabulary: 30522). Returns NULL on bad
33
+ * args / OOM. */
34
+ KciSparse *kci_sparse_new(uint32_t dim);
35
+ void kci_sparse_free(KciSparse *s);
36
+
37
+ /* Append one row. idx[0..nnz) are the dimension numbers, val[0..nnz) their
38
+ * weights; any order. A dimension given twice is summed, zero weights are
39
+ * dropped, negative weights are allowed. Returns the new count, or -1 on bad
40
+ * args (a dimension >= dim, a NaN / infinite weight) / OOM — the row is then
41
+ * not added. Rows added after kci_sparse_build need another build. */
42
+ int64_t kci_sparse_add(KciSparse *s, uint64_t id, const uint32_t *idx, const float *val, int nnz);
43
+
44
+ /* Build the search structure over everything added so far. threads <= 0 = cpu
45
+ * cores. Returns 0 on success, -1 on OOM; writes wall-clock seconds to
46
+ * *out_secs if non-NULL. */
47
+ int kci_sparse_build(KciSparse *s, int threads, double *out_secs);
48
+
49
+ /* Add one row to an index that is already built, without rebuilding. Same arguments and return value as
50
+ * kci_sparse_add; -1 also if the index is not built. Not to be called while searches run on the same handle. */
51
+ int64_t kci_sparse_insert(KciSparse *s, uint64_t id, const uint32_t *idx, const float *val, int nnz);
52
+ uint32_t kci_sparse_pending(const KciSparse *s); /* rows inserted since the last build */
53
+
54
+ /* Remove every row that was added under this id. Searches stop returning it at
55
+ * once — no rebuild is needed and existing searchers stay valid; its memory is
56
+ * given back by the next kci_sparse_build. Returns how many rows were removed
57
+ * (0 = no such id), or -1 on bad args / OOM. Like _add, not to be called while
58
+ * searches run on the same handle. */
59
+ int kci_sparse_delete(KciSparse *s, uint64_t id);
60
+
61
+ /* Reusable per-thread search context (one per worker thread). */
62
+ typedef struct KciSparseSearcher KciSparseSearcher;
63
+ KciSparseSearcher *kci_sparse_searcher_new(KciSparse *s);
64
+ void kci_sparse_searcher_free(KciSparseSearcher *S);
65
+
66
+ /* Restrict every later search of this searcher to the rows whose id passes
67
+ * `fn` (non-zero = allowed; same shape as KciVecFilter, so one function can
68
+ * serve both sides of a hybrid search). fn == NULL removes the restriction.
69
+ * The function is called only for rows that would otherwise enter the result,
70
+ * from the thread that runs the search. With a filter that lets few rows
71
+ * through, the approximate searches find fewer of them: raise budget /
72
+ * query_terms, or use the exact search. */
73
+ typedef int (*KciSparseFilter)(uint64_t id, void *ctx);
74
+ void kci_sparse_searcher_set_filter(KciSparseSearcher *S, KciSparseFilter fn, void *ctx);
75
+
76
+ /* Exact top-k by inner product. Fills out_ids[0..ret) and (if non-NULL) out_scores[], best first; equal scores
77
+ * come in the order the rows were added. Only rows that share a dimension with the query are returned, so ret may
78
+ * be < k. Returns -1 on bad args / not built / a searcher older than the last build. With negative weights a row
79
+ * that shares a dimension can score below 0 and is still returned, while a row that shares none (score 0) is not. */
80
+ int kci_sparse_search_exact(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
81
+ int k, uint64_t *out_ids, float *out_scores);
82
+
83
+ /* Approximate top-k. The best `rerank_n` rows found within the budget are then scored exactly and the top k of
84
+ * those returned (rerank_n < k is raised to k; a few times k is a good start). The scores returned are exact inner
85
+ * products. Same return values as above. */
86
+ int kci_sparse_search(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
87
+ int k, uint32_t budget, int rerank_n, uint64_t *out_ids, float *out_scores);
88
+
89
+ /* ── Block search: for large indexes ───────────────────────────── An extra structure on top of a built index. The
90
+ * front of every dimension's list (its `list_len` largest weights) is cut into groups of similar rows, and each
91
+ * group keeps a short summary that bounds the score any of its rows can reach. A query looks only at its
92
+ * `query_terms` heaviest dimensions, skips the groups whose bound cannot enter the current top k, and scores the
93
+ * rows of the others exactly. Zero / NULL = the default for that field. struct_size: set it to
94
+ * sizeof(KciSparseBlockParams) (or leave it 0 after a memset: 0 means "the fields up to global_cut", the layout of
95
+ * this first published version). Fields added later come after global_cut and are read only when struct_size
96
+ * covers them, so a program compiled against this header keeps working with a newer library. Returns 0, -1 on bad
97
+ * args / not built / OOM (the index itself stays usable). A later kci_sparse_build drops the structure; build it
98
+ * again. */
99
+ typedef struct {
100
+ unsigned struct_size; /* sizeof(KciSparseBlockParams) as the caller compiled it; 0 = up to global_cut */
101
+ int list_len; /* rows kept per dimension, largest weights first (default 3000) */
102
+ int block_size; /* target rows per group (default 6) */
103
+ float summary_mass; /* share of a summary's weight that is kept, 0 < x <= 1 (default 0.4; 1 = a true bound). */
104
+ int threads; /* <= 0 = cpu cores */
105
+ int cluster_terms;
106
+ int centre_terms; /* the same for the row a group is formed around: 0 = as cluster_terms, < 0 = all of its dimensions */
107
+ float head_mass; /* candidates are scored from the heaviest pairs of a row only, as many as carry this share of the sum of its
108
+ * |weights| (default 0.8); the best 2k by that score are then scored whole. Smaller = less memory read per query,
109
+ * slightly less exact. >= 1 = whole rows, which is also the default when summary_mass is 1 */
110
+ int global_cut; /* EXPERIMENTAL, leave 0. 1 = one weight level for all dimensions instead of list_len rows for
111
+ each, set so that the lists average list_len rows (common dimensions keep more). The build
112
+ then handles the long lists on one thread and can take very long on millions of rows
113
+ (2.68 million rows: not finished after 19 minutes); it may change or go away */
114
+ } KciSparseBlockParams;
115
+ int kci_sparse_build_blocks(KciSparse *s, const KciSparseBlockParams *params, double *out_secs);
116
+ int kci_sparse_has_blocks(const KciSparse *s);
117
+ /* Element counts of the parts: out[0] pairs in the rows, [1] pairs in the lists (0 once dropped), [2] groups,
118
+ * [3] rows in groups, [4] summary runs, [5] summary entries, [6] neighbour slots, [7] pairs in the half-size rows. */
119
+ void kci_sparse_sizes(const KciSparse *s, uint64_t out[8]);
120
+
121
+ /* Give back the memory of the per-dimension lists once the blocks are built (about as much as the rows
122
+ * themselves). Returns 0, -1 if there are no blocks. */
123
+ int kci_sparse_drop_lists(KciSparse *s);
124
+
125
+ /* Give back the full rows as well, for an index that is finished: built, blocks built (and the neighbour lists, if
126
+ * wanted), no rows waiting from kci_sparse_insert, dimension below 65536. The per-dimension lists go too. Keep the
127
+ * source data if that may be needed. Returns 0, or -1 when the index is not in the state above (nothing is freed
128
+ * then). */
129
+ int kci_sparse_drop_rows(KciSparse *s);
130
+ int kci_sparse_has_rows(const KciSparse *s); /* 0 after kci_sparse_drop_rows (also for a loaded index saved in that state) */
131
+
132
+ /* Neighbour lists for every row, the `knn` rows most similar to it, found with the block search itself
133
+ * (query_terms / heap_factor as below; <= 0 = 5 and 0.8). Needs kci_sparse_build_blocks. Costs one block search
134
+ * per row. Returns 0, -1 on bad args / no blocks / OOM. A later kci_sparse_build drops the lists. */
135
+ int kci_sparse_build_knn(KciSparse *s, int knn, int query_terms, float heap_factor, int threads, double *out_secs);
136
+ int kci_sparse_knn(const KciSparse *s); /* neighbours kept per row, 0 = not built */
137
+
138
+ /* Scores returned are exact inner products. Returns the count, -1 on bad args, -2 if kci_sparse_build_blocks has
139
+ * not been called. */
140
+ int kci_sparse_search_blocks(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
141
+ int k, int query_terms, float heap_factor, int knn,
142
+ uint64_t *out_ids, float *out_scores);
143
+
144
+ /* With head_mass < 1, how many rows kci_sparse_search_blocks scores whole at the end (the best ones by the score
145
+ * of their heavy part). 0 = the default, 2 * k. More = closer to scoring every candidate whole. */
146
+ void kci_sparse_searcher_set_pool(KciSparseSearcher *S, int rows);
147
+
148
+ /* Work done by the last kci_sparse_search_blocks on this searcher:
149
+ * out[0] = summaries looked at, out[1] = groups opened, out[2] = rows scored. */
150
+ void kci_sparse_searcher_work(const KciSparseSearcher *S, uint64_t out[3]);
151
+
152
+ uint32_t kci_sparse_count(const KciSparse *s); /* rows added and not removed */
153
+ uint32_t kci_sparse_dim(const KciSparse *s);
154
+ int kci_sparse_is_built(const KciSparse *s); /* 1 = built and no row added since */
155
+ int64_t kci_sparse_bytes(const KciSparse *s); /* memory held, in bytes */
156
+
157
+ /* Save the index to a file and read it back: the rows and whatever has been built from them (the lists, the
158
+ * groups, the neighbour lists), so nothing has to be built again after a load. Rows removed and rows inserted
159
+ * since the build are kept as they are.
160
+ * key == NULL (keylen 0): the file is written as is.
161
+ * key != NULL: the file is encrypted with AES-256-CTR and carries an AES-256-CMAC tag; the keys come from
162
+ * `key` (any bytes, keylen > 0) through PBKDF2-HMAC-SHA256 with a random salt, as for kci_vec_save.
163
+ * save writes <path>.tmp and renames it, so a failed save leaves the old file. Returns 0, or -1.
164
+ * load returns NULL when the file cannot be read, is not this kind of file, does not match its own header,
165
+ * was written with another key, fails the tag (damaged or altered), or holds an offset or row number that
166
+ * points outside its arrays. A file saved with a key opens only with that key; a file saved without one is
167
+ * refused when a key is given (the caller expected an encrypted file). Little-endian machines only. */
168
+ int kci_sparse_save(const KciSparse *s, const char *path, const uint8_t *key, int keylen);
169
+ KciSparse *kci_sparse_load(const char *path, const uint8_t *key, int keylen);
170
+
171
+ /* Merge several rankings into one by reciprocal rank fusion:
172
+ * score(id) = sum over lists of weight / (c + rank of id in that list), rank from 1.
173
+ * Only the order inside each list matters, so a dense (cosine) list and a
174
+ * sparse (inner product) list can be merged without scaling their scores.
175
+ * lists[i] holds lens[i] ids, best first; an id repeated inside one list counts
176
+ * once, at its best rank. weights == NULL means 1 for every list; c <= 0 means
177
+ * 60 (the usual value). Fills out_ids[0..ret) and (if non-NULL) out_scores[],
178
+ * best first; equal scores come smaller id first. Returns ret (<= k), or -1 on
179
+ * bad args / OOM.
180
+ *
181
+ * Typical hybrid search: take 3-5 times k from kci_vec_search_r and from
182
+ * kci_sparse_search, then merge the two lists down to k here. */
183
+ int kci_hybrid_rrf(const uint64_t *const *lists, const int *lens, const float *weights, int nlists,
184
+ float c, int k, uint64_t *out_ids, float *out_scores);
185
+
186
+ /* Merge several rankings into one by their scores score(id) = sum over lists of weight * s, s = that list's score
187
+ * of id stretched so that the list's first row is 1 and its last row is 0; 0 for a list that does not hold id.
188
+ * Unlike kci_hybrid_rrf this uses how far apart the scores are, not only the order: a row far ahead in one list
189
+ * stays ahead. The lists must be best first; the direction of the scores does not matter (cosine, inner product,
190
+ * or a distance where smaller is better), nor their unit. scores[i][j] belongs to lists[i][j]. An id repeated
191
+ * inside one list counts once, at its first place. weights == NULL means 1 for every list. Fills out_ids[0..ret)
192
+ * and (if non-NULL) out_scores[], best first; equal scores come smaller id first. Returns ret (<= k), or -1 on bad
193
+ * args (a score that is not finite included) / OOM. */
194
+ int kci_hybrid_mix(const uint64_t *const *lists, const float *const *scores, const int *lens, const float *weights,
195
+ int nlists, int k, uint64_t *out_ids, float *out_scores);
196
+
197
+ /* Encrypt / decrypt a block of bytes with a passphrase — for what lies beside an index, e.g. the texts the vectors
198
+ * were made from. Returns n + 40, or -1 (bad args, no random source). Two seals of the same bytes differ (the
199
+ * salt). kci_unseal: in[0..n) -> out[0..n - 40); `out` must hold n - 40 bytes. Returns n - 40, or -1 when the key
200
+ * is wrong, a byte was changed, the block is cut off or is not a sealed block; `out` is then untouched. The whole
201
+ * block is held in memory; in and out must not overlap. */
202
+ int64_t kci_seal(const uint8_t *in, uint64_t n, const uint8_t *key, int keylen, uint8_t *out);
203
+ int64_t kci_unseal(const uint8_t *in, uint64_t n, const uint8_t *key, int keylen, uint8_t *out);
204
+
205
+ #ifdef __cplusplus
206
+ }
207
+ #endif
208
+ #endif /* KCI_SPARSE_H */