pikelet-wasm 0.9.3 → 0.10.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 CHANGED
@@ -8,6 +8,74 @@ Through 0.6.0 these were published as `pancake-wasm` and
8
8
  packages are pre-1.0: a minor bump may carry breaking changes, and each entry lists them
9
9
  first.
10
10
 
11
+ ## pikelet-wasm 0.10.0 / pikelet 0.10.0 — 2026-10-09
12
+
13
+ `matchQuality` changes meaning for packs compiled with this release: it
14
+ now measures retrieval relevance — whether the pack covers the
15
+ question's topic — instead of trying to say whether the answer is there.
16
+ Packs already built keep their behavior, since the calibration ships
17
+ inside each file. The inline query encoder runs about 1.65× faster in
18
+ Node.js and Chromium and about 2.2× in WebKit with identical embeddings,
19
+ and readers can now run 12-layer and 4-bit encoders. Both packages move
20
+ to 0.10.0 together, and `pikelet` requires `pikelet-wasm` ^0.10.0.
21
+
22
+ ### Compatibility
23
+
24
+ - **Newly compiled packs score relevance.** `none` means the pack does
25
+ not cover the question's topic; a question about a covered topic whose
26
+ specific fact the pack lacks now comes back `strong` or `weak` instead
27
+ of `none`. Do not read `strong` as "answered": an asked-for value in a
28
+ result's `grounding.uncovered` is one no passage states. On the
29
+ repository's labeled questions, answerable questions called `none`
30
+ went from 12 of 44 to 0 (docs) and 26 of 50 to 0 (Veyra registry).
31
+ Rebuild a pack to pick this up; packs compiled by 0.9.x keep their
32
+ calibration.
33
+ - **The calibration summary changes shape.** The evaluation segment's
34
+ `calibration` block gains `method` (`self-templates-v6`) and `target`
35
+ (`relevance`); `cvAuc` is now measured against off-topic queries;
36
+ `cvAucHard`, answerable vs. in-domain-unanswerable, is reported but no
37
+ longer gates the fit; `stage1FloorAuc` is gone. Corpora that shipped
38
+ `unscored` for lack of hard negatives or a low hard-negative AUC now
39
+ calibrate.
40
+ - **MCP wording changes.** The `search` description, the note on a
41
+ `none` result, the server instructions and `verify_pack`'s calibration
42
+ note describe relevance; `verify_pack`'s calibration block gains
43
+ `method` and `target` (null on older packs). Tool names and result
44
+ shapes are unchanged.
45
+ - **Packs that declare a layer count other than 6, or 4-bit weights,
46
+ open only in 0.10.0 readers**; 0.9.x readers refuse them at parse. No
47
+ published pack declares either.
48
+
49
+ ### Added
50
+
51
+ - **Inline encoders with 1 to 12 layers and u4 weights.** A kind-3
52
+ declaration may give `layout.L` from 1 to 12 and `layout.Q: 4` with
53
+ `layout.B: 32` (u4 weights, two per byte, an f32 scale and offset per
54
+ block of 32); `Q` absent means u8 in blocks of 64, as before. Exported
55
+ as `KERNEL_MAX_LAYERS`. The parser and the embedder check the layer
56
+ count, the format and the blob length before the kernel runs. A u4
57
+ BGE-small-en-v1.5 blob is 23.9 MiB against MiniLM's 24.3 and matches
58
+ PyTorch at cosine 0.985 (1.000 against the same weights fake-quantized).
59
+ `compile` has no flag for these layouts yet.
60
+
61
+ ### Changed
62
+
63
+ - **The inline encoder runs its projections over tiles of four tokens**
64
+ instead of one token at a time, so each layer's weights stream through
65
+ memory once per tile. Median query encoding, before → after: about
66
+ 23 → 14 ms for a 10-word question and 213 → 125 ms for 100 words in
67
+ Chromium; 32 → 14 and 285 → 134 ms in WebKit. Embeddings are
68
+ bit-identical, so existing packs and their verification vectors are
69
+ unaffected.
70
+ - **Calibration** (`compile`, `compact` refits) fits verified on-topic
71
+ probes against off-topic ones — the built-in foreign bank, minus
72
+ entries the corpus turns out to cover, plus gibberish — and places
73
+ `none` at the 95th percentile of the off-topic scores. The
74
+ in-domain-unanswerable probe classes are still generated, for the
75
+ `cvAucHard` diagnostic only.
76
+ - **Documentation** (both READMEs, `docs/how-a-query-runs.md`,
77
+ `docs/veyra-ablation.md`) describes `matchQuality` as relevance.
78
+
11
79
  ## pikelet-wasm 0.9.3 / pikelet 0.9.3 — 2026-10-06
12
80
 
13
81
  Hardening for readers that mount packs from other publishers or hosts:
package/README.md CHANGED
@@ -133,7 +133,7 @@ claude \
133
133
  --mcp-config examples/one-file-search/web/public/veyra.mcp.json
134
134
  ```
135
135
 
136
- All three packs derive from the same small synthetic Station Veyra corpus, with controlled differences in the Tovash evidence. Ask where the Tovash project is housed: the full pack supports Chamber 17, the modified pack supports Chamber 43, and the ablated pack should abstain.
136
+ All three packs derive from the same small synthetic Station Veyra corpus, with controlled differences in the Tovash evidence. Ask where the Tovash project is housed: the full pack supports Chamber 17, the modified pack supports Chamber 43, and the ablated pack should not support any chamber.
137
137
 
138
138
  ---
139
139
 
@@ -153,7 +153,7 @@ A layer records its parent's identity, and its location when the parent sits in
153
153
 
154
154
  ## Match quality and abstention
155
155
 
156
- A nearest neighbour is not automatically evidence that a corpus answers a question. At build time Pikelet can fit a classifier over retrieval signals — distances, and how much of the question the top passages actually contain ([details](docs/how-a-query-runs.md#how-abstention-is-decided)). When the corpus supports a reliable classifier, results carry `matchQuality: strong | weak | none`. When calibration can't separate supported from unsupported reliably — a single novel may be semantically homogeneous enough that the fit isn't trustworthy — Pikelet reports `matchQuality: unscored` and records why calibration was skipped, rather than manufacturing confidence. In the library, a `none` verdict withholds `results` by default; pass `query(text, { showAbstained: true })` to see the raw retrieval anyway — `matchQuality` and `confidence` are unaffected either way. MCP `search` does the opposite: it returns results under `none` with a note telling the model the support is indirect, because the calibrator can misjudge a paraphrase; `showAbstained: false` withholds them.
156
+ A nearest neighbour is not automatically evidence that a corpus covers a question. At build time Pikelet fits a classifier over retrieval signals — distances, and how much of the question the top passages actually contain — against queries the corpus does not cover ([details](docs/how-a-query-runs.md#how-abstention-is-decided)), and results carry `matchQuality: strong | weak | none`. It measures retrieval relevance: `none` means the pack does not cover the question's topic; `strong` means it does, not that a returned passage states the specific fact asked for. For that, each result lists the question's words no top passage contains (`grounding.uncovered`), and an asked-for value in that list is unsupported whatever `matchQuality` says. When calibration can't separate on-topic from off-topic queries reliably, Pikelet reports `matchQuality: unscored` and records why calibration was skipped, rather than manufacturing confidence. In the library, a `none` verdict withholds `results` by default; pass `query(text, { showAbstained: true })` to see the raw retrieval anyway — `matchQuality` and `confidence` are unaffected either way. MCP `search` does the opposite: it returns results under `none` with a note telling the model the support is indirect, because the calibrator can misjudge a paraphrase; `showAbstained: false` withholds them.
157
157
 
158
158
  `matchQuality` is evidence about retrieval support. It is **not** a guarantee that an LLM will never hallucinate.
159
159
 
@@ -67,6 +67,14 @@ export declare function httpRangeSource(url: string, options?: {
67
67
  }): HttpRangeSource;
68
68
 
69
69
  export interface CompleteQueryResult {
70
+ /**
71
+ * The pack's calibrated verdict on this retrieval. On packs calibrated
72
+ * by pikelet 0.10 or later (evaluation calibration.target 'relevance')
73
+ * it measures retrieval relevance: 'none' means the pack does not appear
74
+ * to cover the query's topic, 'strong' that it does — not that a
75
+ * returned passage states the specific fact asked for. 'unscored': the
76
+ * pack ships no fitted calibrator.
77
+ */
70
78
  matchQuality: 'strong' | 'weak' | 'none' | 'unscored';
71
79
  confidence?: number;
72
80
  /**
@@ -297,6 +305,8 @@ export declare function verifyHostEncoder(
297
305
 
298
306
  /** Kernel layout compiled into the kind-3 encoder (mirrors encoder.cpp). */
299
307
  export declare const KERNEL_LAYOUT: Record<'V' | 'P' | 'T' | 'D' | 'F' | 'L' | 'B' | 'H', number>;
308
+ /** Largest layer count (layout L) the kind-3 kernel runs; L may be 1 to this. */
309
+ export declare const KERNEL_MAX_LAYERS: number;
300
310
  export declare function expectedBlobBytes(layout?: Record<string, number>): number;
301
311
  export declare function parseInlineTransformerEncoder(encoderBytes: Uint8Array): {
302
312
  declaration: Record<string, unknown>;
@@ -29,7 +29,7 @@ import { PikeletSketchArtifact } from '../src/artifact/pikelet-artifact.js';
29
29
  import { MAGIC, HEADER_BYTES, TABLE_ENTRY_BYTES, KINDS, KIND_NAMES } from './format.mjs';
30
30
 
31
31
  import {
32
- KERNEL_LAYOUT, expectedBlobBytes, parseInlineTransformerEncoder,
32
+ KERNEL_LAYOUT, KERNEL_MAX_LAYERS, expectedBlobBytes, parseInlineTransformerEncoder,
33
33
  createInlineTransformerEmbedder, INLINE_TEST_VECTOR_TEXTS,
34
34
  buildInlineTestVectors, verifyInlineTestVectors,
35
35
  validateExpectedEmbedding, validateTestVectorTolerance,
@@ -44,7 +44,7 @@ export { openLexicalIndex } from './lexical.mjs';
44
44
  export { fuseCandidates, FUSION_DEFAULTS } from './fusion.mjs';
45
45
  import { fuseCandidates } from './fusion.mjs';
46
46
  export {
47
- KERNEL_LAYOUT, expectedBlobBytes, parseInlineTransformerEncoder,
47
+ KERNEL_LAYOUT, KERNEL_MAX_LAYERS, expectedBlobBytes, parseInlineTransformerEncoder,
48
48
  createInlineTransformerEmbedder, INLINE_TEST_VECTOR_TEXTS,
49
49
  buildInlineTestVectors, verifyInlineTestVectors,
50
50
  validateExpectedEmbedding, validateTestVectorTolerance,
@@ -5,8 +5,13 @@ const decoder = new TextDecoder();
5
5
  // The wasm kernel compiles these in (encoder-spike/encoder.cpp `constexpr`
6
6
  // block) and walks the weight blob with a bare running cursor — it never
7
7
  // reads the declaration. Declaration/blob skew is therefore only catchable
8
- // here, host-side, before the first forward.
8
+ // here, host-side, before the first forward. Two values are exceptions,
9
+ // taken by the kernel per call: the layer count, any L from 1 to
10
+ // KERNEL_MAX_LAYERS (KERNEL_LAYOUT.L is MiniLM-L6's, the default), and the
11
+ // weight format, Q bits per weight in blocks of B — u8 in blocks of 64
12
+ // (Q absent or 8, every pack before Q existed) or u4 in blocks of 32.
9
13
  export const KERNEL_LAYOUT = { V: 30522, P: 512, T: 2, D: 384, F: 1536, L: 6, B: 64, H: 12 };
14
+ export const KERNEL_MAX_LAYERS = 12;
10
15
  const KERNEL_MAX_SEQ = 512;
11
16
  // Smallest window that still frames interior tokens between [CLS] and [SEP]
12
17
  // with room to make progress; see the maxTokens check in
@@ -14,11 +19,11 @@ const KERNEL_MAX_SEQ = 512;
14
19
  const MIN_DECLARED_MAX_TOKENS = 8;
15
20
 
16
21
  // Byte size the kernel's fill_layout() will consume for a given layout:
17
- // each quantized matrix is rows*cols u8 plus per-block f32 scales and
18
- // offsets; biases and layer norms are plain f32.
22
+ // each quantized matrix is rows*cols weights of Q bits plus per-block f32
23
+ // scales and offsets; biases and layer norms are plain f32.
19
24
  export function expectedBlobBytes(layout = KERNEL_LAYOUT) {
20
- const { V, P, T, D, F, L, B } = layout;
21
- const quant = (rows, cols) => rows * cols + rows * (cols / B) * 4 * 2;
25
+ const { V, P, T, D, F, L, B, Q = 8 } = layout;
26
+ const quant = (rows, cols) => (rows * cols * Q) / 8 + rows * (cols / B) * 4 * 2;
22
27
  const layer = 4 * quant(D, D) + 4 * (D * 4) // wq,wk,wv,wo + their biases
23
28
  + 2 * (D * 4) // ln1 gamma/beta
24
29
  + quant(F, D) + F * 4 // wu + bu
@@ -27,6 +32,33 @@ export function expectedBlobBytes(layout = KERNEL_LAYOUT) {
27
32
  return quant(V, D) + quant(P, D) + quant(T, D) + 2 * (D * 4) + L * layer;
28
33
  }
29
34
 
35
+ // The declared layer count, which the kernel takes per call. Its
36
+ // Layout struct holds KERNEL_MAX_LAYERS layers (encoder.cpp MAXL), and it
37
+ // returns -3 outside 1..MAXL rather than walking past them.
38
+ function kernelLayers(layout) {
39
+ const layers = layout.L;
40
+ if (!Number.isInteger(layers) || layers < 1 || layers > KERNEL_MAX_LAYERS) {
41
+ throw new Error(`.pikelet inline-encoder declares layout L=${layers}; `
42
+ + `the kernel runs 1 to ${KERNEL_MAX_LAYERS} layers`);
43
+ }
44
+ return layers;
45
+ }
46
+
47
+ // The declared weight format as the kernel's bits argument. The kernel's
48
+ // block size is fixed per format, so B must be the one Q implies.
49
+ const KERNEL_WEIGHT_FORMATS = { 8: 64, 4: 32 };
50
+ function kernelWeightBits(layout) {
51
+ // Only an absent Q means u8 (packs from before Q existed); null is not
52
+ // absent, and expectedBlobBytes() would size it as zero-bit weights.
53
+ const bits = layout.Q === undefined ? 8 : layout.Q;
54
+ if (!Object.hasOwn(KERNEL_WEIGHT_FORMATS, bits) || typeof bits !== 'number'
55
+ || layout.B !== KERNEL_WEIGHT_FORMATS[bits]) {
56
+ throw new Error(`.pikelet inline-encoder declares layout Q=${layout.Q} B=${layout.B}; `
57
+ + 'the kernel runs u8 weights in blocks of 64 (Q absent or 8) or u4 in blocks of 32 (Q=4)');
58
+ }
59
+ return bits;
60
+ }
61
+
30
62
  export function parseInlineTransformerEncoder(encoderBytes) {
31
63
  const view = new DataView(encoderBytes.buffer, encoderBytes.byteOffset, encoderBytes.byteLength);
32
64
  const declLen = view.getUint32(0, true);
@@ -38,7 +70,12 @@ export function parseInlineTransformerEncoder(encoderBytes) {
38
70
  const declaration = JSON.parse(decoder.decode(encoderBytes.subarray(12, 12 + declLen)));
39
71
  const blob = encoderBytes.subarray(12 + declLen + vocabLen);
40
72
  const layout = declaration.layout || {};
73
+ // L, Q and B first: expectedBlobBytes() below scales with them, so they
74
+ // must be bounded before they size anything.
75
+ kernelLayers(layout);
76
+ kernelWeightBits(layout);
41
77
  for (const key of Object.keys(KERNEL_LAYOUT)) {
78
+ if (key === 'L' || key === 'B') continue;
42
79
  if (layout[key] !== KERNEL_LAYOUT[key]) {
43
80
  throw new Error(`.pikelet inline-encoder declares layout ${key}=${layout[key]}; `
44
81
  + `the compiled kernel requires ${key}=${KERNEL_LAYOUT[key]}`);
@@ -80,6 +117,16 @@ export async function createInlineTransformerEmbedder({ declaration, vocabText,
80
117
  if (vocabSize > KERNEL_LAYOUT.V) {
81
118
  throw new Error(`inline-encoder vocab has ${vocabSize} entries; the kernel's embedding table holds ${KERNEL_LAYOUT.V}`);
82
119
  }
120
+ // Like maxTokens below, checked here too because this function is also
121
+ // called directly, without parseInlineTransformerEncoder(): the kernel
122
+ // walks the blob for exactly this many layers in this weight format.
123
+ const layers = kernelLayers({ L: declaration.layout?.L ?? KERNEL_LAYOUT.L });
124
+ const blockSize = declaration.layout?.B ?? KERNEL_LAYOUT.B;
125
+ const bits = kernelWeightBits({ Q: declaration.layout?.Q, B: blockSize });
126
+ const blobBytes = expectedBlobBytes({ ...KERNEL_LAYOUT, L: layers, Q: bits, B: blockSize });
127
+ if (blob.length !== blobBytes) {
128
+ throw new Error(`inline-encoder blob is ${blob.length} bytes but ${layers} layers of u${bits} weights imply ${blobBytes}`);
129
+ }
83
130
  const tokenizer = createWordPiece(vocabText);
84
131
  const EM = await createEncoder();
85
132
  const dim = declaration.dim;
@@ -121,7 +168,7 @@ export async function createInlineTransformerEmbedder({ declaration, vocabText,
121
168
  throw new Error(`inline encoder window is ${tokenIds.length} tokens for a ${maxSeq}-token buffer`);
122
169
  }
123
170
  new Int32Array(EM.HEAP32.buffer, idsPtr, tokenIds.length).set(tokenIds);
124
- const rc = EM._encoder_forward(blobPtr, idsPtr, tokenIds.length, hiddenPtr, 0);
171
+ const rc = EM._encoder_forward(blobPtr, idsPtr, tokenIds.length, hiddenPtr, 0, layers, bits);
125
172
  if (rc !== tokenIds.length) throw new Error(`inline encoder failed: ${rc}`);
126
173
  const hidden = new Float32Array(EM.HEAPF32.buffer, hiddenPtr, tokenIds.length * dim);
127
174
  if (usesClsPooling) {
@@ -181,7 +228,7 @@ export async function createInlineTransformerEmbedder({ declaration, vocabText,
181
228
  throw new Error(`inline encoder window is ${tokenIds.length} tokens for a ${maxSeq}-token buffer`);
182
229
  }
183
230
  new Int32Array(EM.HEAP32.buffer, idsPtr, tokenIds.length).set(tokenIds);
184
- const rc = EM._encoder_forward(blobPtr, idsPtr, tokenIds.length, hiddenPtr, 0);
231
+ const rc = EM._encoder_forward(blobPtr, idsPtr, tokenIds.length, hiddenPtr, 0, layers, bits);
185
232
  if (rc !== tokenIds.length) throw new Error(`inline encoder failed: ${rc}`);
186
233
  const hidden = new Float32Array(EM.HEAPF32.buffer, hiddenPtr, tokenIds.length * dim);
187
234
  // Offset by 1: tokenIds[0] is [CLS], so idSlice's tokens start at
@@ -4,6 +4,12 @@
4
4
  // bloom filter, standardized and passed through the fitted logistic model.
5
5
  // Verdict semantics: 'answer' (strong match), 'weak' (closest match is
6
6
  // distant — shown with a caveat), 'abstain' (nothing useful in the pack).
7
+ // What "match" means is the asset's: pikelet's self-templates-v6 assets
8
+ // (calibration.target 'relevance') are fit against off-topic queries, so
9
+ // 'abstain' means the pack does not cover the query's topic and 'answer'
10
+ // means it does — not that a passage states the asked-for fact. Earlier
11
+ // assets were fit against in-domain-unanswerable queries instead. The
12
+ // scoring math here is the same for both.
7
13
  //
8
14
  // Assets calibrated by pikelet's self-templates-v2+ may carry an additional
9
15
  // grounding term (asset.coverage): the fraction of the query's content
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pikelet-wasm",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "Vector search engine and .pikelet artifact readers/builders, in WebAssembly. Compile a corpus into one self-contained, hash-verified search file, or use the underlying HNSW engine directly. Runs in Node.js, browsers, and Cloudflare Workers with no native dependencies.",
5
5
  "main": "src/pikelet.js",
6
6
  "types": "src/pikelet.d.ts",