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
package/src/config.mjs ADDED
@@ -0,0 +1,342 @@
1
+ // Configuration schema and validation.
2
+ //
3
+ // The foundry runs long, expensive jobs, so a bad config must fail here --
4
+ // before a single training step -- with a message that names the exact path.
5
+ // Validation is therefore total: every field is checked, unknown keys are
6
+ // reported rather than silently ignored, and the returned config is the
7
+ // normalized object the rest of the product consumes.
8
+
9
+ import path from 'node:path';
10
+ import { readJson, exists } from './core/fsx.mjs';
11
+ import { COMPARATORS } from './eval/gates.mjs';
12
+
13
+ export const CONFIG_FORMAT = 'tmf-config-v1';
14
+ export const DEFAULT_CONFIG_FILES = ['tmf.config.json', '.tmfrc.json'];
15
+
16
+ export const CONFIG_DEFAULTS = {
17
+ format: CONFIG_FORMAT,
18
+ project: 'tmf-project',
19
+ runRoot: '.tmf-run',
20
+ backend: 'builtin-js',
21
+ mode: 'lora',
22
+ seed: 'tmf-train',
23
+ model: { maxVocab: 256, maxSeqLen: 96 },
24
+ data: { datasets: [], config: {} },
25
+ hyper: {},
26
+ budget: {},
27
+ trainBudget: {},
28
+ eval: {},
29
+ };
30
+
31
+ const TOP_LEVEL = new Set([
32
+ 'format', 'project', 'runRoot', 'backend', 'mode', 'seed',
33
+ 'model', 'data', 'hyper', 'budget', 'trainBudget', 'eval',
34
+ ]);
35
+ // Mode names must match what a trainer backend advertises in
36
+ // capabilities.modes; anything else can never pass doctor's mode check.
37
+ export const MODES = new Set(['lora', 'pretrain', 'full-finetune']);
38
+
39
+ class Errors {
40
+ constructor() { this.list = []; }
41
+ add(at, message) { this.list.push({ at, message }); }
42
+ get ok() { return this.list.length === 0; }
43
+ }
44
+
45
+ function isPlainObject(value) {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ }
48
+
49
+ function requireString(errors, at, value, fallback) {
50
+ if (value === undefined) return fallback;
51
+ if (typeof value !== 'string' || value.trim() === '') {
52
+ errors.add(at, 'must be a non-empty string');
53
+ return fallback;
54
+ }
55
+ return value;
56
+ }
57
+
58
+ function requirePositiveInt(errors, at, value, fallback) {
59
+ if (value === undefined) return fallback;
60
+ if (!Number.isInteger(value) || value <= 0) {
61
+ errors.add(at, 'must be a positive integer');
62
+ return fallback;
63
+ }
64
+ return value;
65
+ }
66
+
67
+ function requireObject(errors, at, value, fallback) {
68
+ if (value === undefined) return fallback;
69
+ if (!isPlainObject(value)) {
70
+ errors.add(at, 'must be an object');
71
+ return fallback;
72
+ }
73
+ return value;
74
+ }
75
+
76
+ function validateDatasets(errors, raw) {
77
+ if (!Array.isArray(raw)) {
78
+ errors.add('data.datasets', 'must be an array of { name, path } entries');
79
+ return [];
80
+ }
81
+ const seen = new Set();
82
+ return raw.map((entry, i) => {
83
+ const at = `data.datasets[${i}]`;
84
+ if (!isPlainObject(entry)) {
85
+ errors.add(at, 'must be an object with name and path');
86
+ return null;
87
+ }
88
+ const name = requireString(errors, `${at}.name`, entry.name, null);
89
+ const file = requireString(errors, `${at}.path`, entry.path, null);
90
+ if (name === null) errors.add(`${at}.name`, 'is required');
91
+ if (file === null) errors.add(`${at}.path`, 'is required');
92
+ if (name && seen.has(name)) errors.add(`${at}.name`, `duplicate dataset name "${name}"`);
93
+ if (name) seen.add(name);
94
+ const out = { name, path: file };
95
+ if (entry.format !== undefined) out.format = requireString(errors, `${at}.format`, entry.format, 'jsonl');
96
+ if (entry.license !== undefined) out.license = requireString(errors, `${at}.license`, entry.license, null);
97
+ if (entry.source !== undefined) out.source = requireString(errors, `${at}.source`, entry.source, null);
98
+ return out;
99
+ }).filter(Boolean);
100
+ }
101
+
102
+ function validateBudget(errors, at, raw) {
103
+ const budget = requireObject(errors, at, raw, {});
104
+ const out = {};
105
+ for (const [key, value] of Object.entries(budget)) {
106
+ if (!['maxTokens', 'maxSteps', 'maxWallClockMs', 'maxCostCny'].includes(key)) {
107
+ errors.add(`${at}.${key}`, 'unknown budget key (allowed: maxTokens, maxSteps, maxWallClockMs, maxCostCny)');
108
+ continue;
109
+ }
110
+ if (typeof value !== 'number' || !(value > 0)) {
111
+ errors.add(`${at}.${key}`, 'must be a number greater than 0');
112
+ continue;
113
+ }
114
+ out[key] = value;
115
+ }
116
+ return out;
117
+ }
118
+
119
+ // Gate thresholds are project policy, not a toolkit constant: what counts as
120
+ // an acceptable holdout loss depends on the model and the task, and the
121
+ // built-in defaults were tuned against the builtin-js demo. They stayed
122
+ // unreachable until now -- api.mjs already read `eval.gates`, but `eval` was
123
+ // not an allowed top-level key, so no config could ever set it. Declaring a
124
+ // gate list replaces the defaults wholesale rather than merging, because a
125
+ // half-overridden gate set is the kind of thing that silently drops a check.
126
+ const GATE_KEYS = new Set(['id', 'metric', 'comparator', 'threshold', 'sampleMetric', 'minSamples', 'description']);
127
+
128
+ function validateGate(errors, at, raw) {
129
+ if (!isPlainObject(raw)) {
130
+ errors.add(at, 'must be an object');
131
+ return null;
132
+ }
133
+ for (const key of Object.keys(raw)) {
134
+ if (!GATE_KEYS.has(key)) errors.add(`${at}.${key}`, `unknown gate key (allowed: ${[...GATE_KEYS].join(', ')})`);
135
+ }
136
+ const gate = {
137
+ id: requireString(errors, `${at}.id`, raw.id, ''),
138
+ metric: requireString(errors, `${at}.metric`, raw.metric, ''),
139
+ comparator: requireString(errors, `${at}.comparator`, raw.comparator, ''),
140
+ };
141
+ if (gate.comparator && !COMPARATORS[gate.comparator]) {
142
+ errors.add(`${at}.comparator`, `must be one of ${Object.keys(COMPARATORS).join(', ')}`);
143
+ }
144
+ if (typeof raw.threshold !== 'number' || Number.isNaN(raw.threshold)) {
145
+ errors.add(`${at}.threshold`, 'must be a number');
146
+ } else {
147
+ gate.threshold = raw.threshold;
148
+ }
149
+ if (raw.sampleMetric !== undefined) gate.sampleMetric = requireString(errors, `${at}.sampleMetric`, raw.sampleMetric, '');
150
+ if (raw.minSamples !== undefined) gate.minSamples = requirePositiveInt(errors, `${at}.minSamples`, raw.minSamples, 1);
151
+ if (raw.minSamples !== undefined && raw.sampleMetric === undefined) {
152
+ errors.add(`${at}.sampleMetric`, 'is required when minSamples is set, otherwise the sample floor cannot be read');
153
+ }
154
+ if (raw.description !== undefined) gate.description = requireString(errors, `${at}.description`, raw.description, '');
155
+ return gate;
156
+ }
157
+
158
+ function validateEval(errors, at, raw) {
159
+ const evalRaw = requireObject(errors, at, raw, {});
160
+ for (const key of Object.keys(evalRaw)) {
161
+ if (key !== 'gates') errors.add(`${at}.${key}`, 'unknown eval key (allowed: gates)');
162
+ }
163
+ if (evalRaw.gates === undefined) return {};
164
+ if (!Array.isArray(evalRaw.gates)) {
165
+ errors.add(`${at}.gates`, 'must be an array of gate objects');
166
+ return {};
167
+ }
168
+ if (evalRaw.gates.length === 0) {
169
+ errors.add(`${at}.gates`, 'must declare at least one gate; omit `eval.gates` to use the built-in defaults');
170
+ return {};
171
+ }
172
+ const gates = evalRaw.gates.map((gate, i) => validateGate(errors, `${at}.gates[${i}]`, gate)).filter(Boolean);
173
+ const seen = new Set();
174
+ for (const gate of gates) {
175
+ if (!gate.id) continue;
176
+ if (seen.has(gate.id)) errors.add(`${at}.gates`, `duplicate gate id "${gate.id}"`);
177
+ seen.add(gate.id);
178
+ }
179
+ return { gates };
180
+ }
181
+
182
+ // Hyperparameters are a whitelist rather than a free-form bag: an unknown key
183
+ // here used to be accepted and then silently dropped by the trainer, which is
184
+ // how a misspelled `steps` could look like it had been applied.
185
+ const HYPER_NUMBER_KEYS = ['steps', 'lr', 'batchSize', 'beta1', 'beta2', 'eps', 'weightDecay', 'clipNorm', 'warmupRatio', 'minLrRatio'];
186
+ const HYPER_OBJECT_KEYS = ['lora'];
187
+ const HYPER_KEYS = [...HYPER_NUMBER_KEYS, ...HYPER_OBJECT_KEYS];
188
+
189
+ function validateHyper(errors, at, raw) {
190
+ const hyper = requireObject(errors, at, raw, {});
191
+ const out = {};
192
+ for (const [key, value] of Object.entries(hyper)) {
193
+ if (!HYPER_KEYS.includes(key)) {
194
+ errors.add(`${at}.${key}`, `unknown hyper key (allowed: ${HYPER_KEYS.join(', ')})`);
195
+ continue;
196
+ }
197
+ if (HYPER_OBJECT_KEYS.includes(key)) {
198
+ if (!isPlainObject(value)) {
199
+ errors.add(`${at}.${key}`, 'must be an object');
200
+ continue;
201
+ }
202
+ out[key] = value;
203
+ continue;
204
+ }
205
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
206
+ errors.add(`${at}.${key}`, 'must be a finite number greater than 0');
207
+ continue;
208
+ }
209
+ if ((key === 'steps' || key === 'batchSize') && !Number.isInteger(value)) {
210
+ errors.add(`${at}.${key}`, 'must be an integer');
211
+ continue;
212
+ }
213
+ out[key] = value;
214
+ }
215
+ return out;
216
+ }
217
+
218
+ /**
219
+ * Validate and normalize a raw config object.
220
+ *
221
+ * Returns { ok, config, errors } -- never throws on bad input, so callers can
222
+ * render every problem at once instead of one per run.
223
+ */
224
+ export function validateConfig(raw, { baseDir = process.cwd() } = {}) {
225
+ const errors = new Errors();
226
+ if (!isPlainObject(raw)) {
227
+ errors.add('<root>', 'config must be a JSON object');
228
+ return { ok: false, config: null, errors: errors.list };
229
+ }
230
+
231
+ for (const key of Object.keys(raw)) {
232
+ if (!TOP_LEVEL.has(key)) errors.add(key, `unknown config key (allowed: ${[...TOP_LEVEL].join(', ')})`);
233
+ }
234
+
235
+ const format = requireString(errors, 'format', raw.format, CONFIG_FORMAT);
236
+ if (format !== CONFIG_FORMAT) errors.add('format', `must be "${CONFIG_FORMAT}"`);
237
+
238
+ const mode = requireString(errors, 'mode', raw.mode, CONFIG_DEFAULTS.mode);
239
+ if (!MODES.has(mode)) errors.add('mode', `must be one of ${[...MODES].join(', ')}`);
240
+
241
+ const modelRaw = requireObject(errors, 'model', raw.model, {});
242
+ const model = {
243
+ ...modelRaw,
244
+ maxVocab: requirePositiveInt(errors, 'model.maxVocab', modelRaw.maxVocab, CONFIG_DEFAULTS.model.maxVocab),
245
+ maxSeqLen: requirePositiveInt(errors, 'model.maxSeqLen', modelRaw.maxSeqLen, CONFIG_DEFAULTS.model.maxSeqLen),
246
+ };
247
+
248
+ const dataRaw = requireObject(errors, 'data', raw.data, {});
249
+ const datasets = validateDatasets(errors, dataRaw.datasets ?? []);
250
+ if (datasets.length === 0 && Array.isArray(dataRaw.datasets)) {
251
+ errors.add('data.datasets', 'at least one dataset is required to train');
252
+ }
253
+
254
+ const runRoot = requireString(errors, 'runRoot', raw.runRoot, CONFIG_DEFAULTS.runRoot);
255
+
256
+ const config = {
257
+ format: CONFIG_FORMAT,
258
+ project: requireString(errors, 'project', raw.project, CONFIG_DEFAULTS.project),
259
+ runRoot,
260
+ runRootAbsolute: path.resolve(baseDir, runRoot),
261
+ baseDir: path.resolve(baseDir),
262
+ backend: requireString(errors, 'backend', raw.backend, CONFIG_DEFAULTS.backend),
263
+ mode,
264
+ seed: requireString(errors, 'seed', raw.seed, CONFIG_DEFAULTS.seed),
265
+ model,
266
+ data: { datasets, config: requireObject(errors, 'data.config', dataRaw.config, {}) },
267
+ hyper: validateHyper(errors, 'hyper', raw.hyper),
268
+ budget: validateBudget(errors, 'budget', raw.budget),
269
+ trainBudget: requireObject(errors, 'trainBudget', raw.trainBudget, {}),
270
+ eval: validateEval(errors, 'eval', raw.eval),
271
+ };
272
+
273
+ return { ok: errors.ok, config: errors.ok ? config : null, errors: errors.list };
274
+ }
275
+
276
+ export function formatConfigErrors(errors) {
277
+ return errors.map((e) => ` - ${e.at}: ${e.message}`).join('\n');
278
+ }
279
+
280
+ export class ConfigError extends Error {
281
+ constructor(message, errors = []) {
282
+ super(message);
283
+ this.name = 'ConfigError';
284
+ this.code = 'TMF_CONFIG_INVALID';
285
+ this.errors = errors;
286
+ }
287
+ }
288
+
289
+ export async function findConfigFile(baseDir = process.cwd()) {
290
+ for (const name of DEFAULT_CONFIG_FILES) {
291
+ const file = path.join(baseDir, name);
292
+ if (await exists(file)) return file;
293
+ }
294
+ return null;
295
+ }
296
+
297
+ /**
298
+ * Load, validate and normalize a config file. Throws ConfigError carrying the
299
+ * full error list so a CLI can print all problems and exit non-zero.
300
+ */
301
+ export async function loadConfig({ file = null, baseDir = process.cwd() } = {}) {
302
+ const resolved = file ? path.resolve(baseDir, file) : await findConfigFile(baseDir);
303
+ if (!resolved) {
304
+ throw new ConfigError(
305
+ `no config file found in ${baseDir} (looked for ${DEFAULT_CONFIG_FILES.join(', ')})`,
306
+ [{ at: '<file>', message: 'missing config file; run `tmf init` to create one' }],
307
+ );
308
+ }
309
+ if (!(await exists(resolved))) {
310
+ throw new ConfigError(`config file not found: ${resolved}`, [{ at: '<file>', message: 'missing config file' }]);
311
+ }
312
+ let raw;
313
+ try {
314
+ raw = await readJson(resolved);
315
+ } catch (err) {
316
+ throw new ConfigError(`config file is not valid JSON: ${resolved}`, [{ at: '<file>', message: err.message }]);
317
+ }
318
+ const { ok, config, errors } = validateConfig(raw, { baseDir: path.dirname(resolved) });
319
+ if (!ok) throw new ConfigError(`invalid config: ${resolved}`, errors);
320
+ return { file: resolved, config };
321
+ }
322
+
323
+ export function exampleConfig({ project = 'tmf-project', dataDir = 'data' } = {}) {
324
+ return {
325
+ format: CONFIG_FORMAT,
326
+ project,
327
+ runRoot: '.tmf-run',
328
+ backend: 'builtin-js',
329
+ mode: 'lora',
330
+ seed: 'tmf-train',
331
+ model: { maxVocab: 256, maxSeqLen: 96 },
332
+ data: {
333
+ datasets: [{ name: 'tasks', path: `${dataDir}/tasks.jsonl`, format: 'jsonl', license: 'internal', source: 'synthetic' }],
334
+ config: {},
335
+ },
336
+ // lr stays at the small end on purpose: 0.05 oscillates on the builtin-js
337
+ // AdamW path and loses the holdout improvement, while 0.005 converged
338
+ // (holdout loss 0.248876 vs 4.82943 baseline on the reference run).
339
+ hyper: { steps: 120, lr: 0.005, batchSize: 4 },
340
+ budget: { maxTokens: 2000000, maxWallClockMs: 900000 },
341
+ };
342
+ }