taskforce-model-foundry 0.0.0-stage → 0.2.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +75 -0
  5. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  6. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  7. package/docs/integration.md +228 -0
  8. package/docs/releases/v0.2.0.md +24 -0
  9. package/docs/tutorial.md +340 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  11. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  12. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  13. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  14. package/integrations/openclaw-plugin/index.mjs +27 -0
  15. package/integrations/openclaw-plugin/tools.mjs +73 -0
  16. package/openclaw.plugin.json +25 -0
  17. package/package.json +70 -4
  18. package/scripts/e2e-demo.sh +56 -0
  19. package/src/api.mjs +341 -0
  20. package/src/config.mjs +342 -0
  21. package/src/core/autograd.mjs +451 -0
  22. package/src/core/fsx.mjs +65 -0
  23. package/src/core/hash.mjs +47 -0
  24. package/src/core/rng.mjs +70 -0
  25. package/src/data/clean.mjs +115 -0
  26. package/src/data/dedupe.mjs +125 -0
  27. package/src/data/ingest.mjs +184 -0
  28. package/src/data/pii.mjs +142 -0
  29. package/src/data/pipeline.mjs +183 -0
  30. package/src/data/provenance.mjs +88 -0
  31. package/src/data/split.mjs +193 -0
  32. package/src/data/synth.mjs +198 -0
  33. package/src/eval/evaluator.mjs +137 -0
  34. package/src/eval/gates.mjs +114 -0
  35. package/src/eval/metrics.mjs +90 -0
  36. package/src/export/package.mjs +365 -0
  37. package/src/index.mjs +26 -0
  38. package/src/integrations/async-evaluate-worker.mjs +39 -0
  39. package/src/integrations/async-evaluate.mjs +125 -0
  40. package/src/integrations/hermes.mjs +177 -0
  41. package/src/integrations/openclaw.mjs +164 -0
  42. package/src/jobs/evaluate.mjs +172 -0
  43. package/src/jobs/runner.mjs +323 -0
  44. package/src/jobs/train.mjs +303 -0
  45. package/src/model/lora.mjs +53 -0
  46. package/src/model/tokenizer.mjs +73 -0
  47. package/src/model/transformer.mjs +276 -0
  48. package/src/train/backends/builtin-js.mjs +367 -0
  49. package/src/train/backends/hf-peft.mjs +597 -0
  50. package/src/train/backends/hf_peft_runner.py +397 -0
  51. package/src/train/backends/index.mjs +92 -0
  52. package/src/train/dataset.mjs +56 -0
  53. package/src/train/optimizer.mjs +99 -0
  54. package/src/version.mjs +5 -0
@@ -0,0 +1,367 @@
1
+ // The default trainer backend: a real optimizer loop over the pure-JS
2
+ // transformer.
3
+ //
4
+ // "Real" here means the specific things the acceptance plan asks for. Gradients
5
+ // come from the autodiff engine and are numerically verified in the test suite;
6
+ // AdamW mutates the parameter arrays in place; the resulting checkpoint is a
7
+ // byte-for-byte record of those arrays and reloads to identical outputs. No
8
+ // retrieval, no prompt scaffolding and no recorded numbers stand in for the
9
+ // update.
10
+
11
+ import path from 'node:path';
12
+ import { backward } from '../../core/autograd.mjs';
13
+ import { sha256File, sha256Json } from '../../core/hash.mjs';
14
+ import { writeJson, readJson, ensureDir } from '../../core/fsx.mjs';
15
+ import { Rng } from '../../core/rng.mjs';
16
+ import { TransformerModel, snapshotParams, l2Delta, DEFAULT_MODEL_CONFIG, DEFAULT_LORA_CONFIG } from '../../model/transformer.mjs';
17
+ import { Tokenizer } from '../../model/tokenizer.mjs';
18
+ import { AdamW, lrSchedule, DEFAULT_OPTIMIZER_CONFIG } from '../optimizer.mjs';
19
+ import { makeBatches, countTokens, encodeRecords } from '../dataset.mjs';
20
+
21
+ export const CHECKPOINT_FORMAT = 'tmf-checkpoint-v1';
22
+
23
+ export const DEFAULT_HYPER = {
24
+ ...DEFAULT_OPTIMIZER_CONFIG,
25
+ batchSize: 8,
26
+ warmupRatio: 0.1,
27
+ minLrRatio: 0.1,
28
+ };
29
+
30
+ export const DEFAULT_BUDGET = {
31
+ maxSteps: 200,
32
+ maxSeconds: 120,
33
+ maxTokens: null,
34
+ targetLoss: null,
35
+ };
36
+
37
+ // `hyper.steps` is the knob `tmf init` writes, so a config that sets it must
38
+ // actually get that many steps. The budget object stays authoritative when it
39
+ // names maxSteps itself; otherwise hyper.steps supplies it. Without this the
40
+ // step count in the config was silently ignored in favour of DEFAULT_BUDGET.
41
+ export function resolveStepBudget({ budget = {}, hyper = {} } = {}) {
42
+ const fromBudget = budget?.maxSteps;
43
+ if (fromBudget !== undefined) return { maxSteps: fromBudget, source: 'trainBudget.maxSteps' };
44
+ const fromHyper = hyper?.steps;
45
+ if (fromHyper !== undefined && fromHyper !== null) {
46
+ if (!Number.isFinite(fromHyper) || fromHyper <= 0) {
47
+ throw new Error(`hyper.steps must be a positive number or null, got ${fromHyper}`);
48
+ }
49
+ return { maxSteps: fromHyper, source: 'hyper.steps' };
50
+ }
51
+ return { maxSteps: DEFAULT_BUDGET.maxSteps, source: 'default' };
52
+ }
53
+
54
+ function resolveBudget(budget = {}, { hyper = {} } = {}) {
55
+ const step = resolveStepBudget({ budget, hyper });
56
+ const resolved = { ...DEFAULT_BUDGET, ...budget, maxSteps: step.maxSteps };
57
+ resolved.stepBudgetSource = step.source;
58
+ for (const key of ['maxSteps', 'maxSeconds', 'maxTokens']) {
59
+ const value = resolved[key];
60
+ if (value !== null && value !== undefined && (!Number.isFinite(value) || value <= 0)) {
61
+ throw new Error(`budget.${key} must be a positive number or null, got ${value}`);
62
+ }
63
+ }
64
+ if (resolved.maxSteps === null && resolved.maxSeconds === null && resolved.maxTokens === null) {
65
+ throw new Error('a training budget needs at least one of maxSteps, maxSeconds or maxTokens');
66
+ }
67
+ return resolved;
68
+ }
69
+
70
+ const backend = {
71
+ id: 'builtin-js',
72
+
73
+ capabilities: {
74
+ // Every non-lora mode trains the full parameter set through the same
75
+ // optimizer loop (see trainableParams below), so full-finetune is a real
76
+ // capability here, not an alias we reject at the config boundary.
77
+ modes: ['pretrain', 'lora', 'full-finetune'],
78
+ // This backend owns no tokenizer of its own: the training job builds the
79
+ // vocabulary from the data split and hands it in. See prepareDataset().
80
+ ownsTokenizer: false,
81
+ frameworks: ['builtin-autograd'],
82
+ devices: ['cpu'],
83
+ supportsResume: true,
84
+ supportsCancel: true,
85
+ precision: 'float32',
86
+ },
87
+
88
+ // Always available: the implementation ships with the package and has no
89
+ // native dependency, which is why it is the default.
90
+ async probe() {
91
+ return {
92
+ available: true,
93
+ reason: 'bundled pure-JavaScript trainer; no external dependency',
94
+ details: { node: process.version, deps: [] },
95
+ };
96
+ },
97
+
98
+ // Dataset preparation is part of the backend contract so the training job
99
+ // does not have to know whether ids come from a job-built vocabulary (here)
100
+ // or from the model's own tokenizer (hf-peft). Both return the same shape.
101
+ prepareDataset({ handle, records, maxSeqLen = 96 } = {}) {
102
+ if (!handle?.tokenizer) throw new Error('builtin-js prepareDataset() requires a handle with a tokenizer');
103
+ const { examples, skipped } = encodeRecords(records ?? [], handle.tokenizer, { maxSeqLen });
104
+ return { examples, skipped, tokens: countTokens(examples), tokenizer: 'job-built', vocabSize: handle.tokenizer.size };
105
+ },
106
+
107
+ async createModel({ modelConfig = {}, tokenizer, seed = 1 } = {}) {
108
+ if (!tokenizer) throw new Error('createModel requires a tokenizer');
109
+ const config = { ...DEFAULT_MODEL_CONFIG, ...modelConfig, vocabSize: tokenizer.size };
110
+ const model = new TransformerModel(config, { seed });
111
+ return { backend: backend.id, kind: 'base', model, tokenizer, seed, modelConfig: config };
112
+ },
113
+
114
+ async loadModel({ file, attachAdapter = null } = {}) {
115
+ const payload = await readJson(file);
116
+ if (payload.format !== CHECKPOINT_FORMAT) {
117
+ throw new Error(`unsupported checkpoint format "${payload.format}"; expected ${CHECKPOINT_FORMAT}`);
118
+ }
119
+ if (payload.backend !== backend.id) {
120
+ throw new Error(`checkpoint was produced by backend "${payload.backend}", not ${backend.id}`);
121
+ }
122
+ const tokenizer = Tokenizer.fromJSON(payload.tokenizer);
123
+ const model = new TransformerModel(payload.modelConfig, { seed: payload.seed });
124
+ if (payload.kind === 'base') {
125
+ model.loadStateDict(payload.params);
126
+ } else if (payload.kind === 'adapter') {
127
+ if (!payload.baseCheckpoint) throw new Error('adapter checkpoint does not record its base checkpoint');
128
+ throw new Error('load an adapter with loadAdapter(), which needs the base checkpoint first');
129
+ } else {
130
+ // Falling through would hand back freshly initialised weights and
131
+ // silently evaluate the wrong model, so an unknown kind is terminal.
132
+ throw new Error(`unsupported checkpoint kind "${payload.kind}"; expected base or adapter`);
133
+ }
134
+ const handle = { backend: backend.id, kind: 'base', model, tokenizer, seed: payload.seed, modelConfig: payload.modelConfig, meta: payload.meta ?? {} };
135
+ if (attachAdapter) await backend.loadAdapter(handle, attachAdapter);
136
+ return handle;
137
+ },
138
+
139
+ // Adapters are layered onto an already loaded base so that "reload the
140
+ // adapter and get identical outputs" is directly testable.
141
+ async loadAdapter(handle, file) {
142
+ const payload = await readJson(file);
143
+ if (payload.format !== CHECKPOINT_FORMAT || payload.kind !== 'adapter') {
144
+ throw new Error(`"${file}" is not a ${CHECKPOINT_FORMAT} adapter checkpoint`);
145
+ }
146
+ if (payload.baseFingerprint && payload.baseFingerprint !== backend.fingerprint(handle)) {
147
+ throw new Error(
148
+ 'adapter does not match this base model: fingerprint '
149
+ + `${payload.baseFingerprint.slice(0, 12)} != ${backend.fingerprint(handle).slice(0, 12)}`,
150
+ );
151
+ }
152
+ handle.model.loadAdapterState(payload.params);
153
+ handle.adapterMeta = payload.meta ?? {};
154
+ handle.kind = 'base+adapter';
155
+ return handle;
156
+ },
157
+
158
+ // Digest of the base weights; used to bind an adapter to the base it was
159
+ // trained against and to prove in evidence that weights changed.
160
+ fingerprint(handle) {
161
+ return sha256Json(handle.model.stateDict());
162
+ },
163
+
164
+ async saveModel({ handle, file, kind = 'base', meta = {} } = {}) {
165
+ await ensureDir(path.dirname(file));
166
+ const payload = {
167
+ format: CHECKPOINT_FORMAT,
168
+ backend: backend.id,
169
+ kind,
170
+ createdAt: new Date().toISOString(),
171
+ seed: handle.seed,
172
+ modelConfig: handle.modelConfig,
173
+ tokenizer: handle.tokenizer.toJSON(),
174
+ loraConfig: kind === 'adapter' ? handle.model.loraConfig : null,
175
+ baseFingerprint: kind === 'adapter' ? (meta.baseFingerprint ?? null) : null,
176
+ baseCheckpoint: kind === 'adapter' ? (meta.baseCheckpoint ?? null) : null,
177
+ params: kind === 'adapter' ? handle.model.adapterState() : handle.model.stateDict(),
178
+ meta,
179
+ };
180
+ await writeJson(file, payload, { pretty: false });
181
+ return { file, sha256: await sha256File(file), kind, bytes: JSON.stringify(payload).length };
182
+ },
183
+
184
+ async train({ handle, examples, mode = 'pretrain', hyper = {}, budget = {}, hooks = {}, seed = 'tmf-train', resume = null } = {}) {
185
+ if (!examples?.length) throw new Error('training needs at least one example');
186
+ const cfg = { ...DEFAULT_HYPER, ...hyper };
187
+ const limits = resolveBudget(budget, { hyper: cfg });
188
+ const model = handle.model;
189
+
190
+ if (mode === 'lora') {
191
+ if (!model.loraAttached) model.attachLora(cfg.lora ?? DEFAULT_LORA_CONFIG);
192
+ model.setBaseFrozen(true);
193
+ } else {
194
+ model.setBaseFrozen(false);
195
+ }
196
+ const params = model.trainableParams({ mode: mode === 'lora' ? 'lora' : 'full' });
197
+ const optimizer = new AdamW(params, cfg);
198
+ if (resume?.optimizer) optimizer.loadStateDict(resume.optimizer);
199
+
200
+ const before = snapshotParams(params);
201
+ const startStep = resume?.step ?? 0;
202
+ const totalSteps = limits.maxSteps ?? 0;
203
+ const warmupSteps = Math.max(0, Math.floor((totalSteps || 0) * cfg.warmupRatio));
204
+ const startedAt = Date.now();
205
+
206
+ const history = [];
207
+ let step = startStep;
208
+ let tokensSeen = resume?.tokensSeen ?? 0;
209
+ let stopReason = null;
210
+ let lastLoss = null;
211
+ let epoch = resume?.epoch ?? 0;
212
+ // Batch loss is noisy and the tail of training diverged (final >> best), so
213
+ // track an EMA-smoothed best and keep a periodic snapshot to restore from.
214
+ const emaAlpha = 0.1;
215
+ const snapshotEvery = 10;
216
+ let emaLoss = null;
217
+ let bestEmaLoss = null;
218
+ let bestSnapshot = null;
219
+ let bestSnapshotStep = null;
220
+
221
+ outer: while (true) {
222
+ const rng = new Rng(`${seed}:epoch:${epoch}`);
223
+ const batches = makeBatches(examples, cfg.batchSize, rng);
224
+ epoch += 1;
225
+ for (const batch of batches) {
226
+ if (limits.maxSteps !== null && step >= limits.maxSteps) { stopReason = 'max_steps'; break outer; }
227
+ const elapsed = (Date.now() - startedAt) / 1000;
228
+ if (limits.maxSeconds !== null && elapsed >= limits.maxSeconds) { stopReason = 'max_seconds'; break outer; }
229
+ if (limits.maxTokens !== null && tokensSeen >= limits.maxTokens) { stopReason = 'max_tokens'; break outer; }
230
+ if (hooks.shouldCancel && (await hooks.shouldCancel({ step, elapsed }))) { stopReason = 'cancelled'; break outer; }
231
+
232
+ optimizer.zeroGrad();
233
+ let batchLoss = 0;
234
+ let batchTokens = 0;
235
+ for (const example of batch) {
236
+ const loss = model.loss(example.ids, { promptLen: example.promptLen });
237
+ backward(loss);
238
+ batchLoss += loss.lossValue;
239
+ batchTokens += loss.tokenCount;
240
+ }
241
+ // Gradients accumulated across the batch; scale to the mean.
242
+ const scaleFactor = 1 / batch.length;
243
+ for (const p of params) if (p.grad) for (let i = 0; i < p.grad.length; i += 1) p.grad[i] *= scaleFactor;
244
+
245
+ const lr = cfg.lr * lrSchedule(step, totalSteps || batches.length, { warmupSteps, minRatio: cfg.minLrRatio });
246
+ const applied = optimizer.applyStep({ lr });
247
+ lastLoss = batchLoss / batch.length;
248
+ tokensSeen += batchTokens;
249
+ step += 1;
250
+
251
+ const entry = {
252
+ step,
253
+ loss: Number(lastLoss.toFixed(6)),
254
+ lr: Number(lr.toFixed(8)),
255
+ gradNorm: Number(applied.gradNorm.toFixed(6)),
256
+ tokens: tokensSeen,
257
+ elapsedMs: Date.now() - startedAt,
258
+ };
259
+ history.push(entry);
260
+ emaLoss = emaLoss === null ? lastLoss : emaLoss + emaAlpha * (lastLoss - emaLoss);
261
+ if (step > warmupSteps && step % snapshotEvery === 0 && (bestEmaLoss === null || emaLoss < bestEmaLoss)) {
262
+ bestEmaLoss = emaLoss;
263
+ bestSnapshot = snapshotParams(params);
264
+ bestSnapshotStep = step;
265
+ }
266
+ await hooks.onStep?.(entry, { optimizer, model, handle });
267
+
268
+ if (limits.targetLoss !== null && limits.targetLoss !== undefined && lastLoss <= limits.targetLoss) {
269
+ stopReason = 'target_loss';
270
+ break outer;
271
+ }
272
+ }
273
+ if (examples.length === 0) break;
274
+ }
275
+
276
+ // Finalize on the best smoothed weights instead of whatever the last step left.
277
+ let restoredFromStep = null;
278
+ if (bestSnapshot && emaLoss !== null && bestEmaLoss !== null && emaLoss > bestEmaLoss) {
279
+ for (const p of params) {
280
+ const saved = bestSnapshot[p.name];
281
+ if (saved) p.data.set(saved);
282
+ }
283
+ restoredFromStep = bestSnapshotStep;
284
+ }
285
+
286
+ const after = snapshotParams(params);
287
+ const delta = l2Delta(before, after);
288
+ const metrics = {
289
+ mode,
290
+ steps: step - startStep,
291
+ totalSteps: step,
292
+ epochs: epoch,
293
+ firstLoss: history.length ? history[0].loss : null,
294
+ finalLoss: lastLoss === null ? null : Number(lastLoss.toFixed(6)),
295
+ bestLoss: history.length ? Math.min(...history.map((h) => h.loss)) : null,
296
+ finalSmoothedLoss: emaLoss === null ? null : Number(emaLoss.toFixed(6)),
297
+ bestSmoothedLoss: bestEmaLoss === null ? null : Number(bestEmaLoss.toFixed(6)),
298
+ restoredFromStep,
299
+ tokensSeen,
300
+ trainableParams: params.reduce((n, p) => n + p.size, 0),
301
+ // Non-zero L2 displacement is the direct evidence that weights moved.
302
+ parameterL2Delta: Number(delta.toFixed(8)),
303
+ wallClockSeconds: Number(((Date.now() - startedAt) / 1000).toFixed(3)),
304
+ stepBudget: limits.maxSteps,
305
+ stepBudgetSource: limits.stepBudgetSource,
306
+ stopReason: stopReason ?? 'completed',
307
+ };
308
+ return { metrics, history, optimizerState: optimizer.stateDict(), stopReason: metrics.stopReason };
309
+ },
310
+
311
+ async evaluate({ handle, examples } = {}) {
312
+ if (!examples?.length) throw new Error('evaluation needs at least one example');
313
+ let total = 0;
314
+ let tokens = 0;
315
+ for (const example of examples) {
316
+ const loss = handle.model.loss(example.ids, { promptLen: example.promptLen });
317
+ total += loss.lossValue * loss.tokenCount;
318
+ tokens += loss.tokenCount;
319
+ }
320
+ const loss = tokens > 0 ? total / tokens : 0;
321
+ return { loss: Number(loss.toFixed(6)), perplexity: Number(Math.exp(loss).toFixed(6)), tokens, examples: examples.length };
322
+ },
323
+
324
+ async generate({ handle, prompt, maxNewTokens = 32, temperature = 0, stopToken = null, seed = 'tmf-gen' } = {}) {
325
+ const { model, tokenizer } = handle;
326
+ const rng = new Rng(seed);
327
+ let ids = tokenizer.encode(prompt, { bos: true });
328
+ const stopId = stopToken === null ? tokenizer.eosId : tokenizer.index.get(stopToken) ?? tokenizer.eosId;
329
+ const generated = [];
330
+ for (let i = 0; i < maxNewTokens; i += 1) {
331
+ if (ids.length >= model.config.maxSeqLen) break;
332
+ const logits = model.forward(ids);
333
+ const row = logits.rows - 1;
334
+ let nextId;
335
+ if (temperature <= 0) {
336
+ // Greedy decoding keeps generation reproducible for evaluation.
337
+ let best = -Infinity;
338
+ nextId = 0;
339
+ for (let c = 0; c < logits.cols; c += 1) {
340
+ const v = logits.at(row, c);
341
+ if (v > best) { best = v; nextId = c; }
342
+ }
343
+ } else {
344
+ let max = -Infinity;
345
+ for (let c = 0; c < logits.cols; c += 1) max = Math.max(max, logits.at(row, c) / temperature);
346
+ let sum = 0;
347
+ const probs = new Float64Array(logits.cols);
348
+ for (let c = 0; c < logits.cols; c += 1) {
349
+ probs[c] = Math.exp(logits.at(row, c) / temperature - max);
350
+ sum += probs[c];
351
+ }
352
+ let draw = rng.next() * sum;
353
+ nextId = logits.cols - 1;
354
+ for (let c = 0; c < logits.cols; c += 1) {
355
+ draw -= probs[c];
356
+ if (draw <= 0) { nextId = c; break; }
357
+ }
358
+ }
359
+ if (nextId === stopId) break;
360
+ generated.push(nextId);
361
+ ids = [...ids, nextId];
362
+ }
363
+ return tokenizer.decode(generated);
364
+ },
365
+ };
366
+
367
+ export default backend;