@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/native.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// Exact sqlite-vector scans over stored vectors, or over their int8 codes once
|
|
2
|
+
// every vector has them (./coded.ts), the pool then scored from the floats
|
|
3
|
+
// (./near.ts). Native distance work stays inside the engine; no derived index
|
|
4
|
+
// is rebuilt under the graph lock.
|
|
5
|
+
import { and, as, call, col, count, eq, exists, fn, from, lit, member, not, select, sub, table, val } from "@yaks/sql";
|
|
6
|
+
import { BUILD, CODE, DIRTY, TABLE } from "./ddl.js";
|
|
7
|
+
import { coded, pack } from "./vector.js";
|
|
8
|
+
import { complete } from "./coded.js";
|
|
9
|
+
import { sparse } from "./sparse.js";
|
|
10
|
+
/** Explicit one-time installation: back up the database before calling this
|
|
11
|
+
* on shared storage. The adapter loads its vector facility, which adds the
|
|
12
|
+
* extension's metadata table to the database. */ export let install = (db)=>{
|
|
13
|
+
if (!db.facilities?.vector) {
|
|
14
|
+
throw new Error('sqlite-vector extension is unavailable on this storage');
|
|
15
|
+
}
|
|
16
|
+
db.facilities.vector();
|
|
17
|
+
};
|
|
18
|
+
/** How many candidates a search scores exactly, for the `need` nearest. */ export let pool = (need)=>Math.max(128, 32 * need);
|
|
19
|
+
/** Shared generation metadata, as any connection reads it: read once while
|
|
20
|
+
* its table's rows stand. */ let builds = new WeakMap();
|
|
21
|
+
export let current = (db)=>{
|
|
22
|
+
let at = db.revision('data', BUILD);
|
|
23
|
+
let held = builds.get(db);
|
|
24
|
+
if (held?.at !== at) {
|
|
25
|
+
let row = db.query(select({
|
|
26
|
+
from: table(BUILD)
|
|
27
|
+
}))[0] ?? {};
|
|
28
|
+
builds.set(db, held = {
|
|
29
|
+
at,
|
|
30
|
+
build: {
|
|
31
|
+
n: Number(row.n ?? 0),
|
|
32
|
+
model: row.model ?? null,
|
|
33
|
+
dim: Number(row.dim ?? 0),
|
|
34
|
+
rows: Number(row.rows ?? 0)
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
...held.build
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
let tally = (db, name)=>Number(db.query(select({
|
|
43
|
+
cols: [
|
|
44
|
+
as(count(), 'n')
|
|
45
|
+
],
|
|
46
|
+
from: table(name)
|
|
47
|
+
}))[0].n);
|
|
48
|
+
/** Whether sqlite-vector metadata already exists on this database. */ let installations = new WeakMap();
|
|
49
|
+
export let installed = (db)=>{
|
|
50
|
+
let version = db.revision('schema');
|
|
51
|
+
let kept = installations.get(db);
|
|
52
|
+
if (kept?.version == version) return kept.installed;
|
|
53
|
+
let found = !!db.query(select({
|
|
54
|
+
cols: [
|
|
55
|
+
col('name')
|
|
56
|
+
],
|
|
57
|
+
from: table('sqlite_master'),
|
|
58
|
+
where: eq(col('name'), val('_sqliteai_vector'))
|
|
59
|
+
}))[0];
|
|
60
|
+
installations.set(db, {
|
|
61
|
+
version,
|
|
62
|
+
installed: found
|
|
63
|
+
});
|
|
64
|
+
return found;
|
|
65
|
+
};
|
|
66
|
+
/** The model every vector is under, or null while there are two (or none).
|
|
67
|
+
* One model means one vector width; mixed spaces use the ordinary reader.
|
|
68
|
+
* Separate aggregates each seek an edge of the model index; together SQLite
|
|
69
|
+
* scans every model, even when the answer has not changed. */ export let only = (db)=>{
|
|
70
|
+
let edge = (f)=>sub(select({
|
|
71
|
+
cols: [
|
|
72
|
+
fn(f, col('model'))
|
|
73
|
+
],
|
|
74
|
+
from: table(TABLE)
|
|
75
|
+
}));
|
|
76
|
+
let row = db.query(select({
|
|
77
|
+
cols: [
|
|
78
|
+
as(edge('min'), 'lo'),
|
|
79
|
+
as(edge('max'), 'hi')
|
|
80
|
+
]
|
|
81
|
+
}))[0];
|
|
82
|
+
return row?.lo != null && row.lo == row.hi ? String(row.lo) : null;
|
|
83
|
+
};
|
|
84
|
+
/** Vector space and generation metadata for diagnostics. */ export let state = (db)=>({
|
|
85
|
+
installed: installed(db),
|
|
86
|
+
build: current(db),
|
|
87
|
+
model: only(db),
|
|
88
|
+
dirty: db.ownership == 'exclusive' ? tally(db, DIRTY) : 0
|
|
89
|
+
});
|
|
90
|
+
let conns = new WeakMap();
|
|
91
|
+
// This connection's state, loading the extension the first time, or null
|
|
92
|
+
// where it cannot: statements with no vector facility, or a database it was
|
|
93
|
+
// never installed on.
|
|
94
|
+
let conn = (db)=>{
|
|
95
|
+
let had = conns.get(db);
|
|
96
|
+
if (had) return had;
|
|
97
|
+
if (!db.facilities?.vector || !installed(db)) return null;
|
|
98
|
+
install(db);
|
|
99
|
+
let made = {
|
|
100
|
+
dim: 0,
|
|
101
|
+
codes: 0
|
|
102
|
+
};
|
|
103
|
+
conns.set(db, made);
|
|
104
|
+
return made;
|
|
105
|
+
};
|
|
106
|
+
let ask = (db, name, ...args)=>db.query(select({
|
|
107
|
+
cols: [
|
|
108
|
+
as(fn(name, ...args.map(lit)), 'out')
|
|
109
|
+
]
|
|
110
|
+
}))[0]?.out;
|
|
111
|
+
// The table set up on this connection at a dimension, once: sqlite-vector
|
|
112
|
+
// reads its metadata then, and a connection cannot take a second dimension.
|
|
113
|
+
let init = (db, c, dim)=>{
|
|
114
|
+
if (!c.dim) {
|
|
115
|
+
ask(db, 'vector_init', TABLE, 'vec', `type=FLOAT32,dimension=${dim},distance=COSINE`);
|
|
116
|
+
c.dim = dim;
|
|
117
|
+
}
|
|
118
|
+
return c.dim == dim;
|
|
119
|
+
};
|
|
120
|
+
// The codes' table set up the same way, at the floats' dimension.
|
|
121
|
+
let initCodes = (db, c, dim)=>{
|
|
122
|
+
if (!c.codes) {
|
|
123
|
+
ask(db, 'vector_init', CODE, 'code', `type=INT8,dimension=${dim},distance=COSINE`);
|
|
124
|
+
c.codes = dim;
|
|
125
|
+
}
|
|
126
|
+
return c.codes == dim;
|
|
127
|
+
};
|
|
128
|
+
/** Register the vector shape once, before read-only connections use it. */ export let prepare = (db, dim)=>{
|
|
129
|
+
let c = conn(db);
|
|
130
|
+
if (!c || c.dim) return false;
|
|
131
|
+
if (dim == null) {
|
|
132
|
+
let [row] = db.query(select({
|
|
133
|
+
cols: [
|
|
134
|
+
as(fn('length', col('vec')), 'bytes')
|
|
135
|
+
],
|
|
136
|
+
from: table(TABLE),
|
|
137
|
+
limit: lit(1)
|
|
138
|
+
}));
|
|
139
|
+
dim = Number(row?.bytes ?? 0) / 4;
|
|
140
|
+
}
|
|
141
|
+
return !!dim && init(db, c, dim);
|
|
142
|
+
};
|
|
143
|
+
/** Whether this owner is admitted by the selection's keyed predicate. */ export let admitted = member;
|
|
144
|
+
/** How many entities a screen may admit and still be read whole, rather than
|
|
145
|
+
* scanning the whole corpus. */ export let FEW = 5000;
|
|
146
|
+
/** The ids a screen admits, where they are few absolutely ({@link FEW}) or
|
|
147
|
+
* relative to a corpus of `corpus` vectors (an eighth of it); null for a
|
|
148
|
+
* broader screen. Reading a sparse screen whole is one statement on its own
|
|
149
|
+
* indexes, cheaper than reading unrelated vector payloads or asking it of
|
|
150
|
+
* each candidate, even when it has outgrown {@link FEW}. */ export let few = (db, within, corpus)=>{
|
|
151
|
+
let limit = Math.max(FEW, Math.floor(corpus / 8));
|
|
152
|
+
let ids = db.query(select({
|
|
153
|
+
cols: [
|
|
154
|
+
col('id', 's')
|
|
155
|
+
],
|
|
156
|
+
from: from(within, 's'),
|
|
157
|
+
limit: lit(limit + 1)
|
|
158
|
+
}));
|
|
159
|
+
return ids.length > limit ? null : new Set(ids.map((r)=>Number(r.id)));
|
|
160
|
+
};
|
|
161
|
+
/** How many more of the nearest a native search draws when a screen is asked
|
|
162
|
+
* of them: about one in eight of the drawn has to be admitted. */ export let WIDEN = 8;
|
|
163
|
+
/** Native candidates: the nearest pool the screen admits, by the floats or by
|
|
164
|
+
* the codes, which the floats then rank. Small screens rank only admitted
|
|
165
|
+
* codes, or read their floats when the codes are incomplete. */ export let candidates = (db, query, opts)=>{
|
|
166
|
+
let c = conn(db);
|
|
167
|
+
if (!c) return null;
|
|
168
|
+
if (only(db) != opts.model || !init(db, c, query.length)) return null;
|
|
169
|
+
let codes = complete(db) && initCodes(db, c, query.length);
|
|
170
|
+
if (opts.within && few(db, opts.within, tally(db, TABLE))) {
|
|
171
|
+
return codes ? sparse(db, query, opts.within, pool(opts.need)) : null;
|
|
172
|
+
}
|
|
173
|
+
// The codes, where every vector has them: a fifth of the bytes to read.
|
|
174
|
+
let [name, column, probe] = codes ? [
|
|
175
|
+
CODE,
|
|
176
|
+
'code',
|
|
177
|
+
coded(query)
|
|
178
|
+
] : [
|
|
179
|
+
TABLE,
|
|
180
|
+
'vec',
|
|
181
|
+
pack(query)
|
|
182
|
+
];
|
|
183
|
+
let v = (name)=>col(name, 'v');
|
|
184
|
+
let r = (name)=>col(name, 'r');
|
|
185
|
+
let nearest = (draw)=>select({
|
|
186
|
+
cols: [
|
|
187
|
+
as(v('id'), 'owner'),
|
|
188
|
+
as(v('distance'), 'distance')
|
|
189
|
+
],
|
|
190
|
+
from: call('vector_full_scan', [
|
|
191
|
+
lit(name),
|
|
192
|
+
lit(column),
|
|
193
|
+
val(probe)
|
|
194
|
+
], 'v'),
|
|
195
|
+
order: [
|
|
196
|
+
v('distance'),
|
|
197
|
+
v('id')
|
|
198
|
+
],
|
|
199
|
+
limit: val(draw)
|
|
200
|
+
});
|
|
201
|
+
let alive = not(exists(select({
|
|
202
|
+
cols: [
|
|
203
|
+
lit(1)
|
|
204
|
+
],
|
|
205
|
+
from: table('tombstone', 't'),
|
|
206
|
+
where: eq(col('entity', 't'), r('owner'))
|
|
207
|
+
})));
|
|
208
|
+
// The screen and the tombstones are probed after the scan's cut, on the
|
|
209
|
+
// nearest few hundred rather than on every stored vector: a screen asked of
|
|
210
|
+
// each of 310k vectors spent 2.7 s on a CPU and 7.6 s reading the pages its
|
|
211
|
+
// probes touched. Filtering keeps the scan's order, so the first `cut`
|
|
212
|
+
// admitted are the screened scan's own. Too few admitted (a thin screen, a
|
|
213
|
+
// deleted neighbour) draws WIDEN times as many, up to the whole corpus.
|
|
214
|
+
let cut = pool(opts.need);
|
|
215
|
+
let corpus = tally(db, TABLE);
|
|
216
|
+
for(let draw = opts.within ? cut * WIDEN : cut;; draw *= WIDEN){
|
|
217
|
+
let rows = db.query(select({
|
|
218
|
+
cols: [
|
|
219
|
+
r('owner')
|
|
220
|
+
],
|
|
221
|
+
from: from(nearest(Math.min(draw, corpus)), 'r'),
|
|
222
|
+
where: and(alive, ...opts.within ? [
|
|
223
|
+
admitted(opts.within, r('owner'))
|
|
224
|
+
] : []),
|
|
225
|
+
order: [
|
|
226
|
+
r('distance'),
|
|
227
|
+
r('owner')
|
|
228
|
+
],
|
|
229
|
+
limit: val(cut)
|
|
230
|
+
}));
|
|
231
|
+
if (rows.length == cut || draw >= corpus) {
|
|
232
|
+
return rows.map((row)=>Number(row.owner));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
//# sourceMappingURL=native.js.map
|
package/native.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"native.js","sources":["./native.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,2EAA2E;AAC3E,8EAA8E;AAC9E,mCAAmC;AACnC,SACE,GAAG,EACH,EAAE,EACF,IAAI,EACJ,GAAG,EACH,KAAK,EACL,EAAE,EACF,MAAM,EACN,EAAE,EACF,IAAI,EACJ,GAAG,EACH,MAAM,EACN,GAAG,EAEH,MAAM,EAEN,GAAG,EACH,KAAK,EACL,GAAG,yBACwB;AAC7B,SAAS,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,mBAAkB;AACpD,SAAS,KAAK,EAAE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EAClC;EACA,wEAAwE;EACxE,4EAA4E;EAC5E,4EAA4E;EAC5E,uEAAuE;EACvE,2EAA2E;EAC3E,wEAAwE;EACxE,IAAI,MAAM,KAAK,KAAK,IAAI;EACxB,IAAI,SAAS,MAAM,IAAI;EACvB,IAAK,IAAI,OAAO,KAAK,MAAM,GAAG,MAAM,QAAQ,MAAM,QAAQ,MAAO;IAC/D,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO;MACzB,MAAM;QAAC,EAAE;OAAS;MAClB,MAAM,KAAK,QAAQ,KAAK,GAAG,CAAC,MAAM,UAAU;MAC5C,OAAO,IACL,UACG,KAAK,MAAM,GAAG;QAAC,SAAS,KAAK,MAAM,EAAE,EAAE;OAAU,GAAG,EAAE;MAE3D,OAAO;QAAC,EAAE;QAAa,EAAE;OAAS;MAClC,OAAO,IAAI;IACb;IACA,IAAI,KAAK,MAAM,IAAI,OAAO,QAAQ,QAAQ;MACxC,OAAO,KAAK,GAAG,CAAC,CAAC,MAAQ,OAAO,IAAI,KAAK;IAC3C;EACF;AACF,EAAC"}
|
package/native.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// Exact sqlite-vector scans over stored vectors, or over their int8 codes once
|
|
2
|
+
// every vector has them (./coded.ts), the pool then scored from the floats
|
|
3
|
+
// (./near.ts). Native distance work stays inside the engine; no derived index
|
|
4
|
+
// is rebuilt under the graph lock.
|
|
5
|
+
import {
|
|
6
|
+
and,
|
|
7
|
+
as,
|
|
8
|
+
call,
|
|
9
|
+
col,
|
|
10
|
+
count,
|
|
11
|
+
eq,
|
|
12
|
+
exists,
|
|
13
|
+
fn,
|
|
14
|
+
from,
|
|
15
|
+
lit,
|
|
16
|
+
member,
|
|
17
|
+
not,
|
|
18
|
+
type Raw,
|
|
19
|
+
select,
|
|
20
|
+
type Statements,
|
|
21
|
+
sub,
|
|
22
|
+
table,
|
|
23
|
+
val,
|
|
24
|
+
} from '@yaks/sql'
|
|
25
|
+
import { BUILD, CODE, DIRTY, TABLE } from './ddl.js'
|
|
26
|
+
import { coded, pack } from './vector.js'
|
|
27
|
+
import { complete } from './coded.js'
|
|
28
|
+
import { sparse } from './sparse.js'
|
|
29
|
+
|
|
30
|
+
/** Explicit one-time installation: back up the database before calling this
|
|
31
|
+
* on shared storage. The adapter loads its vector facility, which adds the
|
|
32
|
+
* extension's metadata table to the database. */
|
|
33
|
+
export let install = (db: Statements): void => {
|
|
34
|
+
if (!db.facilities?.vector) {
|
|
35
|
+
throw new Error('sqlite-vector extension is unavailable on this storage')
|
|
36
|
+
}
|
|
37
|
+
db.facilities.vector()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How many candidates a search scores exactly, for the `need` nearest. */
|
|
41
|
+
export let pool = (need: number): number => Math.max(128, 32 * need)
|
|
42
|
+
|
|
43
|
+
/** Which build of the index is current: its number (0 before the first), and
|
|
44
|
+
* the model, dimension and count of the vectors it was built from. */
|
|
45
|
+
export type Build = {
|
|
46
|
+
n: number
|
|
47
|
+
model: string | null
|
|
48
|
+
dim: number
|
|
49
|
+
rows: number
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Shared generation metadata, as any connection reads it: read once while
|
|
53
|
+
* its table's rows stand. */
|
|
54
|
+
let builds = new WeakMap<Statements, { at: number; build: Build }>()
|
|
55
|
+
export let current = (db: Statements): Build => {
|
|
56
|
+
let at = db.revision('data', BUILD)
|
|
57
|
+
let held = builds.get(db)
|
|
58
|
+
if (held?.at !== at) {
|
|
59
|
+
let row = db.query(select({ from: table(BUILD) }))[0] ?? {}
|
|
60
|
+
builds.set(
|
|
61
|
+
db,
|
|
62
|
+
held = {
|
|
63
|
+
at,
|
|
64
|
+
build: {
|
|
65
|
+
n: Number(row.n ?? 0),
|
|
66
|
+
model: (row.model as string | null) ?? null,
|
|
67
|
+
dim: Number(row.dim ?? 0),
|
|
68
|
+
rows: Number(row.rows ?? 0),
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
return { ...held.build }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let tally = (db: Statements, name: string): number =>
|
|
77
|
+
Number(db.query(select({ cols: [as(count(), 'n')], from: table(name) }))[0].n)
|
|
78
|
+
|
|
79
|
+
/** Whether sqlite-vector metadata already exists on this database. */
|
|
80
|
+
let installations = new WeakMap<
|
|
81
|
+
Statements,
|
|
82
|
+
{ version: number; installed: boolean }
|
|
83
|
+
>()
|
|
84
|
+
|
|
85
|
+
export let installed = (db: Statements): boolean => {
|
|
86
|
+
let version = db.revision('schema')
|
|
87
|
+
let kept = installations.get(db)
|
|
88
|
+
if (kept?.version == version) return kept.installed
|
|
89
|
+
let found = !!db.query(select({
|
|
90
|
+
cols: [col('name')],
|
|
91
|
+
from: table('sqlite_master'),
|
|
92
|
+
where: eq(col('name'), val('_sqliteai_vector')),
|
|
93
|
+
}))[0]
|
|
94
|
+
installations.set(db, { version, installed: found })
|
|
95
|
+
return found
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The model every vector is under, or null while there are two (or none).
|
|
99
|
+
* One model means one vector width; mixed spaces use the ordinary reader.
|
|
100
|
+
* Separate aggregates each seek an edge of the model index; together SQLite
|
|
101
|
+
* scans every model, even when the answer has not changed. */
|
|
102
|
+
export let only = (db: Statements): string | null => {
|
|
103
|
+
let edge = (f: string) =>
|
|
104
|
+
sub(select({ cols: [fn(f, col('model'))], from: table(TABLE) }))
|
|
105
|
+
let row = db.query(select({
|
|
106
|
+
cols: [as(edge('min'), 'lo'), as(edge('max'), 'hi')],
|
|
107
|
+
}))[0]
|
|
108
|
+
return row?.lo != null && row.lo == row.hi ? String(row.lo) : null
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** What a health check reads, from plain tables any connection can read. */
|
|
112
|
+
export type State = {
|
|
113
|
+
/** whether sqlite-vector was installed on this database */
|
|
114
|
+
installed: boolean
|
|
115
|
+
build: Build
|
|
116
|
+
/** the model every vector is under, or null while there are two (or none) */
|
|
117
|
+
model: string | null
|
|
118
|
+
/** how many vectors changed since the build */
|
|
119
|
+
dirty: number
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Vector space and generation metadata for diagnostics. */
|
|
123
|
+
export let state = (db: Statements): State => ({
|
|
124
|
+
installed: installed(db),
|
|
125
|
+
build: current(db),
|
|
126
|
+
model: only(db),
|
|
127
|
+
dirty: db.ownership == 'exclusive' ? tally(db, DIRTY) : 0,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
// The shapes registered on one connection: the floats', and the codes'.
|
|
131
|
+
type Conn = { dim: number; codes: number }
|
|
132
|
+
let conns = new WeakMap<Statements, Conn>()
|
|
133
|
+
|
|
134
|
+
// This connection's state, loading the extension the first time, or null
|
|
135
|
+
// where it cannot: statements with no vector facility, or a database it was
|
|
136
|
+
// never installed on.
|
|
137
|
+
let conn = (db: Statements): Conn | null => {
|
|
138
|
+
let had = conns.get(db)
|
|
139
|
+
if (had) return had
|
|
140
|
+
if (!db.facilities?.vector || !installed(db)) return null
|
|
141
|
+
install(db)
|
|
142
|
+
let made = { dim: 0, codes: 0 }
|
|
143
|
+
conns.set(db, made)
|
|
144
|
+
return made
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let ask = (
|
|
148
|
+
db: Statements,
|
|
149
|
+
name: string,
|
|
150
|
+
...args: (string | number)[]
|
|
151
|
+
) =>
|
|
152
|
+
db.query(select({
|
|
153
|
+
cols: [as(fn(name, ...args.map(lit)), 'out')],
|
|
154
|
+
}))[0]?.out
|
|
155
|
+
|
|
156
|
+
// The table set up on this connection at a dimension, once: sqlite-vector
|
|
157
|
+
// reads its metadata then, and a connection cannot take a second dimension.
|
|
158
|
+
let init = (db: Statements, c: Conn, dim: number): boolean => {
|
|
159
|
+
if (!c.dim) {
|
|
160
|
+
ask(
|
|
161
|
+
db,
|
|
162
|
+
'vector_init',
|
|
163
|
+
TABLE,
|
|
164
|
+
'vec',
|
|
165
|
+
`type=FLOAT32,dimension=${dim},distance=COSINE`,
|
|
166
|
+
)
|
|
167
|
+
c.dim = dim
|
|
168
|
+
}
|
|
169
|
+
return c.dim == dim
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The codes' table set up the same way, at the floats' dimension.
|
|
173
|
+
let initCodes = (db: Statements, c: Conn, dim: number): boolean => {
|
|
174
|
+
if (!c.codes) {
|
|
175
|
+
ask(
|
|
176
|
+
db,
|
|
177
|
+
'vector_init',
|
|
178
|
+
CODE,
|
|
179
|
+
'code',
|
|
180
|
+
`type=INT8,dimension=${dim},distance=COSINE`,
|
|
181
|
+
)
|
|
182
|
+
c.codes = dim
|
|
183
|
+
}
|
|
184
|
+
return c.codes == dim
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Register the vector shape once, before read-only connections use it. */
|
|
188
|
+
export let prepare = (db: Statements, dim?: number): boolean => {
|
|
189
|
+
let c = conn(db)
|
|
190
|
+
if (!c || c.dim) return false
|
|
191
|
+
if (dim == null) {
|
|
192
|
+
let [row] = db.query(select({
|
|
193
|
+
cols: [as(fn('length', col('vec')), 'bytes')],
|
|
194
|
+
from: table(TABLE),
|
|
195
|
+
limit: lit(1),
|
|
196
|
+
}))
|
|
197
|
+
dim = Number(row?.bytes ?? 0) / 4
|
|
198
|
+
}
|
|
199
|
+
return !!dim && init(db, c, dim)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Whether this owner is admitted by the selection's keyed predicate. */
|
|
203
|
+
export let admitted = member
|
|
204
|
+
|
|
205
|
+
/** How many entities a screen may admit and still be read whole, rather than
|
|
206
|
+
* scanning the whole corpus. */
|
|
207
|
+
export let FEW = 5000
|
|
208
|
+
|
|
209
|
+
/** The ids a screen admits, where they are few absolutely ({@link FEW}) or
|
|
210
|
+
* relative to a corpus of `corpus` vectors (an eighth of it); null for a
|
|
211
|
+
* broader screen. Reading a sparse screen whole is one statement on its own
|
|
212
|
+
* indexes, cheaper than reading unrelated vector payloads or asking it of
|
|
213
|
+
* each candidate, even when it has outgrown {@link FEW}. */
|
|
214
|
+
export let few = (
|
|
215
|
+
db: Statements,
|
|
216
|
+
within: Raw,
|
|
217
|
+
corpus: number,
|
|
218
|
+
): Set<number> | null => {
|
|
219
|
+
let limit = Math.max(FEW, Math.floor(corpus / 8))
|
|
220
|
+
let ids = db.query(select({
|
|
221
|
+
cols: [col('id', 's')],
|
|
222
|
+
from: from(within, 's'),
|
|
223
|
+
limit: lit(limit + 1),
|
|
224
|
+
}))
|
|
225
|
+
return ids.length > limit ? null : new Set(ids.map((r) => Number(r.id)))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** How many more of the nearest a native search draws when a screen is asked
|
|
229
|
+
* of them: about one in eight of the drawn has to be admitted. */
|
|
230
|
+
export let WIDEN = 8
|
|
231
|
+
|
|
232
|
+
/** Native candidates: the nearest pool the screen admits, by the floats or by
|
|
233
|
+
* the codes, which the floats then rank. Small screens rank only admitted
|
|
234
|
+
* codes, or read their floats when the codes are incomplete. */
|
|
235
|
+
export let candidates = (
|
|
236
|
+
db: Statements,
|
|
237
|
+
query: Float32Array,
|
|
238
|
+
opts: { model: string; need: number; within?: Raw },
|
|
239
|
+
): number[] | null => {
|
|
240
|
+
let c = conn(db)
|
|
241
|
+
if (!c) return null
|
|
242
|
+
if (only(db) != opts.model || !init(db, c, query.length)) return null
|
|
243
|
+
let codes = complete(db) && initCodes(db, c, query.length)
|
|
244
|
+
if (opts.within && few(db, opts.within, tally(db, TABLE))) {
|
|
245
|
+
return codes ? sparse(db, query, opts.within, pool(opts.need)) : null
|
|
246
|
+
}
|
|
247
|
+
// The codes, where every vector has them: a fifth of the bytes to read.
|
|
248
|
+
let [name, column, probe] = codes
|
|
249
|
+
? [CODE, 'code', coded(query)]
|
|
250
|
+
: [TABLE, 'vec', pack(query)]
|
|
251
|
+
let v = (name: string) => col(name, 'v')
|
|
252
|
+
let r = (name: string) => col(name, 'r')
|
|
253
|
+
let nearest = (draw: number) =>
|
|
254
|
+
select({
|
|
255
|
+
cols: [as(v('id'), 'owner'), as(v('distance'), 'distance')],
|
|
256
|
+
from: call('vector_full_scan', [lit(name), lit(column), val(probe)], 'v'),
|
|
257
|
+
order: [v('distance'), v('id')],
|
|
258
|
+
limit: val(draw),
|
|
259
|
+
})
|
|
260
|
+
let alive = not(exists(select({
|
|
261
|
+
cols: [lit(1)],
|
|
262
|
+
from: table('tombstone', 't'),
|
|
263
|
+
where: eq(col('entity', 't'), r('owner')),
|
|
264
|
+
})))
|
|
265
|
+
// The screen and the tombstones are probed after the scan's cut, on the
|
|
266
|
+
// nearest few hundred rather than on every stored vector: a screen asked of
|
|
267
|
+
// each of 310k vectors spent 2.7 s on a CPU and 7.6 s reading the pages its
|
|
268
|
+
// probes touched. Filtering keeps the scan's order, so the first `cut`
|
|
269
|
+
// admitted are the screened scan's own. Too few admitted (a thin screen, a
|
|
270
|
+
// deleted neighbour) draws WIDEN times as many, up to the whole corpus.
|
|
271
|
+
let cut = pool(opts.need)
|
|
272
|
+
let corpus = tally(db, TABLE)
|
|
273
|
+
for (let draw = opts.within ? cut * WIDEN : cut;; draw *= WIDEN) {
|
|
274
|
+
let rows = db.query(select({
|
|
275
|
+
cols: [r('owner')],
|
|
276
|
+
from: from(nearest(Math.min(draw, corpus)), 'r'),
|
|
277
|
+
where: and(
|
|
278
|
+
alive,
|
|
279
|
+
...opts.within ? [admitted(opts.within, r('owner'))] : [],
|
|
280
|
+
),
|
|
281
|
+
order: [r('distance'), r('owner')],
|
|
282
|
+
limit: val(cut),
|
|
283
|
+
}))
|
|
284
|
+
if (rows.length == cut || draw >= corpus) {
|
|
285
|
+
return rows.map((row) => Number(row.owner))
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
package/near.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Cosine ranking over canonical vectors. A copy held in memory (./held.ts)
|
|
2
|
+
// selects the candidates where there is one; the native engine, on a shared
|
|
3
|
+
// file whose copy is not held yet. Every candidate is scored from its current
|
|
4
|
+
// float vector before the final cut.
|
|
5
|
+
//
|
|
6
|
+
// A {@link Screen} is the other half of "nearest": nearest among what. The
|
|
7
|
+
// eight nearest entities of any kind are the wrong eight for `.near=X&.memory`
|
|
8
|
+
// — intersecting them with "and a memory" usually leaves nothing — so the rest
|
|
9
|
+
// of the query comes in as a statement selecting the ids it admits, only those
|
|
10
|
+
// vectors are candidates, and the cut to `limit` happens after. Filter, then
|
|
11
|
+
// rank, then cut.
|
|
12
|
+
//
|
|
13
|
+
// A neighbour carries its integer owner id beside its eid for SQL ranking.
|
|
14
|
+
import { among, and, as, at, col, eq, exists, join, lit, not, oneOf, select, table, val } from "@yaks/sql";
|
|
15
|
+
import { TABLE } from "./ddl.js";
|
|
16
|
+
import { hold, ranked } from "./held.js";
|
|
17
|
+
import { admitted, candidates } from "./native.js";
|
|
18
|
+
import { floats, unpack } from "./vector.js";
|
|
19
|
+
import { scored } from "./score.js";
|
|
20
|
+
// The vectors in one model's space whose entity still exists, among what the
|
|
21
|
+
// screen admits, and only the `pool` where the index narrowed it. Deleted
|
|
22
|
+
// entities are excluded here as well as pruned by the sweep: a delete between
|
|
23
|
+
// two sweeps must not leave a neighbour that no longer exists.
|
|
24
|
+
let e = at('e');
|
|
25
|
+
let o = at('o');
|
|
26
|
+
let vectors = (db, model, within, pool)=>db.query(select({
|
|
27
|
+
cols: [
|
|
28
|
+
as(e('owner'), 'owner'),
|
|
29
|
+
as(e('vec'), 'vec')
|
|
30
|
+
],
|
|
31
|
+
from: table(TABLE, 'e'),
|
|
32
|
+
where: and(...pool ? [
|
|
33
|
+
oneOf(e('owner'), pool)
|
|
34
|
+
] : [], eq(e('model'), val(model)), not(exists(select({
|
|
35
|
+
cols: [
|
|
36
|
+
lit(1)
|
|
37
|
+
],
|
|
38
|
+
from: table('tombstone', 't'),
|
|
39
|
+
where: eq(col('entity', 't'), e('owner'))
|
|
40
|
+
}))), // The pool was drawn from what the screen admits already. Without one,
|
|
41
|
+
// every vector is read, so the screen is read whole once.
|
|
42
|
+
...within && !pool ? [
|
|
43
|
+
among(e('owner'), within)
|
|
44
|
+
] : [])
|
|
45
|
+
}));
|
|
46
|
+
let vectorRows = function*(rows) {
|
|
47
|
+
for (let row of rows){
|
|
48
|
+
yield {
|
|
49
|
+
owner: Number(row.owner),
|
|
50
|
+
vector: floats(row.vec)
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* The vector stored for an entity under a model, or null when it has none —
|
|
56
|
+
* because it holds no text, because the sweep has not reached it, or because
|
|
57
|
+
* the model moved and its row belongs to the old space.
|
|
58
|
+
*/ export let vectorOf = (db, entity, model, within)=>{
|
|
59
|
+
let row = db.query(select({
|
|
60
|
+
cols: [
|
|
61
|
+
as(e('vec'), 'vec')
|
|
62
|
+
],
|
|
63
|
+
from: table(TABLE, 'e'),
|
|
64
|
+
joins: [
|
|
65
|
+
join(table('entity', 'o'), eq(o('id'), e('owner')))
|
|
66
|
+
],
|
|
67
|
+
where: and(eq(o('eid'), val(entity)), eq(e('model'), val(model)), ...within ? [
|
|
68
|
+
admitted(within, e('owner'))
|
|
69
|
+
] : [])
|
|
70
|
+
}))[0];
|
|
71
|
+
return row ? unpack(row.vec) : null;
|
|
72
|
+
};
|
|
73
|
+
/** The entities nearest a query vector, most similar first. */ export let nearest = (db, query, opts)=>{
|
|
74
|
+
let limit = opts.limit ?? 8;
|
|
75
|
+
if (limit <= 0) return [];
|
|
76
|
+
let floor = opts.floor ?? 0;
|
|
77
|
+
let without = opts.without && db.query(select({
|
|
78
|
+
cols: [
|
|
79
|
+
col('id')
|
|
80
|
+
],
|
|
81
|
+
from: table('entity'),
|
|
82
|
+
where: eq(col('eid'), val(opts.without))
|
|
83
|
+
}))[0]?.id;
|
|
84
|
+
let held = hold(db, opts.model);
|
|
85
|
+
if (held) {
|
|
86
|
+
return ranked(db, held, query, {
|
|
87
|
+
limit,
|
|
88
|
+
floor,
|
|
89
|
+
without: without == null ? undefined : Number(without),
|
|
90
|
+
within: opts.within
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
let pool = candidates(db, query, {
|
|
94
|
+
model: opts.model,
|
|
95
|
+
need: limit + (without == null ? 0 : 1),
|
|
96
|
+
within: opts.within
|
|
97
|
+
}) ?? undefined;
|
|
98
|
+
if (pool && !pool.length) return [];
|
|
99
|
+
let hits = scored(query, vectorRows(vectors(db, opts.model, opts.within, pool)), {
|
|
100
|
+
limit,
|
|
101
|
+
floor,
|
|
102
|
+
without: without == null ? undefined : Number(without)
|
|
103
|
+
});
|
|
104
|
+
let owners = hits.map((h)=>h.owner);
|
|
105
|
+
if (!owners.length) return [];
|
|
106
|
+
let eids = new Map(db.query(select({
|
|
107
|
+
cols: [
|
|
108
|
+
col('id'),
|
|
109
|
+
col('eid')
|
|
110
|
+
],
|
|
111
|
+
from: table('entity'),
|
|
112
|
+
where: among(col('id'), owners.map((id)=>val(id)))
|
|
113
|
+
})).map((r)=>[
|
|
114
|
+
Number(r.id),
|
|
115
|
+
String(r.eid)
|
|
116
|
+
]));
|
|
117
|
+
return hits.map(({ owner, similarity })=>({
|
|
118
|
+
entity: eids.get(owner),
|
|
119
|
+
owner,
|
|
120
|
+
similarity
|
|
121
|
+
}));
|
|
122
|
+
};
|
|
123
|
+
//# sourceMappingURL=near.js.map
|
package/near.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"near.js","sources":["./near.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,4EAA4E;AAC5E,8EAA8E;AAC9E,qCAAqC;AACrC,EAAE;AACF,2EAA2E;AAC3E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,6EAA6E;AAC7E,kBAAkB;AAClB,EAAE;AACF,2EAA2E;AAG3E,SACE,KAAK,EACL,GAAG,EACH,EAAE,EACF,EAAE,EACF,GAAG,EACH,EAAE,EACF,MAAM,EACN,IAAI,EACJ,GAAG,EACH,GAAG,EACH,KAA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