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,1995 @@
1
+ /*
2
+ * kci_sparse.c — sparse-vector index (inner product) + rank fusion with a dense index.
3
+ * See kci_sparse.h for the API. No dependencies, does not include kci_vec (kci_crypt.h is shared with it).
4
+ */
5
+ #include "kci_sparse.h"
6
+ #include <stdlib.h>
7
+ #include <string.h>
8
+ #include <math.h>
9
+ #include <stdio.h>
10
+ #include <time.h>
11
+ #ifdef _WIN32
12
+ #include "kci_win_compat.h"
13
+ #else
14
+ #include <unistd.h>
15
+ #endif
16
+ #include <pthread.h>
17
+ #include "kci_crypt.h"
18
+ #if defined(__AVX2__) && !defined(KCI_SPARSE_NO_SIMD)
19
+ #include <immintrin.h>
20
+ #define SP_AVX2 1
21
+ #endif
22
+
23
+ typedef struct { uint32_t k; float v; } SpPair; /* (dimension, weight) in a row; (row, weight) in a list */
24
+ #define SP_HF_MAX 4.0f
25
+ #ifndef SP_PF_MAX
26
+ #define SP_PF_MAX 1024 /* bytes of a half-size row asked for ahead (a row of 227 pairs is 940) */
27
+ #endif
28
+ #define SP_CROW_PAD 32 /* entries after the last row, so that a 32-byte load at the end of a row stays inside */
29
+ typedef struct { uint32_t ep; float v; } SpSlot; /* per-row running score; valid when ep == the query's epoch */
30
+ typedef struct { float s; uint32_t d; } SpCand;
31
+
32
+ struct KciSparse {
33
+ uint32_t dim, n, ncap;
34
+ uint64_t *ids; /* [ncap] caller's id of each row */
35
+ uint8_t *dead; /* [ncap] 1 = removed by kci_sparse_delete, still in f / post until the next build */
36
+ uint32_t ndead;
37
+ uint32_t *map; /* id -> row + 1, open addressing, made by the first delete (NULL = not made) */
38
+ uint32_t mapcap; /* a power of two, >= 2 * n */
39
+ uint64_t *row; /* [ncap+1] offset of each row in f */
40
+ SpPair *f; /* rows, dimensions ascending inside a row */
41
+ uint64_t fnnz, fcap;
42
+ uint64_t *tptr; /* [dim+1] offset of each list in post (NULL until built) */
43
+ SpPair *post; /* lists, largest |weight| first */
44
+ int built;
45
+ uint32_t nbuilt; /* rows [0, nbuilt) are in the lists; rows [nbuilt, n) came by kci_sparse_insert since
46
+ the last build and are scored one by one in every search */
47
+ uint32_t gen; /* bumped by every build: a searcher from an older build is refused */
48
+ SpPair *tmp; int tmpcap;
49
+ /* blocks (kci_sparse_build_blocks); bptr == NULL = not built */
50
+ uint64_t *bptr; /* [dim+1] first group of each dimension */
51
+ uint64_t *bdoc; /* [nblk+1] offset of each group's rows in brow */
52
+ uint32_t *brow; /* rows of every group */
53
+ uint64_t *sdp; /* [dim+1] first run of list t (in sdim / slen) */
54
+ uint16_t *sdim16; uint32_t *sdim32; /* dimension of each run (16-bit when dim <= 65536), ascending inside a list */
55
+ uint8_t *slen; /* pairs in each run, 1..255 */
56
+ uint64_t *sck; /* [runs / 16 + 1] first pair of run 16 * i; made from slen, not saved */
57
+ uint64_t *sep; /* [dim+1] first pair of list t */
58
+ uint8_t *ent; /* the pairs: ent[2 * i] = step, ent[2 * i + 1] = byte */
59
+ float *bscale; /* [nblk] */
60
+ uint64_t nblk;
61
+ float head_mass; /* share of a row's weight in the first part of its half-size copy; 1 = all of it */
62
+ int norows; /* kci_sparse_drop_rows: f is gone, the half-size rows are the only copy */
63
+ uint32_t *boff;
64
+ uint32_t pf_bytes; /* bytes asked for ahead when a row's own count is not at hand (a neighbour): the average first part + a line */
65
+ uint8_t *bhl; /* beside boff: how many 64-byte lines the first part of that row touches (255 = or more) */
66
+ uint16_t *crow; uint64_t *coff; uint32_t ncrow; /* coff[ncrow + 1]; rows [0, ncrow) have a half-size copy */
67
+ uint32_t nknn_rows; /* rows that have a neighbour list (n when the lists were made) */
68
+ uint32_t *nbr; /* [nknn_rows * nknn] neighbour rows of each row, most similar first, UINT32_MAX = none */
69
+ int nknn;
70
+ };
71
+
72
+ struct KciSparseSearcher {
73
+ KciSparse *s;
74
+ uint32_t gen, ep, nslot;
75
+ SpSlot *slot; /* [n] */
76
+ uint32_t *touched; /* [n] rows met by this query */
77
+ uint64_t *vis; uint32_t nvis;
78
+ float *qd; /* [dim] the query spread out, zero outside a call */
79
+ uint16_t *q16; float *qv16; int q16cap; uint32_t m16; /* the query, dimensions ascending, for sp_crow_dot */
80
+ SpPair *q; uint64_t *cut; int qcap;
81
+ SpCand *heap; int hcap;
82
+ uint32_t *seed; int seedcap;
83
+ float *bacc; SpCand *bcand; uint32_t bcap; /* bounds of the groups of one list */
84
+ SpCand *pool; int pn, pcap, pall, pool_want;
85
+ KciSparseFilter filt; void *fctx;
86
+ uint64_t work[3];
87
+ };
88
+
89
+ static double sp_now(void){
90
+ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
91
+ return (double)ts.tv_sec + 1e-9 * (double)ts.tv_nsec;
92
+ }
93
+
94
+ static int sp_cmp_key(const void *a, const void *b){
95
+ uint32_t x = ((const SpPair*)a)->k, y = ((const SpPair*)b)->k;
96
+ return x < y ? -1 : x > y;
97
+ }
98
+ /* largest |weight| first; equal weights keep row order so a build is repeatable */
99
+ static int sp_cmp_post(const void *a, const void *b){
100
+ const SpPair *x = a, *y = b;
101
+ float fx = fabsf(x->v), fy = fabsf(y->v);
102
+ if (fx != fy) return fx > fy ? -1 : 1;
103
+ return x->k < y->k ? -1 : x->k > y->k;
104
+ }
105
+
106
+ /* Sort pairs by dimension, sum repeats, drop zeros. Returns the new length, -1 if a sum overflowed. */
107
+ static int sp_canon(SpPair *p, int n){
108
+ if (n > 1) qsort(p, (size_t)n, sizeof *p, sp_cmp_key);
109
+ int m = 0;
110
+ for (int i = 0; i < n; ){
111
+ uint32_t k = p[i].k; float v = 0;
112
+ for (; i < n && p[i].k == k; i++) v += p[i].v;
113
+ if (!isfinite(v)) return -1;
114
+ if (v != 0){ p[m].k = k; p[m].v = v; m++; }
115
+ }
116
+ return m;
117
+ }
118
+
119
+ /* Check and copy caller's pairs into *buf (grown as needed), canonical. Returns length or -1. */
120
+ static int sp_take(SpPair **buf, int *cap, uint32_t dim, const uint32_t *idx, const float *val, int nnz){
121
+ if (nnz < 0 || (nnz > 0 && (!idx || !val))) return -1;
122
+ for (int i = 0; i < nnz; i++) if (idx[i] >= dim || !isfinite(val[i])) return -1;
123
+ if (nnz > *cap){
124
+ int nc = nnz < 64 ? 64 : nnz;
125
+ SpPair *nb = realloc(*buf, (size_t)nc * sizeof **buf);
126
+ if (!nb) return -1;
127
+ *buf = nb; *cap = nc;
128
+ }
129
+ for (int i = 0; i < nnz; i++){ (*buf)[i].k = idx[i]; (*buf)[i].v = val[i]; }
130
+ return sp_canon(*buf, nnz);
131
+ }
132
+
133
+ KciSparse *kci_sparse_new(uint32_t dim){
134
+ if (dim == 0) return NULL;
135
+ KciSparse *s = calloc(1, sizeof *s);
136
+ if (!s) return NULL;
137
+ s->dim = dim; s->head_mass = 1.0f;
138
+ s->row = calloc(1, sizeof *s->row); /* row[0] = 0 */
139
+ if (!s->row){ free(s); return NULL; }
140
+ return s;
141
+ }
142
+
143
+ static void sp_blocks_free(KciSparse *s){
144
+ free(s->bptr); free(s->bdoc); free(s->brow); free(s->bscale);
145
+ free(s->sdp); free(s->sdim16); free(s->sdim32); free(s->slen); free(s->sck); free(s->sep); free(s->ent);
146
+ s->bptr = NULL; s->bdoc = NULL; s->brow = NULL; s->bscale = NULL;
147
+ s->sdp = NULL; s->sdim16 = NULL; s->sdim32 = NULL; s->slen = NULL; s->sck = NULL; s->sep = NULL; s->ent = NULL;
148
+ s->nblk = 0;
149
+ free(s->nbr); s->nbr = NULL; s->nknn = 0; s->nknn_rows = 0; /* made with the blocks, dropped with them */
150
+ free(s->crow); free(s->coff); free(s->boff); free(s->bhl); s->crow = NULL; s->coff = NULL; s->boff = NULL; s->bhl = NULL;
151
+ }
152
+
153
+ void kci_sparse_free(KciSparse *s){
154
+ if (!s) return;
155
+ sp_blocks_free(s);
156
+ free(s->dead); free(s->map);
157
+ free(s->ids); free(s->row); free(s->f); free(s->tptr); free(s->post); free(s->tmp);
158
+ free(s);
159
+ }
160
+
161
+ static inline uint32_t sp_hash(uint64_t x){
162
+ x ^= x >> 30; x *= 0xbf58476d1ce4e5b9ull; x ^= x >> 27; x *= 0x94d049bb133111ebull; x ^= x >> 31;
163
+ return (uint32_t)x;
164
+ }
165
+ static void sp_map_put(KciSparse *s, uint32_t row){
166
+ uint32_t mask = s->mapcap - 1, h = sp_hash(s->ids[row]) & mask;
167
+ while (s->map[h]) h = (h + 1) & mask;
168
+ s->map[h] = row + 1;
169
+ }
170
+ static int sp_map_make(KciSparse *s){
171
+ uint32_t cap = 1024;
172
+ while ((uint64_t)cap < (uint64_t)s->n * 2 && cap < 0x80000000u) cap <<= 1;
173
+ if ((uint64_t)cap < (uint64_t)s->n + 1) return -1; /* must keep one empty slot to stop a probe */
174
+ uint32_t *m = calloc(cap, sizeof *m);
175
+ if (!m) return -1;
176
+ free(s->map); s->map = m; s->mapcap = cap;
177
+ for (uint32_t d = 0; d < s->n; d++) sp_map_put(s, d);
178
+ return 0;
179
+ }
180
+
181
+ int kci_sparse_delete(KciSparse *s, uint64_t id){
182
+ if (!s) return -1;
183
+ if (s->n == 0) return 0;
184
+ if (!s->map && sp_map_make(s) != 0) return -1;
185
+ int removed = 0;
186
+ uint32_t mask = s->mapcap - 1;
187
+ for (uint32_t h = sp_hash(id) & mask; s->map[h]; h = (h + 1) & mask){
188
+ uint32_t d = s->map[h] - 1;
189
+ if (s->ids[d] == id && !s->dead[d]){ s->dead[d] = 1; s->ndead++; removed++; }
190
+ }
191
+ return removed;
192
+ }
193
+
194
+ /* Drop the removed rows from ids / row / f for good. Called by build. */
195
+ static void sp_compact(KciSparse *s){
196
+ uint32_t w = 0; uint64_t fw = 0;
197
+ for (uint32_t d = 0; d < s->n; d++){
198
+ if (s->dead[d]) continue;
199
+ uint64_t a = s->row[d], len = s->row[d + 1] - a;
200
+ if (fw != a && len) memmove(s->f + fw, s->f + a, (size_t)len * sizeof *s->f);
201
+ s->ids[w] = s->ids[d]; s->row[w] = fw; fw += len; w++;
202
+ }
203
+ s->row[w] = fw; s->n = w; s->fnnz = fw; s->ndead = 0;
204
+ if (w) memset(s->dead, 0, w);
205
+ free(s->map); s->map = NULL; s->mapcap = 0; /* row numbers changed */
206
+ }
207
+
208
+ static int64_t sp_append(KciSparse *s, uint64_t id, const uint32_t *idx, const float *val, int nnz, int keep_built){
209
+ if (s && s->norows) return -1; /* the rows were given back: nothing can be added or built */
210
+ if (!s || s->n == UINT32_MAX) return -1;
211
+ int m = sp_take(&s->tmp, &s->tmpcap, s->dim, idx, val, nnz);
212
+ if (m < 0) return -1;
213
+ if (s->n == s->ncap){
214
+ uint64_t nc = s->ncap ? (uint64_t)s->ncap * 2 : 1024;
215
+ if (nc > UINT32_MAX) nc = UINT32_MAX;
216
+ uint64_t *ni = realloc(s->ids, nc * sizeof *ni);
217
+ if (!ni) return -1;
218
+ s->ids = ni;
219
+ uint8_t *nd = realloc(s->dead, nc);
220
+ if (!nd) return -1;
221
+ s->dead = nd;
222
+ uint64_t *nr = realloc(s->row, (nc + 1) * sizeof *nr);
223
+ if (!nr) return -1;
224
+ s->row = nr; s->ncap = (uint32_t)nc;
225
+ }
226
+ if (s->fnnz + (uint64_t)m > s->fcap){
227
+ uint64_t nc = s->fcap ? s->fcap * 2 : 65536;
228
+ while (nc < s->fnnz + (uint64_t)m) nc *= 2;
229
+ SpPair *nf = realloc(s->f, nc * sizeof *nf);
230
+ if (!nf) return -1;
231
+ s->f = nf; s->fcap = nc;
232
+ }
233
+ if (m) memcpy(s->f + s->fnnz, s->tmp, (size_t)m * sizeof *s->f);
234
+ s->fnnz += (uint64_t)m;
235
+ s->ids[s->n] = id; s->dead[s->n] = 0;
236
+ s->row[++s->n] = s->fnnz;
237
+ if (s->map){
238
+ if ((uint64_t)s->n * 2 > s->mapcap){ free(s->map); s->map = NULL; s->mapcap = 0; } /* remade by the next delete */
239
+ else sp_map_put(s, s->n - 1);
240
+ }
241
+ if (!keep_built) s->built = 0;
242
+ return (int64_t)(s->n - s->ndead);
243
+ }
244
+
245
+ int64_t kci_sparse_add(KciSparse *s, uint64_t id, const uint32_t *idx, const float *val, int nnz){
246
+ return sp_append(s, id, idx, val, nnz, 0);
247
+ }
248
+
249
+ int64_t kci_sparse_insert(KciSparse *s, uint64_t id, const uint32_t *idx, const float *val, int nnz){
250
+ if (!s || !s->built) return -1;
251
+ return sp_append(s, id, idx, val, nnz, 1);
252
+ }
253
+ uint32_t kci_sparse_pending(const KciSparse *s){ return s && s->built ? s->n - s->nbuilt : 0; }
254
+
255
+ typedef struct { KciSparse *s; uint32_t next; } SpSortJob;
256
+ static void *sp_sort_worker(void *arg){
257
+ SpSortJob *j = arg; KciSparse *s = j->s;
258
+ for (;;){
259
+ uint32_t t0 = __sync_fetch_and_add(&j->next, 256u);
260
+ if (t0 >= s->dim) break;
261
+ uint32_t t1 = s->dim - t0 > 256u ? t0 + 256u : s->dim;
262
+ for (uint32_t t = t0; t < t1; t++){
263
+ uint64_t len = s->tptr[t + 1] - s->tptr[t];
264
+ if (len > 1) qsort(s->post + s->tptr[t], (size_t)len, sizeof *s->post, sp_cmp_post);
265
+ }
266
+ }
267
+ return NULL;
268
+ }
269
+
270
+ int kci_sparse_build(KciSparse *s, int threads, double *out_secs){
271
+ if (!s) return -1;
272
+ if (s->norows) return -1;
273
+ double t0 = sp_now();
274
+ if (threads <= 0){ long c = sysconf(_SC_NPROCESSORS_ONLN); threads = c > 0 ? (int)c : 1; }
275
+ if (threads > 64) threads = 64;
276
+ free(s->tptr); free(s->post); s->tptr = NULL; s->post = NULL; s->built = 0;
277
+ sp_blocks_free(s);
278
+ if (s->ndead) sp_compact(s);
279
+
280
+ if (s->fcap > s->fnnz && s->fnnz){
281
+ SpPair *nf = realloc(s->f, (size_t)s->fnnz * sizeof *nf);
282
+ if (nf){ s->f = nf; s->fcap = s->fnnz; }
283
+ }
284
+ uint64_t *tptr = calloc((size_t)s->dim + 1, sizeof *tptr);
285
+ uint64_t *cur = malloc((size_t)s->dim * sizeof *cur);
286
+ SpPair *post = malloc((size_t)(s->fnnz ? s->fnnz : 1) * sizeof *post);
287
+ if (!tptr || !cur || !post){ free(tptr); free(cur); free(post); return -1; }
288
+ for (uint64_t i = 0; i < s->fnnz; i++) tptr[s->f[i].k + 1]++;
289
+ for (uint32_t t = 0; t < s->dim; t++){ tptr[t + 1] += tptr[t]; cur[t] = tptr[t]; }
290
+ for (uint32_t d = 0; d < s->n; d++)
291
+ for (uint64_t i = s->row[d]; i < s->row[d + 1]; i++){
292
+ SpPair *p = &post[cur[s->f[i].k]++];
293
+ p->k = d; p->v = s->f[i].v;
294
+ }
295
+ free(cur);
296
+ s->tptr = tptr; s->post = post;
297
+
298
+ SpSortJob job = { s, 0 };
299
+ pthread_t th[64]; int started = 0;
300
+ for (int i = 1; i < threads; i++){
301
+ if (pthread_create(&th[started], NULL, sp_sort_worker, &job) != 0) break;
302
+ started++;
303
+ }
304
+ sp_sort_worker(&job);
305
+ for (int i = 0; i < started; i++) pthread_join(th[i], NULL);
306
+
307
+ s->gen++; s->built = 1; s->nbuilt = s->n;
308
+ if (out_secs) *out_secs = sp_now() - t0;
309
+ return 0;
310
+ }
311
+
312
+ KciSparseSearcher *kci_sparse_searcher_new(KciSparse *s){
313
+ if (!s || !s->built) return NULL;
314
+ KciSparseSearcher *S = calloc(1, sizeof *S);
315
+ if (!S) return NULL;
316
+ S->s = s; S->gen = s->gen;
317
+ size_t n = s->n ? s->n : 1;
318
+ S->nslot = (uint32_t)n;
319
+ S->slot = calloc(n, sizeof *S->slot);
320
+ S->touched = malloc(n * sizeof *S->touched);
321
+ S->vis = calloc(n / 64 + 1, sizeof *S->vis);
322
+ S->qd = calloc(s->dim, sizeof *S->qd);
323
+ if (!S->slot || !S->touched || !S->qd || !S->vis){ kci_sparse_searcher_free(S); return NULL; }
324
+ return S;
325
+ }
326
+
327
+ void kci_sparse_searcher_free(KciSparseSearcher *S){
328
+ if (!S) return;
329
+ free(S->slot); free(S->touched); free(S->vis); free(S->qd); free(S->q16); free(S->qv16); free(S->pool); free(S->q); free(S->cut); free(S->heap); free(S->seed); free(S->bacc); free(S->bcand);
330
+ free(S);
331
+ }
332
+
333
+ static inline int sp_before(SpCand a, SpCand b){ return a.s > b.s || (a.s == b.s && a.d < b.d); }
334
+ static int sp_cmp_cand(const void *a, const void *b){
335
+ SpCand x = *(const SpCand*)a, y = *(const SpCand*)b;
336
+ return sp_before(x, y) ? -1 : sp_before(y, x);
337
+ }
338
+ /* heap[0] is the candidate that ranks last among the kept ones */
339
+ static inline void sp_heap_down(SpCand *h, int n, int i){
340
+ for (;;){
341
+ int l = 2 * i + 1, r = l + 1, w = i;
342
+ if (l < n && sp_before(h[w], h[l])) w = l;
343
+ if (r < n && sp_before(h[w], h[r])) w = r;
344
+ if (w == i) return;
345
+ SpCand t = h[i]; h[i] = h[w]; h[w] = t; i = w;
346
+ }
347
+ }
348
+ /* the other way round: heap[0] is the candidate that ranks first */
349
+ static inline void sp_best_down(SpCand *h, uint32_t n, uint32_t i){
350
+ for (;;){
351
+ uint32_t l = 2 * i + 1, r = l + 1, w = i;
352
+ if (l < n && sp_before(h[l], h[w])) w = l;
353
+ if (r < n && sp_before(h[r], h[w])) w = r;
354
+ if (w == i) return;
355
+ SpCand t = h[i]; h[i] = h[w]; h[w] = t; i = w;
356
+ }
357
+ }
358
+ static inline void sp_heap_offer(SpCand *h, int *n, int cap, SpCand c){
359
+ if (*n < cap){
360
+ int i = (*n)++; h[i] = c;
361
+ while (i > 0){
362
+ int p = (i - 1) / 2;
363
+ if (!sp_before(h[p], h[i])) break;
364
+ SpCand t = h[i]; h[i] = h[p]; h[p] = t; i = p;
365
+ }
366
+ } else if (sp_before(c, h[0])){ h[0] = c; sp_heap_down(h, cap, 0); }
367
+ }
368
+
369
+ void kci_sparse_searcher_set_filter(KciSparseSearcher *S, KciSparseFilter fn, void *ctx){
370
+ if (!S) return;
371
+ S->filt = fn; S->fctx = fn ? ctx : NULL;
372
+ }
373
+
374
+ /* Offer a row that passed everything but the filter: the filter (a call into the caller's code) is asked
375
+ * only if the row would enter. */
376
+ static inline void sp_offer_filtered(const KciSparseSearcher *S, SpCand *h, int *hn, int cap, SpCand c){
377
+ if (S->filt){
378
+ if (*hn == cap && !sp_before(c, h[0])) return;
379
+ if (!S->filt(S->s->ids[c.d], S->fctx)) return;
380
+ }
381
+ sp_heap_offer(h, hn, cap, c);
382
+ }
383
+
384
+ /* The rows inserted since the last build: score each exactly (S->qd must hold the query) and offer it. */
385
+ static void sp_offer_pending(const KciSparseSearcher *S, SpCand *h, int *hn, int cap){
386
+ const KciSparse *s = S->s; const float *qd = S->qd;
387
+ for (uint32_t d = s->nbuilt; d < s->n; d++){
388
+ if (s->dead[d]) continue;
389
+ float sum = 0; int share = 0;
390
+ for (uint64_t y = s->row[d]; y < s->row[d + 1]; y++){
391
+ float qv = qd[s->f[y].k];
392
+ if (qv != 0){ sum += qv * s->f[y].v; share = 1; }
393
+ }
394
+ if (!share) continue; /* like the lists: only rows that share a dimension */
395
+ SpCand c = { sum, d };
396
+ sp_offer_filtered(S, h, hn, cap, c);
397
+ }
398
+ }
399
+
400
+ /* How many pairs at the front of a list (largest |weight| first) have |weight| >= x. */
401
+ static inline uint64_t sp_front(const SpPair *p, uint64_t len, float x){
402
+ uint64_t lo = 0, hi = len;
403
+ while (lo < hi){
404
+ uint64_t mid = lo + (hi - lo) / 2;
405
+ if (fabsf(p[mid].v) >= x) lo = mid + 1; else hi = mid;
406
+ }
407
+ return lo;
408
+ }
409
+
410
+ /* Choose how far to walk each list so that about `budget` pairs are read in total, and they are the
411
+ * pairs with the largest |weight_q * weight_row| over all the query's lists: find the level by
412
+ * bisection, each list answers "how many of mine are above it" by a binary search. Returns 1 if any
413
+ * list was cut short. */
414
+ static int sp_cuts(const KciSparse *s, const SpPair *q, uint64_t *cut, int m, uint32_t budget){
415
+ uint64_t total = 0; float top = 0;
416
+ for (int i = 0; i < m; i++){
417
+ uint64_t len = s->tptr[q[i].k + 1] - s->tptr[q[i].k];
418
+ cut[i] = len; total += len;
419
+ if (len){ float c = fabsf(q[i].v) * fabsf(s->post[s->tptr[q[i].k]].v); if (c > top) top = c; }
420
+ }
421
+ if (budget == 0 || total <= budget) return 0;
422
+ float lo = 0, hi = top; /* above(lo) > budget; hi is the answer so far */
423
+ for (int it = 0; it < 20; it++){
424
+ float mid = 0.5f * (lo + hi);
425
+ if (!(mid > lo && mid < hi)) break;
426
+ uint64_t above = 0;
427
+ for (int i = 0; i < m && above <= budget; i++)
428
+ above += sp_front(s->post + s->tptr[q[i].k], s->tptr[q[i].k + 1] - s->tptr[q[i].k], mid / fabsf(q[i].v));
429
+ if (above > budget) lo = mid; else hi = mid;
430
+ }
431
+ for (int i = 0; i < m; i++)
432
+ cut[i] = sp_front(s->post + s->tptr[q[i].k], s->tptr[q[i].k + 1] - s->tptr[q[i].k], hi / fabsf(q[i].v));
433
+ return 1;
434
+ }
435
+
436
+ int kci_sparse_search(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
437
+ int k, uint32_t budget, int rerank_n, uint64_t *out_ids, float *out_scores){
438
+ if (!S || k <= 0 || !out_ids) return -1;
439
+ KciSparse *s = S->s;
440
+ if (!s->built || S->gen != s->gen || !s->post) return -1;
441
+ int m = sp_take(&S->q, &S->qcap, s->dim, qidx, qval, qnnz);
442
+ if (m < 0) return -1;
443
+ if (m == 0 || s->n == 0) return 0;
444
+ uint64_t *nc = realloc(S->cut, (size_t)S->qcap * sizeof *nc);
445
+ if (!nc) return -1;
446
+ S->cut = nc;
447
+ const SpPair *q = S->q;
448
+
449
+ int partial = sp_cuts(s, q, S->cut, m, budget);
450
+ int want = partial ? (rerank_n > k ? rerank_n : k) : k;
451
+ if ((uint32_t)want > s->n) want = (int)s->n;
452
+ if (want > S->hcap){
453
+ SpCand *nh = realloc(S->heap, (size_t)want * sizeof *nh);
454
+ if (!nh) return -1;
455
+ S->heap = nh; S->hcap = want;
456
+ }
457
+
458
+ if (++S->ep == 0){ memset(S->slot, 0, (size_t)S->nslot * sizeof *S->slot); S->ep = 1; }
459
+ uint32_t ep = S->ep, nt = 0; SpSlot *slot = S->slot; uint32_t *touched = S->touched;
460
+ for (int i = 0; i < m; i++){
461
+ const SpPair *p = s->post + s->tptr[q[i].k]; float w = q[i].v; uint64_t c = S->cut[i];
462
+ for (uint64_t j = 0; j < c; j++){
463
+ SpSlot *a = &slot[p[j].k];
464
+ if (a->ep != ep){ a->ep = ep; a->v = w * p[j].v; touched[nt++] = p[j].k; }
465
+ else a->v += w * p[j].v;
466
+ }
467
+ }
468
+
469
+ SpCand *h = S->heap; int hn = 0;
470
+ const uint8_t *dead = s->ndead ? s->dead : NULL;
471
+ for (uint32_t i = 0; i < nt; i++){
472
+ if (dead && dead[touched[i]]) continue;
473
+ SpCand c = { slot[touched[i]].v, touched[i] };
474
+ sp_offer_filtered(S, h, &hn, want, c);
475
+ }
476
+ if (partial || s->n > s->nbuilt){
477
+ for (int i = 0; i < m; i++) S->qd[q[i].k] = q[i].v;
478
+ if (partial) /* the running score missed the tail of each list: score exactly */
479
+ for (int i = 0; i < hn; i++){
480
+ float sum = 0;
481
+ for (uint64_t j = s->row[h[i].d]; j < s->row[h[i].d + 1]; j++) sum += S->qd[s->f[j].k] * s->f[j].v;
482
+ h[i].s = sum;
483
+ }
484
+ if (s->n > s->nbuilt) sp_offer_pending(S, h, &hn, want);
485
+ for (int i = 0; i < m; i++) S->qd[q[i].k] = 0;
486
+ }
487
+ qsort(h, (size_t)hn, sizeof *h, sp_cmp_cand);
488
+ if (hn > k) hn = k;
489
+ for (int i = 0; i < hn; i++){ out_ids[i] = s->ids[h[i].d]; if (out_scores) out_scores[i] = h[i].s; }
490
+ return hn;
491
+ }
492
+
493
+ int kci_sparse_search_exact(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
494
+ int k, uint64_t *out_ids, float *out_scores){
495
+ return kci_sparse_search(S, qidx, qval, qnnz, k, 0, 0, out_ids, out_scores);
496
+ }
497
+
498
+ uint32_t kci_sparse_count(const KciSparse *s){ return s ? s->n - s->ndead : 0; }
499
+ uint32_t kci_sparse_dim(const KciSparse *s){ return s ? s->dim : 0; }
500
+ int kci_sparse_is_built(const KciSparse *s){ return s ? s->built : 0; }
501
+ int64_t kci_sparse_bytes(const KciSparse *s){
502
+ if (!s) return 0;
503
+ uint64_t b = sizeof *s + (uint64_t)s->ncap * (sizeof *s->ids + 1) + ((uint64_t)s->ncap + 1) * sizeof *s->row
504
+ + (uint64_t)s->mapcap * sizeof *s->map
505
+ + s->fcap * sizeof *s->f + (uint64_t)s->tmpcap * sizeof *s->tmp;
506
+ if (s->post) b += ((uint64_t)s->dim + 1) * sizeof *s->tptr + (s->fnnz ? s->fnnz : 1) * sizeof *s->post;
507
+ if (s->bptr) b += ((uint64_t)s->dim + 1) * (sizeof *s->bptr + sizeof *s->sdp + sizeof *s->sep) + (s->nblk + 1) * sizeof *s->bdoc
508
+ + s->bdoc[s->nblk] * sizeof *s->brow + s->nblk * sizeof *s->bscale
509
+ + s->sdp[s->dim] * ((s->sdim16 ? 2 : 4) + 1) + (s->sdp[s->dim] / 16 + 1) * sizeof *s->sck + s->sep[s->dim] * 2;
510
+ if (s->nbr) b += (uint64_t)s->nknn_rows * (uint64_t)s->nknn * sizeof *s->nbr;
511
+ if (s->crow) b += (s->coff[s->ncrow] + SP_CROW_PAD) * sizeof *s->crow + ((uint64_t)s->ncrow + 1) * sizeof *s->coff;
512
+ if (s->boff) b += s->bdoc[s->nblk] * (sizeof *s->boff + 1);
513
+ return (int64_t)b;
514
+ }
515
+
516
+ typedef struct {
517
+ uint32_t nblk; uint32_t *doff; uint32_t *rows; float *scale;
518
+ uint32_t *soff; /* per group, into the scratch summary; only during the build of the list */
519
+ uint32_t nd, nent; uint32_t *tdim; uint8_t *tlen, *ent; /* runs and pairs of this list, in the final layout */
520
+ } SpTermBlocks;
521
+ typedef struct { uint32_t c; float v; } SpCEnt; /* (centre, its weight) in the centres' list of one dimension */
522
+ typedef struct {
523
+ KciSparse *s; SpTermBlocks *tb; int list_len, block_size, cterms, centre_terms; float mass;
524
+ uint32_t next, end; int err; /* lists [next, end) are this round's */
525
+ float thr; /* > 0: a list is its pairs with |weight| >= thr (global_cut) */
526
+ } SpBlockJob;
527
+
528
+ /* The T-th largest |weight| of a row (0 if the row has no more than T pairs): its heaviest T dimensions
529
+ * are the ones with |weight| >= this. */
530
+ static float sp_row_cut(const KciSparse *s, uint32_t d, int T){
531
+ if (s->row[d + 1] - s->row[d] <= (uint64_t)T) return 0;
532
+ float top[64]; int nt = 0; /* largest first */
533
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
534
+ float a = fabsf(s->f[x].v);
535
+ if (nt < T){ int p = nt++; while (p > 0 && top[p - 1] < a){ top[p] = top[p - 1]; p--; } top[p] = a; }
536
+ else if (a > top[T - 1]){ int p = T - 1; while (p > 0 && top[p - 1] < a){ top[p] = top[p - 1]; p--; } top[p] = a; }
537
+ }
538
+ return top[T - 1];
539
+ }
540
+
541
+ /* How many pairs of list t go into the groups. */
542
+ static uint64_t sp_list_take(const KciSparse *s, uint32_t t, int list_len, int block_size, float thr){
543
+ uint64_t full = s->tptr[t + 1] - s->tptr[t];
544
+ if (!(thr > 0)) return full > (uint64_t)list_len ? (uint64_t)list_len : full;
545
+ uint64_t L = sp_front(s->post + s->tptr[t], full, thr), cap = (uint64_t)65535 * (uint64_t)block_size;
546
+ uint64_t least = full > (uint64_t)block_size ? (uint64_t)block_size : full; /* a rare dimension keeps one group */
547
+ if (L < least) L = least;
548
+ return L > cap ? cap : L;
549
+ }
550
+
551
+ typedef struct {
552
+ int32_t *head; uint32_t *cend; float *smax; uint32_t *tk; uint32_t ntk, tkcap; /* [dim] scratch, clean between uses */
553
+ SpCEnt *ce; size_t cecap; float *acc; uint32_t *assign, *cnt, *order, *mark, *tc; size_t lcap, bcap;
554
+ SpPair *sum; size_t sumcap; float *scale;
555
+ uint64_t *keys; size_t keycap;
556
+ } SpBlockScratch;
557
+
558
+ static int sp_cmp_u64(const void *a, const void *b){
559
+ uint64_t x = *(const uint64_t*)a, y = *(const uint64_t*)b;
560
+ return x < y ? -1 : x > y;
561
+ }
562
+
563
+ /* Write the runs and pairs of one list from its sorted keys (dimension << 24 | group << 8 | byte). With
564
+ * tdim == NULL only counts. */
565
+ static void sp_enc_runs(const uint64_t *keys, size_t nkeys, uint32_t *tdim, uint8_t *tlen, uint8_t *ent, uint32_t *out_nd, uint32_t *out_ne){
566
+ uint32_t nd = 0, ne = 0; size_t x = 0;
567
+ while (x < nkeys){
568
+ uint32_t k = (uint32_t)(keys[x] >> 24), g = 0, len = 0;
569
+ for (; x < nkeys && (uint32_t)(keys[x] >> 24) == k; x++){
570
+ uint32_t grp = (uint32_t)(keys[x] >> 8) & 0xffffu, q = (uint32_t)keys[x] & 0xffu;
571
+ for (;;){
572
+ if (len == 255){ if (tdim){ tdim[nd] = k; tlen[nd] = 255; } nd++; len = 0; g = 0; }
573
+ uint32_t step = grp - g;
574
+ if (step > 255){ if (ent){ ent[2 * (size_t)ne] = 255; ent[2 * (size_t)ne + 1] = 0; } ne++; len++; g += 255; continue; }
575
+ if (ent){ ent[2 * (size_t)ne] = (uint8_t)step; ent[2 * (size_t)ne + 1] = (uint8_t)q; }
576
+ ne++; len++; g = grp; break;
577
+ }
578
+ }
579
+ if (tdim){ tdim[nd] = k; tlen[nd] = (uint8_t)len; }
580
+ nd++;
581
+ }
582
+ *out_nd = nd; *out_ne = ne;
583
+ }
584
+
585
+ /* The offset of every 16th run, from the run lengths. */
586
+ static int sp_make_sck(KciSparse *s){
587
+ uint64_t nr = s->sdp[s->dim], e = 0;
588
+ free(s->sck);
589
+ s->sck = malloc((size_t)(nr / 16 + 1) * sizeof *s->sck);
590
+ if (!s->sck) return -1;
591
+ for (uint64_t r = 0; r < nr; r++){ if ((r & 15) == 0) s->sck[r >> 4] = e; e += s->slen[r]; }
592
+ if ((nr & 15) == 0) s->sck[nr >> 4] = e;
593
+ return 0;
594
+ }
595
+
596
+ static int sp_block_term(const SpBlockJob *j, SpBlockScratch *w, uint32_t t){
597
+ const KciSparse *s = j->s; SpTermBlocks *out = &j->tb[t];
598
+ uint32_t L = (uint32_t)sp_list_take(s, t, j->list_len, j->block_size, j->thr);
599
+ if (L == 0) return 0;
600
+ const SpPair *pl = s->post + s->tptr[t];
601
+ uint32_t nb = (L + (uint32_t)j->block_size - 1) / (uint32_t)j->block_size;
602
+ if (nb > 65535) nb = 65535; /* a group's number inside its list is kept in 16 bits */
603
+
604
+ if (L > w->lcap){
605
+ uint32_t *na = realloc(w->assign, (size_t)L * sizeof *na); if (!na) return -1; w->assign = na;
606
+ uint32_t *no = realloc(w->order, (size_t)L * sizeof *no); if (!no) return -1; w->order = no;
607
+ w->lcap = L;
608
+ }
609
+ if (nb + 1 > w->bcap){
610
+ float *na = realloc(w->acc, (size_t)(nb + 1) * sizeof *na); if (!na) return -1; w->acc = na;
611
+ uint32_t *nc = realloc(w->cnt, (size_t)(nb + 2) * sizeof *nc); if (!nc) return -1; w->cnt = nc;
612
+ float *ns = realloc(w->scale, (size_t)(nb + 1) * sizeof *ns); if (!ns) return -1; w->scale = ns;
613
+ uint32_t *nm = realloc(w->mark, (size_t)(nb + 1) * sizeof *nm); if (!nm) return -1; w->mark = nm;
614
+ uint32_t *nt = realloc(w->tc, (size_t)(nb + 1) * sizeof *nt); if (!nt) return -1; w->tc = nt;
615
+ w->bcap = nb + 1;
616
+ }
617
+
618
+ /* 1. assign every row to a centre */
619
+ if (nb == 1) for (uint32_t i = 0; i < L; i++) w->assign[i] = 0;
620
+ else {
621
+ size_t ne = 0;
622
+ for (uint32_t c = 0; c < nb; c++){
623
+ uint32_t d = pl[(uint64_t)c * L / nb].k;
624
+ float cthr = j->centre_terms < 0 ? 0 : sp_row_cut(s, d, j->centre_terms);
625
+ w->acc[c] = cthr; /* kept for the second pass; acc is not in use yet */
626
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
627
+ uint32_t k = s->f[x].k;
628
+ if (k == t || fabsf(s->f[x].v) < cthr) continue;
629
+ if (w->cend[k]++ == 0) w->tk[w->ntk++] = k;
630
+ ne++;
631
+ }
632
+ }
633
+ if (ne > 0x7fffffffu) return -1;
634
+ if (ne > w->cecap){
635
+ SpCEnt *n2 = realloc(w->ce, ne * sizeof *n2); if (!n2) return -1;
636
+ w->ce = n2; w->cecap = ne;
637
+ }
638
+ { uint32_t pos = 0;
639
+ for (uint32_t x = 0; x < w->ntk; x++){ uint32_t k = w->tk[x], n = w->cend[k]; w->head[k] = (int32_t)pos; w->cend[k] = pos; pos += n; } }
640
+ for (uint32_t c = 0; c < nb; c++){
641
+ uint32_t d = pl[(uint64_t)c * L / nb].k;
642
+ float cthr = w->acc[c];
643
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
644
+ uint32_t k = s->f[x].k;
645
+ if (k == t || fabsf(s->f[x].v) < cthr) continue;
646
+ SpCEnt *e = &w->ce[w->cend[k]++]; e->c = c; e->v = s->f[x].v;
647
+ }
648
+ }
649
+ memset(w->mark, 0, (size_t)nb * sizeof *w->mark);
650
+ for (uint32_t i = 0; i < L; i++){
651
+ uint32_t d = pl[i].k, ntc = 0;
652
+ float thr = sp_row_cut(s, d, j->cterms);
653
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
654
+ float v = s->f[x].v;
655
+ if (fabsf(v) < thr) continue;
656
+ uint32_t k = s->f[x].k;
657
+ if (w->head[k] < 0) continue;
658
+ for (const SpCEnt *e = w->ce + w->head[k], *ee = w->ce + w->cend[k]; e < ee; e++){
659
+ uint32_t c = e->c;
660
+ if (w->mark[c] != i + 1){ w->mark[c] = i + 1; w->acc[c] = 0; w->tc[ntc++] = c; }
661
+ w->acc[c] += v * e->v;
662
+ }
663
+ }
664
+ uint32_t pos = (uint32_t)((uint64_t)i * nb / L), best = pos; /* nothing shared: by position */
665
+ float bv = w->mark[pos] == i + 1 ? w->acc[pos] : 0;
666
+ if (bv < 0){ /* a centre it shares nothing with (sum 0) can win: all of them, in order */
667
+ for (uint32_t c = 0; c < nb; c++){ float a = w->mark[c] == i + 1 ? w->acc[c] : 0; if (a > bv){ bv = a; best = c; } }
668
+ } else {
669
+ float mx = bv; uint32_t cm = pos; /* the largest sum; among equals the lowest centre, as a scan in order gives */
670
+ for (uint32_t x = 0; x < ntc; x++){
671
+ uint32_t c = w->tc[x]; float a = w->acc[c];
672
+ if (a > mx || (a == mx && a > bv && c < cm)){ mx = a; cm = c; }
673
+ }
674
+ best = cm;
675
+ }
676
+ w->assign[i] = best;
677
+ }
678
+ for (uint32_t x = 0; x < w->ntk; x++){ w->head[w->tk[x]] = -1; w->cend[w->tk[x]] = 0; }
679
+ w->ntk = 0;
680
+ }
681
+
682
+ /* 2. group the rows by centre, dropping centres that got none */
683
+ memset(w->cnt, 0, (size_t)(nb + 2) * sizeof *w->cnt);
684
+ for (uint32_t i = 0; i < L; i++) w->cnt[w->assign[i] + 1]++;
685
+ uint32_t used = 0;
686
+ for (uint32_t c = 0; c < nb; c++) if (w->cnt[c + 1]) used++;
687
+ out->doff = malloc((size_t)(used + 1) * sizeof *out->doff);
688
+ out->soff = malloc((size_t)(used + 1) * sizeof *out->soff);
689
+ out->rows = malloc((size_t)L * sizeof *out->rows);
690
+ if (!out->doff || !out->soff || !out->rows) return -1;
691
+ for (uint32_t c = 0; c < nb; c++) w->cnt[c + 1] += w->cnt[c]; /* cnt[c] = start of centre c */
692
+ for (uint32_t i = 0; i < L; i++) w->order[i] = w->cnt[w->assign[i]]++; /* now cnt[c] = end of centre c */
693
+ for (uint32_t i = 0; i < L; i++) out->rows[w->order[i]] = pl[i].k;
694
+
695
+ /* 3. one summary per group */
696
+ size_t nsum = 0; uint32_t b = 0, start = 0;
697
+ for (uint32_t c = 0; c < nb; c++){
698
+ uint32_t end = w->cnt[c];
699
+ if (end == start) continue;
700
+ out->doff[b] = start; out->soff[b] = (uint32_t)nsum;
701
+ for (uint32_t i = start; i < end; i++){
702
+ uint32_t d = out->rows[i];
703
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
704
+ uint32_t k = s->f[x].k; float a = fabsf(s->f[x].v);
705
+ if (w->smax[k] == 0) w->tk[w->ntk++] = k;
706
+ if (a > w->smax[k]) w->smax[k] = a;
707
+ }
708
+ }
709
+ if (nsum + w->ntk > w->sumcap){
710
+ size_t ncap = (nsum + w->ntk) * 2;
711
+ SpPair *n2 = realloc(w->sum, ncap * sizeof *n2); if (!n2) return -1;
712
+ w->sum = n2; w->sumcap = ncap;
713
+ }
714
+ SpPair *sm = w->sum + nsum; double total = 0; float top = 0;
715
+ for (uint32_t x = 0; x < w->ntk; x++){
716
+ sm[x].k = w->tk[x]; sm[x].v = w->smax[w->tk[x]]; total += sm[x].v; w->smax[w->tk[x]] = 0;
717
+ if (sm[x].v > top) top = sm[x].v;
718
+ }
719
+ uint32_t n = w->ntk; w->ntk = 0;
720
+ if (j->mass < 1.0f && n > 1){
721
+ /* keep the heaviest part only. No sort (a group's summary has thousands of entries and there are
722
+ * about as many groups as rows / block_size): 256 equal steps of weight, add them up from the
723
+ * top until the share is reached, keep every entry in those steps. */
724
+ double step[256]; memset(step, 0, sizeof step);
725
+ float sc = 255.0f / top;
726
+ for (uint32_t x = 0; x < n; x++) step[(int)(sm[x].v * sc)] += sm[x].v;
727
+ double run = 0, want = total * (double)j->mass; int cutb = 255;
728
+ for (; cutb > 0; cutb--){ run += step[cutb]; if (run >= want) break; }
729
+ uint32_t keep = 0;
730
+ for (uint32_t x = 0; x < n; x++) if ((int)(sm[x].v * sc) >= cutb) sm[keep++] = sm[x];
731
+ n = keep;
732
+ }
733
+ nsum += n;
734
+ if (nsum > 0xffffffffu) return -1;
735
+ w->scale[b] = top / 255.0f;
736
+ start = end; b++;
737
+ }
738
+ out->doff[b] = L; out->soff[b] = (uint32_t)nsum; out->nblk = b;
739
+ out->scale = malloc((size_t)(b ? b : 1) * sizeof *out->scale);
740
+ if (!out->scale) return -1;
741
+ memcpy(out->scale, w->scale, (size_t)b * sizeof *out->scale);
742
+
743
+ /* 4. turn the summaries round: sort (dimension, group, byte) and cut into one run per dimension */
744
+ if (nsum > w->keycap){
745
+ uint64_t *nk = realloc(w->keys, nsum * 2 * sizeof *nk); if (!nk) return -1;
746
+ w->keys = nk; w->keycap = nsum * 2;
747
+ }
748
+ for (uint32_t g = 0; g < b; g++){
749
+ float inv = out->scale[g] > 0 ? 1.0f / out->scale[g] : 0;
750
+ for (uint32_t x = out->soff[g]; x < out->soff[g + 1]; x++){
751
+ int qv = (int)ceilf(w->sum[x].v * inv); /* up, so that byte * scale >= the weight */
752
+ while (qv < 255 && (float)qv * out->scale[g] < w->sum[x].v) qv++;
753
+ if (qv > 255) qv = 255;
754
+ if (qv < 1) qv = 1;
755
+ w->keys[x] = ((uint64_t)w->sum[x].k << 24) | ((uint64_t)g << 8) | (uint64_t)qv;
756
+ }
757
+ }
758
+ free(out->soff); out->soff = NULL;
759
+ if (nsum > 1) qsort(w->keys, nsum, sizeof *w->keys, sp_cmp_u64);
760
+ uint32_t nd = 0, ne = 0;
761
+ sp_enc_runs(w->keys, nsum, NULL, NULL, NULL, &nd, &ne);
762
+ out->tdim = malloc((size_t)(nd ? nd : 1) * sizeof *out->tdim);
763
+ out->tlen = malloc((size_t)(nd ? nd : 1));
764
+ out->ent = malloc((size_t)(ne ? ne : 1) * 2);
765
+ if (!out->tdim || !out->tlen || !out->ent) return -1;
766
+ sp_enc_runs(w->keys, nsum, out->tdim, out->tlen, out->ent, &nd, &ne);
767
+ out->nd = nd; out->nent = ne;
768
+ return 0;
769
+ }
770
+
771
+ static void *sp_block_worker(void *arg){
772
+ SpBlockJob *j = arg; uint32_t dim = j->s->dim;
773
+ SpBlockScratch w; memset(&w, 0, sizeof w);
774
+ w.head = malloc((size_t)dim * sizeof *w.head);
775
+ w.cend = calloc(dim, sizeof *w.cend);
776
+ w.smax = calloc(dim, sizeof *w.smax);
777
+ w.tk = malloc((size_t)dim * sizeof *w.tk);
778
+ int err = (!w.head || !w.cend || !w.smax || !w.tk);
779
+ if (!err) for (uint32_t k = 0; k < dim; k++) w.head[k] = -1;
780
+ while (!err && !j->err){
781
+ uint32_t t0 = __sync_fetch_and_add(&j->next, 4u);
782
+ if (t0 >= j->end) break;
783
+ uint32_t t1 = j->end - t0 > 4u ? t0 + 4u : j->end;
784
+ for (uint32_t t = t0; t < t1 && !err; t++) err = sp_block_term(j, &w, t) != 0;
785
+ }
786
+ if (err) __sync_fetch_and_or(&j->err, 1);
787
+ free(w.head); free(w.cend); free(w.smax); free(w.tk); free(w.ce); free(w.acc); free(w.assign); free(w.cnt); free(w.order); free(w.mark); free(w.tc); free(w.sum); free(w.scale); free(w.keys);
788
+ return NULL;
789
+ }
790
+
791
+ /* The half-size rows of every row there is now (dim <= 65536). Made with the groups, and again at load. */
792
+ static int sp_cmp_f32_desc(const void *a, const void *b){
793
+ float x = *(const float*)a, y = *(const float*)b;
794
+ return x > y ? -1 : x < y;
795
+ }
796
+ /* The smallest |weight| of the first part of a row: its heaviest pairs up to `mass` of the sum. 0 = all. */
797
+ static float sp_head_cut(const SpPair *fp, uint32_t len, float mass, float *tmp){
798
+ if (!(mass < 1.0f) || len < 2) return 0;
799
+ double tot = 0, run = 0;
800
+ for (uint32_t y = 0; y < len; y++){ tmp[y] = fabsf(fp[y].v); tot += tmp[y]; }
801
+ qsort(tmp, len, sizeof *tmp, sp_cmp_f32_desc);
802
+ double want = tot * (double)mass;
803
+ for (uint32_t i = 0; i < len; i++){ run += tmp[i]; if (run >= want) return tmp[i]; }
804
+ return 0;
805
+ }
806
+ typedef struct { KciSparse *s; float *cut; uint32_t next, maxlen; int pass, err; } SpCrowJob;
807
+ static void *sp_crow_worker(void *arg){
808
+ SpCrowJob *j = arg; KciSparse *s = j->s;
809
+ float *tmp = j->pass == 0 ? malloc((size_t)j->maxlen * sizeof *tmp) : NULL;
810
+ if (j->pass == 0 && !tmp){ __sync_fetch_and_or(&j->err, 1); return NULL; }
811
+ for (;;){
812
+ uint32_t d0 = __sync_fetch_and_add(&j->next, 2048u);
813
+ if (d0 >= s->n) break;
814
+ uint32_t d1 = s->n - d0 > 2048u ? d0 + 2048u : s->n;
815
+ for (uint32_t dd = d0; dd < d1; dd++){
816
+ uint32_t len = (uint32_t)(s->row[dd + 1] - s->row[dd]), nh = 0; const SpPair *fp = s->f + s->row[dd];
817
+ if (j->pass == 0){
818
+ float ct = sp_head_cut(fp, len, s->head_mass, tmp);
819
+ for (uint32_t y = 0; y < len; y++) if (fabsf(fp[y].v) >= ct) nh++;
820
+ uint64_t nd = ((uint64_t)nh + 15) / 16;
821
+ j->cut[dd] = ct; s->coff[dd] = 3 + nd + 16 * nd + nh + 2 * (uint64_t)(len - nh); /* its size; turned into offsets after */
822
+ continue;
823
+ }
824
+ float top = 0, ct = j->cut[dd];
825
+ for (uint32_t y = 0; y < len; y++){ float a = fabsf(fp[y].v); if (a > top) top = a; if (a >= ct) nh++; }
826
+ uint32_t nd = (nh + 15) / 16, nt = len - nh;
827
+ float sc = top / 32767.0f, inv = sc > 0 ? 1.0f / sc : 0;
828
+ uint16_t *h = s->crow + s->coff[dd], *dir = h + 3, *ck = dir + nd; int16_t *cv = (int16_t*)(ck + 16 * nd);
829
+ uint16_t *tk = (uint16_t*)(cv + nh); int16_t *tv = (int16_t*)(tk + nt);
830
+ h[0] = (uint16_t)nh; memcpy(h + 1, &sc, sizeof sc);
831
+ uint32_t ih = 0, it = 0;
832
+ for (uint32_t y = 0; y < len; y++){
833
+ float v = fp[y].v * inv; int iv = (int)(v < 0 ? v - 0.5f : v + 0.5f);
834
+ int16_t q = (int16_t)(iv > 32767 ? 32767 : iv < -32767 ? -32767 : iv);
835
+ if (fabsf(fp[y].v) >= ct){ ck[ih] = (uint16_t)fp[y].k; cv[ih] = q; ih++; }
836
+ else { tk[it] = (uint16_t)fp[y].k; tv[it] = q; it++; }
837
+ }
838
+ for (uint32_t y = nh; y < 16 * nd; y++) ck[y] = 0xFFFF;
839
+ for (uint32_t c = 0; c < nd; c++) dir[c] = ck[16 * c];
840
+ uint64_t used = 3 + (uint64_t)nd + 16 * (uint64_t)nd + nh + 2 * (uint64_t)nt;
841
+ if (s->coff[dd + 1] - s->coff[dd] > used) h[used] = 0; /* the entry between two rows, where there is one */
842
+ }
843
+ }
844
+ free(tmp);
845
+ return NULL;
846
+ }
847
+ static int sp_crow_run(SpCrowJob *j, int threads, int pass){
848
+ j->pass = pass; j->next = 0;
849
+ pthread_t th[64]; int started = 0;
850
+ for (int i = 1; i < threads; i++){
851
+ if (pthread_create(&th[started], NULL, sp_crow_worker, j) != 0) break;
852
+ started++;
853
+ }
854
+ sp_crow_worker(j);
855
+ for (int i = 0; i < started; i++) pthread_join(th[i], NULL);
856
+ return j->err ? -1 : 0;
857
+ }
858
+ static int sp_make_crow(KciSparse *s, int threads){
859
+ free(s->crow); free(s->coff); s->crow = NULL; s->ncrow = 0;
860
+ if (threads <= 0){ long c = sysconf(_SC_NPROCESSORS_ONLN); threads = c > 0 ? (int)c : 1; }
861
+ if (threads > 64) threads = 64;
862
+ SpCrowJob job; memset(&job, 0, sizeof job); job.s = s; job.maxlen = 1;
863
+ for (uint32_t dd = 0; dd < s->n; dd++){ uint64_t l = s->row[dd + 1] - s->row[dd]; if (l > job.maxlen) job.maxlen = (uint32_t)l; }
864
+ job.cut = malloc((size_t)(s->n ? s->n : 1) * sizeof *job.cut);
865
+ s->coff = malloc(((size_t)s->n + 1) * sizeof *s->coff);
866
+ if (!s->coff || !job.cut || sp_crow_run(&job, threads, 0) != 0){ free(job.cut); free(s->coff); s->coff = NULL; return -1; }
867
+ uint64_t tot = 0;
868
+ for (uint32_t dd = 0; dd < s->n; dd++){
869
+ uint64_t sz = s->coff[dd];
870
+ s->coff[dd] = tot; tot += sz;
871
+ tot += tot & 1; /* every row starts on an even entry (boff) */
872
+ }
873
+ s->coff[s->n] = tot;
874
+ s->crow = malloc(((size_t)tot + SP_CROW_PAD) * sizeof *s->crow);
875
+ if (!s->crow || sp_crow_run(&job, threads, 1) != 0){ free(job.cut); free(s->crow); free(s->coff); s->crow = NULL; s->coff = NULL; return -1; }
876
+ free(job.cut);
877
+ memset(s->crow + tot, 0, SP_CROW_PAD * sizeof *s->crow);
878
+ s->ncrow = s->n;
879
+ return 0;
880
+ }
881
+
882
+ /* boff from coff (see KciSparse.boff). Not having it is not an error. */
883
+ static void sp_make_boff(KciSparse *s){
884
+ free(s->boff); free(s->bhl); s->boff = NULL; s->bhl = NULL; s->pf_bytes = SP_PF_MAX;
885
+ if (!s->crow || !s->bptr) return;
886
+ { uint64_t sum = 0;
887
+ for (uint32_t d = 0; d < s->ncrow; d++){ uint64_t nh = s->crow[s->coff[d]], nd = (nh + 15) / 16; sum += (3 + nd + 16 * nd + nh) * 2; }
888
+ uint64_t avg = s->ncrow ? sum / s->ncrow : 0;
889
+ s->pf_bytes = (uint32_t)(avg + 64 > SP_PF_MAX ? SP_PF_MAX : avg + 64); }
890
+ if (s->coff[s->ncrow] / 2 > 0xffffffffu) return;
891
+ for (uint32_t d = 0; d < s->ncrow; d++) if (s->coff[d] & 1) return;
892
+ uint64_t nr = s->bdoc[s->nblk];
893
+ uint32_t *bo = malloc((size_t)(nr ? nr : 1) * sizeof *bo);
894
+ uint8_t *hl = malloc((size_t)(nr ? nr : 1));
895
+ if (!bo || !hl){ free(bo); free(hl); return; }
896
+ for (uint64_t i = 0; i < nr; i++){
897
+ if (s->brow[i] >= s->ncrow){ free(bo); free(hl); return; }
898
+ uint64_t o = s->coff[s->brow[i]]; bo[i] = (uint32_t)(o / 2);
899
+ /* the lines from the row's first byte to the last byte of its first part; the row sits anywhere in a line */
900
+ uint64_t nh = s->crow[o], nd = (nh + 15) / 16, bytes = (3 + nd + 16 * nd + nh) * 2;
901
+ uint64_t first = ((uintptr_t)(s->crow + o)) & 63, lines = (first + bytes + 63) / 64;
902
+ hl[i] = (uint8_t)(lines > 255 ? 255 : lines);
903
+ }
904
+ s->boff = bo; s->bhl = hl;
905
+ }
906
+
907
+ int kci_sparse_has_blocks(const KciSparse *s){ return s && s->bptr != NULL; }
908
+
909
+ void kci_sparse_sizes(const KciSparse *s, uint64_t out[8]){
910
+ memset(out, 0, 8 * sizeof *out);
911
+ if (!s) return;
912
+ out[0] = s->fnnz; out[1] = s->post ? s->fnnz : 0;
913
+ if (s->bptr){ out[2] = s->nblk; out[3] = s->bdoc[s->nblk]; out[4] = s->sdp[s->dim]; out[5] = s->sep[s->dim]; }
914
+ out[6] = s->nbr ? (uint64_t)s->nknn_rows * (uint64_t)s->nknn : 0; out[7] = s->crow ? s->fnnz : 0;
915
+ }
916
+
917
+ int kci_sparse_drop_rows(KciSparse *s){
918
+ if (!s || !s->built || !s->bptr || !s->crow || s->norows || s->n != s->nbuilt || s->ncrow != s->n) return -1;
919
+ free(s->post); s->post = NULL;
920
+ free(s->f); s->f = NULL; s->fcap = 0;
921
+ free(s->tmp); s->tmp = NULL; s->tmpcap = 0;
922
+ s->norows = 1;
923
+ return 0;
924
+ }
925
+ int kci_sparse_has_rows(const KciSparse *s){ return s && !s->norows; }
926
+
927
+ int kci_sparse_drop_lists(KciSparse *s){
928
+ if (!s || !s->built || !s->bptr) return -1;
929
+ free(s->post); s->post = NULL; /* tptr stays: it is small and says how long each list was */
930
+ return 0;
931
+ }
932
+
933
+ int kci_sparse_build_blocks(KciSparse *s, const KciSparseBlockParams *params, double *out_secs){
934
+ KciSparseBlockParams local, *p = NULL;
935
+ if (params){
936
+ size_t have = params->struct_size ? params->struct_size : sizeof local; /* when fields are added: 0 must keep meaning "up to global_cut" */
937
+ if (have < sizeof(unsigned) + sizeof(int)) return -1;
938
+ memset(&local, 0, sizeof local);
939
+ memcpy(&local, params, have < sizeof local ? have : sizeof local);
940
+ p = &local;
941
+ }
942
+ if (!s || !s->built || !s->post) return -1;
943
+ double t0 = sp_now();
944
+ int list_len = p && p->list_len > 0 ? p->list_len : 3000;
945
+ int block_size = p && p->block_size > 0 ? p->block_size : 6;
946
+ float mass = p && p->summary_mass != 0 ? p->summary_mass : 0.4f;
947
+ int threads = p ? p->threads : 0;
948
+ int cterms = p && p->cluster_terms > 0 ? p->cluster_terms : 16;
949
+ if (cterms > 64) cterms = 64;
950
+ int centre_terms = p && p->centre_terms != 0 ? p->centre_terms : cterms;
951
+ if (centre_terms > 64) centre_terms = 64;
952
+ if (!(mass > 0 && mass <= 1.0f) || (p && (p->list_len < 0 || p->block_size < 0 || p->cluster_terms < 0 || p->head_mass < 0))) return -1;
953
+ if (threads <= 0){ long c = sysconf(_SC_NPROCESSORS_ONLN); threads = c > 0 ? (int)c : 1; }
954
+ if (threads > 64) threads = 64;
955
+ sp_blocks_free(s);
956
+
957
+ SpBlockJob job; memset(&job, 0, sizeof job);
958
+ job.s = s; job.list_len = list_len; job.block_size = block_size; job.mass = mass; job.cterms = cterms; job.centre_terms = centre_terms;
959
+ job.tb = calloc(s->dim, sizeof *job.tb);
960
+ if (!job.tb) return -1;
961
+
962
+ if (p && p->global_cut){
963
+ uint64_t nonempty = 0; float hi = 0, lo = 0;
964
+ for (uint32_t t = 0; t < s->dim; t++)
965
+ if (s->tptr[t + 1] > s->tptr[t]){ nonempty++; float a = fabsf(s->post[s->tptr[t]].v); if (a > hi) hi = a; }
966
+ uint64_t want = nonempty * (uint64_t)list_len;
967
+ if (want >= s->tptr[s->dim] || !(hi > 0)) job.thr = 0; /* everything fits: plain lists */
968
+ else {
969
+ for (int it = 0; it < 40; it++){
970
+ float mid = lo + (hi - lo) * 0.5f; uint64_t c = 0;
971
+ for (uint32_t t = 0; t < s->dim; t++) c += sp_front(s->post + s->tptr[t], s->tptr[t + 1] - s->tptr[t], mid);
972
+ if (c > want) lo = mid; else hi = mid;
973
+ }
974
+ job.thr = hi;
975
+ }
976
+ }
977
+ uint64_t nrow = 0, bmax = 0;
978
+ for (uint32_t t = 0; t < s->dim; t++){
979
+ uint64_t Lt = sp_list_take(s, t, list_len, block_size, job.thr);
980
+ uint64_t nb = (Lt + (uint64_t)block_size - 1) / (uint64_t)block_size;
981
+ nrow += Lt; bmax += nb > 65535 ? 65535 : nb;
982
+ }
983
+ uint64_t ecap = nrow * 8 + 1024, dcap = nrow / 2 + 1024; /* first guesses, grown below */
984
+ int rc = 0;
985
+ s->bptr = malloc(((size_t)s->dim + 1) * sizeof *s->bptr);
986
+ s->sdp = malloc(((size_t)s->dim + 1) * sizeof *s->sdp);
987
+ s->sep = malloc(((size_t)s->dim + 1) * sizeof *s->sep);
988
+ s->bdoc = malloc((size_t)(bmax + 1) * sizeof *s->bdoc);
989
+ s->brow = malloc((size_t)(nrow ? nrow : 1) * sizeof *s->brow);
990
+ s->bscale = malloc((size_t)(bmax ? bmax : 1) * sizeof *s->bscale);
991
+ s->slen = malloc((size_t)dcap);
992
+ s->ent = malloc((size_t)ecap * 2);
993
+ if (s->dim <= 65536) s->sdim16 = malloc((size_t)dcap * sizeof *s->sdim16);
994
+ else s->sdim32 = malloc((size_t)dcap * sizeof *s->sdim32);
995
+ if (!s->bptr || !s->sdp || !s->sep || !s->bdoc || !s->brow || !s->bscale || !s->slen || !s->ent
996
+ || (!s->sdim16 && !s->sdim32)) rc = -1;
997
+
998
+ uint64_t b = 0, r = 0, e = 0, d = 0;
999
+ uint64_t target = nrow / 64 + 1; /* rows a round: at most about 65 rounds */
1000
+ for (uint32_t t0 = 0; t0 < s->dim && rc == 0; ){
1001
+ uint32_t t1 = t0; uint64_t acc = 0;
1002
+ while (t1 < s->dim && acc < target){ acc += sp_list_take(s, t1, list_len, block_size, job.thr); t1++; }
1003
+ job.next = t0; job.end = t1;
1004
+ pthread_t th[64]; int started = 0;
1005
+ for (int i = 1; i < threads; i++){
1006
+ if (pthread_create(&th[started], NULL, sp_block_worker, &job) != 0) break;
1007
+ started++;
1008
+ }
1009
+ sp_block_worker(&job);
1010
+ for (int i = 0; i < started; i++) pthread_join(th[i], NULL);
1011
+ if (job.err) rc = -1;
1012
+
1013
+ for (uint32_t t = t0; t < t1; t++){
1014
+ SpTermBlocks *tb = &job.tb[t];
1015
+ if (rc == 0){ s->bptr[t] = b; s->sdp[t] = d; s->sep[t] = e; }
1016
+ if (rc == 0 && tb->nblk){
1017
+ if (e + tb->nent > ecap){
1018
+ uint64_t nc = (e + tb->nent) + (e + tb->nent) / 2;
1019
+ uint8_t *n1 = realloc(s->ent, (size_t)nc * 2);
1020
+ if (!n1) rc = -1; else { s->ent = n1; ecap = nc; }
1021
+ }
1022
+ if (rc == 0 && d + tb->nd > dcap){
1023
+ uint64_t nc = (d + tb->nd) + (d + tb->nd) / 2;
1024
+ uint8_t *n1 = realloc(s->slen, (size_t)nc); if (n1) s->slen = n1;
1025
+ int ok = n1 != NULL;
1026
+ if (s->sdim16){ uint16_t *n2 = realloc(s->sdim16, (size_t)nc * sizeof *n2); if (n2) s->sdim16 = n2; else ok = 0; }
1027
+ else { uint32_t *n2 = realloc(s->sdim32, (size_t)nc * sizeof *n2); if (n2) s->sdim32 = n2; else ok = 0; }
1028
+ if (!ok) rc = -1; else dcap = nc;
1029
+ }
1030
+ }
1031
+ if (rc == 0 && tb->nblk){
1032
+ for (uint32_t i = 0; i < tb->nblk; i++){ s->bdoc[b] = r + tb->doff[i]; s->bscale[b] = tb->scale[i]; b++; }
1033
+ memcpy(s->brow + r, tb->rows, (size_t)tb->doff[tb->nblk] * sizeof *s->brow);
1034
+ r += tb->doff[tb->nblk];
1035
+ memcpy(s->ent + 2 * e, tb->ent, (size_t)tb->nent * 2);
1036
+ memcpy(s->slen + d, tb->tlen, tb->nd);
1037
+ if (s->sdim16) for (uint32_t x = 0; x < tb->nd; x++) s->sdim16[d + x] = (uint16_t)tb->tdim[x];
1038
+ else memcpy(s->sdim32 + d, tb->tdim, (size_t)tb->nd * sizeof *s->sdim32);
1039
+ e += tb->nent; d += tb->nd;
1040
+ }
1041
+ free(tb->doff); free(tb->rows); free(tb->soff); free(tb->scale); free(tb->tdim); free(tb->tlen); free(tb->ent);
1042
+ memset(tb, 0, sizeof *tb);
1043
+ }
1044
+ t0 = t1;
1045
+ }
1046
+ free(job.tb);
1047
+ if (rc == 0){
1048
+ s->bptr[s->dim] = b; s->sdp[s->dim] = d; s->sep[s->dim] = e; s->bdoc[b] = r; s->nblk = b;
1049
+ /* give the unused ends back; a failed shrink keeps the larger piece, which is still right */
1050
+ void *q;
1051
+ if ((q = realloc(s->bdoc, (size_t)(b + 1) * sizeof *s->bdoc)) != NULL) s->bdoc = q;
1052
+ if ((q = realloc(s->bscale, (size_t)(b ? b : 1) * sizeof *s->bscale)) != NULL) s->bscale = q;
1053
+ if ((q = realloc(s->ent, (size_t)(e ? e : 1) * 2)) != NULL) s->ent = q;
1054
+ if ((q = realloc(s->slen, (size_t)(d ? d : 1))) != NULL) s->slen = q;
1055
+ if (s->sdim16){ if ((q = realloc(s->sdim16, (size_t)(d ? d : 1) * sizeof *s->sdim16)) != NULL) s->sdim16 = q; }
1056
+ else { if ((q = realloc(s->sdim32, (size_t)(d ? d : 1) * sizeof *s->sdim32)) != NULL) s->sdim32 = q; }
1057
+ } else sp_blocks_free(s);
1058
+ s->head_mass = p && p->head_mass != 0 ? p->head_mass : mass >= 1.0f ? 1.0f : 0.8f;
1059
+ if (!(p && p->head_mass != 0) && s->head_mass < 1.0f)
1060
+ for (uint64_t y = 0; y < s->fnnz; y++) if (s->f[y].v < 0){ s->head_mass = 1.0f; break; }
1061
+ if (s->head_mass > 0 && s->head_mass < 1.0f){
1062
+ long hk = lrintf(s->head_mass * 200.0f);
1063
+ s->head_mass = hk < 1 ? 1.0f / 200.0f : hk >= 200 ? 1.0f : (float)hk / 200.0f;
1064
+ } else s->head_mass = 1.0f;
1065
+ if (rc == 0 && sp_make_sck(s) != 0){ sp_blocks_free(s); rc = -1; }
1066
+ if (rc == 0 && s->dim < 65536 && sp_make_crow(s, threads) != 0){ sp_blocks_free(s); rc = -1; }
1067
+ if (rc == 0) sp_make_boff(s);
1068
+ if (out_secs) *out_secs = sp_now() - t0;
1069
+ return rc;
1070
+ }
1071
+
1072
+ static int sp_cmp_u16(const void *a, const void *b){ return (int)*(const uint16_t*)a - (int)*(const uint16_t*)b; }
1073
+ static int sp_cmp_absw_desc(const void *a, const void *b){
1074
+ float x = fabsf(((const SpPair*)a)->v), y = fabsf(((const SpPair*)b)->v);
1075
+ if (x != y) return x > y ? -1 : 1;
1076
+ return ((const SpPair*)a)->k < ((const SpPair*)b)->k ? -1 : ((const SpPair*)a)->k > ((const SpPair*)b)->k;
1077
+ }
1078
+
1079
+ static inline float sp_crow_dot(const uint16_t *h, const uint16_t *q16, const float *qv, uint32_t m, const float *qd){
1080
+ uint32_t n = h[0], nd = (n + 15) >> 4; float sc; memcpy(&sc, h + 1, sizeof sc);
1081
+ const uint16_t *dir = h + 3, *a = dir + nd; const int16_t *w = (const int16_t*)(a + 16 * nd);
1082
+ #ifdef SP_AVX2
1083
+ if ((uint64_t)m * 6 > n){
1084
+ __m256 vacc = _mm256_setzero_ps(); uint32_t y = 0; float sum = 0;
1085
+ for (; y + 8 <= n; y += 8){
1086
+ __m256i vk = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*)(const void*)(a + y)));
1087
+ __m256i vw = _mm256_cvtepi16_epi32(_mm_loadu_si128((const __m128i*)(const void*)(w + y)));
1088
+ vacc = _mm256_add_ps(vacc, _mm256_mul_ps(_mm256_i32gather_ps(qd, vk, 4), _mm256_cvtepi32_ps(vw)));
1089
+ }
1090
+ __m128 hs = _mm_add_ps(_mm256_castps256_ps128(vacc), _mm256_extractf128_ps(vacc, 1));
1091
+ hs = _mm_add_ps(hs, _mm_movehl_ps(hs, hs)); hs = _mm_add_ss(hs, _mm_shuffle_ps(hs, hs, 1));
1092
+ sum = _mm_cvtss_f32(hs);
1093
+ for (; y < n; y++) sum += qd[a[y]] * (float)w[y];
1094
+ return sum * sc;
1095
+ }
1096
+ float acc[4] = { 0, 0, 0, 0 };
1097
+ if (nd <= 16){
1098
+ const __m256i iota = _mm256_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
1099
+ const __m256i valid = _mm256_cmpgt_epi16(_mm256_set1_epi16((short)nd), iota);
1100
+ const __m256i vd = _mm256_loadu_si256((const __m256i*)(const void*)dir); /* past nd: masked by `valid` */
1101
+ for (uint32_t i = 0; i < m; i++){
1102
+ __m256i vq = _mm256_set1_epi16((short)q16[i]);
1103
+ uint32_t le = (uint32_t)_mm256_movemask_epi8(_mm256_and_si256(_mm256_cmpeq_epi16(_mm256_max_epu16(vd, vq), vq), valid));
1104
+ uint32_t c = (uint32_t)__builtin_popcount(le) >> 1;
1105
+ c -= (c != 0);
1106
+ uint32_t mk = (uint32_t)_mm256_movemask_epi8(_mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i*)(const void*)(a + 16 * c)), vq));
1107
+ uint32_t pos = 16 * c + ((uint32_t)__builtin_ctz(mk | 0x80000000u) >> 1);
1108
+ int wi = (int)w[pos] & -(int)(mk != 0); /* no match: pos is still inside the row's piece, the weight is dropped */
1109
+ acc[i & 3] += qv[i] * (float)wi;
1110
+ }
1111
+ } else {
1112
+ const __m256i iota = _mm256_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
1113
+ for (uint32_t i = 0; i < m; i++){
1114
+ __m256i vq = _mm256_set1_epi16((short)q16[i]); uint32_t c = 0;
1115
+ for (uint32_t r = 0; r < nd; r += 16){
1116
+ uint32_t left = nd - r < 16 ? nd - r : 16;
1117
+ __m256i valid = _mm256_cmpgt_epi16(_mm256_set1_epi16((short)left), iota);
1118
+ __m256i vd = _mm256_loadu_si256((const __m256i*)(const void*)(dir + r));
1119
+ c += (uint32_t)__builtin_popcount((uint32_t)_mm256_movemask_epi8(_mm256_and_si256(_mm256_cmpeq_epi16(_mm256_max_epu16(vd, vq), vq), valid))) >> 1;
1120
+ }
1121
+ c -= (c != 0);
1122
+ uint32_t mk = (uint32_t)_mm256_movemask_epi8(_mm256_cmpeq_epi16(_mm256_loadu_si256((const __m256i*)(const void*)(a + 16 * c)), vq));
1123
+ uint32_t pos = 16 * c + ((uint32_t)__builtin_ctz(mk | 0x80000000u) >> 1);
1124
+ int wi = (int)w[pos] & -(int)(mk != 0);
1125
+ acc[i & 3] += qv[i] * (float)wi;
1126
+ }
1127
+ }
1128
+ return ((acc[0] + acc[1]) + (acc[2] + acc[3])) * sc;
1129
+ #else
1130
+ (void)q16; (void)qv; (void)m;
1131
+ float sum = 0;
1132
+ for (uint32_t y = 0; y < n; y++) sum += qd[a[y]] * (float)w[y];
1133
+ return sum * sc;
1134
+ #endif
1135
+ }
1136
+
1137
+ /* What the rest of a half-size row (its tail, see KciSparse.crow) adds to the score. ext = the row's extent in
1138
+ * entries. The tail is short and has no list of pieces: its pairs are gone through one by one. */
1139
+ static inline float sp_crow_tail(const uint16_t *h, uint64_t ext, const float *qd){
1140
+ uint32_t n = h[0], nd = (n + 15) >> 4; uint64_t used = 3 + (uint64_t)nd + 16 * (uint64_t)nd + n;
1141
+ if (ext <= used) return 0;
1142
+ uint32_t nt = (uint32_t)((ext - used) / 2); float sc; memcpy(&sc, h + 1, sizeof sc);
1143
+ const uint16_t *tk = h + used; const int16_t *tv = (const int16_t*)(tk + nt);
1144
+ float sum = 0; uint32_t y = 0;
1145
+ #ifdef SP_AVX2
1146
+ __m256 vacc = _mm256_setzero_ps();
1147
+ for (; y + 8 <= nt; y += 8){
1148
+ __m256i vk = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*)(const void*)(tk + y)));
1149
+ __m256i vw = _mm256_cvtepi16_epi32(_mm_loadu_si128((const __m128i*)(const void*)(tv + y)));
1150
+ vacc = _mm256_add_ps(vacc, _mm256_mul_ps(_mm256_i32gather_ps(qd, vk, 4), _mm256_cvtepi32_ps(vw)));
1151
+ }
1152
+ __m128 hs = _mm_add_ps(_mm256_castps256_ps128(vacc), _mm256_extractf128_ps(vacc, 1));
1153
+ hs = _mm_add_ps(hs, _mm_movehl_ps(hs, hs)); hs = _mm_add_ss(hs, _mm_shuffle_ps(hs, hs, 1));
1154
+ sum = _mm_cvtss_f32(hs);
1155
+ #endif
1156
+ for (; y < nt; y++) sum += qd[tk[y]] * (float)tv[y];
1157
+ return sum * sc;
1158
+ }
1159
+
1160
+ #ifndef SP_AHEAD
1161
+ #define SP_AHEAD 5 /* groups taken from the heap ahead of the one being scored (at least 1) */
1162
+ #endif
1163
+ #define SP_AHEAD_ON (SP_AHEAD >= 4)
1164
+ /* Ask for what scoring a list of rows will read, in two steps because the second needs what the first
1165
+ * fetched: (1) each row's "met already" slot and its offset, (2) the row itself, if not met yet. */
1166
+ #define SP_SEEN(vis, d) (((vis)[(d) >> 6] >> ((d) & 63)) & 1)
1167
+ /* offs: for the rows of a group, where each one's half-size row starts (KciSparse.boff), or NULL = look it up */
1168
+ static inline void sp_pf_meta(const KciSparseSearcher *S, const uint32_t *rows, const uint32_t *offs, uint32_t n){
1169
+ const KciSparse *s = S->s; const uint64_t *vis = S->vis;
1170
+ for (uint32_t x = 0; x < n; x++){
1171
+ uint32_t d = rows[x];
1172
+ if (d == UINT32_MAX) break;
1173
+ __builtin_prefetch(&vis[d >> 6]);
1174
+ if (!offs) __builtin_prefetch(s->coff ? (const void*)&s->coff[d] : (const void*)&s->row[d]);
1175
+ }
1176
+ }
1177
+ static inline void sp_pf_data(const KciSparseSearcher *S, const uint32_t *rows, const uint32_t *offs, const uint8_t *hl, uint32_t n){
1178
+ const KciSparse *s = S->s; const uint64_t *vis = S->vis;
1179
+ for (uint32_t x = 0; x < n; x++){
1180
+ uint32_t d = rows[x];
1181
+ if (d == UINT32_MAX) break;
1182
+ if (SP_SEEN(vis, d)) continue;
1183
+ if (s->crow){
1184
+ const uint16_t *h = offs ? s->crow + 2 * (uint64_t)offs[x] : s->crow + s->coff[d];
1185
+ const char *p = (const char*)h;
1186
+ __builtin_prefetch(p);
1187
+ if (offs){ uint32_t ln = hl[x] > 16 ? 16 : hl[x]; for (uint32_t o = 1; o < ln; o++) __builtin_prefetch(p + 64 * o); }
1188
+ else {
1189
+ size_t bytes = (size_t)(s->coff[d + 1] - s->coff[d]) * sizeof *s->crow;
1190
+ if (bytes > s->pf_bytes) bytes = s->pf_bytes;
1191
+ for (size_t o = 64; o < bytes; o += 64) __builtin_prefetch(p + o);
1192
+ }
1193
+ } else {
1194
+ const char *p = (const char*)(s->f + s->row[d]);
1195
+ __builtin_prefetch(p); __builtin_prefetch(p + 64); __builtin_prefetch(p + 128);
1196
+ }
1197
+ }
1198
+ }
1199
+
1200
+ static inline void sp_score_rows(KciSparseSearcher *S, const uint32_t *rows, const uint32_t *offs, const uint8_t *hl, uint32_t n, const uint8_t *dead,
1201
+ SpCand *h, int *hn, int want, uint64_t *w_rows, int ahead){
1202
+ const KciSparse *s = S->s; uint64_t *vis = S->vis; const float *qd = S->qd;
1203
+ for (uint32_t x = 0; x < n; x++) if (rows[x] == UINT32_MAX){ n = x; break; }
1204
+ if (!ahead){ sp_pf_meta(S, rows, offs, n); sp_pf_data(S, rows, offs, hl, n); }
1205
+ const uint16_t *crow = s->crow, *q16 = S->q16; const float *qv16 = S->qv16; uint32_t m16 = S->m16;
1206
+ for (uint32_t x = 0; x < n; x++){
1207
+ uint32_t d = rows[x];
1208
+ if (SP_SEEN(vis, d)) continue;
1209
+ vis[d >> 6] |= (uint64_t)1 << (d & 63); S->touched[S->nvis++] = d;
1210
+ if (dead && dead[d]) continue;
1211
+ float sum = 0;
1212
+ if (crow) sum = sp_crow_dot(offs ? crow + 2 * (uint64_t)offs[x] : crow + s->coff[d], q16, qv16, m16, qd);
1213
+ else
1214
+ for (uint64_t y = s->row[d]; y < s->row[d + 1]; y++) sum += qd[s->f[y].k] * s->f[y].v;
1215
+ (*w_rows)++;
1216
+ SpCand c = { sum, d };
1217
+ if (!S->pcap) sp_offer_filtered(S, h, hn, want, c);
1218
+ else { /* the heap gives the level to skip by, the pool the answer */
1219
+ if (S->filt){
1220
+ if (S->pn == S->pcap && !sp_before(c, S->pool[0])) continue; /* the pool holds the heap's rows and more */
1221
+ if (!S->filt(s->ids[d], S->fctx)) continue;
1222
+ }
1223
+ sp_heap_offer(h, hn, want, c);
1224
+ sp_heap_offer(S->pool, &S->pn, S->pcap, c);
1225
+ }
1226
+ }
1227
+ }
1228
+
1229
+ /* The block search on the query already in S->q[0..m) (canonical). Leaves the best rows in S->heap, best
1230
+ * first, and returns how many (<= k), or -1 on OOM. */
1231
+ static int sp_blocks_core(KciSparseSearcher *S, int m, int k, int query_terms, float heap_factor, int knn){
1232
+ KciSparse *s = S->s;
1233
+ S->work[0] = S->work[1] = S->work[2] = 0;
1234
+ if (m == 0 || s->n == 0) return 0;
1235
+ int want = (uint32_t)k > s->n ? (int)s->n : k;
1236
+ if (want > S->hcap){
1237
+ SpCand *nh = realloc(S->heap, (size_t)want * sizeof *nh);
1238
+ if (!nh) return -1;
1239
+ S->heap = nh; S->hcap = want;
1240
+ }
1241
+ S->pn = 0; S->pcap = 0;
1242
+ if (s->crow && s->head_mass < 1.0f){
1243
+ int pc = S->pool_want > 0 ? S->pool_want : want > 0x3fffffff ? want : 2 * want;
1244
+ if (pc < want) pc = want;
1245
+ if ((uint32_t)pc > s->n) pc = (int)s->n;
1246
+ if (pc > 0){
1247
+ if (pc > S->pall){ SpCand *np = realloc(S->pool, (size_t)pc * sizeof *np); if (!np) return -1; S->pool = np; S->pall = pc; }
1248
+ S->pcap = pc;
1249
+ }
1250
+ }
1251
+ SpPair *q = S->q;
1252
+ if (m > 1) qsort(q, (size_t)m, sizeof *q, sp_cmp_absw_desc);
1253
+ int nt = query_terms > 0 && query_terms < m ? query_terms : m;
1254
+ float *qd = S->qd;
1255
+ for (int i = 0; i < m; i++) qd[q[i].k] = q[i].v;
1256
+ uint32_t m16 = 0;
1257
+ if (s->crow){ /* the query once more, dimensions ascending */
1258
+ if (m > S->q16cap){
1259
+ uint16_t *n16 = realloc(S->q16, (size_t)m * sizeof *n16); if (n16) S->q16 = n16;
1260
+ float *nv = realloc(S->qv16, (size_t)m * sizeof *nv); if (nv) S->qv16 = nv;
1261
+ if (!n16 || !nv){ for (int i = 0; i < m; i++) qd[q[i].k] = 0; return -1; }
1262
+ S->q16cap = m;
1263
+ }
1264
+ for (int i = 0; i < m; i++) S->q16[i] = (uint16_t)q[i].k;
1265
+ if (m > 1) qsort(S->q16, (size_t)m, sizeof *S->q16, sp_cmp_u16);
1266
+ for (int i = 0; i < m; i++) S->qv16[i] = qd[S->q16[i]];
1267
+ m16 = (uint32_t)m;
1268
+ }
1269
+ S->m16 = m16;
1270
+
1271
+ S->nvis = 0; const uint32_t *boff = s->boff;
1272
+ const uint8_t *dead = s->ndead ? s->dead : NULL;
1273
+ SpCand *h = S->heap; int hn = 0, rc = 0;
1274
+ uint64_t w_sum = 0, w_open = 0, w_rows = 0;
1275
+ for (int i = 0; i < nt; i++){
1276
+ uint32_t t = q[i].k; uint64_t b0 = s->bptr[t]; uint32_t nb = (uint32_t)(s->bptr[t + 1] - b0), b = 0;
1277
+ /* until k rows are in hand there is nothing to compare a bound with */
1278
+ for (; b < nb && hn < want; b++){
1279
+ w_open++;
1280
+ sp_score_rows(S, s->brow + s->bdoc[b0 + b], boff ? boff + s->bdoc[b0 + b] : NULL, boff ? s->bhl + s->bdoc[b0 + b] : NULL, (uint32_t)(s->bdoc[b0 + b + 1] - s->bdoc[b0 + b]), dead, h, &hn, want, &w_rows, 0);
1281
+ }
1282
+ if (b == nb) continue;
1283
+ if (nb > S->bcap){
1284
+ float *na = realloc(S->bacc, (size_t)nb * sizeof *na);
1285
+ if (!na){ rc = -1; break; }
1286
+ S->bacc = na;
1287
+ SpCand *nc = realloc(S->bcand, (size_t)nb * sizeof *nc);
1288
+ if (!nc){ rc = -1; break; }
1289
+ S->bcand = nc; S->bcap = nb;
1290
+ }
1291
+ /* the bounds of every group of this list: only the runs of the query's own dimensions are read */
1292
+ float *acc = S->bacc; memset(acc, 0, (size_t)nb * sizeof *acc);
1293
+ uint64_t r0 = s->sdp[t], nd = s->sdp[t + 1] - r0;
1294
+ const uint16_t *sd16 = s->sdim16 ? s->sdim16 + r0 : NULL;
1295
+ const uint32_t *sd32 = s->sdim32 ? s->sdim32 + r0 : NULL;
1296
+ const uint8_t *slen = s->slen, *ent = s->ent; const uint64_t *sck = s->sck;
1297
+ for (int x = 0; x < m; x++){
1298
+ uint32_t key = q[x].k; uint64_t lo = 0, hi = nd;
1299
+ if (sd16){ while (lo < hi){ uint64_t mid = lo + (hi - lo) / 2; if (sd16[mid] < key) lo = mid + 1; else hi = mid; } }
1300
+ else { while (lo < hi){ uint64_t mid = lo + (hi - lo) / 2; if (sd32[mid] < key) lo = mid + 1; else hi = mid; } }
1301
+ float aq = fabsf(q[x].v);
1302
+ for (; lo < nd && (sd16 ? sd16[lo] : sd32[lo]) == key; lo++){ /* one run, or several when it has more than 255 pairs */
1303
+ uint64_t r = r0 + lo, e = sck[r >> 4];
1304
+ for (uint64_t y = r & ~(uint64_t)15; y < r; y++) e += slen[y];
1305
+ const uint8_t *p = ent + 2 * e; uint32_t len = slen[r], g = 0;
1306
+ for (uint32_t i = 0; i < len; i++){ g += p[2 * i]; acc[g] += aq * (float)p[2 * i + 1]; }
1307
+ }
1308
+ }
1309
+ w_sum += nb - b;
1310
+ /* the groups that can still enter, best bound first: the k-th best score only rises, so a group that
1311
+ * fails now fails later too, and once one fails in this order the rest do */
1312
+ SpCand *cand = S->bcand; uint32_t ncand = 0; float thr = h[0].s;
1313
+ for (uint32_t x = b; x < nb; x++){
1314
+ float est = acc[x] * s->bscale[b0 + x];
1315
+ if (!(est * heap_factor < thr)){ cand[ncand].s = est; cand[ncand].d = x; ncand++; }
1316
+ }
1317
+ for (uint32_t x = ncand / 2; x-- > 0; ) sp_best_down(cand, ncand, x);
1318
+ SpCand pipe[SP_AHEAD]; int np = 0;
1319
+ for (;;){
1320
+ while (np < SP_AHEAD && ncand){
1321
+ SpCand top = cand[0];
1322
+ if (top.s * heap_factor < h[0].s){ ncand = 0; break; }
1323
+ cand[0] = cand[--ncand]; sp_best_down(cand, ncand, 0);
1324
+ __builtin_prefetch(&s->bdoc[b0 + top.d]); __builtin_prefetch(&s->bdoc[b0 + top.d + 1]);
1325
+ pipe[np++] = top;
1326
+ }
1327
+ if (np == 0) break;
1328
+ if (np > 3){ uint64_t g = b0 + pipe[3].d; const char *r = (const char*)(s->brow + s->bdoc[g]);
1329
+ __builtin_prefetch(r); __builtin_prefetch(r + 64);
1330
+ if (boff){ r = (const char*)(boff + s->bdoc[g]); __builtin_prefetch(r); __builtin_prefetch(r + 64); __builtin_prefetch(s->bhl + s->bdoc[g]); } }
1331
+ if (np > 2){ uint64_t g = b0 + pipe[2].d; sp_pf_meta(S, s->brow + s->bdoc[g], boff ? boff + s->bdoc[g] : NULL, (uint32_t)(s->bdoc[g + 1] - s->bdoc[g])); }
1332
+ if (np > 1){ uint64_t g = b0 + pipe[1].d; sp_pf_data(S, s->brow + s->bdoc[g], boff ? boff + s->bdoc[g] : NULL, boff ? s->bhl + s->bdoc[g] : NULL, (uint32_t)(s->bdoc[g + 1] - s->bdoc[g])); }
1333
+ SpCand top = pipe[0];
1334
+ for (int x = 1; x < np; x++) pipe[x - 1] = pipe[x];
1335
+ np--;
1336
+ if (top.s * heap_factor < h[0].s){ np = 0; ncand = 0; break; } /* the ones behind it rank lower still */
1337
+ uint64_t g = b0 + top.d;
1338
+ w_open++;
1339
+ sp_score_rows(S, s->brow + s->bdoc[g], boff ? boff + s->bdoc[g] : NULL, boff ? s->bhl + s->bdoc[g] : NULL, (uint32_t)(s->bdoc[g + 1] - s->bdoc[g]), dead, h, &hn, want, &w_rows, SP_AHEAD_ON);
1340
+ }
1341
+ }
1342
+ if (rc == 0 && knn > 0 && s->nbr && hn > 0){
1343
+ if (knn > s->nknn) knn = s->nknn;
1344
+ if (hn > S->seedcap){
1345
+ uint32_t *ns = realloc(S->seed, (size_t)want * sizeof *ns);
1346
+ if (!ns) rc = -1;
1347
+ else { S->seed = ns; S->seedcap = want; }
1348
+ }
1349
+ if (rc == 0){
1350
+ int nseed = hn;
1351
+ for (int i = 0; i < nseed; i++){
1352
+ S->seed[i] = h[i].d;
1353
+ if (h[i].d < s->nknn_rows){ const char *r = (const char*)(s->nbr + (size_t)h[i].d * (size_t)s->nknn);
1354
+ __builtin_prefetch(r); __builtin_prefetch(r + 64); }
1355
+ }
1356
+ /* the same steps ahead as for the groups: seed i is scored, i + 1 has its rows asked for, i + 2 its slots */
1357
+ #define SP_NBR(i) (s->nbr + (size_t)S->seed[i] * (size_t)s->nknn)
1358
+ for (int i = 0; i < nseed; i++){
1359
+ if (i + 2 < nseed && S->seed[i + 2] < s->nknn_rows) sp_pf_meta(S, SP_NBR(i + 2), NULL, (uint32_t)knn);
1360
+ if (i + 1 < nseed && S->seed[i + 1] < s->nknn_rows) sp_pf_data(S, SP_NBR(i + 1), NULL, NULL, (uint32_t)knn);
1361
+ if (S->seed[i] < s->nknn_rows)
1362
+ sp_score_rows(S, SP_NBR(i), NULL, NULL, (uint32_t)knn, dead, h, &hn, want, &w_rows, SP_AHEAD_ON && i >= 2);
1363
+ }
1364
+ #undef SP_NBR
1365
+ }
1366
+ }
1367
+ if (rc == 0 && S->pcap && S->pn > 0){ /* the pool with its tails: the best `want` are the answer */
1368
+ SpCand *pl = S->pool; int pn = S->pn;
1369
+ for (int i = 0; i < pn; i++){ const char *p = (const char*)(s->crow + s->coff[pl[i].d]); __builtin_prefetch(p + 448); __builtin_prefetch(p + 512); }
1370
+ for (int i = 0; i < pn; i++){
1371
+ uint32_t d = pl[i].d;
1372
+ pl[i].s += sp_crow_tail(s->crow + s->coff[d], s->coff[d + 1] - s->coff[d], qd);
1373
+ }
1374
+ qsort(pl, (size_t)pn, sizeof *pl, sp_cmp_cand);
1375
+ hn = pn < want ? pn : want;
1376
+ memcpy(h, pl, (size_t)hn * sizeof *h);
1377
+ for (int i = hn / 2; i-- > 0; ) sp_heap_down(h, hn, i); /* a heap again, for the rows still to be offered */
1378
+ }
1379
+ if (rc == 0 && s->n > s->nbuilt) sp_offer_pending(S, h, &hn, want);
1380
+ if (rc == 0 && s->crow && !s->norows) /* the rows kept were scored from the half-size copy: once more, exactly */
1381
+ for (int i = 0; i < hn; i++){
1382
+ float sum = 0; uint32_t d = h[i].d;
1383
+ for (uint64_t y = s->row[d]; y < s->row[d + 1]; y++) sum += qd[s->f[y].k] * s->f[y].v;
1384
+ h[i].s = sum;
1385
+ }
1386
+ for (int i = 0; i < m; i++) qd[q[i].k] = 0;
1387
+ for (uint32_t i = 0; i < S->nvis; i++) S->vis[S->touched[i] >> 6] = 0; /* a whole word: all its set bits are this query's */
1388
+ S->nvis = 0;
1389
+ if (rc != 0) return -1;
1390
+ S->work[0] = w_sum; S->work[1] = w_open; S->work[2] = w_rows;
1391
+ qsort(h, (size_t)hn, sizeof *h, sp_cmp_cand);
1392
+ return hn;
1393
+ }
1394
+
1395
+ int kci_sparse_search_blocks(KciSparseSearcher *S, const uint32_t *qidx, const float *qval, int qnnz,
1396
+ int k, int query_terms, float heap_factor, int knn,
1397
+ uint64_t *out_ids, float *out_scores){
1398
+ if (!S || k <= 0 || knn < 0 || !out_ids || !(heap_factor > 0 && heap_factor <= SP_HF_MAX)) return -1;
1399
+ KciSparse *s = S->s;
1400
+ if (!s->built || S->gen != s->gen) return -1;
1401
+ if (!s->bptr) return -2;
1402
+ int m = sp_take(&S->q, &S->qcap, s->dim, qidx, qval, qnnz);
1403
+ if (m < 0) return -1;
1404
+ int hn = sp_blocks_core(S, m, k, query_terms, heap_factor, knn);
1405
+ if (hn < 0) return -1;
1406
+ const SpCand *h = S->heap;
1407
+ for (int i = 0; i < hn; i++){ out_ids[i] = s->ids[h[i].d]; if (out_scores) out_scores[i] = h[i].s; }
1408
+ return hn;
1409
+ }
1410
+
1411
+ /* ── neighbour lists ── */
1412
+ typedef struct { KciSparse *s; uint32_t *nbr; int knn, terms; float hf; uint32_t next; int err; } SpKnnJob;
1413
+
1414
+ static void *sp_knn_worker(void *arg){
1415
+ SpKnnJob *j = arg; KciSparse *s = j->s;
1416
+ KciSparseSearcher *S = kci_sparse_searcher_new(s);
1417
+ int err = !S;
1418
+ while (!err && !j->err){
1419
+ uint32_t d0 = __sync_fetch_and_add(&j->next, 256u);
1420
+ if (d0 >= s->n) break;
1421
+ uint32_t d1 = s->n - d0 > 256u ? d0 + 256u : s->n;
1422
+ for (uint32_t d = d0; d < d1; d++){
1423
+ uint32_t *out = j->nbr + (size_t)d * (size_t)j->knn;
1424
+ for (int x = 0; x < j->knn; x++) out[x] = UINT32_MAX;
1425
+ int m = (int)(s->row[d + 1] - s->row[d]);
1426
+ if (m == 0 || s->dead[d]) continue;
1427
+ if (m > S->qcap){
1428
+ SpPair *nq = realloc(S->q, (size_t)m * sizeof *nq);
1429
+ if (!nq){ err = 1; break; }
1430
+ S->q = nq; S->qcap = m;
1431
+ }
1432
+ memcpy(S->q, s->f + s->row[d], (size_t)m * sizeof *S->q); /* a stored row is already canonical */
1433
+ int hn = sp_blocks_core(S, m, j->knn + 1, j->terms, j->hf, 0);
1434
+ if (hn < 0){ err = 1; break; }
1435
+ int w = 0;
1436
+ for (int i = 0; i < hn && w < j->knn; i++)
1437
+ if (S->heap[i].d != d && S->heap[i].d < s->nbuilt) out[w++] = S->heap[i].d;
1438
+ }
1439
+ }
1440
+ if (err) __sync_fetch_and_or(&j->err, 1);
1441
+ kci_sparse_searcher_free(S);
1442
+ return NULL;
1443
+ }
1444
+
1445
+ int kci_sparse_knn(const KciSparse *s){ return s && s->nbr ? s->nknn : 0; }
1446
+
1447
+ int kci_sparse_build_knn(KciSparse *s, int knn, int query_terms, float heap_factor, int threads, double *out_secs){
1448
+ if (!s || !s->built || !s->bptr || s->norows || knn <= 0 || knn > 1024) return -1;
1449
+ if (query_terms <= 0) query_terms = 5;
1450
+ if (heap_factor <= 0) heap_factor = 0.8f; /* and the search using the lists 0.9375 -> 0.9340 at the same speed */
1451
+ if (!(heap_factor <= SP_HF_MAX)) return -1;
1452
+ double t0 = sp_now();
1453
+ if (threads <= 0){ long c = sysconf(_SC_NPROCESSORS_ONLN); threads = c > 0 ? (int)c : 1; }
1454
+ if (threads > 64) threads = 64;
1455
+ free(s->nbr); s->nbr = NULL; s->nknn = 0; s->nknn_rows = 0;
1456
+ SpKnnJob job; memset(&job, 0, sizeof job);
1457
+ job.s = s; job.knn = knn; job.terms = query_terms; job.hf = heap_factor;
1458
+ job.nbr = malloc((size_t)(s->n ? s->n : 1) * (size_t)knn * sizeof *job.nbr);
1459
+ if (!job.nbr) return -1;
1460
+ pthread_t th[64]; int started = 0;
1461
+ for (int i = 1; i < threads; i++){
1462
+ if (pthread_create(&th[started], NULL, sp_knn_worker, &job) != 0) break;
1463
+ started++;
1464
+ }
1465
+ sp_knn_worker(&job);
1466
+ for (int i = 0; i < started; i++) pthread_join(th[i], NULL);
1467
+ if (job.err){ free(job.nbr); return -1; }
1468
+ s->nbr = job.nbr; s->nknn = knn; s->nknn_rows = s->n;
1469
+ if (out_secs) *out_secs = sp_now() - t0;
1470
+ return 0;
1471
+ }
1472
+
1473
+ void kci_sparse_searcher_set_pool(KciSparseSearcher *S, int rows){ if (S) S->pool_want = rows > 0 ? rows : 0; }
1474
+
1475
+ void kci_sparse_searcher_work(const KciSparseSearcher *S, uint64_t out[3]){
1476
+ if (!out) return;
1477
+ out[0] = S ? S->work[0] : 0; out[1] = S ? S->work[1] : 0; out[2] = S ? S->work[2] : 0;
1478
+ }
1479
+
1480
+ /* ── rank fusion ── */
1481
+ typedef struct { uint64_t id; int list, rank; } SpRank;
1482
+ typedef struct { uint64_t id; float s; } SpFused;
1483
+ static int sp_cmp_rank(const void *a, const void *b){
1484
+ const SpRank *x = a, *y = b;
1485
+ if (x->id != y->id) return x->id < y->id ? -1 : 1;
1486
+ if (x->list != y->list) return x->list < y->list ? -1 : 1;
1487
+ return x->rank < y->rank ? -1 : x->rank > y->rank;
1488
+ }
1489
+ static int sp_cmp_fused(const void *a, const void *b){
1490
+ const SpFused *x = a, *y = b;
1491
+ if (x->s != y->s) return x->s > y->s ? -1 : 1;
1492
+ return x->id < y->id ? -1 : x->id > y->id;
1493
+ }
1494
+
1495
+ int kci_hybrid_rrf(const uint64_t *const *lists, const int *lens, const float *weights, int nlists,
1496
+ float c, int k, uint64_t *out_ids, float *out_scores){
1497
+ if (!lists || !lens || nlists <= 0 || k <= 0 || !out_ids || !isfinite(c)) return -1;
1498
+ if (c <= 0) c = 60.0f;
1499
+ size_t total = 0;
1500
+ for (int i = 0; i < nlists; i++){
1501
+ if (lens[i] < 0 || (lens[i] > 0 && !lists[i])) return -1;
1502
+ if (weights && !isfinite(weights[i])) return -1;
1503
+ total += (size_t)lens[i];
1504
+ }
1505
+ if (total == 0) return 0;
1506
+ SpRank *r = malloc(total * sizeof *r);
1507
+ SpFused *f = malloc(total * sizeof *f);
1508
+ if (!r || !f){ free(r); free(f); return -1; }
1509
+ size_t n = 0;
1510
+ for (int i = 0; i < nlists; i++)
1511
+ for (int j = 0; j < lens[i]; j++){ r[n].id = lists[i][j]; r[n].list = i; r[n].rank = j + 1; n++; }
1512
+ qsort(r, n, sizeof *r, sp_cmp_rank);
1513
+ size_t nf = 0;
1514
+ for (size_t i = 0; i < n; i++){
1515
+ if (i > 0 && r[i].id == r[i-1].id && r[i].list == r[i-1].list) continue; /* repeat inside one list */
1516
+ float add = (weights ? weights[r[i].list] : 1.0f) / (c + (float)r[i].rank);
1517
+ if (nf > 0 && f[nf-1].id == r[i].id) f[nf-1].s += add;
1518
+ else { f[nf].id = r[i].id; f[nf].s = add; nf++; }
1519
+ }
1520
+ qsort(f, nf, sizeof *f, sp_cmp_fused);
1521
+ int ret = nf < (size_t)k ? (int)nf : k;
1522
+ for (int i = 0; i < ret; i++){ out_ids[i] = f[i].id; if (out_scores) out_scores[i] = f[i].s; }
1523
+ free(r); free(f);
1524
+ return ret;
1525
+ }
1526
+
1527
+ typedef struct { uint64_t id; int list, rank; float v; } SpMix;
1528
+ static int sp_cmp_mix(const void *a, const void *b){
1529
+ const SpMix *x = a, *y = b;
1530
+ if (x->id != y->id) return x->id < y->id ? -1 : 1;
1531
+ if (x->list != y->list) return x->list < y->list ? -1 : 1;
1532
+ return x->rank < y->rank ? -1 : x->rank > y->rank;
1533
+ }
1534
+ int kci_hybrid_mix(const uint64_t *const *lists, const float *const *scores, const int *lens, const float *weights,
1535
+ int nlists, int k, uint64_t *out_ids, float *out_scores){
1536
+ if (!lists || !scores || !lens || nlists <= 0 || k <= 0 || !out_ids) return -1;
1537
+ size_t total = 0;
1538
+ for (int i = 0; i < nlists; i++){
1539
+ if (lens[i] < 0 || (lens[i] > 0 && (!lists[i] || !scores[i]))) return -1;
1540
+ if (weights && !isfinite(weights[i])) return -1;
1541
+ for (int j = 0; j < lens[i]; j++) if (!isfinite(scores[i][j])) return -1;
1542
+ total += (size_t)lens[i];
1543
+ }
1544
+ if (total == 0) return 0;
1545
+ SpMix *r = malloc(total * sizeof *r);
1546
+ SpFused *f = malloc(total * sizeof *f);
1547
+ if (!r || !f){ free(r); free(f); return -1; }
1548
+ size_t n = 0;
1549
+ for (int i = 0; i < nlists; i++){
1550
+ if (lens[i] == 0) continue;
1551
+ float hi = scores[i][0], lo = scores[i][lens[i] - 1], span = hi - lo; /* best first: works for "smaller is better" too */
1552
+ for (int j = 0; j < lens[i]; j++){
1553
+ float v = span != 0 ? (scores[i][j] - lo) / span : 1.0f;
1554
+ r[n].id = lists[i][j]; r[n].list = i; r[n].rank = j; r[n].v = v < 0 ? 0 : v > 1 ? 1 : v; n++;
1555
+ }
1556
+ }
1557
+ qsort(r, n, sizeof *r, sp_cmp_mix);
1558
+ size_t nf = 0;
1559
+ for (size_t i = 0; i < n; i++){
1560
+ if (i > 0 && r[i].id == r[i-1].id && r[i].list == r[i-1].list) continue; /* repeat inside one list */
1561
+ float add = (weights ? weights[r[i].list] : 1.0f) * r[i].v;
1562
+ if (nf > 0 && f[nf-1].id == r[i].id) f[nf-1].s += add;
1563
+ else { f[nf].id = r[i].id; f[nf].s = add; nf++; }
1564
+ }
1565
+ qsort(f, nf, sizeof *f, sp_cmp_fused);
1566
+ int ret = nf < (size_t)k ? (int)nf : k;
1567
+ for (int i = 0; i < ret; i++){ out_ids[i] = f[i].id; if (out_scores) out_scores[i] = f[i].s; }
1568
+ free(r); free(f);
1569
+ return ret;
1570
+ }
1571
+
1572
+ #define SP_MAGIC "KCISPAR1"
1573
+ #define SP_KEYCHK "KCISPARSE-KEYCHK"
1574
+ #define SP_LABEL_ENC "KCISPAR1 encryption key"
1575
+ #define SP_LABEL_MAC "KCISPAR1 mac key"
1576
+ #define SP_KC_NONCE 0xFFFFFFFEull /* the key check's CTR nonce; the pieces count up from 0 */
1577
+ #define SP_PIECE (64u * 1024 * 1024)
1578
+ #define SP_F_ENC 1u
1579
+ #define SP_F_BUILT 2u
1580
+ #define SP_F_LISTS 4u
1581
+ #define SP_F_BLOCKS 8u
1582
+ #define SP_F_KNN 16u
1583
+ #define SP_F_NOROWS 32u
1584
+ #define SP_F_SUM2 64u
1585
+ #define SP_F_ALL 127u
1586
+ #define SP_F_HEAD(f) (((f) >> 8) & 0xffu)
1587
+ #ifdef _WIN32
1588
+ #define sp_fseek _fseeki64
1589
+ #define sp_ftell _ftelli64
1590
+ static int sp_replace_file(const char *from, const char *to){
1591
+ return MoveFileExA(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) ? 0 : -1;
1592
+ }
1593
+ #else
1594
+ #define sp_fseek fseeko
1595
+ #define sp_ftell ftello
1596
+ static int sp_replace_file(const char *from, const char *to){ return rename(from, to); }
1597
+ #endif
1598
+
1599
+ typedef struct { FILE *f; int enc; KvAes aes; KvCmac mac; uint64_t piece; uint8_t *tmp; } SpIO;
1600
+
1601
+ static int sp_io_keys(SpIO *io, const uint8_t *key, int keylen, const uint8_t salt[16]){
1602
+ uint8_t mk[32], ek[32], ak[32];
1603
+ kdf_derive(key, keylen, salt, 16, mk);
1604
+ kv_subkey(mk, SP_LABEL_ENC, ek); kv_subkey(mk, SP_LABEL_MAC, ak);
1605
+ kv_aes_init(&io->aes, ek); kv_cmac_init(&io->mac, ak); io->enc = 1;
1606
+ memset(mk, 0, 32); memset(ek, 0, 32); memset(ak, 0, 32);
1607
+ io->tmp = malloc(SP_PIECE);
1608
+ return io->tmp ? 0 : -1;
1609
+ }
1610
+ static int sp_wraw(SpIO *io, const void *p, size_t n){ /* written as is; part of the tag */
1611
+ if (io->enc) kv_cmac_update(&io->mac, p, n);
1612
+ return fwrite(p, 1, n, io->f) == n ? 0 : -1;
1613
+ }
1614
+ static int sp_wr(SpIO *io, const void *p, uint64_t n){
1615
+ const uint8_t *b = p;
1616
+ while (n){
1617
+ size_t c = n < SP_PIECE ? (size_t)n : SP_PIECE;
1618
+ if (!io->enc){ if (fwrite(b, 1, c, io->f) != c) return -1; }
1619
+ else {
1620
+ if (io->piece >= SP_KC_NONCE) return -1;
1621
+ memcpy(io->tmp, b, c); kv_ctr(&io->aes, io->piece++, io->tmp, c); kv_cmac_update(&io->mac, io->tmp, c);
1622
+ if (fwrite(io->tmp, 1, c, io->f) != c) return -1;
1623
+ }
1624
+ b += c; n -= c;
1625
+ }
1626
+ return 0;
1627
+ }
1628
+ static int sp_rd(SpIO *io, void *p, uint64_t n){
1629
+ uint8_t *b = p;
1630
+ while (n){
1631
+ size_t c = n < SP_PIECE ? (size_t)n : SP_PIECE;
1632
+ if (fread(b, 1, c, io->f) != c) return -1;
1633
+ if (io->enc){ if (io->piece >= SP_KC_NONCE) return -1; kv_ctr(&io->aes, io->piece++, b, c); }
1634
+ b += c; n -= c;
1635
+ }
1636
+ return 0;
1637
+ }
1638
+
1639
+ /* how many bytes the arrays of a file with this header take; 0 = the header cannot be right */
1640
+ static uint64_t sp_payload(uint32_t flags, const uint32_t h32[8], const uint64_t h64[6], uint64_t limit){
1641
+ uint64_t dim = h32[1], n = h32[2], nknn = h32[4], nkr = h32[5];
1642
+ for (int i = 0; i < 6; i++) if (h64[i] > limit) return 0;
1643
+ if (n > limit) return 0;
1644
+ uint64_t sz = n * 8 + n + (n + 1) * 8, ctot = (uint64_t)h32[6] | ((uint64_t)h32[7] << 32);
1645
+ if (flags & SP_F_NOROWS){
1646
+ if ((flags & (SP_F_BUILT | SP_F_BLOCKS | SP_F_LISTS)) != (SP_F_BUILT | SP_F_BLOCKS) || dim >= 65536 || ctot > limit || h32[3] != h32[2]) return 0;
1647
+ sz += (n + 1) * 8 + ctot * 2;
1648
+ } else {
1649
+ if (ctot) return 0;
1650
+ sz += h64[0] * 8;
1651
+ }
1652
+ if (flags & SP_F_BUILT){ if (dim > limit) return 0; sz += (dim + 1) * 8; }
1653
+ if (flags & SP_F_LISTS) sz += h64[5] * 8;
1654
+ if (flags & SP_F_BLOCKS)
1655
+ sz += (dim + 1) * 8 * 3 + (h64[1] + 1) * 8 + h64[2] * 4 + h64[1] * 4 + h64[3] * (dim <= 65536 ? 2 : 4)
1656
+ + ((flags & SP_F_SUM2) ? h64[3] + h64[4] * 2 : h64[3] * 4 + h64[4] * 3);
1657
+ if (flags & SP_F_KNN){ if (nknn == 0 || nknn > 1024 || nkr > n) return 0; sz += nkr * nknn * 4; }
1658
+ return sz;
1659
+ }
1660
+
1661
+ int kci_sparse_save(const KciSparse *s, const char *path, const uint8_t *key, int keylen){
1662
+ if (!s || !path || (key && keylen <= 0) || (!key && keylen != 0)) return -1;
1663
+ int built = s->built, lists = built && s->post, blocks = built && s->bptr, knn = blocks && s->nbr;
1664
+ SpIO io; memset(&io, 0, sizeof io);
1665
+ uint8_t salt[16];
1666
+ if (key){
1667
+ if (kv_randbytes(salt, 16) != 0) return -1; /* no random salt, no encrypted file */
1668
+ if (sp_io_keys(&io, key, keylen, salt) != 0) return -1;
1669
+ }
1670
+ char tmp[1100];
1671
+ if (snprintf(tmp, sizeof tmp, "%s.tmp", path) >= (int)sizeof tmp){ free(io.tmp); return -1; }
1672
+ io.f = fopen(tmp, "wb");
1673
+ if (!io.f){ free(io.tmp); return -1; }
1674
+ uint32_t dim = s->dim;
1675
+ uint64_t ctot = s->norows ? s->coff[s->n] : 0;
1676
+ uint32_t h32[8] = { (io.enc ? SP_F_ENC : 0) | (built ? SP_F_BUILT : 0) | (lists ? SP_F_LISTS : 0) | (blocks ? SP_F_BLOCKS | SP_F_SUM2 : 0) | (knn ? SP_F_KNN : 0)
1677
+ | (s->norows ? SP_F_NOROWS : 0)
1678
+ | (blocks && s->head_mass < 1.0f ? (uint32_t)lrintf(s->head_mass * 200.0f) << 8 : 0),
1679
+ dim, s->n, built ? s->nbuilt : 0, knn ? (uint32_t)s->nknn : 0, knn ? s->nknn_rows : 0, (uint32_t)ctot, (uint32_t)(ctot >> 32) };
1680
+ uint64_t h64[6] = { s->fnnz, blocks ? s->nblk : 0, blocks ? s->bdoc[s->nblk] : 0, blocks ? s->sdp[dim] : 0,
1681
+ blocks ? s->sep[dim] : 0, built ? s->tptr[dim] : 0 };
1682
+ int ok = sp_wraw(&io, SP_MAGIC, 8) == 0 && sp_wraw(&io, h32, sizeof h32) == 0 && sp_wraw(&io, h64, sizeof h64) == 0;
1683
+ if (io.enc) ok = ok && sp_wraw(&io, salt, 16) == 0;
1684
+ uint8_t kc[16]; memcpy(kc, SP_KEYCHK, 16);
1685
+ if (io.enc) kv_ctr(&io.aes, SP_KC_NONCE, kc, 16);
1686
+ ok = ok && sp_wraw(&io, kc, 16) == 0;
1687
+ ok = ok && sp_wr(&io, s->ids, (uint64_t)s->n * 8) == 0 && sp_wr(&io, s->dead, s->n) == 0
1688
+ && sp_wr(&io, s->row, ((uint64_t)s->n + 1) * 8) == 0 && (s->norows || sp_wr(&io, s->f, s->fnnz * sizeof *s->f) == 0);
1689
+ if (built) ok = ok && sp_wr(&io, s->tptr, ((uint64_t)dim + 1) * 8) == 0;
1690
+ if (lists) ok = ok && sp_wr(&io, s->post, h64[5] * sizeof *s->post) == 0;
1691
+ if (blocks){
1692
+ ok = ok && sp_wr(&io, s->bptr, ((uint64_t)dim + 1) * 8) == 0 && sp_wr(&io, s->sdp, ((uint64_t)dim + 1) * 8) == 0
1693
+ && sp_wr(&io, s->sep, ((uint64_t)dim + 1) * 8) == 0 && sp_wr(&io, s->bdoc, (h64[1] + 1) * 8) == 0
1694
+ && sp_wr(&io, s->brow, h64[2] * 4) == 0 && sp_wr(&io, s->bscale, h64[1] * 4) == 0;
1695
+ if (s->sdim16) ok = ok && sp_wr(&io, s->sdim16, h64[3] * 2) == 0;
1696
+ else ok = ok && sp_wr(&io, s->sdim32, h64[3] * 4) == 0;
1697
+ ok = ok && sp_wr(&io, s->slen, h64[3]) == 0 && sp_wr(&io, s->ent, h64[4] * 2) == 0;
1698
+ }
1699
+ if (knn) ok = ok && sp_wr(&io, s->nbr, (uint64_t)s->nknn_rows * (uint64_t)s->nknn * 4) == 0;
1700
+ if (s->norows) ok = ok && sp_wr(&io, s->coff, ((uint64_t)s->n + 1) * 8) == 0 && sp_wr(&io, s->crow, ctot * 2) == 0;
1701
+ if (ok && io.enc){ uint8_t tag[16]; kv_cmac_final(&io.mac, tag); ok = fwrite(tag, 1, 16, io.f) == 16; }
1702
+ if (fclose(io.f) != 0) ok = 0;
1703
+ free(io.tmp); memset(&io, 0, sizeof io);
1704
+ if (!ok){ remove(tmp); return -1; }
1705
+ if (sp_replace_file(tmp, path) != 0){ remove(tmp); return -1; }
1706
+ return 0;
1707
+ }
1708
+
1709
+ static int sp_mono(const uint64_t *p, uint64_t n, uint64_t last){
1710
+ if (p[0] != 0) return -1;
1711
+ for (uint64_t i = 0; i < n; i++) if (p[i] > p[i + 1]) return -1;
1712
+ return p[n] == last ? 0 : -1;
1713
+ }
1714
+
1715
+ /* Everything a search follows without looking: offsets in order and inside their arrays, row numbers inside
1716
+ * the rows. A file that passes can still be wrong (it then gives wrong answers) but cannot make a search read
1717
+ * or write outside the index. */
1718
+ static int sp_check(KciSparse *s, uint32_t flags, const uint64_t h64[6]){
1719
+ uint32_t dim = s->dim, n = s->n, nb_rows = s->nbuilt;
1720
+ if (sp_mono(s->row, n, s->fnnz) != 0) return -1;
1721
+ uint32_t nd = 0;
1722
+ if (s->norows && (s->coff[0] != 0 || nb_rows != n)) return -1;
1723
+ for (uint32_t d = 0; d < n; d++){
1724
+ if (s->dead[d] > 1) return -1;
1725
+ nd += s->dead[d];
1726
+ if (s->row[d + 1] - s->row[d] > 0x7fffffffu) return -1;
1727
+ if (!s->norows){
1728
+ for (uint64_t x = s->row[d]; x < s->row[d + 1]; x++){
1729
+ if (s->f[x].k >= dim || !isfinite(s->f[x].v)) return -1;
1730
+ if (x > s->row[d] && s->f[x - 1].k >= s->f[x].k) return -1;
1731
+ }
1732
+ } else { /* the half-size row: sp_crow_dot trusts every field of it */
1733
+ uint64_t len = s->row[d + 1] - s->row[d], o = s->coff[d];
1734
+ if (len > 65535 || s->coff[d + 1] < o + 3 || s->coff[d + 1] > s->coff[n]) return -1;
1735
+ const uint16_t *h = s->crow + o; float sc; memcpy(&sc, h + 1, sizeof sc);
1736
+ uint64_t nh = h[0], cnd = (nh + 15) / 16, nt = len - nh; /* first part, then the tail */
1737
+ uint64_t ext = s->coff[d + 1] - o, used = 3 + cnd + 16 * cnd + nh + 2 * nt;
1738
+ if (nh > len || (ext != used && ext != used + 1) || !isfinite(sc) || sc < 0) return -1; /* + 1: rows start on even entries */
1739
+ if (nt > 0 && !(s->head_mass < 1.0f)) return -1; /* a tail in a file that says whole rows: it would never be added */
1740
+ const uint16_t *dir = h + 3, *ck = dir + cnd, *tk = ck + 16 * cnd + nh;
1741
+ for (uint64_t y = 0; y < 16 * cnd; y++){
1742
+ if (y < nh ? (ck[y] >= dim || (y > 0 && ck[y - 1] >= ck[y])) : ck[y] != 0xFFFF) return -1;
1743
+ }
1744
+ for (uint64_t c = 0; c < cnd; c++) if (dir[c] != ck[16 * c]) return -1;
1745
+ for (uint64_t y = 0; y < nt; y++) if (tk[y] >= dim || (y > 0 && tk[y - 1] >= tk[y])) return -1;
1746
+ }
1747
+ }
1748
+ s->ndead = nd;
1749
+ if (!(flags & SP_F_BUILT)) return (flags & (SP_F_LISTS | SP_F_BLOCKS | SP_F_KNN)) || nb_rows != 0 ? -1 : 0;
1750
+ if (nb_rows > n || sp_mono(s->tptr, dim, h64[5]) != 0 || h64[5] != s->row[nb_rows]) return -1;
1751
+ if (flags & SP_F_LISTS)
1752
+ for (uint32_t t = 0; t < dim; t++)
1753
+ for (uint64_t x = s->tptr[t]; x < s->tptr[t + 1]; x++){
1754
+ if (s->post[x].k >= nb_rows || !isfinite(s->post[x].v)) return -1;
1755
+ if (x > s->tptr[t] && fabsf(s->post[x - 1].v) < fabsf(s->post[x].v)) return -1;
1756
+ }
1757
+ if (flags & SP_F_BLOCKS){
1758
+ if (sp_mono(s->bptr, dim, s->nblk) != 0 || sp_mono(s->bdoc, s->nblk, h64[2]) != 0
1759
+ || sp_mono(s->sdp, dim, h64[3]) != 0 || sp_mono(s->sep, dim, h64[4]) != 0) return -1;
1760
+ for (uint64_t g = 0; g < s->nblk; g++)
1761
+ if (s->bdoc[g + 1] - s->bdoc[g] > 0xffffffffu || !isfinite(s->bscale[g]) || s->bscale[g] < 0) return -1;
1762
+ for (uint64_t x = 0; x < h64[2]; x++) if (s->brow[x] >= nb_rows) return -1;
1763
+ for (uint32_t t = 0; t < dim; t++){
1764
+ uint64_t nb = s->bptr[t + 1] - s->bptr[t], e = s->sep[t];
1765
+ if (nb > 65535) return -1;
1766
+ for (uint64_t x = s->sdp[t]; x < s->sdp[t + 1]; x++){
1767
+ uint32_t k = s->sdim16 ? s->sdim16[x] : s->sdim32[x], len = s->slen[x], g = 0;
1768
+ if (k >= dim || len == 0 || e + len > s->sep[t + 1]) return -1;
1769
+ if (x > s->sdp[t] && (s->sdim16 ? s->sdim16[x - 1] : s->sdim32[x - 1]) > k) return -1;
1770
+ for (uint64_t y = e; y < e + len; y++){ g += s->ent[2 * y]; if (g >= nb) return -1; } /* every group a search adds into */
1771
+ e += len;
1772
+ }
1773
+ if (e != s->sep[t + 1]) return -1;
1774
+ }
1775
+ } else if (!(flags & SP_F_LISTS)) return -1; /* built, but neither way to search it */
1776
+ if (flags & SP_F_KNN){
1777
+ if (!(flags & SP_F_BLOCKS)) return -1;
1778
+ uint64_t tot = (uint64_t)s->nknn_rows * (uint64_t)s->nknn;
1779
+ for (uint64_t x = 0; x < tot; x++) if (s->nbr[x] != UINT32_MAX && s->nbr[x] >= nb_rows) return -1;
1780
+ }
1781
+ return 0;
1782
+ }
1783
+
1784
+ static int sp_sum_from_v1(KciSparse *s, const uint32_t *soff, const uint16_t *eblk, const uint8_t *eq, uint64_t tot[2]){
1785
+ uint32_t dim = s->dim; int rc = -1;
1786
+ if (sp_mono(s->bptr, dim, s->nblk) != 0 || sp_mono(s->sdp, dim, tot[0]) != 0 || sp_mono(s->sep, dim, tot[1]) != 0) return -1;
1787
+ uint64_t maxe = 0;
1788
+ for (uint32_t t = 0; t < dim; t++){ uint64_t et = s->sep[t + 1] - s->sep[t]; if (et > 0xffffffffu) return -1; if (et > maxe) maxe = et; }
1789
+ uint64_t *keys = malloc((size_t)(maxe ? maxe : 1) * sizeof *keys);
1790
+ uint32_t *tdim = NULL; uint8_t *tlen = NULL, *slen = NULL, *ent = NULL; uint16_t *d16 = NULL; uint32_t *d32 = NULL;
1791
+ uint64_t *nsdp = malloc(((size_t)dim + 1) * sizeof *nsdp), *nsep = malloc(((size_t)dim + 1) * sizeof *nsep);
1792
+ uint64_t nd_all = 0, ne_all = 0, tcap = 0;
1793
+ if (!keys || !nsdp || !nsep) goto done;
1794
+ for (int pass = 0; pass < 2; pass++){
1795
+ uint64_t d = 0, e = 0;
1796
+ for (uint32_t t = 0; t < dim; t++){
1797
+ uint64_t nb = s->bptr[t + 1] - s->bptr[t], et = s->sep[t + 1] - s->sep[t], n = 0;
1798
+ if (nb > 65535) goto done;
1799
+ for (uint64_t x = s->sdp[t]; x < s->sdp[t + 1]; x++){
1800
+ uint32_t k = s->sdim16 ? s->sdim16[x] : s->sdim32[x];
1801
+ uint64_t e0 = soff[x], e1 = x + 1 < s->sdp[t + 1] ? soff[x + 1] : et;
1802
+ if (k >= dim || e0 > e1 || e1 > et) goto done;
1803
+ if (x > s->sdp[t] && (s->sdim16 ? s->sdim16[x - 1] : s->sdim32[x - 1]) >= k) goto done;
1804
+ if (x == s->sdp[t] && e0 != 0) goto done;
1805
+ for (uint64_t y = e0; y < e1; y++){
1806
+ uint32_t g = eblk[s->sep[t] + y];
1807
+ if (g >= nb || (y > e0 && eblk[s->sep[t] + y - 1] >= g)) goto done;
1808
+ keys[n++] = ((uint64_t)k << 24) | ((uint64_t)g << 8) | (uint64_t)eq[s->sep[t] + y];
1809
+ }
1810
+ }
1811
+ uint32_t nd = 0, ne = 0;
1812
+ if (pass == 0){
1813
+ sp_enc_runs(keys, (size_t)n, NULL, NULL, NULL, &nd, &ne);
1814
+ if (nd > tcap) tcap = nd;
1815
+ } else {
1816
+ sp_enc_runs(keys, (size_t)n, tdim, tlen, ent + 2 * e, &nd, &ne);
1817
+ memcpy(slen + d, tlen, nd);
1818
+ if (d16) for (uint32_t x = 0; x < nd; x++) d16[d + x] = (uint16_t)tdim[x];
1819
+ else memcpy(d32 + d, tdim, (size_t)nd * sizeof *d32);
1820
+ nsdp[t] = d; nsep[t] = e;
1821
+ }
1822
+ d += nd; e += ne;
1823
+ }
1824
+ if (pass == 0){
1825
+ nd_all = d; ne_all = e;
1826
+ tdim = malloc((size_t)(tcap ? tcap : 1) * sizeof *tdim); tlen = malloc((size_t)(tcap ? tcap : 1));
1827
+ slen = malloc((size_t)(nd_all ? nd_all : 1)); ent = malloc((size_t)(ne_all ? ne_all : 1) * 2);
1828
+ if (s->sdim16) d16 = malloc((size_t)(nd_all ? nd_all : 1) * sizeof *d16); else d32 = malloc((size_t)(nd_all ? nd_all : 1) * sizeof *d32);
1829
+ if (!tdim || !tlen || !slen || !ent || (!d16 && !d32)) goto done;
1830
+ } else { nsdp[dim] = d; nsep[dim] = e; }
1831
+ }
1832
+ if (s->sdim16){ free(s->sdim16); s->sdim16 = d16; d16 = NULL; } else { free(s->sdim32); s->sdim32 = d32; d32 = NULL; }
1833
+ free(s->sdp); s->sdp = nsdp; nsdp = NULL; free(s->sep); s->sep = nsep; nsep = NULL;
1834
+ s->slen = slen; slen = NULL; s->ent = ent; ent = NULL;
1835
+ tot[0] = nd_all; tot[1] = ne_all; rc = 0;
1836
+ done:
1837
+ free(keys); free(tdim); free(tlen); free(slen); free(ent); free(d16); free(d32); free(nsdp); free(nsep);
1838
+ return rc;
1839
+ }
1840
+
1841
+ KciSparse *kci_sparse_load(const char *path, const uint8_t *key, int keylen){
1842
+ if (!path || (key && keylen <= 0) || (!key && keylen != 0)) return NULL;
1843
+ SpIO io; memset(&io, 0, sizeof io);
1844
+ KciSparse *s = NULL; int ok = 0;
1845
+ io.f = fopen(path, "rb");
1846
+ if (!io.f) return NULL;
1847
+ uint8_t magic[8], salt[16], kc[16]; uint32_t h32[8]; uint64_t h64[6];
1848
+ do {
1849
+ if (fread(magic, 1, 8, io.f) != 8 || memcmp(magic, SP_MAGIC, 8) != 0) break;
1850
+ if (fread(h32, sizeof h32, 1, io.f) != 1 || fread(h64, sizeof h64, 1, io.f) != 1) break;
1851
+ uint32_t flags = h32[0], dim = h32[1];
1852
+ if ((flags & ~(SP_F_ALL | 0xff00u)) || SP_F_HEAD(flags) >= 200 || dim == 0 || ((flags & SP_F_SUM2) && !(flags & SP_F_BLOCKS))) break;
1853
+ /* a key says the caller expects an encrypted, authenticated file: a plain one in its place is refused */
1854
+ if (((flags & SP_F_ENC) != 0) != (key != NULL)) break;
1855
+ if (sp_fseek(io.f, 0, SEEK_END) != 0) break;
1856
+ int64_t fsize = (int64_t)sp_ftell(io.f);
1857
+ uint64_t head = 8 + sizeof h32 + sizeof h64 + (key ? 16 : 0) + 16, tail = key ? 16 : 0;
1858
+ if (fsize < 0 || (uint64_t)fsize < head + tail) break;
1859
+ uint64_t pay = sp_payload(flags, h32, h64, (uint64_t)fsize);
1860
+ if (pay == 0 || pay != (uint64_t)fsize - head - tail) break;
1861
+ if (sp_fseek(io.f, (int64_t)(8 + sizeof h32 + sizeof h64), SEEK_SET) != 0) break;
1862
+ if (key){
1863
+ if (fread(salt, 1, 16, io.f) != 16 || sp_io_keys(&io, key, keylen, salt) != 0) break;
1864
+ }
1865
+ if (fread(kc, 1, 16, io.f) != 16) break;
1866
+ if (key) kv_ctr(&io.aes, SP_KC_NONCE, kc, 16);
1867
+ if (memcmp(kc, SP_KEYCHK, 16) != 0) break; /* wrong key (or not this kind of file) */
1868
+ if (key){
1869
+ uint64_t left = (uint64_t)fsize - 16; uint8_t tag[16], want[16], diff = 0;
1870
+ if (sp_fseek(io.f, 0, SEEK_SET) != 0) break;
1871
+ int bad = 0;
1872
+ while (left && !bad){
1873
+ size_t c = left < SP_PIECE ? (size_t)left : SP_PIECE;
1874
+ if (fread(io.tmp, 1, c, io.f) != c) bad = 1; else kv_cmac_update(&io.mac, io.tmp, c);
1875
+ left -= c;
1876
+ }
1877
+ if (bad || fread(want, 1, 16, io.f) != 16) break;
1878
+ kv_cmac_final(&io.mac, tag);
1879
+ for (int i = 0; i < 16; i++) diff |= (uint8_t)(tag[i] ^ want[i]);
1880
+ if (diff) break;
1881
+ if (sp_fseek(io.f, (int64_t)head, SEEK_SET) != 0) break;
1882
+ }
1883
+ s = calloc(1, sizeof *s);
1884
+ if (!s) break;
1885
+ uint32_t n = h32[2];
1886
+ s->dim = dim; s->n = n; s->ncap = n; s->fnnz = h64[0]; s->fcap = h64[0]; s->gen = 1;
1887
+ s->built = (flags & SP_F_BUILT) != 0; s->nbuilt = h32[3];
1888
+ s->ids = malloc(((size_t)n ? (size_t)n : 1) * 8); s->dead = malloc((size_t)n ? (size_t)n : 1);
1889
+ s->norows = (flags & SP_F_NOROWS) != 0;
1890
+ s->head_mass = SP_F_HEAD(flags) ? (float)SP_F_HEAD(flags) / 200.0f : 1.0f;
1891
+ if (s->norows) s->fcap = 0;
1892
+ s->row = malloc(((size_t)n + 1) * 8);
1893
+ if (!s->norows) s->f = malloc((size_t)(h64[0] ? h64[0] : 1) * sizeof *s->f);
1894
+ if (!s->ids || !s->dead || !s->row || (!s->norows && !s->f)) break;
1895
+ if (sp_rd(&io, s->ids, (uint64_t)n * 8) != 0 || sp_rd(&io, s->dead, n) != 0
1896
+ || sp_rd(&io, s->row, ((uint64_t)n + 1) * 8) != 0 || (!s->norows && sp_rd(&io, s->f, h64[0] * sizeof *s->f) != 0)) break;
1897
+ if (flags & SP_F_BUILT){
1898
+ s->tptr = malloc(((size_t)dim + 1) * 8);
1899
+ if (!s->tptr || sp_rd(&io, s->tptr, ((uint64_t)dim + 1) * 8) != 0) break;
1900
+ }
1901
+ if (flags & SP_F_LISTS){
1902
+ s->post = malloc((size_t)(h64[5] ? h64[5] : 1) * sizeof *s->post);
1903
+ if (!s->post || sp_rd(&io, s->post, h64[5] * sizeof *s->post) != 0) break;
1904
+ }
1905
+ if (flags & SP_F_BLOCKS){
1906
+ size_t nblk = (size_t)h64[1], nr = (size_t)h64[2], nd = (size_t)h64[3], ne = (size_t)h64[4];
1907
+ s->nblk = h64[1];
1908
+ s->bptr = malloc(((size_t)dim + 1) * 8); s->sdp = malloc(((size_t)dim + 1) * 8); s->sep = malloc(((size_t)dim + 1) * 8);
1909
+ s->bdoc = malloc((nblk + 1) * 8); s->brow = malloc((nr ? nr : 1) * 4); s->bscale = malloc((nblk ? nblk : 1) * 4);
1910
+ if (dim <= 65536) s->sdim16 = malloc((nd ? nd : 1) * 2); else s->sdim32 = malloc((nd ? nd : 1) * 4);
1911
+ if (!s->bptr || !s->sdp || !s->sep || !s->bdoc || !s->brow || !s->bscale || (!s->sdim16 && !s->sdim32)) break;
1912
+ if (sp_rd(&io, s->bptr, ((uint64_t)dim + 1) * 8) != 0 || sp_rd(&io, s->sdp, ((uint64_t)dim + 1) * 8) != 0
1913
+ || sp_rd(&io, s->sep, ((uint64_t)dim + 1) * 8) != 0 || sp_rd(&io, s->bdoc, (h64[1] + 1) * 8) != 0
1914
+ || sp_rd(&io, s->brow, h64[2] * 4) != 0 || sp_rd(&io, s->bscale, h64[1] * 4) != 0) break;
1915
+ if (s->sdim16 ? sp_rd(&io, s->sdim16, h64[3] * 2) != 0 : sp_rd(&io, s->sdim32, h64[3] * 4) != 0) break;
1916
+ if (flags & SP_F_SUM2){
1917
+ s->slen = malloc(nd ? nd : 1); s->ent = malloc((ne ? ne : 1) * 2);
1918
+ if (!s->slen || !s->ent || sp_rd(&io, s->slen, h64[3]) != 0 || sp_rd(&io, s->ent, h64[4] * 2) != 0) break;
1919
+ } else {
1920
+ uint32_t *soff = malloc((nd ? nd : 1) * 4); uint16_t *eblk = malloc((ne ? ne : 1) * 2); uint8_t *eq = malloc(ne ? ne : 1);
1921
+ int bad = !soff || !eblk || !eq || sp_rd(&io, soff, h64[3] * 4) != 0 || sp_rd(&io, eblk, h64[4] * 2) != 0 || sp_rd(&io, eq, h64[4]) != 0;
1922
+ if (!bad) bad = sp_sum_from_v1(s, soff, eblk, eq, &h64[3]) != 0;
1923
+ free(soff); free(eblk); free(eq);
1924
+ if (bad) break;
1925
+ }
1926
+ }
1927
+ if (flags & SP_F_KNN){
1928
+ s->nknn = (int)h32[4]; s->nknn_rows = h32[5];
1929
+ uint64_t tot = (uint64_t)h32[4] * (uint64_t)h32[5];
1930
+ s->nbr = malloc((size_t)(tot ? tot : 1) * 4);
1931
+ if (!s->nbr || sp_rd(&io, s->nbr, tot * 4) != 0) break;
1932
+ }
1933
+ if (s->norows){
1934
+ uint64_t ctot = (uint64_t)h32[6] | ((uint64_t)h32[7] << 32);
1935
+ s->coff = malloc(((size_t)n + 1) * 8); s->crow = malloc(((size_t)ctot + SP_CROW_PAD) * sizeof *s->crow);
1936
+ if (!s->coff || !s->crow || sp_rd(&io, s->coff, ((uint64_t)n + 1) * 8) != 0 || sp_rd(&io, s->crow, ctot * 2) != 0) break;
1937
+ memset(s->crow + ctot, 0, SP_CROW_PAD * sizeof *s->crow);
1938
+ if (s->coff[n] != ctot) break;
1939
+ s->ncrow = n;
1940
+ }
1941
+ if (sp_check(s, flags, h64) != 0) break;
1942
+ if ((flags & SP_F_BLOCKS) && sp_make_sck(s) != 0) break;
1943
+ if ((flags & SP_F_BLOCKS) && dim < 65536 && !s->norows && sp_make_crow(s, 0) != 0) break;
1944
+ if (flags & SP_F_BLOCKS) sp_make_boff(s);
1945
+ ok = 1;
1946
+ } while (0);
1947
+ fclose(io.f); free(io.tmp); memset(&io, 0, sizeof io);
1948
+ if (!ok){ kci_sparse_free(s); return NULL; }
1949
+ return s;
1950
+ }
1951
+
1952
+ #define SP_SEAL_MAGIC "KCISEAL1"
1953
+ #define SP_SEAL_ENC "KCISEAL1 encryption key"
1954
+ #define SP_SEAL_MAC "KCISEAL1 mac key"
1955
+ #define SP_SEAL_OVER 40u
1956
+ static void sp_seal_keys(const uint8_t *key, int keylen, const uint8_t salt[16], KvAes *aes, KvCmac *mac){
1957
+ uint8_t mk[32], ek[32], ak[32];
1958
+ kdf_derive(key, keylen, salt, 16, mk);
1959
+ kv_subkey(mk, SP_SEAL_ENC, ek); kv_subkey(mk, SP_SEAL_MAC, ak);
1960
+ kv_aes_init(aes, ek); kv_cmac_init(mac, ak);
1961
+ memset(mk, 0, 32); memset(ek, 0, 32); memset(ak, 0, 32);
1962
+ }
1963
+ static void sp_seal_ctr(const KvAes *aes, uint8_t *buf, uint64_t n){
1964
+ uint64_t piece = 0;
1965
+ while (n){ size_t c = n < SP_PIECE ? (size_t)n : SP_PIECE; kv_ctr(aes, piece++, buf, c); buf += c; n -= c; }
1966
+ }
1967
+ int64_t kci_seal(const uint8_t *in, uint64_t n, const uint8_t *key, int keylen, uint8_t *out){
1968
+ if ((!in && n) || !key || keylen <= 0 || !out || n > (uint64_t)INT64_MAX - SP_SEAL_OVER) return -1;
1969
+ uint8_t salt[16];
1970
+ if (kv_randbytes(salt, 16) != 0) return -1; /* no random salt, nothing written */
1971
+ KvAes aes; KvCmac mac;
1972
+ sp_seal_keys(key, keylen, salt, &aes, &mac);
1973
+ memcpy(out, SP_SEAL_MAGIC, 8); memcpy(out + 8, salt, 16);
1974
+ if (n) memcpy(out + 24, in, (size_t)n);
1975
+ sp_seal_ctr(&aes, out + 24, n);
1976
+ kv_cmac_update(&mac, out, (size_t)(24 + n));
1977
+ kv_cmac_final(&mac, out + 24 + n);
1978
+ memset(&aes, 0, sizeof aes); memset(&mac, 0, sizeof mac);
1979
+ return (int64_t)(n + SP_SEAL_OVER);
1980
+ }
1981
+ int64_t kci_unseal(const uint8_t *in, uint64_t n, const uint8_t *key, int keylen, uint8_t *out){
1982
+ if (!in || !key || keylen <= 0 || n < SP_SEAL_OVER || n > (uint64_t)INT64_MAX) return -1;
1983
+ if (memcmp(in, SP_SEAL_MAGIC, 8) != 0) return -1;
1984
+ uint64_t m = n - SP_SEAL_OVER;
1985
+ if (m && !out) return -1;
1986
+ KvAes aes; KvCmac mac; uint8_t tag[16], diff = 0;
1987
+ sp_seal_keys(key, keylen, in + 8, &aes, &mac);
1988
+ kv_cmac_update(&mac, in, (size_t)(24 + m));
1989
+ kv_cmac_final(&mac, tag);
1990
+ for (int i = 0; i < 16; i++) diff |= (uint8_t)(tag[i] ^ in[24 + m + i]);
1991
+ if (!diff && m){ memcpy(out, in + 24, (size_t)m); sp_seal_ctr(&aes, out, m); }
1992
+ memset(&aes, 0, sizeof aes); memset(&mac, 0, sizeof mac);
1993
+ return diff ? -1 : (int64_t)m;
1994
+ }
1995
+