@seanhogg/builderforce-memory-engine 2026.9.34 → 2026.10.1

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 (170) hide show
  1. package/dist/evermind/delta_wire.d.ts +10 -1
  2. package/dist/evermind/delta_wire.d.ts.map +1 -1
  3. package/dist/evermind/delta_wire.js +25 -3
  4. package/dist/evermind/delta_wire.js.map +1 -1
  5. package/dist/evermind/index.d.ts +4 -4
  6. package/dist/evermind/index.d.ts.map +1 -1
  7. package/dist/evermind/index.js +2 -2
  8. package/dist/evermind/index.js.map +1 -1
  9. package/dist/evermind/merge.d.ts +25 -0
  10. package/dist/evermind/merge.d.ts.map +1 -1
  11. package/dist/evermind/merge.js +30 -0
  12. package/dist/evermind/merge.js.map +1 -1
  13. package/dist/evermind/package.d.ts +9 -0
  14. package/dist/evermind/package.d.ts.map +1 -1
  15. package/dist/evermind/package.js +20 -0
  16. package/dist/evermind/package.js.map +1 -1
  17. package/dist/index.d.ts +6 -5
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +5 -3
  20. package/dist/index.js.map +1 -1
  21. package/dist/limbic/index.d.ts +3 -0
  22. package/dist/limbic/index.d.ts.map +1 -1
  23. package/dist/limbic/index.js +3 -0
  24. package/dist/limbic/index.js.map +1 -1
  25. package/dist/limbic/limbic_task.d.ts +22 -0
  26. package/dist/limbic/limbic_task.d.ts.map +1 -0
  27. package/dist/limbic/limbic_task.js +45 -0
  28. package/dist/limbic/limbic_task.js.map +1 -0
  29. package/dist/limbic/limbic_trainer.d.ts +17 -30
  30. package/dist/limbic/limbic_trainer.d.ts.map +1 -1
  31. package/dist/limbic/limbic_trainer.js +38 -144
  32. package/dist/limbic/limbic_trainer.js.map +1 -1
  33. package/dist/ml/classical/ewma.d.ts +32 -0
  34. package/dist/ml/classical/ewma.d.ts.map +1 -0
  35. package/dist/ml/classical/ewma.js +46 -0
  36. package/dist/ml/classical/ewma.js.map +1 -0
  37. package/dist/ml/classical/gbm.d.ts +42 -0
  38. package/dist/ml/classical/gbm.d.ts.map +1 -0
  39. package/dist/ml/classical/gbm.js +116 -0
  40. package/dist/ml/classical/gbm.js.map +1 -0
  41. package/dist/ml/classical/index.d.ts +48 -0
  42. package/dist/ml/classical/index.d.ts.map +1 -0
  43. package/dist/ml/classical/index.js +45 -0
  44. package/dist/ml/classical/index.js.map +1 -0
  45. package/dist/ml/classical/isolation_forest.d.ts +37 -0
  46. package/dist/ml/classical/isolation_forest.d.ts.map +1 -0
  47. package/dist/ml/classical/isolation_forest.js +72 -0
  48. package/dist/ml/classical/isolation_forest.js.map +1 -0
  49. package/dist/ml/classical/kmeans.d.ts +31 -0
  50. package/dist/ml/classical/kmeans.d.ts.map +1 -0
  51. package/dist/ml/classical/kmeans.js +93 -0
  52. package/dist/ml/classical/kmeans.js.map +1 -0
  53. package/dist/ml/classical/knn.d.ts +48 -0
  54. package/dist/ml/classical/knn.d.ts.map +1 -0
  55. package/dist/ml/classical/knn.js +68 -0
  56. package/dist/ml/classical/knn.js.map +1 -0
  57. package/dist/ml/classical/linear.d.ts +29 -0
  58. package/dist/ml/classical/linear.d.ts.map +1 -0
  59. package/dist/ml/classical/linear.js +114 -0
  60. package/dist/ml/classical/linear.js.map +1 -0
  61. package/dist/ml/classical/logistic.d.ts +39 -0
  62. package/dist/ml/classical/logistic.d.ts.map +1 -0
  63. package/dist/ml/classical/logistic.js +103 -0
  64. package/dist/ml/classical/logistic.js.map +1 -0
  65. package/dist/ml/classical/math.d.ts +26 -0
  66. package/dist/ml/classical/math.d.ts.map +1 -0
  67. package/dist/ml/classical/math.js +90 -0
  68. package/dist/ml/classical/math.js.map +1 -0
  69. package/dist/ml/classical/naive_bayes.d.ts +24 -0
  70. package/dist/ml/classical/naive_bayes.d.ts.map +1 -0
  71. package/dist/ml/classical/naive_bayes.js +67 -0
  72. package/dist/ml/classical/naive_bayes.js.map +1 -0
  73. package/dist/ml/classical/robust_z.d.ts +30 -0
  74. package/dist/ml/classical/robust_z.d.ts.map +1 -0
  75. package/dist/ml/classical/robust_z.js +46 -0
  76. package/dist/ml/classical/robust_z.js.map +1 -0
  77. package/dist/ml/dense_head.d.ts +33 -0
  78. package/dist/ml/dense_head.d.ts.map +1 -0
  79. package/dist/ml/dense_head.js +140 -0
  80. package/dist/ml/dense_head.js.map +1 -0
  81. package/dist/ml/features.d.ts +25 -0
  82. package/dist/ml/features.d.ts.map +1 -0
  83. package/dist/ml/features.js +46 -0
  84. package/dist/ml/features.js.map +1 -0
  85. package/dist/ml/federate.d.ts +70 -0
  86. package/dist/ml/federate.d.ts.map +1 -0
  87. package/dist/ml/federate.js +122 -0
  88. package/dist/ml/federate.js.map +1 -0
  89. package/dist/ml/head_trainer.d.ts +76 -0
  90. package/dist/ml/head_trainer.d.ts.map +1 -0
  91. package/dist/ml/head_trainer.js +182 -0
  92. package/dist/ml/head_trainer.js.map +1 -0
  93. package/dist/ml/index.d.ts +23 -0
  94. package/dist/ml/index.d.ts.map +1 -0
  95. package/dist/ml/index.js +11 -0
  96. package/dist/ml/index.js.map +1 -0
  97. package/dist/ml/registry.d.ts +20 -0
  98. package/dist/ml/registry.d.ts.map +1 -0
  99. package/dist/ml/registry.js +43 -0
  100. package/dist/ml/registry.js.map +1 -0
  101. package/dist/ml/run.d.ts +94 -0
  102. package/dist/ml/run.d.ts.map +1 -0
  103. package/dist/ml/run.js +130 -0
  104. package/dist/ml/run.js.map +1 -0
  105. package/dist/ml/tasks/experience.d.ts +90 -0
  106. package/dist/ml/tasks/experience.d.ts.map +1 -0
  107. package/dist/ml/tasks/experience.js +156 -0
  108. package/dist/ml/tasks/experience.js.map +1 -0
  109. package/dist/ml/tasks/index.d.ts +10 -0
  110. package/dist/ml/tasks/index.d.ts.map +1 -0
  111. package/dist/ml/tasks/index.js +28 -0
  112. package/dist/ml/tasks/index.js.map +1 -0
  113. package/dist/ml/tasks/local_success.d.ts +55 -0
  114. package/dist/ml/tasks/local_success.d.ts.map +1 -0
  115. package/dist/ml/tasks/local_success.js +77 -0
  116. package/dist/ml/tasks/local_success.js.map +1 -0
  117. package/dist/ml/tasks/run_anomaly.d.ts +51 -0
  118. package/dist/ml/tasks/run_anomaly.d.ts.map +1 -0
  119. package/dist/ml/tasks/run_anomaly.js +60 -0
  120. package/dist/ml/tasks/run_anomaly.js.map +1 -0
  121. package/dist/ml/train.d.ts +64 -0
  122. package/dist/ml/train.d.ts.map +1 -0
  123. package/dist/ml/train.js +101 -0
  124. package/dist/ml/train.js.map +1 -0
  125. package/dist/ml/types.d.ts +112 -0
  126. package/dist/ml/types.d.ts.map +1 -0
  127. package/dist/ml/types.js +23 -0
  128. package/dist/ml/types.js.map +1 -0
  129. package/dist/moe/moe_model.d.ts.map +1 -1
  130. package/dist/moe/moe_model.js +1 -16
  131. package/dist/moe/moe_model.js.map +1 -1
  132. package/dist/training/cpu_ops.d.ts +2 -0
  133. package/dist/training/cpu_ops.d.ts.map +1 -1
  134. package/dist/training/cpu_ops.js +16 -0
  135. package/dist/training/cpu_ops.js.map +1 -1
  136. package/package.json +1 -1
  137. package/src/evermind/delta_wire.ts +148 -114
  138. package/src/evermind/index.ts +35 -32
  139. package/src/evermind/merge.ts +53 -0
  140. package/src/evermind/package.ts +488 -464
  141. package/src/index.ts +15 -1
  142. package/src/limbic/index.ts +5 -0
  143. package/src/limbic/limbic_task.ts +62 -0
  144. package/src/limbic/limbic_trainer.ts +91 -258
  145. package/src/ml/classical/ewma.ts +68 -0
  146. package/src/ml/classical/gbm.ts +143 -0
  147. package/src/ml/classical/index.ts +76 -0
  148. package/src/ml/classical/isolation_forest.ts +88 -0
  149. package/src/ml/classical/kmeans.ts +102 -0
  150. package/src/ml/classical/knn.ts +98 -0
  151. package/src/ml/classical/linear.ts +119 -0
  152. package/src/ml/classical/logistic.ts +125 -0
  153. package/src/ml/classical/math.ts +93 -0
  154. package/src/ml/classical/naive_bayes.ts +77 -0
  155. package/src/ml/classical/robust_z.ts +65 -0
  156. package/src/ml/dense_head.ts +157 -0
  157. package/src/ml/features.ts +61 -0
  158. package/src/ml/federate.ts +160 -0
  159. package/src/ml/head_trainer.ts +268 -0
  160. package/src/ml/index.ts +57 -0
  161. package/src/ml/registry.ts +44 -0
  162. package/src/ml/run.ts +178 -0
  163. package/src/ml/tasks/experience.ts +214 -0
  164. package/src/ml/tasks/index.ts +30 -0
  165. package/src/ml/tasks/local_success.ts +118 -0
  166. package/src/ml/tasks/run_anomaly.ts +90 -0
  167. package/src/ml/train.ts +136 -0
  168. package/src/ml/types.ts +132 -0
  169. package/src/moe/moe_model.ts +1 -13
  170. package/src/training/cpu_ops.ts +141 -127
package/src/index.ts CHANGED
@@ -45,6 +45,9 @@ export {
45
45
  deltaUnusableReason,
46
46
  MAX_DELTA_B64_CHARS,
47
47
  mergeCheckpointDiffs,
48
+ mergeCheckpointDiffsGated,
49
+ DELTA_TARGET_RE,
50
+ mlHeadTarget,
48
51
  meanEvalLoss,
49
52
  } from './evermind/index.js';
50
53
  export type {
@@ -61,6 +64,8 @@ export type {
61
64
  DeltaLearnPayload,
62
65
  DeltaParseResult,
63
66
  MergeResult,
67
+ GatedMergeResult,
68
+ MergeGateOptions,
64
69
  EvalExample,
65
70
  EvalTokenizer,
66
71
  } from './evermind/index.js';
@@ -103,7 +108,7 @@ export type {
103
108
  } from './training/mamba1_cpu.js';
104
109
  export {
105
110
  linearForward, linearBackward, rmsNormForward, rmsNormBackward,
106
- silu, siluGrad, softplus, sigmoid, RMSNORM_EPS,
111
+ silu, siluGrad, softplus, sigmoid, softmax, RMSNORM_EPS,
107
112
  } from './training/cpu_ops.js';
108
113
  export {
109
114
  Tensor,
@@ -372,6 +377,9 @@ export {
372
377
  DEFAULT_LIMBIC_CONFIG,
373
378
  DEFAULT_LIMBIC_SEED,
374
379
  LimbicTrainer,
380
+ limbicHead,
381
+ LIMBIC_AFFECT_TASK,
382
+ limbicAffectPredictor,
375
383
  } from './limbic/index.js';
376
384
  export type {
377
385
  Region,
@@ -388,6 +396,8 @@ export type {
388
396
  LimbicParam,
389
397
  LimbicSample,
390
398
  LimbicTrainOptions,
399
+ LimbicAffectInput,
400
+ LimbicAffectOutput,
391
401
  } from './limbic/index.js';
392
402
 
393
403
  export { LIMBIC_AFFECT_WGSL } from './kernels/limbic_affect.js';
@@ -396,3 +406,7 @@ export { LIMBIC_AFFECT_WGSL } from './kernels/limbic_affect.js';
396
406
  // ── Experience (demonstrations, Train Once skills, runs) ─────────────────────
397
407
 
398
408
  export * from './experience/index.js';
409
+
410
+ // ── ML task catalog (non-LLM learning: registry, runner, trainer, federation) ──
411
+
412
+ export * from './ml/index.js';
@@ -54,3 +54,8 @@ export type { LimbicModelConfig, LimbicForward, LimbicParam } from "./limbic_mod
54
54
 
55
55
  export { LimbicTrainer } from "./limbic_trainer.js";
56
56
  export type { LimbicSample, LimbicTrainOptions } from "./limbic_trainer.js";
57
+ export { limbicHead } from "./limbic_trainer.js";
58
+
59
+ // The ML catalog row for the affect head (`ml/`), registered by limbic itself.
60
+ export { LIMBIC_AFFECT_TASK, limbicAffectPredictor } from "./limbic_task.js";
61
+ export type { LimbicAffectInput, LimbicAffectOutput } from "./limbic_task.js";
@@ -0,0 +1,62 @@
1
+ /**
2
+ * limbic/limbic_task.ts — `limbic.affect`, the ML catalog's first row, registered
3
+ * by limbic/ itself.
4
+ *
5
+ * Nothing about the affect head changes: the row describes it (input = experience
6
+ * embedding + affective state, output = bounded affect delta + reward), the
7
+ * predictor adapter lets the ONE runner answer with an existing `LimbicModel`, and
8
+ * training stays `LimbicTrainer` (itself a thin registration over `HeadTrainer`).
9
+ * Its flat parameters are what federate when the head travels with the model.
10
+ */
11
+ import { assignParams, flattenParams } from "../ml/head_trainer.js";
12
+ import type { MlPrediction, MlPredictor, MlTask } from "../ml/types.js";
13
+ import type { LimbicModel } from "./limbic_model.js";
14
+
15
+ export interface LimbicAffectInput {
16
+ /** Experience embedding (length = model.inputDim). */
17
+ embedding: ArrayLike<number>;
18
+ /** Current affective state (length = model.stateDim). */
19
+ state: ArrayLike<number>;
20
+ }
21
+
22
+ export interface LimbicAffectOutput {
23
+ /** Bounded affect delta in (-1, 1) per state dim. */
24
+ delta: Float32Array;
25
+ /** Reward prediction. */
26
+ reward: number;
27
+ }
28
+
29
+ export const LIMBIC_AFFECT_TASK: MlTask<LimbicAffectInput, LimbicAffectOutput> = {
30
+ kind: "regress",
31
+ id: "limbic.affect",
32
+ description: "How an experience moves the agent's affective state, and how rewarding it was.",
33
+ features: { numeric: (i) => [...Array.from(i.embedding), ...Array.from(i.state)] },
34
+ engines: [{ tier: "local", engine: "head", head: "mlp" }],
35
+ train: { minSamples: 1, trainedBy: "LimbicTrainer" },
36
+ output: {
37
+ decode: (p: MlPrediction) => ({
38
+ delta: Float32Array.from(p.scores.slice(0, -1)),
39
+ reward: p.scores[p.scores.length - 1] ?? 0,
40
+ }),
41
+ },
42
+ };
43
+
44
+ /**
45
+ * Answer `limbic.affect` with `model`. The feature vector is `[embedding, state]`;
46
+ * the hidden scratch resets per call, exactly as the trainer treats each sample.
47
+ * Confidence is 1: a deterministic regression head has no calibrated uncertainty.
48
+ */
49
+ export function limbicAffectPredictor(model: LimbicModel): MlPredictor {
50
+ const { inputDim, stateDim } = model.config;
51
+ return {
52
+ predict(x: Float32Array): MlPrediction {
53
+ if (x.length !== inputDim + stateDim) {
54
+ throw new Error(`limbic.affect: expected ${inputDim + stateDim} features (embedding ${inputDim} + state ${stateDim}), got ${x.length}`);
55
+ }
56
+ const f = model.forward(x.subarray(0, inputDim), model.initHidden(), x.subarray(inputDim));
57
+ return { scores: [...Array.from(f.delta), f.reward], confidence: 1 };
58
+ },
59
+ exportParams: () => flattenParams(model.parameters()),
60
+ importParams: (params) => assignParams(model.parameters(), params),
61
+ };
62
+ }
@@ -1,258 +1,91 @@
1
- /**
2
- * limbic_trainer.ts – LimbicTrainer: gradient-based training for the LimbicModel.
3
- *
4
- * Trains the affect head to predict affect deltas and reward from
5
- * (experience embedding, current state) pairs, using full-batch gradient
6
- * descent with AdamW. When a GPUDevice is supplied the optimiser step runs on
7
- * the GPU via the shared WEIGHT_UPDATE_WGSL kernel (real WebGPU training); with
8
- * no device it uses a numerically-equivalent CPU AdamW so training works
9
- * everywhere (CI, Node without @webgpu/node, etc.).
10
- *
11
- * The objective is MSE (regression), not the cross-entropy used by the
12
- * language-model {@link MambaTrainer} — a limbic experience has continuous
13
- * targets, not a next-token distribution.
14
- */
15
-
16
- import {
17
- createUniformBuffer,
18
- createStorageBuffer,
19
- createComputePipeline,
20
- createBindGroup,
21
- dispatchKernel,
22
- readBuffer,
23
- cdiv,
24
- } from "../utils/gpu_utils.js";
25
- import { WEIGHT_UPDATE_WGSL } from "../kernels/weight_update.js";
26
- import type { LimbicModel, LimbicParam } from "./limbic_model.js";
27
-
28
- /** One training example: an experience and the affect change it should produce. */
29
- export interface LimbicSample {
30
- /** Experience embedding (length = model.inputDim). */
31
- input: ArrayLike<number>;
32
- /** Affective state at the time of the experience (length = model.stateDim). */
33
- state: ArrayLike<number>;
34
- /** Observed affect delta target in (-1, 1) per state dim (length = model.stateDim). */
35
- deltaTarget: ArrayLike<number>;
36
- /** Observed scalar reward for the experience. */
37
- reward: number;
38
- }
39
-
40
- export interface LimbicTrainOptions {
41
- learningRate?: number;
42
- epochs?: number;
43
- weightDecay?: number;
44
- beta1?: number;
45
- beta2?: number;
46
- eps?: number;
47
- /** Max global gradient L2 norm before the optimiser step. Default 1.0. */
48
- maxGradNorm?: number;
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;
53
- }
54
-
55
- interface AdamMoment {
56
- m: Float32Array;
57
- v: Float32Array;
58
- }
59
-
60
- function packAdamParams(
61
- numElements: number,
62
- lr: number,
63
- beta1: number,
64
- beta2: number,
65
- eps: number,
66
- weightDecay: number,
67
- beta1_t: number,
68
- beta2_t: number,
69
- ): ArrayBuffer {
70
- const buf = new ArrayBuffer(32);
71
- new Uint32Array(buf, 0, 1).set([numElements]);
72
- new Float32Array(buf, 4, 7).set([lr, beta1, beta2, eps, weightDecay, beta1_t, beta2_t]);
73
- return buf;
74
- }
75
-
76
- export class LimbicTrainer {
77
- readonly model: LimbicModel;
78
- readonly device: GPUDevice | null;
79
- private _moments: AdamMoment[] | null = null;
80
- private _step = 0;
81
- private readonly _adamwPipeline: GPUComputePipeline | null;
82
-
83
- constructor(model: LimbicModel, device: GPUDevice | null = null) {
84
- this.model = model;
85
- this.device = device;
86
- this._adamwPipeline = device
87
- ? createComputePipeline(device, WEIGHT_UPDATE_WGSL, "adamw_update")
88
- : null;
89
- }
90
-
91
- /** Whether the optimiser step runs on the GPU. */
92
- get gpuTraining(): boolean {
93
- return this.device != null && this._adamwPipeline != null;
94
- }
95
-
96
- private _initMoments(): void {
97
- if (this._moments) return;
98
- this._moments = this.model.parameters().map((p) => ({
99
- m: new Float32Array(p.numel),
100
- v: new Float32Array(p.numel),
101
- }));
102
- }
103
-
104
- /**
105
- * Train on a batch of samples for `epochs` passes. Returns the per-epoch mean
106
- * loss (monotonically decreasing on a learnable mapping). Full-batch: grads
107
- * accumulate across the whole sequence (recurrent hidden carried, reset per
108
- * epoch), are averaged, clipped, then applied once per epoch.
109
- */
110
- async train(samples: LimbicSample[], opts: LimbicTrainOptions = {}): Promise<number[]> {
111
- if (samples.length === 0) throw new Error("LimbicTrainer.train: no samples");
112
- const {
113
- learningRate = 0.05,
114
- epochs = 50,
115
- weightDecay = 0.0,
116
- beta1 = 0.9,
117
- beta2 = 0.999,
118
- eps = 1e-8,
119
- maxGradNorm = 1.0,
120
- onEpochEnd = null,
121
- } = opts;
122
-
123
- this._initMoments();
124
- const losses: number[] = [];
125
-
126
- for (let epoch = 0; epoch < epochs; epoch++) {
127
- this.model.zeroGrad();
128
- let epochLoss = 0;
129
-
130
- // Each sample is one experience appraisal: cross-experience memory flows
131
- // through the affective state `s` (fed back by the runtime), not through
132
- // the hidden scratch `h`, so the hidden state resets per sample. This also
133
- // makes BPTT(1) exact — there is no truncated carry.
134
- for (const s of samples) {
135
- const { loss } = this.model.backwardStep(
136
- s.input,
137
- this.model.initHidden(),
138
- s.state,
139
- s.deltaTarget,
140
- s.reward,
141
- );
142
- epochLoss += loss;
143
- }
144
-
145
- // Average gradients over the batch.
146
- const grads = this.model.gradients();
147
- const invN = 1 / samples.length;
148
- for (const g of grads) {
149
- for (let i = 0; i < g.data.length; i++) g.data[i]! *= invN;
150
- }
151
-
152
- const gradNorm = this._clipGradients(grads, maxGradNorm);
153
-
154
- this._step++;
155
- const beta1_t = Math.pow(beta1, this._step);
156
- const beta2_t = Math.pow(beta2, this._step);
157
- const hp = { learningRate, weightDecay, beta1, beta2, eps, beta1_t, beta2_t };
158
- if (this.gpuTraining) {
159
- await this._adamwStepGpu(grads, hp);
160
- } else {
161
- this._adamwStepCpu(grads, hp);
162
- }
163
-
164
- const avg = epochLoss / samples.length;
165
- losses.push(avg);
166
- if (onEpochEnd) onEpochEnd(epoch + 1, avg, gradNorm);
167
- }
168
- return losses;
169
- }
170
-
171
- /** Mean MSE loss over samples (no weight update). Hidden resets per sample. */
172
- evaluate(samples: LimbicSample[]): number {
173
- if (samples.length === 0) return 0;
174
- let total = 0;
175
- const { rewardWeight } = this.model.config;
176
- for (const s of samples) {
177
- const f = this.model.forward(s.input, this.model.initHidden(), s.state);
178
- let loss = 0;
179
- for (let k = 0; k < f.delta.length; k++) {
180
- const d = f.delta[k]! - (s.deltaTarget[k] ?? 0);
181
- loss += 0.5 * d * d;
182
- }
183
- const rd = f.reward - s.reward;
184
- loss += 0.5 * rewardWeight * rd * rd;
185
- total += loss;
186
- }
187
- return total / samples.length;
188
- }
189
-
190
- /** Clip grads to `maxNorm` in place; returns the PRE-clip L2 norm (the signal). */
191
- private _clipGradients(grads: LimbicParam[], maxNorm: number): number {
192
- let normSq = 0;
193
- for (const g of grads) for (let i = 0; i < g.data.length; i++) normSq += g.data[i]! * g.data[i]!;
194
- const norm = Math.sqrt(normSq);
195
- if (norm > maxNorm && norm > 0) {
196
- const scale = maxNorm / norm;
197
- for (const g of grads) for (let i = 0; i < g.data.length; i++) g.data[i]! *= scale;
198
- }
199
- return norm;
200
- }
201
-
202
- private _adamwStepCpu(
203
- grads: LimbicParam[],
204
- hp: { learningRate: number; weightDecay: number; beta1: number; beta2: number; eps: number; beta1_t: number; beta2_t: number },
205
- ): void {
206
- const params = this.model.parameters();
207
- const { learningRate: lr, weightDecay: wd, beta1, beta2, eps, beta1_t, beta2_t } = hp;
208
- for (let pi = 0; pi < params.length; pi++) {
209
- const p = params[pi]!.data;
210
- const g = grads[pi]!.data;
211
- const mom = this._moments![pi]!;
212
- for (let i = 0; i < p.length; i++) {
213
- const gi = g[i]!;
214
- mom.m[i] = beta1 * mom.m[i]! + (1 - beta1) * gi;
215
- mom.v[i] = beta2 * mom.v[i]! + (1 - beta2) * gi * gi;
216
- const mHat = mom.m[i]! / (1 - beta1_t);
217
- const vHat = mom.v[i]! / (1 - beta2_t);
218
- p[i] = p[i]! * (1 - lr * wd) - (lr * mHat) / (Math.sqrt(vHat) + eps);
219
- }
220
- }
221
- }
222
-
223
- /** AdamW on the GPU via the shared WEIGHT_UPDATE_WGSL kernel. Awaited per step. */
224
- private async _adamwStepGpu(
225
- grads: LimbicParam[],
226
- hp: { learningRate: number; weightDecay: number; beta1: number; beta2: number; eps: number; beta1_t: number; beta2_t: number },
227
- ): Promise<void> {
228
- const device = this.device!;
229
- const pipeline = this._adamwPipeline!;
230
- const params = this.model.parameters();
231
- const { learningRate: lr, weightDecay: wd, beta1, beta2, eps, beta1_t, beta2_t } = hp;
232
-
233
- for (let pi = 0; pi < params.length; pi++) {
234
- const p = params[pi]!;
235
- const mom = this._moments![pi]!;
236
- const paramBuf = createStorageBuffer(device, p.data, true);
237
- const gradBuf = createStorageBuffer(device, grads[pi]!.data, false);
238
- const mBuf = createStorageBuffer(device, mom.m, true);
239
- const vBuf = createStorageBuffer(device, mom.v, true);
240
- const uni = createUniformBuffer(
241
- device,
242
- packAdamParams(p.numel, lr, beta1, beta2, eps, wd, beta1_t, beta2_t),
243
- );
244
- const bg = createBindGroup(device, pipeline, [uni, paramBuf, gradBuf, mBuf, vBuf]);
245
- dispatchKernel(device, pipeline, bg, [cdiv(p.numel, 256), 1, 1]);
246
-
247
- p.data.set((await readBuffer(device, paramBuf, p.numel * 4)).subarray(0, p.numel));
248
- mom.m.set((await readBuffer(device, mBuf, p.numel * 4)).subarray(0, p.numel));
249
- mom.v.set((await readBuffer(device, vBuf, p.numel * 4)).subarray(0, p.numel));
250
-
251
- paramBuf.destroy();
252
- gradBuf.destroy();
253
- mBuf.destroy();
254
- vBuf.destroy();
255
- uni.destroy();
256
- }
257
- }
258
- }
1
+ /**
2
+ * limbic_trainer.ts – LimbicTrainer: gradient-based training for the LimbicModel.
3
+ *
4
+ * Trains the affect head to predict affect deltas and reward from
5
+ * (experience embedding, current state) pairs, using full-batch gradient
6
+ * descent with AdamW — through the shared {@link HeadTrainer} (`ml/head_trainer.ts`),
7
+ * which runs the optimiser step on the GPU via WEIGHT_UPDATE_WGSL when a device is
8
+ * supplied and on a numerically-equivalent CPU AdamW otherwise. This file is only
9
+ * the limbic registration: the head adapter and the public trainer surface.
10
+ *
11
+ * The objective is MSE (regression), not the cross-entropy used by the
12
+ * language-model {@link MambaTrainer} — a limbic experience has continuous
13
+ * targets, not a next-token distribution.
14
+ */
15
+
16
+ import { HeadTrainer, type HeadTrainOptions, type TrainableHead } from "../ml/head_trainer.js";
17
+ import type { LimbicModel, LimbicParam } from "./limbic_model.js";
18
+
19
+ /** One training example: an experience and the affect change it should produce. */
20
+ export interface LimbicSample {
21
+ /** Experience embedding (length = model.inputDim). */
22
+ input: ArrayLike<number>;
23
+ /** Affective state at the time of the experience (length = model.stateDim). */
24
+ state: ArrayLike<number>;
25
+ /** Observed affect delta target in (-1, 1) per state dim (length = model.stateDim). */
26
+ deltaTarget: ArrayLike<number>;
27
+ /** Observed scalar reward for the experience. */
28
+ reward: number;
29
+ }
30
+
31
+ /** The limbic trainer's options are the shared head trainer's. */
32
+ export type LimbicTrainOptions = HeadTrainOptions;
33
+
34
+ /**
35
+ * The limbic model as a {@link TrainableHead}. Each sample is one experience
36
+ * appraisal: cross-experience memory flows through the affective state `s` (fed
37
+ * back by the runtime), not through the hidden scratch `h`, so the hidden state
38
+ * resets per sample. This also makes BPTT(1) exact — there is no truncated carry.
39
+ */
40
+ export function limbicHead(model: LimbicModel): TrainableHead<LimbicSample> {
41
+ return {
42
+ parameters: (): LimbicParam[] => model.parameters(),
43
+ gradients: (): LimbicParam[] => model.gradients(),
44
+ zeroGrad: () => model.zeroGrad(),
45
+ accumulate: (s) =>
46
+ model.backwardStep(s.input, model.initHidden(), s.state, s.deltaTarget, s.reward).loss,
47
+ loss: (s) => {
48
+ const { rewardWeight } = model.config;
49
+ const f = model.forward(s.input, model.initHidden(), s.state);
50
+ let loss = 0;
51
+ for (let k = 0; k < f.delta.length; k++) {
52
+ const d = f.delta[k]! - (s.deltaTarget[k] ?? 0);
53
+ loss += 0.5 * d * d;
54
+ }
55
+ const rd = f.reward - s.reward;
56
+ loss += 0.5 * rewardWeight * rd * rd;
57
+ return loss;
58
+ },
59
+ };
60
+ }
61
+
62
+ /** Thin registration of the limbic head over the shared {@link HeadTrainer}. */
63
+ export class LimbicTrainer {
64
+ readonly model: LimbicModel;
65
+ readonly device: GPUDevice | null;
66
+ private readonly _trainer: HeadTrainer<LimbicSample>;
67
+
68
+ constructor(model: LimbicModel, device: GPUDevice | null = null) {
69
+ this.model = model;
70
+ this.device = device;
71
+ this._trainer = new HeadTrainer(limbicHead(model), device, "LimbicTrainer");
72
+ }
73
+
74
+ /** Whether the optimiser step runs on the GPU. */
75
+ get gpuTraining(): boolean {
76
+ return this._trainer.gpuTraining;
77
+ }
78
+
79
+ /**
80
+ * Train on a batch of samples for `epochs` passes. Returns the per-epoch mean
81
+ * loss (monotonically decreasing on a learnable mapping).
82
+ */
83
+ train(samples: LimbicSample[], opts: LimbicTrainOptions = {}): Promise<number[]> {
84
+ return this._trainer.train(samples, opts);
85
+ }
86
+
87
+ /** Mean MSE loss over samples (no weight update). Hidden resets per sample. */
88
+ evaluate(samples: LimbicSample[]): number {
89
+ return this._trainer.evaluate(samples);
90
+ }
91
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * ml/classical/ewma.ts — exponentially-weighted moving average + variance, for
3
+ * drift anomalies in an ordered series (a run's cost creeping up over the week).
4
+ *
5
+ * Per feature, over the history IN ORDER: diff = x − μ; μ += α·diff;
6
+ * σ² = (1 − α)(σ² + α·diff²). A new point scores z = |x − μ| / σ against the
7
+ * state BEFORE it is folded in. Prediction: `scores[0] = max_i z_i / threshold`.
8
+ */
9
+ import type { MlPrediction, MlPredictor, MlSample } from "../types.js";
10
+ import { featureDim } from "./math.js";
11
+ import { anomalyConfidence } from "./robust_z.js";
12
+
13
+ export interface EwmaOptions {
14
+ /** Smoothing factor in (0, 1]. Default 0.3. */
15
+ alpha?: number;
16
+ /** z at which a feature counts as anomalous. Default 3. */
17
+ threshold?: number;
18
+ /** Smallest σ per feature, as a fraction of |μ| (plus 1e-9). Default 0.01. */
19
+ minScaleFraction?: number;
20
+ }
21
+
22
+ export class EwmaModel implements MlPredictor {
23
+ constructor(
24
+ readonly mean: Float64Array,
25
+ readonly variance: Float64Array,
26
+ readonly alpha: number,
27
+ readonly threshold: number,
28
+ readonly minScaleFraction: number,
29
+ ) {
30
+ if (!(alpha > 0 && alpha <= 1)) throw new Error(`EwmaModel: alpha must be in (0, 1] (got ${alpha})`);
31
+ }
32
+
33
+ zScores(x: ArrayLike<number>): number[] {
34
+ return Array.from(this.mean, (m, i) => {
35
+ const sd = Math.max(Math.sqrt(this.variance[i]!), this.minScaleFraction * Math.abs(m) + 1e-9);
36
+ return Math.abs((x[i] ?? 0) - m) / sd;
37
+ });
38
+ }
39
+
40
+ /** Fold one observation into the running state. */
41
+ update(x: ArrayLike<number>): void {
42
+ for (let i = 0; i < this.mean.length; i++) {
43
+ const diff = (x[i] ?? 0) - this.mean[i]!;
44
+ const incr = this.alpha * diff;
45
+ this.mean[i] = this.mean[i]! + incr;
46
+ this.variance[i] = (1 - this.alpha) * (this.variance[i]! + diff * incr);
47
+ }
48
+ }
49
+
50
+ predict(x: Float32Array): MlPrediction {
51
+ const score = Math.max(0, ...this.zScores(x)) / this.threshold;
52
+ return { scores: [score], confidence: anomalyConfidence(score) };
53
+ }
54
+ }
55
+
56
+ /** Fit over `samples` in the given (chronological) order. */
57
+ export function fitEwma(samples: readonly MlSample[], opts: EwmaOptions = {}): EwmaModel {
58
+ const d = featureDim(samples.map((s) => s.x));
59
+ const model = new EwmaModel(
60
+ Float64Array.from(samples[0]!.x),
61
+ new Float64Array(d),
62
+ opts.alpha ?? 0.3,
63
+ opts.threshold ?? 3,
64
+ opts.minScaleFraction ?? 0.01,
65
+ );
66
+ for (let i = 1; i < samples.length; i++) model.update(samples[i]!.x);
67
+ return model;
68
+ }