@hviana/sema 0.4.2 → 0.4.3
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 +136 -0
- package/dist/src/derive/src/deduction.js +159 -0
- package/dist/src/derive/src/index.d.ts +8 -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 +175 -0
- package/dist/src/geometry.js +823 -0
- package/dist/src/index.d.ts +17 -0
- package/dist/src/index.js +19 -0
- package/dist/src/ingest-cache.d.ts +41 -0
- package/dist/src/ingest-cache.js +165 -0
- package/dist/src/meter.d.ts +176 -0
- package/dist/src/meter.js +274 -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 +414 -0
- package/dist/src/mind/attention.js +2082 -0
- package/dist/src/mind/bridge.d.ts +39 -0
- package/dist/src/mind/bridge.js +947 -0
- package/dist/src/mind/canonical.d.ts +34 -0
- package/dist/src/mind/canonical.js +93 -0
- package/dist/src/mind/graph-search.d.ts +294 -0
- package/dist/src/mind/graph-search.js +996 -0
- package/dist/src/mind/index.d.ts +9 -0
- package/dist/src/mind/index.js +5 -0
- package/dist/src/mind/junction.d.ts +137 -0
- package/dist/src/mind/junction.js +342 -0
- package/dist/src/mind/learning.d.ts +75 -0
- package/dist/src/mind/learning.js +270 -0
- package/dist/src/mind/match.d.ts +181 -0
- package/dist/src/mind/match.js +655 -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 +784 -0
- package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
- package/dist/src/mind/mechanisms/confluence.js +255 -0
- package/dist/src/mind/mechanisms/cover.d.ts +6 -0
- package/dist/src/mind/mechanisms/cover.js +227 -0
- package/dist/src/mind/mechanisms/extraction.d.ts +33 -0
- package/dist/src/mind/mechanisms/extraction.js +300 -0
- package/dist/src/mind/mechanisms/recall.d.ts +16 -0
- package/dist/src/mind/mechanisms/recall.js +364 -0
- package/dist/src/mind/mind.d.ts +337 -0
- package/dist/src/mind/mind.js +617 -0
- package/dist/src/mind/pipeline-mechanism.d.ts +172 -0
- package/dist/src/mind/pipeline-mechanism.js +465 -0
- package/dist/src/mind/pipeline.d.ts +49 -0
- package/dist/src/mind/pipeline.js +275 -0
- package/dist/src/mind/primitives.d.ts +66 -0
- package/dist/src/mind/primitives.js +306 -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 +40 -0
- package/dist/src/mind/reasoning.js +280 -0
- package/dist/src/mind/recognition.d.ts +20 -0
- package/dist/src/mind/recognition.js +504 -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 +126 -0
- package/dist/src/mind/traverse.js +650 -0
- package/dist/src/mind/types.d.ts +333 -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 +678 -0
- package/dist/src/store.js +1703 -0
- package/dist/src/vec.d.ts +31 -0
- package/dist/src/vec.js +109 -0
- package/package.json +1 -1
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
// geometry.ts — every modality is a stream; geometry is only a reading order.
|
|
2
|
+
//
|
|
3
|
+
// 1. Each byte is a leaf — an atom carrying its own vector straight from
|
|
4
|
+
// the alphabet.
|
|
5
|
+
// 2. The river folds leaves upward in fixed-size groups (maxGroup). Items
|
|
6
|
+
// that cross the stable-prefix boundary are split so the prefix folds
|
|
7
|
+
// identically regardless of what follows — pure structural stability.
|
|
8
|
+
// 3. The same rule recurses level after level until one root remains.
|
|
9
|
+
import { addInto, copy, normalize, zeros } from "./vec.js";
|
|
10
|
+
import { sema } from "./sema.js";
|
|
11
|
+
// ---- geometric constants ----
|
|
12
|
+
//
|
|
13
|
+
// Every threshold below is a derived function of the fold's own geometry —
|
|
14
|
+
// dimension D, maxGroup, etc. — never a tuned magic number. They live here
|
|
15
|
+
// (not in a config file) because they follow from the structure itself.
|
|
16
|
+
//
|
|
17
|
+
// MEASUREMENT CAVEAT: these thresholds are compared against RaBitQ-ESTIMATED
|
|
18
|
+
// cosines (1-bit stored codes scored against a 4-bit-quantized query; the
|
|
19
|
+
// index never reranks with exact vectors). The derivations assume an exact
|
|
20
|
+
// cosine; the estimator adds a small, rotation-uniformised error the bars do
|
|
21
|
+
// not model. This is benign for the inequality thresholds (they gate broad
|
|
22
|
+
// regions), but it means NO decision may treat an estimated score as exact —
|
|
23
|
+
// identity in particular is decided by content-addressed resolve(), never by
|
|
24
|
+
// `score >= 1` (see recallByResonance tier 0).
|
|
25
|
+
/** The store's geometric identity bar: cosine ≥ 1 − 1/√D is the similarity at
|
|
26
|
+
* which `intern` already treats two gists as the SAME node. Recall reuses it
|
|
27
|
+
* to accept a near-identical query, and the climb to accept a containing form —
|
|
28
|
+
* one derived constant, never a tuned threshold. NOTE: this fixed bar is
|
|
29
|
+
* the ESTIMATOR floor of an identity claim; a whole-span claim over a span
|
|
30
|
+
* longer than the perception quantum must use the scale-aware
|
|
31
|
+
* {@link identityBar}, which converts the tolerated fraction into bytes. */
|
|
32
|
+
export function mergeThreshold(D) {
|
|
33
|
+
return 1 - 1 / Math.sqrt(D);
|
|
34
|
+
}
|
|
35
|
+
/** The scale-aware IDENTITY bar for a whole-span resonance claim over a span
|
|
36
|
+
* of `len` bytes. Under the linear fold a cosine reads "fraction of aligned
|
|
37
|
+
* shared bytes", so a FIXED cosine bar admits a byte budget that grows with
|
|
38
|
+
* the span: 1 − 1/√D over a 4·√D-byte span tolerates four whole river
|
|
39
|
+
* windows of foreign content while still claiming "near-identical". An
|
|
40
|
+
* identity claim may tolerate at most ONE river window W — the perception
|
|
41
|
+
* quantum, the same single-window budget near-dedup's differsByOneWindow
|
|
42
|
+
* grants — so the bar is 1 − W/len, floored at mergeThreshold(D), below
|
|
43
|
+
* which the RaBitQ estimator cannot certify identity anyway. This is the
|
|
44
|
+
* angle+magnitude form of the identity test: the ANGLE carries the shared
|
|
45
|
+
* fraction, the span's MAGNITUDE (√len, the linear fold's own norm) converts
|
|
46
|
+
* the tolerated fraction into tolerated bytes. Derived from W, D and the
|
|
47
|
+
* span; never tuned. */
|
|
48
|
+
export function identityBar(D, maxGroup, len) {
|
|
49
|
+
return Math.max(mergeThreshold(D), 1 - maxGroup / Math.max(1, len));
|
|
50
|
+
}
|
|
51
|
+
/** The reach bar: half a river quantum, derived from the fold's own geometry.
|
|
52
|
+
* A branch folds up to `maxGroup` children, so two forms that differ in ONE
|
|
53
|
+
* whole child — the smallest distinction perception can mean — sit at cosine
|
|
54
|
+
* ≈ 1 − 1/maxGroup. Half that quantum, 1 − 1/(2·maxGroup), is closer than any
|
|
55
|
+
* single-child difference can be: a positional echo of the same content.
|
|
56
|
+
*
|
|
57
|
+
* Recall uses this as its confidence floor: a query whose nearest resonant
|
|
58
|
+
* form sits below this bar is structurally unrelated to everything in the store
|
|
59
|
+
* — further than any single-child variant — and the system returns null rather
|
|
60
|
+
* than fabricate an answer from an unrelated form. Derived, never tuned. */
|
|
61
|
+
export function reachThreshold(maxGroup) {
|
|
62
|
+
return 1 - 1 / (2 * maxGroup);
|
|
63
|
+
}
|
|
64
|
+
/** The estimator's own noise floor: 1/√D — ONE standard deviation of the
|
|
65
|
+
* cosine between two independent random vectors in D dimensions (the same σ
|
|
66
|
+
* {@link significanceBar} takes three of). It is the smallest difference in
|
|
67
|
+
* cosine that is distinguishable from the rotation-uniformised RaBitQ
|
|
68
|
+
* estimation error (see the MEASUREMENT CAVEAT above): a contrastive margin
|
|
69
|
+
* below it is quantisation noise, not evidence. The consensus climb gates a
|
|
70
|
+
* region's vote on its discriminative margin clearing this floor — the
|
|
71
|
+
* minimal "above noise" bar, one σ, not the stricter 3σ relatedness bar.
|
|
72
|
+
* Derived, never tuned. */
|
|
73
|
+
export function estimatorNoise(D) {
|
|
74
|
+
return 1 / Math.sqrt(D);
|
|
75
|
+
}
|
|
76
|
+
/** The statistical-significance bar for whole-query resonance: 3/√D.
|
|
77
|
+
* In D dimensions the expected cosine of two independent random vectors is 0
|
|
78
|
+
* with standard deviation 1/√D. A cosine ≥ 3/√D is three standard deviations
|
|
79
|
+
* above chance — the query is statistically related to the store, not merely
|
|
80
|
+
* sharing random byte noise. Below this bar the consensus climb (which trusts
|
|
81
|
+
* sub-region resonance) is skipped: there is no evidence the query belongs to
|
|
82
|
+
* the same distribution as the stored content. Derived, never tuned. */
|
|
83
|
+
export function significanceBar(D) {
|
|
84
|
+
return 3 / Math.sqrt(D);
|
|
85
|
+
}
|
|
86
|
+
/** The concept (halo) threshold: the cosine above which two nodes share a
|
|
87
|
+
* distributional concept. A halo is a superposition of episode signatures in
|
|
88
|
+
* D-dimensional space, so the expected cosine between two unrelated halos is 0
|
|
89
|
+
* with standard deviation 1/√D. The structural midpoint 0.5 separates "more
|
|
90
|
+
* similar than not" from noise; the +0.5/√D term adds one half-sigma margin
|
|
91
|
+
* that vanishes as D → ∞, accounting for the wider noise band at lower D
|
|
92
|
+
* without inventing a tuned constant. At D=1024 this gives 0.516, within
|
|
93
|
+
* 3% of 0.5 — existing behavior is preserved while threshold and D move
|
|
94
|
+
* together. Derived, never tuned. */
|
|
95
|
+
export function conceptThreshold(D) {
|
|
96
|
+
return 0.5 + 0.5 / Math.sqrt(D);
|
|
97
|
+
}
|
|
98
|
+
/** The HALF-DOMINANCE predicate: whether a part covering `partLen` of a
|
|
99
|
+
* whole of `wholeLen` covers STRICTLY more than half of it. A span that
|
|
100
|
+
* dominates its whole can no longer discriminate the whole's own content —
|
|
101
|
+
* the one test behind liftAnswer's keep-the-frame rule, collectRegions'
|
|
102
|
+
* wrapper exclusion, and CAST's frame-depth majority (each cites this).
|
|
103
|
+
* CAST's frame-FRACTION gate is the deliberately CLOSED variant (≥ ½ is
|
|
104
|
+
* already unusable there) and stays inline where it is documented.
|
|
105
|
+
* Derived from the structural midpoint, never tuned. */
|
|
106
|
+
export function dominates(partLen, wholeLen) {
|
|
107
|
+
return partLen * 2 > wholeLen;
|
|
108
|
+
}
|
|
109
|
+
/** The consensus-vote significance floor: ln(N) + 1/2, where N is the number
|
|
110
|
+
* of learnt contexts (edge sources). A single region's IDF-weighted vote for
|
|
111
|
+
* an anchor reached through c contexts is at most ln(N/c) ≤ ln(N); the +1/2
|
|
112
|
+
* demands the pooled vote exceed what ONE maximally-specific region could
|
|
113
|
+
* contribute by half a unit — i.e. genuine corroboration beyond a lone
|
|
114
|
+
* region's echo at this corpus scale. The ONE floor both consumers gate on:
|
|
115
|
+
* recallByResonance trusting a climb anchor, and commitVotes admitting a
|
|
116
|
+
* further point of attention. Defined once here so the two can never
|
|
117
|
+
* drift apart. Derived from N, never tuned. */
|
|
118
|
+
export function consensusFloor(N) {
|
|
119
|
+
return Math.log(N) + 1 / 2;
|
|
120
|
+
}
|
|
121
|
+
/** The coverage bar for the reach (interior) index, when vector-similarity
|
|
122
|
+
* gating is used. Returns the concept threshold — the structural midpoint
|
|
123
|
+
* (~0.5 at D=1024) where two forms are "more similar than not."
|
|
124
|
+
*
|
|
125
|
+
* Currently UNUSED in the hot training path: interior nodes are indexed
|
|
126
|
+
* unconditionally (hash-cons dedup bounds the index naturally).
|
|
127
|
+
* Post-hoc structural compaction ({@link Store.compactContentIndex})
|
|
128
|
+
* replaces runtime coverage gating with a batch pass that removes
|
|
129
|
+
* structurally-isolated entries. Derived, never tuned. */
|
|
130
|
+
export function coverageBar(_maxGroup, D) {
|
|
131
|
+
return conceptThreshold(D);
|
|
132
|
+
}
|
|
133
|
+
// ---- folding ----
|
|
134
|
+
//
|
|
135
|
+
// The river fold is a hierarchical prefix network: each level contracts
|
|
136
|
+
// groups of `maxGroup` adjacent items into one via permute-then-add
|
|
137
|
+
// (positional seat binding), recursing until one root remains.
|
|
138
|
+
//
|
|
139
|
+
// FLAT per-level fold — one inline loop per level (foldSlice): no per-group
|
|
140
|
+
// function calls, no Array.slice per group, the permute and add FUSED
|
|
141
|
+
// (`gist[d] += v[seat[d]]`, no scratch buffer), and subtree byte lengths
|
|
142
|
+
// carried incrementally on Folded (the old boundary scan re-walked subtrees
|
|
143
|
+
// every level — O(n log n)). The per-level SUPERPOSITION is byte-identical
|
|
144
|
+
// to the original recursive foldGroup: the same FP additions in the same
|
|
145
|
+
// order.
|
|
146
|
+
//
|
|
147
|
+
// LINEAR fold — intermediate gists are NOT normalized; only the final root is
|
|
148
|
+
// (riverFold's single normalize). This is a deliberate change of similarity
|
|
149
|
+
// semantics from the original per-group normalize, not a cached optimization:
|
|
150
|
+
// the fold is now a pure linear operator — a superposition of positionally-
|
|
151
|
+
// bound leaf vectors — so an interior node carries its span's natural
|
|
152
|
+
// magnitude and a resonance score reads as byte-proportional overlap rather
|
|
153
|
+
// than a scale-free cosine. The mechanisms that depend on that reading
|
|
154
|
+
// compensate for it EXPLICITLY, never silently: the contrastive margin on
|
|
155
|
+
// approximate votes (voteRegions), company signatures decoupling halo company
|
|
156
|
+
// from gist content (sema.ts), and the shared-frame analogy tier (match.ts).
|
|
157
|
+
/** Fold `items[start .. start+count)` in groups of `mg` into `out`.
|
|
158
|
+
*
|
|
159
|
+
* With `force`, the trailing incomplete group (2..mg-1 items) is folded as
|
|
160
|
+
* well — only a lone singleton passes through. The river always folds with
|
|
161
|
+
* force: every level contracts by ~mg, so the tree's DEPTH is a function of
|
|
162
|
+
* ceil(log_mg(n)) alone. Letting leftovers pass through unfolded made depth
|
|
163
|
+
* depend on the exact byte count (39 bytes folded in 3 levels, 41 in 4), and
|
|
164
|
+
* each extra level applies another seat permutation to the whole gist —
|
|
165
|
+
* near-identical inputs straddling such a cliff read as orthogonal
|
|
166
|
+
* (measured: 33-byte-identical prefixes at cos ≈ 0). */
|
|
167
|
+
function foldSlice(space, items, start, count, out, force) {
|
|
168
|
+
const mg = space.maxGroup;
|
|
169
|
+
const D = space.D;
|
|
170
|
+
const complete = count - (count % mg);
|
|
171
|
+
const foldAt = (at, size) => {
|
|
172
|
+
const gist = new Float32Array(D);
|
|
173
|
+
const kids = new Array(size);
|
|
174
|
+
let len = 0;
|
|
175
|
+
for (let k = 0; k < size; k++) {
|
|
176
|
+
const f = items[at + k];
|
|
177
|
+
const seat = space.seats[k].fwd;
|
|
178
|
+
const v = f.tree.v;
|
|
179
|
+
// Fused permute-and-accumulate — same FP ops, same order as the old
|
|
180
|
+
// permuteInto + addInto pair, with no scratch buffer.
|
|
181
|
+
for (let d = 0; d < D; d++)
|
|
182
|
+
gist[d] += v[seat[d]];
|
|
183
|
+
kids[k] = f.tree;
|
|
184
|
+
len += f.len;
|
|
185
|
+
}
|
|
186
|
+
out.push({ tree: sema(gist, null, kids), len });
|
|
187
|
+
};
|
|
188
|
+
for (let i = 0; i < complete; i += mg)
|
|
189
|
+
foldAt(start + i, mg);
|
|
190
|
+
const leftover = count - complete;
|
|
191
|
+
if (leftover === 0)
|
|
192
|
+
return;
|
|
193
|
+
if (force && leftover >= 2)
|
|
194
|
+
foldAt(start + complete, leftover);
|
|
195
|
+
else
|
|
196
|
+
for (let i = complete; i < count; i++)
|
|
197
|
+
out.push(items[start + i]);
|
|
198
|
+
}
|
|
199
|
+
function riverFold(space, row, stableBytes) {
|
|
200
|
+
if (row.length === 0) {
|
|
201
|
+
const z = new Float32Array(space.D);
|
|
202
|
+
return { tree: sema(z, new Uint8Array(0), null), len: 0 };
|
|
203
|
+
}
|
|
204
|
+
let level = row;
|
|
205
|
+
while (level.length > 1) {
|
|
206
|
+
// Find the item index where accumulated bytes reaches stableBytes.
|
|
207
|
+
let boundary = level.length;
|
|
208
|
+
if (stableBytes > 0) {
|
|
209
|
+
let acc = 0;
|
|
210
|
+
for (let i = 0; i < level.length; i++) {
|
|
211
|
+
acc += level[i].len;
|
|
212
|
+
if (acc >= stableBytes) {
|
|
213
|
+
boundary = i + 1;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const next = [];
|
|
219
|
+
if (boundary < level.length) {
|
|
220
|
+
// Prefix folds independently of the suffix — structural stability.
|
|
221
|
+
foldSlice(space, level, 0, boundary, next, true);
|
|
222
|
+
foldSlice(space, level, boundary, level.length - boundary, next, true);
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
foldSlice(space, level, 0, level.length, next, true);
|
|
226
|
+
}
|
|
227
|
+
level = next;
|
|
228
|
+
}
|
|
229
|
+
// LINEAR fold — this root normalize is the ONLY normalize of the entire
|
|
230
|
+
// fold; every intermediate gist stays unnormalized (see the folding
|
|
231
|
+
// header). Skipped for a single-leaf input: that root IS the shared
|
|
232
|
+
// alphabet vector (already unit), and normalizing in place would mutate the
|
|
233
|
+
// alphabet itself.
|
|
234
|
+
if (row.length > 1)
|
|
235
|
+
normalize(level[0].tree.v);
|
|
236
|
+
return level[0];
|
|
237
|
+
}
|
|
238
|
+
// ---- public API ----
|
|
239
|
+
function bytesToLeaves(alphabet, bytes) {
|
|
240
|
+
return Array.from(bytes, (b, i) => {
|
|
241
|
+
const v = alphabet.vecs[b];
|
|
242
|
+
return { tree: sema(v, bytes.slice(i, i + 1), null), len: 1 };
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** CONTENT-DEFINED FOLD BOUNDARIES — where a byte stream segments, chosen by
|
|
246
|
+
* the bytes rather than by arithmetic.
|
|
247
|
+
*
|
|
248
|
+
* `riverFold` groups FIXED arity from byte 0 and permutes item k by
|
|
249
|
+
* `seats[k]`, k = index mod W, so a byte's contribution is a function of its
|
|
250
|
+
* ABSOLUTE OFFSET: the same byte run is a different vector at a different
|
|
251
|
+
* position, and the same content is a different SUBTREE. W's size has nothing
|
|
252
|
+
* to do with it — any fixed modulus does this, and identity must not depend on
|
|
253
|
+
* W at all.
|
|
254
|
+
*
|
|
255
|
+
* A rolling hash removes the dependence without touching the fold's arity: the
|
|
256
|
+
* cut lands where the hash of the recent bytes vanishes mod W, so a change
|
|
257
|
+
* upstream moves only the cut it falls inside — every downstream boundary, and
|
|
258
|
+
* therefore every downstream segment, is unchanged. Because
|
|
259
|
+
* {@link stablePrefixFold} folds each segment independently from its own slot
|
|
260
|
+
* 0, byte-identical content then produces byte-identical subtrees, and
|
|
261
|
+
* hash-consing makes it the SAME NODE ID wherever it appears. That — not the
|
|
262
|
+
* root cosine, which should and does still move when content is added — is
|
|
263
|
+
* what recognition, cover and resolve need.
|
|
264
|
+
*
|
|
265
|
+
* Measured over 400 real deposits, shifts of 1..7 bytes, downstream cuts
|
|
266
|
+
* preserved / segments byte-identical:
|
|
267
|
+
*
|
|
268
|
+
* content-defined, deposit text 99.7% / 98.4% mean seg 6.61 B
|
|
269
|
+
* content-defined, non-Latin scripts 99.6% / 98.3% mean seg 6.43 B
|
|
270
|
+
* content-defined, random binary 99.9% / 99.2% mean seg 6.92 B
|
|
271
|
+
* the arithmetic grid, same corpus 14.3% (only the k≡0 mod W
|
|
272
|
+
* shifts survive)
|
|
273
|
+
*
|
|
274
|
+
* The three content-defined rows agreeing is the load-bearing part: this reads
|
|
275
|
+
* BYTES, never text. Mind is not a text engine — the same fold carries grids
|
|
276
|
+
* and any other modality — so a boundary rule justified by where words or
|
|
277
|
+
* sentences fall would be importing an assumption the architecture rejects.
|
|
278
|
+
* Random binary must, and does, behave exactly like prose.
|
|
279
|
+
*
|
|
280
|
+
* Every constant is derived (§2.2): the cut mask is W, so a cut is offered once
|
|
281
|
+
* per quantum of bytes — which, composed with the minimum below, puts the
|
|
282
|
+
* expected segment at minLen + W − 1 ≈ 6 B rather than at W, deliberately (see
|
|
283
|
+
* the refutation recorded at `cutRate` in {@link contentLevels}: a segment is
|
|
284
|
+
* the flat PHRASE-scale unit the W-ary groups are built from, not a group of W
|
|
285
|
+
* children, and forcing E[len] = W costs 15 tests). The minimum is W−1, `canonicalWindows`'s
|
|
286
|
+
* straddle neighbour and the write side's own floor for a unit; and the maximum
|
|
287
|
+
* is the KEYRING's seat count, because a segment folds as ONE flat node and
|
|
288
|
+
* `fold` has exactly that many seats to bind children into. Capping there is
|
|
289
|
+
* what keeps the fold light: a segment of 3..seats leaves is a single node,
|
|
290
|
+
* where splitting it into W-groups plus a remainder would cost two or three
|
|
291
|
+
* and the remainders barely share (measured: partial-arity nodes 504 → 3,590,
|
|
292
|
+
* and total distinct nodes 8,142 → 9,712, when segments folded as [W][rest]). */
|
|
293
|
+
/** {@link contentBoundaries} plus, for each cut, its LEVEL — how deep in the
|
|
294
|
+
* tree that cut reaches.
|
|
295
|
+
*
|
|
296
|
+
* One rolling hash serves every scale. A cut is level 0 when its hash vanishes
|
|
297
|
+
* mod W, level 1 when mod W², and so on: level-L cuts are by construction a
|
|
298
|
+
* subset of level-(L−1) cuts, which is exactly the nesting a tree needs. The
|
|
299
|
+
* expected span of a level-L node is therefore W^(L+1) bytes — the same growth
|
|
300
|
+
* the grid fold had, but with boundaries the content chose, so a shift moves
|
|
301
|
+
* one node at each level instead of all of them.
|
|
302
|
+
*
|
|
303
|
+
* Levels are read from the hash the cut was ACCEPTED at, not recomputed, so
|
|
304
|
+
* they cost nothing beyond the divisions already being done. */
|
|
305
|
+
function contentLevels(space, bytes) {
|
|
306
|
+
const W = space.maxGroup;
|
|
307
|
+
const minLen = W - 1;
|
|
308
|
+
const maxLen = space.seats.length;
|
|
309
|
+
// MEASURED AND REFUTED — making E[segment] equal W. A segment is at least
|
|
310
|
+
// `minLen` bytes and then cuts with probability p, so E[len] = minLen +
|
|
311
|
+
// (1−p)/p; with `h % W === 0` that is minLen + W − 1 = 6 for W = 4 (measured
|
|
312
|
+
// mean 6.61 B on real deposits), half again coarser than the fold's own
|
|
313
|
+
// arity, and the doc above used to claim the mask made the two equal. It
|
|
314
|
+
// does not, and the mismatch looked like the cause of a real deficit: the
|
|
315
|
+
// climb perceives one region per segment, so on `Michelangelo is to sculpture
|
|
316
|
+
// as who is to literature?` it sees 9 regions where the grid saw 19, reaches
|
|
317
|
+
// one ranked anchor instead of two, and CAST's weave never includes the
|
|
318
|
+
// writing-domain exemplar it needs (test/29 A2, C1).
|
|
319
|
+
//
|
|
320
|
+
// Fixing the rate to hit E[len] = W (a threshold `h % W < W − minLen + 1` on
|
|
321
|
+
// the same rolling value, keeping the two bytes of history) does exactly what
|
|
322
|
+
// it says — mean segment 3.60 B on text, 3.93 B on random binary, 14 segments
|
|
323
|
+
// on that query instead of 9 — and takes the suite from 3 failures to 18,
|
|
324
|
+
// across think, universality, scaling, decomposition, bridge, generalization,
|
|
325
|
+
// saturation, audit and recognition. The coarser-than-arity scale is
|
|
326
|
+
// load-bearing: W is the arity `riverFold` groups CHILDREN at, and a segment
|
|
327
|
+
// is not a group of W children but the flat unit those groups are built from
|
|
328
|
+
// — a phrase-scale unit, and the mechanisms above all read it that way.
|
|
329
|
+
// Do not re-derive the rate from W.
|
|
330
|
+
//
|
|
331
|
+
// MEASURED AND REFUTED — reading the hash's HIGH bits instead of its low
|
|
332
|
+
// ones. The accumulator shifts LEFT, so `h % W` is the part the mixing has
|
|
333
|
+
// had no chance to reach: with `h = (h << 1) + byte·K` and K odd, `h mod 4`
|
|
334
|
+
// reduces to `(2·(prev mod 2) + byte) mod 4` — two bytes of history, and only
|
|
335
|
+
// their parity. It reads like a hash test that is really a byte-parity test,
|
|
336
|
+
// and it shows: on `Michelangelo is to sculpture as who is to literature?`
|
|
337
|
+
// the segments come out 8,8,8,8,8,7,4,2 — almost every boundary the FORCED
|
|
338
|
+
// one at maxLen, which is the one offset-dependent cut in the rule.
|
|
339
|
+
//
|
|
340
|
+
// Testing the top bits instead (`h < 2^32 / W`, the same 1/W rate, with the
|
|
341
|
+
// level test falling out as `h < 2^32 / W^(L+1)` — cleaner nesting than
|
|
342
|
+
// divisibility) takes the suite from 2 failures to 21 AND breaks the
|
|
343
|
+
// invariance floor in test/59. The reason is the whole point: in a
|
|
344
|
+
// shift-accumulator the LOW bits have a short effective window and the HIGH
|
|
345
|
+
// bits a long one, so a disturbance upstream perturbs the high bits for the
|
|
346
|
+
// next ~32 bytes while the low bits re-sync within two. The narrow window is
|
|
347
|
+
// not a defect in this hash — it IS the invariance. A boundary rule here is
|
|
348
|
+
// choosing how far a change may propagate, not how well the bits mix.
|
|
349
|
+
//
|
|
350
|
+
// MEASURED AND REFUTED — normalized chunking, to shrink the forced cut. The
|
|
351
|
+
// hard cut at maxLen is the ONE offset-dependent boundary left in the rule,
|
|
352
|
+
// and it is not rare: 32% of segments on a mixed sample end there, five of
|
|
353
|
+
// the eight in the query above, so for those streams the fold IS a grid of 2W
|
|
354
|
+
// with all of the grid's phase. The standard remedy applies cleanly here —
|
|
355
|
+
// past a target length, relax the mask by one power of the same radix
|
|
356
|
+
// (W → W/2), still content-defined and so still invariant, just coarser
|
|
357
|
+
// evidence for a boundary; both quantities are already in the rule, nothing
|
|
358
|
+
// introduced. It works as advertised: forced cuts fall from 32% to 8.3% and
|
|
359
|
+
// test/59's invariance floors still hold.
|
|
360
|
+
//
|
|
361
|
+
// And the suite goes from 2 failures to 5 relaxing at the expected length
|
|
362
|
+
// (minLen + W − 1), or to 6 relaxing at the last opportunity (maxLen − 1) —
|
|
363
|
+
// 22-multihop, 24-generalization, 29, 36. Taken with the two results above
|
|
364
|
+
// (changing the rate costs 15 tests; changing which bits are read costs 19),
|
|
365
|
+
// the reading is that the segment DISTRIBUTION is what the mechanisms
|
|
366
|
+
// downstream are fitted to, not the purity of the rule that produces it. The
|
|
367
|
+
// forced cut is part of that distribution. Do not tidy it away without
|
|
368
|
+
// re-measuring everything that reads a region.
|
|
369
|
+
const cuts = [];
|
|
370
|
+
const levels = [];
|
|
371
|
+
let h = 0;
|
|
372
|
+
let last = 0;
|
|
373
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
374
|
+
h = (((h << 1) >>> 0) + Math.imul(bytes[i], 2654435761)) >>> 0;
|
|
375
|
+
if (i + 1 >= bytes.length)
|
|
376
|
+
break;
|
|
377
|
+
const hit = h % W === 0;
|
|
378
|
+
if (i - last >= minLen && (hit || i - last + 1 >= maxLen)) {
|
|
379
|
+
cuts.push(i + 1);
|
|
380
|
+
// How many further powers of W divide the hash — 0 for a forced cut.
|
|
381
|
+
let lvl = 0;
|
|
382
|
+
if (hit) {
|
|
383
|
+
let m = W;
|
|
384
|
+
while (lvl < 24 && m <= 0x40000000 && h % (m * W) === 0) {
|
|
385
|
+
lvl++;
|
|
386
|
+
m *= W;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
levels.push(lvl);
|
|
390
|
+
last = i + 1;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return { cuts, levels };
|
|
394
|
+
}
|
|
395
|
+
export function contentBoundaries(space, bytes) {
|
|
396
|
+
// ONE implementation of the rule. This used to carry its own copy of the
|
|
397
|
+
// rolling-hash loop, which is exactly how a write side and a read side drift
|
|
398
|
+
// apart without a type error; the levels are computed from the hash the cut
|
|
399
|
+
// was accepted at, so asking for them costs nothing but an array.
|
|
400
|
+
return contentLevels(space, bytes).cuts;
|
|
401
|
+
}
|
|
402
|
+
/** Find the longest prefix of `bytes` whose leaf-id signature matches a
|
|
403
|
+
* known branch via `lookup`. Returns the byte-length of that prefix, or 0. */
|
|
404
|
+
export function knownPrefixLength(bytes, leafAt, lookup) {
|
|
405
|
+
const leafIds = [];
|
|
406
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
407
|
+
const lid = leafAt(i);
|
|
408
|
+
if (lid === null)
|
|
409
|
+
break;
|
|
410
|
+
leafIds.push(lid);
|
|
411
|
+
}
|
|
412
|
+
// Match the longest PROPER prefix — a full-length match means the entire
|
|
413
|
+
// input already exists as a stored form (e.g. the flat leaf-id branch
|
|
414
|
+
// stored alongside the structural root). That would hide the true split
|
|
415
|
+
// point and prevent the river from producing the same tree it folded
|
|
416
|
+
// during training, so the structural recognition cannot find the right
|
|
417
|
+
// forms. A proper prefix guarantees at least two regions.
|
|
418
|
+
for (let len = bytes.length - 1; len >= 2; len--) {
|
|
419
|
+
if (lookup(leafIds.slice(0, len)) !== null)
|
|
420
|
+
return len;
|
|
421
|
+
}
|
|
422
|
+
return 0;
|
|
423
|
+
}
|
|
424
|
+
/** Bytes → Sema tree. `leafAt` and `lookup` are store capabilities for
|
|
425
|
+
* detecting previously-stored prefixes so the river can split at the
|
|
426
|
+
* correct boundary. Pass them through from `perceive`; the geometry
|
|
427
|
+
* computes the stable prefix internally.
|
|
428
|
+
*
|
|
429
|
+
* `boundaries` is the CALLER-computed stable-prefix boundary set (§10.3):
|
|
430
|
+
* strictly-increasing proper byte offsets, each the length of a prefix that
|
|
431
|
+
* is already a stored whole-stream form. When given, the fold splits into
|
|
432
|
+
* the segments between consecutive boundaries — each folded independently,
|
|
433
|
+
* exactly as it folded when it was learned — and the segment roots join
|
|
434
|
+
* LEFT-NESTED (((s₀·s₁)·s₂)…), so every learnt cumulative-context root
|
|
435
|
+
* reappears as an identical subtree (and, by hash-consing, the very same
|
|
436
|
+
* node) inside the grown stream. This is what lets a conversation's next
|
|
437
|
+
* turn extend perception instead of refolding it: identical prefixes
|
|
438
|
+
* produce identical subtrees regardless of what follows them. */
|
|
439
|
+
export function bytesToTree(space, alphabet, bytes, leafAt, lookup, boundaries) {
|
|
440
|
+
if (bytes.length === 0) {
|
|
441
|
+
return sema(alphabet.vecs[0], new Uint8Array(0), null);
|
|
442
|
+
}
|
|
443
|
+
// WHERE A STREAM SEGMENTS IS DECIDED BY ITS BYTES ({@link contentBoundaries}),
|
|
444
|
+
// and the segments then fold BALANCED, W-ary, like any other row of items.
|
|
445
|
+
//
|
|
446
|
+
// The two must not be confused. Content cuts are what make identity
|
|
447
|
+
// offset-free: a segment folds from its own slot 0, so the same bytes give the
|
|
448
|
+
// same subtree wherever they sit. The shape ABOVE the segments is a separate
|
|
449
|
+
// question, and it must stay the river's own — grouping W at a time, depth
|
|
450
|
+
// log_W(n). Joining segments left-nested instead (as the stable-prefix fold
|
|
451
|
+
// does, for its own good reason) costs a node per segment on a single spine:
|
|
452
|
+
// at a cut every ~6.6 B a 3 KB deposit becomes a 450-deep spine of 450 fresh
|
|
453
|
+
// D-vectors, ~1.8 MB for one deposit, and every walker above inherits the
|
|
454
|
+
// depth. That is an implementation blunder, not a property of content-defined
|
|
455
|
+
// folding, and it is what riverFold below avoids.
|
|
456
|
+
//
|
|
457
|
+
// Caller-supplied boundaries stay left-nested (see stablePrefixFold): there are
|
|
458
|
+
// a handful of them, one per conversation turn, and the cumulative-context-root
|
|
459
|
+
// contract depends on that shape. Each SPAN between them content-folds.
|
|
460
|
+
const sb = (leafAt && lookup) ? knownPrefixLength(bytes, leafAt, lookup) : 0;
|
|
461
|
+
const outer = new Set();
|
|
462
|
+
if (boundaries !== undefined) {
|
|
463
|
+
for (const b of boundaries)
|
|
464
|
+
outer.add(b);
|
|
465
|
+
}
|
|
466
|
+
if (sb > 0)
|
|
467
|
+
outer.add(sb);
|
|
468
|
+
if (outer.size === 0) {
|
|
469
|
+
return rootOf(contentFoldSpan(space, alphabet, bytes, 0, bytes.length));
|
|
470
|
+
}
|
|
471
|
+
return stablePrefixFold(space, alphabet, bytes, [...outer].sort((a, b) => a - b));
|
|
472
|
+
}
|
|
473
|
+
/** One span, folded over its own content cuts — AT EVERY LEVEL.
|
|
474
|
+
*
|
|
475
|
+
* A segment becomes ONE FLAT NODE: every leaf bound into its own seat and
|
|
476
|
+
* summed, arity = the segment's length. `contentBoundaries` caps a segment at
|
|
477
|
+
* the keyring's seat count so this is always possible, and the flat form is
|
|
478
|
+
* both lighter (one node per segment instead of a [W][remainder] pair) and the
|
|
479
|
+
* natural unit — a segment IS the smallest thing the cuts claim is a unit.
|
|
480
|
+
*
|
|
481
|
+
* Above the segments the cutting RECURSES rather than reverting to the grid.
|
|
482
|
+
* Grouping segment roots W-at-a-time from index 0 would reintroduce the very
|
|
483
|
+
* bug content cuts exist to remove, one level up: a form spanning segments
|
|
484
|
+
* 12..17 straddles the [12-15] and [16-17] groups and is no node at all, so
|
|
485
|
+
* recognition can only reach it by an alignment accident (test/44 pins exactly
|
|
486
|
+
* this — at HEAD the grid happened to put a node one byte before the target).
|
|
487
|
+
* {@link contentLevels} assigns each cut a level from how divisible its hash
|
|
488
|
+
* is, so level-L cuts are a subset of level-(L−1) cuts and every node at every
|
|
489
|
+
* scale is delimited by content. Identity is then offset-free at all scales,
|
|
490
|
+
* which is the whole requirement — it must not depend on W. */
|
|
491
|
+
function contentFoldSpan(space, alphabet, bytes, from, to) {
|
|
492
|
+
const span = bytes.subarray(from, to);
|
|
493
|
+
const { cuts, levels } = contentLevels(space, span);
|
|
494
|
+
const edges = [0, ...cuts, span.length];
|
|
495
|
+
const segs = [];
|
|
496
|
+
for (let i = 0; i + 1 < edges.length; i++) {
|
|
497
|
+
segs.push(flatFold(space, alphabet, span, edges[i], edges[i + 1]));
|
|
498
|
+
}
|
|
499
|
+
if (segs.length > 1)
|
|
500
|
+
return groupByLevel(space, segs, levels, 1);
|
|
501
|
+
return segs[0];
|
|
502
|
+
}
|
|
503
|
+
/** Group a row of items by the level of the cut BETWEEN them: items separated
|
|
504
|
+
* by a cut of level < L belong to the same parent, and a cut of level ≥ L ends
|
|
505
|
+
* it. Recurses upward until one root remains, so the shape at every level is
|
|
506
|
+
* the content's, not an index's. `levels[i]` is the level of the cut that
|
|
507
|
+
* precedes item i+1 (there are items.length − 1 of them).
|
|
508
|
+
*
|
|
509
|
+
* A level that fails to split (every cut below L) or that would exceed the
|
|
510
|
+
* keyring falls through to the plain river fold for that row — the fold stays
|
|
511
|
+
* total on any input, and the fallback is rare enough not to reintroduce a
|
|
512
|
+
* systematic alignment. */
|
|
513
|
+
function groupByLevel(space, items, levels, level) {
|
|
514
|
+
if (items.length === 1)
|
|
515
|
+
return items[0];
|
|
516
|
+
const maxSeats = space.seats.length;
|
|
517
|
+
const groups = [];
|
|
518
|
+
const groupLevels = [];
|
|
519
|
+
let start = 0;
|
|
520
|
+
for (let i = 0; i <= levels.length; i++) {
|
|
521
|
+
const atEnd = i === levels.length;
|
|
522
|
+
const cutHere = atEnd || levels[i] >= level;
|
|
523
|
+
const wouldOverflow = i - start + 1 >= maxSeats;
|
|
524
|
+
if (!cutHere && !wouldOverflow)
|
|
525
|
+
continue;
|
|
526
|
+
const slice = items.slice(start, i + 1);
|
|
527
|
+
groups.push(slice.length === 1 ? slice[0] : joinFlat(space, slice));
|
|
528
|
+
if (!atEnd)
|
|
529
|
+
groupLevels.push(levels[i]);
|
|
530
|
+
start = i + 1;
|
|
531
|
+
}
|
|
532
|
+
if (groups.length === items.length) {
|
|
533
|
+
// This level split nothing — climb rather than spin.
|
|
534
|
+
return level < 24
|
|
535
|
+
? groupByLevel(space, items, levels, level + 1)
|
|
536
|
+
: riverFoldRaw(space, items);
|
|
537
|
+
}
|
|
538
|
+
return groupByLevel(space, groups, groupLevels, level + 1);
|
|
539
|
+
}
|
|
540
|
+
/** Join a row of already-folded items as one unnormalized node — the same
|
|
541
|
+
* seat-bound accumulate `flatFold` does for bytes, one level up. */
|
|
542
|
+
function joinFlat(space, items) {
|
|
543
|
+
const gist = new Float32Array(space.D);
|
|
544
|
+
const kids = new Array(items.length);
|
|
545
|
+
let len = 0;
|
|
546
|
+
for (let k = 0; k < items.length; k++) {
|
|
547
|
+
const v = items[k].tree.v;
|
|
548
|
+
const seat = space.seats[k].fwd;
|
|
549
|
+
for (let d = 0; d < space.D; d++)
|
|
550
|
+
gist[d] += v[seat[d]];
|
|
551
|
+
kids[k] = items[k].tree;
|
|
552
|
+
len += items[k].len;
|
|
553
|
+
}
|
|
554
|
+
return { tree: sema(gist, null, kids), len };
|
|
555
|
+
}
|
|
556
|
+
/** One segment as a single unnormalized node: leaf per byte, each bound into
|
|
557
|
+
* seat k, summed. Same FP ops and same seat order as foldSlice's group fold —
|
|
558
|
+
* only the arity is the segment's own length rather than a fixed W. Never
|
|
559
|
+
* normalizes: the linear-fold contract keeps every interior gist raw and
|
|
560
|
+
* normalizes once at the root. */
|
|
561
|
+
function flatFold(space, alphabet, bytes, from, to) {
|
|
562
|
+
const n = to - from;
|
|
563
|
+
if (n === 1) {
|
|
564
|
+
const b = bytes[from];
|
|
565
|
+
return {
|
|
566
|
+
tree: sema(alphabet.vecs[b], bytes.slice(from, to), null),
|
|
567
|
+
len: 1,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
const gist = new Float32Array(space.D);
|
|
571
|
+
const kids = new Array(n);
|
|
572
|
+
for (let k = 0; k < n; k++) {
|
|
573
|
+
const b = bytes[from + k];
|
|
574
|
+
const v = alphabet.vecs[b];
|
|
575
|
+
const seat = space.seats[k].fwd;
|
|
576
|
+
for (let d = 0; d < space.D; d++)
|
|
577
|
+
gist[d] += v[seat[d]];
|
|
578
|
+
kids[k] = sema(v, bytes.slice(from + k, from + k + 1), null);
|
|
579
|
+
}
|
|
580
|
+
return { tree: sema(gist, null, kids), len: n };
|
|
581
|
+
}
|
|
582
|
+
/** The stable-prefix segmented fold (§10.3). Each segment between
|
|
583
|
+
* consecutive boundaries folds PLAINLY and independently; segment roots
|
|
584
|
+
* join left-nested, and only the final root is normalized (the linear-fold
|
|
585
|
+
* contract: one normalize per perception). A segment's own inner splits
|
|
586
|
+
* need no recursion here: a nested learnt prefix is itself an earlier
|
|
587
|
+
* boundary, so the left-nested join reproduces every intermediate learnt
|
|
588
|
+
* root ((s₀·s₁) IS the root the store learnt for the first two segments'
|
|
589
|
+
* bytes, and so on). */
|
|
590
|
+
/** A fold's ROOT: ONE normalize per perception, at the root, exactly as
|
|
591
|
+
* riverFold did — the interior stays raw (the linear-fold contract).
|
|
592
|
+
*
|
|
593
|
+
* Normalizes EXCEPT when the whole stream folded to a single
|
|
594
|
+
* leaf: a leaf's vector IS the alphabet's own, shared by every occurrence of
|
|
595
|
+
* that byte, and `normalize` writes in place. Every fold entry point returns
|
|
596
|
+
* through here, because the guard is exactly the kind that gets written at one
|
|
597
|
+
* site and missed at the next two — which is what had happened: only
|
|
598
|
+
* {@link bytesToTree} carried it, while `stablePrefixFold` and its incremental
|
|
599
|
+
* twin normalized unconditionally, reachable by a one-byte stream whose only
|
|
600
|
+
* boundary is its own length. */
|
|
601
|
+
function rootOf(f) {
|
|
602
|
+
if (f.tree.kids !== null)
|
|
603
|
+
normalize(f.tree.v);
|
|
604
|
+
return f.tree;
|
|
605
|
+
}
|
|
606
|
+
function stablePrefixFold(space, alphabet, bytes, boundaries) {
|
|
607
|
+
const cuts = [];
|
|
608
|
+
let prev = 0;
|
|
609
|
+
for (const b of boundaries) {
|
|
610
|
+
if (b > prev && b < bytes.length) {
|
|
611
|
+
cuts.push(b);
|
|
612
|
+
prev = b;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (cuts.length === 0) {
|
|
616
|
+
return rootOf(contentFoldSpan(space, alphabet, bytes, 0, bytes.length));
|
|
617
|
+
}
|
|
618
|
+
const edges = [0, ...cuts, bytes.length];
|
|
619
|
+
const segs = [];
|
|
620
|
+
for (let i = 0; i + 1 < edges.length; i++) {
|
|
621
|
+
segs.push(contentFoldSpan(space, alphabet, bytes, edges[i], edges[i + 1]));
|
|
622
|
+
}
|
|
623
|
+
let cur = segs[0];
|
|
624
|
+
for (let i = 1; i < segs.length; i++)
|
|
625
|
+
cur = fold2(space, cur, segs[i]);
|
|
626
|
+
return rootOf(cur);
|
|
627
|
+
}
|
|
628
|
+
/** {@link stablePrefixFold} with incremental segment reuse — same cuts, same
|
|
629
|
+
* segment folds, same left-nested join, same single root normalize; `prev`
|
|
630
|
+
* only elides recomputing segments whose [start,end) offsets it already
|
|
631
|
+
* folded over a byte-identical prefix (the caller keys the cache by
|
|
632
|
+
* content). Requires a non-empty effective boundary set. */
|
|
633
|
+
export function stablePrefixFoldIncremental(space, alphabet, bytes, boundaries, prev) {
|
|
634
|
+
const cuts = [];
|
|
635
|
+
let prevB = 0;
|
|
636
|
+
for (const b of boundaries) {
|
|
637
|
+
if (b > prevB && b < bytes.length) {
|
|
638
|
+
cuts.push(b);
|
|
639
|
+
prevB = b;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const edges = [0, ...cuts, bytes.length];
|
|
643
|
+
const segs = [];
|
|
644
|
+
for (let i = 0; i + 1 < edges.length; i++) {
|
|
645
|
+
const hit = prev !== undefined && prev.edges[i] === edges[i] &&
|
|
646
|
+
prev.edges[i + 1] === edges[i + 1]
|
|
647
|
+
? prev.segs[i]
|
|
648
|
+
: undefined;
|
|
649
|
+
segs.push(hit ?? contentFoldSpan(space, alphabet, bytes, edges[i], edges[i + 1]));
|
|
650
|
+
}
|
|
651
|
+
if (segs.length === 1) {
|
|
652
|
+
// Degenerate boundary set — one span, which IS the whole stream, and it was
|
|
653
|
+
// just folded (or reused from `prev`) right above. It cannot go through
|
|
654
|
+
// `rootOf`: the ROOT is normalized, a cached SEGMENT never is (a later turn
|
|
655
|
+
// reuses it as one), and `normalize` writes in place. Re-folding `bytes`
|
|
656
|
+
// to get a separate object is what this used to do — and a first-seen
|
|
657
|
+
// deposit has no boundaries, so it always lands here, paying the fold
|
|
658
|
+
// twice. Copying the gist is the same result for one vector copy. A
|
|
659
|
+
// single LEAF needs neither: its vector is the shared alphabet entry and
|
|
660
|
+
// must not be written at all.
|
|
661
|
+
const only = segs[0].tree;
|
|
662
|
+
const tree = only.kids === null
|
|
663
|
+
? only
|
|
664
|
+
: sema(Float32Array.from(only.v), null, only.kids);
|
|
665
|
+
if (tree.kids !== null)
|
|
666
|
+
normalize(tree.v);
|
|
667
|
+
return { tree, fold: { edges, segs } };
|
|
668
|
+
}
|
|
669
|
+
let cur = segs[0];
|
|
670
|
+
for (let i = 1; i < segs.length; i++)
|
|
671
|
+
cur = fold2(space, cur, segs[i]);
|
|
672
|
+
return { tree: rootOf(cur), fold: { edges, segs } };
|
|
673
|
+
}
|
|
674
|
+
/** Join two folded items as one 2-kid branch — the top-level join of the
|
|
675
|
+
* stable-prefix fold, identical FP ops to foldSlice's seat-bound
|
|
676
|
+
* accumulation over a group of two. Unnormalized (interior). */
|
|
677
|
+
function fold2(space, a, b) {
|
|
678
|
+
const D = space.D;
|
|
679
|
+
const gist = new Float32Array(D);
|
|
680
|
+
const kids = [a.tree, b.tree];
|
|
681
|
+
for (let k = 0; k < 2; k++) {
|
|
682
|
+
const seat = space.seats[k].fwd;
|
|
683
|
+
const v = kids[k].v;
|
|
684
|
+
for (let d = 0; d < D; d++)
|
|
685
|
+
gist[d] += v[seat[d]];
|
|
686
|
+
}
|
|
687
|
+
return { tree: sema(gist, null, kids), len: a.len + b.len };
|
|
688
|
+
}
|
|
689
|
+
/** Plain river fold WITHOUT the final root normalize — the segment-level
|
|
690
|
+
* building block of {@link stablePrefixFold} (interiors must keep their
|
|
691
|
+
* byte-proportional magnitude; only the whole perception's root is ever
|
|
692
|
+
* normalized). Exported so callers that COMPOSE already-existing structural
|
|
693
|
+
* parts into a hypothetical synthetic root (see {@link composeStructuralGist})
|
|
694
|
+
* can feed the same raw primitive instead of duplicating its mathematics. */
|
|
695
|
+
export function riverFoldRaw(space, row) {
|
|
696
|
+
if (row.length === 0) {
|
|
697
|
+
const z = new Float32Array(space.D);
|
|
698
|
+
return { tree: sema(z, new Uint8Array(0), null), len: 0 };
|
|
699
|
+
}
|
|
700
|
+
if (row.length === 1)
|
|
701
|
+
return row[0];
|
|
702
|
+
let level = row;
|
|
703
|
+
while (level.length > 1) {
|
|
704
|
+
const next = [];
|
|
705
|
+
foldSlice(space, level, 0, level.length, next, true);
|
|
706
|
+
level = next;
|
|
707
|
+
}
|
|
708
|
+
return level[0];
|
|
709
|
+
}
|
|
710
|
+
/** Synthesize a hypothetical internal structure from already-existing
|
|
711
|
+
* structural vectors — NOT from bytes. This is the raw positional
|
|
712
|
+
* composition the linear river fold already uses (see the folding header
|
|
713
|
+
* above): each part is positionally bound into its own seat, its natural
|
|
714
|
+
* span magnitude is preserved, the parts are linearly superposed, and only
|
|
715
|
+
* the final synthetic root is normalized. It never calls {@link gistOf}
|
|
716
|
+
* (there is no `gistOf` here — geometry.ts has no store), never perceives a
|
|
717
|
+
* concatenated byte string, and never interns or stores a new node: the
|
|
718
|
+
* result is an opaque, ungrounded Vec for an ANN probe only. */
|
|
719
|
+
export function composeStructuralGist(space, parts) {
|
|
720
|
+
const foldedParts = [];
|
|
721
|
+
for (const part of parts) {
|
|
722
|
+
if (part.len <= 0)
|
|
723
|
+
continue;
|
|
724
|
+
const direction = copy(part.v);
|
|
725
|
+
normalize(direction);
|
|
726
|
+
const scaled = zeros(space.D);
|
|
727
|
+
addInto(scaled, direction, Math.sqrt(part.len));
|
|
728
|
+
foldedParts.push({ tree: sema(scaled), len: part.len });
|
|
729
|
+
}
|
|
730
|
+
if (foldedParts.length === 0)
|
|
731
|
+
return zeros(space.D);
|
|
732
|
+
const rawRoot = riverFoldRaw(space, foldedParts);
|
|
733
|
+
const result = copy(rawRoot.tree.v);
|
|
734
|
+
normalize(result);
|
|
735
|
+
return result;
|
|
736
|
+
}
|
|
737
|
+
// ---- n-D Hilbert curve ----
|
|
738
|
+
function gridDims(grid) {
|
|
739
|
+
if (grid.dims && grid.dims.length > 0)
|
|
740
|
+
return grid.dims.slice();
|
|
741
|
+
const dims = [grid.height, grid.width];
|
|
742
|
+
if (grid.channels > 1)
|
|
743
|
+
dims.push(grid.channels);
|
|
744
|
+
return dims;
|
|
745
|
+
}
|
|
746
|
+
function hilbertPoint(index, n, bits) {
|
|
747
|
+
const x = new Array(n).fill(0);
|
|
748
|
+
for (let b = 0; b < bits; b++) {
|
|
749
|
+
for (let d = 0; d < n; d++) {
|
|
750
|
+
const bit = (index >>> (b * n + (n - 1 - d))) & 1;
|
|
751
|
+
x[d] |= bit << b;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
const N = 1 << bits;
|
|
755
|
+
let t = x[n - 1] >> 1;
|
|
756
|
+
for (let i = n - 1; i > 0; i--)
|
|
757
|
+
x[i] ^= x[i - 1];
|
|
758
|
+
x[0] ^= t;
|
|
759
|
+
for (let q = 2; q !== N; q <<= 1) {
|
|
760
|
+
const p = q - 1;
|
|
761
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
762
|
+
if (x[i] & q)
|
|
763
|
+
x[0] ^= p;
|
|
764
|
+
else {
|
|
765
|
+
t = (x[0] ^ x[i]) & p;
|
|
766
|
+
x[0] ^= t;
|
|
767
|
+
x[i] ^= t;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return x;
|
|
772
|
+
}
|
|
773
|
+
export function hilbertBytes(grid) {
|
|
774
|
+
const dims = gridDims(grid);
|
|
775
|
+
const n = dims.length;
|
|
776
|
+
if (n === 0 || grid.data.length === 0)
|
|
777
|
+
return new Uint8Array(0);
|
|
778
|
+
if (n === 1)
|
|
779
|
+
return grid.data.slice(0, dims[0]);
|
|
780
|
+
const maxAxis = Math.max(...dims);
|
|
781
|
+
const bits = Math.max(1, Math.ceil(Math.log2(maxAxis)));
|
|
782
|
+
const side = 1 << bits;
|
|
783
|
+
const total = Math.pow(side, n);
|
|
784
|
+
const stride = new Array(n);
|
|
785
|
+
stride[n - 1] = 1;
|
|
786
|
+
for (let d = n - 2; d >= 0; d--)
|
|
787
|
+
stride[d] = stride[d + 1] * dims[d + 1];
|
|
788
|
+
const out = [];
|
|
789
|
+
for (let h = 0; h < total; h++) {
|
|
790
|
+
const pt = hilbertPoint(h, n, bits);
|
|
791
|
+
let inside = true, flat = 0;
|
|
792
|
+
for (let d = 0; d < n; d++) {
|
|
793
|
+
if (pt[d] >= dims[d]) {
|
|
794
|
+
inside = false;
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
flat += pt[d] * stride[d];
|
|
798
|
+
}
|
|
799
|
+
if (inside)
|
|
800
|
+
out.push(grid.data[flat]);
|
|
801
|
+
}
|
|
802
|
+
return Uint8Array.from(out);
|
|
803
|
+
}
|
|
804
|
+
export function gridToTree(space, alphabet, grid) {
|
|
805
|
+
return bytesToTree(space, alphabet, hilbertBytes(grid));
|
|
806
|
+
}
|
|
807
|
+
export function stackGrids(frames) {
|
|
808
|
+
if (frames.length === 0) {
|
|
809
|
+
return { width: 0, height: 0, channels: 0, data: new Uint8Array(0) };
|
|
810
|
+
}
|
|
811
|
+
const frameDims = gridDims(frames[0]);
|
|
812
|
+
const per = frames[0].data.length;
|
|
813
|
+
const data = new Uint8Array(per * frames.length);
|
|
814
|
+
for (let i = 0; i < frames.length; i++)
|
|
815
|
+
data.set(frames[i].data, i * per);
|
|
816
|
+
return {
|
|
817
|
+
width: 0,
|
|
818
|
+
height: 0,
|
|
819
|
+
channels: 0,
|
|
820
|
+
dims: [frames.length, ...frameDims],
|
|
821
|
+
data,
|
|
822
|
+
};
|
|
823
|
+
}
|