@hviana/sema 0.1.5 → 0.1.6

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.
Files changed (160) hide show
  1. package/AGENTS.md +6 -5
  2. package/CITATION.cff +49 -0
  3. package/HOW_IT_WORKS.md +11 -12
  4. package/README.md +7 -5
  5. package/dist/example/demo.js +25 -25
  6. package/dist/example/train_base.d.ts +19 -21
  7. package/dist/example/train_base.js +1687 -1952
  8. package/dist/src/alphabet.d.ts +3 -3
  9. package/dist/src/alphabet.js +24 -27
  10. package/dist/src/alu/src/alu.d.ts +169 -194
  11. package/dist/src/alu/src/alu.js +374 -414
  12. package/dist/src/alu/src/expr.d.ts +36 -43
  13. package/dist/src/alu/src/expr.js +252 -278
  14. package/dist/src/alu/src/index.d.ts +9 -98
  15. package/dist/src/alu/src/index.js +10 -64
  16. package/dist/src/alu/src/kernel-arith.d.ts +1 -5
  17. package/dist/src/alu/src/kernel-arith.js +195 -285
  18. package/dist/src/alu/src/kernel-bits.d.ts +1 -5
  19. package/dist/src/alu/src/kernel-bits.js +81 -115
  20. package/dist/src/alu/src/kernel-logic.js +33 -63
  21. package/dist/src/alu/src/kernel-nd.js +155 -195
  22. package/dist/src/alu/src/kernel-numeric.d.ts +16 -80
  23. package/dist/src/alu/src/kernel-numeric.js +259 -331
  24. package/dist/src/alu/src/operation.d.ts +112 -132
  25. package/dist/src/alu/src/operation.js +149 -163
  26. package/dist/src/alu/src/parser.d.ts +168 -175
  27. package/dist/src/alu/src/parser.js +382 -421
  28. package/dist/src/alu/src/resonance.d.ts +16 -25
  29. package/dist/src/alu/src/resonance.js +49 -56
  30. package/dist/src/alu/src/text.d.ts +3 -7
  31. package/dist/src/alu/src/text.js +31 -37
  32. package/dist/src/alu/src/value.d.ts +14 -14
  33. package/dist/src/alu/src/value.js +150 -160
  34. package/dist/src/alu/test/alu.test.js +543 -656
  35. package/dist/src/bytes.d.ts +1 -5
  36. package/dist/src/bytes.js +33 -40
  37. package/dist/src/config.d.ts +99 -102
  38. package/dist/src/config.js +78 -83
  39. package/dist/src/derive/src/deduction.d.ts +60 -62
  40. package/dist/src/derive/src/deduction.js +103 -109
  41. package/dist/src/derive/src/index.d.ts +1 -7
  42. package/dist/src/derive/src/priority-queue.d.ts +8 -8
  43. package/dist/src/derive/src/priority-queue.js +57 -61
  44. package/dist/src/derive/src/rewrite.d.ts +15 -18
  45. package/dist/src/derive/src/rewrite.js +59 -67
  46. package/dist/src/derive/src/trie.d.ts +56 -56
  47. package/dist/src/derive/src/trie.js +175 -179
  48. package/dist/src/derive/test/derive.test.js +96 -100
  49. package/dist/src/extension.d.ts +13 -16
  50. package/dist/src/geometry.d.ts +17 -42
  51. package/dist/src/geometry.js +235 -266
  52. package/dist/src/index.d.ts +2 -17
  53. package/dist/src/index.js +2 -12
  54. package/dist/src/ingest-cache.d.ts +25 -30
  55. package/dist/src/ingest-cache.js +108 -127
  56. package/dist/src/mind/articulation.d.ts +1 -5
  57. package/dist/src/mind/articulation.js +77 -112
  58. package/dist/src/mind/attention.d.ts +40 -108
  59. package/dist/src/mind/attention.js +749 -871
  60. package/dist/src/mind/canonical.d.ts +4 -19
  61. package/dist/src/mind/canonical.js +27 -31
  62. package/dist/src/mind/graph-search.d.ts +201 -225
  63. package/dist/src/mind/graph-search.js +742 -821
  64. package/dist/src/mind/index.d.ts +2 -10
  65. package/dist/src/mind/junction.d.ts +31 -58
  66. package/dist/src/mind/junction.js +172 -237
  67. package/dist/src/mind/learning.d.ts +16 -52
  68. package/dist/src/mind/learning.js +143 -165
  69. package/dist/src/mind/match.d.ts +20 -69
  70. package/dist/src/mind/match.js +259 -318
  71. package/dist/src/mind/mechanisms/alu.js +16 -16
  72. package/dist/src/mind/mechanisms/cast.d.ts +9 -13
  73. package/dist/src/mind/mechanisms/cast.js +363 -456
  74. package/dist/src/mind/mechanisms/confluence.d.ts +8 -12
  75. package/dist/src/mind/mechanisms/confluence.js +152 -183
  76. package/dist/src/mind/mechanisms/cover.d.ts +2 -8
  77. package/dist/src/mind/mechanisms/cover.js +148 -210
  78. package/dist/src/mind/mechanisms/extraction.d.ts +8 -34
  79. package/dist/src/mind/mechanisms/extraction.js +234 -288
  80. package/dist/src/mind/mechanisms/recall.d.ts +6 -10
  81. package/dist/src/mind/mechanisms/recall.js +126 -185
  82. package/dist/src/mind/mind.d.ts +129 -154
  83. package/dist/src/mind/mind.js +258 -288
  84. package/dist/src/mind/pipeline-mechanism.d.ts +112 -124
  85. package/dist/src/mind/pipeline-mechanism.js +161 -172
  86. package/dist/src/mind/pipeline.d.ts +4 -14
  87. package/dist/src/mind/pipeline.js +125 -189
  88. package/dist/src/mind/primitives.d.ts +8 -32
  89. package/dist/src/mind/primitives.js +99 -117
  90. package/dist/src/mind/rationale.d.ts +86 -98
  91. package/dist/src/mind/rationale.js +113 -121
  92. package/dist/src/mind/reasoning.d.ts +2 -13
  93. package/dist/src/mind/reasoning.js +129 -166
  94. package/dist/src/mind/recognition.d.ts +1 -4
  95. package/dist/src/mind/recognition.js +183 -208
  96. package/dist/src/mind/resonance.d.ts +5 -22
  97. package/dist/src/mind/resonance.js +0 -0
  98. package/dist/src/mind/trace.d.ts +6 -25
  99. package/dist/src/mind/trace.js +50 -58
  100. package/dist/src/mind/traverse.d.ts +16 -58
  101. package/dist/src/mind/traverse.js +304 -357
  102. package/dist/src/mind/types.d.ts +120 -127
  103. package/dist/src/mind/types.js +60 -69
  104. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  105. package/dist/src/rabitq-ivf/src/database.js +201 -0
  106. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  107. package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/index.js +1 -3
  108. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  109. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  110. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  111. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  112. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  113. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  114. package/dist/src/sema.d.ts +9 -13
  115. package/dist/src/sema.js +26 -40
  116. package/dist/src/store-sqlite.d.ts +169 -166
  117. package/dist/src/store-sqlite.js +762 -662
  118. package/dist/src/store.d.ts +586 -630
  119. package/dist/src/store.js +1423 -1581
  120. package/dist/src/vec.d.ts +5 -9
  121. package/dist/src/vec.js +61 -73
  122. package/example/train_base.ts +13 -10
  123. package/package.json +1 -1
  124. package/src/alu/README.md +1 -1
  125. package/src/alu/src/index.ts +1 -1
  126. package/src/config.ts +19 -27
  127. package/src/index.ts +6 -11
  128. package/src/rabitq-ivf/README.md +56 -0
  129. package/src/rabitq-ivf/src/database.ts +276 -0
  130. package/src/{rabitq-hnsw → rabitq-ivf}/src/index.ts +2 -5
  131. package/src/rabitq-ivf/src/ivf.ts +1330 -0
  132. package/src/{rabitq-hnsw → rabitq-ivf}/src/prng.ts +1 -1
  133. package/src/store-sqlite.ts +196 -9
  134. package/src/store.ts +8 -32
  135. package/test/08-storage.test.mjs +3 -3
  136. package/test/14-scaling.test.mjs +2 -2
  137. package/test/35-ivf.test.mjs +263 -0
  138. package/test/36-bloom.test.mjs +123 -0
  139. package/dist/src/rabitq-hnsw/src/database.d.ts +0 -202
  140. package/dist/src/rabitq-hnsw/src/database.js +0 -405
  141. package/dist/src/rabitq-hnsw/src/heap.d.ts +0 -22
  142. package/dist/src/rabitq-hnsw/src/heap.js +0 -94
  143. package/dist/src/rabitq-hnsw/src/hnsw.d.ts +0 -125
  144. package/dist/src/rabitq-hnsw/src/hnsw.js +0 -500
  145. package/dist/src/rabitq-hnsw/src/index.d.ts +0 -15
  146. package/dist/src/rabitq-hnsw/src/prng.d.ts +0 -19
  147. package/dist/src/rabitq-hnsw/src/prng.js +0 -38
  148. package/dist/src/rabitq-hnsw/src/rabitq.d.ts +0 -95
  149. package/dist/src/rabitq-hnsw/src/rabitq.js +0 -299
  150. package/dist/src/rabitq-hnsw/src/store.d.ts +0 -162
  151. package/dist/src/rabitq-hnsw/src/store.js +0 -916
  152. package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +0 -1
  153. package/dist/src/rabitq-hnsw/test/hnsw.test.js +0 -1197
  154. package/src/rabitq-hnsw/README.md +0 -303
  155. package/src/rabitq-hnsw/src/database.ts +0 -492
  156. package/src/rabitq-hnsw/src/heap.ts +0 -90
  157. package/src/rabitq-hnsw/src/hnsw.ts +0 -514
  158. package/src/rabitq-hnsw/src/store.ts +0 -994
  159. package/src/rabitq-hnsw/test/hnsw.test.ts +0 -1213
  160. /package/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.ts +0 -0
@@ -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
+ }
@@ -2,28 +2,24 @@ import { Permutation, Vec } from "./vec.js";
2
2
  /** The one structure. A node's vector is the gist of its whole subtree; it also
3
3
  * carries the structure the DAG store interns — its leaf bytes, or its kids. */
4
4
  export interface Sema {
5
- v: Vec;
6
- leaf: Uint8Array | null;
7
- kids: Sema[] | null;
5
+ v: Vec;
6
+ leaf: Uint8Array | null;
7
+ kids: Sema[] | null;
8
8
  }
9
- export declare const sema: (
10
- v: Vec,
11
- leaf?: Uint8Array | null,
12
- kids?: Sema[] | null,
13
- ) => Sema;
9
+ export declare const sema: (v: Vec, leaf?: Uint8Array | null, kids?: Sema[] | null) => Sema;
14
10
  /** Whether a node is a CHUNK — a leaf-parent whose children are ALL leaves,
15
11
  * the perception tree's smallest grouped unit. The one predicate behind
16
12
  * region collection, canonical segmentation seams, and sub-span indexing;
17
13
  * named here beside the type so no consumer restates the shape inline. */
18
14
  export declare const isChunk: (n: Sema) => n is Sema & {
19
- kids: Sema[];
15
+ kids: Sema[];
20
16
  };
21
17
  /** The medium: dimension, keyring, and noise source. */
22
18
  export interface Space {
23
- D: number;
24
- seats: Permutation[];
25
- rand: () => number;
26
- maxGroup: number;
19
+ D: number;
20
+ seats: Permutation[];
21
+ rand: () => number;
22
+ maxGroup: number;
27
23
  }
28
24
  /** Bind one vector into a seat — the elementary half of fold. Used to index an
29
25
  * episode from either side and to pour a partner into a form's halo. */
package/dist/src/sema.js CHANGED
@@ -1,19 +1,10 @@
1
- import {
2
- addInto,
3
- normalize,
4
- permute,
5
- permuteInto,
6
- randomUnit,
7
- rng,
8
- zeros,
9
- } from "./vec.js";
1
+ import { addInto, normalize, permute, permuteInto, randomUnit, rng, zeros, } from "./vec.js";
10
2
  export const sema = (v, leaf = null, kids = null) => ({ v, leaf, kids });
11
3
  /** Whether a node is a CHUNK — a leaf-parent whose children are ALL leaves,
12
4
  * the perception tree's smallest grouped unit. The one predicate behind
13
5
  * region collection, canonical segmentation seams, and sub-span indexing;
14
6
  * named here beside the type so no consumer restates the shape inline. */
15
- export const isChunk = (n) =>
16
- n.kids !== null && n.kids.every((k) => k.kids === null);
7
+ export const isChunk = (n) => n.kids !== null && n.kids.every((k) => k.kids === null);
17
8
  // Reusable permute buffer for fold.
18
9
  let _foldBuf = null;
19
10
  /** Bind one vector into a seat — the elementary half of fold. Used to index an
@@ -41,37 +32,32 @@ const _sigCache = new WeakMap();
41
32
  const SIG_CACHE_MAX = 65_536;
42
33
  /** The company signature of node `id` — the halo's pour unit (see above). */
43
34
  export function companySignature(space, id) {
44
- let cache = _sigCache.get(space);
45
- if (!cache) {
46
- _sigCache.set(space, cache = new Map());
47
- }
48
- const hit = cache.get(id);
49
- if (hit) {
50
- return hit;
51
- }
52
- const v = randomUnit(space.D, rng((id ^ 0x9e3779b9) >>> 0));
53
- if (cache.size >= SIG_CACHE_MAX) {
54
- cache.clear(); // flat cap; regeneration is cheap
55
- }
56
- cache.set(id, v);
57
- return v;
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;
58
46
  }
59
47
  /** fold — combine ordered children into one gist.
60
48
  * Each child is turned with its seat's own key, superposed, normalized. */
61
49
  export function fold(space, kids) {
62
- if (kids.length > space.seats.length) {
63
- throw new Error(
64
- `fold: ${kids.length} children but the keyring has only ${space.seats.length} seats`,
65
- );
66
- }
67
- const out = zeros(space.D);
68
- if (!_foldBuf || _foldBuf.length !== space.D) {
69
- _foldBuf = new Float32Array(space.D);
70
- }
71
- const buf = _foldBuf;
72
- for (let i = 0; i < kids.length; i++) {
73
- permuteInto(buf, kids[i], space.seats[i].fwd);
74
- addInto(out, buf);
75
- }
76
- return normalize(out);
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);
77
63
  }