@seanhogg/builderforce-memory-engine 2026.7.12 → 2026.7.14
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/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/lm/evermind_lm.d.ts +70 -3
- package/dist/lm/evermind_lm.d.ts.map +1 -1
- package/dist/lm/evermind_lm.js +242 -110
- package/dist/lm/evermind_lm.js.map +1 -1
- package/dist/lm/index.d.ts +5 -1
- package/dist/lm/index.d.ts.map +1 -1
- package/dist/lm/index.js +3 -0
- package/dist/lm/index.js.map +1 -1
- package/dist/optim/adamw.d.ts +26 -1
- package/dist/optim/adamw.d.ts.map +1 -1
- package/dist/optim/adamw.js +35 -4
- package/dist/optim/adamw.js.map +1 -1
- package/dist/training/lora.d.ts +153 -0
- package/dist/training/lora.d.ts.map +1 -0
- package/dist/training/lora.js +324 -0
- package/dist/training/lora.js.map +1 -0
- package/dist/training/mixed_precision.d.ts +67 -0
- package/dist/training/mixed_precision.d.ts.map +1 -0
- package/dist/training/mixed_precision.js +101 -0
- package/dist/training/mixed_precision.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +8 -2
- package/src/lm/evermind_lm.ts +254 -110
- package/src/lm/index.ts +7 -1
- package/src/optim/adamw.ts +55 -7
- package/src/training/lora.ts +365 -0
- package/src/training/mixed_precision.ts +119 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lora.ts — Low-Rank Adaptation (LoRA) + QLoRA for the EvermindLM CPU reference.
|
|
3
|
+
*
|
|
4
|
+
* The Meta llama-cookbook's central PEFT idea: freeze the base weights and train
|
|
5
|
+
* a tiny low-rank delta ΔW = (α/r)·B·A on top. Three payoffs, all realised here:
|
|
6
|
+
*
|
|
7
|
+
* • Cheap — you train r·(rows+cols) params instead of rows·cols. For the tied
|
|
8
|
+
* embedding (vocab×dModel) at rank 8 that is orders of magnitude smaller.
|
|
9
|
+
* • Composable — the adapter serialises to a few KB (see {@link LoRAAdapter.serialize}),
|
|
10
|
+
* so a persona / tenant / project is an MB-scale artifact you swap at load
|
|
11
|
+
* time, not a full checkpoint.
|
|
12
|
+
* • Forgetting-safe — the base never moves, so an adapter cannot catastrophically
|
|
13
|
+
* overwrite the pretrained model (the exact property WSLA approximates with a
|
|
14
|
+
* trust region; LoRA gets it structurally).
|
|
15
|
+
*
|
|
16
|
+
* QLoRA adds one more: the frozen base is held QUANTIZED (fp16 or int8) and
|
|
17
|
+
* dequantized on the fly for the merged forward, while the small adapter trains
|
|
18
|
+
* in fp32. On a single constrained device (our WebGPU target) the frozen base is
|
|
19
|
+
* where most bytes live, so quantizing it is the biggest memory unlock.
|
|
20
|
+
*
|
|
21
|
+
* Pure CPU, exact gradients (finite-difference checked in tests). The WGSL path
|
|
22
|
+
* is a future acceleration with the same shapes — same contract as EvermindLM.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { AdamW, type AdamWOptions } from "../optim/adamw.js";
|
|
26
|
+
import { SeededRng } from "../utils/rng.js";
|
|
27
|
+
import {
|
|
28
|
+
quantizeFp16,
|
|
29
|
+
dequantizeFp16,
|
|
30
|
+
quantizeInt8,
|
|
31
|
+
dequantizeInt8,
|
|
32
|
+
} from "../utils/quantization.js";
|
|
33
|
+
|
|
34
|
+
/** How the frozen base matrix is stored. `none` = fp32 (plain LoRA); the others = QLoRA. */
|
|
35
|
+
export type BaseQuant = "none" | "fp16" | "int8";
|
|
36
|
+
|
|
37
|
+
export interface LoRAConfig {
|
|
38
|
+
/** Low-rank bottleneck. Higher = more capacity, larger adapter. Default 8. */
|
|
39
|
+
rank?: number;
|
|
40
|
+
/** LoRA scaling; the delta is scaled by alpha/rank. Default = rank (unit scale). */
|
|
41
|
+
alpha?: number;
|
|
42
|
+
/** Deterministic init seed for the A matrix. */
|
|
43
|
+
seed?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const ADAPTER_MAGIC = 0x4c4f5241; // "LORA"
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A low-rank adapter over one base matrix of shape [rows × cols] (row-major).
|
|
50
|
+
*
|
|
51
|
+
* ΔW[i,j] = (α/r) · Σ_k B[i,k]·A[k,j] B: [rows×r] A: [r×cols]
|
|
52
|
+
*
|
|
53
|
+
* Standard LoRA init: A ~ N(0, σ²), B = 0, so ΔW starts at exactly zero and the
|
|
54
|
+
* adapted model equals the base until training moves it. Only A and B are
|
|
55
|
+
* trainable ({@link parameters}/{@link gradients} expose them to {@link AdamW});
|
|
56
|
+
* the base is supplied by the caller and never mutated here.
|
|
57
|
+
*/
|
|
58
|
+
export class LoRAAdapter {
|
|
59
|
+
readonly rows: number;
|
|
60
|
+
readonly cols: number;
|
|
61
|
+
readonly rank: number;
|
|
62
|
+
readonly alpha: number;
|
|
63
|
+
readonly scale: number;
|
|
64
|
+
/** [rows × rank], zero-initialised. */
|
|
65
|
+
readonly B: Float32Array;
|
|
66
|
+
/** [rank × cols], gaussian-initialised. */
|
|
67
|
+
readonly A: Float32Array;
|
|
68
|
+
private readonly gB: Float32Array;
|
|
69
|
+
private readonly gA: Float32Array;
|
|
70
|
+
|
|
71
|
+
constructor(rows: number, cols: number, config: LoRAConfig = {}) {
|
|
72
|
+
if (rows <= 0 || cols <= 0) throw new Error("LoRAAdapter: rows and cols must be > 0");
|
|
73
|
+
const rank = config.rank ?? 8;
|
|
74
|
+
if (rank <= 0 || rank > Math.min(rows, cols)) {
|
|
75
|
+
throw new Error(`LoRAAdapter: rank must be in [1, min(rows,cols)=${Math.min(rows, cols)}]`);
|
|
76
|
+
}
|
|
77
|
+
this.rows = rows;
|
|
78
|
+
this.cols = cols;
|
|
79
|
+
this.rank = rank;
|
|
80
|
+
this.alpha = config.alpha ?? rank;
|
|
81
|
+
this.scale = this.alpha / rank;
|
|
82
|
+
|
|
83
|
+
this.B = new Float32Array(rows * rank); // zero-init ⇒ ΔW starts at 0
|
|
84
|
+
this.A = new Float32Array(rank * cols);
|
|
85
|
+
const rng = new SeededRng((config.seed ?? 0x4c6f5241) >>> 0 || 1);
|
|
86
|
+
// Kaiming-ish small init for A (std ~ 1/sqrt(cols)).
|
|
87
|
+
const std = 1 / Math.sqrt(cols);
|
|
88
|
+
for (let i = 0; i < this.A.length; i++) {
|
|
89
|
+
const u1 = Math.max(rng.next(), 1e-12);
|
|
90
|
+
const u2 = rng.next();
|
|
91
|
+
this.A[i] = std * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
|
|
92
|
+
}
|
|
93
|
+
this.gB = new Float32Array(this.B.length);
|
|
94
|
+
this.gA = new Float32Array(this.A.length);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Trainable count — the LoRA saving vs a full rows·cols matrix. */
|
|
98
|
+
numParams(): number {
|
|
99
|
+
return this.B.length + this.A.length;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Materialise ΔW = scale·B·A as a flat [rows·cols] row-major array. */
|
|
103
|
+
delta(): Float32Array {
|
|
104
|
+
const { rows, cols, rank, scale } = this;
|
|
105
|
+
const out = new Float32Array(rows * cols);
|
|
106
|
+
for (let i = 0; i < rows; i++) {
|
|
107
|
+
const bOff = i * rank;
|
|
108
|
+
const oOff = i * cols;
|
|
109
|
+
for (let k = 0; k < rank; k++) {
|
|
110
|
+
const b = this.B[bOff + k]! * scale;
|
|
111
|
+
if (b === 0) continue;
|
|
112
|
+
const aOff = k * cols;
|
|
113
|
+
for (let j = 0; j < cols; j++) out[oOff + j] = out[oOff + j]! + b * this.A[aOff + j]!;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Base + ΔW (new array; `base` is not mutated). */
|
|
120
|
+
applyTo(base: Float32Array): Float32Array {
|
|
121
|
+
if (base.length !== this.rows * this.cols) {
|
|
122
|
+
throw new Error("LoRAAdapter.applyTo: base length mismatch");
|
|
123
|
+
}
|
|
124
|
+
const d = this.delta();
|
|
125
|
+
const out = new Float32Array(base.length);
|
|
126
|
+
for (let i = 0; i < out.length; i++) out[i] = base[i]! + d[i]!;
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Project dL/dW (flat [rows·cols], the gradient the base matrix WOULD receive)
|
|
132
|
+
* onto the adapter, accumulating dL/dA and dL/dB. Exact chain rule for
|
|
133
|
+
* ΔW = scale·B·A: gA = scale·Bᵀ·G, gB = scale·G·Aᵀ.
|
|
134
|
+
*/
|
|
135
|
+
accumulateGradient(gW: Float32Array): void {
|
|
136
|
+
const { rows, cols, rank, scale } = this;
|
|
137
|
+
if (gW.length !== rows * cols) throw new Error("LoRAAdapter.accumulateGradient: gW length mismatch");
|
|
138
|
+
for (let i = 0; i < rows; i++) {
|
|
139
|
+
const gOff = i * cols;
|
|
140
|
+
const bOff = i * rank;
|
|
141
|
+
for (let k = 0; k < rank; k++) {
|
|
142
|
+
const aOff = k * cols;
|
|
143
|
+
let gb = 0;
|
|
144
|
+
const bScaled = this.B[bOff + k]! * scale;
|
|
145
|
+
for (let j = 0; j < cols; j++) {
|
|
146
|
+
const g = gW[gOff + j]!;
|
|
147
|
+
gb += g * this.A[aOff + j]!; // gB[i,k] = scale·Σ_j G[i,j]·A[k,j]
|
|
148
|
+
this.gA[aOff + j] = this.gA[aOff + j]! + bScaled * g; // gA[k,j] += scale·B[i,k]·G[i,j]
|
|
149
|
+
}
|
|
150
|
+
this.gB[bOff + k] = this.gB[bOff + k]! + scale * gb;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// AdamW OptimTarget surface — trains ONLY the adapter.
|
|
156
|
+
parameters(): { data: Float32Array }[] {
|
|
157
|
+
return [{ data: this.B }, { data: this.A }];
|
|
158
|
+
}
|
|
159
|
+
gradients(): { data: Float32Array }[] {
|
|
160
|
+
return [{ data: this.gB }, { data: this.gA }];
|
|
161
|
+
}
|
|
162
|
+
zeroGrad(): void {
|
|
163
|
+
this.gB.fill(0);
|
|
164
|
+
this.gA.fill(0);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Compact self-describing adapter blob (magic, rows, cols, rank, alpha, B, A). */
|
|
168
|
+
serialize(): ArrayBuffer {
|
|
169
|
+
const headerEls = 5;
|
|
170
|
+
const headerBytes = headerEls * 4;
|
|
171
|
+
const buf = new ArrayBuffer(headerBytes + (this.B.length + this.A.length) * 4);
|
|
172
|
+
const head = new Uint32Array(buf, 0, headerEls);
|
|
173
|
+
head[0] = ADAPTER_MAGIC;
|
|
174
|
+
head[1] = this.rows;
|
|
175
|
+
head[2] = this.cols;
|
|
176
|
+
head[3] = this.rank;
|
|
177
|
+
new Float32Array(buf, 16, 1)[0] = this.alpha;
|
|
178
|
+
const body = new Float32Array(buf, headerBytes);
|
|
179
|
+
body.set(this.B, 0);
|
|
180
|
+
body.set(this.A, this.B.length);
|
|
181
|
+
return buf;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
static deserialize(buffer: ArrayBuffer): LoRAAdapter {
|
|
185
|
+
const head = new Uint32Array(buffer, 0, 5);
|
|
186
|
+
if (head[0] !== ADAPTER_MAGIC) throw new Error("LoRAAdapter.deserialize: bad magic");
|
|
187
|
+
const rows = head[1]!;
|
|
188
|
+
const cols = head[2]!;
|
|
189
|
+
const rank = head[3]!;
|
|
190
|
+
const alpha = new Float32Array(buffer, 16, 1)[0]!;
|
|
191
|
+
const adapter = new LoRAAdapter(rows, cols, { rank, alpha });
|
|
192
|
+
const body = new Float32Array(buffer, 20);
|
|
193
|
+
adapter.B.set(body.subarray(0, adapter.B.length));
|
|
194
|
+
adapter.A.set(body.subarray(adapter.B.length, adapter.B.length + adapter.A.length));
|
|
195
|
+
return adapter;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Quantize a base matrix for QLoRA storage; returns a dequantized view + byte cost. */
|
|
200
|
+
export function quantizeBase(base: Float32Array, mode: BaseQuant): { view: Float32Array; bytes: number } {
|
|
201
|
+
switch (mode) {
|
|
202
|
+
case "none":
|
|
203
|
+
return { view: base, bytes: base.length * 4 };
|
|
204
|
+
case "fp16": {
|
|
205
|
+
const q = quantizeFp16(base);
|
|
206
|
+
return { view: dequantizeFp16(q), bytes: q.length * 2 };
|
|
207
|
+
}
|
|
208
|
+
case "int8": {
|
|
209
|
+
const q = quantizeInt8(base);
|
|
210
|
+
return { view: dequantizeInt8(q.data, q.scale), bytes: q.data.length + 4 };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
import { EvermindLM } from "../lm/evermind_lm.js";
|
|
216
|
+
|
|
217
|
+
export interface LoRAFitOptions extends AdamWOptions {
|
|
218
|
+
epochs?: number;
|
|
219
|
+
/**
|
|
220
|
+
* Gradient accumulation: average the adapter gradient over this many sequences
|
|
221
|
+
* (micro-batches) before each optimiser step. Lets a memory-constrained device
|
|
222
|
+
* train at a larger *effective* batch. Default 1 (step per sequence).
|
|
223
|
+
*/
|
|
224
|
+
accumSteps?: number;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* LoRA / QLoRA fine-tuning of an {@link EvermindLM} through its tied token
|
|
229
|
+
* embedding — the dominant parameter (vocab×dModel) and the natural adapter
|
|
230
|
+
* target (input lookup and output head share it). The base model is frozen; only
|
|
231
|
+
* the {@link LoRAAdapter} trains.
|
|
232
|
+
*
|
|
233
|
+
* QLoRA: pass `baseQuant: "fp16" | "int8"` and the frozen base is stored
|
|
234
|
+
* quantized and dequantized on the fly for the merged forward, so the resident
|
|
235
|
+
* base costs half (fp16) or a quarter (int8) of the bytes while the adapter
|
|
236
|
+
* trains full-precision.
|
|
237
|
+
*
|
|
238
|
+
* The adapter is the shippable artifact: {@link serializeAdapter} emits a few KB
|
|
239
|
+
* you swap per persona/tenant/project, versus rewriting the whole checkpoint.
|
|
240
|
+
*/
|
|
241
|
+
export class EvermindLMLoRA {
|
|
242
|
+
readonly adapter: LoRAAdapter;
|
|
243
|
+
readonly baseQuant: BaseQuant;
|
|
244
|
+
/** Frozen base embedding as used in the merged forward (dequantized under QLoRA). */
|
|
245
|
+
private readonly frozenBase: Float32Array;
|
|
246
|
+
private readonly baseBytesStored: number;
|
|
247
|
+
private readonly rows: number;
|
|
248
|
+
private readonly cols: number;
|
|
249
|
+
|
|
250
|
+
constructor(
|
|
251
|
+
private readonly model: EvermindLM,
|
|
252
|
+
config: LoRAConfig & { baseQuant?: BaseQuant } = {},
|
|
253
|
+
) {
|
|
254
|
+
this.rows = model.config.vocabSize;
|
|
255
|
+
this.cols = model.config.dModel;
|
|
256
|
+
this.baseQuant = config.baseQuant ?? "none";
|
|
257
|
+
const { view, bytes } = quantizeBase(Float32Array.from(model.emb), this.baseQuant);
|
|
258
|
+
this.frozenBase = view;
|
|
259
|
+
this.baseBytesStored = bytes;
|
|
260
|
+
this.adapter = new LoRAAdapter(this.rows, this.cols, config);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The frozen base model this adapter rides on. */
|
|
264
|
+
get baseModel(): EvermindLM {
|
|
265
|
+
return this.model;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Effective embedding used for training/generation: frozenBase + adapter delta. */
|
|
269
|
+
mergedEmb(): Float32Array {
|
|
270
|
+
return this.adapter.applyTo(this.frozenBase);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* One forward+backward on the merged weights, projecting the base-embedding
|
|
275
|
+
* gradient onto the adapter. The underlying model's own weights are left
|
|
276
|
+
* exactly as they were (base frozen); adapter gradients ACCUMULATE (caller
|
|
277
|
+
* zeroes between optimiser windows).
|
|
278
|
+
*/
|
|
279
|
+
private _accumulate(seq: number[]): number {
|
|
280
|
+
const merged = this.mergedEmb();
|
|
281
|
+
const saved = this.model.emb;
|
|
282
|
+
this.model.emb = merged; // swap in effective weights (tied lookup + head)
|
|
283
|
+
this.model.zeroGrad();
|
|
284
|
+
const loss = this.model.lossAndBackward(seq);
|
|
285
|
+
const gW = this.model.gradients()[0]!.data; // dL/dW_eff == dL/dΔW, shape [rows×cols]
|
|
286
|
+
this.adapter.accumulateGradient(gW);
|
|
287
|
+
this.model.emb = saved; // restore the frozen base
|
|
288
|
+
return loss;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Train the adapter (only) with AdamW + optional gradient accumulation. */
|
|
292
|
+
fit(sequences: number[][], opts: LoRAFitOptions = {}): number[] {
|
|
293
|
+
const epochs = opts.epochs ?? 1;
|
|
294
|
+
const accum = Math.max(1, opts.accumSteps ?? 1);
|
|
295
|
+
const adam = new AdamW(this.adapter, opts);
|
|
296
|
+
const grads = this.adapter.gradients();
|
|
297
|
+
const history: number[] = [];
|
|
298
|
+
for (let e = 0; e < epochs; e++) {
|
|
299
|
+
let total = 0;
|
|
300
|
+
let n = 0;
|
|
301
|
+
let pending = 0;
|
|
302
|
+
this.adapter.zeroGrad();
|
|
303
|
+
const flush = () => {
|
|
304
|
+
if (pending === 0) return;
|
|
305
|
+
if (pending !== 1) for (const g of grads) for (let i = 0; i < g.data.length; i++) g.data[i] = g.data[i]! / pending;
|
|
306
|
+
adam.step();
|
|
307
|
+
this.adapter.zeroGrad();
|
|
308
|
+
pending = 0;
|
|
309
|
+
};
|
|
310
|
+
for (const seq of sequences) {
|
|
311
|
+
if (seq.length < 2) continue;
|
|
312
|
+
total += this._accumulate(seq);
|
|
313
|
+
n++;
|
|
314
|
+
if (++pending >= accum) flush();
|
|
315
|
+
}
|
|
316
|
+
flush();
|
|
317
|
+
history.push(n > 0 ? total / n : 0);
|
|
318
|
+
}
|
|
319
|
+
return history;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
generate(prompt: number[], opts: import("../lm/evermind_lm.js").LMGenerateOptions): number[] {
|
|
323
|
+
const saved = this.model.emb;
|
|
324
|
+
this.model.emb = this.mergedEmb();
|
|
325
|
+
try {
|
|
326
|
+
return this.model.generate(prompt, opts);
|
|
327
|
+
} finally {
|
|
328
|
+
this.model.emb = saved;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
generateText(prompt: string, codec: import("../lm/evermind_lm.js").TextCodec, opts: import("../lm/evermind_lm.js").LMGenerateOptions): string {
|
|
333
|
+
return codec.decode(this.generate(codec.encode(prompt), opts));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The shippable adapter artifact (a few KB). */
|
|
337
|
+
serializeAdapter(): ArrayBuffer {
|
|
338
|
+
return this.adapter.serialize();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Reconstruct a fine-tuned model from a base model + a serialized adapter. */
|
|
342
|
+
static loadAdapter(model: EvermindLM, adapterBuffer: ArrayBuffer, baseQuant: BaseQuant = "none"): EvermindLMLoRA {
|
|
343
|
+
const loaded = LoRAAdapter.deserialize(adapterBuffer);
|
|
344
|
+
const wrap = new EvermindLMLoRA(model, { rank: loaded.rank, alpha: loaded.alpha, baseQuant });
|
|
345
|
+
wrap.adapter.B.set(loaded.B);
|
|
346
|
+
wrap.adapter.A.set(loaded.A);
|
|
347
|
+
return wrap;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Bake the adapter into the base and return a standalone EVL0 checkpoint. */
|
|
351
|
+
merge(opts: { fp16?: boolean } = {}): ArrayBuffer {
|
|
352
|
+
this.model.emb.set(this.mergedEmb());
|
|
353
|
+
return this.model.exportWeights(opts);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Byte cost of the trainable adapter vs the frozen base — the LoRA/QLoRA saving. */
|
|
357
|
+
footprint(): { adapterBytes: number; baseBytes: number; trainableParams: number; baseParams: number } {
|
|
358
|
+
return {
|
|
359
|
+
adapterBytes: this.adapter.serialize().byteLength,
|
|
360
|
+
baseBytes: this.baseBytesStored,
|
|
361
|
+
trainableParams: this.adapter.numParams(),
|
|
362
|
+
baseParams: this.rows * this.cols,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mixed_precision.ts — mixed-precision training discipline (AMP) for the CPU
|
|
3
|
+
* reference, faithful to the cookbook's recipe:
|
|
4
|
+
*
|
|
5
|
+
* • fp16 compute, fp32 MASTER weights. The model's Float32Array params ARE the
|
|
6
|
+
* master copy; the forward runs on an fp16-rounded view, so tiny weight
|
|
7
|
+
* updates still accumulate in fp32 instead of vanishing.
|
|
8
|
+
* • Dynamic LOSS SCALING. fp16 gradients underflow to zero below ~6e-5; scaling
|
|
9
|
+
* the loss by a large factor S lifts them into fp16 range, then we unscale by
|
|
10
|
+
* S before the optimiser step. On overflow (inf/nan) we skip the step and back
|
|
11
|
+
* the scale off; after a clean streak we grow it. This is the mechanism that
|
|
12
|
+
* makes fp16 training numerically stable.
|
|
13
|
+
*
|
|
14
|
+
* The payoff is memory/throughput: activations and gradients at half precision.
|
|
15
|
+
* On CPU we can't reclaim the bytes, so this module models the NUMERICS exactly
|
|
16
|
+
* (fp16 rounding + loss scaling) — the property the WGSL path will inherit — and
|
|
17
|
+
* its tests prove a small gradient survives WITH scaling and underflows WITHOUT.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { floatToFp16, fp16ToFloat } from "../utils/quantization.js";
|
|
21
|
+
|
|
22
|
+
/** Round a value to what fp16 storage would preserve (half-precision simulation). */
|
|
23
|
+
export function roundFp16(x: number): number {
|
|
24
|
+
return fp16ToFloat(floatToFp16(x));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Round every element of a copy to fp16 precision (leaves the input untouched). */
|
|
28
|
+
export function fp16View(a: Float32Array): Float32Array {
|
|
29
|
+
const out = new Float32Array(a.length);
|
|
30
|
+
for (let i = 0; i < a.length; i++) out[i] = roundFp16(a[i]!);
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface LossScalerOptions {
|
|
35
|
+
/** Initial scale. Default 2^14 = 16384. */
|
|
36
|
+
initScale?: number;
|
|
37
|
+
/** Multiply the scale by this after `growthInterval` clean steps. Default 2. */
|
|
38
|
+
growthFactor?: number;
|
|
39
|
+
/** Multiply the scale by this on overflow. Default 0.5. */
|
|
40
|
+
backoffFactor?: number;
|
|
41
|
+
/** Clean steps between growth attempts. Default 200. */
|
|
42
|
+
growthInterval?: number;
|
|
43
|
+
/** Floor for the scale so it can't collapse to zero. Default 1. */
|
|
44
|
+
minScale?: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Dynamic loss scaler — the standard AMP controller. Scale the loss/grads up
|
|
49
|
+
* before backward, {@link check} them for overflow, {@link unscale} the good ones,
|
|
50
|
+
* and {@link update} the scale based on whether this step overflowed.
|
|
51
|
+
*/
|
|
52
|
+
export class DynamicLossScaler {
|
|
53
|
+
private _scale: number;
|
|
54
|
+
private readonly growthFactor: number;
|
|
55
|
+
private readonly backoffFactor: number;
|
|
56
|
+
private readonly growthInterval: number;
|
|
57
|
+
private readonly minScale: number;
|
|
58
|
+
private cleanStreak = 0;
|
|
59
|
+
private _overflows = 0;
|
|
60
|
+
private _skipped = 0;
|
|
61
|
+
|
|
62
|
+
constructor(opts: LossScalerOptions = {}) {
|
|
63
|
+
this._scale = opts.initScale ?? 16384;
|
|
64
|
+
this.growthFactor = opts.growthFactor ?? 2;
|
|
65
|
+
this.backoffFactor = opts.backoffFactor ?? 0.5;
|
|
66
|
+
this.growthInterval = opts.growthInterval ?? 200;
|
|
67
|
+
this.minScale = opts.minScale ?? 1;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
get scale(): number {
|
|
71
|
+
return this._scale;
|
|
72
|
+
}
|
|
73
|
+
get overflows(): number {
|
|
74
|
+
return this._overflows;
|
|
75
|
+
}
|
|
76
|
+
get skipped(): number {
|
|
77
|
+
return this._skipped;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** True if any gradient is inf/nan (an fp16 overflow) — such a step must be skipped. */
|
|
81
|
+
check(grads: { data: Float32Array }[]): boolean {
|
|
82
|
+
for (const g of grads) {
|
|
83
|
+
const a = g.data;
|
|
84
|
+
for (let i = 0; i < a.length; i++) {
|
|
85
|
+
const x = a[i]!;
|
|
86
|
+
if (!Number.isFinite(x)) return true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Divide gradients back down by the current scale, in place. */
|
|
93
|
+
unscale(grads: { data: Float32Array }[]): void {
|
|
94
|
+
const inv = 1 / this._scale;
|
|
95
|
+
for (const g of grads) {
|
|
96
|
+
const a = g.data;
|
|
97
|
+
for (let i = 0; i < a.length; i++) a[i] = a[i]! * inv;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Advance the scale controller. Pass whether this step overflowed. Returns
|
|
103
|
+
* `true` if the optimiser step should PROCEED, `false` if it must be skipped.
|
|
104
|
+
*/
|
|
105
|
+
update(overflow: boolean): boolean {
|
|
106
|
+
if (overflow) {
|
|
107
|
+
this._overflows++;
|
|
108
|
+
this._skipped++;
|
|
109
|
+
this._scale = Math.max(this.minScale, this._scale * this.backoffFactor);
|
|
110
|
+
this.cleanStreak = 0;
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
if (++this.cleanStreak >= this.growthInterval) {
|
|
114
|
+
this._scale *= this.growthFactor;
|
|
115
|
+
this.cleanStreak = 0;
|
|
116
|
+
}
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
}
|