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,124 @@
1
+ // Independent evaluation of a trained checkpoint.
2
+ //
3
+ // "Independent" means two concrete things. First, the evaluator only ever
4
+ // reads the holdout and validation splits, and it refuses to run at all if a
5
+ // holdout record also appears in train: a leaked holdout makes every number
6
+ // below meaningless. Second, it scores a model that was loaded back from a
7
+ // checkpoint file rather than the in-memory handle the trainer just finished
8
+ // with, so what gets measured is what would actually ship.
9
+
10
+ import { relativeImprovement, fieldAccuracy, characterF1, normalizedExactMatchScore } from './metrics.mjs';
11
+ import { sha256 } from '../core/hash.mjs';
12
+
13
+ export const EVAL_REPORT_FORMAT = 'tmf-eval-report-v1';
14
+
15
+ export function recordFingerprint(record) {
16
+ // Corpus records come in two shapes: supervised pairs (prompt/completion)
17
+ // and plain text. Keying only on the pair made every text-only record
18
+ // fingerprint as "undefined|undefined", which reported the whole holdout as
19
+ // leaked, so fall back to the text and refuse a record with neither.
20
+ const prompt = record?.prompt ?? null;
21
+ const completion = record?.completion ?? null;
22
+ if (prompt !== null || completion !== null) return sha256(`pair:${prompt}|${completion}`);
23
+ const text = record?.text ?? null;
24
+ if (text !== null) return sha256(`text:${text}`);
25
+ throw new Error('recordFingerprint needs a record with prompt/completion or text');
26
+ }
27
+
28
+ // Leakage is a gate, not a warning: a holdout set that overlaps train cannot
29
+ // be used to claim improvement, so this throws instead of annotating.
30
+ export function assertHoldoutIndependence({ holdout = [], train = [], validation = [] } = {}) {
31
+ if (!holdout.length) {
32
+ const err = new Error('evaluation needs a non-empty holdout split');
33
+ err.code = 'HOLDOUT_EMPTY';
34
+ throw err;
35
+ }
36
+ const trainPrints = new Set(train.map(recordFingerprint));
37
+ const leaked = holdout.filter((r) => trainPrints.has(recordFingerprint(r)));
38
+ if (leaked.length) {
39
+ const err = new Error(
40
+ `holdout is not independent: ${leaked.length}/${holdout.length} holdout records also appear in train`,
41
+ );
42
+ err.code = 'HOLDOUT_LEAKED';
43
+ err.leaked = leaked.map((r) => recordFingerprint(r).slice(0, 12));
44
+ throw err;
45
+ }
46
+ return {
47
+ ok: true,
48
+ holdout: holdout.length,
49
+ train: train.length,
50
+ validation: validation.length,
51
+ holdoutFingerprint: sha256(holdout.map(recordFingerprint).sort().join('')),
52
+ };
53
+ }
54
+
55
+ // Document-style records have no prompt/completion pair at all -- the data
56
+ // pipeline leaves both null for text-only rows -- so greedy decode can never
57
+ // score them. Keeping them in the denominator silently deflated accuracy (and
58
+ // fed the literal string 'null' to the tokenizer), so they are excluded here
59
+ // and reported separately instead.
60
+ export function isScorableRecord(record) {
61
+ return typeof record?.prompt === 'string' && typeof record?.completion === 'string';
62
+ }
63
+
64
+ export async function exactMatchOnRecords(backend, handle, records, { maxNewTokens = 48, sampleLimit = 3 } = {}) {
65
+ const scorable = records.filter(isScorableRecord);
66
+ const excluded = records.length - scorable.length;
67
+ let hit = 0;
68
+ const samples = [];
69
+ const predictions = [];
70
+ for (const record of scorable) {
71
+ const got = await backend.generate({ handle, prompt: record.prompt, maxNewTokens });
72
+ if (got === record.completion) hit += 1;
73
+ predictions.push({ predicted: got, expected: record.completion });
74
+ if (samples.length < sampleLimit) samples.push({ prompt: record.prompt, got, want: record.completion });
75
+ }
76
+ // The gated number stays byte-identical exact match. The three below are
77
+ // diagnostics only: with exact match pinned at 0 the report said nothing
78
+ // about *how* wrong the completions were, which is the difference between a
79
+ // formatting bug and an undertrained model.
80
+ return {
81
+ accuracy: scorable.length ? Number((hit / scorable.length).toFixed(6)) : null,
82
+ hit,
83
+ total: scorable.length,
84
+ considered: records.length,
85
+ excluded,
86
+ normalized: predictions.length ? normalizedExactMatchScore(predictions) : null,
87
+ fields: predictions.length ? fieldAccuracy(predictions) : null,
88
+ characterF1: predictions.length ? characterF1(predictions) : null,
89
+ samples,
90
+ };
91
+ }
92
+
93
+ // One model, both splits, plus greedy-decode exact match on holdout.
94
+ export async function evaluateSplitSet(backend, handle, { encoded, records = {}, maxNewTokens = 48 } = {}) {
95
+ if (!encoded?.holdout?.length) throw new Error('evaluateSplitSet needs encoded holdout examples');
96
+ const holdout = await backend.evaluate({ handle, examples: encoded.holdout });
97
+ const exactMatch = records.holdout?.some(isScorableRecord)
98
+ ? await exactMatchOnRecords(backend, handle, records.holdout, { maxNewTokens })
99
+ : null;
100
+ const validation = encoded.validation?.length
101
+ ? await backend.evaluate({ handle, examples: encoded.validation })
102
+ : null;
103
+ return { holdout: { ...holdout, exactMatch }, validation };
104
+ }
105
+
106
+ export function computeImprovement(baseline, tuned) {
107
+ const baseExact = baseline.holdout.exactMatch?.accuracy ?? null;
108
+ const tunedExact = tuned.holdout.exactMatch?.accuracy ?? null;
109
+ return {
110
+ holdoutLossRelative: relativeImprovement(baseline.holdout.loss, tuned.holdout.loss),
111
+ holdoutLossAbsolute: Number((baseline.holdout.loss - tuned.holdout.loss).toFixed(6)),
112
+ validationLossRelative: baseline.validation && tuned.validation
113
+ ? relativeImprovement(baseline.validation.loss, tuned.validation.loss)
114
+ : null,
115
+ exactMatchAbsolute: baseExact === null || tunedExact === null
116
+ ? null
117
+ : Number((tunedExact - baseExact).toFixed(6)),
118
+ };
119
+ }
120
+
121
+ export function assembleMetrics({ baseline, tuned }) {
122
+ if (!tuned) return { baseline, tuned: null, improvement: null };
123
+ return { baseline, tuned, improvement: computeImprovement(baseline, tuned) };
124
+ }
@@ -0,0 +1,114 @@
1
+ // Threshold gates.
2
+ //
3
+ // The gate is the thing that stops an unimproved model from being called an
4
+ // improvement. It is evaluated against the measured metrics object and returns
5
+ // a per-rule verdict; `assertGatesPass` is what export and delivery paths call,
6
+ // and a failure there is terminal rather than advisory.
7
+
8
+ export const COMPARATORS = {
9
+ gte: { test: (a, b) => a >= b, label: '>=' },
10
+ lte: { test: (a, b) => a <= b, label: '<=' },
11
+ gt: { test: (a, b) => a > b, label: '>' },
12
+ lt: { test: (a, b) => a < b, label: '<' },
13
+ };
14
+
15
+ // Exact match is a proportion, and a proportion over a handful of records is
16
+ // not a measurement. train-ws-full scored it on the 2 supervised pairs that
17
+ // landed in a 25-record holdout, where a single lucky completion reads as 0.5
18
+ // and clears the 0.25 threshold outright. A gate whose sample count is below
19
+ // this floor is reported as unmeasured and fails; the floor constrains the
20
+ // denominator only -- no threshold moves -- and 10 samples give the estimate
21
+ // the same 0.1 resolution as the improvement threshold it is compared with.
22
+ export const MIN_EXACT_MATCH_SAMPLES = 10;
23
+
24
+ export const DEFAULT_GATES = [
25
+ { id: 'holdout_loss_improvement', metric: 'improvement.holdoutLossRelative', comparator: 'gte', threshold: 0.3, description: 'post-training must cut holdout loss by at least 30% relative to the baseline' },
26
+ { id: 'holdout_loss_absolute', metric: 'tuned.holdout.loss', comparator: 'lte', threshold: 1.5, description: 'absolute holdout loss ceiling' },
27
+ { id: 'exact_match', metric: 'tuned.holdout.exactMatch.accuracy', comparator: 'gte', threshold: 0.25, sampleMetric: 'tuned.holdout.exactMatch.total', minSamples: MIN_EXACT_MATCH_SAMPLES, description: 'greedy-decoded completions must match exactly on at least a quarter of the holdout set' },
28
+ { id: 'exact_match_improvement', metric: 'improvement.exactMatchAbsolute', comparator: 'gte', threshold: 0.1, sampleMetric: 'tuned.holdout.exactMatch.total', minSamples: MIN_EXACT_MATCH_SAMPLES, description: 'exact match must improve over the baseline by at least 10 points' },
29
+ { id: 'no_validation_regression', metric: 'improvement.validationLossRelative', comparator: 'gte', threshold: -0.05, description: 'validation loss must not regress by more than 5% relative' },
30
+ ];
31
+
32
+ export function readMetric(metrics, dottedPath) {
33
+ return dottedPath.split('.').reduce((acc, key) => (acc === null || acc === undefined ? undefined : acc[key]), metrics);
34
+ }
35
+
36
+ export function evaluateGates(metrics, gates = DEFAULT_GATES) {
37
+ const results = gates.map((gate) => {
38
+ const comparator = COMPARATORS[gate.comparator];
39
+ if (!comparator) throw new Error(`unknown gate comparator "${gate.comparator}" on gate "${gate.id}"`);
40
+ const actual = readMetric(metrics, gate.metric);
41
+ if (actual === undefined || actual === null || Number.isNaN(actual)) {
42
+ return { ...gate, actual: actual ?? null, ok: false, reason: `metric "${gate.metric}" is missing from the evaluation report` };
43
+ }
44
+ if (gate.minSamples) {
45
+ const samples = gate.sampleMetric ? readMetric(metrics, gate.sampleMetric) : undefined;
46
+ if (typeof samples !== 'number' || Number.isNaN(samples)) {
47
+ return {
48
+ ...gate,
49
+ actual: typeof actual === 'number' ? Number(actual.toFixed(6)) : actual,
50
+ samples: null,
51
+ ok: false,
52
+ reason: `sample count "${gate.sampleMetric}" is missing, so ${gate.metric}=${actual} cannot be trusted`,
53
+ };
54
+ }
55
+ if (samples < gate.minSamples) {
56
+ return {
57
+ ...gate,
58
+ actual: typeof actual === 'number' ? Number(actual.toFixed(6)) : actual,
59
+ samples,
60
+ ok: false,
61
+ reason: `${gate.metric}=${actual} was measured on ${samples} scorable holdout record(s), below the minimum of ${gate.minSamples}; the estimate is not usable`,
62
+ };
63
+ }
64
+ }
65
+ const ok = comparator.test(actual, gate.threshold);
66
+ return {
67
+ ...gate,
68
+ actual: typeof actual === 'number' ? Number(actual.toFixed(6)) : actual,
69
+ ...(gate.minSamples ? { samples: readMetric(metrics, gate.sampleMetric) ?? null } : {}),
70
+ ok,
71
+ reason: ok ? null : `${gate.metric}=${actual} fails ${comparator.label} ${gate.threshold}`,
72
+ };
73
+ });
74
+ const failed = results.filter((r) => !r.ok);
75
+ return {
76
+ passed: failed.length === 0,
77
+ results,
78
+ failed: failed.map((r) => ({ id: r.id, reason: r.reason })),
79
+ summary: `${results.length - failed.length}/${results.length} gates passed`,
80
+ };
81
+ }
82
+
83
+ export function assertGatesPass(metrics, gates = DEFAULT_GATES) {
84
+ const verdict = evaluateGates(metrics, gates);
85
+ if (!verdict.passed) {
86
+ const err = new Error(
87
+ `evaluation gates failed (${verdict.summary}): ${verdict.failed.map((f) => f.reason).join('; ')}`,
88
+ );
89
+ err.code = 'GATES_FAILED';
90
+ err.verdict = verdict;
91
+ throw err;
92
+ }
93
+ return verdict;
94
+ }
95
+
96
+ // Regression check against a previously recorded evaluation of the same task.
97
+ export function checkRegression(current, previous, { tolerance = 0.02 } = {}) {
98
+ if (!previous) return { ok: true, checked: false, reason: 'no previous evaluation recorded' };
99
+ const findings = [];
100
+ const currentLoss = readMetric(current, 'tuned.holdout.loss');
101
+ const previousLoss = readMetric(previous, 'tuned.holdout.loss');
102
+ if (typeof currentLoss === 'number' && typeof previousLoss === 'number') {
103
+ const allowed = previousLoss * (1 + tolerance);
104
+ if (currentLoss > allowed) {
105
+ findings.push(`holdout loss regressed from ${previousLoss} to ${currentLoss} (allowed up to ${allowed.toFixed(6)})`);
106
+ }
107
+ }
108
+ const currentEm = readMetric(current, 'tuned.holdout.exactMatch.accuracy');
109
+ const previousEm = readMetric(previous, 'tuned.holdout.exactMatch.accuracy');
110
+ if (typeof currentEm === 'number' && typeof previousEm === 'number' && currentEm < previousEm - tolerance) {
111
+ findings.push(`exact match regressed from ${previousEm} to ${currentEm}`);
112
+ }
113
+ return { ok: findings.length === 0, checked: true, findings, tolerance };
114
+ }
@@ -0,0 +1,90 @@
1
+ // Evaluation metrics.
2
+ //
3
+ // Loss and perplexity come from the same forward pass the trainer uses; the
4
+ // generation metrics decode greedily so a reported number is reproducible from
5
+ // the checkpoint alone.
6
+
7
+ export function parseKeyValues(text) {
8
+ const out = {};
9
+ for (const line of String(text ?? '').split('\n')) {
10
+ const match = /^\s*([A-Za-z_][\w.-]*)\s*=\s*(.*?)\s*$/.exec(line);
11
+ if (match) out[match[1]] = match[2];
12
+ }
13
+ return out;
14
+ }
15
+
16
+ export function exactMatchScore(predictions) {
17
+ const hit = predictions.filter((p) => p.predicted === p.expected).length;
18
+ return { hit, total: predictions.length, accuracy: predictions.length ? hit / predictions.length : 0 };
19
+ }
20
+
21
+ // Diagnostic normalization: the gate metric stays byte-identical, but a
22
+ // completion that differs only in surrounding whitespace or blank lines is a
23
+ // different failure from one that got the content wrong, and a report that
24
+ // cannot tell them apart cannot direct the next experiment.
25
+ export function normalizeCompletion(text) {
26
+ return String(text ?? '')
27
+ .split('\n')
28
+ .map((line) => line.trim().replace(/\s+/g, ' '))
29
+ .filter((line) => line.length > 0)
30
+ .join('\n');
31
+ }
32
+
33
+ export function normalizedExactMatchScore(predictions) {
34
+ const hit = predictions.filter(
35
+ (p) => normalizeCompletion(p.predicted) === normalizeCompletion(p.expected),
36
+ ).length;
37
+ return { hit, total: predictions.length, accuracy: predictions.length ? Number((hit / predictions.length).toFixed(6)) : 0 };
38
+ }
39
+
40
+ // Per-field accuracy for structured completions: a model can get the queue
41
+ // right and the priority wrong, and the report should say so.
42
+ export function fieldAccuracy(predictions) {
43
+ const fields = new Map();
44
+ for (const p of predictions) {
45
+ const got = parseKeyValues(p.predicted);
46
+ const want = parseKeyValues(p.expected);
47
+ for (const key of Object.keys(want)) {
48
+ if (!fields.has(key)) fields.set(key, { field: key, hit: 0, total: 0 });
49
+ const entry = fields.get(key);
50
+ entry.total += 1;
51
+ if (got[key] === want[key]) entry.hit += 1;
52
+ }
53
+ }
54
+ return [...fields.values()]
55
+ .map((e) => ({ ...e, accuracy: e.total ? Number((e.hit / e.total).toFixed(6)) : 0 }))
56
+ .sort((a, b) => (a.field < b.field ? -1 : 1));
57
+ }
58
+
59
+ // Character-level similarity, so a near-miss is distinguishable from noise.
60
+ export function characterF1(predictions) {
61
+ let tp = 0;
62
+ let predLen = 0;
63
+ let goldLen = 0;
64
+ for (const p of predictions) {
65
+ const got = String(p.predicted ?? '');
66
+ const want = String(p.expected ?? '');
67
+ predLen += got.length;
68
+ goldLen += want.length;
69
+ const counts = new Map();
70
+ for (const ch of want) counts.set(ch, (counts.get(ch) ?? 0) + 1);
71
+ for (const ch of got) {
72
+ const left = counts.get(ch) ?? 0;
73
+ if (left > 0) {
74
+ tp += 1;
75
+ counts.set(ch, left - 1);
76
+ }
77
+ }
78
+ }
79
+ const precision = predLen ? tp / predLen : 0;
80
+ const recall = goldLen ? tp / goldLen : 0;
81
+ const f1 = precision + recall ? (2 * precision * recall) / (precision + recall) : 0;
82
+ return { precision: Number(precision.toFixed(6)), recall: Number(recall.toFixed(6)), f1: Number(f1.toFixed(6)) };
83
+ }
84
+
85
+ export function relativeImprovement(baseline, candidate, { lowerIsBetter = true } = {}) {
86
+ if (baseline === null || candidate === null || baseline === undefined || candidate === undefined) return null;
87
+ if (baseline === 0) return candidate === 0 ? 0 : (lowerIsBetter ? -Infinity : Infinity);
88
+ const raw = lowerIsBetter ? (baseline - candidate) / Math.abs(baseline) : (candidate - baseline) / Math.abs(baseline);
89
+ return Number(raw.toFixed(6));
90
+ }