pikelet-wasm 0.16.0 → 0.17.0
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/CHANGELOG.md +130 -0
- package/FORMAT.md +52 -59
- package/README.md +2 -2
- package/complete/builder.d.ts +8 -7
- package/complete/builder.mjs +18 -36
- package/complete/fusion.mjs +3 -4
- package/complete/grounding.mjs +5 -9
- package/complete/index.d.ts +14 -32
- package/complete/index.mjs +94 -288
- package/complete/inline-transformer.mjs +0 -64
- package/complete/layer-append.mjs +5 -31
- package/complete/layer-chain.mjs +7 -53
- package/complete/layer-compact.mjs +3 -4
- package/complete/layer-encoder.mjs +17 -123
- package/complete/layer-reader.mjs +20 -147
- package/complete/layer-rebase.mjs +1 -1
- package/complete/wordpiece.mjs +0 -22
- package/dist/engine.js +1 -1
- package/dist/engine.scalar.js +1 -1
- package/dist/engine.scalar.wasm +0 -0
- package/dist/engine.wasm +0 -0
- package/package.json +1 -1
- package/src/artifact/pikelet-artifact-sketch.js +48 -124
- package/src/core/pikelet-core.js +6 -3
- package/complete/retrieval-abstention.mjs +0 -232
- package/complete/student-abstention.mjs +0 -102
- package/complete/student-embedder.mjs +0 -231
|
@@ -119,11 +119,14 @@ function exportSketchArtifact(index, outPath, options = {}) {
|
|
|
119
119
|
// residentSha256 (and any identity that commits to the header) anchors
|
|
120
120
|
// every lazily fetched row. The 2026-08-25 measurement chose the
|
|
121
121
|
// defaults: 16 rows x 16-byte digests ride inside the reader's existing
|
|
122
|
-
// coalesced runs at ~0% latency cost. rowIntegrity:false
|
|
123
|
-
|
|
122
|
+
// coalesced runs at ~0% latency cost. Format 1 (rowIntegrity: false,
|
|
123
|
+
// no per-row digests) was dropped in 0.17.
|
|
124
|
+
if (options.rowIntegrity === false) {
|
|
125
|
+
throw pikeletError(PIKELET_ERROR_CODES.INVALID_ARGUMENT, 'rowIntegrity: false (sketch format 1) is no longer supported');
|
|
126
|
+
}
|
|
124
127
|
const rowsPerBlock = options.rowsPerBlock || 16;
|
|
125
128
|
const rowDigestBytes = options.rowDigestBytes || 16;
|
|
126
|
-
|
|
129
|
+
{
|
|
127
130
|
if (!Number.isInteger(rowsPerBlock) || rowsPerBlock < 1 || rowsPerBlock > 4096) {
|
|
128
131
|
throw pikeletError(PIKELET_ERROR_CODES.INVALID_ARGUMENT, 'rowsPerBlock must be an integer in [1, 4096]', { rowsPerBlock });
|
|
129
132
|
}
|
|
@@ -152,20 +155,18 @@ function exportSketchArtifact(index, outPath, options = {}) {
|
|
|
152
155
|
const sketchesEnd = sketchesOffset + count * sketchRowBytes;
|
|
153
156
|
const microOffset = microDims ? sketchesEnd : 0;
|
|
154
157
|
const tiersEnd = microDims ? microOffset + count * microRowBytes : sketchesEnd;
|
|
155
|
-
const numBlocks =
|
|
156
|
-
const pageTableOffset =
|
|
157
|
-
const residentEnd =
|
|
158
|
+
const numBlocks = Math.ceil(count / rowsPerBlock);
|
|
159
|
+
const pageTableOffset = tiersEnd;
|
|
160
|
+
const residentEnd = pageTableOffset + numBlocks * 32;
|
|
158
161
|
const vectorsOffset = Math.ceil(residentEnd / 16) * 16;
|
|
159
|
-
const pageBytes =
|
|
160
|
-
const blockBytes =
|
|
161
|
-
const vectorsRegionBytes =
|
|
162
|
-
? (numBlocks - 1) * blockBytes + pageBytes + (count - (numBlocks - 1) * rowsPerBlock) * dim
|
|
163
|
-
: count * dim;
|
|
162
|
+
const pageBytes = rowsPerBlock * rowDigestBytes;
|
|
163
|
+
const blockBytes = pageBytes + rowsPerBlock * dim;
|
|
164
|
+
const vectorsRegionBytes = (numBlocks - 1) * blockBytes + pageBytes + (count - (numBlocks - 1) * rowsPerBlock) * dim;
|
|
164
165
|
const fileBytes = vectorsOffset + vectorsRegionBytes;
|
|
165
166
|
|
|
166
167
|
const out = Buffer.alloc(fileBytes);
|
|
167
168
|
out.writeUInt32LE(SKETCH_MAGIC, 0);
|
|
168
|
-
out.writeUInt32LE(
|
|
169
|
+
out.writeUInt32LE(2, 4);
|
|
169
170
|
out.writeUInt32LE(SKETCH_KIND_U8, 8);
|
|
170
171
|
out.writeUInt32LE(index.metric, 12);
|
|
171
172
|
out.writeUInt32LE(dim, 16);
|
|
@@ -183,11 +184,9 @@ function exportSketchArtifact(index, outPath, options = {}) {
|
|
|
183
184
|
out.writeUInt32LE(microBits, 128);
|
|
184
185
|
out.writeUInt32LE(microOffset, 132);
|
|
185
186
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
out.writeUInt32LE(pageTableOffset, 176);
|
|
190
|
-
}
|
|
187
|
+
out.writeUInt32LE(rowsPerBlock, 168);
|
|
188
|
+
out.writeUInt32LE(rowDigestBytes, 172);
|
|
189
|
+
out.writeUInt32LE(pageTableOffset, 176);
|
|
191
190
|
|
|
192
191
|
for (let i = 0; i < count; i++) out.writeFloatLE(index.scales[i], scalesOffset + i * 4);
|
|
193
192
|
for (let i = 0; i < count; i++) out.writeFloatLE(index.offsets[i], offsetsOffset + i * 4);
|
|
@@ -224,7 +223,7 @@ function exportSketchArtifact(index, outPath, options = {}) {
|
|
|
224
223
|
}
|
|
225
224
|
}
|
|
226
225
|
|
|
227
|
-
|
|
226
|
+
{
|
|
228
227
|
// Interleaved vectors region: [digest page][rows] per block. Digest
|
|
229
228
|
// pages are written first per block so the page hash (into the
|
|
230
229
|
// resident page table) covers the final page bytes; unused digest
|
|
@@ -240,37 +239,33 @@ function exportSketchArtifact(index, outPath, options = {}) {
|
|
|
240
239
|
}
|
|
241
240
|
out.set(sha256Bytes(out.subarray(blockStart, blockStart + pageBytes)), pageTableOffset + b * 32);
|
|
242
241
|
}
|
|
243
|
-
} else {
|
|
244
|
-
Buffer.from(index.qdata.buffer, index.qdata.byteOffset, count * dim).copy(out, vectorsOffset);
|
|
245
242
|
}
|
|
246
243
|
|
|
247
244
|
sha256Bytes(out.subarray(SKETCH_HEADER_BYTES, vectorsOffset)).copy(out, 56);
|
|
248
245
|
sha256Bytes(out.subarray(vectorsOffset)).copy(out, 88);
|
|
249
246
|
if (microDims) {
|
|
250
|
-
// Stage-1 hash: scales+offsets plus the micro segment
|
|
251
|
-
//
|
|
247
|
+
// Stage-1 hash: scales+offsets plus the micro segment and the
|
|
248
|
+
// page-hash table (so staged readers can verify rows during the
|
|
252
249
|
// micro window) — exactly the bytes a staged open serves from,
|
|
253
250
|
// verifiable before the full sketches arrive. The full resident hash
|
|
254
251
|
// still covers everything.
|
|
255
252
|
const stage1Parts = [
|
|
256
253
|
out.subarray(SKETCH_HEADER_BYTES, sketchesOffset),
|
|
257
254
|
out.subarray(microOffset, microOffset + count * microRowBytes),
|
|
255
|
+
out.subarray(pageTableOffset, pageTableOffset + numBlocks * 32),
|
|
258
256
|
];
|
|
259
|
-
if (rowIntegrity) stage1Parts.push(out.subarray(pageTableOffset, pageTableOffset + numBlocks * 32));
|
|
260
257
|
sha256Bytes(Buffer.concat(stage1Parts)).copy(out, 136);
|
|
261
258
|
}
|
|
262
259
|
|
|
263
260
|
const manifest = {
|
|
264
261
|
format: 'pikelet-sketch-artifact',
|
|
265
|
-
formatVersion:
|
|
262
|
+
formatVersion: 2,
|
|
266
263
|
sizeBytes: fileBytes,
|
|
267
264
|
metric: index.metric === 1 ? 'cosine' : 'l2',
|
|
268
265
|
graph: { count, dim },
|
|
269
266
|
sketch: { sketchDims, sketchBits, pool, residentBytes: vectorsOffset },
|
|
270
267
|
micro: microDims ? { microDims, microBits, microPool, stage1Bytes: sketchesOffset + count * microRowBytes } : null,
|
|
271
|
-
rowIntegrity:
|
|
272
|
-
? { rowsPerBlock, rowDigestBytes, blocks: numBlocks, pageTableBytes: numBlocks * 32, regionBytes: vectorsRegionBytes }
|
|
273
|
-
: null,
|
|
268
|
+
rowIntegrity: { rowsPerBlock, rowDigestBytes, blocks: numBlocks, pageTableBytes: numBlocks * 32, regionBytes: vectorsRegionBytes },
|
|
274
269
|
addressing: { scalesOffset, offsetsOffset, sketchesOffset, vectorsOffset },
|
|
275
270
|
recommendedRerank,
|
|
276
271
|
};
|
|
@@ -373,8 +368,11 @@ class PikeletSketchArtifact {
|
|
|
373
368
|
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, 'Not a Pikelet sketch artifact (bad magic)');
|
|
374
369
|
}
|
|
375
370
|
const version = view.getUint32(4, true);
|
|
376
|
-
if (version !==
|
|
377
|
-
|
|
371
|
+
if (version !== 2) {
|
|
372
|
+
// Format 1 (no per-row digests) was dropped in 0.17.
|
|
373
|
+
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, version === 1
|
|
374
|
+
? 'Sketch artifact format 1 is no longer supported; rebuild it with Pikelet 0.17 or later'
|
|
375
|
+
: 'Unsupported sketch artifact version', { version });
|
|
378
376
|
}
|
|
379
377
|
artifact.formatVersion = version;
|
|
380
378
|
if (view.getUint32(8, true) !== SKETCH_KIND_U8) {
|
|
@@ -398,9 +396,9 @@ class PikeletSketchArtifact {
|
|
|
398
396
|
artifact.microDims = view.getUint32(124, true);
|
|
399
397
|
artifact.microBits = artifact.microDims ? view.getUint32(128, true) : 0;
|
|
400
398
|
const microOffset = artifact.microDims ? view.getUint32(132, true) : 0;
|
|
401
|
-
artifact.rowsPerBlock =
|
|
402
|
-
artifact.rowDigestBytes =
|
|
403
|
-
const pageTableOffset =
|
|
399
|
+
artifact.rowsPerBlock = view.getUint32(168, true);
|
|
400
|
+
artifact.rowDigestBytes = view.getUint32(172, true);
|
|
401
|
+
const pageTableOffset = view.getUint32(176, true);
|
|
404
402
|
artifact.maxCacheBytes = resolveMaxCacheBytes(options.maxCacheBytes, 256 * artifact.dim, artifact.maxCacheBytes);
|
|
405
403
|
|
|
406
404
|
const { metric, dim, count, sketchDims, sketchBits, vectorsOffset } = artifact;
|
|
@@ -414,10 +412,10 @@ class PikeletSketchArtifact {
|
|
|
414
412
|
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, 'Invalid sketch encoding', { sketchBits, sketchDims });
|
|
415
413
|
}
|
|
416
414
|
const sketchRowBytes = (sketchDims * sketchBits) / 8;
|
|
417
|
-
//
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
|
|
415
|
+
// A digest page sits ahead of each rowsPerBlock rows and a
|
|
416
|
+
// 32-byte-per-block page-hash table at the end of the resident
|
|
417
|
+
// prefix; the vectors region size follows from that geometry.
|
|
418
|
+
{
|
|
421
419
|
const P = artifact.rowsPerBlock;
|
|
422
420
|
const D = artifact.rowDigestBytes;
|
|
423
421
|
if (!Number.isInteger(P) || P < 1 || P > 4096 || !Number.isInteger(D) || D < 8 || D > 32) {
|
|
@@ -433,9 +431,6 @@ class PikeletSketchArtifact {
|
|
|
433
431
|
|| pageTableOffset + artifact.numBlocks * 32 > vectorsOffset) {
|
|
434
432
|
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, 'Sketch artifact page table layout is inconsistent', { pageTableOffset });
|
|
435
433
|
}
|
|
436
|
-
} else {
|
|
437
|
-
artifact.numBlocks = 0;
|
|
438
|
-
artifact.vectorsRegionBytes = count * dim;
|
|
439
434
|
}
|
|
440
435
|
const expectVectors = artifact.vectorsRegionBytes;
|
|
441
436
|
if (!Number.isSafeInteger(fileBytes) || !Number.isSafeInteger(expectVectors)
|
|
@@ -458,7 +453,7 @@ class PikeletSketchArtifact {
|
|
|
458
453
|
}
|
|
459
454
|
}
|
|
460
455
|
artifact.microOffset = microOffset;
|
|
461
|
-
|
|
456
|
+
{
|
|
462
457
|
// The page table must sit exactly at the end of the sketch tiers,
|
|
463
458
|
// still inside the resident prefix residentSha256 covers.
|
|
464
459
|
const tiersEnd = artifact.microDims ? microOffset + count * microRowBytes : sketchesOffset + count * sketchRowBytes;
|
|
@@ -469,9 +464,9 @@ class PikeletSketchArtifact {
|
|
|
469
464
|
artifact.pageTableOffset = pageTableOffset;
|
|
470
465
|
|
|
471
466
|
const verify = options.verify !== false;
|
|
472
|
-
// Per-row verification
|
|
473
|
-
//
|
|
474
|
-
artifact.verifyRows =
|
|
467
|
+
// Per-row verification follows the same switch as the resident
|
|
468
|
+
// hash: on by default, verify:false opts the whole open out.
|
|
469
|
+
artifact.verifyRows = verify;
|
|
475
470
|
// Per-query pieces (digest pages and rows) use the same cache as the
|
|
476
471
|
// resident prefix, but only where each read is verified on its own.
|
|
477
472
|
artifact.blobCache = artifact.verifyRows && options.blobCache ? options.blobCache : null;
|
|
@@ -511,24 +506,24 @@ class PikeletSketchArtifact {
|
|
|
511
506
|
// integrity contract. Result semantics differ between tiers, so the
|
|
512
507
|
// tier is reported on every search result rather than hidden.
|
|
513
508
|
artifact.tier = 'micro';
|
|
514
|
-
//
|
|
515
|
-
//
|
|
516
|
-
const pageTableBytes =
|
|
509
|
+
// The page-hash table joins the stage-1 wave (and its hash), so rows
|
|
510
|
+
// fetched during the micro window are verifiable too.
|
|
511
|
+
const pageTableBytes = artifact.numBlocks * 32;
|
|
517
512
|
const [affineBytes, microBytes, pageTableRead] = await Promise.all([
|
|
518
513
|
readChecked(source, SKETCH_HEADER_BYTES, sketchesOffset - SKETCH_HEADER_BYTES, 'stage-1 affine', artifact.maxReadBytes),
|
|
519
514
|
readChecked(source, microOffset, count * microRowBytes, 'stage-1 micro', artifact.maxReadBytes),
|
|
520
|
-
|
|
515
|
+
readChecked(source, pageTableOffset, pageTableBytes, 'stage-1 page table', artifact.maxReadBytes),
|
|
521
516
|
]);
|
|
522
517
|
if (affineBytes.byteLength !== sketchesOffset - SKETCH_HEADER_BYTES || microBytes.byteLength !== count * microRowBytes
|
|
523
|
-
||
|
|
518
|
+
|| pageTableRead.byteLength !== pageTableBytes) {
|
|
524
519
|
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, 'Sketch artifact stage-1 read is truncated');
|
|
525
520
|
}
|
|
526
521
|
const affineCopy = new Uint8Array(affineBytes.byteLength);
|
|
527
522
|
affineCopy.set(affineBytes);
|
|
528
523
|
const microCopy = new Uint8Array(microBytes.byteLength);
|
|
529
524
|
microCopy.set(microBytes);
|
|
530
|
-
const pageTableCopy =
|
|
531
|
-
|
|
525
|
+
const pageTableCopy = new Uint8Array(pageTableRead.byteLength);
|
|
526
|
+
pageTableCopy.set(pageTableRead);
|
|
532
527
|
if (verify) {
|
|
533
528
|
const stage1 = new Uint8Array(affineCopy.byteLength + microCopy.byteLength + (pageTableCopy ? pageTableCopy.byteLength : 0));
|
|
534
529
|
stage1.set(affineCopy, 0);
|
|
@@ -598,9 +593,7 @@ class PikeletSketchArtifact {
|
|
|
598
593
|
if (this.microDims) {
|
|
599
594
|
this.microSketches = new Uint8Array(residentCopy.buffer, microOffset - SKETCH_HEADER_BYTES, count * microRowBytes);
|
|
600
595
|
}
|
|
601
|
-
|
|
602
|
-
this.pageTable = new Uint8Array(residentCopy.buffer, this.pageTableOffset - SKETCH_HEADER_BYTES, this.numBlocks * 32);
|
|
603
|
-
}
|
|
596
|
+
this.pageTable = new Uint8Array(residentCopy.buffer, this.pageTableOffset - SKETCH_HEADER_BYTES, this.numBlocks * 32);
|
|
604
597
|
this.residentBytes = this.vectorsOffset;
|
|
605
598
|
}
|
|
606
599
|
|
|
@@ -684,79 +677,10 @@ class PikeletSketchArtifact {
|
|
|
684
677
|
}
|
|
685
678
|
|
|
686
679
|
async fetchRows(ids, options = {}) {
|
|
687
|
-
|
|
688
|
-
const defaultGap = this.source.preferredGapBytes === undefined ? 2048 : this.source.preferredGapBytes;
|
|
689
|
-
const gap = Math.max(0, options.gap === undefined ? defaultGap : options.gap);
|
|
690
|
-
const preferredParallelism = this.source.preferredParallelism === undefined ? 32 : this.source.preferredParallelism;
|
|
691
|
-
const requestedParallelism = options.parallelism === undefined ? preferredParallelism : options.parallelism;
|
|
692
|
-
const parallelism = requestedParallelism === 0 ? Infinity : Math.max(1, Math.trunc(requestedParallelism || 32));
|
|
693
|
-
const rows = new Map();
|
|
694
|
-
const missing = [];
|
|
695
|
-
for (const id of ids) {
|
|
696
|
-
if (rows.has(id)) continue;
|
|
697
|
-
if (!Number.isInteger(id) || id < 0 || id >= this.count) {
|
|
698
|
-
throw pikeletError(PIKELET_ERROR_CODES.INVALID_ARGUMENT, 'row id out of range', { id });
|
|
699
|
-
}
|
|
700
|
-
const cached = this.cachedRow(id);
|
|
701
|
-
if (cached !== undefined) rows.set(id, cached);
|
|
702
|
-
else {
|
|
703
|
-
rows.set(id, null);
|
|
704
|
-
missing.push(id);
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
if (!missing.length) return rows;
|
|
708
|
-
missing.sort((a, b) => a - b);
|
|
709
|
-
const dim = this.dim;
|
|
710
|
-
// Coalesced runs are split at maxRangeBytes (row-aligned) so no gap
|
|
711
|
-
// setting — or a bulk fetch of every row — turns into one unbounded
|
|
712
|
-
// read and allocation.
|
|
713
|
-
const maxRunRows = Math.max(1, Math.floor(Math.trunc(options.maxRangeBytes || MAX_COALESCED_RANGE_BYTES) / dim));
|
|
714
|
-
const ranges = [];
|
|
715
|
-
const pushRun = (startId, endId) => {
|
|
716
|
-
for (let piece = startId; piece < endId; piece += maxRunRows) {
|
|
717
|
-
ranges.push([piece, Math.min(piece + maxRunRows, endId)]);
|
|
718
|
-
}
|
|
719
|
-
};
|
|
720
|
-
let runStartId = missing[0];
|
|
721
|
-
let runEndId = missing[0] + 1;
|
|
722
|
-
for (let i = 1; i < missing.length; i++) {
|
|
723
|
-
const id = missing[i];
|
|
724
|
-
if (id * dim <= runEndId * dim + gap) {
|
|
725
|
-
runEndId = id + 1;
|
|
726
|
-
} else {
|
|
727
|
-
pushRun(runStartId, runEndId);
|
|
728
|
-
runStartId = id;
|
|
729
|
-
runEndId = id + 1;
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
pushRun(runStartId, runEndId);
|
|
733
|
-
const buffers = await mapLimit(ranges, parallelism, async ([startId, endId]) => {
|
|
734
|
-
const offset = this.vectorsOffset + startId * dim;
|
|
735
|
-
const length = (endId - startId) * dim;
|
|
736
|
-
const bytes = await readChecked(this.source, offset, length, 'row');
|
|
737
|
-
if (bytes.byteLength !== length) {
|
|
738
|
-
throw pikeletError(PIKELET_ERROR_CODES.SNAPSHOT_INVALID, 'Sketch artifact row read returned a truncated range', { offset, length });
|
|
739
|
-
}
|
|
740
|
-
this.rangeRequests++;
|
|
741
|
-
this.rangeBytes += length;
|
|
742
|
-
return { startId, endId, bytes };
|
|
743
|
-
});
|
|
744
|
-
for (const { startId, endId, bytes } of buffers) {
|
|
745
|
-
for (let id = startId; id < endId; id++) {
|
|
746
|
-
// Copy each row out of the coalesced fetch buffer: a view
|
|
747
|
-
// would pin the whole range in the LRU, so cacheBytes
|
|
748
|
-
// would count dim bytes while retaining the full fetch.
|
|
749
|
-
// (Explicit copy constructor — .slice() is unreliable here
|
|
750
|
-
// because Node Buffers override it with view semantics.)
|
|
751
|
-
const row = new Uint8Array(bytes.subarray((id - startId) * dim, (id - startId + 1) * dim));
|
|
752
|
-
if (rows.has(id)) rows.set(id, row);
|
|
753
|
-
this.cacheRow(id, row);
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
return rows;
|
|
680
|
+
return this._fetchRowsVerified(ids, options);
|
|
757
681
|
}
|
|
758
682
|
|
|
759
|
-
//
|
|
683
|
+
// Row fetch: rows live in interleaved blocks
|
|
760
684
|
// [digest page][rowsPerBlock rows], so each needed block is fetched from
|
|
761
685
|
// its page through the last needed row (the page rides inside the same
|
|
762
686
|
// read), the page is verified against the resident page-hash table —
|
package/src/core/pikelet-core.js
CHANGED
|
@@ -917,9 +917,12 @@ function createPikeletApi(loadEngineImpl) {
|
|
|
917
917
|
// std::bad_alloc inside pikelet_init — reject it here with the
|
|
918
918
|
// estimate instead. Per-element cost mirrors the constructor
|
|
919
919
|
// allocations (uint8_float_hnsw.hpp / float_hnsw.hpp): quantized rows
|
|
920
|
-
// cost dim bytes
|
|
921
|
-
//
|
|
922
|
-
|
|
920
|
+
// cost a 16-byte header plus dim bytes padded to 16, 16*M edge bytes,
|
|
921
|
+
// a 4*(2M+1)-byte compact id list and ~23 bytes of bookkeeping; float
|
|
922
|
+
// rows cost 4*dim plus 8*M plus ~23.
|
|
923
|
+
const bytesPerElement = isQuantized
|
|
924
|
+
? 16 * Math.ceil(dim / 16) + 24 * M + 43
|
|
925
|
+
: 4 * dim + 8 * M + 23;
|
|
923
926
|
const estimatedBytes = maxElements * bytesPerElement;
|
|
924
927
|
if (estimatedBytes > MAX_INDEX_ARENA_BYTES) {
|
|
925
928
|
throw pikeletError(PIKELET_ERROR_CODES.WASM_ALLOCATION_FAILED,
|
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
// Reader-side matchQuality scorer. Mirrors the fit in pikelet/src/calibrate.mjs
|
|
2
|
-
// (and examples/static-wiki-pack/calibrate_abstention.mjs): retrieval signals
|
|
3
|
-
// (d0, margin, mean10) plus the known-token fraction from the shipped bloom,
|
|
4
|
-
// standardized and passed through the fitted logistic model.
|
|
5
|
-
//
|
|
6
|
-
// Verdicts: 'answer' (strong), 'weak' (shown with a caveat), 'abstain'.
|
|
7
|
-
// For self-templates-v6 assets (calibration.target 'relevance'), 'abstain'
|
|
8
|
-
// means the pack does not cover the query's topic, not that no passage
|
|
9
|
-
// states the fact. Older assets used a different target; the math is the same.
|
|
10
|
-
//
|
|
11
|
-
// asset.coverage, when present, adds coverage1: the share of the query's
|
|
12
|
-
// content words found in the top passages. It lives outside
|
|
13
|
-
// features[]/weights[] so a reader that predates it scores the topic-only
|
|
14
|
-
// model instead of NaN. Word rules ship in the asset so builder and reader
|
|
15
|
-
// cannot drift. There is no semantic (maxSim) grounding path; see
|
|
16
|
-
// docs/calibration.md for why it was removed.
|
|
17
|
-
//
|
|
18
|
-
// asset.gate, when present, is a second, distance-only model that alone
|
|
19
|
-
// decides 'abstain': results are hidden only when the retrieval itself is
|
|
20
|
-
// far, never because the query's words are missing from the passages (a
|
|
21
|
-
// paraphrase). The model above then only splits shown results into
|
|
22
|
-
// 'answer' and 'weak'. A reader that predates the gate ignores it and
|
|
23
|
-
// scores as before. See docs/calibration.md, "Two decisions".
|
|
24
|
-
|
|
25
|
-
// Upper bound on asset.coverage.topK. calibrate.mjs ships 5; every passage
|
|
26
|
-
// counted here is a record hydrated on every query, so a pack must not be
|
|
27
|
-
// able to turn one query into a hydration of its whole rerank window.
|
|
28
|
-
export const MAX_COVERAGE_TOP_K = 10;
|
|
29
|
-
|
|
30
|
-
// The signals a gate may name: the retrieval-side ones score() computes.
|
|
31
|
-
const GATE_SIGNALS = new Set(['d0', 'margin', 'mean10', 'known_frac']);
|
|
32
|
-
|
|
33
|
-
// A gate that is present but malformed returns undefined, which the caller
|
|
34
|
-
// turns into an unscored scorer: falling back to the coverage model would
|
|
35
|
-
// silently restore the behaviour the gate exists to replace.
|
|
36
|
-
function parseGate(gate) {
|
|
37
|
-
if (gate === undefined) return null;
|
|
38
|
-
if (!gate || typeof gate !== 'object') return undefined;
|
|
39
|
-
const { features, weights, bias, standardize, hard } = gate;
|
|
40
|
-
if (!Array.isArray(features) || features.length === 0 || !Array.isArray(weights) || weights.length !== features.length) return undefined;
|
|
41
|
-
if (!features.every((f) => GATE_SIGNALS.has(f)) || !weights.every(Number.isFinite) || !Number.isFinite(bias)) return undefined;
|
|
42
|
-
const mean = standardize?.mean, std = standardize?.std;
|
|
43
|
-
if (!features.every((f) => Number.isFinite(mean?.[f]) && Number.isFinite(std?.[f]) && std[f] > 0)) return undefined;
|
|
44
|
-
if (!Number.isFinite(hard) || hard < 0 || hard > 1) return undefined;
|
|
45
|
-
return { features, weights, bias, mean, std, hard };
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function createAbstentionScorer(asset, bloomBytes) {
|
|
49
|
-
if (!asset || !Array.isArray(asset.weights) || !asset.thresholds) return null;
|
|
50
|
-
// Thresholds that are missing, non-numeric or out of order compare false
|
|
51
|
-
// against every p and would answer everything; a malformed asset must
|
|
52
|
-
// degrade to unscored instead (callers map a null scorer to it).
|
|
53
|
-
const { hard, weak } = asset.thresholds;
|
|
54
|
-
if (!Number.isFinite(hard) || !Number.isFinite(weak) || hard < 0 || hard > weak || weak > 1) return null;
|
|
55
|
-
const gate = parseGate(asset.gate);
|
|
56
|
-
if (gate === undefined) return null;
|
|
57
|
-
const coverageCfg = asset.coverage && typeof asset.coverage.weight === 'number'
|
|
58
|
-
&& Number.isFinite(asset.coverage.mean) && Number.isFinite(asset.coverage.std)
|
|
59
|
-
? asset.coverage : null;
|
|
60
|
-
if (coverageCfg && coverageCfg.topK !== undefined
|
|
61
|
-
&& !(Number.isInteger(coverageCfg.topK) && coverageCfg.topK >= 1 && coverageCfg.topK <= MAX_COVERAGE_TOP_K)) {
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
const coverageStopwords = coverageCfg ? new Set(coverageCfg.stopwords || []) : null;
|
|
65
|
-
const coverageMinLen = coverageCfg ? (coverageCfg.minWordLen || 3) : 3;
|
|
66
|
-
// Words the corpus uses everywhere ground any query that mentions them,
|
|
67
|
-
// so they are excluded from coverage; the builder ships them as a bloom.
|
|
68
|
-
const commonBloom = coverageCfg?.commonBloom?.base64
|
|
69
|
-
? (typeof Buffer !== 'undefined'
|
|
70
|
-
? new Uint8Array(Buffer.from(coverageCfg.commonBloom.base64, 'base64'))
|
|
71
|
-
: Uint8Array.from(atob(coverageCfg.commonBloom.base64), (c) => c.charCodeAt(0)))
|
|
72
|
-
: null;
|
|
73
|
-
const commonBits = coverageCfg?.commonBloom?.bits;
|
|
74
|
-
const isCommon = commonBloom ? (w) => SEEDS.every((seed) => {
|
|
75
|
-
let h = 0x811c9dc5 ^ seed;
|
|
76
|
-
for (let i = 0; i < w.length; i++) { h ^= w.charCodeAt(i); h = Math.imul(h, 0x01000193); }
|
|
77
|
-
const bit = (h >>> 0) % commonBits;
|
|
78
|
-
return (commonBloom[bit >> 3] >> (bit & 7)) & 1;
|
|
79
|
-
}) : null;
|
|
80
|
-
|
|
81
|
-
// Max over the scored passages, with corpus-common words counted at
|
|
82
|
-
// reduced weight — mirrors pikelet/src/calibrate.mjs
|
|
83
|
-
// coverageFrac exactly (the weight ships in the asset).
|
|
84
|
-
const commonWordWeight = coverageCfg?.commonWordWeight ?? 1 / 3;
|
|
85
|
-
// Light suffix stripping ("configure" grounds "configuration"). Must stay
|
|
86
|
-
// byte-identical to calibrate.mjs's stem() (same suffix list and order).
|
|
87
|
-
const STEM_MIN_LEN = 4;
|
|
88
|
-
const STEM_SUFFIXES = ['ization', 'isation', 'ication', 'ation', 'ition', 'tion', 'ing', 'ed', 'ate', 'ize', 'ise'];
|
|
89
|
-
function stem(w) {
|
|
90
|
-
for (const suf of STEM_SUFFIXES) {
|
|
91
|
-
if (w.length - suf.length >= STEM_MIN_LEN && w.endsWith(suf)) return w.slice(0, -suf.length);
|
|
92
|
-
}
|
|
93
|
-
if (w.length - 1 >= STEM_MIN_LEN && w.endsWith('e')) return w.slice(0, -1);
|
|
94
|
-
return w;
|
|
95
|
-
}
|
|
96
|
-
// Byte-identical to calibrate.mjs's stripPossessive: the tokenizer keeps
|
|
97
|
-
// apostrophes, so "darcy's" would never match "darcy".
|
|
98
|
-
function stripPossessive(w) {
|
|
99
|
-
if (w.endsWith("'s")) return w.slice(0, -2);
|
|
100
|
-
if (w.endsWith("s'")) return w.slice(0, -1);
|
|
101
|
-
if (w.endsWith("'")) return w.slice(0, -1);
|
|
102
|
-
return w;
|
|
103
|
-
}
|
|
104
|
-
// Byte-identical to calibrate.mjs's isNumeral: numerals skip the
|
|
105
|
-
// coverageMinLen floor ("Chamber 4" vs "Chamber 5").
|
|
106
|
-
const isNumeral = (w) => /^\d+$/.test(w);
|
|
107
|
-
// A heading-only match grounds at reduced credit, byte-identical to
|
|
108
|
-
// calibrate.mjs's HEADING_COVERAGE_WEIGHT.
|
|
109
|
-
const HEADING_COVERAGE_WEIGHT = 0.5;
|
|
110
|
-
// Returns { value, grounding } instead of writing to shared state, so two
|
|
111
|
-
// concurrent queries on the same open pack cannot read each other's
|
|
112
|
-
// grounding.
|
|
113
|
-
function coverageFrac(text, passages) {
|
|
114
|
-
const content = (String(text).toLowerCase().match(/[a-z0-9']+/g) || [])
|
|
115
|
-
.map(stripPossessive)
|
|
116
|
-
.filter((w) => (w.length >= coverageMinLen || isNumeral(w)) && !coverageStopwords.has(w));
|
|
117
|
-
if (!content.length) return { value: 0, grounding: null };
|
|
118
|
-
const weights = content.map((w) => (isCommon && isCommon(w) ? commonWordWeight : 1));
|
|
119
|
-
const weightSum = weights.reduce((a, c) => a + c, 0);
|
|
120
|
-
let best = 0; let bestGrounding = null; let passageIndex = 0;
|
|
121
|
-
for (const { heading, body } of passages || []) {
|
|
122
|
-
const bodyWords = (String(body || '').toLowerCase().match(/[a-z0-9']+/g) || []).map(stripPossessive);
|
|
123
|
-
const bodySet = new Set(bodyWords);
|
|
124
|
-
const bodyStems = new Set(bodyWords.map(stem));
|
|
125
|
-
const headingSet = new Set((String(heading || '').toLowerCase().match(/[a-z0-9']+/g) || []).map(stripPossessive));
|
|
126
|
-
const presentIn = (set, stems, w) => set.has(w) || set.has(`${w}s`) || set.has(`${w}es`)
|
|
127
|
-
|| (w.endsWith('s') && set.has(w.slice(0, -1)))
|
|
128
|
-
|| (stems && stems.has(stem(w)));
|
|
129
|
-
const creditFor = (w) => {
|
|
130
|
-
if (presentIn(bodySet, bodyStems, w)) return 1;
|
|
131
|
-
if (presentIn(headingSet, null, w)) return HEADING_COVERAGE_WEIGHT;
|
|
132
|
-
return 0;
|
|
133
|
-
};
|
|
134
|
-
const grounded = content.reduce((sum, w, i) => sum + creditFor(w) * weights[i], 0);
|
|
135
|
-
const frac = grounded / weightSum;
|
|
136
|
-
if (frac > best) {
|
|
137
|
-
best = frac;
|
|
138
|
-
bestGrounding = { passageIndex, coverage: +frac.toFixed(3), covered: content.filter((w) => creditFor(w) > 0), uncovered: content.filter((w) => creditFor(w) === 0) };
|
|
139
|
-
}
|
|
140
|
-
passageIndex++;
|
|
141
|
-
}
|
|
142
|
-
return { value: best, grounding: bestGrounding };
|
|
143
|
-
}
|
|
144
|
-
const bloom = new Uint8Array(bloomBytes);
|
|
145
|
-
const bits = asset.vocabBloom.bits;
|
|
146
|
-
|
|
147
|
-
function fnv1a(str, seed) {
|
|
148
|
-
let h = 0x811c9dc5 ^ seed;
|
|
149
|
-
for (let i = 0; i < str.length; i++) {
|
|
150
|
-
h ^= str.charCodeAt(i);
|
|
151
|
-
h = Math.imul(h, 0x01000193);
|
|
152
|
-
}
|
|
153
|
-
return (h >>> 0) % bits;
|
|
154
|
-
}
|
|
155
|
-
const SEEDS = [0, 0x9e3779b9];
|
|
156
|
-
|
|
157
|
-
// `override` is the layered profile's union bloom (LAYERED_PROFILE.md
|
|
158
|
-
// 4.5): the bitwise OR of the base's bloom and every mounted layer's,
|
|
159
|
-
// which a chain MUST score against rather than the base's alone.
|
|
160
|
-
// Identical geometry is enforced where the union is built, and re-checked
|
|
161
|
-
// here because reading a different-sized bloom with these `bits` would
|
|
162
|
-
// silently probe the wrong positions rather than fail.
|
|
163
|
-
function knownFrac(text, override) {
|
|
164
|
-
const table = override || bloom;
|
|
165
|
-
if (table !== bloom && table.length !== bloom.length) {
|
|
166
|
-
throw new Error(`abstention: bloom override is ${table.length} bytes but the fit's is ${bloom.length}; `
|
|
167
|
-
+ 'known_frac would probe the wrong bits');
|
|
168
|
-
}
|
|
169
|
-
const words = text.toLowerCase().match(/[a-z0-9']+/g) || [];
|
|
170
|
-
if (!words.length) return 0;
|
|
171
|
-
let known = 0;
|
|
172
|
-
for (const w of words) {
|
|
173
|
-
const hit = SEEDS.every((seed) => {
|
|
174
|
-
const bit = fnv1a(w, seed);
|
|
175
|
-
return (table[bit >> 3] >> (bit & 7)) & 1;
|
|
176
|
-
});
|
|
177
|
-
if (hit) known++;
|
|
178
|
-
}
|
|
179
|
-
return known / words.length;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
return {
|
|
183
|
-
// When usesPassage is true the caller must hydrate the top passagesNeeded
|
|
184
|
-
// results' text before scoring; coverage reads them.
|
|
185
|
-
usesPassage: !!coverageCfg,
|
|
186
|
-
passagesNeeded: coverageCfg ? (coverageCfg.topK || 1) : 0,
|
|
187
|
-
async score(queryText, results, passageTexts, options = {}) {
|
|
188
|
-
// The fit always scores a fixed top-10 window (K = min(10, candidates)),
|
|
189
|
-
// whatever k the caller passes. Slicing to k first would change the
|
|
190
|
-
// verdict for an identical retrieval.
|
|
191
|
-
const top = results.slice(0, Math.min(10, results.length));
|
|
192
|
-
const d0 = top.length ? top[0].distance : 1;
|
|
193
|
-
const margin = top.length > 1
|
|
194
|
-
? top[Math.min(4, top.length - 1)].distance - d0 : 0;
|
|
195
|
-
const mean10 = top.length
|
|
196
|
-
? top.reduce((s, r) => s + r.distance, 0) / top.length : 1;
|
|
197
|
-
const signals = { d0, margin, mean10, known_frac: knownFrac(queryText, options.vocabBloom) };
|
|
198
|
-
let z = asset.bias;
|
|
199
|
-
asset.features.forEach((f, j) => {
|
|
200
|
-
z += ((signals[f] - asset.standardize.mean[f]) / asset.standardize.std[f]) * asset.weights[j];
|
|
201
|
-
});
|
|
202
|
-
// Local to this call so concurrent queries never share grounding detail.
|
|
203
|
-
let grounding = null;
|
|
204
|
-
if (coverageCfg) {
|
|
205
|
-
// passageTexts covers the fixed top-COVERAGE_TOP_PASSAGES window, matching
|
|
206
|
-
// calibrate.mjs's top.slice(0, COVERAGE_TOP_PASSAGES).
|
|
207
|
-
const passages = Array.isArray(passageTexts) ? passageTexts : [passageTexts];
|
|
208
|
-
const coverage = coverageFrac(queryText, passages);
|
|
209
|
-
signals.coverage1 = coverage.value;
|
|
210
|
-
grounding = coverage.grounding;
|
|
211
|
-
// grounding1 is coverage1 alone (see docs/calibration.md).
|
|
212
|
-
z += ((signals.coverage1 - coverageCfg.mean) / (coverageCfg.std || 1)) * coverageCfg.weight;
|
|
213
|
-
}
|
|
214
|
-
// A malformed asset (unknown feature name, non-numeric term) must
|
|
215
|
-
// degrade to unscored, never to a NaN that compares false against
|
|
216
|
-
// both thresholds and answers everything.
|
|
217
|
-
if (!Number.isFinite(z)) return { p: null, verdict: 'unscored', signals };
|
|
218
|
-
const p = 1 / (1 + Math.exp(-z));
|
|
219
|
-
if (gate) {
|
|
220
|
-
let zGate = gate.bias;
|
|
221
|
-
gate.features.forEach((f, j) => { zGate += ((signals[f] - gate.mean[f]) / gate.std[f]) * gate.weights[j]; });
|
|
222
|
-
if (!Number.isFinite(zGate)) return { p: null, verdict: 'unscored', signals };
|
|
223
|
-
const pGate = 1 / (1 + Math.exp(-zGate));
|
|
224
|
-
const verdict = pGate < gate.hard ? 'abstain' : p < asset.thresholds.weak ? 'weak' : 'answer';
|
|
225
|
-
return { p, pGate, verdict, signals, grounding };
|
|
226
|
-
}
|
|
227
|
-
const verdict = p < asset.thresholds.hard ? 'abstain'
|
|
228
|
-
: p < asset.thresholds.weak ? 'weak' : 'answer';
|
|
229
|
-
return { p, verdict, signals, grounding };
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
}
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
// Abstention scoring, extracted from 03's worker.js and parameterized on
|
|
2
|
-
// the calibration model. Pure JS, no runtime dependencies — shared by the
|
|
3
|
-
// Node spike facade and the browser one-file reader. The scoreQuery import
|
|
4
|
-
// is the only coupling to the encoder module (they form one
|
|
5
|
-
// query-interpretation unit; see spec/COMPLETE_PROFILE.md section 3.6).
|
|
6
|
-
|
|
7
|
-
import { scoreQuery } from './student-embedder.mjs';
|
|
8
|
-
|
|
9
|
-
export function buildKnownBucketTables(model) {
|
|
10
|
-
const word = new Set();
|
|
11
|
-
let maxIdf = 0;
|
|
12
|
-
for (const entry of model?.wordBuckets || []) {
|
|
13
|
-
if (!Array.isArray(entry) || entry.length < 2) continue;
|
|
14
|
-
const bucket = Number(entry[0]);
|
|
15
|
-
const idf = Number(entry[1]);
|
|
16
|
-
if (Number.isInteger(bucket) && bucket >= 0) {
|
|
17
|
-
word.add(bucket);
|
|
18
|
-
if (idf > maxIdf) maxIdf = idf;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
const char = new Set();
|
|
22
|
-
for (const value of model?.charBuckets || []) {
|
|
23
|
-
const bucket = Number(value);
|
|
24
|
-
if (Number.isInteger(bucket) && bucket >= 0) char.add(bucket);
|
|
25
|
-
}
|
|
26
|
-
return { word, char, maxIdf: maxIdf || 255 };
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function computeKnownFractions(features, model) {
|
|
30
|
-
if (!model) return { known_word: 0, known_char: 0, n_feats: features.length };
|
|
31
|
-
const tables = model._knownBucketTables || (model._knownBucketTables = buildKnownBucketTables(model));
|
|
32
|
-
let wordKnown = 0;
|
|
33
|
-
let wordTotal = 0;
|
|
34
|
-
let charKnown = 0;
|
|
35
|
-
let charTotal = 0;
|
|
36
|
-
for (const feature of features) {
|
|
37
|
-
if (feature.family === 'word') {
|
|
38
|
-
wordTotal += 1;
|
|
39
|
-
if (tables.word.has(feature.bucket)) wordKnown += 1;
|
|
40
|
-
} else if (feature.family === 'char') {
|
|
41
|
-
charTotal += 1;
|
|
42
|
-
if (tables.char.has(feature.bucket)) charKnown += 1;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
known_word: wordTotal > 0 ? wordKnown / wordTotal : 0,
|
|
47
|
-
known_char: charTotal > 0 ? charKnown / charTotal : 0,
|
|
48
|
-
n_feats: features.length,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function computeHiddenProbe(embedded, model) {
|
|
53
|
-
const probe = model?.hiddenProbe;
|
|
54
|
-
if (!probe || !Array.isArray(probe.weights) || !embedded.hidden) return 0;
|
|
55
|
-
let logit = Number(probe.bias) || 0;
|
|
56
|
-
const limit = Math.min(probe.weights.length, embedded.hidden.length);
|
|
57
|
-
for (let index = 0; index < limit; index++) {
|
|
58
|
-
logit += (Number(probe.weights[index]) || 0) * embedded.hidden[index];
|
|
59
|
-
}
|
|
60
|
-
if (logit >= 0) {
|
|
61
|
-
const z = Math.exp(-logit);
|
|
62
|
-
return 1 / (1 + z);
|
|
63
|
-
}
|
|
64
|
-
const z = Math.exp(logit);
|
|
65
|
-
return z / (1 + z);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function computeMatchQuality(hits, embedded, model) {
|
|
69
|
-
if (!model) return { match_quality: 'unscored' };
|
|
70
|
-
const d0 = hits.length > 0 ? hits[0].distance : 1;
|
|
71
|
-
const marginIndex = Math.min(4, hits.length - 1);
|
|
72
|
-
const margin = marginIndex > 0 ? hits[marginIndex].distance - d0 : 0;
|
|
73
|
-
const known = computeKnownFractions(embedded.features, model);
|
|
74
|
-
const signals = {
|
|
75
|
-
d0,
|
|
76
|
-
margin,
|
|
77
|
-
pre_norm: embedded.preNorm,
|
|
78
|
-
known_word: known.known_word,
|
|
79
|
-
known_char: known.known_char,
|
|
80
|
-
hidden_probe: computeHiddenProbe(embedded, model),
|
|
81
|
-
n_feats: known.n_feats,
|
|
82
|
-
};
|
|
83
|
-
return scoreQuery(signals, model);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function computePreSearchAbstention(embedded, model) {
|
|
87
|
-
if (!model) return null;
|
|
88
|
-
const thresholds = model.thresholds || {};
|
|
89
|
-
const minFeatures = Number.isInteger(thresholds.minFeatures) ? thresholds.minFeatures : 3;
|
|
90
|
-
const preNormFloor = Number.isFinite(thresholds.preNormFloor) ? thresholds.preNormFloor : 0.4;
|
|
91
|
-
if (embedded.features.length >= minFeatures && embedded.preNorm >= preNormFloor) return null;
|
|
92
|
-
const known = computeKnownFractions(embedded.features, model);
|
|
93
|
-
return scoreQuery({
|
|
94
|
-
d0: 1,
|
|
95
|
-
margin: 0,
|
|
96
|
-
pre_norm: embedded.preNorm,
|
|
97
|
-
known_word: known.known_word,
|
|
98
|
-
known_char: known.known_char,
|
|
99
|
-
hidden_probe: computeHiddenProbe(embedded, model),
|
|
100
|
-
n_feats: known.n_feats,
|
|
101
|
-
}, model);
|
|
102
|
-
}
|