@seanhogg/builderforce-memory-engine 2026.6.39 → 2026.7.12

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 (66) hide show
  1. package/dist/codec/evermind_video.d.ts +35 -0
  2. package/dist/codec/evermind_video.d.ts.map +1 -0
  3. package/dist/codec/evermind_video.js +37 -0
  4. package/dist/codec/evermind_video.js.map +1 -0
  5. package/dist/codec/image_rvq.d.ts +28 -0
  6. package/dist/codec/image_rvq.d.ts.map +1 -0
  7. package/dist/codec/image_rvq.js +39 -0
  8. package/dist/codec/image_rvq.js.map +1 -0
  9. package/dist/codec/index.d.ts +13 -0
  10. package/dist/codec/index.d.ts.map +1 -0
  11. package/dist/codec/index.js +11 -0
  12. package/dist/codec/index.js.map +1 -0
  13. package/dist/codec/multimodal_vocab.d.ts +79 -0
  14. package/dist/codec/multimodal_vocab.d.ts.map +1 -0
  15. package/dist/codec/multimodal_vocab.js +96 -0
  16. package/dist/codec/multimodal_vocab.js.map +1 -0
  17. package/dist/codec/video_rvq.d.ts +116 -0
  18. package/dist/codec/video_rvq.d.ts.map +1 -0
  19. package/dist/codec/video_rvq.js +450 -0
  20. package/dist/codec/video_rvq.js.map +1 -0
  21. package/dist/index.d.ts +3 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/kernels/selective_scan.d.ts.map +1 -1
  26. package/dist/kernels/selective_scan.js +9 -3
  27. package/dist/kernels/selective_scan.js.map +1 -1
  28. package/dist/kernels/ssd.d.ts.map +1 -1
  29. package/dist/kernels/ssd.js +8 -2
  30. package/dist/kernels/ssd.js.map +1 -1
  31. package/dist/kernels/weight_update.d.ts.map +1 -1
  32. package/dist/kernels/weight_update.js +22 -3
  33. package/dist/kernels/weight_update.js.map +1 -1
  34. package/dist/limbic/limbic_trainer.d.ts +5 -1
  35. package/dist/limbic/limbic_trainer.d.ts.map +1 -1
  36. package/dist/limbic/limbic_trainer.js +4 -2
  37. package/dist/limbic/limbic_trainer.js.map +1 -1
  38. package/dist/model/mamba_model.d.ts +17 -0
  39. package/dist/model/mamba_model.d.ts.map +1 -1
  40. package/dist/model/mamba_model.js +27 -0
  41. package/dist/model/mamba_model.js.map +1 -1
  42. package/dist/moe/index.d.ts +1 -1
  43. package/dist/moe/index.d.ts.map +1 -1
  44. package/dist/moe/moe_package.d.ts +40 -2
  45. package/dist/moe/moe_package.d.ts.map +1 -1
  46. package/dist/moe/moe_package.js +90 -7
  47. package/dist/moe/moe_package.js.map +1 -1
  48. package/dist/training/trainer.d.ts +34 -2
  49. package/dist/training/trainer.d.ts.map +1 -1
  50. package/dist/training/trainer.js +76 -26
  51. package/dist/training/trainer.js.map +1 -1
  52. package/package.json +1 -1
  53. package/src/codec/evermind_video.ts +55 -0
  54. package/src/codec/image_rvq.ts +50 -0
  55. package/src/codec/index.ts +16 -0
  56. package/src/codec/multimodal_vocab.ts +115 -0
  57. package/src/codec/video_rvq.ts +496 -0
  58. package/src/index.ts +22 -0
  59. package/src/kernels/selective_scan.ts +9 -3
  60. package/src/kernels/ssd.ts +8 -2
  61. package/src/kernels/weight_update.ts +22 -3
  62. package/src/limbic/limbic_trainer.ts +9 -4
  63. package/src/model/mamba_model.ts +27 -0
  64. package/src/moe/index.ts +1 -0
  65. package/src/moe/moe_package.ts +107 -6
  66. package/src/training/trainer.ts +92 -28
@@ -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
+ }
package/src/index.ts CHANGED
@@ -33,6 +33,8 @@ export type {
33
33
  MoEEpochResult,
34
34
  EvermindModelManifest,
35
35
  EvermindModelCard,
36
+ EvermindModelType,
37
+ EvermindModality,
36
38
  PackageMeta,
37
39
  ValidationResult,
38
40
  } from './moe/index.js';
@@ -62,6 +64,26 @@ export {
62
64
  export { BPETokenizer } from './tokenizer/bpe.js';
63
65
  export type { BPEEncodeOptions, PadSide, HuggingFaceTokenizerSpec, SpecialTokenOverrides } from './tokenizer/bpe.js';
64
66
 
67
+ // ── Modality codecs (media ⇄ tokens; lets EvermindLM generate video) ────────────
68
+
69
+ export {
70
+ MultimodalVocab,
71
+ VIDEO_BANK_INTRA,
72
+ VIDEO_BANK_INTER,
73
+ VideoRVQCodec,
74
+ ImageRVQCodec,
75
+ buildVideoSequence,
76
+ generateVideo,
77
+ generateImage,
78
+ } from './codec/index.js';
79
+ export type {
80
+ MultimodalVocabConfig,
81
+ TokenKind,
82
+ VideoRVQConfig,
83
+ Frame,
84
+ Video,
85
+ } from './codec/index.js';
86
+
65
87
  // ── Model export (the publishing step: ONNX / safetensors / GGUF / HF repo) ─────
66
88
 
67
89
  export {
@@ -60,12 +60,15 @@ fn softplus(x: f32) -> f32 {
60
60
  // B_bar = (A_bar - 1) / A * B ≈ Δ * B (first-order for simplicity)
61
61
  fn discretise_A(delta_val: f32, a_log: f32) -> f32 {
62
62
  // A is stored as -exp(a_log) to ensure A_bar < 1 (stable)
63
- let a_cont = -exp(a_log);
63
+ // Clamp log-decay so -exp(a_log) can't overflow to -Inf (A_bar→0, state
64
+ // death) nor collapse toward 0 (A_bar→1, no decay). Keeps A_bar strictly in
65
+ // (0,1) across repeated adapts. Belt-and-suspenders: WSLA also freezes A_log.
66
+ let a_cont = -exp(clamp(a_log, -10.0, 5.0));
64
67
  return exp(delta_val * a_cont);
65
68
  }
66
69
 
67
70
  fn discretise_B(delta_val: f32, a_log: f32, b_val: f32) -> f32 {
68
- let a_cont = -exp(a_log);
71
+ let a_cont = -exp(clamp(a_log, -10.0, 5.0));
69
72
  let a_bar = exp(delta_val * a_cont);
70
73
  // (A_bar - 1) / A_cont * B
71
74
  let b_bar = (a_bar - 1.0) / a_cont * b_val;
@@ -264,7 +267,10 @@ fn softplus_grad(x: f32) -> f32 {
264
267
  }
265
268
 
266
269
  fn discretise_A(delta_val: f32, a_log: f32) -> f32 {
267
- let a_cont = -exp(a_log);
270
+ // Clamp log-decay so -exp(a_log) can't overflow to -Inf (A_bar→0, state
271
+ // death) nor collapse toward 0 (A_bar→1, no decay). Keeps A_bar strictly in
272
+ // (0,1) across repeated adapts. Belt-and-suspenders: WSLA also freezes A_log.
273
+ let a_cont = -exp(clamp(a_log, -10.0, 5.0));
268
274
  return exp(delta_val * a_cont);
269
275
  }
270
276
 
@@ -50,7 +50,10 @@ struct SsdParams {
50
50
  @group(0) @binding(9) var<storage, read_write> state_carry : array<f32>; // [n_chunks+1,B,H,N,d_head]
51
51
 
52
52
  fn softplus(x: f32) -> f32 {
53
- return log(1.0 + exp(x));
53
+ // Numerically stable: max(x,0) + log1p(exp(-|x|)). The naive log(1+exp(x))
54
+ // overflows to +Inf for x ≳ 88 (f32 exp range) — and a downstream
55
+ // exp(-Inf*0) then yields NaN, poisoning the state. This form never overflows.
56
+ return max(x, 0.0) + log(1.0 + exp(-abs(x)));
54
57
  }
55
58
 
56
59
  // Workgroup: one chunk × one head × one batch item
@@ -186,7 +189,10 @@ struct SsdParams {
186
189
  @group(0) @binding(14) var<storage, read_write> dD_vec : array<f32>;
187
190
 
188
191
  fn softplus(x: f32) -> f32 {
189
- return log(1.0 + exp(x));
192
+ // Numerically stable: max(x,0) + log1p(exp(-|x|)). The naive log(1+exp(x))
193
+ // overflows to +Inf for x ≳ 88 (f32 exp range) — and a downstream
194
+ // exp(-Inf*0) then yields NaN, poisoning the state. This form never overflows.
195
+ return max(x, 0.0) + log(1.0 + exp(-abs(x)));
190
196
  }
191
197
  fn d_softplus(x: f32) -> f32 {
192
198
  return 1.0 / (1.0 + exp(-x));
@@ -19,6 +19,10 @@ struct AdamParams {
19
19
  weight_decay : f32, // default 0.01
20
20
  beta1_t : f32, // beta1^t (precomputed bias correction term)
21
21
  beta2_t : f32, // beta2^t
22
+ max_delta : f32, // trust region: max |Δθ| per step (0 ⇒ unbounded)
23
+ _pad0 : f32, // pad struct to a 16-byte multiple (uniform layout)
24
+ _pad1 : f32,
25
+ _pad2 : f32,
22
26
  };
23
27
 
24
28
  @group(0) @binding(0) var<uniform> adam : AdamParams;
@@ -52,9 +56,24 @@ fn adamw_update(
52
56
  let m_hat = m_new / (1.0 - adam.beta1_t);
53
57
  let v_hat = v_new / (1.0 - adam.beta2_t);
54
58
 
55
- // Weight decay (decoupled) + gradient step
56
- param[i] = p * (1.0 - adam.lr * adam.weight_decay) -
57
- adam.lr * m_hat / (sqrt(v_hat) + adam.eps);
59
+ // Adam step.
60
+ var step = adam.lr * m_hat / (sqrt(v_hat) + adam.eps);
61
+
62
+ // Numerical guard: never write a non-finite step into a weight. A NaN or Inf
63
+ // here (from a bad gradient, a zero v_hat, an overflow) would permanently
64
+ // poison the parameter and every future forward — the "model dies" failure.
65
+ // NaN fails self-comparison; treat ±Inf-magnitude as non-finite too.
66
+ if (step != step || step > 3.4e38 || step < -3.4e38) { step = 0.0; }
67
+
68
+ // Trust region: bound how far ONE step can move a weight. With write-through
69
+ // adaptation running repeatedly, an unbounded step (even from a noisy
70
+ // gradient) compounds across executions and blows the weights up; clamping
71
+ // the per-element delta keeps every adapt small and reversible. max_delta==0
72
+ // disables the bound (full-training callers that don't set it).
73
+ if (adam.max_delta > 0.0) { step = clamp(step, -adam.max_delta, adam.max_delta); }
74
+
75
+ // Weight decay (decoupled) + bounded gradient step
76
+ param[i] = p * (1.0 - adam.lr * adam.weight_decay) - step;
58
77
  }
59
78
  `;
60
79
 
@@ -46,7 +46,10 @@ export interface LimbicTrainOptions {
46
46
  eps?: number;
47
47
  /** Max global gradient L2 norm before the optimiser step. Default 1.0. */
48
48
  maxGradNorm?: number;
49
- onEpochEnd?: ((epoch: number, loss: number) => void) | null;
49
+ /** Per-epoch hook. `gradNorm` is the pre-clip gradient L2 norm this epoch (the
50
+ * instability early-warning) — computed CPU-side so it's always available, unlike
51
+ * the GPU trainer where it's opt-in. */
52
+ onEpochEnd?: ((epoch: number, loss: number, gradNorm?: number) => void) | null;
50
53
  }
51
54
 
52
55
  interface AdamMoment {
@@ -146,7 +149,7 @@ export class LimbicTrainer {
146
149
  for (let i = 0; i < g.data.length; i++) g.data[i]! *= invN;
147
150
  }
148
151
 
149
- this._clipGradients(grads, maxGradNorm);
152
+ const gradNorm = this._clipGradients(grads, maxGradNorm);
150
153
 
151
154
  this._step++;
152
155
  const beta1_t = Math.pow(beta1, this._step);
@@ -160,7 +163,7 @@ export class LimbicTrainer {
160
163
 
161
164
  const avg = epochLoss / samples.length;
162
165
  losses.push(avg);
163
- if (onEpochEnd) onEpochEnd(epoch + 1, avg);
166
+ if (onEpochEnd) onEpochEnd(epoch + 1, avg, gradNorm);
164
167
  }
165
168
  return losses;
166
169
  }
@@ -184,7 +187,8 @@ export class LimbicTrainer {
184
187
  return total / samples.length;
185
188
  }
186
189
 
187
- private _clipGradients(grads: LimbicParam[], maxNorm: number): void {
190
+ /** Clip grads to `maxNorm` in place; returns the PRE-clip L2 norm (the signal). */
191
+ private _clipGradients(grads: LimbicParam[], maxNorm: number): number {
188
192
  let normSq = 0;
189
193
  for (const g of grads) for (let i = 0; i < g.data.length; i++) normSq += g.data[i]! * g.data[i]!;
190
194
  const norm = Math.sqrt(normSq);
@@ -192,6 +196,7 @@ export class LimbicTrainer {
192
196
  const scale = maxNorm / norm;
193
197
  for (const g of grads) for (let i = 0; i < g.data.length; i++) g.data[i]! *= scale;
194
198
  }
199
+ return norm;
195
200
  }
196
201
 
197
202
  private _adamwStepCpu(