@hviana/sema 0.2.6 → 0.2.8
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/dist/example/demo.d.ts +1 -0
- package/dist/example/demo.js +39 -0
- package/dist/example/train_base.d.ts +87 -0
- package/dist/example/train_base.js +2252 -0
- package/dist/src/alphabet.d.ts +7 -0
- package/dist/src/alphabet.js +33 -0
- package/dist/src/alu/src/alu.d.ts +185 -0
- package/dist/src/alu/src/alu.js +440 -0
- package/dist/src/alu/src/expr.d.ts +61 -0
- package/dist/src/alu/src/expr.js +318 -0
- package/dist/src/alu/src/index.d.ts +11 -0
- package/dist/src/alu/src/index.js +19 -0
- package/dist/src/alu/src/kernel-arith.d.ts +16 -0
- package/dist/src/alu/src/kernel-arith.js +264 -0
- package/dist/src/alu/src/kernel-bits.d.ts +19 -0
- package/dist/src/alu/src/kernel-bits.js +152 -0
- package/dist/src/alu/src/kernel-logic.d.ts +4 -0
- package/dist/src/alu/src/kernel-logic.js +60 -0
- package/dist/src/alu/src/kernel-nd.d.ts +3 -0
- package/dist/src/alu/src/kernel-nd.js +208 -0
- package/dist/src/alu/src/kernel-numeric.d.ts +54 -0
- package/dist/src/alu/src/kernel-numeric.js +366 -0
- package/dist/src/alu/src/operation.d.ts +168 -0
- package/dist/src/alu/src/operation.js +189 -0
- package/dist/src/alu/src/parser.d.ts +221 -0
- package/dist/src/alu/src/parser.js +577 -0
- package/dist/src/alu/src/resonance.d.ts +55 -0
- package/dist/src/alu/src/resonance.js +126 -0
- package/dist/src/alu/src/text.d.ts +31 -0
- package/dist/src/alu/src/text.js +73 -0
- package/dist/src/alu/src/value.d.ts +109 -0
- package/dist/src/alu/src/value.js +300 -0
- package/dist/src/alu/test/alu.test.d.ts +1 -0
- package/dist/src/alu/test/alu.test.js +764 -0
- package/dist/src/bytes.d.ts +14 -0
- package/dist/src/bytes.js +59 -0
- package/dist/src/canon.d.ts +26 -0
- package/dist/src/canon.js +57 -0
- package/dist/src/config.d.ts +111 -0
- package/dist/src/config.js +91 -0
- package/dist/src/derive/src/deduction.d.ts +125 -0
- package/dist/src/derive/src/deduction.js +155 -0
- package/dist/src/derive/src/index.d.ts +7 -0
- package/dist/src/derive/src/index.js +11 -0
- package/dist/src/derive/src/priority-queue.d.ts +20 -0
- package/dist/src/derive/src/priority-queue.js +73 -0
- package/dist/src/derive/src/rewrite.d.ts +56 -0
- package/dist/src/derive/src/rewrite.js +100 -0
- package/dist/src/derive/src/trie.d.ts +90 -0
- package/dist/src/derive/src/trie.js +217 -0
- package/dist/src/derive/test/derive.test.d.ts +1 -0
- package/dist/src/derive/test/derive.test.js +122 -0
- package/dist/src/extension.d.ts +37 -0
- package/dist/src/extension.js +7 -0
- package/dist/src/geometry.d.ts +202 -0
- package/dist/src/geometry.js +575 -0
- package/dist/src/index.d.ts +16 -0
- package/dist/src/index.js +18 -0
- package/dist/src/ingest-cache.d.ts +41 -0
- package/dist/src/ingest-cache.js +161 -0
- package/dist/src/mind/articulation.d.ts +6 -0
- package/dist/src/mind/articulation.js +99 -0
- package/dist/src/mind/attention.d.ts +405 -0
- package/dist/src/mind/attention.js +1829 -0
- package/dist/src/mind/bridge.d.ts +30 -0
- package/dist/src/mind/bridge.js +569 -0
- package/dist/src/mind/canonical.d.ts +29 -0
- package/dist/src/mind/canonical.js +88 -0
- package/dist/src/mind/graph-search.d.ts +285 -0
- package/dist/src/mind/graph-search.js +956 -0
- package/dist/src/mind/index.d.ts +7 -0
- package/dist/src/mind/index.js +5 -0
- package/dist/src/mind/junction.d.ts +124 -0
- package/dist/src/mind/junction.js +317 -0
- package/dist/src/mind/learning.d.ts +47 -0
- package/dist/src/mind/learning.js +248 -0
- package/dist/src/mind/match.d.ts +126 -0
- package/dist/src/mind/match.js +441 -0
- package/dist/src/mind/mechanisms/alu.d.ts +4 -0
- package/dist/src/mind/mechanisms/alu.js +36 -0
- package/dist/src/mind/mechanisms/cast.d.ts +89 -0
- package/dist/src/mind/mechanisms/cast.js +716 -0
- package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
- package/dist/src/mind/mechanisms/confluence.js +225 -0
- package/dist/src/mind/mechanisms/cover.d.ts +6 -0
- package/dist/src/mind/mechanisms/cover.js +203 -0
- package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
- package/dist/src/mind/mechanisms/extraction.js +387 -0
- package/dist/src/mind/mechanisms/recall.d.ts +13 -0
- package/dist/src/mind/mechanisms/recall.js +325 -0
- package/dist/src/mind/mind.d.ts +276 -0
- package/dist/src/mind/mind.js +572 -0
- package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
- package/dist/src/mind/pipeline-mechanism.js +213 -0
- package/dist/src/mind/pipeline.d.ts +20 -0
- package/dist/src/mind/pipeline.js +217 -0
- package/dist/src/mind/primitives.d.ts +70 -0
- package/dist/src/mind/primitives.js +287 -0
- package/dist/src/mind/rationale.d.ts +139 -0
- package/dist/src/mind/rationale.js +163 -0
- package/dist/src/mind/reasoning.d.ts +34 -0
- package/dist/src/mind/reasoning.js +240 -0
- package/dist/src/mind/recognition.d.ts +20 -0
- package/dist/src/mind/recognition.js +390 -0
- package/dist/src/mind/resonance.d.ts +23 -0
- package/dist/src/mind/resonance.js +0 -0
- package/dist/src/mind/trace.d.ts +15 -0
- package/dist/src/mind/trace.js +73 -0
- package/dist/src/mind/traverse.d.ts +113 -0
- package/dist/src/mind/traverse.js +568 -0
- package/dist/src/mind/types.d.ts +289 -0
- package/dist/src/mind/types.js +130 -0
- package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
- package/dist/src/rabitq-ivf/src/database.js +201 -0
- package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
- package/dist/src/rabitq-ivf/src/index.js +4 -0
- package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
- package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
- package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
- package/dist/src/rabitq-ivf/src/prng.js +36 -0
- package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
- package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
- package/dist/src/sema.d.ts +31 -0
- package/dist/src/sema.js +63 -0
- package/dist/src/store-sqlite.d.ts +184 -0
- package/dist/src/store-sqlite.js +942 -0
- package/dist/src/store.d.ts +663 -0
- package/dist/src/store.js +1618 -0
- package/dist/src/vec.d.ts +31 -0
- package/dist/src/vec.js +109 -0
- package/package.json +1 -1
- package/src/mind/attention.ts +178 -63
- package/test/51-structural-resonance-ladder.test.mjs +6 -3
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small deterministic pseudo-random number generator (mulberry32).
|
|
3
|
+
*
|
|
4
|
+
* Pure ECMAScript. It is used so that the random orthogonal rotation of the
|
|
5
|
+
* RaBitQ quantizer rotation is reproducible and can be
|
|
6
|
+
* regenerated after (de)serialization without storing large matrices.
|
|
7
|
+
*/
|
|
8
|
+
export declare class Prng {
|
|
9
|
+
private state;
|
|
10
|
+
constructor(seed: number);
|
|
11
|
+
/** Uniform float in [0, 1). */
|
|
12
|
+
next(): number;
|
|
13
|
+
/** Uniform integer in [0, n). */
|
|
14
|
+
int(n: number): number;
|
|
15
|
+
/** Current internal state (one uint32), for persisting/resuming the stream. */
|
|
16
|
+
snapshot(): number;
|
|
17
|
+
/** Resume the stream from a previously snapshotted state. */
|
|
18
|
+
restore(state: number): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small deterministic pseudo-random number generator (mulberry32).
|
|
3
|
+
*
|
|
4
|
+
* Pure ECMAScript. It is used so that the random orthogonal rotation of the
|
|
5
|
+
* RaBitQ quantizer rotation is reproducible and can be
|
|
6
|
+
* regenerated after (de)serialization without storing large matrices.
|
|
7
|
+
*/
|
|
8
|
+
export class Prng {
|
|
9
|
+
state;
|
|
10
|
+
constructor(seed) {
|
|
11
|
+
this.state = seed >>> 0;
|
|
12
|
+
if (this.state === 0)
|
|
13
|
+
this.state = 0x9e3779b9;
|
|
14
|
+
}
|
|
15
|
+
/** Uniform float in [0, 1). */
|
|
16
|
+
next() {
|
|
17
|
+
let t = (this.state = (this.state + 0x6d2b79f5) | 0);
|
|
18
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
19
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
20
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
21
|
+
}
|
|
22
|
+
/** Uniform integer in [0, n). */
|
|
23
|
+
int(n) {
|
|
24
|
+
return (this.next() * n) | 0;
|
|
25
|
+
}
|
|
26
|
+
/** Current internal state (one uint32), for persisting/resuming the stream. */
|
|
27
|
+
snapshot() {
|
|
28
|
+
return this.state >>> 0;
|
|
29
|
+
}
|
|
30
|
+
/** Resume the stream from a previously snapshotted state. */
|
|
31
|
+
restore(state) {
|
|
32
|
+
this.state = state >>> 0;
|
|
33
|
+
if (this.state === 0)
|
|
34
|
+
this.state = 0x9e3779b9;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export interface QueryContext {
|
|
2
|
+
vmin: number;
|
|
3
|
+
delta: number;
|
|
4
|
+
sumQInt: number;
|
|
5
|
+
/**
|
|
6
|
+
* Per-query lookup table of length nbytes*256. `qlut[p*256 + b]` is the sum of
|
|
7
|
+
* the quantised query values at the (up to 8) coordinates whose code bits are
|
|
8
|
+
* set in byte value `b` at code-byte position `p`. The query/code inner product
|
|
9
|
+
* for a stored code is then sum over its bytes of qlut[p*256 + codeByte_p].
|
|
10
|
+
*/
|
|
11
|
+
qlut: Uint8Array | Uint16Array;
|
|
12
|
+
/** number of bytes per code (paddedDim / 8). */
|
|
13
|
+
nbytes: number;
|
|
14
|
+
/** true when the (centered) query has zero norm. */
|
|
15
|
+
zero: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface RaBitQOptions {
|
|
18
|
+
queryBits?: number;
|
|
19
|
+
rounds?: number;
|
|
20
|
+
seed?: number;
|
|
21
|
+
centroid?: ArrayLike<number>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 1-bit RaBitQ quantizer (cosine) -- the ONLY representation of a vector kept by
|
|
25
|
+
* the index. A D-dimensional vector collapses to ceil(D/32) 32-bit words of sign
|
|
26
|
+
* bits, e.g. a 256-d vector goes from 256*4 = 1024 bytes to 32 bytes of code.
|
|
27
|
+
*
|
|
28
|
+
* Each vector is centered by an optional centroid, normalised, rotated by a
|
|
29
|
+
* fast random orthogonal transform (random sign flips + Walsh-Hadamard,
|
|
30
|
+
* O(D log D)) and reduced to one sign bit per padded dimension. The random
|
|
31
|
+
* rotation makes the quantisation error essentially uniform across vectors, so
|
|
32
|
+
* the cosine estimate needs only a single fixed scale (`cosFactor`) rather than
|
|
33
|
+
* any per-vector correction.
|
|
34
|
+
*
|
|
35
|
+
* Two estimators are provided:
|
|
36
|
+
* - `estimate` : full-precision query vs stored code (accurate)
|
|
37
|
+
* - `codeDistanceBytes` : stored code vs stored code (Hamming based; used while
|
|
38
|
+
* building the graph, where neither side is full precision)
|
|
39
|
+
*
|
|
40
|
+
* Reference: Gao & Long, "RaBitQ: Quantizing High-Dimensional Vectors with a
|
|
41
|
+
* Theoretical Error Bound for Approximate Nearest Neighbor Search", SIGMOD 2024.
|
|
42
|
+
*/
|
|
43
|
+
export declare class RaBitQuantizer {
|
|
44
|
+
readonly dim: number;
|
|
45
|
+
readonly paddedDim: number;
|
|
46
|
+
readonly codeWords: number;
|
|
47
|
+
readonly queryBits: number;
|
|
48
|
+
readonly rounds: number;
|
|
49
|
+
readonly seed: number;
|
|
50
|
+
readonly centroid: Float64Array;
|
|
51
|
+
private readonly sqrtD;
|
|
52
|
+
private readonly maxQInt;
|
|
53
|
+
private readonly signs;
|
|
54
|
+
private readonly scratch;
|
|
55
|
+
/** Fixed cosine inner-product scale (= 1 / E[L1] of a rotated unit vector). */
|
|
56
|
+
readonly cosFactor: number;
|
|
57
|
+
private readonly nbytes;
|
|
58
|
+
/** coordinate index sitting at byte position p, bit k -> bitCoord[p*8 + k]. */
|
|
59
|
+
private readonly bitCoord;
|
|
60
|
+
/** true when the largest possible LUT entry overflows a Uint8. */
|
|
61
|
+
private readonly lutWide;
|
|
62
|
+
constructor(dim: number, opts?: RaBitQOptions);
|
|
63
|
+
/** In-place fast Walsh-Hadamard transform; `a.length` must be a power of two. */
|
|
64
|
+
private fwht;
|
|
65
|
+
/** Apply the orthogonal rotation in place (a.length === paddedDim). */
|
|
66
|
+
private rotate;
|
|
67
|
+
/** Encode a raw vector into its 1-bit sign code (the whole representation). */
|
|
68
|
+
encode(vec: ArrayLike<number>): Uint32Array;
|
|
69
|
+
/** Pre-process a full-precision query into the structure consumed by `estimate`. */
|
|
70
|
+
prepareQuery(vec: ArrayLike<number>): QueryContext;
|
|
71
|
+
/**
|
|
72
|
+
* Estimate the cosine distance (1 - cosine) between a stored code and a
|
|
73
|
+
* full-precision query, reading the code's bytes against the query's byte LUT.
|
|
74
|
+
* The code's set-bit count is tallied in the same byte scan, so nothing beyond
|
|
75
|
+
* the code itself is needed.
|
|
76
|
+
*
|
|
77
|
+
* `codeBytes` is a Uint8 view of the packed code buffer and `byteOffset` is the
|
|
78
|
+
* code's start byte (id * paddedDim/8).
|
|
79
|
+
*/
|
|
80
|
+
estimate(codeBytes: Uint8Array, byteOffset: number, q: QueryContext): number;
|
|
81
|
+
/**
|
|
82
|
+
* Cosine distance (1 - cosine, in [0, 2]) between two packed codes, computed
|
|
83
|
+
* directly from the BLOB bytes via their sign-bit Hamming distance — no word
|
|
84
|
+
* reinterpretation, so it is endianness-agnostic. Identical codes score 0.
|
|
85
|
+
*
|
|
86
|
+
* This is the distance used to build the graph (code vs code) and to answer a
|
|
87
|
+
* query given an already-quantized code. It is coarser than `estimate`, where
|
|
88
|
+
* one side is full precision.
|
|
89
|
+
*/
|
|
90
|
+
codeDistanceBytes(a: Uint8Array, b: Uint8Array): number;
|
|
91
|
+
/** Pack a code (codeWords 32-bit words) into its little-endian BLOB bytes. */
|
|
92
|
+
codeToBytes(code: ArrayLike<number>): Uint8Array;
|
|
93
|
+
/** Reinterpret a code BLOB as a copy of codeWords 32-bit words. */
|
|
94
|
+
bytesToCode(bytes: Uint8Array): Uint32Array;
|
|
95
|
+
}
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { Prng } from "./prng.js";
|
|
2
|
+
function nextPow2(n) {
|
|
3
|
+
let p = 1;
|
|
4
|
+
while (p < n)
|
|
5
|
+
p <<= 1;
|
|
6
|
+
return p;
|
|
7
|
+
}
|
|
8
|
+
/** Set-bit count for every byte value, for counting code bits during the byte scan. */
|
|
9
|
+
const POPCOUNT8 = new Uint8Array(256);
|
|
10
|
+
for (let i = 1; i < 256; i++)
|
|
11
|
+
POPCOUNT8[i] = POPCOUNT8[i >> 1] + (i & 1);
|
|
12
|
+
/**
|
|
13
|
+
* 1-bit RaBitQ quantizer (cosine) -- the ONLY representation of a vector kept by
|
|
14
|
+
* the index. A D-dimensional vector collapses to ceil(D/32) 32-bit words of sign
|
|
15
|
+
* bits, e.g. a 256-d vector goes from 256*4 = 1024 bytes to 32 bytes of code.
|
|
16
|
+
*
|
|
17
|
+
* Each vector is centered by an optional centroid, normalised, rotated by a
|
|
18
|
+
* fast random orthogonal transform (random sign flips + Walsh-Hadamard,
|
|
19
|
+
* O(D log D)) and reduced to one sign bit per padded dimension. The random
|
|
20
|
+
* rotation makes the quantisation error essentially uniform across vectors, so
|
|
21
|
+
* the cosine estimate needs only a single fixed scale (`cosFactor`) rather than
|
|
22
|
+
* any per-vector correction.
|
|
23
|
+
*
|
|
24
|
+
* Two estimators are provided:
|
|
25
|
+
* - `estimate` : full-precision query vs stored code (accurate)
|
|
26
|
+
* - `codeDistanceBytes` : stored code vs stored code (Hamming based; used while
|
|
27
|
+
* building the graph, where neither side is full precision)
|
|
28
|
+
*
|
|
29
|
+
* Reference: Gao & Long, "RaBitQ: Quantizing High-Dimensional Vectors with a
|
|
30
|
+
* Theoretical Error Bound for Approximate Nearest Neighbor Search", SIGMOD 2024.
|
|
31
|
+
*/
|
|
32
|
+
export class RaBitQuantizer {
|
|
33
|
+
dim;
|
|
34
|
+
paddedDim;
|
|
35
|
+
codeWords;
|
|
36
|
+
queryBits;
|
|
37
|
+
rounds;
|
|
38
|
+
seed;
|
|
39
|
+
centroid;
|
|
40
|
+
sqrtD;
|
|
41
|
+
maxQInt;
|
|
42
|
+
signs;
|
|
43
|
+
scratch;
|
|
44
|
+
/** Fixed cosine inner-product scale (= 1 / E[L1] of a rotated unit vector). */
|
|
45
|
+
cosFactor;
|
|
46
|
+
// byte-LUT machinery for the query/code estimator
|
|
47
|
+
nbytes;
|
|
48
|
+
/** coordinate index sitting at byte position p, bit k -> bitCoord[p*8 + k]. */
|
|
49
|
+
bitCoord;
|
|
50
|
+
/** true when the largest possible LUT entry overflows a Uint8. */
|
|
51
|
+
lutWide;
|
|
52
|
+
constructor(dim, opts = {}) {
|
|
53
|
+
this.dim = dim;
|
|
54
|
+
this.paddedDim = nextPow2(dim);
|
|
55
|
+
this.codeWords = Math.ceil(this.paddedDim / 32);
|
|
56
|
+
this.queryBits = opts.queryBits ?? 8;
|
|
57
|
+
this.rounds = opts.rounds ?? 3;
|
|
58
|
+
this.seed = (opts.seed ?? 0x1234abcd) >>> 0;
|
|
59
|
+
this.sqrtD = Math.sqrt(this.paddedDim);
|
|
60
|
+
this.cosFactor = Math.sqrt(Math.PI / (2 * this.paddedDim));
|
|
61
|
+
this.maxQInt = (1 << this.queryBits) - 1;
|
|
62
|
+
this.centroid = new Float64Array(dim);
|
|
63
|
+
if (opts.centroid) {
|
|
64
|
+
for (let i = 0; i < dim; i++)
|
|
65
|
+
this.centroid[i] = opts.centroid[i] ?? 0;
|
|
66
|
+
}
|
|
67
|
+
const prng = new Prng(this.seed);
|
|
68
|
+
this.signs = [];
|
|
69
|
+
for (let r = 0; r < this.rounds; r++) {
|
|
70
|
+
const s = new Float64Array(this.paddedDim);
|
|
71
|
+
for (let i = 0; i < this.paddedDim; i++) {
|
|
72
|
+
s[i] = prng.next() < 0.5 ? -1 : 1;
|
|
73
|
+
}
|
|
74
|
+
this.signs.push(s);
|
|
75
|
+
}
|
|
76
|
+
this.scratch = new Float64Array(this.paddedDim);
|
|
77
|
+
// Map (code-byte position, bit-in-byte) -> coordinate, honouring the host
|
|
78
|
+
// byte order so the Uint8 view of the (Uint32) code buffer is interpreted
|
|
79
|
+
// correctly on both little- and big-endian platforms.
|
|
80
|
+
this.nbytes = this.paddedDim >>> 3;
|
|
81
|
+
const littleEndian = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
|
|
82
|
+
this.bitCoord = new Int32Array(this.nbytes * 8);
|
|
83
|
+
for (let p = 0; p < this.nbytes; p++) {
|
|
84
|
+
const word = p >>> 2;
|
|
85
|
+
const localByte = littleEndian ? p & 3 : 3 - (p & 3);
|
|
86
|
+
const bitBase = word * 32 + localByte * 8;
|
|
87
|
+
for (let k = 0; k < 8; k++)
|
|
88
|
+
this.bitCoord[p * 8 + k] = bitBase + k;
|
|
89
|
+
}
|
|
90
|
+
this.lutWide = 8 * this.maxQInt > 255;
|
|
91
|
+
}
|
|
92
|
+
/** In-place fast Walsh-Hadamard transform; `a.length` must be a power of two. */
|
|
93
|
+
fwht(a) {
|
|
94
|
+
const n = a.length;
|
|
95
|
+
for (let len = 1; len < n; len <<= 1) {
|
|
96
|
+
const span = len << 1;
|
|
97
|
+
for (let i = 0; i < n; i += span) {
|
|
98
|
+
for (let j = i; j < i + len; j++) {
|
|
99
|
+
const u = a[j];
|
|
100
|
+
const v = a[j + len];
|
|
101
|
+
a[j] = u + v;
|
|
102
|
+
a[j + len] = u - v;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Apply the orthogonal rotation in place (a.length === paddedDim). */
|
|
108
|
+
rotate(a) {
|
|
109
|
+
const n = this.paddedDim;
|
|
110
|
+
const inv = 1 / this.sqrtD;
|
|
111
|
+
for (let r = 0; r < this.rounds; r++) {
|
|
112
|
+
const s = this.signs[r];
|
|
113
|
+
for (let i = 0; i < n; i++)
|
|
114
|
+
a[i] *= s[i];
|
|
115
|
+
this.fwht(a);
|
|
116
|
+
for (let i = 0; i < n; i++)
|
|
117
|
+
a[i] *= inv;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Encode a raw vector into its 1-bit sign code (the whole representation). */
|
|
121
|
+
encode(vec) {
|
|
122
|
+
const dim = this.dim;
|
|
123
|
+
const pd = this.paddedDim;
|
|
124
|
+
const buf = this.scratch;
|
|
125
|
+
let sq = 0;
|
|
126
|
+
for (let i = 0; i < dim; i++) {
|
|
127
|
+
const v = vec[i] - this.centroid[i];
|
|
128
|
+
buf[i] = v;
|
|
129
|
+
sq += v * v;
|
|
130
|
+
}
|
|
131
|
+
for (let i = dim; i < pd; i++)
|
|
132
|
+
buf[i] = 0;
|
|
133
|
+
const code = new Uint32Array(this.codeWords);
|
|
134
|
+
if (sq === 0) {
|
|
135
|
+
return code;
|
|
136
|
+
}
|
|
137
|
+
const invNorm = 1 / Math.sqrt(sq);
|
|
138
|
+
for (let i = 0; i < dim; i++)
|
|
139
|
+
buf[i] *= invNorm; // unit residual; padded dims stay 0
|
|
140
|
+
this.rotate(buf);
|
|
141
|
+
for (let i = 0; i < pd; i++) {
|
|
142
|
+
if (buf[i] > 0)
|
|
143
|
+
code[i >>> 5] |= 1 << (i & 31);
|
|
144
|
+
}
|
|
145
|
+
return code;
|
|
146
|
+
}
|
|
147
|
+
/** Pre-process a full-precision query into the structure consumed by `estimate`. */
|
|
148
|
+
prepareQuery(vec) {
|
|
149
|
+
const dim = this.dim;
|
|
150
|
+
const pd = this.paddedDim;
|
|
151
|
+
const nb = this.nbytes;
|
|
152
|
+
const buf = this.scratch;
|
|
153
|
+
let sq = 0;
|
|
154
|
+
for (let i = 0; i < dim; i++) {
|
|
155
|
+
const v = vec[i] - this.centroid[i];
|
|
156
|
+
buf[i] = v;
|
|
157
|
+
sq += v * v;
|
|
158
|
+
}
|
|
159
|
+
for (let i = dim; i < pd; i++)
|
|
160
|
+
buf[i] = 0;
|
|
161
|
+
const qNorm = Math.sqrt(sq);
|
|
162
|
+
const qlut = this.lutWide
|
|
163
|
+
? new Uint16Array(nb * 256)
|
|
164
|
+
: new Uint8Array(nb * 256);
|
|
165
|
+
if (qNorm === 0) {
|
|
166
|
+
return { vmin: 0, delta: 0, sumQInt: 0, qlut, nbytes: nb, zero: true };
|
|
167
|
+
}
|
|
168
|
+
const invNorm = 1 / qNorm;
|
|
169
|
+
for (let i = 0; i < dim; i++)
|
|
170
|
+
buf[i] *= invNorm;
|
|
171
|
+
this.rotate(buf);
|
|
172
|
+
let vmin = Infinity;
|
|
173
|
+
let vmax = -Infinity;
|
|
174
|
+
for (let i = 0; i < pd; i++) {
|
|
175
|
+
const x = buf[i];
|
|
176
|
+
if (x < vmin)
|
|
177
|
+
vmin = x;
|
|
178
|
+
if (x > vmax)
|
|
179
|
+
vmax = x;
|
|
180
|
+
}
|
|
181
|
+
const range = vmax - vmin;
|
|
182
|
+
const delta = range > 0 ? range / this.maxQInt : 0;
|
|
183
|
+
const invDelta = delta > 0 ? 1 / delta : 0;
|
|
184
|
+
// Quantise each (rotated) query coordinate to queryBits bits.
|
|
185
|
+
const qint = buf; // reuse: write the integer code back over the float buffer
|
|
186
|
+
let sumQInt = 0;
|
|
187
|
+
for (let i = 0; i < pd; i++) {
|
|
188
|
+
let q = delta > 0 ? Math.round((buf[i] - vmin) * invDelta) : 0;
|
|
189
|
+
if (q < 0)
|
|
190
|
+
q = 0;
|
|
191
|
+
else if (q > this.maxQInt)
|
|
192
|
+
q = this.maxQInt;
|
|
193
|
+
qint[i] = q;
|
|
194
|
+
sumQInt += q;
|
|
195
|
+
}
|
|
196
|
+
// Build the byte LUT: qlut[p*256 + v] = sum of qint at coords whose bit is
|
|
197
|
+
// set in v, grown incrementally as qlut[..(v with lowest set bit cleared)..]
|
|
198
|
+
// plus the contribution of that lowest set bit.
|
|
199
|
+
const bitCoord = this.bitCoord;
|
|
200
|
+
for (let p = 0; p < nb; p++) {
|
|
201
|
+
const base = p << 8;
|
|
202
|
+
const cb = p << 3;
|
|
203
|
+
for (let v = 1; v < 256; v++) {
|
|
204
|
+
const low = v & -v;
|
|
205
|
+
const k = 31 - Math.clz32(low);
|
|
206
|
+
qlut[base + v] = qlut[base + (v & (v - 1))] + qint[bitCoord[cb + k]];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return { vmin, delta, sumQInt, qlut, nbytes: nb, zero: false };
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Estimate the cosine distance (1 - cosine) between a stored code and a
|
|
213
|
+
* full-precision query, reading the code's bytes against the query's byte LUT.
|
|
214
|
+
* The code's set-bit count is tallied in the same byte scan, so nothing beyond
|
|
215
|
+
* the code itself is needed.
|
|
216
|
+
*
|
|
217
|
+
* `codeBytes` is a Uint8 view of the packed code buffer and `byteOffset` is the
|
|
218
|
+
* code's start byte (id * paddedDim/8).
|
|
219
|
+
*/
|
|
220
|
+
estimate(codeBytes, byteOffset, q) {
|
|
221
|
+
if (q.zero) {
|
|
222
|
+
return 1;
|
|
223
|
+
}
|
|
224
|
+
const nb = q.nbytes;
|
|
225
|
+
const lut = q.qlut;
|
|
226
|
+
let dot = 0;
|
|
227
|
+
let popcount = 0;
|
|
228
|
+
for (let p = 0; p < nb; p++) {
|
|
229
|
+
const b = codeBytes[byteOffset + p];
|
|
230
|
+
dot += lut[(p << 8) + b];
|
|
231
|
+
popcount += POPCOUNT8[b];
|
|
232
|
+
}
|
|
233
|
+
// A = sum_i sign_i * q_rot_i, recovered from the quantised query.
|
|
234
|
+
const A = q.vmin * (2 * popcount - this.paddedDim) +
|
|
235
|
+
q.delta * (2 * dot - q.sumQInt);
|
|
236
|
+
return 1 - this.cosFactor * A;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Cosine distance (1 - cosine, in [0, 2]) between two packed codes, computed
|
|
240
|
+
* directly from the BLOB bytes via their sign-bit Hamming distance — no word
|
|
241
|
+
* reinterpretation, so it is endianness-agnostic. Identical codes score 0.
|
|
242
|
+
*
|
|
243
|
+
* This is the distance used to build the graph (code vs code) and to answer a
|
|
244
|
+
* query given an already-quantized code. It is coarser than `estimate`, where
|
|
245
|
+
* one side is full precision.
|
|
246
|
+
*/
|
|
247
|
+
codeDistanceBytes(a, b) {
|
|
248
|
+
const nb = this.nbytes;
|
|
249
|
+
let ham = 0;
|
|
250
|
+
// 32-bit-word Hamming: this is the hot arithmetic of graph construction
|
|
251
|
+
// (every candidate/prune comparison), so fold 4 bytes into one word and
|
|
252
|
+
// popcount it — ~4× fewer loop iterations than a byte-LUT scan, with no
|
|
253
|
+
// allocation and no dependence on the buffers' alignment or endianness
|
|
254
|
+
// (both sides are composed identically, so XOR is order-agnostic).
|
|
255
|
+
let p = 0;
|
|
256
|
+
for (const n4 = nb & ~3; p < n4; p += 4) {
|
|
257
|
+
let x = (a[p] ^ b[p]) |
|
|
258
|
+
((a[p + 1] ^ b[p + 1]) << 8) |
|
|
259
|
+
((a[p + 2] ^ b[p + 2]) << 16) |
|
|
260
|
+
((a[p + 3] ^ b[p + 3]) << 24);
|
|
261
|
+
x -= (x >>> 1) & 0x55555555;
|
|
262
|
+
x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
|
|
263
|
+
x = (x + (x >>> 4)) & 0x0f0f0f0f;
|
|
264
|
+
ham += Math.imul(x, 0x01010101) >>> 24;
|
|
265
|
+
}
|
|
266
|
+
for (; p < nb; p++)
|
|
267
|
+
ham += POPCOUNT8[a[p] ^ b[p]];
|
|
268
|
+
return (2 * ham) / this.paddedDim;
|
|
269
|
+
}
|
|
270
|
+
/** Pack a code (codeWords 32-bit words) into its little-endian BLOB bytes. */
|
|
271
|
+
codeToBytes(code) {
|
|
272
|
+
const u = new Uint32Array(this.codeWords);
|
|
273
|
+
for (let i = 0; i < this.codeWords; i++)
|
|
274
|
+
u[i] = code[i];
|
|
275
|
+
return new Uint8Array(u.buffer, 0, u.byteLength);
|
|
276
|
+
}
|
|
277
|
+
/** Reinterpret a code BLOB as a copy of codeWords 32-bit words. */
|
|
278
|
+
bytesToCode(bytes) {
|
|
279
|
+
const u = new Uint32Array(this.codeWords);
|
|
280
|
+
new Uint8Array(u.buffer).set(bytes);
|
|
281
|
+
return u;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Permutation, Vec } from "./vec.js";
|
|
2
|
+
/** The one structure. A node's vector is the gist of its whole subtree; it also
|
|
3
|
+
* carries the structure the DAG store interns — its leaf bytes, or its kids. */
|
|
4
|
+
export interface Sema {
|
|
5
|
+
v: Vec;
|
|
6
|
+
leaf: Uint8Array | null;
|
|
7
|
+
kids: Sema[] | null;
|
|
8
|
+
}
|
|
9
|
+
export declare const sema: (v: Vec, leaf?: Uint8Array | null, kids?: Sema[] | null) => Sema;
|
|
10
|
+
/** Whether a node is a CHUNK — a leaf-parent whose children are ALL leaves,
|
|
11
|
+
* the perception tree's smallest grouped unit. The one predicate behind
|
|
12
|
+
* region collection, canonical segmentation seams, and sub-span indexing;
|
|
13
|
+
* named here beside the type so no consumer restates the shape inline. */
|
|
14
|
+
export declare const isChunk: (n: Sema) => n is Sema & {
|
|
15
|
+
kids: Sema[];
|
|
16
|
+
};
|
|
17
|
+
/** The medium: dimension, keyring, and noise source. */
|
|
18
|
+
export interface Space {
|
|
19
|
+
D: number;
|
|
20
|
+
seats: Permutation[];
|
|
21
|
+
rand: () => number;
|
|
22
|
+
maxGroup: number;
|
|
23
|
+
}
|
|
24
|
+
/** Bind one vector into a seat — the elementary half of fold. Used to index an
|
|
25
|
+
* episode from either side and to pour a partner into a form's halo. */
|
|
26
|
+
export declare const bindSeat: (space: Space, v: Vec, seat: number) => Vec;
|
|
27
|
+
/** The company signature of node `id` — the halo's pour unit (see above). */
|
|
28
|
+
export declare function companySignature(space: Space, id: number): Vec;
|
|
29
|
+
/** fold — combine ordered children into one gist.
|
|
30
|
+
* Each child is turned with its seat's own key, superposed, normalized. */
|
|
31
|
+
export declare function fold(space: Space, kids: Vec[]): Vec;
|
package/dist/src/sema.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { addInto, normalize, permute, permuteInto, randomUnit, rng, zeros, } from "./vec.js";
|
|
2
|
+
export const sema = (v, leaf = null, kids = null) => ({ v, leaf, kids });
|
|
3
|
+
/** Whether a node is a CHUNK — a leaf-parent whose children are ALL leaves,
|
|
4
|
+
* the perception tree's smallest grouped unit. The one predicate behind
|
|
5
|
+
* region collection, canonical segmentation seams, and sub-span indexing;
|
|
6
|
+
* named here beside the type so no consumer restates the shape inline. */
|
|
7
|
+
export const isChunk = (n) => n.kids !== null && n.kids.every((k) => k.kids === null);
|
|
8
|
+
// Reusable permute buffer for fold.
|
|
9
|
+
let _foldBuf = null;
|
|
10
|
+
/** Bind one vector into a seat — the elementary half of fold. Used to index an
|
|
11
|
+
* episode from either side and to pour a partner into a form's halo. */
|
|
12
|
+
export const bindSeat = (space, v, seat) => permute(v, space.seats[seat].fwd);
|
|
13
|
+
// ── Company signatures ──────────────────────────────────────────────────
|
|
14
|
+
//
|
|
15
|
+
// A halo is a superposition of EPISODE SIGNATURES: it answers "who does this
|
|
16
|
+
// form keep company with", and two forms share a concept when they keep the
|
|
17
|
+
// SAME company (the same partner nodes). Pouring the partner's raw GIST was
|
|
18
|
+
// an approximation of that: it worked while the hierarchical fold decorrelated
|
|
19
|
+
// unrelated gists quickly, but any byte-overlap between partners leaks CONTENT
|
|
20
|
+
// similarity into COMPANY similarity, silently shifting the halo null model
|
|
21
|
+
// that conceptThreshold's derivation (unrelated halos ⇒ cosine 0 ± 1/√D)
|
|
22
|
+
// depends on. A signature makes the semantics exact and fold-independent:
|
|
23
|
+
// a deterministic unit vector derived from the partner's IDENTITY, so two
|
|
24
|
+
// halos correlate exactly as much as their company overlaps — never because
|
|
25
|
+
// their partners merely contain similar bytes.
|
|
26
|
+
//
|
|
27
|
+
// Seeded by node id: ids are content-addressed mint order, stable for a given
|
|
28
|
+
// corpus (including checkpoint/resume, which re-derives identical ids), and
|
|
29
|
+
// halos are per-store training artifacts that are never compared across
|
|
30
|
+
// stores.
|
|
31
|
+
const _sigCache = new WeakMap();
|
|
32
|
+
const SIG_CACHE_MAX = 65_536;
|
|
33
|
+
/** The company signature of node `id` — the halo's pour unit (see above). */
|
|
34
|
+
export function companySignature(space, id) {
|
|
35
|
+
let cache = _sigCache.get(space);
|
|
36
|
+
if (!cache)
|
|
37
|
+
_sigCache.set(space, cache = new Map());
|
|
38
|
+
const hit = cache.get(id);
|
|
39
|
+
if (hit)
|
|
40
|
+
return hit;
|
|
41
|
+
const v = randomUnit(space.D, rng((id ^ 0x9e3779b9) >>> 0));
|
|
42
|
+
if (cache.size >= SIG_CACHE_MAX)
|
|
43
|
+
cache.clear(); // flat cap; regeneration is cheap
|
|
44
|
+
cache.set(id, v);
|
|
45
|
+
return v;
|
|
46
|
+
}
|
|
47
|
+
/** fold — combine ordered children into one gist.
|
|
48
|
+
* Each child is turned with its seat's own key, superposed, normalized. */
|
|
49
|
+
export function fold(space, kids) {
|
|
50
|
+
if (kids.length > space.seats.length) {
|
|
51
|
+
throw new Error(`fold: ${kids.length} children but the keyring has only ${space.seats.length} seats`);
|
|
52
|
+
}
|
|
53
|
+
const out = zeros(space.D);
|
|
54
|
+
if (!_foldBuf || _foldBuf.length !== space.D) {
|
|
55
|
+
_foldBuf = new Float32Array(space.D);
|
|
56
|
+
}
|
|
57
|
+
const buf = _foldBuf;
|
|
58
|
+
for (let i = 0; i < kids.length; i++) {
|
|
59
|
+
permuteInto(buf, kids[i], space.seats[i].fwd);
|
|
60
|
+
addInto(out, buf);
|
|
61
|
+
}
|
|
62
|
+
return normalize(out);
|
|
63
|
+
}
|