taskforce-model-foundry 0.1.0 → 0.3.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.
- package/README.md +20 -2
- package/bin/tmf.mjs +53 -1
- package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +75 -0
- package/docs/external-quality.md +59 -0
- package/docs/integration.md +12 -9
- package/docs/releases/v0.2.0.md +24 -0
- package/docs/releases/v0.3.0.md +28 -0
- package/docs/tutorial.md +7 -3
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +1 -1
- package/integrations/openclaw-plugin/tools.mjs +4 -0
- package/openclaw.plugin.json +4 -1
- package/package.json +1 -1
- package/src/api.mjs +46 -2
- package/src/config.mjs +63 -5
- package/src/data/split.mjs +23 -8
- package/src/eval/evaluator.mjs +27 -3
- package/src/eval/external-quality.mjs +52 -0
- package/src/export/package.mjs +24 -6
- package/src/index.mjs +2 -0
- package/src/integrations/async-evaluate-worker.mjs +40 -0
- package/src/integrations/async-evaluate.mjs +130 -0
- package/src/integrations/async-train-worker.mjs +51 -0
- package/src/integrations/async-train.mjs +135 -0
- package/src/integrations/openclaw.mjs +38 -6
- package/src/jobs/evaluate.mjs +13 -5
- package/src/jobs/train.mjs +38 -14
- package/src/train/backends/hf-peft.mjs +117 -6
- package/src/train/backends/hf_peft_runner.py +217 -9
- package/src/version.mjs +1 -1
package/src/config.mjs
CHANGED
|
@@ -158,16 +158,43 @@ function validateGate(errors, at, raw) {
|
|
|
158
158
|
function validateEval(errors, at, raw) {
|
|
159
159
|
const evalRaw = requireObject(errors, at, raw, {});
|
|
160
160
|
for (const key of Object.keys(evalRaw)) {
|
|
161
|
-
if (
|
|
161
|
+
if (!['gates', 'externalQuality'].includes(key)) errors.add(`${at}.${key}`, 'unknown eval key (allowed: gates, externalQuality)');
|
|
162
162
|
}
|
|
163
|
-
|
|
163
|
+
const result = {};
|
|
164
|
+
if (evalRaw.externalQuality !== undefined) {
|
|
165
|
+
const quality = requireObject(errors, `${at}.externalQuality`, evalRaw.externalQuality, {});
|
|
166
|
+
for (const key of Object.keys(quality)) {
|
|
167
|
+
if (!['suiteSha256', 'scorerSha256', 'gates', 'profile', 'references'].includes(key)) errors.add(`${at}.externalQuality.${key}`, 'unknown external quality key');
|
|
168
|
+
}
|
|
169
|
+
for (const key of ['suiteSha256', 'scorerSha256']) {
|
|
170
|
+
if (typeof quality[key] !== 'string' || !/^[a-f0-9]{64}$/.test(quality[key])) errors.add(`${at}.externalQuality.${key}`, 'must be a lowercase SHA-256 digest');
|
|
171
|
+
}
|
|
172
|
+
if (!Array.isArray(quality.gates) || quality.gates.length === 0) {
|
|
173
|
+
errors.add(`${at}.externalQuality.gates`, 'must contain at least one predeclared gate');
|
|
174
|
+
} else {
|
|
175
|
+
const gates = quality.gates.map((gate, i) => validateGate(errors, `${at}.externalQuality.gates[${i}]`, gate)).filter(Boolean);
|
|
176
|
+
if (new Set(gates.map((gate) => gate.id)).size !== gates.length) errors.add(`${at}.externalQuality.gates`, 'duplicate gate id');
|
|
177
|
+
result.externalQuality = { suiteSha256: quality.suiteSha256, scorerSha256: quality.scorerSha256, gates };
|
|
178
|
+
if (quality.profile !== undefined) result.externalQuality.profile = requireString(errors, `${at}.externalQuality.profile`, quality.profile, null);
|
|
179
|
+
if (quality.references !== undefined) {
|
|
180
|
+
const refs = requireObject(errors, `${at}.externalQuality.references`, quality.references, {});
|
|
181
|
+
for (const [name, digest] of Object.entries(refs)) {
|
|
182
|
+
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name) || typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {
|
|
183
|
+
errors.add(`${at}.externalQuality.references.${name}`, 'must be a named lowercase SHA-256 digest');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
result.externalQuality.references = refs;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (evalRaw.gates === undefined) return result;
|
|
164
191
|
if (!Array.isArray(evalRaw.gates)) {
|
|
165
192
|
errors.add(`${at}.gates`, 'must be an array of gate objects');
|
|
166
|
-
return
|
|
193
|
+
return result;
|
|
167
194
|
}
|
|
168
195
|
if (evalRaw.gates.length === 0) {
|
|
169
196
|
errors.add(`${at}.gates`, 'must declare at least one gate; omit `eval.gates` to use the built-in defaults');
|
|
170
|
-
return
|
|
197
|
+
return result;
|
|
171
198
|
}
|
|
172
199
|
const gates = evalRaw.gates.map((gate, i) => validateGate(errors, `${at}.gates[${i}]`, gate)).filter(Boolean);
|
|
173
200
|
const seen = new Set();
|
|
@@ -176,7 +203,7 @@ function validateEval(errors, at, raw) {
|
|
|
176
203
|
if (seen.has(gate.id)) errors.add(`${at}.gates`, `duplicate gate id "${gate.id}"`);
|
|
177
204
|
seen.add(gate.id);
|
|
178
205
|
}
|
|
179
|
-
return { gates };
|
|
206
|
+
return { ...result, gates };
|
|
180
207
|
}
|
|
181
208
|
|
|
182
209
|
// Hyperparameters are a whitelist rather than a free-form bag: an unknown key
|
|
@@ -215,6 +242,36 @@ function validateHyper(errors, at, raw) {
|
|
|
215
242
|
return out;
|
|
216
243
|
}
|
|
217
244
|
|
|
245
|
+
const HF_OPTIONS = new Set([
|
|
246
|
+
'loadIn4Bit', 'quantType', 'doubleQuant', 'dtype', 'gradientCheckpointing',
|
|
247
|
+
'gradientAccumulationSteps', 'lrScheduler', 'warmupSteps', 'optimizer', 'maxGradNorm',
|
|
248
|
+
'maxMemoryMb', 'evalMaxSeconds',
|
|
249
|
+
]);
|
|
250
|
+
|
|
251
|
+
function validateHfOptions(errors, raw) {
|
|
252
|
+
const hf = requireObject(errors, 'model.hf', raw, {});
|
|
253
|
+
for (const [key, value] of Object.entries(hf)) {
|
|
254
|
+
if (!HF_OPTIONS.has(key)) {
|
|
255
|
+
errors.add(`model.hf.${key}`, 'unknown HF option');
|
|
256
|
+
} else if (['loadIn4Bit', 'doubleQuant', 'gradientCheckpointing'].includes(key) && typeof value !== 'boolean') {
|
|
257
|
+
errors.add(`model.hf.${key}`, 'must be boolean');
|
|
258
|
+
} else if (['quantType', 'dtype', 'lrScheduler', 'optimizer'].includes(key) &&
|
|
259
|
+
(typeof value !== 'string' || !value.trim())) {
|
|
260
|
+
errors.add(`model.hf.${key}`, 'must be a non-empty string');
|
|
261
|
+
} else if (['gradientAccumulationSteps', 'warmupSteps', 'maxMemoryMb', 'evalMaxSeconds'].includes(key) &&
|
|
262
|
+
(!Number.isInteger(value) || value < (key === 'warmupSteps' ? 0 : 1))) {
|
|
263
|
+
errors.add(`model.hf.${key}`, 'must be a non-negative or positive integer');
|
|
264
|
+
} else if (key === 'maxGradNorm' && (typeof value !== 'number' || value <= 0)) {
|
|
265
|
+
errors.add(`model.hf.${key}`, 'must be a positive number');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (hf.quantType !== undefined && hf.quantType !== 'nf4') errors.add('model.hf.quantType', 'only nf4 is supported');
|
|
269
|
+
if (hf.dtype !== undefined && !['float32', 'bfloat16'].includes(hf.dtype)) {
|
|
270
|
+
errors.add('model.hf.dtype', 'must be float32 or bfloat16');
|
|
271
|
+
}
|
|
272
|
+
return hf;
|
|
273
|
+
}
|
|
274
|
+
|
|
218
275
|
/**
|
|
219
276
|
* Validate and normalize a raw config object.
|
|
220
277
|
*
|
|
@@ -244,6 +301,7 @@ export function validateConfig(raw, { baseDir = process.cwd() } = {}) {
|
|
|
244
301
|
maxVocab: requirePositiveInt(errors, 'model.maxVocab', modelRaw.maxVocab, CONFIG_DEFAULTS.model.maxVocab),
|
|
245
302
|
maxSeqLen: requirePositiveInt(errors, 'model.maxSeqLen', modelRaw.maxSeqLen, CONFIG_DEFAULTS.model.maxSeqLen),
|
|
246
303
|
};
|
|
304
|
+
if (modelRaw.hf !== undefined) model.hf = validateHfOptions(errors, modelRaw.hf);
|
|
247
305
|
|
|
248
306
|
const dataRaw = requireObject(errors, 'data', raw.data, {});
|
|
249
307
|
const datasets = validateDatasets(errors, dataRaw.datasets ?? []);
|
package/src/data/split.mjs
CHANGED
|
@@ -73,15 +73,30 @@ function assignStratum(records, cfg) {
|
|
|
73
73
|
|
|
74
74
|
export function splitRecords(records, config = {}) {
|
|
75
75
|
const cfg = { ...DEFAULT_SPLIT_CONFIG, ...config };
|
|
76
|
-
const
|
|
77
|
-
if (
|
|
78
|
-
throw new Error(
|
|
76
|
+
const fixed = cfg.datasetAssignments;
|
|
77
|
+
if (fixed !== undefined && (fixed === null || typeof fixed !== 'object' || Array.isArray(fixed))) {
|
|
78
|
+
throw new Error('split.datasetAssignments must map dataset names to train, validation or holdout');
|
|
79
79
|
}
|
|
80
|
-
|
|
81
|
-
|
|
80
|
+
if (!fixed) {
|
|
81
|
+
const total = cfg.train + cfg.validation + cfg.holdout;
|
|
82
|
+
if (Math.abs(total - 1) > 1e-6) {
|
|
83
|
+
throw new Error(`split ratios must sum to 1, got ${total} (train=${cfg.train}, validation=${cfg.validation}, holdout=${cfg.holdout})`);
|
|
84
|
+
}
|
|
85
|
+
for (const name of SPLIT_NAMES) {
|
|
86
|
+
if (cfg[name] < 0) throw new Error(`split ratio "${name}" must not be negative`);
|
|
87
|
+
}
|
|
82
88
|
}
|
|
83
89
|
const splits = { train: [], validation: [], holdout: [] };
|
|
84
|
-
if (
|
|
90
|
+
if (fixed) {
|
|
91
|
+
for (const record of records) {
|
|
92
|
+
const source = record.source?.dataset;
|
|
93
|
+
const name = fixed[source];
|
|
94
|
+
if (!SPLIT_NAMES.includes(name)) {
|
|
95
|
+
throw new Error(`split.datasetAssignments has no valid assignment for dataset "${source}"`);
|
|
96
|
+
}
|
|
97
|
+
splits[name].push({ ...record, split: name, stratum: splitStratum(record) });
|
|
98
|
+
}
|
|
99
|
+
} else if (cfg.stratify) {
|
|
85
100
|
const strata = new Map();
|
|
86
101
|
for (const record of records) {
|
|
87
102
|
const stratum = splitStratum(record);
|
|
@@ -104,7 +119,7 @@ export function splitRecords(records, config = {}) {
|
|
|
104
119
|
}
|
|
105
120
|
// A holdout with no supervised pair cannot produce an exact-match number at
|
|
106
121
|
// all, which is a silent hole in evaluation rather than a bad score.
|
|
107
|
-
if (cfg.requireScorableHoldout && cfg.holdout > 0) {
|
|
122
|
+
if (cfg.requireScorableHoldout && (fixed || cfg.holdout > 0)) {
|
|
108
123
|
const pairsAvailable = records.some((r) => splitStratum(r) === 'pair');
|
|
109
124
|
const pairsHeldOut = splits.holdout.some((r) => splitStratum(r) === 'pair');
|
|
110
125
|
if (pairsAvailable && !pairsHeldOut) {
|
|
@@ -114,7 +129,7 @@ export function splitRecords(records, config = {}) {
|
|
|
114
129
|
const scorable = splits.holdout.filter((r) => splitStratum(r) === 'pair').length;
|
|
115
130
|
if (pairsAvailable && scorable < minScorable) {
|
|
116
131
|
const pairs = records.filter((r) => splitStratum(r) === 'pair').length;
|
|
117
|
-
const needed = Math.ceil(minScorable / cfg.holdout);
|
|
132
|
+
const needed = fixed ? minScorable : Math.ceil(minScorable / cfg.holdout);
|
|
118
133
|
throw new Error(
|
|
119
134
|
`holdout has ${scorable} scorable pair(s), below the minimum ${minScorable}: `
|
|
120
135
|
+ `the corpus carries ${pairs} supervised pair(s) and a ${cfg.holdout} holdout share, `
|
package/src/eval/evaluator.mjs
CHANGED
|
@@ -61,16 +61,28 @@ export function isScorableRecord(record) {
|
|
|
61
61
|
return typeof record?.prompt === 'string' && typeof record?.completion === 'string';
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
export async function exactMatchOnRecords(backend, handle, records, { maxNewTokens = 48, sampleLimit = 3 } = {}) {
|
|
64
|
+
export async function exactMatchOnRecords(backend, handle, records, { maxNewTokens = 48, sampleLimit = 3, generatedTexts = null } = {}) {
|
|
65
65
|
const scorable = records.filter(isScorableRecord);
|
|
66
66
|
const excluded = records.length - scorable.length;
|
|
67
67
|
let hit = 0;
|
|
68
68
|
const samples = [];
|
|
69
69
|
const predictions = [];
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
const predictionDigests = [];
|
|
71
|
+
// Backends that own a large model may load it once and generate each prompt
|
|
72
|
+
// sequentially. The result order and exact-match definition stay identical.
|
|
73
|
+
const generated = generatedTexts ?? (scorable.length && typeof backend.generateBatch === 'function'
|
|
74
|
+
? await backend.generateBatch({ handle, prompts: scorable.map((record) => record.prompt), maxNewTokens })
|
|
75
|
+
: null);
|
|
76
|
+
if (generated && (!Array.isArray(generated) || generated.length !== scorable.length)) {
|
|
77
|
+
throw new Error(`generateBatch returned ${generated?.length ?? 'invalid'} result(s) for ${scorable.length} prompt(s)`);
|
|
78
|
+
}
|
|
79
|
+
for (let index = 0; index < scorable.length; index += 1) {
|
|
80
|
+
const record = scorable[index];
|
|
81
|
+
const got = generated ? generated[index] : await backend.generate({ handle, prompt: record.prompt, maxNewTokens });
|
|
82
|
+
if (typeof got !== 'string') throw new Error(`generation result ${index} is not a string`);
|
|
72
83
|
if (got === record.completion) hit += 1;
|
|
73
84
|
predictions.push({ predicted: got, expected: record.completion });
|
|
85
|
+
predictionDigests.push({ record: recordFingerprint(record), output: sha256(got) });
|
|
74
86
|
if (samples.length < sampleLimit) samples.push({ prompt: record.prompt, got, want: record.completion });
|
|
75
87
|
}
|
|
76
88
|
// The gated number stays byte-identical exact match. The three below are
|
|
@@ -86,6 +98,7 @@ export async function exactMatchOnRecords(backend, handle, records, { maxNewToke
|
|
|
86
98
|
normalized: predictions.length ? normalizedExactMatchScore(predictions) : null,
|
|
87
99
|
fields: predictions.length ? fieldAccuracy(predictions) : null,
|
|
88
100
|
characterF1: predictions.length ? characterF1(predictions) : null,
|
|
101
|
+
predictionDigests,
|
|
89
102
|
samples,
|
|
90
103
|
};
|
|
91
104
|
}
|
|
@@ -93,6 +106,17 @@ export async function exactMatchOnRecords(backend, handle, records, { maxNewToke
|
|
|
93
106
|
// One model, both splits, plus greedy-decode exact match on holdout.
|
|
94
107
|
export async function evaluateSplitSet(backend, handle, { encoded, records = {}, maxNewTokens = 48 } = {}) {
|
|
95
108
|
if (!encoded?.holdout?.length) throw new Error('evaluateSplitSet needs encoded holdout examples');
|
|
109
|
+
if (typeof backend.evaluateSplitSet === 'function') {
|
|
110
|
+
const scorable = (records.holdout ?? []).filter(isScorableRecord);
|
|
111
|
+
const combined = await backend.evaluateSplitSet({
|
|
112
|
+
handle, holdoutExamples: encoded.holdout, validationExamples: encoded.validation ?? [],
|
|
113
|
+
prompts: scorable.map((record) => record.prompt), maxNewTokens,
|
|
114
|
+
});
|
|
115
|
+
const exactMatch = scorable.length
|
|
116
|
+
? await exactMatchOnRecords(backend, handle, records.holdout, { maxNewTokens, generatedTexts: combined.texts })
|
|
117
|
+
: null;
|
|
118
|
+
return { holdout: { ...combined.holdout, exactMatch }, validation: combined.validation };
|
|
119
|
+
}
|
|
96
120
|
const holdout = await backend.evaluate({ handle, examples: encoded.holdout });
|
|
97
121
|
const exactMatch = records.holdout?.some(isScorableRecord)
|
|
98
122
|
? await exactMatchOnRecords(backend, handle, records.holdout, { maxNewTokens })
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Bind an independently scored, predeclared quality suite to a trained job.
|
|
2
|
+
// The scorer is outside Foundry; Foundry verifies its evidence and gates.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readJson } from '../core/fsx.mjs';
|
|
5
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
6
|
+
import { evaluateGates, readMetric } from './gates.mjs';
|
|
7
|
+
import { ExportBlockedError } from '../export/package.mjs';
|
|
8
|
+
|
|
9
|
+
export const EXTERNAL_QUALITY_FORMAT = 'tmf.external-quality/v1';
|
|
10
|
+
export const externalQualityContractDigest = (contract) => sha256Json(contract);
|
|
11
|
+
|
|
12
|
+
// Convenience for an external scorer. This is an integrity checksum, not a
|
|
13
|
+
// signature or proof that the scorer's measurements are truthful.
|
|
14
|
+
export function sealExternalQualityEvidence(report) {
|
|
15
|
+
return { ...report, reportDigest: sha256Json({ ...report, reportDigest: undefined }) };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function blocked(message, failed = []) {
|
|
19
|
+
throw new ExportBlockedError(`export blocked: ${message}`, { status: 'external_quality', failed });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function verifyExternalQuality({ contract, evidence, artifacts, evalReport, baseDir }) {
|
|
23
|
+
if (!evidence) blocked('predeclared external quality evidence is missing');
|
|
24
|
+
if (typeof evidence !== 'string') blocked('external quality evidence must be a report file path');
|
|
25
|
+
const file = path.resolve(baseDir, evidence);
|
|
26
|
+
let report;
|
|
27
|
+
try { report = await readJson(file); } catch (err) { blocked(`external quality report is unreadable: ${err.message}`); }
|
|
28
|
+
if (!report || report.format !== EXTERNAL_QUALITY_FORMAT) blocked('external quality report format mismatch');
|
|
29
|
+
if (contract.profile && report.profile !== contract.profile) blocked('external quality profile differs from the frozen contract');
|
|
30
|
+
const digest = sha256Json({ ...report, reportDigest: undefined });
|
|
31
|
+
if (report.reportDigest !== digest) blocked('external quality report digest mismatch');
|
|
32
|
+
if (report.jobId !== artifacts.jobId) blocked('external quality report belongs to another job');
|
|
33
|
+
if (report.suiteSha256 !== contract.suiteSha256 || report.scorerSha256 !== contract.scorerSha256) {
|
|
34
|
+
blocked('external quality suite/scorer differs from the predeclared contract');
|
|
35
|
+
}
|
|
36
|
+
if (report.contractDigest !== sha256Json(contract)) blocked('external quality contract digest mismatch');
|
|
37
|
+
if (report.evalReportDigest !== evalReport.reportDigest) blocked('external quality report is bound to a different technical evaluation');
|
|
38
|
+
if (!evalReport.lineage?.tunedFingerprint || report.tunedFingerprint !== evalReport.lineage.tunedFingerprint) {
|
|
39
|
+
blocked('external quality report is bound to a different tuned model fingerprint');
|
|
40
|
+
}
|
|
41
|
+
const checkpoint = artifacts.adapterCheckpoint ?? artifacts.tunedCheckpoint;
|
|
42
|
+
if (!checkpoint || report.checkpointSha256 !== await sha256File(checkpoint)) blocked('external quality report is bound to a different trained checkpoint');
|
|
43
|
+
for (const gate of contract.gates) {
|
|
44
|
+
if (!Number.isFinite(readMetric(report.metrics, gate.metric))) blocked(`external quality metric ${gate.metric} is not a finite number`);
|
|
45
|
+
if (gate.minSamples && !Number.isInteger(readMetric(report.metrics, gate.sampleMetric))) {
|
|
46
|
+
blocked(`external quality sample count ${gate.sampleMetric} is not an integer`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const gates = evaluateGates(report.metrics ?? {}, contract.gates);
|
|
50
|
+
if (!gates.passed) blocked(`external quality gates failed (${gates.summary})`, gates.failed.map((gate) => gate.id));
|
|
51
|
+
return { file, fileSha256: await sha256File(file), report, gates, contractDigest: sha256Json(contract) };
|
|
52
|
+
}
|
package/src/export/package.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import path from 'node:path';
|
|
|
10
10
|
import { copyFile, readFile, readdir } from 'node:fs/promises';
|
|
11
11
|
import { ensureDir, writeJson, writeFileAtomic, exists } from '../core/fsx.mjs';
|
|
12
12
|
import { sha256File, sha256Json, stableStringify } from '../core/hash.mjs';
|
|
13
|
+
import { VERSION } from '../version.mjs';
|
|
13
14
|
|
|
14
15
|
export const EXPORT_FORMAT = 'tmf.export/v1';
|
|
15
16
|
|
|
@@ -59,6 +60,12 @@ function metricSummary(report) {
|
|
|
59
60
|
};
|
|
60
61
|
}
|
|
61
62
|
|
|
63
|
+
function isSyntheticData(config) {
|
|
64
|
+
const datasets = config?.data?.datasets;
|
|
65
|
+
return Array.isArray(datasets) && datasets.length > 0 && datasets.every((dataset) =>
|
|
66
|
+
dataset === 'synthetic' || dataset?.source === 'synthetic' || dataset?.license === 'synthetic');
|
|
67
|
+
}
|
|
68
|
+
|
|
62
69
|
function renderModelCard({ name, version, createdAt, report, artifacts, config, files }) {
|
|
63
70
|
const s = metricSummary(report);
|
|
64
71
|
const num = (v) => (typeof v === 'number' ? v.toFixed(6) : 'n/a');
|
|
@@ -72,9 +79,9 @@ Exported ${createdAt} by taskforce-model-foundry.
|
|
|
72
79
|
|
|
73
80
|
## What this is
|
|
74
81
|
|
|
75
|
-
|
|
76
|
-
toolkit**. It is a demonstration-scale artifact
|
|
77
|
-
|
|
82
|
+
${isSyntheticData(config)
|
|
83
|
+
? 'A small post-trained model produced from **synthetic data generated by this toolkit**. It is a demonstration-scale artifact, not a claim of fitness for production use.'
|
|
84
|
+
: 'A post-trained model. Inspect the dataset provenance and independent evaluation reports before making any fitness-for-use claim.'}
|
|
78
85
|
|
|
79
86
|
- Mode: \`${config?.mode ?? artifacts?.metrics?.mode ?? 'unknown'}\`
|
|
80
87
|
- Backend: \`${report.backend?.id ?? 'unknown'}\`
|
|
@@ -244,9 +251,10 @@ export async function exportModel({
|
|
|
244
251
|
outDir,
|
|
245
252
|
artifacts,
|
|
246
253
|
evalReport,
|
|
254
|
+
externalQuality = null,
|
|
247
255
|
config = null,
|
|
248
256
|
name = config?.project ?? 'taskforce-model',
|
|
249
|
-
version =
|
|
257
|
+
version = VERSION,
|
|
250
258
|
toolkitVersion = null,
|
|
251
259
|
clock = () => new Date().toISOString(),
|
|
252
260
|
}) {
|
|
@@ -264,6 +272,7 @@ export async function exportModel({
|
|
|
264
272
|
artifacts.tunedCheckpoint ? { from: artifacts.tunedCheckpoint, to: 'weights/tuned.json', role: 'tuned' } : null,
|
|
265
273
|
artifacts.dataReportFile ? { from: artifacts.dataReportFile, to: 'data-report.json', role: 'data-report' } : null,
|
|
266
274
|
evalReport.reportFile ? { from: evalReport.reportFile, to: 'eval-report.json', role: 'eval-report' } : null,
|
|
275
|
+
externalQuality ? { from: externalQuality.file, to: 'external-quality-report.json', role: 'external-quality-report' } : null,
|
|
267
276
|
].filter(Boolean);
|
|
268
277
|
|
|
269
278
|
const files = [];
|
|
@@ -271,7 +280,11 @@ export async function exportModel({
|
|
|
271
280
|
if (!(await exists(copy.from))) throw new Error(`exportModel: missing input ${copy.role}: ${copy.from}`);
|
|
272
281
|
const dest = path.join(root, copy.to);
|
|
273
282
|
await copyFile(copy.from, dest);
|
|
274
|
-
|
|
283
|
+
const copiedSha256 = await sha256File(dest);
|
|
284
|
+
if (copy.role === 'external-quality-report' && copiedSha256 !== externalQuality.fileSha256) {
|
|
285
|
+
throw new Error('external quality evidence changed between verification and export copy');
|
|
286
|
+
}
|
|
287
|
+
files.push({ path: copy.to, role: copy.role, sha256: copiedSha256, source: copy.from });
|
|
275
288
|
}
|
|
276
289
|
// A `hf-peft` checkpoint file is a *pointer*: it names a local model dir and
|
|
277
290
|
// an adapter dir rather than carrying weights. Copying only the pointer would
|
|
@@ -296,7 +309,7 @@ export async function exportModel({
|
|
|
296
309
|
reportFile: artifacts.dataReportFile ?? null,
|
|
297
310
|
splits: evalReport.inputs?.splits ?? null,
|
|
298
311
|
datasets: config?.data?.datasets ?? null,
|
|
299
|
-
synthetic:
|
|
312
|
+
synthetic: isSyntheticData(config),
|
|
300
313
|
},
|
|
301
314
|
parameters: {
|
|
302
315
|
mode: config?.mode ?? null,
|
|
@@ -316,6 +329,11 @@ export async function exportModel({
|
|
|
316
329
|
gates: evalReport.gates?.results ?? [],
|
|
317
330
|
lineage: evalReport.lineage ?? null,
|
|
318
331
|
},
|
|
332
|
+
externalQuality: externalQuality ? {
|
|
333
|
+
reportDigest: externalQuality.report.reportDigest,
|
|
334
|
+
contractDigest: externalQuality.contractDigest,
|
|
335
|
+
gates: externalQuality.gates.results,
|
|
336
|
+
} : null,
|
|
319
337
|
baseCheckpoint: files.find((f) => f.role === 'base')?.sha256 ?? null,
|
|
320
338
|
};
|
|
321
339
|
|
package/src/index.mjs
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
export { PRODUCT, doctor, synthesize, train, status, evaluate } from './api.mjs';
|
|
8
8
|
export { exportModel as exportBundle } from './api.mjs';
|
|
9
|
+
export { qualityContext } from './api.mjs';
|
|
9
10
|
export {
|
|
10
11
|
CONFIG_FORMAT, CONFIG_DEFAULTS, validateConfig, loadConfig, findConfigFile,
|
|
11
12
|
exampleConfig, formatConfigErrors, ConfigError,
|
|
@@ -17,6 +18,7 @@ export * as jobs from './jobs/runner.mjs';
|
|
|
17
18
|
export * as trainJob from './jobs/train.mjs';
|
|
18
19
|
export * as evalJob from './jobs/evaluate.mjs';
|
|
19
20
|
export * as gates from './eval/gates.mjs';
|
|
21
|
+
export * as externalQuality from './eval/external-quality.mjs';
|
|
20
22
|
export * as backends from './train/backends/index.mjs';
|
|
21
23
|
export * as exporter from './export/package.mjs';
|
|
22
24
|
export { exportModel, assertDeliverable, ExportBlockedError, EXPORT_FORMAT } from './export/package.mjs';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readJson, writeJson } from '../core/fsx.mjs';
|
|
2
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
3
|
+
import { evaluate } from '../api.mjs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const [, , requestFile, statusFile] = process.argv;
|
|
7
|
+
if (!requestFile || !statusFile) throw new Error('worker requires request and status files');
|
|
8
|
+
const request = await readJson(requestFile);
|
|
9
|
+
const old = await readJson(statusFile);
|
|
10
|
+
if (old.requestId !== request.requestId || old.attempt !== request.attempt) {
|
|
11
|
+
throw new Error('background request attempt no longer owns the status file');
|
|
12
|
+
}
|
|
13
|
+
if (await sha256File(request.configFile) !== request.configDigest) {
|
|
14
|
+
throw new Error('background request config changed since submission');
|
|
15
|
+
}
|
|
16
|
+
process.env.TMF_DEVICE = request.device;
|
|
17
|
+
process.env.TMF_PYTHON = request.pythonBin;
|
|
18
|
+
if (request.hfMaxMemoryMb !== null) process.env.TMF_HF_MAX_MEMORY_MB = request.hfMaxMemoryMb;
|
|
19
|
+
// The HF backend uses cwd for its transient spec/output directories. Keep
|
|
20
|
+
// separate background requests from racing on those files.
|
|
21
|
+
process.chdir(path.dirname(statusFile));
|
|
22
|
+
const common = { ...old };
|
|
23
|
+
await writeJson(statusFile, { ...common, state: 'running', pid: process.pid, startedAt: new Date().toISOString() });
|
|
24
|
+
try {
|
|
25
|
+
const { report } = await evaluate({ ...request, reportFile: request.stageReportFile });
|
|
26
|
+
const published = { ...report, backgroundRequest: { requestId: request.requestId, attempt: request.attempt } };
|
|
27
|
+
delete published.reportFile;
|
|
28
|
+
published.reportDigest = sha256Json({ ...published, reportDigest: undefined });
|
|
29
|
+
await writeJson(request.reportFile, published);
|
|
30
|
+
await writeJson(statusFile, {
|
|
31
|
+
...common, state: 'succeeded', pid: process.pid, finishedAt: new Date().toISOString(),
|
|
32
|
+
reportDigest: published.reportDigest, verdict: published.verdict, gates: published.gates,
|
|
33
|
+
});
|
|
34
|
+
} catch (err) {
|
|
35
|
+
await writeJson(statusFile, {
|
|
36
|
+
...common, state: 'failed', pid: process.pid, finishedAt: new Date().toISOString(),
|
|
37
|
+
error: { code: err?.code ?? 'action-failed', message: err?.message ?? String(err) },
|
|
38
|
+
});
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Background evaluations use a transient user service when available, outside
|
|
2
|
+
// the Gateway cgroup. Every attempt owns its report; old output is never proof
|
|
3
|
+
// that a new attempt finished.
|
|
4
|
+
import { spawn, execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { open, mkdir } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { loadConfig } from '../config.mjs';
|
|
10
|
+
import { ensureDir, exists, readJsonIfExists, writeJson } from '../core/fsx.mjs';
|
|
11
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
12
|
+
|
|
13
|
+
const workerFile = fileURLToPath(new URL('./async-evaluate-worker.mjs', import.meta.url));
|
|
14
|
+
const execFileAsync = promisify(execFile);
|
|
15
|
+
|
|
16
|
+
export function requireJobId(jobId) {
|
|
17
|
+
if (typeof jobId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(jobId) || jobId === '..') {
|
|
18
|
+
throw new Error('background work requires a safe, explicit jobId');
|
|
19
|
+
}
|
|
20
|
+
return jobId;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function location({ baseDir, configFile, jobId, requestId }) {
|
|
24
|
+
const { file, config } = await loadConfig({ file: configFile, baseDir });
|
|
25
|
+
const root = path.join(config.runRootAbsolute, requireJobId(jobId), 'plugin-evaluations');
|
|
26
|
+
const dir = path.join(root, requestId);
|
|
27
|
+
return { file, root, dir, statusFile: path.join(dir, 'status.json') };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function reportMatches(report, status) {
|
|
31
|
+
if (report?.backgroundRequest?.requestId !== status.requestId || report?.backgroundRequest?.attempt !== status.attempt) return false;
|
|
32
|
+
return report.reportDigest === sha256Json({ ...report, reportDigest: undefined });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function launchBackgroundWorker(workerPath, requestFile, statusFile, unit, logFile) {
|
|
36
|
+
const launcher = process.env.TMF_BACKGROUND_LAUNCHER ?? process.env.TMF_EVAL_LAUNCHER;
|
|
37
|
+
if (launcher !== 'direct' && process.platform === 'linux') {
|
|
38
|
+
try {
|
|
39
|
+
await execFileAsync('systemd-run', ['--user', '--collect', '--unit=' + unit, process.execPath, workerPath, requestFile, statusFile], { timeout: 10000 });
|
|
40
|
+
return { launcher: 'systemd', unit, restartDurable: true };
|
|
41
|
+
} catch (err) {
|
|
42
|
+
if (launcher === 'systemd') throw err;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const log = await open(logFile, 'a');
|
|
46
|
+
try {
|
|
47
|
+
const child = spawn(process.execPath, [workerPath, requestFile, statusFile], {
|
|
48
|
+
detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env,
|
|
49
|
+
});
|
|
50
|
+
if (!child.pid) throw new Error('background evaluation worker did not start');
|
|
51
|
+
child.unref();
|
|
52
|
+
return { launcher: 'direct', restartDurable: false, pid: child.pid };
|
|
53
|
+
} finally {
|
|
54
|
+
await log.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function startBackgroundEvaluation({ baseDir, configFile, jobId, gates = null, reportFile = null, maxNewTokens = 48, retry = false }) {
|
|
59
|
+
requireJobId(jobId);
|
|
60
|
+
const { file, config } = await loadConfig({ file: configFile, baseDir });
|
|
61
|
+
const output = path.resolve(config.baseDir, reportFile ?? path.join(config.runRootAbsolute, jobId, 'eval-report.json'));
|
|
62
|
+
const device = process.env.TMF_DEVICE ?? 'cpu';
|
|
63
|
+
if (!['cpu', 'cuda'].includes(device)) throw new Error('unsupported TMF_DEVICE=' + device);
|
|
64
|
+
const request = {
|
|
65
|
+
configFile: file, configDigest: await sha256File(file), jobId, gates, reportFile: output,
|
|
66
|
+
maxNewTokens, device, pythonBin: process.env.TMF_PYTHON ?? 'python3',
|
|
67
|
+
hfMaxMemoryMb: process.env.TMF_HF_MAX_MEMORY_MB ?? null,
|
|
68
|
+
};
|
|
69
|
+
const requestId = sha256Json(request).slice(0, 24);
|
|
70
|
+
const loc = await location({ baseDir, configFile: file, jobId, requestId });
|
|
71
|
+
await ensureDir(loc.root);
|
|
72
|
+
let attempt = 1;
|
|
73
|
+
try {
|
|
74
|
+
await mkdir(loc.dir);
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (err.code !== 'EEXIST') throw err;
|
|
77
|
+
const prior = await backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
|
|
78
|
+
if (!retry || !['interrupted', 'failed'].includes(prior.state)) return prior;
|
|
79
|
+
attempt = (prior.attempt ?? 1) + 1;
|
|
80
|
+
}
|
|
81
|
+
const attemptDir = path.join(loc.dir, 'attempt-' + attempt);
|
|
82
|
+
try {
|
|
83
|
+
await mkdir(attemptDir);
|
|
84
|
+
} catch (err) {
|
|
85
|
+
if (err.code !== 'EEXIST') throw err;
|
|
86
|
+
return backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
|
|
87
|
+
}
|
|
88
|
+
const requestFile = path.join(attemptDir, 'request.json');
|
|
89
|
+
await writeJson(requestFile, { ...request, requestId, attempt, stageReportFile: path.join(attemptDir, 'report.json') });
|
|
90
|
+
const status = { requestId, jobId, state: 'queued', attempt, reportFile: output, createdAt: new Date().toISOString(), device };
|
|
91
|
+
await writeJson(loc.statusFile, status);
|
|
92
|
+
try {
|
|
93
|
+
const launch = await launchBackgroundWorker(workerFile, requestFile, loc.statusFile, 'tmf-eval-' + requestId + '-' + attempt, path.join(attemptDir, 'worker.log'));
|
|
94
|
+
const now = await readJsonIfExists(loc.statusFile);
|
|
95
|
+
if (now?.state === 'queued' && now.attempt === attempt) await writeJson(loc.statusFile, { ...now, ...launch });
|
|
96
|
+
} catch (err) {
|
|
97
|
+
await writeJson(loc.statusFile, { ...status, state: 'failed', error: { code: 'WORKER_LAUNCH_FAILED', message: err.message }, finishedAt: new Date().toISOString() });
|
|
98
|
+
}
|
|
99
|
+
return backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function backgroundEvaluationStatus({ baseDir, configFile, jobId, requestId }) {
|
|
103
|
+
requireJobId(jobId);
|
|
104
|
+
if (typeof requestId !== 'string' || !/^[a-f0-9]{24}$/.test(requestId)) throw new Error('requestId must be a 24-character hex digest');
|
|
105
|
+
const loc = await location({ baseDir, configFile, jobId, requestId });
|
|
106
|
+
const status = await readJsonIfExists(loc.statusFile);
|
|
107
|
+
if (!status) {
|
|
108
|
+
if (!(await exists(loc.dir))) throw new Error('background evaluation not found: ' + requestId);
|
|
109
|
+
return { requestId, jobId, state: 'initializing', statusFile: loc.statusFile };
|
|
110
|
+
}
|
|
111
|
+
if (status.state === 'running' && status.pid) {
|
|
112
|
+
try {
|
|
113
|
+
process.kill(status.pid, 0);
|
|
114
|
+
} catch (err) {
|
|
115
|
+
if (err.code === 'ESRCH') {
|
|
116
|
+
const report = await readJsonIfExists(status.reportFile);
|
|
117
|
+
if (reportMatches(report, status)) {
|
|
118
|
+
const succeeded = { ...status, state: 'succeeded', finishedAt: report.finishedAt, reportDigest: report.reportDigest, verdict: report.verdict, gates: report.gates };
|
|
119
|
+
delete succeeded.error;
|
|
120
|
+
await writeJson(loc.statusFile, succeeded);
|
|
121
|
+
return { ...succeeded, statusFile: loc.statusFile };
|
|
122
|
+
}
|
|
123
|
+
const interrupted = { ...status, state: 'interrupted', finishedAt: new Date().toISOString(), error: { code: 'WORKER_EXITED', message: 'worker exited without a matching final report; retry the same request explicitly' } };
|
|
124
|
+
await writeJson(loc.statusFile, interrupted);
|
|
125
|
+
return { ...interrupted, statusFile: loc.statusFile };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { ...status, statusFile: loc.statusFile };
|
|
130
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readJson, writeJson, exists } from '../core/fsx.mjs';
|
|
3
|
+
import { sha256File } from '../core/hash.mjs';
|
|
4
|
+
import { train, status as trainingStatus } from '../api.mjs';
|
|
5
|
+
|
|
6
|
+
const [, , requestFile, statusFile] = process.argv;
|
|
7
|
+
if (!requestFile || !statusFile) throw new Error('training worker requires request and status files');
|
|
8
|
+
const request = await readJson(requestFile);
|
|
9
|
+
const cancelFile = path.join(path.dirname(requestFile), 'cancel.json');
|
|
10
|
+
const old = await readJson(statusFile);
|
|
11
|
+
if (old.requestId !== request.requestId || old.attempt !== request.attempt) {
|
|
12
|
+
throw new Error('background training attempt no longer owns the status file');
|
|
13
|
+
}
|
|
14
|
+
if (await sha256File(request.configFile) !== request.configDigest) {
|
|
15
|
+
throw new Error('background training config changed since submission');
|
|
16
|
+
}
|
|
17
|
+
if (old.state === 'cancel_requested' || await exists(cancelFile)) {
|
|
18
|
+
await writeJson(statusFile, { ...old, state: 'cancelled', finishedAt: new Date().toISOString() });
|
|
19
|
+
process.exit(130);
|
|
20
|
+
}
|
|
21
|
+
process.env.TMF_DEVICE = request.device;
|
|
22
|
+
process.env.TMF_PYTHON = request.pythonBin;
|
|
23
|
+
if (request.hfMaxMemoryMb !== null) process.env.TMF_HF_MAX_MEMORY_MB = request.hfMaxMemoryMb;
|
|
24
|
+
process.chdir(path.dirname(statusFile));
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
for (const signal of ['SIGTERM', 'SIGINT']) {
|
|
27
|
+
process.on(signal, () => controller.abort(new Error(`operator cancelled with ${signal}`)));
|
|
28
|
+
}
|
|
29
|
+
const common = { ...old };
|
|
30
|
+
await writeJson(statusFile, { ...common, state: 'running', pid: process.pid, startedAt: new Date().toISOString() });
|
|
31
|
+
if (await exists(cancelFile)) controller.abort(new Error('operator cancelled before training started'));
|
|
32
|
+
try {
|
|
33
|
+
const result = await train({
|
|
34
|
+
baseDir: path.dirname(request.configFile), configFile: request.configFile, jobId: request.jobId,
|
|
35
|
+
resume: request.resume, resumeCancelled: request.resumeCancelled, auditEveryStep: request.auditEveryStep, signal: controller.signal,
|
|
36
|
+
});
|
|
37
|
+
await writeJson(statusFile, {
|
|
38
|
+
...common, state: result.job.state, pid: process.pid, finishedAt: new Date().toISOString(),
|
|
39
|
+
jobState: result.job.state, checkpoint: result.artifacts?.adapterCheckpoint ?? result.artifacts?.tunedCheckpoint ?? null,
|
|
40
|
+
});
|
|
41
|
+
if (result.job.state !== 'succeeded') process.exitCode = 1;
|
|
42
|
+
} catch (err) {
|
|
43
|
+
const durable = await trainingStatus({ baseDir: path.dirname(request.configFile), configFile: request.configFile, jobId: request.jobId });
|
|
44
|
+
const cancelled = controller.signal.aborted || durable.state?.state === 'cancelled';
|
|
45
|
+
await writeJson(statusFile, {
|
|
46
|
+
...common, state: cancelled ? 'cancelled' : 'failed', pid: process.pid,
|
|
47
|
+
finishedAt: new Date().toISOString(), jobState: durable.state?.state ?? null,
|
|
48
|
+
error: { code: err?.code ?? 'action-failed', message: err?.message ?? String(err) },
|
|
49
|
+
});
|
|
50
|
+
process.exitCode = cancelled ? 130 : 1;
|
|
51
|
+
}
|