@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/ddl.ts
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// Canonical vectors, the changes copies held in memory follow, and the
|
|
2
|
+
// embedding queue. An exclusive store notes each changed owner in a set its
|
|
3
|
+
// one process clears; shared storage keeps each vector's int8 codes, which a
|
|
4
|
+
// copy loads from (a fifth of the bytes the floats take), and a journal of
|
|
5
|
+
// every vector written, which each process's copy reads on from (./held.ts).
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
col,
|
|
9
|
+
type CreateTrigger,
|
|
10
|
+
eq,
|
|
11
|
+
exists,
|
|
12
|
+
type Expr,
|
|
13
|
+
lit,
|
|
14
|
+
not,
|
|
15
|
+
NOW,
|
|
16
|
+
select,
|
|
17
|
+
type Statements,
|
|
18
|
+
type Stmt,
|
|
19
|
+
table,
|
|
20
|
+
val,
|
|
21
|
+
type Write,
|
|
22
|
+
} from '@yaks/sql'
|
|
23
|
+
|
|
24
|
+
/** The vector table's name. */
|
|
25
|
+
export let TABLE = 'embedding'
|
|
26
|
+
|
|
27
|
+
/** The exclusive cache generation. Legacy native metadata stays readable by
|
|
28
|
+
* older CLI processes; new searches ignore it. */
|
|
29
|
+
export let BUILD = 'embedding_build'
|
|
30
|
+
|
|
31
|
+
/** Vectors changed since the exclusive reader refreshed its cache. */
|
|
32
|
+
export let DIRTY = 'embedding_dirty'
|
|
33
|
+
|
|
34
|
+
/** Each vector's int8 codes, on shared storage. A row is the codes of the
|
|
35
|
+
* vector its owner holds now: triggers delete it when that vector changes or
|
|
36
|
+
* goes, so the table only ever lacks codes, and a scan uses it once it has as
|
|
37
|
+
* many rows as the vectors (./coded.ts). */
|
|
38
|
+
export let CODE = 'embedding_code'
|
|
39
|
+
|
|
40
|
+
/** The owners of the vectors that have no codes, kept by triggers on both
|
|
41
|
+
* tables whoever writes them, so asking whether every vector has its codes
|
|
42
|
+
* reads one row rather than counting both tables (./coded.ts). */
|
|
43
|
+
export let UNCODED = 'embedding_uncoded'
|
|
44
|
+
|
|
45
|
+
/** Every vector written or deleted on shared storage, in the order the writes
|
|
46
|
+
* committed: each process's copy reads on from the last change it folded in
|
|
47
|
+
* (./held.ts). Triggers append to it, whoever writes, and the sweep trims all
|
|
48
|
+
* but the newest. */
|
|
49
|
+
export let JOURNAL = 'embedding_change'
|
|
50
|
+
|
|
51
|
+
/** The queue's name: one row per entity owed a look, and how many writes have
|
|
52
|
+
* queued it since it was last settled. */
|
|
53
|
+
export let OWED = 'embedding_owed'
|
|
54
|
+
|
|
55
|
+
/** Durable cursors of source tables being reconciled into the queue. */
|
|
56
|
+
export let FILL = 'embedding_fill'
|
|
57
|
+
|
|
58
|
+
// An upsert keeps one notice per owner even when the outer write replaces
|
|
59
|
+
// rows: a trigger's `insert or ignore` inherits the outer conflict policy.
|
|
60
|
+
let triggers = (['insert', 'update', 'delete'] as const).map((
|
|
61
|
+
event,
|
|
62
|
+
): CreateTrigger => ({
|
|
63
|
+
t: 'create trigger',
|
|
64
|
+
name: `${DIRTY}_a${event[0]}`,
|
|
65
|
+
ifNot: true,
|
|
66
|
+
timing: 'after',
|
|
67
|
+
event,
|
|
68
|
+
on: TABLE,
|
|
69
|
+
body: [{
|
|
70
|
+
t: 'insert',
|
|
71
|
+
into: DIRTY,
|
|
72
|
+
cols: ['owner'],
|
|
73
|
+
rows: [[col('owner', event == 'delete' ? 'old' : 'new')]],
|
|
74
|
+
upsert: [{ on: [col('owner')] }],
|
|
75
|
+
}],
|
|
76
|
+
}))
|
|
77
|
+
|
|
78
|
+
// A vector's codes go with the vector they were made from, whoever writes it.
|
|
79
|
+
let stale = (event: 'update' | 'delete'): CreateTrigger => ({
|
|
80
|
+
t: 'create trigger',
|
|
81
|
+
name: `${CODE}_stale_${event}`,
|
|
82
|
+
ifNot: true,
|
|
83
|
+
timing: 'after',
|
|
84
|
+
event,
|
|
85
|
+
...event == 'update' ? { of: ['vec'] } : {},
|
|
86
|
+
on: TABLE,
|
|
87
|
+
body: [{
|
|
88
|
+
t: 'delete',
|
|
89
|
+
from: CODE,
|
|
90
|
+
where: eq(col('owner'), col('owner', 'old')),
|
|
91
|
+
}],
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
// Each vector written, changed or deleted, journaled in the statement that
|
|
95
|
+
// wrote it.
|
|
96
|
+
let journaled = (['insert', 'update', 'delete'] as const).map((
|
|
97
|
+
event,
|
|
98
|
+
): CreateTrigger => ({
|
|
99
|
+
t: 'create trigger',
|
|
100
|
+
name: `${JOURNAL}_a${event[0]}`,
|
|
101
|
+
ifNot: true,
|
|
102
|
+
timing: 'after',
|
|
103
|
+
event,
|
|
104
|
+
...event == 'update' ? { of: ['model', 'vec'] } : {},
|
|
105
|
+
on: TABLE,
|
|
106
|
+
body: [{
|
|
107
|
+
t: 'insert',
|
|
108
|
+
into: JOURNAL,
|
|
109
|
+
cols: ['owner'],
|
|
110
|
+
rows: [[col('owner', event == 'delete' ? 'old' : 'new')]],
|
|
111
|
+
}],
|
|
112
|
+
}))
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Heal a store whose vector tables were made while their key was named
|
|
116
|
+
* `entity`: each such table has the column renamed to `owner`, which SQLite
|
|
117
|
+
* carries into every trigger and index that names it. Run it before
|
|
118
|
+
* {@link schema}. It can be deleted once every store has opened with it.
|
|
119
|
+
*/
|
|
120
|
+
export let rekey = (db: Statements): void => {
|
|
121
|
+
for (let name of [TABLE, DIRTY, OWED]) {
|
|
122
|
+
let cols = db.query({ t: 'pragma', name: 'table_info', arg: name })
|
|
123
|
+
if (!cols.some((c) => c.name == 'entity')) continue
|
|
124
|
+
db.query({
|
|
125
|
+
t: 'alter table',
|
|
126
|
+
table: name,
|
|
127
|
+
rename: { column: 'entity', to: 'owner' },
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The schema the vectors need, as ordered statements. Run them after the
|
|
134
|
+
* component tables exist — the table references the entity spine. Every
|
|
135
|
+
* statement is idempotent, so a table that already exists is left as it is.
|
|
136
|
+
*/
|
|
137
|
+
export let schema = (
|
|
138
|
+
ownership: Statements['ownership'] = 'exclusive',
|
|
139
|
+
): Stmt[] => [
|
|
140
|
+
{
|
|
141
|
+
t: 'create table',
|
|
142
|
+
name: TABLE,
|
|
143
|
+
ifNot: true,
|
|
144
|
+
cols: [
|
|
145
|
+
{
|
|
146
|
+
name: 'owner',
|
|
147
|
+
type: 'integer',
|
|
148
|
+
pk: true,
|
|
149
|
+
ref: { table: 'entity', cols: ['id'] },
|
|
150
|
+
},
|
|
151
|
+
{ name: 'model', type: 'text', notNull: true },
|
|
152
|
+
{ name: 'hash', type: 'text', notNull: true },
|
|
153
|
+
{ name: 'vec', type: 'blob', notNull: true },
|
|
154
|
+
{ name: 'at', type: 'text', notNull: true, default: NOW },
|
|
155
|
+
],
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
t: 'create index',
|
|
159
|
+
name: `${TABLE}_model`,
|
|
160
|
+
on: TABLE,
|
|
161
|
+
cols: [col('model')],
|
|
162
|
+
ifNot: true,
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
t: 'create table',
|
|
166
|
+
name: BUILD,
|
|
167
|
+
ifNot: true,
|
|
168
|
+
cols: [
|
|
169
|
+
{ name: 'id', type: 'integer', pk: true, check: eq(col('id'), lit(1)) },
|
|
170
|
+
{ name: 'n', type: 'integer', notNull: true },
|
|
171
|
+
{ name: 'model', type: 'text' },
|
|
172
|
+
{ name: 'dim', type: 'integer' },
|
|
173
|
+
{ name: 'rows', type: 'integer' },
|
|
174
|
+
],
|
|
175
|
+
},
|
|
176
|
+
// The exclusive cache has not loaded a generation yet.
|
|
177
|
+
{
|
|
178
|
+
t: 'insert',
|
|
179
|
+
or: 'ignore',
|
|
180
|
+
into: BUILD,
|
|
181
|
+
cols: ['id', 'n'],
|
|
182
|
+
rows: [[lit(1), lit(0)]],
|
|
183
|
+
},
|
|
184
|
+
...(ownership == 'exclusive' ? tracked() : coded()),
|
|
185
|
+
{
|
|
186
|
+
t: 'create table',
|
|
187
|
+
name: OWED,
|
|
188
|
+
ifNot: true,
|
|
189
|
+
cols: [
|
|
190
|
+
{ name: 'owner', type: 'integer', pk: true },
|
|
191
|
+
{ name: 'n', type: 'integer', notNull: true },
|
|
192
|
+
],
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
t: 'create table',
|
|
196
|
+
name: FILL,
|
|
197
|
+
ifNot: true,
|
|
198
|
+
cols: [
|
|
199
|
+
{ name: 'name', type: 'text', pk: true },
|
|
200
|
+
{ name: 'after', type: 'integer', notNull: true },
|
|
201
|
+
{ name: 'last', type: 'integer', notNull: true },
|
|
202
|
+
],
|
|
203
|
+
},
|
|
204
|
+
]
|
|
205
|
+
|
|
206
|
+
let tracked = (): Stmt[] => [{
|
|
207
|
+
t: 'create table',
|
|
208
|
+
name: DIRTY,
|
|
209
|
+
ifNot: true,
|
|
210
|
+
cols: [{ name: 'owner', type: 'integer', pk: true }],
|
|
211
|
+
}, ...triggers]
|
|
212
|
+
|
|
213
|
+
let coded = (): Stmt[] => [
|
|
214
|
+
{
|
|
215
|
+
t: 'create table',
|
|
216
|
+
name: CODE,
|
|
217
|
+
ifNot: true,
|
|
218
|
+
cols: [
|
|
219
|
+
{
|
|
220
|
+
name: 'owner',
|
|
221
|
+
type: 'integer',
|
|
222
|
+
pk: true,
|
|
223
|
+
ref: { table: 'entity', cols: ['id'] },
|
|
224
|
+
},
|
|
225
|
+
{ name: 'code', type: 'blob', notNull: true },
|
|
226
|
+
],
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
// What counting the codes reads: a few bytes a row, not the codes.
|
|
230
|
+
t: 'create index',
|
|
231
|
+
name: `${CODE}_owner`,
|
|
232
|
+
on: CODE,
|
|
233
|
+
cols: [col('owner')],
|
|
234
|
+
ifNot: true,
|
|
235
|
+
},
|
|
236
|
+
stale('update'),
|
|
237
|
+
stale('delete'),
|
|
238
|
+
{
|
|
239
|
+
t: 'create table',
|
|
240
|
+
name: UNCODED,
|
|
241
|
+
ifNot: true,
|
|
242
|
+
cols: [{ name: 'owner', type: 'integer', pk: true }],
|
|
243
|
+
},
|
|
244
|
+
seed,
|
|
245
|
+
...uncoded,
|
|
246
|
+
{
|
|
247
|
+
// Autoincrement, so a number is never handed out twice: a copy that has
|
|
248
|
+
// read to change n reads on from n + 1, and a first change past that says
|
|
249
|
+
// the trim took what it had not read.
|
|
250
|
+
t: 'create table',
|
|
251
|
+
name: JOURNAL,
|
|
252
|
+
ifNot: true,
|
|
253
|
+
cols: [
|
|
254
|
+
{ name: 'seq', type: 'integer', pk: true, autoincrement: true },
|
|
255
|
+
{ name: 'owner', type: 'integer', notNull: true },
|
|
256
|
+
],
|
|
257
|
+
},
|
|
258
|
+
...journaled,
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
// An owner's codes, or its vector, stand.
|
|
262
|
+
let holds = (name: string, owner: Expr) =>
|
|
263
|
+
exists(select({
|
|
264
|
+
cols: [lit(1)],
|
|
265
|
+
from: table(name),
|
|
266
|
+
where: eq(col('owner'), owner),
|
|
267
|
+
}))
|
|
268
|
+
|
|
269
|
+
// Note an owner as uncoded once, when `when` holds.
|
|
270
|
+
let note = (owner: Expr, when: Expr): Write => ({
|
|
271
|
+
t: 'insert',
|
|
272
|
+
into: UNCODED,
|
|
273
|
+
cols: ['owner'],
|
|
274
|
+
q: select({ cols: [owner], where: when }),
|
|
275
|
+
upsert: [{ on: [col('owner')] }],
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
let forget = (owner: Expr): Write => ({
|
|
279
|
+
t: 'delete',
|
|
280
|
+
from: UNCODED,
|
|
281
|
+
where: eq(col('owner'), owner),
|
|
282
|
+
})
|
|
283
|
+
|
|
284
|
+
let keep = (
|
|
285
|
+
on: string,
|
|
286
|
+
event: 'insert' | 'delete',
|
|
287
|
+
body: Write,
|
|
288
|
+
): CreateTrigger => ({
|
|
289
|
+
t: 'create trigger',
|
|
290
|
+
name: `${UNCODED}_${on == TABLE ? 'vector' : 'code'}_${event}`,
|
|
291
|
+
ifNot: true,
|
|
292
|
+
timing: 'after',
|
|
293
|
+
event,
|
|
294
|
+
on,
|
|
295
|
+
body: [body],
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
// A new vector is uncoded until its codes come, a vector that goes is
|
|
299
|
+
// forgotten, and codes that go while their vector stands (the vector changed,
|
|
300
|
+
// ./stale) leave it uncoded again.
|
|
301
|
+
let uncoded = [
|
|
302
|
+
keep(
|
|
303
|
+
TABLE,
|
|
304
|
+
'insert',
|
|
305
|
+
note(col('owner', 'new'), not(holds(CODE, col('owner', 'new')))),
|
|
306
|
+
),
|
|
307
|
+
keep(TABLE, 'delete', forget(col('owner', 'old'))),
|
|
308
|
+
keep(CODE, 'insert', forget(col('owner', 'new'))),
|
|
309
|
+
keep(
|
|
310
|
+
CODE,
|
|
311
|
+
'delete',
|
|
312
|
+
note(col('owner', 'old'), holds(TABLE, col('owner', 'old'))),
|
|
313
|
+
),
|
|
314
|
+
]
|
|
315
|
+
|
|
316
|
+
// A store whose vectors predate the triggers notes every one that has no
|
|
317
|
+
// codes, once: in the unit that makes the triggers, and only while they are
|
|
318
|
+
// missing. The guard is the outer side of a cross join, so a store that has
|
|
319
|
+
// them reads its catalogue, not its vectors.
|
|
320
|
+
let seed: Write = {
|
|
321
|
+
t: 'insert',
|
|
322
|
+
into: UNCODED,
|
|
323
|
+
cols: ['owner'],
|
|
324
|
+
q: select({
|
|
325
|
+
cols: [col('owner', 'e')],
|
|
326
|
+
from: {
|
|
327
|
+
t: 'from',
|
|
328
|
+
as: 'g',
|
|
329
|
+
q: select({
|
|
330
|
+
cols: [lit(1)],
|
|
331
|
+
where: not(exists(select({
|
|
332
|
+
cols: [lit(1)],
|
|
333
|
+
from: table('sqlite_master'),
|
|
334
|
+
where: eq(col('name'), val(uncoded[0].name)),
|
|
335
|
+
}))),
|
|
336
|
+
}),
|
|
337
|
+
},
|
|
338
|
+
joins: [{ how: 'cross', src: table(TABLE, 'e') }],
|
|
339
|
+
where: not(exists(select({
|
|
340
|
+
cols: [lit(1)],
|
|
341
|
+
from: table(CODE, 'c'),
|
|
342
|
+
where: eq(col('owner', 'c'), col('owner', 'e')),
|
|
343
|
+
}))),
|
|
344
|
+
}),
|
|
345
|
+
upsert: [{ on: [col('owner')] }],
|
|
346
|
+
}
|
package/deno.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"publish":{"exclude":["**/*_test.ts","testing.ts"]},"name":"@yaks/embedding","version":"0.2.36","license":"Apache-2.0","description":"Maintains text embeddings for graph entities and adds nearest-neighbor ranking to queries through an injected embedder.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./tools":"./tools.ts","./graph":"./graph.ts","./service":"./service.ts","./neighbours":"./neighbours.ts"},"imports":{"@yaks/embedding":"./mod.ts","@yaks/embedding/vocab":"./vocab.ts","@yaks/embedding/tools":"./tools.ts","@yaks/embedding/graph":"./graph.ts","@yaks/embedding/service":"./service.ts","@yaks/embedding/neighbours":"./neighbours.ts"}}
|
package/embedder.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// What turns text into a vector, and how a stored vector records which text and
|
|
2
|
+
// which model it came from.
|
|
3
|
+
//
|
|
4
|
+
// An `Embedder` is injected — a local model, a hosted API, whatever an
|
|
5
|
+
// application already pays for — because this package has an opinion about
|
|
6
|
+
// storing and searching vectors and none at all about producing them. It names
|
|
7
|
+
// its model beside the function: two vectors are only comparable within one
|
|
8
|
+
// model's space, so the name is stored on every row, filters every search, and
|
|
9
|
+
// is part of the content hash that decides what needs re-embedding.
|
|
10
|
+
//
|
|
11
|
+
// {@link hashEmbedder} is the one embedder shipped here: no model, no network,
|
|
12
|
+
// the same answer every time. It is what the tests use and what a new
|
|
13
|
+
// application can develop against before choosing a model.
|
|
14
|
+
import { unit } from "./vector.js";
|
|
15
|
+
/**
|
|
16
|
+
* What an embedder throws for a text it will not take, as distinct from an
|
|
17
|
+
* embedder that cannot be reached: the sweep drops a refused text and carries
|
|
18
|
+
* on, and stops at anything else, keeping the rest owed.
|
|
19
|
+
*/ export class Refused extends Error {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What an embedder throws when its provider answered but will not embed for
|
|
23
|
+
* this host until a ceiling it set lifts, such as a monthly budget that is
|
|
24
|
+
* spent. Nothing failed: the texts stay owed, asking again sooner changes
|
|
25
|
+
* nothing, and the drain after the ceiling lifts embeds them (./outage.ts).
|
|
26
|
+
*/ export class Withheld extends Error {
|
|
27
|
+
name = 'Withheld';
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* What an embedder throws when its provider failed every time it was asked
|
|
31
|
+
* (./remote.ts `retrying`). One provider out is one failure, however many
|
|
32
|
+
* texts it was asked for or in which words it failed, so the message names
|
|
33
|
+
* only the provider: what varies rides `context` (the model, how many texts,
|
|
34
|
+
* how many tries), and the provider's last failure is the `cause`.
|
|
35
|
+
*/ export class Unanswered extends Error {
|
|
36
|
+
name = 'Unanswered';
|
|
37
|
+
context;
|
|
38
|
+
constructor(provider, context, cause){
|
|
39
|
+
super(`@yaks/embedding: ${provider} did not answer`, {
|
|
40
|
+
cause
|
|
41
|
+
});
|
|
42
|
+
this.context = context;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Names the exact embedding a stored row holds: FNV-1a over the model and the
|
|
47
|
+
* text. It is what lets the sweep skip what has not changed without keeping a
|
|
48
|
+
* second copy of the prose.
|
|
49
|
+
*/ export let hash = (model, text)=>fnv(`${model}\n${text}`).toString(36);
|
|
50
|
+
// FNV-1a, 32 bits. Small, fast, and stable across runtimes — which is all
|
|
51
|
+
// either caller needs: naming a stored embedding, and choosing a bucket.
|
|
52
|
+
let fnv = (s)=>{
|
|
53
|
+
let h = 2166136261;
|
|
54
|
+
for(let i = 0; i < s.length; i++){
|
|
55
|
+
h = (h ^ s.charCodeAt(i)) * 16777619 >>> 0;
|
|
56
|
+
}
|
|
57
|
+
return h;
|
|
58
|
+
};
|
|
59
|
+
// The words a text is made of, lowercased. Deliberately crude — letters and
|
|
60
|
+
// digits, nothing else — because the point is a stable, language-independent
|
|
61
|
+
// split, not a tokenizer.
|
|
62
|
+
let words = (text)=>text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
63
|
+
/**
|
|
64
|
+
* A deterministic embedder with no model behind it: every word is hashed into
|
|
65
|
+
* one of `dim` buckets and the counts are normalized. Instant, offline, and the
|
|
66
|
+
* same answer on every machine, so tests and local development never reach the
|
|
67
|
+
* network.
|
|
68
|
+
*
|
|
69
|
+
* What it captures is vocabulary overlap — two texts sharing words score high,
|
|
70
|
+
* two texts sharing none score 0 — and nothing else. It has no sense of
|
|
71
|
+
* meaning, so swap in an embedding model before promising anyone semantic
|
|
72
|
+
* search; the rest of this package does not change when you do.
|
|
73
|
+
*/ export let hashEmbedder = (dim = 64)=>({
|
|
74
|
+
model: `hash-${dim}`,
|
|
75
|
+
embed: (text)=>{
|
|
76
|
+
let v = new Float32Array(dim);
|
|
77
|
+
// Counts, never signed: two words sharing a bucket then make two texts look
|
|
78
|
+
// more alike, which is the harmless direction to be wrong in. A signed
|
|
79
|
+
// sketch cancels instead, and a cancelled word is one the embedder stops
|
|
80
|
+
// being able to see at all.
|
|
81
|
+
for (let w of words(text))v[fnv(w) % dim] += 1;
|
|
82
|
+
return unit(v);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
//# sourceMappingURL=embedder.js.map
|
package/embedder.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embedder.js","sources":["./embedder.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,4BAA4B;AAC5B,EAAE;AACF,uEAAuE;AACvE,2EAA2E;AAC3E,+EAA+E;AAC/E,4EAA4E;AAC5E,+EAA+E;AAC/E,oEAAoE;AACpE,EAAE;AACF,+EAA+E;AAC/E,sEAAsE;AACtE,2DAA2D;AAE3D,SAAS,IAAI,sBAAqB;AAelC;;;;CAIC,GACD,OAAO,MAAM,gBAAgB;AAAO;AAEpC;;;;;CAKC,GACD,OAAO,MAAM,iBAAiB;EACnB,OAAO,WAAU;AAC5B;AAEA;;;;;;CAMC,GACD,OAAO,MAAM,mBAAmB;EACrB,OAAO,aAAY;EAC5B,QAAwD;EACxD,YACE,QAAgB,EAChB,OAA8B,EAC9B,KAAc,CACd;IACA,KAAK,CAAC,CAAC,iBAAiB,EAAE,SAAS,eAAe,CAAC,EAAE;MAAE;IAAM;IAC7D,IAAI,CAAC,OAAO,GAAG;EACjB;AACF;AAEA;;;;CAIC,GACD,OAAO,IAAI,OAAO,CAAC,OAAe,OAChC,IAAI,GAAG,MAAM,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,IAAG;AAEvC,0EAA0E;AAC1E,yEAAyE;AACzE,IAAI,MAAM,CAAC;EACT,IAAI,IAAI;EACR,IAAK,IAAI,IAAI,GAAG,IAAI,EAAE,MAAM,EAAE,IAAK;IACjC,IAAI,AAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,IAAI,aAAc;EAC7C;EACA,OAAO;AACT;AAEA,4EAA4E;AAC5E,6EAA6E;AAC7E,0BAA0B;AAC1B,IAAI,QAAQ,CAAC,OACX,KAAK,WAAW,GAAG,KAAK,CAAC,sBAAsB,EAAE;AAEnD;;;;;;;;;;CAUC,GACD,OAAO,IAAI,eAAe,CAAC,MAAM,EAAE,GAAe,CAAC;IACjD,OAAO,CAAC,KAAK,EAAE,KAAK;IACpB,OAAO,CAAC;MACN,IAAI,IAAI,IAAI,aAAa;MACzB,4EAA4E;MAC5E,uEAAuE;MACvE,yEAAyE;MACzE,4BAA4B;MAC5B,KAAK,IAAI,KAAK,MAAM,MAAO,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI;MAC9C,OAAO,KAAK;IACd;EACF,CAAC,EAAC"}
|
package/embedder.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// What turns text into a vector, and how a stored vector records which text and
|
|
2
|
+
// which model it came from.
|
|
3
|
+
//
|
|
4
|
+
// An `Embedder` is injected — a local model, a hosted API, whatever an
|
|
5
|
+
// application already pays for — because this package has an opinion about
|
|
6
|
+
// storing and searching vectors and none at all about producing them. It names
|
|
7
|
+
// its model beside the function: two vectors are only comparable within one
|
|
8
|
+
// model's space, so the name is stored on every row, filters every search, and
|
|
9
|
+
// is part of the content hash that decides what needs re-embedding.
|
|
10
|
+
//
|
|
11
|
+
// {@link hashEmbedder} is the one embedder shipped here: no model, no network,
|
|
12
|
+
// the same answer every time. It is what the tests use and what a new
|
|
13
|
+
// application can develop against before choosing a model.
|
|
14
|
+
|
|
15
|
+
import { unit } from './vector.js'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Text in, vector out — plus the name of the space the vectors live in. A model
|
|
19
|
+
* change is a `model` change: the stored hash covers it, so the sweep re-embeds
|
|
20
|
+
* the corpus and a search never mixes two spaces.
|
|
21
|
+
*/
|
|
22
|
+
export type Embedder<Input = string> = {
|
|
23
|
+
/** names the vector space; changing it invalidates every stored vector */
|
|
24
|
+
model: string
|
|
25
|
+
/** the vector for a piece of text; may be async (a hosted model). Calls
|
|
26
|
+
* made together may be answered together (./remote.ts batches them). */
|
|
27
|
+
embed: (input: Input) => Float32Array | Promise<Float32Array>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* What an embedder throws for a text it will not take, as distinct from an
|
|
32
|
+
* embedder that cannot be reached: the sweep drops a refused text and carries
|
|
33
|
+
* on, and stops at anything else, keeping the rest owed.
|
|
34
|
+
*/
|
|
35
|
+
export class Refused extends Error {}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What an embedder throws when its provider answered but will not embed for
|
|
39
|
+
* this host until a ceiling it set lifts, such as a monthly budget that is
|
|
40
|
+
* spent. Nothing failed: the texts stay owed, asking again sooner changes
|
|
41
|
+
* nothing, and the drain after the ceiling lifts embeds them (./outage.ts).
|
|
42
|
+
*/
|
|
43
|
+
export class Withheld extends Error {
|
|
44
|
+
override name = 'Withheld'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What an embedder throws when its provider failed every time it was asked
|
|
49
|
+
* (./remote.ts `retrying`). One provider out is one failure, however many
|
|
50
|
+
* texts it was asked for or in which words it failed, so the message names
|
|
51
|
+
* only the provider: what varies rides `context` (the model, how many texts,
|
|
52
|
+
* how many tries), and the provider's last failure is the `cause`.
|
|
53
|
+
*/
|
|
54
|
+
export class Unanswered extends Error {
|
|
55
|
+
override name = 'Unanswered'
|
|
56
|
+
context: { model: string; texts: string; tries: string }
|
|
57
|
+
constructor(
|
|
58
|
+
provider: string,
|
|
59
|
+
context: Unanswered['context'],
|
|
60
|
+
cause: unknown,
|
|
61
|
+
) {
|
|
62
|
+
super(`@yaks/embedding: ${provider} did not answer`, { cause })
|
|
63
|
+
this.context = context
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Names the exact embedding a stored row holds: FNV-1a over the model and the
|
|
69
|
+
* text. It is what lets the sweep skip what has not changed without keeping a
|
|
70
|
+
* second copy of the prose.
|
|
71
|
+
*/
|
|
72
|
+
export let hash = (model: string, text: string): string =>
|
|
73
|
+
fnv(`${model}\n${text}`).toString(36)
|
|
74
|
+
|
|
75
|
+
// FNV-1a, 32 bits. Small, fast, and stable across runtimes — which is all
|
|
76
|
+
// either caller needs: naming a stored embedding, and choosing a bucket.
|
|
77
|
+
let fnv = (s: string): number => {
|
|
78
|
+
let h = 2166136261
|
|
79
|
+
for (let i = 0; i < s.length; i++) {
|
|
80
|
+
h = ((h ^ s.charCodeAt(i)) * 16777619) >>> 0
|
|
81
|
+
}
|
|
82
|
+
return h
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The words a text is made of, lowercased. Deliberately crude — letters and
|
|
86
|
+
// digits, nothing else — because the point is a stable, language-independent
|
|
87
|
+
// split, not a tokenizer.
|
|
88
|
+
let words = (text: string): string[] =>
|
|
89
|
+
text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A deterministic embedder with no model behind it: every word is hashed into
|
|
93
|
+
* one of `dim` buckets and the counts are normalized. Instant, offline, and the
|
|
94
|
+
* same answer on every machine, so tests and local development never reach the
|
|
95
|
+
* network.
|
|
96
|
+
*
|
|
97
|
+
* What it captures is vocabulary overlap — two texts sharing words score high,
|
|
98
|
+
* two texts sharing none score 0 — and nothing else. It has no sense of
|
|
99
|
+
* meaning, so swap in an embedding model before promising anyone semantic
|
|
100
|
+
* search; the rest of this package does not change when you do.
|
|
101
|
+
*/
|
|
102
|
+
export let hashEmbedder = (dim = 64): Embedder => ({
|
|
103
|
+
model: `hash-${dim}`,
|
|
104
|
+
embed: (text) => {
|
|
105
|
+
let v = new Float32Array(dim)
|
|
106
|
+
// Counts, never signed: two words sharing a bucket then make two texts look
|
|
107
|
+
// more alike, which is the harmless direction to be wrong in. A signed
|
|
108
|
+
// sketch cancels instead, and a cancelled word is one the embedder stops
|
|
109
|
+
// being able to see at all.
|
|
110
|
+
for (let w of words(text)) v[fnv(w) % dim] += 1
|
|
111
|
+
return unit(v)
|
|
112
|
+
},
|
|
113
|
+
})
|