@yaks/embedding 0.0.0-stage → 0.2.36
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.
- package/LICENSE +202 -0
- package/README.md +549 -2
- package/_dist/compile.d.ts +34 -0
- package/_dist/compile.d.ts.map +1 -0
- package/_dist/ddl.d.ts +31 -0
- package/_dist/ddl.d.ts.map +1 -0
- package/_dist/embedder.d.ts +55 -0
- package/_dist/embedder.d.ts.map +1 -0
- package/_dist/fields.d.ts +70 -0
- package/_dist/fields.d.ts.map +1 -0
- package/_dist/graph.d.ts +63 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/held.d.ts +16 -0
- package/_dist/held.d.ts.map +1 -0
- package/_dist/image.d.ts +20 -0
- package/_dist/image.d.ts.map +1 -0
- package/_dist/mod.d.ts +105 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/native.d.ts +20 -0
- package/_dist/native.d.ts.map +1 -0
- package/_dist/near.d.ts +35 -0
- package/_dist/near.d.ts.map +1 -0
- package/_dist/neighbours.d.ts +29 -0
- package/_dist/neighbours.d.ts.map +1 -0
- package/_dist/options.d.ts +37 -0
- package/_dist/options.d.ts.map +1 -0
- package/_dist/outage.d.ts +64 -0
- package/_dist/outage.d.ts.map +1 -0
- package/_dist/owed.d.ts +79 -0
- package/_dist/owed.d.ts.map +1 -0
- package/_dist/remote.d.ts +116 -0
- package/_dist/remote.d.ts.map +1 -0
- package/_dist/score.d.ts +10 -0
- package/_dist/score.d.ts.map +1 -0
- package/_dist/search.d.ts +24 -0
- package/_dist/search.d.ts.map +1 -0
- package/_dist/service.d.ts +23 -0
- package/_dist/service.d.ts.map +1 -0
- package/_dist/sleeper.d.ts +37 -0
- package/_dist/sleeper.d.ts.map +1 -0
- package/_dist/sweep.d.ts +71 -0
- package/_dist/sweep.d.ts.map +1 -0
- package/_dist/tools.d.ts +14 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/vector.d.ts +30 -0
- package/_dist/vector.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/coded.js +98 -0
- package/coded.js.map +1 -0
- package/coded.ts +85 -0
- package/compile.js +145 -0
- package/compile.js.map +1 -0
- package/compile.ts +206 -0
- package/ddl.js +476 -0
- package/ddl.js.map +1 -0
- package/ddl.ts +346 -0
- package/deno.json +1 -0
- package/embedder.js +85 -0
- package/embedder.js.map +1 -0
- package/embedder.ts +113 -0
- package/fields.js +178 -0
- package/fields.js.map +1 -0
- package/fields.ts +259 -0
- package/fill.js +177 -0
- package/fill.js.map +1 -0
- package/fill.ts +144 -0
- package/graph.js +113 -0
- package/graph.js.map +1 -0
- package/graph.ts +167 -0
- package/held.js +680 -0
- package/held.js.map +1 -0
- package/held.ts +726 -0
- package/image.js +202 -0
- package/image.js.map +1 -0
- package/image.ts +185 -0
- package/mod.js +105 -0
- package/mod.js.map +1 -0
- package/mod.ts +113 -0
- package/native.js +236 -0
- package/native.js.map +1 -0
- package/native.ts +288 -0
- package/near.js +123 -0
- package/near.js.map +1 -0
- package/near.ts +192 -0
- package/neighbours.js +223 -0
- package/neighbours.js.map +1 -0
- package/neighbours.ts +303 -0
- package/options.js +187 -0
- package/options.js.map +1 -0
- package/options.ts +269 -0
- package/outage.js +128 -0
- package/outage.js.map +1 -0
- package/outage.ts +132 -0
- package/owed.js +287 -0
- package/owed.js.map +1 -0
- package/owed.ts +346 -0
- package/package.json +45 -4
- package/remote.js +264 -0
- package/remote.js.map +1 -0
- package/remote.ts +391 -0
- package/score.js +46 -0
- package/score.js.map +1 -0
- package/score.ts +60 -0
- package/search.js +65 -0
- package/search.js.map +1 -0
- package/search.ts +118 -0
- package/service.js +107 -0
- package/service.js.map +1 -0
- package/service.ts +133 -0
- package/sleeper.js +107 -0
- package/sleeper.js.map +1 -0
- package/sleeper.ts +166 -0
- package/sparse.js +36 -0
- package/sparse.js.map +1 -0
- package/sparse.ts +49 -0
- package/sweep.js +374 -0
- package/sweep.js.map +1 -0
- package/sweep.ts +446 -0
- package/tools.js +57 -0
- package/tools.js.map +1 -0
- package/tools.ts +88 -0
- package/vector.js +78 -0
- package/vector.js.map +1 -0
- package/vector.ts +96 -0
- package/visibility.js +83 -0
- package/visibility.js.map +1 -0
- package/visibility.ts +111 -0
- package/vocab.js +22 -0
- package/vocab.js.map +1 -0
- package/vocab.json +19 -0
- package/vocab.ts +22 -0
package/held.js
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
// The vectors held in this process's memory, so a search compares without
|
|
2
|
+
// reading them all: one copy per statement capability, loaded the first time a
|
|
3
|
+
// search asks for it, or before where a process answers many (./graph.ts
|
|
4
|
+
// `preload`, which a read worker runs). A database only this process has open
|
|
5
|
+
// (a Durable Object's, or one in memory; @yaks/sql `Statements.ownership` says
|
|
6
|
+
// which) keeps its copy current by a dirty set; shared storage, by a journal.
|
|
7
|
+
//
|
|
8
|
+
// The copy is int8. Each vector is held as one signed byte per coordinate, its
|
|
9
|
+
// coordinates over its own largest in 127 steps, and one float that scales
|
|
10
|
+
// them back. A search scans every code, keeps the best {@link RESCORE} the
|
|
11
|
+
// graph lets stand, reads those few vectors' float rows, and ranks them by
|
|
12
|
+
// their exact cosine. Scaling each vector by its own largest coordinate is the
|
|
13
|
+
// calibration that suits an embedding model's unit vectors: Qwen3-Embedding's
|
|
14
|
+
// largest coordinate is ~3.8 times its root mean square, and no one dimension
|
|
15
|
+
// holds it, so one step is ~1/33 of a typical coordinate and the scan's error
|
|
16
|
+
// is far below the gap between a neighbour and the hundredth candidate. It
|
|
17
|
+
// needs no ranges drawn from the data, so a vector codes the same whenever and
|
|
18
|
+
// wherever it is coded, and a copy kept current write by write codes exactly
|
|
19
|
+
// what one loaded afresh would.
|
|
20
|
+
//
|
|
21
|
+
// The table stays the truth, and the copy is the table as of one build. An
|
|
22
|
+
// exclusive store's copy is kept current by triggers on the table, which note
|
|
23
|
+
// every vector written or deleted, by anyone, in the same statement as the
|
|
24
|
+
// write (./ddl.ts, the dirty set), and a search codes what the set names from
|
|
25
|
+
// its rows beside the copy. After each sweep pass, the process that ran it
|
|
26
|
+
// folds the set into its copy and clears it ({@link absorb}), numbering a new
|
|
27
|
+
// build; a copy that sees a build it did not make loads again. So no write can
|
|
28
|
+
// leave a copy behind: a write another driver made, a migration, a rollback
|
|
29
|
+
// are all in the set or in the build number.
|
|
30
|
+
//
|
|
31
|
+
// Shared storage is a file on a box that other processes write too, and its
|
|
32
|
+
// copy loads from the codes kept beside the floats (./coded.ts), a fifth of
|
|
33
|
+
// their bytes, once every vector has them under one model. Triggers journal
|
|
34
|
+
// every vector written, whoever writes it (./ddl.ts `JOURNAL`), and a search
|
|
35
|
+
// first folds in what the journal names past the last change its copy read,
|
|
36
|
+
// coding those vectors from their floats. A copy further behind than
|
|
37
|
+
// {@link FOLLOW} changes, or behind what the sweep trimmed, loads again. So
|
|
38
|
+
// once a copy is held, a search reads only the few vectors it rescores: the
|
|
39
|
+
// native scan it replaces read every code, 7 s of them from disk when the
|
|
40
|
+
// box's page cache had let the file go.
|
|
41
|
+
//
|
|
42
|
+
// Memory is the limit. A vector costs its width in bytes and ~40 bytes beside
|
|
43
|
+
// it (1 KB at 1024 dimensions), and every object in a Worker's isolate shares
|
|
44
|
+
// its 128 MB, so all copies together stay within {@link HELD}: the least
|
|
45
|
+
// recently searched is dropped to make room, and a store whose vectors alone
|
|
46
|
+
// would pass it is not held at all and is read row by row. Today's largest
|
|
47
|
+
// store (24k vectors) holds 25 MB; ten times that would not fit. Shared
|
|
48
|
+
// storage is never in a Worker, so its copies share {@link SHARED} instead: the
|
|
49
|
+
// box's 314k vectors at 384 dimensions hold 133 MB.
|
|
50
|
+
import { among, and, as, at, col, each, eq, exists, fn, from, gt, join, lit, not, op, select, table, tally, val } from "@yaks/sql";
|
|
51
|
+
import { BUILD, CODE, DIRTY, JOURNAL, TABLE } from "./ddl.js";
|
|
52
|
+
import { admitted, current, few, only } from "./native.js";
|
|
53
|
+
import { complete } from "./coded.js";
|
|
54
|
+
import { code, cosine, floats } from "./vector.js";
|
|
55
|
+
/** How many bytes of vectors this process holds across every copy: 48 MB of
|
|
56
|
+
* a Worker isolate's 128 MB, which every object in it shares. */ export let HELD = 48 * 2 ** 20;
|
|
57
|
+
/** How many bytes of shared storage's vectors this process holds across every
|
|
58
|
+
* copy: a box's process, which has the memory a Worker's isolate does not. */ export let SHARED = 512 * 2 ** 20;
|
|
59
|
+
/** How many changes a copy of shared storage reads on through before it loads
|
|
60
|
+
* again instead, and how many the sweep keeps when it trims the journal. */ export let FOLLOW = 4096;
|
|
61
|
+
/** How many of the scan's best a search reads from their rows and ranks by
|
|
62
|
+
* their exact cosine (more where it asks for more neighbours). */ export let RESCORE = 100;
|
|
63
|
+
// Rows read to a statement while a copy loads.
|
|
64
|
+
let PAGE = 2048;
|
|
65
|
+
// The bytes one vector costs held: its codes, its owner, its scale, and its
|
|
66
|
+
// entry in the owner index.
|
|
67
|
+
let cost = (dim)=>dim + 4 + 4 + 32;
|
|
68
|
+
// The first `size` coded vectors' scores against `query`: each one's codes'
|
|
69
|
+
// dot product, term after term, times its scale. Four vectors share a pass
|
|
70
|
+
// over the query, which V8 runs nearly twice as fast as one at a time, and
|
|
71
|
+
// each one's sum is still its own terms in order, so a vector scores the same
|
|
72
|
+
// to the last bit however many are scored beside it.
|
|
73
|
+
let scores = (query, codes, scales, size)=>{
|
|
74
|
+
let out = new Float64Array(size);
|
|
75
|
+
let dim = query.length, i = 0;
|
|
76
|
+
for(; i + 4 <= size; i += 4){
|
|
77
|
+
let a = 0, b = 0, c = 0, d = 0;
|
|
78
|
+
let p = i * dim, q = p + dim, r = q + dim, s = r + dim;
|
|
79
|
+
for(let j = 0; j < dim; j++){
|
|
80
|
+
let x = query[j];
|
|
81
|
+
a += x * codes[p + j];
|
|
82
|
+
b += x * codes[q + j];
|
|
83
|
+
c += x * codes[r + j];
|
|
84
|
+
d += x * codes[s + j];
|
|
85
|
+
}
|
|
86
|
+
out[i] = scales[i] * a;
|
|
87
|
+
out[i + 1] = scales[i + 1] * b;
|
|
88
|
+
out[i + 2] = scales[i + 2] * c;
|
|
89
|
+
out[i + 3] = scales[i + 3] * d;
|
|
90
|
+
}
|
|
91
|
+
for(; i < size; i++){
|
|
92
|
+
let a = 0, p = i * dim;
|
|
93
|
+
for(let j = 0; j < dim; j++)a += query[j] * codes[p + j];
|
|
94
|
+
out[i] = scales[i] * a;
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
};
|
|
98
|
+
// Each driver's copy, gone with the driver. The copies are also listed, least
|
|
99
|
+
// recently searched first, to share one budget; the list holds them weakly, so
|
|
100
|
+
// an object the runtime let go of takes its copy with it.
|
|
101
|
+
let copies = new WeakMap();
|
|
102
|
+
let lru = new Set();
|
|
103
|
+
let refs = new WeakMap();
|
|
104
|
+
// The drivers whose vectors would not fit.
|
|
105
|
+
let over = new WeakSet();
|
|
106
|
+
let bytes = (h)=>h.ids.length * cost(h.dim);
|
|
107
|
+
let touch = (h)=>{
|
|
108
|
+
let r = refs.get(h) ?? new WeakRef(h);
|
|
109
|
+
refs.set(h, r);
|
|
110
|
+
lru.delete(r);
|
|
111
|
+
lru.add(r);
|
|
112
|
+
};
|
|
113
|
+
let listed = ()=>[
|
|
114
|
+
...lru
|
|
115
|
+
].flatMap((r)=>{
|
|
116
|
+
let h = r.deref();
|
|
117
|
+
if (!h) lru.delete(r);
|
|
118
|
+
return h ? [
|
|
119
|
+
h
|
|
120
|
+
] : [];
|
|
121
|
+
});
|
|
122
|
+
let drop = (h)=>{
|
|
123
|
+
let r = refs.get(h);
|
|
124
|
+
if (r) lru.delete(r);
|
|
125
|
+
Object.assign(h, {
|
|
126
|
+
n: -1,
|
|
127
|
+
size: 0,
|
|
128
|
+
ids: new Int32Array(0),
|
|
129
|
+
scales: new Float32Array(0),
|
|
130
|
+
codes: new Int8Array(0),
|
|
131
|
+
slot: new Map()
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
// Room for `need` more bytes, dropping the least recently searched copies of
|
|
135
|
+
// its kind other than `mine`; false when `need` could not fit even then.
|
|
136
|
+
let room = (need, mine)=>{
|
|
137
|
+
let held = listed().filter((h)=>h.shared == mine.shared);
|
|
138
|
+
let budget = mine.shared ? SHARED : HELD;
|
|
139
|
+
let used = 0;
|
|
140
|
+
for (let h of held)used += bytes(h);
|
|
141
|
+
for (let h of held){
|
|
142
|
+
if (used + need <= budget) break;
|
|
143
|
+
if (h == mine) continue;
|
|
144
|
+
used -= bytes(h);
|
|
145
|
+
drop(h);
|
|
146
|
+
}
|
|
147
|
+
return used + need <= budget;
|
|
148
|
+
};
|
|
149
|
+
// Room for `cap` vectors, keeping the ones held.
|
|
150
|
+
let grow = (h, cap)=>{
|
|
151
|
+
if (!room((cap - h.ids.length) * cost(h.dim), h)) return false;
|
|
152
|
+
let ids = new Int32Array(cap), scales = new Float32Array(cap);
|
|
153
|
+
let codes = new Int8Array(cap * h.dim);
|
|
154
|
+
ids.set(h.ids.subarray(0, h.size));
|
|
155
|
+
scales.set(h.scales.subarray(0, h.size));
|
|
156
|
+
codes.set(h.codes.subarray(0, h.size * h.dim));
|
|
157
|
+
Object.assign(h, {
|
|
158
|
+
ids,
|
|
159
|
+
scales,
|
|
160
|
+
codes
|
|
161
|
+
});
|
|
162
|
+
return true;
|
|
163
|
+
};
|
|
164
|
+
// Forget `owner`'s vector: the last slot moves into its place.
|
|
165
|
+
let lose = (h, owner)=>{
|
|
166
|
+
let i = h.slot.get(owner);
|
|
167
|
+
if (i == null) return;
|
|
168
|
+
let last = --h.size;
|
|
169
|
+
h.slot.delete(owner);
|
|
170
|
+
if (i == last) return;
|
|
171
|
+
let moved = h.ids[last];
|
|
172
|
+
h.ids[i] = moved;
|
|
173
|
+
h.scales[i] = h.scales[last];
|
|
174
|
+
h.codes.copyWithin(i * h.dim, last * h.dim, (last + 1) * h.dim);
|
|
175
|
+
h.slot.set(moved, i);
|
|
176
|
+
};
|
|
177
|
+
// The slot `owner`'s vector is held in, the one it had or a new one; null
|
|
178
|
+
// when there is no room for it.
|
|
179
|
+
let slot = (h, owner)=>{
|
|
180
|
+
let i = h.slot.get(owner);
|
|
181
|
+
if (i != null) return i;
|
|
182
|
+
if (h.size == h.ids.length && !grow(h, h.size + (h.size >> 3) + 64)) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
i = h.size++;
|
|
186
|
+
h.slot.set(owner, i);
|
|
187
|
+
h.ids[i] = owner;
|
|
188
|
+
return i;
|
|
189
|
+
};
|
|
190
|
+
// Hold `owner`'s vector, coded from its floats; false when there is no room
|
|
191
|
+
// for it.
|
|
192
|
+
let keep = (h, owner, bytes)=>{
|
|
193
|
+
if (!h.dim) h.dim = bytes.byteLength / 4;
|
|
194
|
+
// A vector of another width is from another space; the model name says
|
|
195
|
+
// which, so this is a row nothing should have written, and it is not held.
|
|
196
|
+
if (bytes.byteLength != h.dim * 4) {
|
|
197
|
+
lose(h, owner);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
let i = slot(h, owner);
|
|
201
|
+
if (i == null) return false;
|
|
202
|
+
h.scales[i] = code(floats(bytes), h.codes, i * h.dim);
|
|
203
|
+
return true;
|
|
204
|
+
};
|
|
205
|
+
// Hold `owner`'s vector as the codes stored for it (./coded.ts), scaled by
|
|
206
|
+
// their own length: their cosine is the vector's, give or take a step.
|
|
207
|
+
let kept = (h, owner, bytes)=>{
|
|
208
|
+
if (bytes.byteLength != h.dim) {
|
|
209
|
+
lose(h, owner);
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
let i = slot(h, owner);
|
|
213
|
+
if (i == null) return false;
|
|
214
|
+
let codes = new Int8Array(bytes.buffer, bytes.byteOffset, h.dim);
|
|
215
|
+
h.codes.set(codes, i * h.dim);
|
|
216
|
+
let sum = 0;
|
|
217
|
+
for (let x of codes)sum += x * x;
|
|
218
|
+
h.scales[i] = sum ? 1 / Math.sqrt(sum) : 0;
|
|
219
|
+
return true;
|
|
220
|
+
};
|
|
221
|
+
// What the dirty set names, as each entity's vector stands now: its bytes
|
|
222
|
+
// under `model`, or null where it has none (deleted, or another model's).
|
|
223
|
+
let d = at('d'), e = at('e');
|
|
224
|
+
let dirty = (db, model)=>new Map(db.query(select({
|
|
225
|
+
cols: [
|
|
226
|
+
d('owner'),
|
|
227
|
+
as(e('model'), 'model'),
|
|
228
|
+
as(e('vec'), 'vec')
|
|
229
|
+
],
|
|
230
|
+
from: table(DIRTY, 'd'),
|
|
231
|
+
joins: [
|
|
232
|
+
{
|
|
233
|
+
how: 'left',
|
|
234
|
+
src: table(TABLE, 'e'),
|
|
235
|
+
on: eq(e('owner'), d('owner'))
|
|
236
|
+
}
|
|
237
|
+
]
|
|
238
|
+
})).map((r)=>[
|
|
239
|
+
Number(r.owner),
|
|
240
|
+
r.model == model ? r.vec : null
|
|
241
|
+
]));
|
|
242
|
+
// Where this process alone owns the database, the set is the copies' alone:
|
|
243
|
+
// cleared, with a new
|
|
244
|
+
// build numbered so every other copy of it loads again.
|
|
245
|
+
let owned = (db)=>db.ownership == 'exclusive';
|
|
246
|
+
let advance = (db)=>{
|
|
247
|
+
db.query({
|
|
248
|
+
t: 'update',
|
|
249
|
+
table: BUILD,
|
|
250
|
+
set: {
|
|
251
|
+
n: op('+', col('n'), lit(1))
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
db.query({
|
|
255
|
+
t: 'delete',
|
|
256
|
+
from: DIRTY
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
let clear = (db)=>{
|
|
260
|
+
advance(db);
|
|
261
|
+
return current(db).n;
|
|
262
|
+
};
|
|
263
|
+
// Every vector under `model`, a page at a time, into a copy made to their
|
|
264
|
+
// count; null where they will not fit.
|
|
265
|
+
let load = (db, model)=>{
|
|
266
|
+
let was = copies.get(db);
|
|
267
|
+
if (was) drop(was);
|
|
268
|
+
let h = {
|
|
269
|
+
model,
|
|
270
|
+
dim: 0,
|
|
271
|
+
shared: false,
|
|
272
|
+
n: current(db).n,
|
|
273
|
+
size: 0,
|
|
274
|
+
ids: new Int32Array(0),
|
|
275
|
+
scales: new Float32Array(0),
|
|
276
|
+
codes: new Int8Array(0),
|
|
277
|
+
slot: new Map()
|
|
278
|
+
};
|
|
279
|
+
touch(h);
|
|
280
|
+
copies.set(db, h);
|
|
281
|
+
let [first] = db.query(select({
|
|
282
|
+
cols: [
|
|
283
|
+
as(fn('length', col('vec')), 'bytes')
|
|
284
|
+
],
|
|
285
|
+
from: table(TABLE),
|
|
286
|
+
where: eq(col('model'), val(model)),
|
|
287
|
+
limit: lit(1)
|
|
288
|
+
}));
|
|
289
|
+
h.dim = Number(first?.bytes ?? 0) / 4;
|
|
290
|
+
if (!grow(h, tally(db, TABLE, eq(col('model'), val(model))))) {
|
|
291
|
+
drop(h);
|
|
292
|
+
copies.delete(db);
|
|
293
|
+
over.add(db);
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
for(let after = 0;;){
|
|
297
|
+
let rows = db.query(select({
|
|
298
|
+
cols: [
|
|
299
|
+
col('owner'),
|
|
300
|
+
col('vec')
|
|
301
|
+
],
|
|
302
|
+
from: table(TABLE),
|
|
303
|
+
where: and(gt(col('owner'), val(after)), eq(col('model'), val(model))),
|
|
304
|
+
order: [
|
|
305
|
+
col('owner')
|
|
306
|
+
],
|
|
307
|
+
limit: lit(PAGE)
|
|
308
|
+
}));
|
|
309
|
+
for (let r of rows){
|
|
310
|
+
if (!keep(h, Number(r.owner), r.vec)) return refuse(db, h);
|
|
311
|
+
}
|
|
312
|
+
if (rows.length < PAGE) break;
|
|
313
|
+
after = Number(rows[rows.length - 1].owner);
|
|
314
|
+
}
|
|
315
|
+
// The copy is the table now, so what the set named is in it.
|
|
316
|
+
if (owned(db) && dirty(db, model).size) h.n = clear(db);
|
|
317
|
+
return h;
|
|
318
|
+
};
|
|
319
|
+
// A copy that will not fit: dropped, and `db` never held again.
|
|
320
|
+
let refuse = (db, h)=>{
|
|
321
|
+
drop(h);
|
|
322
|
+
copies.delete(db);
|
|
323
|
+
over.add(db);
|
|
324
|
+
return null;
|
|
325
|
+
};
|
|
326
|
+
// Whether this database journals its vectors, asked again once its schema
|
|
327
|
+
// changes: a file a process of an older schema opened has no journal yet.
|
|
328
|
+
let journals = new WeakMap();
|
|
329
|
+
let journaled = (db)=>{
|
|
330
|
+
let version = db.revision('schema');
|
|
331
|
+
let had = journals.get(db);
|
|
332
|
+
if (had?.version == version) return had.has;
|
|
333
|
+
let has = !!db.query(select({
|
|
334
|
+
cols: [
|
|
335
|
+
col('name')
|
|
336
|
+
],
|
|
337
|
+
from: table('sqlite_master'),
|
|
338
|
+
where: eq(col('name'), val(JOURNAL))
|
|
339
|
+
}))[0];
|
|
340
|
+
journals.set(db, {
|
|
341
|
+
version,
|
|
342
|
+
has
|
|
343
|
+
});
|
|
344
|
+
return has;
|
|
345
|
+
};
|
|
346
|
+
// The last change the journal holds, 0 before the first.
|
|
347
|
+
let newest = (db)=>Number(db.query(select({
|
|
348
|
+
cols: [
|
|
349
|
+
as(fn('max', col('seq')), 'n')
|
|
350
|
+
],
|
|
351
|
+
from: table(JOURNAL)
|
|
352
|
+
}))[0]?.n ?? 0);
|
|
353
|
+
// Shared storage's vectors under `model`, from their codes: the journal's
|
|
354
|
+
// newest change read first, so whatever is written while the pages are read
|
|
355
|
+
// is a change past it, which the next search folds in. Null where some vector
|
|
356
|
+
// has no codes yet or there are two models' vectors, which the native scan
|
|
357
|
+
// answers until the sweep has coded them.
|
|
358
|
+
let loadCodes = (db, model)=>{
|
|
359
|
+
if (!complete(db) || only(db) != model) return null;
|
|
360
|
+
let was = copies.get(db);
|
|
361
|
+
if (was) drop(was);
|
|
362
|
+
let h = {
|
|
363
|
+
model,
|
|
364
|
+
dim: 0,
|
|
365
|
+
shared: true,
|
|
366
|
+
n: newest(db),
|
|
367
|
+
size: 0,
|
|
368
|
+
ids: new Int32Array(0),
|
|
369
|
+
scales: new Float32Array(0),
|
|
370
|
+
codes: new Int8Array(0),
|
|
371
|
+
slot: new Map()
|
|
372
|
+
};
|
|
373
|
+
touch(h);
|
|
374
|
+
copies.set(db, h);
|
|
375
|
+
let [first] = db.query(select({
|
|
376
|
+
cols: [
|
|
377
|
+
as(fn('length', col('code')), 'bytes')
|
|
378
|
+
],
|
|
379
|
+
from: table(CODE),
|
|
380
|
+
limit: lit(1)
|
|
381
|
+
}));
|
|
382
|
+
h.dim = Number(first?.bytes ?? 0);
|
|
383
|
+
if (!grow(h, tally(db, CODE))) return refuse(db, h);
|
|
384
|
+
for(let after = 0;;){
|
|
385
|
+
let rows = db.query(select({
|
|
386
|
+
cols: [
|
|
387
|
+
col('owner'),
|
|
388
|
+
col('code')
|
|
389
|
+
],
|
|
390
|
+
from: table(CODE),
|
|
391
|
+
where: gt(col('owner'), val(after)),
|
|
392
|
+
order: [
|
|
393
|
+
col('owner')
|
|
394
|
+
],
|
|
395
|
+
limit: lit(PAGE)
|
|
396
|
+
}));
|
|
397
|
+
for (let r of rows){
|
|
398
|
+
if (!kept(h, Number(r.owner), r.code)) return refuse(db, h);
|
|
399
|
+
}
|
|
400
|
+
if (rows.length < PAGE) break;
|
|
401
|
+
after = Number(rows[rows.length - 1].owner);
|
|
402
|
+
}
|
|
403
|
+
return h;
|
|
404
|
+
};
|
|
405
|
+
// A copy of shared storage brought to the journal's newest change: each owner
|
|
406
|
+
// it names as its vector stands now, coded from its floats, or forgotten where
|
|
407
|
+
// it has none under the copy's model. Null where the copy has to load again:
|
|
408
|
+
// more changes than FOLLOW, or a first one past the next number, which says
|
|
409
|
+
// the sweep trimmed changes this copy had not read.
|
|
410
|
+
let follow = (db, h)=>{
|
|
411
|
+
let rows = db.query(select({
|
|
412
|
+
cols: [
|
|
413
|
+
col('seq'),
|
|
414
|
+
col('owner')
|
|
415
|
+
],
|
|
416
|
+
from: table(JOURNAL),
|
|
417
|
+
where: gt(col('seq'), val(h.n)),
|
|
418
|
+
order: [
|
|
419
|
+
col('seq')
|
|
420
|
+
],
|
|
421
|
+
limit: lit(FOLLOW + 1)
|
|
422
|
+
}));
|
|
423
|
+
if (!rows.length) return h;
|
|
424
|
+
if (rows.length > FOLLOW || Number(rows[0].seq) != h.n + 1) return null;
|
|
425
|
+
let owners = [
|
|
426
|
+
...new Set(rows.map((r)=>Number(r.owner)))
|
|
427
|
+
];
|
|
428
|
+
let now = new Map(db.query(select({
|
|
429
|
+
cols: [
|
|
430
|
+
col('owner'),
|
|
431
|
+
col('model'),
|
|
432
|
+
col('vec')
|
|
433
|
+
],
|
|
434
|
+
from: table(TABLE),
|
|
435
|
+
where: among(col('owner'), owners.map((o)=>val(o)))
|
|
436
|
+
})).map((r)=>[
|
|
437
|
+
Number(r.owner),
|
|
438
|
+
r
|
|
439
|
+
]));
|
|
440
|
+
for (let owner of owners){
|
|
441
|
+
let r = now.get(owner);
|
|
442
|
+
if (r?.model != h.model) lose(h, owner);
|
|
443
|
+
else if (!keep(h, owner, r.vec)) return refuse(db, h);
|
|
444
|
+
}
|
|
445
|
+
h.n = Number(rows[rows.length - 1].seq);
|
|
446
|
+
return h;
|
|
447
|
+
};
|
|
448
|
+
// This process's copy of shared storage's vectors under `model`, brought up
|
|
449
|
+
// to date, or loaded where it has none, it is another model's, or it fell
|
|
450
|
+
// too far behind.
|
|
451
|
+
let followed = (db, model)=>{
|
|
452
|
+
if (!journaled(db)) return null;
|
|
453
|
+
let had = copies.get(db);
|
|
454
|
+
let h = had?.model == model ? follow(db, had) : null;
|
|
455
|
+
if (over.has(db)) return null;
|
|
456
|
+
return h ?? loadCodes(db, model);
|
|
457
|
+
};
|
|
458
|
+
/**
|
|
459
|
+
* This process's copy of `db`'s vectors under `model`, loaded if it has none
|
|
460
|
+
* or its copy is from an older build, and brought up to date; null where the
|
|
461
|
+
* vectors are not held: more than {@link HELD} of them ({@link SHARED} on
|
|
462
|
+
* shared storage), or a shared file whose codes or journal are not there yet.
|
|
463
|
+
*/ export let hold = (db, model)=>{
|
|
464
|
+
if (over.has(db)) return null;
|
|
465
|
+
let h;
|
|
466
|
+
if (db.ownership == 'shared') h = followed(db, model);
|
|
467
|
+
else {
|
|
468
|
+
let had = copies.get(db);
|
|
469
|
+
h = had && had.model == model && had.n == current(db).n ? had : load(db, model);
|
|
470
|
+
}
|
|
471
|
+
if (!h) return null;
|
|
472
|
+
touch(h);
|
|
473
|
+
return h;
|
|
474
|
+
};
|
|
475
|
+
/**
|
|
476
|
+
* Fold what the dirty set names into this process's copy and clear the set:
|
|
477
|
+
* what a sweep pass wrote, from the process that wrote it (./sweep.ts
|
|
478
|
+
* `drain`). On shared storage, where each process's copy reads the journal
|
|
479
|
+
* itself, trim the journal to its newest {@link FOLLOW} changes instead.
|
|
480
|
+
*/ export let absorb = (db)=>{
|
|
481
|
+
if (db.ownership == 'shared') return trim(db);
|
|
482
|
+
if (!owned(db)) return;
|
|
483
|
+
let h = copies.get(db);
|
|
484
|
+
// Until a search holds a copy, there are no codes to refresh. Settle the
|
|
485
|
+
// dirty owners and invalidate any other copy without reading their vectors
|
|
486
|
+
// or the build number nobody here needs.
|
|
487
|
+
if (!h) {
|
|
488
|
+
if (tally(db, DIRTY)) advance(db);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
let now = current(db).n;
|
|
492
|
+
let set = dirty(db, h.model);
|
|
493
|
+
if (!set.size) return;
|
|
494
|
+
if (h.n == now) {
|
|
495
|
+
for (let [owner, vec] of set){
|
|
496
|
+
if (!vec) lose(h, owner);
|
|
497
|
+
else if (!keep(h, owner, vec)) {
|
|
498
|
+
drop(h);
|
|
499
|
+
copies.delete(db);
|
|
500
|
+
over.add(db);
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
let n = clear(db);
|
|
506
|
+
if (h.n == now) h.n = n;
|
|
507
|
+
};
|
|
508
|
+
// The journal past its newest FOLLOW changes deleted: a copy further behind
|
|
509
|
+
// than that loads again.
|
|
510
|
+
let trim = (db)=>{
|
|
511
|
+
if (!journaled(db)) return;
|
|
512
|
+
let cut = newest(db) - FOLLOW;
|
|
513
|
+
if (cut <= 0) return;
|
|
514
|
+
db.query({
|
|
515
|
+
t: 'delete',
|
|
516
|
+
from: JOURNAL,
|
|
517
|
+
where: not(gt(col('seq'), val(cut)))
|
|
518
|
+
});
|
|
519
|
+
};
|
|
520
|
+
// The `m` best of the scored, best first: the highest score, and for equal
|
|
521
|
+
// ones the lower owner id, as the scan breaks a tie.
|
|
522
|
+
let top = (owners, sims, m)=>{
|
|
523
|
+
let worse = (a, b)=>sims[a] < sims[b] || sims[a] == sims[b] && owners[a] > owners[b];
|
|
524
|
+
let heap = [];
|
|
525
|
+
let sift = (i)=>{
|
|
526
|
+
for(;;){
|
|
527
|
+
let c = 2 * i + 1;
|
|
528
|
+
if (c >= heap.length) return;
|
|
529
|
+
if (c + 1 < heap.length && worse(heap[c + 1], heap[c])) c++;
|
|
530
|
+
if (!worse(heap[c], heap[i])) return;
|
|
531
|
+
[heap[c], heap[i]] = [
|
|
532
|
+
heap[i],
|
|
533
|
+
heap[c]
|
|
534
|
+
];
|
|
535
|
+
i = c;
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
for(let k = 0; k < owners.length; k++){
|
|
539
|
+
if (heap.length < m) {
|
|
540
|
+
heap.push(k);
|
|
541
|
+
for(let i = heap.length - 1; i;){
|
|
542
|
+
let p = i - 1 >> 1;
|
|
543
|
+
if (!worse(heap[i], heap[p])) break;
|
|
544
|
+
[heap[i], heap[p]] = [
|
|
545
|
+
heap[p],
|
|
546
|
+
heap[i]
|
|
547
|
+
];
|
|
548
|
+
i = p;
|
|
549
|
+
}
|
|
550
|
+
} else if (worse(heap[0], k)) {
|
|
551
|
+
heap[0] = k;
|
|
552
|
+
sift(0);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return heap.sort((a, b)=>worse(a, b) ? 1 : worse(b, a) ? -1 : 0);
|
|
556
|
+
};
|
|
557
|
+
// Which of `owners` stand as neighbours, with their eids and their vectors as
|
|
558
|
+
// stored: an entity that is not buried, whose vector is still in `model`'s
|
|
559
|
+
// space, and one the screen admits. Driven by the list, so each candidate
|
|
560
|
+
// costs one read of its entity, its vector and its tombstone.
|
|
561
|
+
let o = at('o'), j = at('j');
|
|
562
|
+
let standing = (db, model, owners, within)=>new Map(db.query(select({
|
|
563
|
+
cols: [
|
|
564
|
+
as(o('id'), 'owner'),
|
|
565
|
+
as(o('eid'), 'eid'),
|
|
566
|
+
as(e('model'), 'model'),
|
|
567
|
+
as(e('vec'), 'vec')
|
|
568
|
+
],
|
|
569
|
+
from: from(each(owners), 'j'),
|
|
570
|
+
joins: [
|
|
571
|
+
join(table('entity', 'o'), eq(o('id'), j('value'))),
|
|
572
|
+
join(table(TABLE, 'e'), eq(e('owner'), o('id')))
|
|
573
|
+
],
|
|
574
|
+
where: and(not(exists(select({
|
|
575
|
+
cols: [
|
|
576
|
+
lit(1)
|
|
577
|
+
],
|
|
578
|
+
from: table('tombstone', 't'),
|
|
579
|
+
where: eq(col('entity', 't'), o('id'))
|
|
580
|
+
}))), ...within ? [
|
|
581
|
+
admitted(within, o('id'))
|
|
582
|
+
] : [])
|
|
583
|
+
})).flatMap((r)=>r.model == model ? [
|
|
584
|
+
[
|
|
585
|
+
Number(r.owner),
|
|
586
|
+
{
|
|
587
|
+
eid: String(r.eid),
|
|
588
|
+
vec: r.vec
|
|
589
|
+
}
|
|
590
|
+
]
|
|
591
|
+
] : []));
|
|
592
|
+
/**
|
|
593
|
+
* The `limit` nearest to `query` in a copy, most similar first: every held
|
|
594
|
+
* vector's codes scanned, what the dirty set names coded from its rows, the
|
|
595
|
+
* best tested against the graph a few at a time until {@link RESCORE} of
|
|
596
|
+
* them stand (reaching further while too few do), and those ranked by the
|
|
597
|
+
* exact cosine of their stored vectors.
|
|
598
|
+
*/ export let ranked = (db, h, query, opts)=>{
|
|
599
|
+
// A shared copy folded its changes in as it was held.
|
|
600
|
+
let fresh = h.shared ? new Map() : dirty(db, h.model);
|
|
601
|
+
let all = query.length == h.dim ? scores(query, h.codes, h.scales, h.size) : new Float64Array(h.size);
|
|
602
|
+
let owners = new Int32Array(h.size + fresh.size);
|
|
603
|
+
let sims = new Float64Array(h.size + fresh.size);
|
|
604
|
+
let count = 0;
|
|
605
|
+
let score = (owner, sim)=>{
|
|
606
|
+
if (owner == opts.without) return;
|
|
607
|
+
owners[count] = owner;
|
|
608
|
+
sims[count++] = sim;
|
|
609
|
+
};
|
|
610
|
+
for(let i = 0; i < h.size; i++){
|
|
611
|
+
if (!fresh.has(h.ids[i])) score(h.ids[i], all[i]);
|
|
612
|
+
}
|
|
613
|
+
let one = new Int8Array(h.dim), scale = new Float32Array(1);
|
|
614
|
+
for (let [owner, vec] of fresh){
|
|
615
|
+
if (vec?.byteLength != h.dim * 4 || query.length != h.dim) continue;
|
|
616
|
+
scale[0] = code(floats(vec), one);
|
|
617
|
+
score(owner, scores(query, one, scale, 1)[0]);
|
|
618
|
+
}
|
|
619
|
+
owners = owners.subarray(0, count);
|
|
620
|
+
sims = sims.subarray(0, count);
|
|
621
|
+
// The ranking narrowed to what a screen admits, less what was tested.
|
|
622
|
+
let narrow = (admits, tested = new Set())=>{
|
|
623
|
+
let rest = [
|
|
624
|
+
...owners.keys()
|
|
625
|
+
].filter((k)=>!tested.has(k) && admits.has(owners[k]));
|
|
626
|
+
[owners, sims] = [
|
|
627
|
+
Int32Array.from(rest, (k)=>owners[k]),
|
|
628
|
+
Float64Array.from(rest, (k)=>sims[k])
|
|
629
|
+
];
|
|
630
|
+
};
|
|
631
|
+
let want = Math.max(RESCORE, opts.limit);
|
|
632
|
+
let found = [];
|
|
633
|
+
let within = opts.within;
|
|
634
|
+
// A screen that admits few is read whole first, and the ranking is only
|
|
635
|
+
// what it admits: asked of each candidate instead, it reads every row the
|
|
636
|
+
// candidate's test touches. A person's 7,228 earlier words among 316k
|
|
637
|
+
// vectors read whole in 87 ms, and asked of the 1,600 nearest took 0.6 s
|
|
638
|
+
// with the pages in memory and 7.9 s with them on disk.
|
|
639
|
+
let admits = within && few(db, within, owners.length);
|
|
640
|
+
if (admits) {
|
|
641
|
+
narrow(admits);
|
|
642
|
+
within = undefined;
|
|
643
|
+
}
|
|
644
|
+
for(let seen = 0, reach = want; found.length < want;){
|
|
645
|
+
let best = top(owners, sims, Math.min(reach, owners.length));
|
|
646
|
+
if (best.length == seen) break;
|
|
647
|
+
let batch = best.slice(seen);
|
|
648
|
+
let rows = standing(db, h.model, batch.map((k)=>owners[k]), within);
|
|
649
|
+
for (let k of batch){
|
|
650
|
+
let row = rows.get(owners[k]);
|
|
651
|
+
if (!row || found.length == want) continue;
|
|
652
|
+
let similarity = cosine(query, floats(row.vec));
|
|
653
|
+
found.push({
|
|
654
|
+
entity: row.eid,
|
|
655
|
+
owner: owners[k],
|
|
656
|
+
similarity
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
seen = best.length;
|
|
660
|
+
reach *= 4;
|
|
661
|
+
// A broad screen that admits few of the nearest costs a walk through most
|
|
662
|
+
// of the ranking. Once the rate so far says the walk would test more than
|
|
663
|
+
// half of it, the screen is read whole, and the rest of the ranking is
|
|
664
|
+
// what it admits, all of it below everything already tested.
|
|
665
|
+
let rate = Math.max(found.length, 1) / seen;
|
|
666
|
+
if (within && found.length < want && want / rate > owners.length / 2) {
|
|
667
|
+
narrow(new Set(db.query(select({
|
|
668
|
+
cols: [
|
|
669
|
+
col('id', 's')
|
|
670
|
+
],
|
|
671
|
+
from: from(within, 's')
|
|
672
|
+
})).map((r)=>Number(r.id))), new Set(best));
|
|
673
|
+
within = undefined;
|
|
674
|
+
seen = 0;
|
|
675
|
+
reach = want - found.length;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return found.filter((n)=>n.similarity >= opts.floor).sort((a, b)=>b.similarity - a.similarity || a.owner - b.owner).slice(0, opts.limit);
|
|
679
|
+
};
|
|
680
|
+
//# sourceMappingURL=held.js.map
|