@seanhogg/builderforce-memory-engine 2026.10.1 → 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.
Files changed (122) hide show
  1. package/dist/evermind/delta_wire.d.ts +16 -1
  2. package/dist/evermind/delta_wire.d.ts.map +1 -1
  3. package/dist/evermind/delta_wire.js +22 -2
  4. package/dist/evermind/delta_wire.js.map +1 -1
  5. package/dist/evermind/index.d.ts +2 -2
  6. package/dist/evermind/index.d.ts.map +1 -1
  7. package/dist/evermind/index.js +1 -1
  8. package/dist/evermind/index.js.map +1 -1
  9. package/dist/evermind/merge.d.ts +5 -2
  10. package/dist/evermind/merge.d.ts.map +1 -1
  11. package/dist/evermind/merge.js +5 -2
  12. package/dist/evermind/merge.js.map +1 -1
  13. package/dist/evermind/ml_head.d.ts +28 -0
  14. package/dist/evermind/ml_head.d.ts.map +1 -0
  15. package/dist/evermind/ml_head.js +47 -0
  16. package/dist/evermind/ml_head.js.map +1 -0
  17. package/dist/evermind/package.d.ts +2 -2
  18. package/dist/evermind/package.d.ts.map +1 -1
  19. package/dist/evermind/package.js +1 -1
  20. package/dist/evermind/package.js.map +1 -1
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/limbic/limbic_model.d.ts.map +1 -1
  26. package/dist/limbic/limbic_model.js +1 -3
  27. package/dist/limbic/limbic_model.js.map +1 -1
  28. package/dist/ml/classical/anomaly_composite.d.ts +32 -0
  29. package/dist/ml/classical/anomaly_composite.d.ts.map +1 -0
  30. package/dist/ml/classical/anomaly_composite.js +29 -0
  31. package/dist/ml/classical/anomaly_composite.js.map +1 -0
  32. package/dist/ml/classical/ewma.d.ts +6 -1
  33. package/dist/ml/classical/ewma.d.ts.map +1 -1
  34. package/dist/ml/classical/ewma.js +5 -3
  35. package/dist/ml/classical/ewma.js.map +1 -1
  36. package/dist/ml/classical/gbm.d.ts.map +1 -1
  37. package/dist/ml/classical/gbm.js +2 -1
  38. package/dist/ml/classical/gbm.js.map +1 -1
  39. package/dist/ml/classical/index.d.ts +4 -0
  40. package/dist/ml/classical/index.d.ts.map +1 -1
  41. package/dist/ml/classical/index.js +4 -0
  42. package/dist/ml/classical/index.js.map +1 -1
  43. package/dist/ml/classical/kmeans.d.ts.map +1 -1
  44. package/dist/ml/classical/kmeans.js +23 -4
  45. package/dist/ml/classical/kmeans.js.map +1 -1
  46. package/dist/ml/classical/knn.d.ts +4 -1
  47. package/dist/ml/classical/knn.d.ts.map +1 -1
  48. package/dist/ml/classical/knn.js +2 -1
  49. package/dist/ml/classical/knn.js.map +1 -1
  50. package/dist/ml/classical/logistic.d.ts +1 -9
  51. package/dist/ml/classical/logistic.d.ts.map +1 -1
  52. package/dist/ml/classical/logistic.js +17 -9
  53. package/dist/ml/classical/logistic.js.map +1 -1
  54. package/dist/ml/classical/naive_bayes.d.ts +5 -1
  55. package/dist/ml/classical/naive_bayes.d.ts.map +1 -1
  56. package/dist/ml/classical/naive_bayes.js +8 -3
  57. package/dist/ml/classical/naive_bayes.js.map +1 -1
  58. package/dist/ml/classical/robust_z.d.ts +9 -1
  59. package/dist/ml/classical/robust_z.d.ts.map +1 -1
  60. package/dist/ml/classical/robust_z.js +2 -1
  61. package/dist/ml/classical/robust_z.js.map +1 -1
  62. package/dist/ml/eval_loss.d.ts +15 -0
  63. package/dist/ml/eval_loss.d.ts.map +1 -0
  64. package/dist/ml/eval_loss.js +20 -0
  65. package/dist/ml/eval_loss.js.map +1 -0
  66. package/dist/ml/federate.d.ts +11 -25
  67. package/dist/ml/federate.d.ts.map +1 -1
  68. package/dist/ml/federate.js +15 -38
  69. package/dist/ml/federate.js.map +1 -1
  70. package/dist/ml/head_trainer.d.ts +4 -2
  71. package/dist/ml/head_trainer.d.ts.map +1 -1
  72. package/dist/ml/head_trainer.js +19 -19
  73. package/dist/ml/head_trainer.js.map +1 -1
  74. package/dist/ml/run.d.ts +11 -2
  75. package/dist/ml/run.d.ts.map +1 -1
  76. package/dist/ml/run.js +56 -17
  77. package/dist/ml/run.js.map +1 -1
  78. package/dist/ml/tasks/experience.d.ts +42 -5
  79. package/dist/ml/tasks/experience.d.ts.map +1 -1
  80. package/dist/ml/tasks/experience.js +76 -19
  81. package/dist/ml/tasks/experience.js.map +1 -1
  82. package/dist/ml/tasks/run_anomaly.d.ts +20 -19
  83. package/dist/ml/tasks/run_anomaly.d.ts.map +1 -1
  84. package/dist/ml/tasks/run_anomaly.js +20 -30
  85. package/dist/ml/tasks/run_anomaly.js.map +1 -1
  86. package/dist/ml/train.d.ts +2 -7
  87. package/dist/ml/train.d.ts.map +1 -1
  88. package/dist/ml/train.js +2 -19
  89. package/dist/ml/train.js.map +1 -1
  90. package/dist/ml/types.d.ts +6 -3
  91. package/dist/ml/types.d.ts.map +1 -1
  92. package/dist/ml/types.js +3 -2
  93. package/dist/ml/types.js.map +1 -1
  94. package/package.json +1 -1
  95. package/src/evermind/delta_wire.ts +173 -148
  96. package/src/evermind/index.ts +36 -35
  97. package/src/evermind/merge.ts +10 -4
  98. package/src/evermind/ml_head.ts +63 -0
  99. package/src/evermind/package.ts +488 -488
  100. package/src/index.ts +2 -0
  101. package/src/limbic/limbic_model.ts +1 -4
  102. package/src/limbic/limbic_trainer.ts +91 -91
  103. package/src/ml/classical/anomaly_composite.ts +46 -0
  104. package/src/ml/classical/ewma.ts +7 -1
  105. package/src/ml/classical/gbm.ts +144 -143
  106. package/src/ml/classical/index.ts +6 -0
  107. package/src/ml/classical/kmeans.ts +22 -4
  108. package/src/ml/classical/knn.ts +6 -2
  109. package/src/ml/classical/logistic.ts +9 -9
  110. package/src/ml/classical/math.ts +93 -93
  111. package/src/ml/classical/naive_bayes.ts +10 -3
  112. package/src/ml/classical/robust_z.ts +11 -2
  113. package/src/ml/eval_loss.ts +27 -0
  114. package/src/ml/federate.ts +22 -52
  115. package/src/ml/head_trainer.ts +21 -42
  116. package/src/ml/registry.ts +44 -44
  117. package/src/ml/run.ts +57 -13
  118. package/src/ml/tasks/experience.ts +98 -19
  119. package/src/ml/tasks/run_anomaly.ts +30 -36
  120. package/src/ml/train.ts +3 -19
  121. package/src/ml/types.ts +135 -132
  122. package/src/training/cpu_ops.ts +141 -141
package/src/ml/types.ts CHANGED
@@ -1,132 +1,135 @@
1
- /**
2
- * ml/types.ts — the ML task catalog contract (docs/ml-task-catalog.md §3).
3
- *
4
- * One bounded question Evermind answers without an LLM is ONE data row: how its
5
- * input becomes a vector, which engines may answer it (in preference order), how
6
- * it trains, and what its output means. Pure types — no vscode, no DOM, no network.
7
- */
8
-
9
- /** The shape of the question. */
10
- export type MlTaskKind = "classify" | "regress" | "cluster" | "anomaly" | "rank";
11
-
12
- /** Pure-TypeScript algorithms that run everywhere (`ml/classical/`). */
13
- export type ClassicalAlgorithm =
14
- | "knn"
15
- | "naive-bayes"
16
- | "logistic"
17
- | "linear"
18
- | "kmeans"
19
- | "robust-z"
20
- | "ewma"
21
- | "isolation-forest"
22
- | "gbm-small";
23
-
24
- /** An engine that can answer a task. Cloud engines are a port the HOST supplies. */
25
- export type MlEngineRef =
26
- | { tier: "local"; engine: "classical"; algorithm: ClassicalAlgorithm }
27
- | { tier: "local"; engine: "head"; head: "mlp" | "linear" }
28
- | { tier: "local"; engine: "onnx"; model: string }
29
- | { tier: "cloud"; engine: "workers-ai"; model: string };
30
-
31
- /**
32
- * Which engines a run may use — the person's inference setting.
33
- * - `local-only`: local tiers only, never the network.
34
- * - `hybrid`: local first, the cloud port when no local engine can answer (or the
35
- * local answer is below the caller's confidence floor).
36
- * - `specific`: exactly the engine the caller names.
37
- */
38
- export type InferenceMode = "local-only" | "hybrid" | "specific";
39
-
40
- /** What an engine returns before the task decodes it. */
41
- export interface MlPrediction {
42
- /**
43
- * classify: one probability per label; regress: the predicted value(s);
44
- * cluster: `[clusterId]`; anomaly: `[score]` where ≥ 1 is anomalous;
45
- * rank: one score per candidate.
46
- */
47
- scores: number[];
48
- /** Calibrated confidence in [0, 1]. */
49
- confidence: number;
50
- }
51
-
52
- /** A fitted model that answers on a feature vector. */
53
- export interface MlPredictor {
54
- predict(x: Float32Array): MlPrediction;
55
- /** Trainable state as one flat vector — present on models that federate. */
56
- exportParams?(): Float32Array;
57
- /** Load a flat vector produced by {@link exportParams} (e.g. after a merge). */
58
- importParams?(params: ArrayLike<number>): void;
59
- }
60
-
61
- /** How an input becomes a vector: an embedded text part, numeric fields, or both. */
62
- export interface FeatureSpec<I> {
63
- /** Text to embed (needs an embedder in the run context). */
64
- text?: (input: I) => string;
65
- /** Numeric fields, already on a stable scale (so federated weights mean the same thing everywhere). */
66
- numeric?: (input: I) => number[];
67
- /** Names of the numeric fields, index-aligned — documentation and Insights labels. */
68
- numericNames?: readonly string[];
69
- }
70
-
71
- /** One labelled training example in feature space. */
72
- export interface MlSample {
73
- x: Float32Array;
74
- /** classify: class index; regress: target value; cluster/anomaly: ignored. */
75
- y: number;
76
- /** Sample weight (default 1). */
77
- weight?: number;
78
- }
79
-
80
- /** How a task trains. Absent on the task = rule-based or pre-trained only. */
81
- export interface TrainSpec {
82
- /** Fewer labelled examples than this and the task stays untrained. */
83
- minSamples: number;
84
- /** Fraction held out for the eval gate (default 0.2). */
85
- holdoutFraction?: number;
86
- /**
87
- * A task-specific fit (e.g. a composite of two classical detectors). When absent
88
- * the trainer fits the engine named by the run (`ml/train.ts`).
89
- */
90
- fit?: (samples: readonly MlSample[], engine: MlEngineRef) => MlPredictor;
91
- /** Who trains it when not `ml/train.ts` (e.g. `LimbicTrainer` for `limbic.affect`). */
92
- trainedBy?: string;
93
- }
94
-
95
- /** What a task's answer means. */
96
- export interface OutputSpec<O> {
97
- /** Label set for classify tasks (index-aligned with `MlPrediction.scores`). */
98
- labels?: readonly string[];
99
- /** Decode an engine prediction into the task's output. */
100
- decode(p: MlPrediction): O;
101
- }
102
-
103
- /** One bounded question Evermind can answer without an LLM. DATA, not a class tree. */
104
- export interface MlTask<I = unknown, O = unknown> {
105
- kind: MlTaskKind;
106
- /** Stable id, e.g. `experience.quality`. */
107
- id: string;
108
- /** One line on what it answers. */
109
- description: string;
110
- features: FeatureSpec<I>;
111
- /** In preference order; filtered by the inference mode. */
112
- engines: readonly MlEngineRef[];
113
- train?: TrainSpec;
114
- output: OutputSpec<O>;
115
- }
116
-
117
- /** Task ids: lowercase dotted segments, e.g. `run.local-success`. */
118
- export const ML_TASK_ID_RE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
119
-
120
- /** A stable string key for an engine ref, e.g. `local:classical:logistic`. */
121
- export function engineKey(ref: MlEngineRef): string {
122
- switch (ref.engine) {
123
- case "classical":
124
- return `local:classical:${ref.algorithm}`;
125
- case "head":
126
- return `local:head:${ref.head}`;
127
- case "onnx":
128
- return `local:onnx:${ref.model}`;
129
- case "workers-ai":
130
- return `cloud:workers-ai:${ref.model}`;
131
- }
132
- }
1
+ /**
2
+ * ml/types.ts — the ML task catalog contract (docs/ml-task-catalog.md §3).
3
+ *
4
+ * One bounded question Evermind answers without an LLM is ONE data row: how its
5
+ * input becomes a vector, which engines may answer it (in preference order), how
6
+ * it trains, and what its output means. Pure types — no vscode, no DOM, no network.
7
+ * (Imports only the leaf `evermind/ml_head.ts`; evermind/ never imports ml/.)
8
+ */
9
+
10
+ /** The shape of the question. */
11
+ export type MlTaskKind = "classify" | "regress" | "cluster" | "anomaly" | "rank";
12
+
13
+ /** Pure-TypeScript algorithms that run everywhere (`ml/classical/`). */
14
+ export type ClassicalAlgorithm =
15
+ | "knn"
16
+ | "naive-bayes"
17
+ | "logistic"
18
+ | "linear"
19
+ | "kmeans"
20
+ | "robust-z"
21
+ | "ewma"
22
+ /** robust z + EWMA as one fitted engine (`classical/anomaly_composite.ts`). */
23
+ | "anomaly-composite"
24
+ | "isolation-forest"
25
+ | "gbm-small";
26
+
27
+ /** An engine that can answer a task. Cloud engines are a port the HOST supplies. */
28
+ export type MlEngineRef =
29
+ | { tier: "local"; engine: "classical"; algorithm: ClassicalAlgorithm }
30
+ | { tier: "local"; engine: "head"; head: "mlp" | "linear" }
31
+ | { tier: "local"; engine: "onnx"; model: string }
32
+ | { tier: "cloud"; engine: "workers-ai"; model: string };
33
+
34
+ /**
35
+ * Which engines a run may use — the person's inference setting.
36
+ * - `local-only`: local tiers only, never the network.
37
+ * - `hybrid`: local first, the cloud port when no local engine can answer (or the
38
+ * local answer is below the caller's confidence floor).
39
+ * - `specific`: exactly the engine the caller names.
40
+ */
41
+ export type InferenceMode = "local-only" | "hybrid" | "specific";
42
+
43
+ /** What an engine returns before the task decodes it. */
44
+ export interface MlPrediction {
45
+ /**
46
+ * classify: one probability per label; regress: the predicted value(s);
47
+ * cluster: `[clusterId]`; anomaly: `[score]` where ≥ 1 is anomalous;
48
+ * rank: one score per candidate.
49
+ */
50
+ scores: number[];
51
+ /** Calibrated confidence in [0, 1]. */
52
+ confidence: number;
53
+ }
54
+
55
+ /** A fitted model that answers on a feature vector. */
56
+ export interface MlPredictor {
57
+ predict(x: Float32Array): MlPrediction;
58
+ /** Trainable state as one flat vector — present on models that federate. */
59
+ exportParams?(): Float32Array;
60
+ /** Load a flat vector produced by {@link exportParams} (e.g. after a merge). */
61
+ importParams?(params: ArrayLike<number>): void;
62
+ }
63
+
64
+ /** How an input becomes a vector: an embedded text part, numeric fields, or both. */
65
+ export interface FeatureSpec<I> {
66
+ /** Text to embed (needs an embedder in the run context). */
67
+ text?: (input: I) => string;
68
+ /** Numeric fields, already on a stable scale (so federated weights mean the same thing everywhere). */
69
+ numeric?: (input: I) => number[];
70
+ /** Names of the numeric fields, index-aligned — documentation and Insights labels. */
71
+ numericNames?: readonly string[];
72
+ }
73
+
74
+ /** One labelled training example in feature space. */
75
+ export interface MlSample {
76
+ x: Float32Array;
77
+ /** classify: class index; regress: target value; cluster/anomaly: ignored. */
78
+ y: number;
79
+ /** Sample weight (default 1). */
80
+ weight?: number;
81
+ }
82
+
83
+ /** How a task trains. Absent on the task = rule-based or pre-trained only. */
84
+ export interface TrainSpec {
85
+ /** Fewer labelled examples than this and the task stays untrained. */
86
+ minSamples: number;
87
+ /** Fraction held out for the eval gate (default 0.2). */
88
+ holdoutFraction?: number;
89
+ /**
90
+ * A task-specific fit (e.g. a composite of two classical detectors). When absent
91
+ * the trainer fits the engine named by the run (`ml/train.ts`).
92
+ */
93
+ fit?: (samples: readonly MlSample[], engine: MlEngineRef) => MlPredictor;
94
+ /** Who trains it when not `ml/train.ts` (e.g. `LimbicTrainer` for `limbic.affect`). */
95
+ trainedBy?: string;
96
+ }
97
+
98
+ /** What a task's answer means. */
99
+ export interface OutputSpec<O> {
100
+ /** Label set for classify tasks (index-aligned with `MlPrediction.scores`). */
101
+ labels?: readonly string[];
102
+ /** Decode an engine prediction into the task's output. */
103
+ decode(p: MlPrediction): O;
104
+ }
105
+
106
+ /** One bounded question Evermind can answer without an LLM. DATA, not a class tree. */
107
+ export interface MlTask<I = unknown, O = unknown> {
108
+ kind: MlTaskKind;
109
+ /** Stable id, e.g. `experience.quality`. */
110
+ id: string;
111
+ /** One line on what it answers. */
112
+ description: string;
113
+ features: FeatureSpec<I>;
114
+ /** In preference order; filtered by the inference mode. */
115
+ engines: readonly MlEngineRef[];
116
+ train?: TrainSpec;
117
+ output: OutputSpec<O>;
118
+ }
119
+
120
+ /** Task ids: lowercase dotted segments — defined once with the artifact's head contract. */
121
+ export { ML_TASK_ID_RE } from "../evermind/ml_head.js";
122
+
123
+ /** A stable string key for an engine ref, e.g. `local:classical:logistic`. */
124
+ export function engineKey(ref: MlEngineRef): string {
125
+ switch (ref.engine) {
126
+ case "classical":
127
+ return `local:classical:${ref.algorithm}`;
128
+ case "head":
129
+ return `local:head:${ref.head}`;
130
+ case "onnx":
131
+ return `local:onnx:${ref.model}`;
132
+ case "workers-ai":
133
+ return `cloud:workers-ai:${ref.model}`;
134
+ }
135
+ }
@@ -1,141 +1,141 @@
1
- /**
2
- * cpu_ops.ts — the small set of exact CPU primitives the reference forward and
3
- * backward passes share (linear, RMSNorm, SiLU, softplus).
4
- *
5
- * Each one mirrors a WGSL kernel exactly, so a gradient computed here is the
6
- * gradient of the function the GPU actually evaluates. They are deliberately
7
- * plain loops over `Float32Array`: correctness first, and small enough that the
8
- * finite-difference check in `tests/backprop.test.ts` is meaningful.
9
- */
10
-
11
- /** Epsilon used by `rmsnorm_forward` in `ACTIVATIONS_WGSL`. */
12
- export const RMSNORM_EPS = 1e-6;
13
-
14
- export function sigmoid(x: number): number {
15
- return 1 / (1 + Math.exp(-x));
16
- }
17
-
18
- /** Numerically-stable softmax over a flat array. */
19
- export function softmax(logits: ArrayLike<number>): Float32Array {
20
- let max = -Infinity;
21
- for (let i = 0; i < logits.length; i++) if (logits[i]! > max) max = logits[i]!;
22
- const out = new Float32Array(logits.length);
23
- let sum = 0;
24
- for (let i = 0; i < logits.length; i++) {
25
- out[i] = Math.exp(logits[i]! - max);
26
- sum += out[i]!;
27
- }
28
- for (let i = 0; i < logits.length; i++) out[i] = out[i]! / sum;
29
- return out;
30
- }
31
-
32
- /** SiLU(x) = x * sigmoid(x) — mirrors `silu_forward`. */
33
- export function silu(x: number): number {
34
- return x / (1 + Math.exp(-x));
35
- }
36
-
37
- /** d/dx SiLU(x) = sigmoid(x) * (1 + x * (1 - sigmoid(x))). */
38
- export function siluGrad(x: number): number {
39
- const s = sigmoid(x);
40
- return s * (1 + x * (1 - s));
41
- }
42
-
43
- /** Numerically stable softplus — mirrors the kernel's `max(x,0) + log1p(exp(-|x|))`. */
44
- export function softplus(x: number): number {
45
- return Math.max(x, 0) + Math.log1p(Math.exp(-Math.abs(x)));
46
- }
47
-
48
- /**
49
- * Y = X @ W^T + b, mirroring `linear_forward`.
50
- *
51
- * @param X (M, K)
52
- * @param W (N, K) row-major
53
- * @param b (N,)
54
- * @param out (M, N) — written, not accumulated
55
- */
56
- export function linearForward(
57
- X: Float32Array, W: Float32Array, b: Float32Array,
58
- M: number, K: number, N: number, out: Float32Array,
59
- ): void {
60
- for (let r = 0; r < M; r++) {
61
- const xo = r * K;
62
- const yo = r * N;
63
- for (let n = 0; n < N; n++) {
64
- let acc = b[n]!;
65
- const wo = n * K;
66
- for (let k = 0; k < K; k++) acc += X[xo + k]! * W[wo + k]!;
67
- out[yo + n] = acc;
68
- }
69
- }
70
- }
71
-
72
- /**
73
- * Backward of {@link linearForward}. `dX` is written; `dW` and `db` are
74
- * ACCUMULATED into (so one parameter can collect gradient from several call
75
- * sites without a temporary).
76
- */
77
- export function linearBackward(
78
- dY: Float32Array, X: Float32Array, W: Float32Array,
79
- M: number, K: number, N: number,
80
- dX: Float32Array, dW: Float32Array, db: Float32Array,
81
- ): void {
82
- dX.fill(0);
83
- for (let r = 0; r < M; r++) {
84
- const xo = r * K;
85
- const yo = r * N;
86
- for (let n = 0; n < N; n++) {
87
- const g = dY[yo + n]!;
88
- if (g === 0) continue;
89
- db[n] = db[n]! + g;
90
- const wo = n * K;
91
- for (let k = 0; k < K; k++) {
92
- dX[xo + k] = dX[xo + k]! + g * W[wo + k]!;
93
- dW[wo + k] = dW[wo + k]! + g * X[xo + k]!;
94
- }
95
- }
96
- }
97
- }
98
-
99
- /**
100
- * RMSNorm forward — mirrors `rmsnorm_forward`:
101
- * inv[r] = 1 / sqrt(mean(x[r]²) + eps); y[r,i] = x[r,i] * inv[r] * w[i]
102
- */
103
- export function rmsNormForward(
104
- x: Float32Array, w: Float32Array, M: number, D: number,
105
- out: Float32Array, inv: Float32Array, eps: number = RMSNORM_EPS,
106
- ): void {
107
- for (let r = 0; r < M; r++) {
108
- const base = r * D;
109
- let sq = 0;
110
- for (let i = 0; i < D; i++) { const v = x[base + i]!; sq += v * v; }
111
- const iv = 1 / Math.sqrt(sq / D + eps);
112
- inv[r] = iv;
113
- for (let i = 0; i < D; i++) out[base + i] = x[base + i]! * iv * w[i]!;
114
- }
115
- }
116
-
117
- /**
118
- * RMSNorm backward. `dx` and `dw` are ACCUMULATED into — `dx` in particular is
119
- * usually the residual path, which already carries a gradient.
120
- */
121
- export function rmsNormBackward(
122
- dY: Float32Array, x: Float32Array, w: Float32Array, inv: Float32Array,
123
- M: number, D: number,
124
- dx: Float32Array, dw: Float32Array, _eps: number = RMSNORM_EPS,
125
- ): void {
126
- for (let r = 0; r < M; r++) {
127
- const base = r * D;
128
- const iv = inv[r]!;
129
- let dot = 0; // Σ_i (dY[r,i] * w[i]) * x[r,i]
130
- for (let i = 0; i < D; i++) {
131
- const g = dY[base + i]! * w[i]!;
132
- dot += g * x[base + i]!;
133
- dw[i] = dw[i]! + dY[base + i]! * x[base + i]! * iv;
134
- }
135
- const scale = (iv * iv * iv) / D;
136
- for (let i = 0; i < D; i++) {
137
- const g = dY[base + i]! * w[i]!;
138
- dx[base + i] = dx[base + i]! + g * iv - scale * dot * x[base + i]!;
139
- }
140
- }
141
- }
1
+ /**
2
+ * cpu_ops.ts — the small set of exact CPU primitives the reference forward and
3
+ * backward passes share (linear, RMSNorm, SiLU, softplus).
4
+ *
5
+ * Each one mirrors a WGSL kernel exactly, so a gradient computed here is the
6
+ * gradient of the function the GPU actually evaluates. They are deliberately
7
+ * plain loops over `Float32Array`: correctness first, and small enough that the
8
+ * finite-difference check in `tests/backprop.test.ts` is meaningful.
9
+ */
10
+
11
+ /** Epsilon used by `rmsnorm_forward` in `ACTIVATIONS_WGSL`. */
12
+ export const RMSNORM_EPS = 1e-6;
13
+
14
+ export function sigmoid(x: number): number {
15
+ return 1 / (1 + Math.exp(-x));
16
+ }
17
+
18
+ /** Numerically-stable softmax over a flat array. */
19
+ export function softmax(logits: ArrayLike<number>): Float32Array {
20
+ let max = -Infinity;
21
+ for (let i = 0; i < logits.length; i++) if (logits[i]! > max) max = logits[i]!;
22
+ const out = new Float32Array(logits.length);
23
+ let sum = 0;
24
+ for (let i = 0; i < logits.length; i++) {
25
+ out[i] = Math.exp(logits[i]! - max);
26
+ sum += out[i]!;
27
+ }
28
+ for (let i = 0; i < logits.length; i++) out[i] = out[i]! / sum;
29
+ return out;
30
+ }
31
+
32
+ /** SiLU(x) = x * sigmoid(x) — mirrors `silu_forward`. */
33
+ export function silu(x: number): number {
34
+ return x / (1 + Math.exp(-x));
35
+ }
36
+
37
+ /** d/dx SiLU(x) = sigmoid(x) * (1 + x * (1 - sigmoid(x))). */
38
+ export function siluGrad(x: number): number {
39
+ const s = sigmoid(x);
40
+ return s * (1 + x * (1 - s));
41
+ }
42
+
43
+ /** Numerically stable softplus — mirrors the kernel's `max(x,0) + log1p(exp(-|x|))`. */
44
+ export function softplus(x: number): number {
45
+ return Math.max(x, 0) + Math.log1p(Math.exp(-Math.abs(x)));
46
+ }
47
+
48
+ /**
49
+ * Y = X @ W^T + b, mirroring `linear_forward`.
50
+ *
51
+ * @param X (M, K)
52
+ * @param W (N, K) row-major
53
+ * @param b (N,)
54
+ * @param out (M, N) — written, not accumulated
55
+ */
56
+ export function linearForward(
57
+ X: Float32Array, W: Float32Array, b: Float32Array,
58
+ M: number, K: number, N: number, out: Float32Array,
59
+ ): void {
60
+ for (let r = 0; r < M; r++) {
61
+ const xo = r * K;
62
+ const yo = r * N;
63
+ for (let n = 0; n < N; n++) {
64
+ let acc = b[n]!;
65
+ const wo = n * K;
66
+ for (let k = 0; k < K; k++) acc += X[xo + k]! * W[wo + k]!;
67
+ out[yo + n] = acc;
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Backward of {@link linearForward}. `dX` is written; `dW` and `db` are
74
+ * ACCUMULATED into (so one parameter can collect gradient from several call
75
+ * sites without a temporary).
76
+ */
77
+ export function linearBackward(
78
+ dY: Float32Array, X: Float32Array, W: Float32Array,
79
+ M: number, K: number, N: number,
80
+ dX: Float32Array, dW: Float32Array, db: Float32Array,
81
+ ): void {
82
+ dX.fill(0);
83
+ for (let r = 0; r < M; r++) {
84
+ const xo = r * K;
85
+ const yo = r * N;
86
+ for (let n = 0; n < N; n++) {
87
+ const g = dY[yo + n]!;
88
+ if (g === 0) continue;
89
+ db[n] = db[n]! + g;
90
+ const wo = n * K;
91
+ for (let k = 0; k < K; k++) {
92
+ dX[xo + k] = dX[xo + k]! + g * W[wo + k]!;
93
+ dW[wo + k] = dW[wo + k]! + g * X[xo + k]!;
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * RMSNorm forward — mirrors `rmsnorm_forward`:
101
+ * inv[r] = 1 / sqrt(mean(x[r]²) + eps); y[r,i] = x[r,i] * inv[r] * w[i]
102
+ */
103
+ export function rmsNormForward(
104
+ x: Float32Array, w: Float32Array, M: number, D: number,
105
+ out: Float32Array, inv: Float32Array, eps: number = RMSNORM_EPS,
106
+ ): void {
107
+ for (let r = 0; r < M; r++) {
108
+ const base = r * D;
109
+ let sq = 0;
110
+ for (let i = 0; i < D; i++) { const v = x[base + i]!; sq += v * v; }
111
+ const iv = 1 / Math.sqrt(sq / D + eps);
112
+ inv[r] = iv;
113
+ for (let i = 0; i < D; i++) out[base + i] = x[base + i]! * iv * w[i]!;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * RMSNorm backward. `dx` and `dw` are ACCUMULATED into — `dx` in particular is
119
+ * usually the residual path, which already carries a gradient.
120
+ */
121
+ export function rmsNormBackward(
122
+ dY: Float32Array, x: Float32Array, w: Float32Array, inv: Float32Array,
123
+ M: number, D: number,
124
+ dx: Float32Array, dw: Float32Array, _eps: number = RMSNORM_EPS,
125
+ ): void {
126
+ for (let r = 0; r < M; r++) {
127
+ const base = r * D;
128
+ const iv = inv[r]!;
129
+ let dot = 0; // Σ_i (dY[r,i] * w[i]) * x[r,i]
130
+ for (let i = 0; i < D; i++) {
131
+ const g = dY[base + i]! * w[i]!;
132
+ dot += g * x[base + i]!;
133
+ dw[i] = dw[i]! + dY[base + i]! * x[base + i]! * iv;
134
+ }
135
+ const scale = (iv * iv * iv) / D;
136
+ for (let i = 0; i < D; i++) {
137
+ const g = dY[base + i]! * w[i]!;
138
+ dx[base + i] = dx[base + i]! + g * iv - scale * dot * x[base + i]!;
139
+ }
140
+ }
141
+ }