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,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 };