@seanhogg/builderforce-memory-engine 2026.9.34 → 2026.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/evermind/delta_wire.d.ts +26 -2
- package/dist/evermind/delta_wire.d.ts.map +1 -1
- package/dist/evermind/delta_wire.js +46 -4
- package/dist/evermind/delta_wire.js.map +1 -1
- package/dist/evermind/index.d.ts +5 -5
- package/dist/evermind/index.d.ts.map +1 -1
- package/dist/evermind/index.js +2 -2
- package/dist/evermind/index.js.map +1 -1
- package/dist/evermind/merge.d.ts +28 -0
- package/dist/evermind/merge.d.ts.map +1 -1
- package/dist/evermind/merge.js +33 -0
- package/dist/evermind/merge.js.map +1 -1
- package/dist/evermind/ml_head.d.ts +28 -0
- package/dist/evermind/ml_head.d.ts.map +1 -0
- package/dist/evermind/ml_head.js +47 -0
- package/dist/evermind/ml_head.js.map +1 -0
- package/dist/evermind/package.d.ts +9 -0
- package/dist/evermind/package.d.ts.map +1 -1
- package/dist/evermind/package.js +20 -0
- package/dist/evermind/package.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/limbic/index.d.ts +3 -0
- package/dist/limbic/index.d.ts.map +1 -1
- package/dist/limbic/index.js +3 -0
- package/dist/limbic/index.js.map +1 -1
- package/dist/limbic/limbic_model.d.ts.map +1 -1
- package/dist/limbic/limbic_model.js +1 -3
- package/dist/limbic/limbic_model.js.map +1 -1
- package/dist/limbic/limbic_task.d.ts +22 -0
- package/dist/limbic/limbic_task.d.ts.map +1 -0
- package/dist/limbic/limbic_task.js +45 -0
- package/dist/limbic/limbic_task.js.map +1 -0
- package/dist/limbic/limbic_trainer.d.ts +17 -30
- package/dist/limbic/limbic_trainer.d.ts.map +1 -1
- package/dist/limbic/limbic_trainer.js +38 -144
- package/dist/limbic/limbic_trainer.js.map +1 -1
- package/dist/ml/classical/anomaly_composite.d.ts +32 -0
- package/dist/ml/classical/anomaly_composite.d.ts.map +1 -0
- package/dist/ml/classical/anomaly_composite.js +29 -0
- package/dist/ml/classical/anomaly_composite.js.map +1 -0
- package/dist/ml/classical/ewma.d.ts +37 -0
- package/dist/ml/classical/ewma.d.ts.map +1 -0
- package/dist/ml/classical/ewma.js +48 -0
- package/dist/ml/classical/ewma.js.map +1 -0
- package/dist/ml/classical/gbm.d.ts +42 -0
- package/dist/ml/classical/gbm.d.ts.map +1 -0
- package/dist/ml/classical/gbm.js +117 -0
- package/dist/ml/classical/gbm.js.map +1 -0
- package/dist/ml/classical/index.d.ts +52 -0
- package/dist/ml/classical/index.d.ts.map +1 -0
- package/dist/ml/classical/index.js +49 -0
- package/dist/ml/classical/index.js.map +1 -0
- package/dist/ml/classical/isolation_forest.d.ts +37 -0
- package/dist/ml/classical/isolation_forest.d.ts.map +1 -0
- package/dist/ml/classical/isolation_forest.js +72 -0
- package/dist/ml/classical/isolation_forest.js.map +1 -0
- package/dist/ml/classical/kmeans.d.ts +31 -0
- package/dist/ml/classical/kmeans.d.ts.map +1 -0
- package/dist/ml/classical/kmeans.js +112 -0
- package/dist/ml/classical/kmeans.js.map +1 -0
- package/dist/ml/classical/knn.d.ts +51 -0
- package/dist/ml/classical/knn.d.ts.map +1 -0
- package/dist/ml/classical/knn.js +69 -0
- package/dist/ml/classical/knn.js.map +1 -0
- package/dist/ml/classical/linear.d.ts +29 -0
- package/dist/ml/classical/linear.d.ts.map +1 -0
- package/dist/ml/classical/linear.js +114 -0
- package/dist/ml/classical/linear.js.map +1 -0
- package/dist/ml/classical/logistic.d.ts +31 -0
- package/dist/ml/classical/logistic.d.ts.map +1 -0
- package/dist/ml/classical/logistic.js +111 -0
- package/dist/ml/classical/logistic.js.map +1 -0
- package/dist/ml/classical/math.d.ts +26 -0
- package/dist/ml/classical/math.d.ts.map +1 -0
- package/dist/ml/classical/math.js +90 -0
- package/dist/ml/classical/math.js.map +1 -0
- package/dist/ml/classical/naive_bayes.d.ts +28 -0
- package/dist/ml/classical/naive_bayes.d.ts.map +1 -0
- package/dist/ml/classical/naive_bayes.js +72 -0
- package/dist/ml/classical/naive_bayes.js.map +1 -0
- package/dist/ml/classical/robust_z.d.ts +38 -0
- package/dist/ml/classical/robust_z.d.ts.map +1 -0
- package/dist/ml/classical/robust_z.js +47 -0
- package/dist/ml/classical/robust_z.js.map +1 -0
- package/dist/ml/dense_head.d.ts +33 -0
- package/dist/ml/dense_head.d.ts.map +1 -0
- package/dist/ml/dense_head.js +140 -0
- package/dist/ml/dense_head.js.map +1 -0
- package/dist/ml/eval_loss.d.ts +15 -0
- package/dist/ml/eval_loss.d.ts.map +1 -0
- package/dist/ml/eval_loss.js +20 -0
- package/dist/ml/eval_loss.js.map +1 -0
- package/dist/ml/features.d.ts +25 -0
- package/dist/ml/features.d.ts.map +1 -0
- package/dist/ml/features.js +46 -0
- package/dist/ml/features.js.map +1 -0
- package/dist/ml/federate.d.ts +56 -0
- package/dist/ml/federate.d.ts.map +1 -0
- package/dist/ml/federate.js +99 -0
- package/dist/ml/federate.js.map +1 -0
- package/dist/ml/head_trainer.d.ts +78 -0
- package/dist/ml/head_trainer.d.ts.map +1 -0
- package/dist/ml/head_trainer.js +182 -0
- package/dist/ml/head_trainer.js.map +1 -0
- package/dist/ml/index.d.ts +23 -0
- package/dist/ml/index.d.ts.map +1 -0
- package/dist/ml/index.js +11 -0
- package/dist/ml/index.js.map +1 -0
- package/dist/ml/registry.d.ts +20 -0
- package/dist/ml/registry.d.ts.map +1 -0
- package/dist/ml/registry.js +43 -0
- package/dist/ml/registry.js.map +1 -0
- package/dist/ml/run.d.ts +103 -0
- package/dist/ml/run.d.ts.map +1 -0
- package/dist/ml/run.js +169 -0
- package/dist/ml/run.js.map +1 -0
- package/dist/ml/tasks/experience.d.ts +127 -0
- package/dist/ml/tasks/experience.d.ts.map +1 -0
- package/dist/ml/tasks/experience.js +213 -0
- package/dist/ml/tasks/experience.js.map +1 -0
- package/dist/ml/tasks/index.d.ts +10 -0
- package/dist/ml/tasks/index.d.ts.map +1 -0
- package/dist/ml/tasks/index.js +28 -0
- package/dist/ml/tasks/index.js.map +1 -0
- package/dist/ml/tasks/local_success.d.ts +55 -0
- package/dist/ml/tasks/local_success.d.ts.map +1 -0
- package/dist/ml/tasks/local_success.js +77 -0
- package/dist/ml/tasks/local_success.js.map +1 -0
- package/dist/ml/tasks/run_anomaly.d.ts +52 -0
- package/dist/ml/tasks/run_anomaly.d.ts.map +1 -0
- package/dist/ml/tasks/run_anomaly.js +50 -0
- package/dist/ml/tasks/run_anomaly.js.map +1 -0
- package/dist/ml/train.d.ts +59 -0
- package/dist/ml/train.d.ts.map +1 -0
- package/dist/ml/train.js +84 -0
- package/dist/ml/train.js.map +1 -0
- package/dist/ml/types.d.ts +115 -0
- package/dist/ml/types.d.ts.map +1 -0
- package/dist/ml/types.js +24 -0
- package/dist/ml/types.js.map +1 -0
- package/dist/moe/moe_model.d.ts.map +1 -1
- package/dist/moe/moe_model.js +1 -16
- package/dist/moe/moe_model.js.map +1 -1
- package/dist/training/cpu_ops.d.ts +2 -0
- package/dist/training/cpu_ops.d.ts.map +1 -1
- package/dist/training/cpu_ops.js +16 -0
- package/dist/training/cpu_ops.js.map +1 -1
- package/package.json +1 -1
- package/src/evermind/delta_wire.ts +63 -4
- package/src/evermind/index.ts +7 -3
- package/src/evermind/merge.ts +59 -0
- package/src/evermind/ml_head.ts +63 -0
- package/src/evermind/package.ts +24 -0
- package/src/index.ts +17 -1
- package/src/limbic/index.ts +5 -0
- package/src/limbic/limbic_model.ts +1 -4
- package/src/limbic/limbic_task.ts +62 -0
- package/src/limbic/limbic_trainer.ts +41 -208
- package/src/ml/classical/anomaly_composite.ts +46 -0
- package/src/ml/classical/ewma.ts +74 -0
- package/src/ml/classical/gbm.ts +144 -0
- package/src/ml/classical/index.ts +82 -0
- package/src/ml/classical/isolation_forest.ts +88 -0
- package/src/ml/classical/kmeans.ts +120 -0
- package/src/ml/classical/knn.ts +102 -0
- package/src/ml/classical/linear.ts +119 -0
- package/src/ml/classical/logistic.ts +125 -0
- package/src/ml/classical/math.ts +93 -0
- package/src/ml/classical/naive_bayes.ts +84 -0
- package/src/ml/classical/robust_z.ts +74 -0
- package/src/ml/dense_head.ts +157 -0
- package/src/ml/eval_loss.ts +27 -0
- package/src/ml/features.ts +61 -0
- package/src/ml/federate.ts +130 -0
- package/src/ml/head_trainer.ts +247 -0
- package/src/ml/index.ts +57 -0
- package/src/ml/registry.ts +44 -0
- package/src/ml/run.ts +222 -0
- package/src/ml/tasks/experience.ts +293 -0
- package/src/ml/tasks/index.ts +30 -0
- package/src/ml/tasks/local_success.ts +118 -0
- package/src/ml/tasks/run_anomaly.ts +84 -0
- package/src/ml/train.ts +120 -0
- package/src/ml/types.ts +135 -0
- package/src/moe/moe_model.ts +1 -13
- package/src/training/cpu_ops.ts +14 -0
|
@@ -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
|
+
}
|
|
@@ -3,26 +3,17 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Trains the affect head to predict affect deltas and reward from
|
|
5
5
|
* (experience embedding, current state) pairs, using full-batch gradient
|
|
6
|
-
* descent with AdamW
|
|
7
|
-
* the
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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
10
|
*
|
|
11
11
|
* The objective is MSE (regression), not the cross-entropy used by the
|
|
12
12
|
* language-model {@link MambaTrainer} — a limbic experience has continuous
|
|
13
13
|
* targets, not a next-token distribution.
|
|
14
14
|
*/
|
|
15
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";
|
|
16
|
+
import { HeadTrainer, type HeadTrainOptions, type TrainableHead } from "../ml/head_trainer.js";
|
|
26
17
|
import type { LimbicModel, LimbicParam } from "./limbic_model.js";
|
|
27
18
|
|
|
28
19
|
/** One training example: an experience and the affect change it should produce. */
|
|
@@ -37,222 +28,64 @@ export interface LimbicSample {
|
|
|
37
28
|
reward: number;
|
|
38
29
|
}
|
|
39
30
|
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
}
|
|
31
|
+
/** The limbic trainer's options are the shared head trainer's. */
|
|
32
|
+
export type LimbicTrainOptions = HeadTrainOptions;
|
|
59
33
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
):
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
+
};
|
|
74
60
|
}
|
|
75
61
|
|
|
62
|
+
/** Thin registration of the limbic head over the shared {@link HeadTrainer}. */
|
|
76
63
|
export class LimbicTrainer {
|
|
77
64
|
readonly model: LimbicModel;
|
|
78
65
|
readonly device: GPUDevice | null;
|
|
79
|
-
private
|
|
80
|
-
private _step = 0;
|
|
81
|
-
private readonly _adamwPipeline: GPUComputePipeline | null;
|
|
66
|
+
private readonly _trainer: HeadTrainer<LimbicSample>;
|
|
82
67
|
|
|
83
68
|
constructor(model: LimbicModel, device: GPUDevice | null = null) {
|
|
84
69
|
this.model = model;
|
|
85
70
|
this.device = device;
|
|
86
|
-
this.
|
|
87
|
-
? createComputePipeline(device, WEIGHT_UPDATE_WGSL, "adamw_update")
|
|
88
|
-
: null;
|
|
71
|
+
this._trainer = new HeadTrainer(limbicHead(model), device, "LimbicTrainer");
|
|
89
72
|
}
|
|
90
73
|
|
|
91
74
|
/** Whether the optimiser step runs on the GPU. */
|
|
92
75
|
get gpuTraining(): boolean {
|
|
93
|
-
return this.
|
|
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
|
-
}));
|
|
76
|
+
return this._trainer.gpuTraining;
|
|
102
77
|
}
|
|
103
78
|
|
|
104
79
|
/**
|
|
105
80
|
* Train on a batch of samples for `epochs` passes. Returns the per-epoch mean
|
|
106
|
-
* loss (monotonically decreasing on a learnable mapping).
|
|
107
|
-
* accumulate across the whole sequence (recurrent hidden carried, reset per
|
|
108
|
-
* epoch), are averaged, clipped, then applied once per epoch.
|
|
81
|
+
* loss (monotonically decreasing on a learnable mapping).
|
|
109
82
|
*/
|
|
110
|
-
|
|
111
|
-
|
|
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;
|
|
83
|
+
train(samples: LimbicSample[], opts: LimbicTrainOptions = {}): Promise<number[]> {
|
|
84
|
+
return this._trainer.train(samples, opts);
|
|
169
85
|
}
|
|
170
86
|
|
|
171
87
|
/** Mean MSE loss over samples (no weight update). Hidden resets per sample. */
|
|
172
88
|
evaluate(samples: LimbicSample[]): number {
|
|
173
|
-
|
|
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
|
-
}
|
|
89
|
+
return this._trainer.evaluate(samples);
|
|
257
90
|
}
|
|
258
91
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ml/classical/anomaly_composite.ts — robust z and EWMA as ONE anomaly engine.
|
|
3
|
+
*
|
|
4
|
+
* Two detectors, one answer: robust z (median/MAD over the whole history — "far
|
|
5
|
+
* from normal") and EWMA (the recent trend — "drifting away from lately"). The
|
|
6
|
+
* score is the larger of the two normalised scores, so either one can flag. It is
|
|
7
|
+
* one engine because it is one fitted thing: a task that lists it gets back exactly
|
|
8
|
+
* what it stores under `local:classical:anomaly-composite`.
|
|
9
|
+
*/
|
|
10
|
+
import type { MlPrediction, MlPredictor, MlSample } from "../types.js";
|
|
11
|
+
import { EwmaModel, fitEwma, type EwmaOptions } from "./ewma.js";
|
|
12
|
+
import { anomalyConfidence, fitRobustZ, RobustZModel, type RobustZOptions } from "./robust_z.js";
|
|
13
|
+
|
|
14
|
+
export interface AnomalyCompositeOptions {
|
|
15
|
+
robustZ?: RobustZOptions;
|
|
16
|
+
ewma?: EwmaOptions;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class AnomalyCompositeModel implements MlPredictor {
|
|
20
|
+
constructor(
|
|
21
|
+
readonly population: RobustZModel,
|
|
22
|
+
readonly trend: EwmaModel,
|
|
23
|
+
) {}
|
|
24
|
+
|
|
25
|
+
/** Per feature, per detector: z / threshold (≥ 1 = out of range). */
|
|
26
|
+
featureScores(x: ArrayLike<number>): { population: number; trend: number }[] {
|
|
27
|
+
const pz = this.population.zScores(x);
|
|
28
|
+
const tz = this.trend.zScores(x);
|
|
29
|
+
return pz.map((z, i) => ({ population: z / this.population.threshold, trend: tz[i]! / this.trend.threshold }));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Fold a finished, non-anomalous observation into the trend. */
|
|
33
|
+
observe(x: ArrayLike<number>): void {
|
|
34
|
+
this.trend.update(x);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
predict(x: Float32Array): MlPrediction {
|
|
38
|
+
const score = Math.max(this.population.predict(x).scores[0]!, this.trend.predict(x).scores[0]!);
|
|
39
|
+
return { scores: [score], confidence: anomalyConfidence(score) };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Fit both detectors on a chronological history (feature vectors, oldest first). */
|
|
44
|
+
export function fitAnomalyComposite(samples: readonly MlSample[], opts: AnomalyCompositeOptions = {}): AnomalyCompositeModel {
|
|
45
|
+
return new AnomalyCompositeModel(fitRobustZ(samples, opts.robustZ), fitEwma(samples, opts.ewma));
|
|
46
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
* σ is floored like robust z's scale: a fraction of |μ|, and `minScale` in absolute
|
|
9
|
+
* units — σ² starts at 0, so a constant history would otherwise flag any change.
|
|
10
|
+
*/
|
|
11
|
+
import type { MlPrediction, MlPredictor, MlSample } from "../types.js";
|
|
12
|
+
import { featureDim } from "./math.js";
|
|
13
|
+
import { anomalyConfidence } from "./robust_z.js";
|
|
14
|
+
|
|
15
|
+
export interface EwmaOptions {
|
|
16
|
+
/** Smoothing factor in (0, 1]. Default 0.3. */
|
|
17
|
+
alpha?: number;
|
|
18
|
+
/** z at which a feature counts as anomalous. Default 3. */
|
|
19
|
+
threshold?: number;
|
|
20
|
+
/** Smallest σ per feature, as a fraction of |μ| (plus 1e-9). Default 0.01. */
|
|
21
|
+
minScaleFraction?: number;
|
|
22
|
+
/** Smallest σ per feature in absolute feature units. Default 0 (see `RobustZOptions.minScale`). */
|
|
23
|
+
minScale?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class EwmaModel implements MlPredictor {
|
|
27
|
+
constructor(
|
|
28
|
+
readonly mean: Float64Array,
|
|
29
|
+
readonly variance: Float64Array,
|
|
30
|
+
readonly alpha: number,
|
|
31
|
+
readonly threshold: number,
|
|
32
|
+
readonly minScaleFraction: number,
|
|
33
|
+
readonly minScale: number = 0,
|
|
34
|
+
) {
|
|
35
|
+
if (!(alpha > 0 && alpha <= 1)) throw new Error(`EwmaModel: alpha must be in (0, 1] (got ${alpha})`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
zScores(x: ArrayLike<number>): number[] {
|
|
39
|
+
return Array.from(this.mean, (m, i) => {
|
|
40
|
+
const sd = Math.max(Math.sqrt(this.variance[i]!), this.minScaleFraction * Math.abs(m) + 1e-9, this.minScale);
|
|
41
|
+
return Math.abs((x[i] ?? 0) - m) / sd;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Fold one observation into the running state. */
|
|
46
|
+
update(x: ArrayLike<number>): void {
|
|
47
|
+
for (let i = 0; i < this.mean.length; i++) {
|
|
48
|
+
const diff = (x[i] ?? 0) - this.mean[i]!;
|
|
49
|
+
const incr = this.alpha * diff;
|
|
50
|
+
this.mean[i] = this.mean[i]! + incr;
|
|
51
|
+
this.variance[i] = (1 - this.alpha) * (this.variance[i]! + diff * incr);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
predict(x: Float32Array): MlPrediction {
|
|
56
|
+
const score = Math.max(0, ...this.zScores(x)) / this.threshold;
|
|
57
|
+
return { scores: [score], confidence: anomalyConfidence(score) };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Fit over `samples` in the given (chronological) order. */
|
|
62
|
+
export function fitEwma(samples: readonly MlSample[], opts: EwmaOptions = {}): EwmaModel {
|
|
63
|
+
const d = featureDim(samples.map((s) => s.x));
|
|
64
|
+
const model = new EwmaModel(
|
|
65
|
+
Float64Array.from(samples[0]!.x),
|
|
66
|
+
new Float64Array(d),
|
|
67
|
+
opts.alpha ?? 0.3,
|
|
68
|
+
opts.threshold ?? 3,
|
|
69
|
+
opts.minScaleFraction ?? 0.01,
|
|
70
|
+
opts.minScale ?? 0,
|
|
71
|
+
);
|
|
72
|
+
for (let i = 1; i < samples.length; i++) model.update(samples[i]!.x);
|
|
73
|
+
return model;
|
|
74
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ml/classical/gbm.ts — a small gradient-boosted tree ensemble.
|
|
3
|
+
*
|
|
4
|
+
* Depth-limited regression trees fitted to the loss gradient, one after another,
|
|
5
|
+
* shrunk by a learning rate. Objectives: `binary` (log-loss, Newton leaf values)
|
|
6
|
+
* and `regression` (squared error). Exhaustive split search over midpoints —
|
|
7
|
+
* fine for the catalog's small numeric feature sets, not for wide embeddings.
|
|
8
|
+
*/
|
|
9
|
+
import type { MlPrediction, MlPredictor, MlSample } from "../types.js";
|
|
10
|
+
import { featureDim, sigmoid, type Vec } from "./math.js";
|
|
11
|
+
|
|
12
|
+
export type GbmObjective = "binary" | "regression";
|
|
13
|
+
|
|
14
|
+
export interface GbmOptions {
|
|
15
|
+
objective?: GbmObjective;
|
|
16
|
+
trees?: number;
|
|
17
|
+
maxDepth?: number;
|
|
18
|
+
learningRate?: number;
|
|
19
|
+
/** Minimum summed sample weight in a leaf. Default 1. */
|
|
20
|
+
minLeafWeight?: number;
|
|
21
|
+
/** L2 on leaf values (Newton denominator). Default 1. */
|
|
22
|
+
lambda?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type RTree = { value: number } | { feature: number; split: number; left: RTree; right: RTree };
|
|
26
|
+
|
|
27
|
+
interface Row {
|
|
28
|
+
x: Vec;
|
|
29
|
+
g: number; // gradient
|
|
30
|
+
h: number; // hessian
|
|
31
|
+
w: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function leafValue(rows: readonly Row[], lambda: number): number {
|
|
35
|
+
let g = 0;
|
|
36
|
+
let h = 0;
|
|
37
|
+
for (const r of rows) {
|
|
38
|
+
g += r.w * r.g;
|
|
39
|
+
h += r.w * r.h;
|
|
40
|
+
}
|
|
41
|
+
return -g / (h + lambda);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** XGBoost-style structure score G²/(H+λ) of a node. */
|
|
45
|
+
function gain(g: number, h: number, lambda: number): number {
|
|
46
|
+
return (g * g) / (h + lambda);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildTree(rows: Row[], depth: number, opts: Required<Omit<GbmOptions, "objective" | "trees" | "learningRate">>): RTree {
|
|
50
|
+
if (depth >= opts.maxDepth || rows.length < 2) return { value: leafValue(rows, opts.lambda) };
|
|
51
|
+
let G = 0;
|
|
52
|
+
let H = 0;
|
|
53
|
+
let W = 0;
|
|
54
|
+
for (const r of rows) {
|
|
55
|
+
G += r.w * r.g;
|
|
56
|
+
H += r.w * r.h;
|
|
57
|
+
W += r.w;
|
|
58
|
+
}
|
|
59
|
+
const parent = gain(G, H, opts.lambda);
|
|
60
|
+
let best: { feature: number; split: number; score: number } | null = null;
|
|
61
|
+
const d = rows[0]!.x.length;
|
|
62
|
+
for (let f = 0; f < d; f++) {
|
|
63
|
+
const sorted = [...rows].sort((a, b) => a.x[f]! - b.x[f]!);
|
|
64
|
+
let gl = 0;
|
|
65
|
+
let hl = 0;
|
|
66
|
+
let wl = 0;
|
|
67
|
+
for (let i = 0; i < sorted.length - 1; i++) {
|
|
68
|
+
const r = sorted[i]!;
|
|
69
|
+
gl += r.w * r.g;
|
|
70
|
+
hl += r.w * r.h;
|
|
71
|
+
wl += r.w;
|
|
72
|
+
const a = r.x[f]!;
|
|
73
|
+
const b = sorted[i + 1]!.x[f]!;
|
|
74
|
+
if (a === b) continue;
|
|
75
|
+
if (wl < opts.minLeafWeight || W - wl < opts.minLeafWeight) continue;
|
|
76
|
+
const score = gain(gl, hl, opts.lambda) + gain(G - gl, H - hl, opts.lambda) - parent;
|
|
77
|
+
if (score > 1e-12 && (!best || score > best.score)) best = { feature: f, split: (a + b) / 2, score };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (!best) return { value: leafValue(rows, opts.lambda) };
|
|
81
|
+
const left = rows.filter((r) => r.x[best!.feature]! < best!.split);
|
|
82
|
+
const right = rows.filter((r) => r.x[best!.feature]! >= best!.split);
|
|
83
|
+
return { feature: best.feature, split: best.split, left: buildTree(left, depth + 1, opts), right: buildTree(right, depth + 1, opts) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function treeValue(t: RTree, x: Vec): number {
|
|
87
|
+
while (!("value" in t)) t = x[t.feature]! < t.split ? t.left : t.right;
|
|
88
|
+
return t.value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export class GbmModel implements MlPredictor {
|
|
92
|
+
constructor(
|
|
93
|
+
readonly objective: GbmObjective,
|
|
94
|
+
readonly base: number,
|
|
95
|
+
readonly trees: readonly RTree[],
|
|
96
|
+
readonly learningRate: number,
|
|
97
|
+
) {}
|
|
98
|
+
|
|
99
|
+
/** The raw additive score (log-odds for `binary`). */
|
|
100
|
+
margin(x: Vec): number {
|
|
101
|
+
let s = this.base;
|
|
102
|
+
for (const t of this.trees) s += this.learningRate * treeValue(t, x);
|
|
103
|
+
return s;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
predict(x: Float32Array): MlPrediction {
|
|
107
|
+
const m = this.margin(x);
|
|
108
|
+
if (this.objective === "regression") return { scores: [m], confidence: 1 };
|
|
109
|
+
const p = sigmoid(m);
|
|
110
|
+
return { scores: [1 - p, p], confidence: Math.max(p, 1 - p) };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function fitGbm(samples: readonly MlSample[], opts: GbmOptions = {}): GbmModel {
|
|
115
|
+
featureDim(samples.map((s) => s.x));
|
|
116
|
+
const objective = opts.objective ?? "binary";
|
|
117
|
+
const lr = opts.learningRate ?? 0.3;
|
|
118
|
+
const treeOpts = { maxDepth: opts.maxDepth ?? 2, minLeafWeight: opts.minLeafWeight ?? 1, lambda: opts.lambda ?? 1 };
|
|
119
|
+
|
|
120
|
+
let wSum = 0;
|
|
121
|
+
let ySum = 0;
|
|
122
|
+
for (const s of samples) {
|
|
123
|
+
wSum += s.weight ?? 1;
|
|
124
|
+
ySum += (s.weight ?? 1) * s.y;
|
|
125
|
+
}
|
|
126
|
+
// All-zero weights would make this 0/0: fall back to the unweighted mean.
|
|
127
|
+
const yMean = wSum > 0 ? ySum / wSum : samples.reduce((a, s) => a + s.y, 0) / samples.length;
|
|
128
|
+
const base = objective === "binary" ? Math.log(Math.max(yMean, 1e-6) / Math.max(1 - yMean, 1e-6)) : yMean;
|
|
129
|
+
const margins = samples.map(() => base);
|
|
130
|
+
const trees: RTree[] = [];
|
|
131
|
+
for (let t = 0; t < (opts.trees ?? 50); t++) {
|
|
132
|
+
const rows: Row[] = samples.map((s, i) => {
|
|
133
|
+
if (objective === "binary") {
|
|
134
|
+
const p = sigmoid(margins[i]!);
|
|
135
|
+
return { x: s.x, g: p - s.y, h: Math.max(p * (1 - p), 1e-6), w: s.weight ?? 1 };
|
|
136
|
+
}
|
|
137
|
+
return { x: s.x, g: margins[i]! - s.y, h: 1, w: s.weight ?? 1 };
|
|
138
|
+
});
|
|
139
|
+
const tree = buildTree(rows, 0, treeOpts);
|
|
140
|
+
trees.push(tree);
|
|
141
|
+
samples.forEach((s, i) => (margins[i] = margins[i]! + lr * treeValue(tree, s.x)));
|
|
142
|
+
}
|
|
143
|
+
return new GbmModel(objective, base, trees, lr);
|
|
144
|
+
}
|