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,56 @@
1
+ #!/usr/bin/env bash
2
+ # Repeatable end-to-end demonstration of taskforce-model-foundry.
3
+ #
4
+ # Everything here is real work: a synthetic corpus is generated, a model is
5
+ # actually post-trained (weights move), and the job state it leaves behind is
6
+ # re-read from disk afterwards. No private data and no network are involved.
7
+ #
8
+ # Usage:
9
+ # bash scripts/e2e-demo.sh [workdir]
10
+ # TMF_DEMO_KEEP=1 bash scripts/e2e-demo.sh # keep the workdir for inspection
11
+ set -euo pipefail
12
+
13
+ REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
14
+ TMF="node $REPO/bin/tmf.mjs"
15
+ WORKDIR="${1:-$(mktemp -d "${TMPDIR:-/tmp}/tmf-demo-XXXXXX")}"
16
+ mkdir -p "$WORKDIR"
17
+
18
+ finish() {
19
+ status=$?
20
+ if [ "${TMF_DEMO_KEEP:-0}" = "1" ] || [ "$status" -ne 0 ]; then
21
+ echo "workdir kept for inspection: $WORKDIR"
22
+ else
23
+ rm -rf "$WORKDIR"
24
+ echo "workdir removed (set TMF_DEMO_KEEP=1 to keep it)"
25
+ fi
26
+ }
27
+ trap finish EXIT
28
+
29
+ step() { echo; echo "=== $* ==="; }
30
+
31
+ step "0. version and backends"
32
+ $TMF version
33
+ $TMF backends
34
+
35
+ step "1. init: starter config + synthetic corpus (no private data)"
36
+ $TMF init -C "$WORKDIR" --count 160
37
+
38
+ step "2. config validate: every problem at once, with field paths"
39
+ $TMF config validate -C "$WORKDIR"
40
+
41
+ step "3. doctor: environment, backend and dataset self-check"
42
+ $TMF doctor -C "$WORKDIR"
43
+
44
+ step "4. train: a real post-training job (deterministic seed from the config)"
45
+ $TMF train -C "$WORKDIR" --job demo-job
46
+
47
+ step "5. status: durable job state and audit trail re-read from disk"
48
+ $TMF status -C "$WORKDIR" demo-job
49
+
50
+ step "6. re-run train: resumes the finished job instead of redoing the work"
51
+ $TMF train -C "$WORKDIR" --job demo-job
52
+
53
+ step "demo complete"
54
+ echo "Trained artifacts and job state live under: $WORKDIR"
55
+ echo "Independent held-out evaluation and its gate verdict are exercised by the"
56
+ echo "test suite (test/eval-job.test.mjs, test/eval.test.mjs): npm test"
package/src/api.mjs ADDED
@@ -0,0 +1,341 @@
1
+ // The programmatic API.
2
+ //
3
+ // Everything the CLI does, it does through this module, so an embedder (the
4
+ // OpenClaw / Hermes adapters included) gets exactly the same behaviour without
5
+ // shelling out. Functions here return plain JSON-serializable records.
6
+
7
+ import path from 'node:path';
8
+ import process from 'node:process';
9
+ import { loadConfig, validateConfig, exampleConfig, ConfigError } from './config.mjs';
10
+ import { loadDefaultBackends, probeBackends, resolveBackend, listBackends } from './train/backends/index.mjs';
11
+ import { runTrainingJob, trainingArtifacts } from './jobs/train.mjs';
12
+ import { readJobState, readAuditLog } from './jobs/runner.mjs';
13
+ import { writeSyntheticCorpus } from './data/synth.mjs';
14
+ import { runEvaluationJob, assertReportIntegrity } from './jobs/evaluate.mjs';
15
+ import { DEFAULT_GATES } from './eval/gates.mjs';
16
+ import { encodeRecords } from './train/dataset.mjs';
17
+ import { exportModel as packageExport } from './export/package.mjs';
18
+ import { exists, readJson, readJsonl } from './core/fsx.mjs';
19
+ import { VERSION } from './version.mjs';
20
+
21
+ export const PRODUCT = 'taskforce-model-foundry';
22
+ const MIN_NODE_MAJOR = 20;
23
+
24
+ let backendsLoaded = false;
25
+ async function ensureBackends() {
26
+ if (!backendsLoaded) {
27
+ await loadDefaultBackends();
28
+ backendsLoaded = true;
29
+ }
30
+ return listBackends();
31
+ }
32
+
33
+ /**
34
+ * Environment and configuration self-check.
35
+ *
36
+ * Reports every check rather than throwing on the first failure: `ok` is false
37
+ * when any required check fails, while optional checks (an absent GPU backend,
38
+ * a missing config file when none was requested) are reported as warnings.
39
+ */
40
+ export async function doctor({ baseDir = process.cwd(), configFile = null, requireConfig = false } = {}) {
41
+ const checks = [];
42
+ const nodeMajor = Number(process.versions.node.split('.')[0]);
43
+ checks.push({
44
+ id: 'node-version',
45
+ level: 'required',
46
+ ok: nodeMajor >= MIN_NODE_MAJOR,
47
+ detail: `node ${process.versions.node} (requires >=${MIN_NODE_MAJOR})`,
48
+ });
49
+
50
+ await ensureBackends();
51
+ const probes = await probeBackends();
52
+ const availableBackends = probes.filter((p) => p.available).map((p) => p.id);
53
+ checks.push({
54
+ id: 'trainer-backend',
55
+ level: 'required',
56
+ ok: availableBackends.length > 0,
57
+ detail: availableBackends.length > 0
58
+ ? `available: ${availableBackends.join(', ')}`
59
+ : 'no trainer backend is available in this environment',
60
+ });
61
+ for (const probe of probes.filter((p) => !p.available)) {
62
+ checks.push({
63
+ id: `backend:${probe.id}`,
64
+ level: 'optional',
65
+ ok: false,
66
+ detail: `unavailable: ${probe.reason ?? 'unknown reason'}`,
67
+ });
68
+ }
69
+
70
+ let config = null;
71
+ let configPath = null;
72
+ let configErrors = [];
73
+ try {
74
+ const loaded = await loadConfig({ file: configFile, baseDir });
75
+ config = loaded.config;
76
+ configPath = loaded.file;
77
+ checks.push({ id: 'config', level: 'required', ok: true, detail: `valid: ${path.relative(baseDir, loaded.file) || loaded.file}` });
78
+ } catch (err) {
79
+ if (!(err instanceof ConfigError)) throw err;
80
+ configErrors = err.errors;
81
+ checks.push({
82
+ id: 'config',
83
+ level: requireConfig || configFile ? 'required' : 'optional',
84
+ ok: false,
85
+ detail: err.message,
86
+ });
87
+ }
88
+
89
+ if (config) {
90
+ for (const dataset of config.data.datasets) {
91
+ const file = path.resolve(config.baseDir, dataset.path);
92
+ checks.push({
93
+ id: `dataset:${dataset.name}`,
94
+ level: 'required',
95
+ ok: await exists(file),
96
+ detail: (await exists(file)) ? file : `missing dataset file: ${file}`,
97
+ });
98
+ }
99
+ checks.push({
100
+ id: 'backend-supports-mode',
101
+ level: 'required',
102
+ ok: probes.some((p) => p.id === config.backend && p.available && p.capabilities?.modes?.includes(config.mode)),
103
+ detail: `backend "${config.backend}" must be available and support mode "${config.mode}"`,
104
+ });
105
+ }
106
+
107
+ const failed = checks.filter((c) => c.level === 'required' && !c.ok);
108
+ return {
109
+ product: PRODUCT,
110
+ ok: failed.length === 0,
111
+ node: process.versions.node,
112
+ platform: `${process.platform}-${process.arch}`,
113
+ backends: probes.map(({ id, available, reason = null, capabilities }) => ({ id, available, reason, capabilities })),
114
+ configFile: configPath,
115
+ configErrors,
116
+ checks,
117
+ failed: failed.map((c) => c.id),
118
+ };
119
+ }
120
+
121
+ /** Generate a synthetic corpus so a first run needs no private data. */
122
+ export async function synthesize({ baseDir = process.cwd(), outDir = 'data', ...options } = {}) {
123
+ const dir = path.resolve(baseDir, outDir);
124
+ const written = await writeSyntheticCorpus(dir, options);
125
+ return { outDir: dir, ...written };
126
+ }
127
+
128
+ /** Run a real post-training job from a validated config. */
129
+ export async function train({
130
+ config,
131
+ configFile = null,
132
+ baseDir = process.cwd(),
133
+ jobId = null,
134
+ signal = null,
135
+ resume = true,
136
+ resumeCancelled = false,
137
+ auditEveryStep = 10,
138
+ } = {}) {
139
+ const resolved = config ?? (await loadConfig({ file: configFile, baseDir })).config;
140
+ await ensureBackends();
141
+ const backend = await resolveBackend(resolved.backend);
142
+ const job = await runTrainingJob({
143
+ jobId: jobId ?? `train-${resolved.project}`,
144
+ root: resolved.runRootAbsolute,
145
+ backend,
146
+ datasets: resolved.data.datasets,
147
+ baseDir: resolved.baseDir,
148
+ dataConfig: resolved.data.config,
149
+ modelConfig: resolved.model,
150
+ hyper: resolved.hyper,
151
+ trainBudget: resolved.trainBudget,
152
+ mode: resolved.mode,
153
+ seed: resolved.seed,
154
+ maxVocab: resolved.model.maxVocab,
155
+ maxSeqLen: resolved.model.maxSeqLen,
156
+ budget: resolved.budget,
157
+ signal,
158
+ resume,
159
+ resumeCancelled,
160
+ auditEveryStep,
161
+ });
162
+ return {
163
+ job,
164
+ artifacts: job.state === 'succeeded' ? trainingArtifacts(job) : null,
165
+ };
166
+ }
167
+
168
+ /** Durable status of a job: its state record plus a tail of the audit log. */
169
+ export async function status({ config = null, configFile = null, baseDir = process.cwd(), jobId, auditTail = 10 } = {}) {
170
+ if (!jobId) throw new Error('status requires jobId');
171
+ const resolved = config ?? (await loadConfig({ file: configFile, baseDir })).config;
172
+ const state = await readJobState(resolved.runRootAbsolute, jobId);
173
+ if (!state) return { jobId, found: false, state: null, audit: [] };
174
+ const audit = await readAuditLog(resolved.runRootAbsolute, jobId);
175
+ return {
176
+ jobId,
177
+ found: true,
178
+ state,
179
+ auditCount: audit.length,
180
+ audit: auditTail > 0 ? audit.slice(-auditTail) : [],
181
+ };
182
+ }
183
+
184
+ const EVAL_SPLITS = ['holdout', 'validation', 'train'];
185
+
186
+ /**
187
+ * Re-read the splits a training job wrote and encode them with the *saved*
188
+ * tokenizer, so an evaluation run depends on checkpoints on disk rather than
189
+ * on any state left behind by the trainer.
190
+ */
191
+ async function loadEvalSplits({ backend, artifacts, maxSeqLen }) {
192
+ const handle = await backend.loadModel({ file: artifacts.baseCheckpoint });
193
+ const records = {};
194
+ const encoded = {};
195
+ for (const split of EVAL_SPLITS) {
196
+ const file = path.join(artifacts.dataDir, `${split}.jsonl`);
197
+ if (!(await exists(file))) continue;
198
+ records[split] = await readJsonl(file);
199
+ // Same backend contract the training job uses: whichever side owns the
200
+ // tokenizer is the side that encodes, so evaluation never feeds a
201
+ // job-built vocabulary to a model that carries its own.
202
+ encoded[split] = typeof backend.prepareDataset === 'function'
203
+ ? (await backend.prepareDataset({ handle, records: records[split], maxSeqLen })).examples
204
+ : encodeRecords(records[split], handle.tokenizer, { maxSeqLen }).examples;
205
+ }
206
+ if (!encoded.holdout?.length) {
207
+ throw new Error(`evaluate: no encodable holdout split under ${artifacts.dataDir}`);
208
+ }
209
+ return { records, encoded };
210
+ }
211
+
212
+ /** Resolve the training artifacts an evaluate/export call should work from. */
213
+ async function resolveArtifacts({ artifacts, config, jobId }) {
214
+ if (artifacts) return artifacts;
215
+ const id = jobId ?? `train-${config.project}`;
216
+ const state = await readJobState(config.runRootAbsolute, id);
217
+ if (!state) throw new Error(`no durable job state for "${id}" under ${config.runRootAbsolute}; run tmf train first`);
218
+ // The state file keeps each step's output under completedSteps; rebuilding
219
+ // the step map from it is what lets evaluate/export run in a fresh process
220
+ // instead of only inside the one that trained.
221
+ const result = Object.fromEntries((state.completedSteps ?? [])
222
+ .filter((step) => step && typeof step === 'object' && step.name)
223
+ .map((step) => [step.name, step.output]));
224
+ return trainingArtifacts({ ...state, result });
225
+ }
226
+
227
+ /**
228
+ * Independent evaluation of a finished training job: baseline vs tuned on a
229
+ * holdout split that is checked for leakage, scored against the configured
230
+ * gates, and written to a durable report.
231
+ */
232
+ export async function evaluate({
233
+ config,
234
+ configFile = null,
235
+ baseDir = process.cwd(),
236
+ jobId = null,
237
+ artifacts = null,
238
+ gates = null,
239
+ reportFile = null,
240
+ maxNewTokens = 48,
241
+ } = {}) {
242
+ const resolved = config ?? (await loadConfig({ file: configFile, baseDir })).config;
243
+ await ensureBackends();
244
+ const backend = await resolveBackend(resolved.backend);
245
+ const resolvedArtifacts = await resolveArtifacts({ artifacts, config: resolved, jobId });
246
+ const { records, encoded } = await loadEvalSplits({
247
+ backend,
248
+ artifacts: resolvedArtifacts,
249
+ maxSeqLen: resolved.model.maxSeqLen,
250
+ });
251
+ const file = path.resolve(
252
+ resolved.baseDir,
253
+ reportFile ?? path.join(resolved.runRootAbsolute, resolvedArtifacts.jobId, 'eval-report.json'),
254
+ );
255
+ const report = await runEvaluationJob({
256
+ backend,
257
+ baseCheckpoint: resolvedArtifacts.baseCheckpoint,
258
+ adapterCheckpoint: resolvedArtifacts.adapterCheckpoint,
259
+ tunedCheckpoint: resolvedArtifacts.tunedCheckpoint ?? null,
260
+ encoded,
261
+ records,
262
+ gates: gates ?? resolved.eval?.gates ?? DEFAULT_GATES,
263
+ lineage: {
264
+ jobId: resolvedArtifacts.jobId,
265
+ project: resolved.project,
266
+ mode: resolved.mode,
267
+ seed: resolved.seed,
268
+ dataDir: resolvedArtifacts.dataDir,
269
+ dataReportFile: resolvedArtifacts.dataReportFile ?? null,
270
+ },
271
+ reportFile: file,
272
+ maxNewTokens,
273
+ jobId: resolvedArtifacts.jobId,
274
+ });
275
+ return { artifacts: resolvedArtifacts, report };
276
+ }
277
+
278
+ async function readPinnedReport(file, baseDir) {
279
+ const abs = path.resolve(baseDir ?? process.cwd(), file);
280
+ if (!(await exists(abs))) throw new Error(`eval report file not found: ${abs}`);
281
+ let parsed;
282
+ try {
283
+ parsed = await readJson(abs);
284
+ } catch (err) {
285
+ throw new Error(`eval report file is not valid JSON: ${abs} (${err.message})`);
286
+ }
287
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
288
+ throw new Error(`eval report file does not contain a report object: ${abs}`);
289
+ }
290
+ // Keep the on-disk location in the record so the bundle copies the reviewed
291
+ // file itself instead of re-serializing it.
292
+ return parsed.reportFile ? parsed : { ...parsed, reportFile: abs };
293
+ }
294
+
295
+ /**
296
+ * Package a deliverable bundle. The gate lives inside exportModel, so a
297
+ * failed or baseline-only evaluation cannot produce an export.
298
+ */
299
+ export async function exportModel({
300
+ config,
301
+ configFile = null,
302
+ baseDir = process.cwd(),
303
+ jobId = null,
304
+ artifacts = null,
305
+ evalReport = null,
306
+ outDir = null,
307
+ version = null,
308
+ evaluateIfMissing = true,
309
+ } = {}) {
310
+ const resolved = config ?? (await loadConfig({ file: configFile, baseDir })).config;
311
+ let resolvedArtifacts = artifacts;
312
+ // Hosts (Hermes / OpenClaw tool calls) can only hand over JSON scalars, so
313
+ // evalReport arrives as a path there while in-process callers pass the loaded
314
+ // report object. Resolve the path form here, once, rather than in each host
315
+ // adapter, so both entry points pin reports the same way.
316
+ let report = typeof evalReport === 'string' ? await readPinnedReport(evalReport, resolved.baseDir ?? baseDir) : evalReport;
317
+ if (!report) {
318
+ if (!evaluateIfMissing) throw new Error('exportModel requires an evalReport (or evaluateIfMissing)');
319
+ const run = await evaluate({ config: resolved, baseDir, jobId, artifacts });
320
+ resolvedArtifacts = run.artifacts;
321
+ report = run.report;
322
+ } else {
323
+ // An externally supplied report pins the bundle to numbers a human already
324
+ // reviewed, so it has to prove it has not been edited since.
325
+ assertReportIntegrity(report, { jobId });
326
+ resolvedArtifacts = await resolveArtifacts({ artifacts, config: resolved, jobId });
327
+ }
328
+ const target = path.resolve(resolved.baseDir, outDir ?? path.join(resolved.runRootAbsolute, resolvedArtifacts.jobId, 'export'));
329
+ const bundle = await packageExport({
330
+ outDir: target,
331
+ artifacts: resolvedArtifacts,
332
+ evalReport: report,
333
+ config: resolved,
334
+ name: resolved.project,
335
+ version: version ?? '0.1.0',
336
+ toolkitVersion: VERSION,
337
+ });
338
+ return { artifacts: resolvedArtifacts, report, bundle };
339
+ }
340
+
341
+ export { loadConfig, validateConfig, exampleConfig, ConfigError, probeBackends, listBackends };