taskforce-model-foundry 0.0.0-stage → 0.1.0

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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  5. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  6. package/docs/integration.md +227 -0
  7. package/docs/tutorial.md +336 -0
  8. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  9. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  11. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  12. package/integrations/openclaw-plugin/index.mjs +27 -0
  13. package/integrations/openclaw-plugin/tools.mjs +70 -0
  14. package/openclaw.plugin.json +24 -0
  15. package/package.json +70 -4
  16. package/scripts/e2e-demo.sh +56 -0
  17. package/src/api.mjs +341 -0
  18. package/src/config.mjs +342 -0
  19. package/src/core/autograd.mjs +451 -0
  20. package/src/core/fsx.mjs +65 -0
  21. package/src/core/hash.mjs +47 -0
  22. package/src/core/rng.mjs +70 -0
  23. package/src/data/clean.mjs +115 -0
  24. package/src/data/dedupe.mjs +125 -0
  25. package/src/data/ingest.mjs +184 -0
  26. package/src/data/pii.mjs +142 -0
  27. package/src/data/pipeline.mjs +183 -0
  28. package/src/data/provenance.mjs +88 -0
  29. package/src/data/split.mjs +193 -0
  30. package/src/data/synth.mjs +198 -0
  31. package/src/eval/evaluator.mjs +124 -0
  32. package/src/eval/gates.mjs +114 -0
  33. package/src/eval/metrics.mjs +90 -0
  34. package/src/export/package.mjs +365 -0
  35. package/src/index.mjs +26 -0
  36. package/src/integrations/hermes.mjs +177 -0
  37. package/src/integrations/openclaw.mjs +154 -0
  38. package/src/jobs/evaluate.mjs +164 -0
  39. package/src/jobs/runner.mjs +323 -0
  40. package/src/jobs/train.mjs +303 -0
  41. package/src/model/lora.mjs +53 -0
  42. package/src/model/tokenizer.mjs +73 -0
  43. package/src/model/transformer.mjs +276 -0
  44. package/src/train/backends/builtin-js.mjs +367 -0
  45. package/src/train/backends/hf-peft.mjs +549 -0
  46. package/src/train/backends/hf_peft_runner.py +326 -0
  47. package/src/train/backends/index.mjs +92 -0
  48. package/src/train/dataset.mjs +56 -0
  49. package/src/train/optimizer.mjs +99 -0
  50. package/src/version.mjs +5 -0
@@ -0,0 +1,303 @@
1
+ // Training job: data preparation, base checkpoint, and post-training run as
2
+ // one auditable job.
3
+ //
4
+ // The point of routing training through `runJob` is that the operator gets the
5
+ // same guarantees as every other foundry job -- durable state, a reviewable
6
+ // audit log, resume at step granularity, cooperative cancellation and hard
7
+ // budget caps -- without the training code having to re-implement any of it.
8
+ //
9
+ // Each step persists its real artifacts to disk and returns only small
10
+ // references (paths, digests, counts). That is deliberate: a resumed attempt
11
+ // reloads from those artifacts instead of trusting in-memory trainer state,
12
+ // so "resume" is the same code path as "load a checkpoint someone else wrote".
13
+
14
+ import path from 'node:path';
15
+ import { runJob, JobCancelledError } from './runner.mjs';
16
+ import { runDataPipeline } from '../data/pipeline.mjs';
17
+ import { buildTokenizer, encodeRecords } from '../train/dataset.mjs';
18
+ import { ensureDir, readJsonl, writeJson } from '../core/fsx.mjs';
19
+ import { sha256Json } from '../core/hash.mjs';
20
+
21
+ export const TRAIN_JOB_KIND = 'train';
22
+
23
+ export const DEFAULT_TRAIN_JOB_OPTIONS = {
24
+ mode: 'lora',
25
+ seed: 'tmf-train',
26
+ maxVocab: 256,
27
+ maxSeqLen: 96,
28
+ };
29
+
30
+ function splitFile(dataDir, name) {
31
+ return path.join(dataDir, `${name}.jsonl`);
32
+ }
33
+
34
+ // Charging tokens as they are actually consumed is what makes `maxTokens` a
35
+ // real cap: the throw lands inside the training loop and the runner records
36
+ // state=budget_exceeded instead of discovering the overspend afterwards.
37
+ function makeStepHook({ signal, audit, budget, auditEveryStep }) {
38
+ let lastCharged = 0;
39
+ return async (entry) => {
40
+ if (signal?.aborted) throw new JobCancelledError('cancelled during training step');
41
+ const delta = Math.max(0, entry.tokens - lastCharged);
42
+ lastCharged = entry.tokens;
43
+ budget.charge({ tokens: delta });
44
+ if (auditEveryStep > 0 && entry.step % auditEveryStep === 0) {
45
+ await audit('train.step', { step: entry.step, loss: entry.loss, lr: entry.lr, tokens: entry.tokens });
46
+ }
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Run a full data -> base -> post-training job under the auditable runner.
52
+ *
53
+ * Returns the runner's job record; `result` holds the artifact references the
54
+ * evaluation and export jobs consume (data report, base checkpoint, adapter
55
+ * or tuned checkpoint, and the real training metrics).
56
+ */
57
+ export async function runTrainingJob({
58
+ jobId,
59
+ root,
60
+ backend,
61
+ datasets,
62
+ baseDir = process.cwd(),
63
+ dataConfig = {},
64
+ modelConfig = {},
65
+ hyper = {},
66
+ trainBudget = {},
67
+ mode = DEFAULT_TRAIN_JOB_OPTIONS.mode,
68
+ seed = DEFAULT_TRAIN_JOB_OPTIONS.seed,
69
+ maxVocab = DEFAULT_TRAIN_JOB_OPTIONS.maxVocab,
70
+ maxSeqLen = DEFAULT_TRAIN_JOB_OPTIONS.maxSeqLen,
71
+ budget = {},
72
+ signal = null,
73
+ auditEveryStep = 1,
74
+ resume = true,
75
+ resumeCancelled = false,
76
+ now = () => Date.now(),
77
+ } = {}) {
78
+ if (!jobId) throw new Error('runTrainingJob requires jobId');
79
+ if (!root) throw new Error('runTrainingJob requires root');
80
+ if (!backend) throw new Error('runTrainingJob requires a backend');
81
+ if (!Array.isArray(datasets) || datasets.length === 0) {
82
+ throw new Error('runTrainingJob requires at least one dataset');
83
+ }
84
+ if (!backend.capabilities?.modes?.includes(mode)) {
85
+ throw new Error(`backend "${backend.id}" does not support mode "${mode}"`);
86
+ }
87
+
88
+ // Artifacts live in the same directory the runner uses for this job's state
89
+ // and audit log, so one directory is the whole durable record of the job.
90
+ const jobDir = path.join(root, jobId);
91
+ const dataDir = path.join(jobDir, 'data');
92
+ const modelDir = path.join(jobDir, 'model');
93
+
94
+ // The input digest binds this jobId to its configuration: the runner refuses
95
+ // to resume a job whose inputs changed, which is what stops a "resume" from
96
+ // silently becoming a different experiment.
97
+ const input = {
98
+ kind: TRAIN_JOB_KIND,
99
+ backend: backend.id,
100
+ datasets: datasets.map((d) => ({ name: d.name, path: d.path, format: d.format ?? null })),
101
+ dataConfig,
102
+ modelConfig,
103
+ hyper,
104
+ trainBudget,
105
+ mode,
106
+ seed,
107
+ maxVocab,
108
+ maxSeqLen,
109
+ };
110
+
111
+ const steps = [
112
+ {
113
+ name: 'data',
114
+ run: async ({ audit }) => {
115
+ await ensureDir(dataDir);
116
+ const { report, splits, provenance } = await runDataPipeline({
117
+ datasets,
118
+ outDir: dataDir,
119
+ baseDir,
120
+ config: dataConfig,
121
+ });
122
+ const reportFile = path.join(dataDir, 'data-report.json');
123
+ await writeJson(reportFile, { report, provenance });
124
+ await audit('data.prepared', {
125
+ splits: Object.fromEntries(Object.entries(splits).map(([k, v]) => [k, v.length])),
126
+ accepted: report.accepted ?? null,
127
+ });
128
+ return {
129
+ dataDir,
130
+ reportFile,
131
+ reportDigest: sha256Json(report),
132
+ splits: Object.fromEntries(Object.entries(splits).map(([k, v]) => [k, v.length])),
133
+ };
134
+ },
135
+ },
136
+ {
137
+ name: 'base',
138
+ run: async ({ outputs, audit }) => {
139
+ const trainRecords = await readJsonl(splitFile(outputs.data.dataDir, 'train'));
140
+ if (trainRecords.length === 0) throw new Error('data step produced an empty train split');
141
+ // Tokenizer ownership is a backend capability, not a job assumption: a
142
+ // backend whose model carries its own tokenizer (hf-peft) must not be
143
+ // handed a vocabulary built from this split, because ids from a JS
144
+ // vocabulary mean nothing to that model's embedding table.
145
+ const ownsTokenizer = backend.capabilities?.ownsTokenizer === true;
146
+ const tokenizer = ownsTokenizer ? null : buildTokenizer(trainRecords, { maxVocab });
147
+ const handle = await backend.createModel({
148
+ modelConfig,
149
+ tokenizer,
150
+ seed: 1,
151
+ modelId: modelConfig.modelId ?? modelConfig.baseModel ?? null,
152
+ outDir: modelDir,
153
+ });
154
+ const file = path.join(modelDir, 'base.json');
155
+ const saved = await backend.saveModel({
156
+ handle,
157
+ file,
158
+ kind: 'base',
159
+ meta: { jobId, dataReportDigest: outputs.data.reportDigest },
160
+ });
161
+ const fingerprint = backend.fingerprint(handle);
162
+ const vocabSize = tokenizer ? tokenizer.size : null;
163
+ await audit('base.saved', {
164
+ file: saved.file,
165
+ sha256: saved.sha256,
166
+ vocabSize,
167
+ tokenizerOwner: ownsTokenizer ? 'backend' : 'job',
168
+ fingerprint,
169
+ });
170
+ return { file: saved.file, sha256: saved.sha256, fingerprint, vocabSize, tokenizerOwner: ownsTokenizer ? 'backend' : 'job' };
171
+ },
172
+ },
173
+ {
174
+ name: 'train',
175
+ run: async ({ outputs, audit, budget: jobBudget }) => {
176
+ const trainRecords = await readJsonl(splitFile(outputs.data.dataDir, 'train'));
177
+ // Reloading the base from disk (rather than reusing the handle built in
178
+ // the previous step) is what makes a resumed attempt equivalent to a
179
+ // fresh process picking the job up.
180
+ const handle = await backend.loadModel({ file: outputs.base.file });
181
+ // One call for both backends: prepareDataset() is the single place that
182
+ // knows whether ids come from a job-built vocabulary or from the
183
+ // model's own tokenizer. The fallback keeps older backends working.
184
+ const prepared = typeof backend.prepareDataset === 'function'
185
+ ? await backend.prepareDataset({ handle, records: trainRecords, maxSeqLen, outDir: modelDir })
186
+ : { ...encodeRecords(trainRecords, handle.tokenizer, { maxSeqLen }), tokens: null, tokenizer: 'job-built' };
187
+ const examples = prepared.examples ?? [];
188
+ const skipped = prepared.skipped ?? [];
189
+ if (examples.length === 0) throw new Error('no train examples survived encoding');
190
+ const beforeFingerprint = backend.fingerprint(handle);
191
+ await audit('train.started', {
192
+ mode,
193
+ examples: examples.length,
194
+ skipped: skipped.length,
195
+ tokens: prepared.tokens ?? null,
196
+ tokenizer: prepared.tokenizer ?? 'job-built',
197
+ baseFingerprint: beforeFingerprint,
198
+ });
199
+
200
+ const trained = await backend.train({
201
+ handle,
202
+ examples,
203
+ examplesFile: prepared.examplesFile ?? null,
204
+ mode,
205
+ hyper,
206
+ budget: trainBudget,
207
+ seed,
208
+ outDir: modelDir,
209
+ signal,
210
+ resume: null,
211
+ hooks: { onStep: makeStepHook({ signal, audit, budget: jobBudget, auditEveryStep }) },
212
+ });
213
+ const { metrics, history, stopReason } = trained;
214
+ // A backend may return a moved handle (hf-peft points it at the adapter
215
+ // directory the worker just wrote); saving the pre-train handle would
216
+ // persist a checkpoint that does not reference the trained weights.
217
+ const trainedHandle = trained.handle ?? handle;
218
+
219
+ const historyFile = path.join(modelDir, 'train-history.json');
220
+ await writeJson(historyFile, { jobId, mode, metrics, history });
221
+ const isAdapter = mode === 'lora';
222
+ const file = path.join(modelDir, isAdapter ? 'adapter.json' : 'tuned.json');
223
+ const saved = await backend.saveModel({
224
+ handle: trainedHandle,
225
+ file,
226
+ kind: isAdapter ? 'adapter' : 'base',
227
+ meta: {
228
+ jobId,
229
+ mode,
230
+ baseCheckpoint: outputs.base.file,
231
+ baseFingerprint: beforeFingerprint,
232
+ metrics,
233
+ },
234
+ });
235
+ await audit('train.finished', {
236
+ file: saved.file,
237
+ sha256: saved.sha256,
238
+ stopReason,
239
+ steps: metrics.steps,
240
+ finalLoss: metrics.finalLoss,
241
+ parameterL2Delta: metrics.parameterL2Delta,
242
+ });
243
+ if (!(metrics.parameterL2Delta > 0)) {
244
+ throw new Error('training reported zero parameter displacement; weights did not change');
245
+ }
246
+ return {
247
+ checkpoint: saved.file,
248
+ sha256: saved.sha256,
249
+ kind: saved.kind,
250
+ historyFile,
251
+ baseFingerprint: beforeFingerprint,
252
+ metrics,
253
+ stopReason,
254
+ };
255
+ },
256
+ },
257
+ {
258
+ // The runner's `result` is the last step's output, so the job ends with a
259
+ // step whose only work is to collect the artifact references and write
260
+ // them down as a manifest a downstream job can consume directly.
261
+ name: 'finalize',
262
+ run: async ({ outputs, audit }) => {
263
+ const manifest = {
264
+ jobId,
265
+ kind: TRAIN_JOB_KIND,
266
+ backend: backend.id,
267
+ mode,
268
+ data: outputs.data,
269
+ base: outputs.base,
270
+ train: outputs.train,
271
+ };
272
+ const manifestFile = path.join(jobDir, 'train-manifest.json');
273
+ await writeJson(manifestFile, manifest);
274
+ await audit('train.manifest', { manifestFile, digest: sha256Json(manifest) });
275
+ return { ...manifest, manifestFile };
276
+ },
277
+ },
278
+ ];
279
+
280
+ return runJob({ jobId, kind: TRAIN_JOB_KIND, root, steps, input, budget, signal, resume, resumeCancelled, now });
281
+ }
282
+
283
+ /**
284
+ * Artifact references a downstream evaluation or export job needs. Throws when
285
+ * the job did not actually finish, so a caller cannot mistake a cancelled or
286
+ * over-budget job for a trained model.
287
+ */
288
+ export function trainingArtifacts(job) {
289
+ if (job?.state !== 'succeeded') {
290
+ throw new Error(`training job ${job?.jobId ?? '<unknown>'} is ${job?.state ?? 'missing'}, not succeeded`);
291
+ }
292
+ const { data, base, train } = job.result ?? {};
293
+ if (!data || !base || !train) throw new Error('training job result is missing step outputs');
294
+ return {
295
+ jobId: job.jobId,
296
+ dataDir: data.dataDir,
297
+ dataReportFile: data.reportFile,
298
+ baseCheckpoint: base.file,
299
+ adapterCheckpoint: train.kind === 'adapter' ? train.checkpoint : null,
300
+ tunedCheckpoint: train.kind === 'adapter' ? null : train.checkpoint,
301
+ metrics: train.metrics,
302
+ };
303
+ }
@@ -0,0 +1,53 @@
1
+ // LoRA adapters: W_eff = W + (A @ B) * (alpha / r).
2
+ //
3
+ // B is zero-initialized so a freshly attached adapter is mathematically a no-op.
4
+ // That property is what makes "the adapter actually changed the model" testable:
5
+ // before training, base and adapted outputs must match exactly.
6
+
7
+ import { matmul, randn, scale, zeros, add } from '../core/autograd.mjs';
8
+
9
+ export class LoraLayer {
10
+ constructor(inDim, outDim, rank, alpha, rng, name) {
11
+ this.inDim = inDim;
12
+ this.outDim = outDim;
13
+ this.rank = rank;
14
+ this.alpha = alpha;
15
+ this.scaling = alpha / rank;
16
+ this.A = randn(inDim, rank, rng, 1 / Math.sqrt(inDim), { requiresGrad: true, name: `${name}.lora_A` });
17
+ this.B = zeros(rank, outDim, { requiresGrad: true, name: `${name}.lora_B` });
18
+ }
19
+
20
+ params() {
21
+ return [this.A, this.B];
22
+ }
23
+
24
+ // delta(x) = (x @ A) @ B * scaling
25
+ apply(x) {
26
+ return scale(matmul(matmul(x, this.A), this.B), this.scaling);
27
+ }
28
+
29
+ forward(x, baseOut) {
30
+ return add(baseOut, this.apply(x));
31
+ }
32
+
33
+ toJSON() {
34
+ return {
35
+ inDim: this.inDim,
36
+ outDim: this.outDim,
37
+ rank: this.rank,
38
+ alpha: this.alpha,
39
+ A: Array.from(this.A.data),
40
+ B: Array.from(this.B.data),
41
+ };
42
+ }
43
+
44
+ loadJSON(json) {
45
+ if (json.inDim !== this.inDim || json.outDim !== this.outDim || json.rank !== this.rank) {
46
+ throw new Error(`lora shape mismatch: expected ${this.inDim}x${this.rank}x${this.outDim}, got ${json.inDim}x${json.rank}x${json.outDim}`);
47
+ }
48
+ this.A.data.set(json.A);
49
+ this.B.data.set(json.B);
50
+ this.alpha = json.alpha;
51
+ this.scaling = json.alpha / json.rank;
52
+ }
53
+ }
@@ -0,0 +1,73 @@
1
+ // Character-level tokenizer with explicit control tokens.
2
+ //
3
+ // A char vocab is the right trade-off here: the foundry trains genuinely small
4
+ // models on CPU, and a learned subword vocab would add a dependency without
5
+ // changing whether the weight update is real.
6
+
7
+ export const PAD = '<pad>';
8
+ export const BOS = '<bos>';
9
+ export const EOS = '<eos>';
10
+ export const UNK = '<unk>';
11
+ export const SEP = '<sep>';
12
+ export const SPECIALS = [PAD, BOS, EOS, UNK, SEP];
13
+
14
+ export class Tokenizer {
15
+ constructor(tokens) {
16
+ this.tokens = tokens.slice();
17
+ this.index = new Map(this.tokens.map((t, i) => [t, i]));
18
+ this.padId = this.index.get(PAD);
19
+ this.bosId = this.index.get(BOS);
20
+ this.eosId = this.index.get(EOS);
21
+ this.unkId = this.index.get(UNK);
22
+ this.sepId = this.index.get(SEP);
23
+ }
24
+
25
+ get size() {
26
+ return this.tokens.length;
27
+ }
28
+
29
+ static fromTexts(texts, { maxVocab = 512 } = {}) {
30
+ const counts = new Map();
31
+ for (const text of texts) {
32
+ for (const ch of String(text)) counts.set(ch, (counts.get(ch) ?? 0) + 1);
33
+ }
34
+ // Sort by frequency then codepoint so the vocab is deterministic.
35
+ const chars = [...counts.entries()]
36
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : 1))
37
+ .map(([ch]) => ch)
38
+ .filter((ch) => !SPECIALS.includes(ch))
39
+ .slice(0, Math.max(0, maxVocab - SPECIALS.length));
40
+ return new Tokenizer([...SPECIALS, ...chars]);
41
+ }
42
+
43
+ static fromJSON(json) {
44
+ return new Tokenizer(json.tokens);
45
+ }
46
+
47
+ toJSON() {
48
+ return { kind: 'char-v1', tokens: this.tokens };
49
+ }
50
+
51
+ encode(text, { bos = false, eos = false } = {}) {
52
+ const ids = [];
53
+ if (bos) ids.push(this.bosId);
54
+ for (const ch of String(text)) ids.push(this.index.has(ch) ? this.index.get(ch) : this.unkId);
55
+ if (eos) ids.push(this.eosId);
56
+ return ids;
57
+ }
58
+
59
+ decode(ids, { skipSpecial = true } = {}) {
60
+ let out = '';
61
+ for (const id of ids) {
62
+ const tok = this.tokens[id];
63
+ if (tok === undefined) continue;
64
+ if (SPECIALS.includes(tok)) {
65
+ if (skipSpecial) continue;
66
+ out += tok;
67
+ continue;
68
+ }
69
+ out += tok;
70
+ }
71
+ return out;
72
+ }
73
+ }
@@ -0,0 +1,276 @@
1
+ // A small decoder-only transformer with real forward and backward passes.
2
+ //
3
+ // Config defaults are sized so that CPU-only training on a synthetic corpus
4
+ // finishes in seconds, which is what lets the acceptance suite exercise a
5
+ // genuine weight update instead of asserting against a recorded number.
6
+
7
+ import {
8
+ Tensor, zeros, filled, randn, matmul, matmulT, add, addRow, scale, gelu,
9
+ layerNorm, causalSoftmax, sliceCols, concatCols, embeddingLookup, crossEntropy,
10
+ } from '../core/autograd.mjs';
11
+ import { Rng } from '../core/rng.mjs';
12
+ import { LoraLayer } from './lora.mjs';
13
+
14
+ export const DEFAULT_MODEL_CONFIG = {
15
+ vocabSize: 96,
16
+ dModel: 64,
17
+ nLayers: 2,
18
+ nHeads: 4,
19
+ dFF: 128,
20
+ maxSeqLen: 96,
21
+ initStd: 0.02,
22
+ };
23
+
24
+ export const DEFAULT_LORA_CONFIG = {
25
+ rank: 4,
26
+ alpha: 8,
27
+ targets: ['attn.q', 'attn.v'],
28
+ };
29
+
30
+ class Linear {
31
+ constructor(inDim, outDim, rng, name, { bias = true, std } = {}) {
32
+ this.inDim = inDim;
33
+ this.outDim = outDim;
34
+ this.name = name;
35
+ this.weight = randn(inDim, outDim, rng, std ?? 1 / Math.sqrt(inDim), { requiresGrad: true, name: `${name}.weight` });
36
+ this.bias = bias ? zeros(1, outDim, { requiresGrad: true, name: `${name}.bias` }) : null;
37
+ this.lora = null;
38
+ }
39
+
40
+ attachLora(rank, alpha, rng) {
41
+ this.lora = new LoraLayer(this.inDim, this.outDim, rank, alpha, rng, this.name);
42
+ return this.lora;
43
+ }
44
+
45
+ params() {
46
+ return this.bias ? [this.weight, this.bias] : [this.weight];
47
+ }
48
+
49
+ forward(x) {
50
+ let out = matmul(x, this.weight);
51
+ if (this.bias) out = addRow(out, this.bias);
52
+ if (this.lora) out = this.lora.forward(x, out);
53
+ return out;
54
+ }
55
+ }
56
+
57
+ class Block {
58
+ constructor(cfg, rng, idx) {
59
+ this.cfg = cfg;
60
+ this.idx = idx;
61
+ const d = cfg.dModel;
62
+ this.ln1g = filled(1, d, 1, { requiresGrad: true, name: `block${idx}.ln1.gamma` });
63
+ this.ln1b = zeros(1, d, { requiresGrad: true, name: `block${idx}.ln1.beta` });
64
+ this.q = new Linear(d, d, rng, `block${idx}.attn.q`);
65
+ this.k = new Linear(d, d, rng, `block${idx}.attn.k`);
66
+ this.v = new Linear(d, d, rng, `block${idx}.attn.v`);
67
+ this.o = new Linear(d, d, rng, `block${idx}.attn.o`);
68
+ this.ln2g = filled(1, d, 1, { requiresGrad: true, name: `block${idx}.ln2.gamma` });
69
+ this.ln2b = zeros(1, d, { requiresGrad: true, name: `block${idx}.ln2.beta` });
70
+ this.ff1 = new Linear(d, cfg.dFF, rng, `block${idx}.ffn.in`);
71
+ this.ff2 = new Linear(cfg.dFF, d, rng, `block${idx}.ffn.out`);
72
+ }
73
+
74
+ linears() {
75
+ return { 'attn.q': this.q, 'attn.k': this.k, 'attn.v': this.v, 'attn.o': this.o, 'ffn.in': this.ff1, 'ffn.out': this.ff2 };
76
+ }
77
+
78
+ params() {
79
+ return [
80
+ this.ln1g, this.ln1b, ...this.q.params(), ...this.k.params(), ...this.v.params(), ...this.o.params(),
81
+ this.ln2g, this.ln2b, ...this.ff1.params(), ...this.ff2.params(),
82
+ ];
83
+ }
84
+
85
+ forward(x) {
86
+ const h = layerNorm(x, this.ln1g, this.ln1b);
87
+ const q = this.q.forward(h);
88
+ const k = this.k.forward(h);
89
+ const v = this.v.forward(h);
90
+ const headDim = this.cfg.dModel / this.cfg.nHeads;
91
+ const invSqrt = 1 / Math.sqrt(headDim);
92
+ const heads = [];
93
+ for (let head = 0; head < this.cfg.nHeads; head += 1) {
94
+ const start = head * headDim;
95
+ const end = start + headDim;
96
+ const qh = sliceCols(q, start, end);
97
+ const kh = sliceCols(k, start, end);
98
+ const vh = sliceCols(v, start, end);
99
+ const scores = scale(matmulT(qh, kh), invSqrt);
100
+ heads.push(matmul(causalSoftmax(scores), vh));
101
+ }
102
+ const attn = this.o.forward(this.cfg.nHeads === 1 ? heads[0] : concatCols(heads));
103
+ const res1 = add(x, attn);
104
+ const h2 = layerNorm(res1, this.ln2g, this.ln2b);
105
+ const ffn = this.ff2.forward(gelu(this.ff1.forward(h2)));
106
+ return add(res1, ffn);
107
+ }
108
+ }
109
+
110
+ export class TransformerModel {
111
+ constructor(config = {}, { seed = 1 } = {}) {
112
+ this.config = { ...DEFAULT_MODEL_CONFIG, ...config };
113
+ if (this.config.dModel % this.config.nHeads !== 0) {
114
+ throw new Error(`dModel ${this.config.dModel} must be divisible by nHeads ${this.config.nHeads}`);
115
+ }
116
+ this.seed = seed;
117
+ const rng = new Rng(seed);
118
+ const cfg = this.config;
119
+ this.tokEmb = randn(cfg.vocabSize, cfg.dModel, rng, cfg.initStd, { requiresGrad: true, name: 'tok_emb' });
120
+ this.posEmb = randn(cfg.maxSeqLen, cfg.dModel, rng, cfg.initStd, { requiresGrad: true, name: 'pos_emb' });
121
+ this.blocks = Array.from({ length: cfg.nLayers }, (_, i) => new Block(cfg, rng, i));
122
+ this.lnfg = filled(1, cfg.dModel, 1, { requiresGrad: true, name: 'ln_f.gamma' });
123
+ this.lnfb = zeros(1, cfg.dModel, { requiresGrad: true, name: 'ln_f.beta' });
124
+ this.head = new Linear(cfg.dModel, cfg.vocabSize, rng, 'lm_head');
125
+ this.loraLayers = [];
126
+ }
127
+
128
+ baseParams() {
129
+ return [
130
+ this.tokEmb, this.posEmb, ...this.blocks.flatMap((b) => b.params()),
131
+ this.lnfg, this.lnfb, ...this.head.params(),
132
+ ];
133
+ }
134
+
135
+ loraParams() {
136
+ return this.loraLayers.flatMap(({ layer }) => layer.params());
137
+ }
138
+
139
+ // Which parameters the optimizer may touch. During adapter post-training the
140
+ // base stays frozen, which also stops the engine from allocating base grads.
141
+ trainableParams({ mode = 'full' } = {}) {
142
+ if (mode === 'lora') {
143
+ if (this.loraLayers.length === 0) throw new Error('no LoRA adapter attached; call attachLora() first');
144
+ return this.loraParams();
145
+ }
146
+ return this.baseParams();
147
+ }
148
+
149
+ setBaseFrozen(frozen) {
150
+ for (const p of this.baseParams()) p.requiresGrad = !frozen;
151
+ }
152
+
153
+ attachLora(loraConfig = {}) {
154
+ const cfg = { ...DEFAULT_LORA_CONFIG, ...loraConfig };
155
+ const rng = new Rng(`${this.seed}:lora:${cfg.rank}:${cfg.alpha}`);
156
+ this.loraLayers = [];
157
+ for (const block of this.blocks) {
158
+ const linears = block.linears();
159
+ for (const target of cfg.targets) {
160
+ const linear = linears[target];
161
+ if (!linear) throw new Error(`unknown LoRA target "${target}"; valid: ${Object.keys(linears).join(', ')}`);
162
+ const layer = linear.attachLora(cfg.rank, cfg.alpha, rng);
163
+ this.loraLayers.push({ key: `block${block.idx}.${target}`, layer, linear });
164
+ }
165
+ }
166
+ this.loraConfig = cfg;
167
+ return this.loraLayers.length;
168
+ }
169
+
170
+ detachLora() {
171
+ for (const { linear } of this.loraLayers) linear.lora = null;
172
+ this.loraLayers = [];
173
+ this.loraConfig = null;
174
+ }
175
+
176
+ get loraAttached() {
177
+ return this.loraLayers.length > 0;
178
+ }
179
+
180
+ forward(ids) {
181
+ if (ids.length === 0) throw new Error('forward requires at least one token');
182
+ if (ids.length > this.config.maxSeqLen) {
183
+ throw new Error(`sequence length ${ids.length} exceeds maxSeqLen ${this.config.maxSeqLen}`);
184
+ }
185
+ const tok = embeddingLookup(this.tokEmb, ids);
186
+ const posIds = ids.map((_, i) => i);
187
+ const pos = embeddingLookup(this.posEmb, posIds);
188
+ let h = add(tok, pos);
189
+ for (const block of this.blocks) h = block.forward(h);
190
+ h = layerNorm(h, this.lnfg, this.lnfb);
191
+ return this.head.forward(h);
192
+ }
193
+
194
+ // Next-token loss over a single sequence. `promptLen` masks prompt positions
195
+ // so instruction-style data only trains on the completion.
196
+ loss(ids, { promptLen = 0 } = {}) {
197
+ if (ids.length < 2) throw new Error('loss requires at least two tokens');
198
+ const inputs = ids.slice(0, -1);
199
+ const targets = ids.slice(1);
200
+ const masked = targets.map((t, i) => (i < Math.max(0, promptLen - 1) ? -1 : t));
201
+ const logits = this.forward(inputs);
202
+ return crossEntropy(logits, masked, -1);
203
+ }
204
+
205
+ zeroGrads(params) {
206
+ for (const p of params ?? [...this.baseParams(), ...this.loraParams()]) p.zeroGrad();
207
+ }
208
+
209
+ parameterCount({ mode = 'full' } = {}) {
210
+ return this.trainableParams({ mode }).reduce((n, p) => n + p.size, 0);
211
+ }
212
+
213
+ stateDict() {
214
+ const out = {};
215
+ for (const p of this.baseParams()) out[p.name] = { rows: p.rows, cols: p.cols, data: Array.from(p.data) };
216
+ return out;
217
+ }
218
+
219
+ loadStateDict(state) {
220
+ for (const p of this.baseParams()) {
221
+ const entry = state[p.name];
222
+ if (!entry) throw new Error(`checkpoint is missing parameter "${p.name}"`);
223
+ if (entry.rows !== p.rows || entry.cols !== p.cols) {
224
+ throw new Error(`parameter "${p.name}" shape mismatch: checkpoint ${entry.rows}x${entry.cols} vs model ${p.rows}x${p.cols}`);
225
+ }
226
+ p.data.set(entry.data);
227
+ }
228
+ return this;
229
+ }
230
+
231
+ adapterState() {
232
+ if (!this.loraAttached) throw new Error('no adapter attached');
233
+ const layers = {};
234
+ for (const { key, layer } of this.loraLayers) layers[key] = layer.toJSON();
235
+ return { kind: 'lora-v1', config: this.loraConfig, layers };
236
+ }
237
+
238
+ loadAdapterState(state) {
239
+ if (!this.loraAttached) this.attachLora(state.config);
240
+ for (const { key, layer } of this.loraLayers) {
241
+ const entry = state.layers[key];
242
+ if (!entry) throw new Error(`adapter is missing layer "${key}"`);
243
+ layer.loadJSON(entry);
244
+ }
245
+ return this;
246
+ }
247
+ }
248
+
249
+ export function paramVectorDigestInput(params) {
250
+ // Flattens parameters in a stable order for checksum / drift comparison.
251
+ const out = [];
252
+ for (const p of params) out.push(p.name, p.rows, p.cols, ...p.data);
253
+ return out;
254
+ }
255
+
256
+ export function l2Delta(before, after) {
257
+ let sum = 0;
258
+ for (const name of Object.keys(before)) {
259
+ const a = before[name];
260
+ const b = after[name];
261
+ if (!b) continue;
262
+ for (let i = 0; i < a.length; i += 1) {
263
+ const d = a[i] - b[i];
264
+ sum += d * d;
265
+ }
266
+ }
267
+ return Math.sqrt(sum);
268
+ }
269
+
270
+ export function snapshotParams(params) {
271
+ const out = {};
272
+ for (const p of params) out[p.name] = Float64Array.from(p.data);
273
+ return out;
274
+ }
275
+
276
+ export { Tensor };