@seanhogg/builderforce-memory-engine 2026.6.35 → 2026.7.11

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 (96) hide show
  1. package/README.md +30 -2
  2. package/dist/codec/evermind_video.d.ts +35 -0
  3. package/dist/codec/evermind_video.d.ts.map +1 -0
  4. package/dist/codec/evermind_video.js +37 -0
  5. package/dist/codec/evermind_video.js.map +1 -0
  6. package/dist/codec/image_rvq.d.ts +28 -0
  7. package/dist/codec/image_rvq.d.ts.map +1 -0
  8. package/dist/codec/image_rvq.js +39 -0
  9. package/dist/codec/image_rvq.js.map +1 -0
  10. package/dist/codec/index.d.ts +13 -0
  11. package/dist/codec/index.d.ts.map +1 -0
  12. package/dist/codec/index.js +11 -0
  13. package/dist/codec/index.js.map +1 -0
  14. package/dist/codec/multimodal_vocab.d.ts +79 -0
  15. package/dist/codec/multimodal_vocab.d.ts.map +1 -0
  16. package/dist/codec/multimodal_vocab.js +96 -0
  17. package/dist/codec/multimodal_vocab.js.map +1 -0
  18. package/dist/codec/video_rvq.d.ts +116 -0
  19. package/dist/codec/video_rvq.d.ts.map +1 -0
  20. package/dist/codec/video_rvq.js +450 -0
  21. package/dist/codec/video_rvq.js.map +1 -0
  22. package/dist/import/evermind.d.ts +48 -0
  23. package/dist/import/evermind.d.ts.map +1 -0
  24. package/dist/import/evermind.js +111 -0
  25. package/dist/import/evermind.js.map +1 -0
  26. package/dist/import/index.d.ts +11 -0
  27. package/dist/import/index.d.ts.map +1 -0
  28. package/dist/import/index.js +10 -0
  29. package/dist/import/index.js.map +1 -0
  30. package/dist/import/safetensors.d.ts +13 -0
  31. package/dist/import/safetensors.d.ts.map +1 -0
  32. package/dist/import/safetensors.js +64 -0
  33. package/dist/import/safetensors.js.map +1 -0
  34. package/dist/index.d.ts +8 -3
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/kernels/selective_scan.d.ts.map +1 -1
  39. package/dist/kernels/selective_scan.js +9 -3
  40. package/dist/kernels/selective_scan.js.map +1 -1
  41. package/dist/kernels/ssd.d.ts.map +1 -1
  42. package/dist/kernels/ssd.js +8 -2
  43. package/dist/kernels/ssd.js.map +1 -1
  44. package/dist/kernels/weight_update.d.ts.map +1 -1
  45. package/dist/kernels/weight_update.js +22 -3
  46. package/dist/kernels/weight_update.js.map +1 -1
  47. package/dist/limbic/index.d.ts +2 -2
  48. package/dist/limbic/index.d.ts.map +1 -1
  49. package/dist/limbic/index.js +1 -1
  50. package/dist/limbic/index.js.map +1 -1
  51. package/dist/limbic/regions.d.ts +31 -0
  52. package/dist/limbic/regions.d.ts.map +1 -1
  53. package/dist/limbic/regions.js +34 -0
  54. package/dist/limbic/regions.js.map +1 -1
  55. package/dist/model/mamba_model.d.ts +17 -0
  56. package/dist/model/mamba_model.d.ts.map +1 -1
  57. package/dist/model/mamba_model.js +27 -0
  58. package/dist/model/mamba_model.js.map +1 -1
  59. package/dist/moe/index.d.ts +1 -1
  60. package/dist/moe/index.d.ts.map +1 -1
  61. package/dist/moe/moe_package.d.ts +40 -2
  62. package/dist/moe/moe_package.d.ts.map +1 -1
  63. package/dist/moe/moe_package.js +90 -7
  64. package/dist/moe/moe_package.js.map +1 -1
  65. package/dist/tokenizer/bpe.d.ts +37 -0
  66. package/dist/tokenizer/bpe.d.ts.map +1 -1
  67. package/dist/tokenizer/bpe.js +47 -0
  68. package/dist/tokenizer/bpe.js.map +1 -1
  69. package/dist/training/trainer.d.ts +34 -2
  70. package/dist/training/trainer.d.ts.map +1 -1
  71. package/dist/training/trainer.js +76 -26
  72. package/dist/training/trainer.js.map +1 -1
  73. package/dist/utils/quantization.d.ts.map +1 -1
  74. package/dist/utils/quantization.js +4 -1
  75. package/dist/utils/quantization.js.map +1 -1
  76. package/package.json +1 -1
  77. package/src/codec/evermind_video.ts +55 -0
  78. package/src/codec/image_rvq.ts +50 -0
  79. package/src/codec/index.ts +16 -0
  80. package/src/codec/multimodal_vocab.ts +115 -0
  81. package/src/codec/video_rvq.ts +496 -0
  82. package/src/import/evermind.ts +128 -0
  83. package/src/import/index.ts +11 -0
  84. package/src/import/safetensors.ts +67 -0
  85. package/src/index.ts +35 -0
  86. package/src/kernels/selective_scan.ts +9 -3
  87. package/src/kernels/ssd.ts +8 -2
  88. package/src/kernels/weight_update.ts +22 -3
  89. package/src/limbic/index.ts +2 -1
  90. package/src/limbic/regions.ts +60 -0
  91. package/src/model/mamba_model.ts +27 -0
  92. package/src/moe/index.ts +1 -0
  93. package/src/moe/moe_package.ts +107 -6
  94. package/src/tokenizer/bpe.ts +59 -0
  95. package/src/training/trainer.ts +92 -28
  96. package/src/utils/quantization.ts +4 -1
@@ -0,0 +1,496 @@
1
+ /**
2
+ * video_rvq.ts — VideoRVQCodec: the pixels ⇄ tokens bottleneck that lets Evermind
3
+ * generate video without changing the generator.
4
+ *
5
+ * Evermind is a discrete-token autoregressive SSM. To make it a video model you
6
+ * do NOT touch the model — you give it a codec that maps a clip to a stream of
7
+ * discrete tokens and back. This is the visual analogue of the BPE tokenizer:
8
+ * where BPE turns text ⇄ ids, VideoRVQCodec turns frames ⇄ ids.
9
+ *
10
+ * Design — TEMPORAL residual vector quantization (the "video-from-the-start"
11
+ * choice):
12
+ *
13
+ * • Each frame is cut into non-overlapping p×p patches; each patch is a vector
14
+ * of length p·p·C (the "latent").
15
+ * • KEYFRAMES (frame 0 and every `keyframeInterval`-th frame) are quantized
16
+ * directly against the INTRA codebook bank.
17
+ * • Every other frame is INTER: we quantize the *residual against the previous
18
+ * RECONSTRUCTED frame* against the INTER bank. Video is mostly temporally
19
+ * redundant, so these deltas are small and cheap — this is exactly why an
20
+ * SSM (linear-time in sequence length) is the right generator for the long
21
+ * token streams video produces.
22
+ * • Quantization at each bank is RESIDUAL VQ over `levels` codebooks: level 0
23
+ * picks the nearest entry, level 1 quantizes what level 0 missed, and so on.
24
+ * More levels ⇒ finer reconstruction ⇒ more tokens per patch.
25
+ *
26
+ * The encoder runs closed-loop (it references its own reconstruction, never the
27
+ * ground-truth previous frame) so the decoder — which only ever has
28
+ * reconstructions — stays exactly in sync.
29
+ *
30
+ * Codebooks start random (a cold codec is lossy, like any untrained neural
31
+ * codec) and are learned by {@link VideoRVQCodec.fit} (greedy per-level k-means).
32
+ * Reaching photoreal fidelity needs training on a real corpus with real compute
33
+ * — that is the one genuine blocker on shipping generated video, not the wiring.
34
+ *
35
+ * Pure CPU, zero deps, deterministic under a seed — same conventions as the rest
36
+ * of the engine. A WGSL/WebGPU acceleration is a future drop-in with these shapes.
37
+ */
38
+
39
+ import { SeededRng } from "../utils/rng.js";
40
+ import { MultimodalVocab, VIDEO_BANK_INTRA, VIDEO_BANK_INTER } from "./multimodal_vocab.js";
41
+
42
+ /** A single frame: length `height·width·channels`, layout `((y·W)+x)·C + ch`, values in [0,1]. */
43
+ export type Frame = Float32Array;
44
+ /** A clip: T frames, all the same shape. */
45
+ export type Video = Frame[];
46
+
47
+ export interface VideoRVQConfig {
48
+ height: number;
49
+ width: number;
50
+ /** Colour channels. Default 3 (RGB). */
51
+ channels?: number;
52
+ /** Square patch size; `height` and `width` must be divisible by it. Default 4. */
53
+ patch?: number;
54
+ /** Residual-VQ depth (codes per patch). Default 2. */
55
+ levels?: number;
56
+ /** Codebook entries per level per bank. Default 16. */
57
+ codebookSize?: number;
58
+ /** Emit a keyframe every N frames (frame 0 is always a keyframe). Default 12. */
59
+ keyframeInterval?: number;
60
+ /** Size of the text region this codec's tokens sit above; 0 ⇒ pure-video vocab. Default 0. */
61
+ textVocabSize?: number;
62
+ /** Deterministic seed for codebook init. */
63
+ seed?: number;
64
+ }
65
+
66
+ const VRQ_MAGIC = 0x56525130; // "VRQ0"
67
+
68
+ const DEFAULTS = {
69
+ channels: 3,
70
+ patch: 4,
71
+ levels: 2,
72
+ codebookSize: 16,
73
+ keyframeInterval: 12,
74
+ textVocabSize: 0,
75
+ seed: 0x56524651, // "VRFQ"
76
+ } as const;
77
+
78
+ export class VideoRVQCodec {
79
+ readonly height: number;
80
+ readonly width: number;
81
+ readonly channels: number;
82
+ readonly patch: number;
83
+ readonly levels: number;
84
+ readonly codebookSize: number;
85
+ readonly keyframeInterval: number;
86
+
87
+ /** Patch latent dimension = patch·patch·channels. */
88
+ readonly latentDim: number;
89
+ /** Patches per frame = (H/patch)·(W/patch). */
90
+ readonly patchesPerFrame: number;
91
+ /** Code tokens emitted per frame = patchesPerFrame·levels. */
92
+ readonly tokensPerFrame: number;
93
+
94
+ /** The unified text+video vocabulary; feed `.vocab.size` to EvermindLM. */
95
+ readonly vocab: MultimodalVocab;
96
+
97
+ /** Two banks × levels codebooks; each codebook is `codebookSize × latentDim` row-major. */
98
+ private readonly banks: [Float32Array[], Float32Array[]];
99
+
100
+ constructor(config: VideoRVQConfig) {
101
+ const channels = config.channels ?? DEFAULTS.channels;
102
+ const patch = config.patch ?? DEFAULTS.patch;
103
+ if (config.height <= 0 || config.width <= 0) throw new Error("VideoRVQCodec: height/width must be > 0");
104
+ if (config.height % patch !== 0 || config.width % patch !== 0) {
105
+ throw new Error(`VideoRVQCodec: height/width must be divisible by patch (${patch})`);
106
+ }
107
+ this.height = config.height;
108
+ this.width = config.width;
109
+ this.channels = channels;
110
+ this.patch = patch;
111
+ this.levels = config.levels ?? DEFAULTS.levels;
112
+ this.codebookSize = config.codebookSize ?? DEFAULTS.codebookSize;
113
+ this.keyframeInterval = Math.max(1, config.keyframeInterval ?? DEFAULTS.keyframeInterval);
114
+ this.latentDim = patch * patch * channels;
115
+ this.patchesPerFrame = (this.height / patch) * (this.width / patch);
116
+ this.tokensPerFrame = this.patchesPerFrame * this.levels;
117
+
118
+ this.vocab = new MultimodalVocab({
119
+ textVocabSize: config.textVocabSize ?? DEFAULTS.textVocabSize,
120
+ levels: this.levels,
121
+ codebookSize: this.codebookSize,
122
+ });
123
+
124
+ const rng = new SeededRng((config.seed ?? DEFAULTS.seed) >>> 0 || 1);
125
+ const mkBank = (): Float32Array[] =>
126
+ Array.from({ length: this.levels }, () => {
127
+ const cb = new Float32Array(this.codebookSize * this.latentDim);
128
+ // Small-magnitude init: intra entries hover near mid-grey, inter (delta) near 0.
129
+ for (let i = 0; i < cb.length; i++) cb[i] = (rng.next() - 0.5) * 0.1;
130
+ return cb;
131
+ });
132
+ this.banks = [mkBank(), mkBank()];
133
+ // Bias the intra bank toward the [0,1] pixel range so a cold codec is not black.
134
+ for (const cb of this.banks[VIDEO_BANK_INTRA]) for (let i = 0; i < cb.length; i++) cb[i] += 0.5;
135
+ }
136
+
137
+ /** Total vocabulary size for this codec's model. */
138
+ get vocabSize(): number {
139
+ return this.vocab.size;
140
+ }
141
+
142
+ // ── Serialize (so a trained codec ships alongside the model artifact) ───────────
143
+
144
+ /**
145
+ * Serialize config + learned codebooks to a compact "VRQ0" binary. A generated
146
+ * video model is only servable if its codec travels with it (the decoder needs
147
+ * these codebooks), so this is the video analogue of EvermindLM.exportWeights.
148
+ */
149
+ serialize(): ArrayBuffer {
150
+ const headerEls = 9; // magic, h, w, channels, patch, levels, codebookSize, keyframeInterval, textVocabSize
151
+ const total = 2 * this.levels * this.codebookSize * this.latentDim;
152
+ const buf = new ArrayBuffer(headerEls * 4 + total * 4);
153
+ const head = new Uint32Array(buf, 0, headerEls);
154
+ head[0] = VRQ_MAGIC;
155
+ head[1] = this.height;
156
+ head[2] = this.width;
157
+ head[3] = this.channels;
158
+ head[4] = this.patch;
159
+ head[5] = this.levels;
160
+ head[6] = this.codebookSize;
161
+ head[7] = this.keyframeInterval;
162
+ head[8] = this.vocab.textVocabSize;
163
+ const body = new Float32Array(buf, headerEls * 4, total);
164
+ let o = 0;
165
+ for (const bank of this.banks) {
166
+ for (const cb of bank) {
167
+ body.set(cb, o);
168
+ o += cb.length;
169
+ }
170
+ }
171
+ return buf;
172
+ }
173
+
174
+ /** Reconstruct a codec (config + codebooks) from a "VRQ0" binary. */
175
+ static deserialize(buffer: ArrayBuffer): VideoRVQCodec {
176
+ const head = new Uint32Array(buffer, 0, 9);
177
+ if (head[0] !== VRQ_MAGIC) throw new Error("VideoRVQCodec.deserialize: bad magic (not a VRQ0 blob)");
178
+ const codec = new VideoRVQCodec({
179
+ height: head[1]!,
180
+ width: head[2]!,
181
+ channels: head[3]!,
182
+ patch: head[4]!,
183
+ levels: head[5]!,
184
+ codebookSize: head[6]!,
185
+ keyframeInterval: head[7]!,
186
+ textVocabSize: head[8]!,
187
+ });
188
+ const total = 2 * codec.levels * codec.codebookSize * codec.latentDim;
189
+ const body = new Float32Array(buffer.slice(36, 36 + total * 4));
190
+ let o = 0;
191
+ for (const bank of codec.banks) {
192
+ for (const cb of bank) {
193
+ cb.set(body.subarray(o, o + cb.length));
194
+ o += cb.length;
195
+ }
196
+ }
197
+ return codec;
198
+ }
199
+
200
+ // ── Encode ───────────────────────────────────────────────────────────────────
201
+
202
+ /** Encode a clip to a self-delimiting token stream: `<vid> (marker codes…)… </vid>`. */
203
+ encode(video: Video): number[] {
204
+ this.assertShape(video);
205
+ const out: number[] = [this.vocab.bosVideo];
206
+ let prevRecon: Float32Array[] | null = null;
207
+
208
+ for (let t = 0; t < video.length; t++) {
209
+ const patches = this.toPatches(video[t]!);
210
+ const isKey = prevRecon === null || t % this.keyframeInterval === 0;
211
+ const bankId = isKey ? VIDEO_BANK_INTRA : VIDEO_BANK_INTER;
212
+ out.push(isKey ? this.vocab.frameKey : this.vocab.frameDelta);
213
+
214
+ const reconPatches: Float32Array[] = [];
215
+ for (let p = 0; p < this.patchesPerFrame; p++) {
216
+ const target = isKey ? patches[p]! : sub(patches[p]!, prevRecon![p]!);
217
+ const { codes, recon } = this.rvqEncode(bankId, target);
218
+ for (let l = 0; l < this.levels; l++) out.push(this.vocab.codeToken(bankId, l, codes[l]!));
219
+ reconPatches.push(isKey ? recon : add(prevRecon![p]!, recon));
220
+ }
221
+ prevRecon = reconPatches;
222
+ }
223
+
224
+ out.push(this.vocab.eosVideo);
225
+ return out;
226
+ }
227
+
228
+ // ── Decode ───────────────────────────────────────────────────────────────────
229
+
230
+ /**
231
+ * Decode a token stream back to frames. Tolerant by design: it skips text /
232
+ * stray tokens, treats a frame whose codes run short as zero-padded, and stops
233
+ * at `</vid>` or end-of-stream — so a stream sampled from an under-trained
234
+ * generator still yields a valid (if noisy) clip instead of throwing.
235
+ */
236
+ decode(tokens: number[]): Video {
237
+ const frames: Video = [];
238
+ let prevRecon: Float32Array[] | null = null;
239
+ let i = 0;
240
+
241
+ // Advance to the first frame marker (tolerate a leading prompt / <vid>).
242
+ while (i < tokens.length && !this.vocab.isVideoMarker(tokens[i]!)) {
243
+ if (tokens[i] === this.vocab.eosVideo) return frames;
244
+ i++;
245
+ }
246
+
247
+ while (i < tokens.length) {
248
+ const marker = tokens[i]!;
249
+ if (!this.vocab.isVideoMarker(marker)) break; // </vid>, text, or garbage → end
250
+ i++;
251
+ const isKey = marker === this.vocab.frameKey || prevRecon === null;
252
+ const bankId = isKey ? VIDEO_BANK_INTRA : VIDEO_BANK_INTER;
253
+
254
+ // Pull up to tokensPerFrame code tokens; stop early on the next marker/EOS.
255
+ const codes: number[] = [];
256
+ while (codes.length < this.tokensPerFrame && i < tokens.length && this.vocab.isCode(tokens[i]!)) {
257
+ codes.push(tokens[i]!);
258
+ i++;
259
+ }
260
+
261
+ const reconPatches: Float32Array[] = [];
262
+ for (let p = 0; p < this.patchesPerFrame; p++) {
263
+ const recon = new Float32Array(this.latentDim);
264
+ for (let l = 0; l < this.levels; l++) {
265
+ const slot = p * this.levels + l;
266
+ const tok = slot < codes.length ? codes[slot]! : -1;
267
+ if (tok < 0) continue; // missing → contribute zero (graceful degradation)
268
+ const { level, code } = this.vocab.decodeCode(tok);
269
+ addRowInto(recon, this.banks[bankId]![level]!, code, this.latentDim);
270
+ }
271
+ reconPatches.push(isKey ? recon : add(prevRecon![p]!, recon));
272
+ }
273
+
274
+ frames.push(this.fromPatches(reconPatches));
275
+ prevRecon = reconPatches;
276
+ }
277
+
278
+ return frames;
279
+ }
280
+
281
+ // ── Learn codebooks ────────────────────────────────────────────────────────────
282
+
283
+ /**
284
+ * Learn both codebook banks from a set of clips (greedy per-level k-means over
285
+ * residuals — the standard way to train residual VQ). Returns the mean
286
+ * reconstruction MSE over the training clips after fitting. This is the codec's
287
+ * "training"; the generator is trained separately on the resulting token streams.
288
+ */
289
+ fit(videos: Video[], opts: { iterations?: number; seed?: number } = {}): number {
290
+ const iterations = opts.iterations ?? 8;
291
+ const rng = new SeededRng((opts.seed ?? 0x66697421) >>> 0 || 1); // "fit!"
292
+ for (const v of videos) this.assertShape(v);
293
+
294
+ // Gather intra patches and inter deltas (open-loop deltas are a fine proxy for fitting).
295
+ const intra: Float32Array[] = [];
296
+ const inter: Float32Array[] = [];
297
+ for (const video of videos) {
298
+ let prev: Float32Array[] | null = null;
299
+ for (let t = 0; t < video.length; t++) {
300
+ const patches = this.toPatches(video[t]!);
301
+ const isKey = prev === null || t % this.keyframeInterval === 0;
302
+ if (isKey) for (const p of patches) intra.push(p);
303
+ else for (let p = 0; p < patches.length; p++) inter.push(sub(patches[p]!, prev![p]!));
304
+ prev = patches;
305
+ }
306
+ }
307
+
308
+ this.fitBank(VIDEO_BANK_INTRA, intra, iterations, rng);
309
+ this.fitBank(VIDEO_BANK_INTER, inter, iterations, rng);
310
+
311
+ // Report closed-loop reconstruction error over the corpus.
312
+ let se = 0;
313
+ let n = 0;
314
+ for (const video of videos) {
315
+ const recon = this.decode(this.encode(video));
316
+ for (let t = 0; t < video.length; t++) {
317
+ const a = video[t]!;
318
+ const b = recon[t]!;
319
+ for (let k = 0; k < a.length; k++) {
320
+ const d = a[k]! - b[k]!;
321
+ se += d * d;
322
+ }
323
+ n += a.length;
324
+ }
325
+ }
326
+ return n > 0 ? se / n : 0;
327
+ }
328
+
329
+ /** Fit one bank's `levels` codebooks greedily over residuals. */
330
+ private fitBank(bankId: number, vectors: Float32Array[], iterations: number, rng: SeededRng): void {
331
+ if (vectors.length === 0) return;
332
+ let residuals = vectors.map((v) => Float32Array.from(v));
333
+ for (let l = 0; l < this.levels; l++) {
334
+ const centroids = kmeans(residuals, this.codebookSize, this.latentDim, iterations, rng);
335
+ this.banks[bankId]![l] = centroids;
336
+ residuals = residuals.map((r) => {
337
+ const idx = nearestRow(centroids, r, this.codebookSize, this.latentDim);
338
+ const out = Float32Array.from(r);
339
+ const off = idx * this.latentDim;
340
+ for (let d = 0; d < this.latentDim; d++) out[d] = out[d]! - centroids[off + d]!;
341
+ return out;
342
+ });
343
+ }
344
+ }
345
+
346
+ // ── Residual VQ over one bank ───────────────────────────────────────────────────
347
+
348
+ private rvqEncode(bankId: number, vector: Float32Array): { codes: number[]; recon: Float32Array } {
349
+ const residual = Float32Array.from(vector);
350
+ const recon = new Float32Array(this.latentDim);
351
+ const codes: number[] = [];
352
+ for (let l = 0; l < this.levels; l++) {
353
+ const cb = this.banks[bankId]![l]!;
354
+ const idx = nearestRow(cb, residual, this.codebookSize, this.latentDim);
355
+ codes.push(idx);
356
+ const off = idx * this.latentDim;
357
+ for (let d = 0; d < this.latentDim; d++) {
358
+ recon[d] = recon[d]! + cb[off + d]!;
359
+ residual[d] = residual[d]! - cb[off + d]!;
360
+ }
361
+ }
362
+ return { codes, recon };
363
+ }
364
+
365
+ // ── Patch <-> frame ─────────────────────────────────────────────────────────────
366
+
367
+ private toPatches(frame: Frame): Float32Array[] {
368
+ const { patch, channels, width } = this;
369
+ const pw = this.width / patch;
370
+ const ph = this.height / patch;
371
+ const out: Float32Array[] = [];
372
+ for (let py = 0; py < ph; py++) {
373
+ for (let px = 0; px < pw; px++) {
374
+ const vec = new Float32Array(this.latentDim);
375
+ for (let dy = 0; dy < patch; dy++) {
376
+ for (let dx = 0; dx < patch; dx++) {
377
+ const y = py * patch + dy;
378
+ const x = px * patch + dx;
379
+ const src = ((y * width) + x) * channels;
380
+ const dst = ((dy * patch) + dx) * channels;
381
+ for (let c = 0; c < channels; c++) vec[dst + c] = frame[src + c]!;
382
+ }
383
+ }
384
+ out.push(vec);
385
+ }
386
+ }
387
+ return out;
388
+ }
389
+
390
+ private fromPatches(patches: Float32Array[]): Frame {
391
+ const { patch, channels, width } = this;
392
+ const pw = this.width / patch;
393
+ const frame = new Float32Array(this.height * this.width * channels);
394
+ for (let p = 0; p < patches.length; p++) {
395
+ const py = Math.floor(p / pw);
396
+ const px = p - py * pw;
397
+ const vec = patches[p]!;
398
+ for (let dy = 0; dy < patch; dy++) {
399
+ for (let dx = 0; dx < patch; dx++) {
400
+ const y = py * patch + dy;
401
+ const x = px * patch + dx;
402
+ const dst = ((y * width) + x) * channels;
403
+ const src = ((dy * patch) + dx) * channels;
404
+ for (let c = 0; c < channels; c++) frame[dst + c] = clamp01(vec[src + c]!);
405
+ }
406
+ }
407
+ }
408
+ return frame;
409
+ }
410
+
411
+ private assertShape(video: Video): void {
412
+ const expect = this.height * this.width * this.channels;
413
+ for (let t = 0; t < video.length; t++) {
414
+ if (video[t]!.length !== expect) {
415
+ throw new Error(`VideoRVQCodec: frame ${t} has length ${video[t]!.length}, expected ${expect}`);
416
+ }
417
+ }
418
+ }
419
+ }
420
+
421
+ // ── free helpers ─────────────────────────────────────────────────────────────────
422
+
423
+ function sub(a: Float32Array, b: Float32Array): Float32Array {
424
+ const out = new Float32Array(a.length);
425
+ for (let i = 0; i < a.length; i++) out[i] = a[i]! - b[i]!;
426
+ return out;
427
+ }
428
+
429
+ function add(a: Float32Array, b: Float32Array): Float32Array {
430
+ const out = new Float32Array(a.length);
431
+ for (let i = 0; i < a.length; i++) out[i] = a[i]! + b[i]!;
432
+ return out;
433
+ }
434
+
435
+ function addRowInto(acc: Float32Array, codebook: Float32Array, row: number, dim: number): void {
436
+ const off = row * dim;
437
+ for (let d = 0; d < dim; d++) acc[d] = acc[d]! + codebook[off + d]!;
438
+ }
439
+
440
+ function clamp01(v: number): number {
441
+ return v < 0 ? 0 : v > 1 ? 1 : v;
442
+ }
443
+
444
+ /** Nearest codebook row to `v` by squared L2. `codebook` is `count × dim` row-major. */
445
+ function nearestRow(codebook: Float32Array, v: Float32Array, count: number, dim: number): number {
446
+ let best = 0;
447
+ let bestD = Infinity;
448
+ for (let r = 0; r < count; r++) {
449
+ const off = r * dim;
450
+ let d = 0;
451
+ for (let k = 0; k < dim; k++) {
452
+ const diff = v[k]! - codebook[off + k]!;
453
+ d += diff * diff;
454
+ if (d >= bestD) break;
455
+ }
456
+ if (d < bestD) {
457
+ bestD = d;
458
+ best = r;
459
+ }
460
+ }
461
+ return best;
462
+ }
463
+
464
+ /** Lloyd's k-means → `count × dim` centroids. Empty clusters reseed to a random sample. */
465
+ function kmeans(vectors: Float32Array[], count: number, dim: number, iterations: number, rng: SeededRng): Float32Array {
466
+ const centroids = new Float32Array(count * dim);
467
+ // Init: distinct random samples.
468
+ for (let r = 0; r < count; r++) {
469
+ const src = vectors[Math.floor(rng.next() * vectors.length) % vectors.length]!;
470
+ centroids.set(src, r * dim);
471
+ }
472
+ const sums = new Float32Array(count * dim);
473
+ const counts = new Int32Array(count);
474
+ for (let it = 0; it < iterations; it++) {
475
+ sums.fill(0);
476
+ counts.fill(0);
477
+ for (const v of vectors) {
478
+ const r = nearestRow(centroids, v, count, dim);
479
+ counts[r] = counts[r]! + 1;
480
+ const off = r * dim;
481
+ for (let d = 0; d < dim; d++) sums[off + d] = sums[off + d]! + v[d]!;
482
+ }
483
+ for (let r = 0; r < count; r++) {
484
+ const off = r * dim;
485
+ if (counts[r]! === 0) {
486
+ // Reseed the dead centroid onto a random sample so it can win points next round.
487
+ const src = vectors[Math.floor(rng.next() * vectors.length) % vectors.length]!;
488
+ centroids.set(src, off);
489
+ continue;
490
+ }
491
+ const inv = 1 / counts[r]!;
492
+ for (let d = 0; d < dim; d++) centroids[off + d] = sums[off + d]! * inv;
493
+ }
494
+ }
495
+ return centroids;
496
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * import/evermind.ts — build a live {@link EvermindLM} FROM imported weights.
3
+ *
4
+ * The inverse of the export path: given a named/shaped tensor list (e.g. from
5
+ * {@link safetensorsToTensors}), reconstruct the model. This is the warm-start /
6
+ * weight-port seam — it lets Evermind be *initialised* from an existing
7
+ * checkpoint instead of only from random init + training.
8
+ *
9
+ * Two entry points:
10
+ * • round-trip our OWN exports — the tensor names already match the canonical
11
+ * {@link evermindTensorSpec}; arch is inferred from the tensor shapes.
12
+ * • warm-start a FOREIGN SSM checkpoint (e.g. Codestral-Mamba) — pass a
13
+ * `rename` map that translates its tensor names into our canonical names.
14
+ * Shapes must then line up with {@link evermindTensorSpec}; a mismatch throws
15
+ * with the exact offending tensor (the honest failure for an incompatible
16
+ * mixer, rather than silently loading garbage).
17
+ */
18
+
19
+ import { EvermindLM } from "../lm/evermind_lm.js";
20
+ import { evermindTensorSpec, type EvermindArch, type NamedTensor } from "../export/tensors.js";
21
+ import { safetensorsToTensors } from "./safetensors.js";
22
+
23
+ export interface ImportOptions {
24
+ /**
25
+ * Rename each source tensor before matching against the canonical spec. Return
26
+ * `null` to drop a tensor. Use this to warm-start a foreign SSM checkpoint whose
27
+ * weight names differ from Evermind's.
28
+ */
29
+ rename?: (name: string) => string | null;
30
+ /**
31
+ * `topK` (active experts per token) is not encoded in the weights — supply it
32
+ * when importing (default: min(2, numExperts)).
33
+ */
34
+ topK?: number;
35
+ /** Override the inferred architecture entirely (advanced). */
36
+ arch?: EvermindArch;
37
+ }
38
+
39
+ /**
40
+ * Infer the architecture from the tensor shapes alone, so a bare safetensors
41
+ * file (no config.json) can be imported. `topK` cannot be recovered from weights.
42
+ */
43
+ export function inferArchFromTensors(tensors: NamedTensor[], topK?: number): EvermindArch {
44
+ const byName = new Map(tensors.map((t) => [t.name, t]));
45
+ const emb = byName.get("token_embedding.weight");
46
+ if (!emb || emb.shape.length !== 2) throw new Error("import: missing token_embedding.weight [vocab, dModel]");
47
+ const [vocabSize, dModel] = emb.shape as [number, number];
48
+
49
+ // Count layers by the `layers.<n>.` prefix; experts by `moe.experts.<e>`.
50
+ let numLayers = 0;
51
+ let numExperts = 0;
52
+ for (const t of tensors) {
53
+ const lm = /^layers\.(\d+)\./.exec(t.name);
54
+ if (lm) numLayers = Math.max(numLayers, Number(lm[1]) + 1);
55
+ const em = /^layers\.\d+\.moe\.experts\.(\d+)\./.exec(t.name);
56
+ if (em) numExperts = Math.max(numExperts, Number(em[1]) + 1);
57
+ }
58
+ if (numLayers === 0) throw new Error("import: no `layers.<n>.` tensors found");
59
+
60
+ const conv = byName.get("layers.0.conv.weight");
61
+ if (!conv || conv.shape.length !== 2) throw new Error("import: missing layers.0.conv.weight [dModel, convKernel]");
62
+ const convKernel = conv.shape[1]!;
63
+
64
+ const w1 = byName.get("layers.0.moe.shared.w1");
65
+ if (!w1 || w1.shape.length !== 2) throw new Error("import: missing layers.0.moe.shared.w1 [hiddenDim, dModel]");
66
+ const hiddenDim = w1.shape[0]!;
67
+
68
+ return {
69
+ vocabSize,
70
+ dModel,
71
+ numLayers,
72
+ convKernel,
73
+ hiddenDim,
74
+ numExperts,
75
+ topK: Math.min(topK ?? 2, Math.max(1, numExperts)),
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Reconstruct an {@link EvermindLM} from a named tensor list. Validates every
81
+ * canonical parameter is present with the right element count, then copies the
82
+ * data into the model's parameter buffers (canonical order).
83
+ */
84
+ export function importEvermindTensors(tensors: NamedTensor[], opts: ImportOptions = {}): EvermindLM {
85
+ const renamed: NamedTensor[] = [];
86
+ for (const t of tensors) {
87
+ const name = opts.rename ? opts.rename(t.name) : t.name;
88
+ if (name != null) renamed.push({ ...t, name });
89
+ }
90
+ const byName = new Map(renamed.map((t) => [t.name, t]));
91
+
92
+ const arch = opts.arch ?? inferArchFromTensors(renamed, opts.topK);
93
+ const specs = evermindTensorSpec(arch);
94
+
95
+ // Validate presence + element count BEFORE constructing, so we fail with the
96
+ // exact missing/mismatched tensor rather than loading a corrupt model.
97
+ const ordered: Float32Array[] = [];
98
+ for (const s of specs) {
99
+ const t = byName.get(s.name);
100
+ if (!t) throw new Error(`import: missing tensor "${s.name}" (expected shape [${s.shape.join(", ")}])`);
101
+ const numel = s.shape.reduce((n, d) => n * d, 1);
102
+ if (t.data.length !== numel) {
103
+ throw new Error(`import: tensor "${s.name}" has ${t.data.length} elements, expected ${numel} ([${s.shape.join(", ")}])`);
104
+ }
105
+ ordered.push(t.data);
106
+ }
107
+
108
+ const lm = new EvermindLM({
109
+ vocabSize: arch.vocabSize,
110
+ dModel: arch.dModel,
111
+ numLayers: arch.numLayers,
112
+ convKernel: arch.convKernel,
113
+ hiddenDim: arch.hiddenDim,
114
+ numExperts: arch.numExperts,
115
+ topK: arch.topK,
116
+ });
117
+ const params = lm.parameters();
118
+ if (params.length !== ordered.length) {
119
+ throw new Error(`import: parameter-count drift (model ${params.length} vs imported ${ordered.length})`);
120
+ }
121
+ for (let i = 0; i < params.length; i++) params[i]!.data.set(ordered[i]!);
122
+ return lm;
123
+ }
124
+
125
+ /** Convenience: import an {@link EvermindLM} directly from a `.safetensors` buffer. */
126
+ export function importEvermind(bytes: Uint8Array, opts: ImportOptions = {}): EvermindLM {
127
+ return importEvermindTensors(safetensorsToTensors(bytes), opts);
128
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * import/index.ts — the model-import (warm-start / weight-port) registry.
3
+ *
4
+ * The inverse of {@link ../export}: read a `.safetensors` checkpoint back into a
5
+ * live {@link ../lm/evermind_lm.EvermindLM}. Round-trips Evermind's own exports,
6
+ * and warm-starts a foreign SSM checkpoint via a `rename` map.
7
+ */
8
+
9
+ export { safetensorsToTensors } from "./safetensors.js";
10
+ export { importEvermind, importEvermindTensors, inferArchFromTensors } from "./evermind.js";
11
+ export type { ImportOptions } from "./evermind.js";