taskforce-model-foundry 0.2.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 +18 -0
- package/bin/tmf.mjs +53 -1
- package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +1 -1
- package/docs/external-quality.md +59 -0
- package/docs/integration.md +9 -7
- package/docs/releases/v0.3.0.md +28 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +1 -1
- package/integrations/openclaw-plugin/tools.mjs +3 -2
- package/openclaw.plugin.json +3 -1
- package/package.json +1 -1
- package/src/api.mjs +45 -1
- package/src/config.mjs +63 -5
- package/src/data/split.mjs +23 -8
- package/src/eval/evaluator.mjs +14 -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 +1 -0
- package/src/integrations/async-evaluate.mjs +14 -9
- package/src/integrations/async-train-worker.mjs +51 -0
- package/src/integrations/async-train.mjs +135 -0
- package/src/integrations/openclaw.mjs +26 -4
- package/src/jobs/train.mjs +38 -14
- package/src/train/backends/hf-peft.mjs +68 -5
- package/src/train/backends/hf_peft_runner.py +145 -8
- package/src/version.mjs +1 -1
package/README.md
CHANGED
|
@@ -89,6 +89,24 @@ random-init local fixture (`docs/reports/g12d-cli-e2e-evidence.json`):
|
|
|
89
89
|
`tmf evaluate` scores baseline and tuned in two independent processes (tuned
|
|
90
90
|
holdout loss 3.9% better).
|
|
91
91
|
|
|
92
|
+
Long jobs can use `tmf train --background --job <id>` and
|
|
93
|
+
`tmf evaluate --background --job <id>`; each returns a request ID for
|
|
94
|
+
`train-status` / `evaluate-status`. Training also supports `train-cancel` and
|
|
95
|
+
explicit `--retry` after failure/interruption; `--resume-cancelled` resumes a
|
|
96
|
+
cancelled request as a new attempt. A job ID is bound to one training request:
|
|
97
|
+
changed config/device needs a new job ID. On Linux a user systemd unit
|
|
98
|
+
keeps the worker outside the calling CLI or Gateway process; a direct detached
|
|
99
|
+
fallback is reported as `restartDurable: false`. HF evaluation scores holdout,
|
|
100
|
+
generates predictions and scores validation in one model load per side.
|
|
101
|
+
The report records the actual evaluation device. See
|
|
102
|
+
[`docs/external-quality.md`](docs/external-quality.md) to require separate,
|
|
103
|
+
predeclared domain-quality gates before export.
|
|
104
|
+
`restartDurable: true` means isolated from a **Gateway process restart**, not
|
|
105
|
+
survival of a host reboot or power loss. HF `maxTokens` stops before the next
|
|
106
|
+
over-budget batch; after a hard-killed attempt, tokens spent since the last
|
|
107
|
+
durable training-step receipt cannot be reconstructed and must not be reported
|
|
108
|
+
as a verified cumulative total.
|
|
109
|
+
|
|
92
110
|
Cancel and resume are stated at the precision the evidence supports.
|
|
93
111
|
`Ctrl-C` or `SIGTERM` during `tmf train` aborts the job's `AbortSignal`: the
|
|
94
112
|
job stops between steps, persists `cancelled` with the steps it did finish,
|
package/bin/tmf.mjs
CHANGED
|
@@ -14,6 +14,8 @@ import {
|
|
|
14
14
|
} from '../src/config.mjs';
|
|
15
15
|
import { writeJson, readJson, exists } from '../src/core/fsx.mjs';
|
|
16
16
|
import { VERSION } from '../src/index.mjs';
|
|
17
|
+
import { startBackgroundEvaluation, backgroundEvaluationStatus } from '../src/integrations/async-evaluate.mjs';
|
|
18
|
+
import { startBackgroundTraining, backgroundTrainingStatus, cancelBackgroundTraining } from '../src/integrations/async-train.mjs';
|
|
17
19
|
|
|
18
20
|
const USAGE = `taskforce-model-foundry ${VERSION}
|
|
19
21
|
|
|
@@ -27,8 +29,12 @@ Commands:
|
|
|
27
29
|
synth Generate a synthetic corpus (no private data needed)
|
|
28
30
|
train Run a real post-training job
|
|
29
31
|
evaluate Score a finished job on an independent holdout
|
|
32
|
+
train-status <job> <requestId> Read a background training receipt
|
|
33
|
+
evaluate-status <job> <requestId> Read a background evaluation receipt
|
|
34
|
+
train-cancel <job> <requestId> Cancel background training
|
|
30
35
|
export Package a deliverable bundle (gated on evaluation)
|
|
31
36
|
--report <file> reuses an existing eval report instead of re-evaluating
|
|
37
|
+
--quality-report <file> pins predeclared external quality evidence
|
|
32
38
|
status <jobId> Show durable job state and recent audit events
|
|
33
39
|
version Print the version
|
|
34
40
|
help Print this help
|
|
@@ -42,6 +48,8 @@ Options:
|
|
|
42
48
|
--count <n> Record count (synth/init, default: 160)
|
|
43
49
|
--resume-cancelled Resume a job that an operator cancelled
|
|
44
50
|
--no-resume Ignore existing job state instead of resuming
|
|
51
|
+
--background Run train/evaluate in an independent worker; return requestId
|
|
52
|
+
--retry Explicitly retry a failed/interrupted background request
|
|
45
53
|
|
|
46
54
|
Exit codes:
|
|
47
55
|
0 ok 1 the job ran and did not succeed 2 usage error
|
|
@@ -49,7 +57,7 @@ Exit codes:
|
|
|
49
57
|
`;
|
|
50
58
|
|
|
51
59
|
function parseArgs(argv) {
|
|
52
|
-
const opts = { _: [], json: false, resume: true, resumeCancelled: false };
|
|
60
|
+
const opts = { _: [], json: false, resume: true, resumeCancelled: false, background: false, retry: false };
|
|
53
61
|
for (let i = 0; i < argv.length; i += 1) {
|
|
54
62
|
const arg = argv[i];
|
|
55
63
|
const next = () => {
|
|
@@ -65,10 +73,13 @@ function parseArgs(argv) {
|
|
|
65
73
|
case '--job': opts.job = next(); break;
|
|
66
74
|
case '--out': opts.out = next(); break;
|
|
67
75
|
case '--report': opts.report = next(); break;
|
|
76
|
+
case '--quality-report': opts.qualityReport = next(); break;
|
|
68
77
|
case '--bundle-version': opts.bundleVersion = next(); break;
|
|
69
78
|
case '--count': opts.count = Number(next()); break;
|
|
70
79
|
case '--resume-cancelled': opts.resumeCancelled = true; break;
|
|
71
80
|
case '--no-resume': opts.resume = false; break;
|
|
81
|
+
case '--background': opts.background = true; break;
|
|
82
|
+
case '--retry': opts.retry = true; break;
|
|
72
83
|
case '-h': case '--help': opts.help = true; break;
|
|
73
84
|
case '-v': case '--version': opts.version = true; break;
|
|
74
85
|
default:
|
|
@@ -185,6 +196,16 @@ function installCancelHandlers(controller) {
|
|
|
185
196
|
|
|
186
197
|
async function cmdTrain(opts, baseDir) {
|
|
187
198
|
const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
|
|
199
|
+
if (opts.background) {
|
|
200
|
+
if (!opts.job) throw new UsageError('background training requires --job <stable-id>');
|
|
201
|
+
if (!opts.resume) throw new UsageError('background training does not accept --no-resume');
|
|
202
|
+
const receipt = await startBackgroundTraining({
|
|
203
|
+
baseDir, configFile: file, jobId: opts.job, resumeCancelled: opts.resumeCancelled, retry: opts.retry,
|
|
204
|
+
});
|
|
205
|
+
out(opts, receipt, [`training request ${receipt.requestId}: ${receipt.state}`, `status: tmf train-status ${opts.job} ${receipt.requestId} --config ${file}`, `log: ${receipt.logFile ?? '(pending)'}`]);
|
|
206
|
+
return receipt.state === 'failed' ? 1 : 0;
|
|
207
|
+
}
|
|
208
|
+
if (opts.retry) throw new UsageError('--retry requires --background');
|
|
188
209
|
const controller = new AbortController();
|
|
189
210
|
const disarm = installCancelHandlers(controller);
|
|
190
211
|
let job; let artifacts;
|
|
@@ -232,6 +253,15 @@ async function cmdTrain(opts, baseDir) {
|
|
|
232
253
|
|
|
233
254
|
async function cmdEvaluate(opts, baseDir) {
|
|
234
255
|
const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
|
|
256
|
+
if (opts.background) {
|
|
257
|
+
if (!opts.job) throw new UsageError('background evaluation requires --job <stable-id>');
|
|
258
|
+
const receipt = await startBackgroundEvaluation({
|
|
259
|
+
baseDir, configFile: file, jobId: opts.job, reportFile: opts.report ?? null, retry: opts.retry,
|
|
260
|
+
});
|
|
261
|
+
out(opts, receipt, [`evaluation request ${receipt.requestId}: ${receipt.state}`, `status: tmf evaluate-status ${opts.job} ${receipt.requestId} --config ${file}`]);
|
|
262
|
+
return receipt.state === 'failed' ? 1 : 0;
|
|
263
|
+
}
|
|
264
|
+
if (opts.retry) throw new UsageError('--retry requires --background');
|
|
235
265
|
const { artifacts, report } = await evaluate({
|
|
236
266
|
config, baseDir, jobId: opts.job ?? null, reportFile: opts.report ?? null,
|
|
237
267
|
});
|
|
@@ -270,6 +300,7 @@ async function cmdExport(opts, baseDir) {
|
|
|
270
300
|
({ bundle, report } = await exportModel({
|
|
271
301
|
config, baseDir, jobId: opts.job ?? null, outDir: opts.out ?? null, version: opts.bundleVersion ?? null,
|
|
272
302
|
evalReport, evaluateIfMissing: !evalReport,
|
|
303
|
+
qualityReport: opts.qualityReport ?? null,
|
|
273
304
|
}));
|
|
274
305
|
} catch (err) {
|
|
275
306
|
// A blocked export is an expected outcome, not a crash: report the reason
|
|
@@ -308,6 +339,24 @@ async function cmdStatus(opts, baseDir, rest) {
|
|
|
308
339
|
return 0;
|
|
309
340
|
}
|
|
310
341
|
|
|
342
|
+
async function cmdBackgroundStatus(opts, baseDir, rest, kind) {
|
|
343
|
+
const [jobId, requestId] = rest;
|
|
344
|
+
if (!jobId || !requestId) throw new UsageError(`usage: tmf ${kind}-status <jobId> <requestId>`);
|
|
345
|
+
const receipt = kind === 'train'
|
|
346
|
+
? await backgroundTrainingStatus({ baseDir, configFile: opts.config ?? null, jobId, requestId })
|
|
347
|
+
: await backgroundEvaluationStatus({ baseDir, configFile: opts.config ?? null, jobId, requestId });
|
|
348
|
+
out(opts, receipt, [`${kind} request ${requestId}: ${receipt.state}`, `status: ${receipt.statusFile}`, ...(receipt.logFile ? [`log: ${receipt.logFile}`] : [])]);
|
|
349
|
+
return ['failed', 'interrupted'].includes(receipt.state) ? 1 : 0;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function cmdTrainCancel(opts, baseDir, rest) {
|
|
353
|
+
const [jobId, requestId] = rest;
|
|
354
|
+
if (!jobId || !requestId) throw new UsageError('usage: tmf train-cancel <jobId> <requestId>');
|
|
355
|
+
const receipt = await cancelBackgroundTraining({ baseDir, configFile: opts.config ?? null, jobId, requestId });
|
|
356
|
+
out(opts, receipt, [`training request ${requestId}: ${receipt.state}`]);
|
|
357
|
+
return 0;
|
|
358
|
+
}
|
|
359
|
+
|
|
311
360
|
async function main(argv) {
|
|
312
361
|
let opts;
|
|
313
362
|
try {
|
|
@@ -333,6 +382,9 @@ async function main(argv) {
|
|
|
333
382
|
case 'synth': return cmdSynth(opts, baseDir);
|
|
334
383
|
case 'train': return cmdTrain(opts, baseDir);
|
|
335
384
|
case 'evaluate': case 'eval': return cmdEvaluate(opts, baseDir);
|
|
385
|
+
case 'train-status': return cmdBackgroundStatus(opts, baseDir, rest, 'train');
|
|
386
|
+
case 'evaluate-status': return cmdBackgroundStatus(opts, baseDir, rest, 'evaluate');
|
|
387
|
+
case 'train-cancel': return cmdTrainCancel(opts, baseDir, rest);
|
|
336
388
|
case 'export': return cmdExport(opts, baseDir);
|
|
337
389
|
case 'status': return cmdStatus(opts, baseDir, rest);
|
|
338
390
|
default:
|
|
@@ -63,7 +63,7 @@ test and live plugin verification.
|
|
|
63
63
|
running Gateway restart with a live worker, full 77-class BANKING77 quality,
|
|
64
64
|
and authorized de-identified enterprise data. SIGKILL and targeted `ENOSPC`
|
|
65
65
|
injection exercise failure paths, not those physical events. The public pilot
|
|
66
|
-
does not establish production or
|
|
66
|
+
does not establish production or any other domain-specific model quality.
|
|
67
67
|
|
|
68
68
|
For a local fixture regression run with a supported Python environment:
|
|
69
69
|
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# External quality gates for domain-specific models
|
|
2
|
+
|
|
3
|
+
Foundry's independent loss/strict-match report is a **technical** gate, not a
|
|
4
|
+
domain-quality judgement. A project may require separately scored quality
|
|
5
|
+
evidence before export. Foundry does not ship domain datasets, scorers, judges,
|
|
6
|
+
rubrics or promotion thresholds. This mechanism does not run a scorer or claim
|
|
7
|
+
that a checksum proves the scores are truthful.
|
|
8
|
+
|
|
9
|
+
1. **Before starting a new training job**, add `eval.externalQuality` to
|
|
10
|
+
`tmf.config.json`. Freeze the complete suite and scorer files; put their
|
|
11
|
+
SHA-256 digests in `suiteSha256` and `scorerSha256`. Declare nonempty gates
|
|
12
|
+
using the same `id`, `metric`, `comparator`, `threshold`, optional
|
|
13
|
+
`sampleMetric`/`minSamples` syntax as `eval.gates`. The training manifest
|
|
14
|
+
and job input digest pin this contract. Do not retrofit it onto an old job.
|
|
15
|
+
Optional `profile` names the project's protocol; optional `references` is a
|
|
16
|
+
map of project-defined names to SHA-256 digests (for example a baseline
|
|
17
|
+
output or rubric). Foundry stores them in the frozen contract without
|
|
18
|
+
interpreting their domain meaning.
|
|
19
|
+
2. Evaluate the trained checkpoint with `tmf evaluate`. An external scorer can
|
|
20
|
+
call `qualityContext({configFile, jobId, evalReport})` to get the frozen
|
|
21
|
+
contract and checkpoint hash only after a passing technical report. Run the project's
|
|
22
|
+
independently maintained suite and scorer only after its protocol and
|
|
23
|
+
thresholds are frozen. Translate **all** required criteria into contract
|
|
24
|
+
gates before looking at candidate results. Foundry supplies no default
|
|
25
|
+
domain thresholds.
|
|
26
|
+
3. The external scorer writes a JSON report with:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"format": "tmf.external-quality/v1",
|
|
31
|
+
"jobId": "new-training-job-id",
|
|
32
|
+
"suiteSha256": "<predeclared-suite-sha256>",
|
|
33
|
+
"scorerSha256": "<predeclared-scorer-sha256>",
|
|
34
|
+
"contractDigest": "<sha256Json(eval.externalQuality)>",
|
|
35
|
+
"checkpointSha256": "<sha256 of trained adapter or tuned checkpoint file>",
|
|
36
|
+
"evalReportDigest": "<technical eval reportDigest>",
|
|
37
|
+
"tunedFingerprint": "<technical eval lineage.tunedFingerprint>",
|
|
38
|
+
"metrics": { "quality": { "overall": 0.0 } },
|
|
39
|
+
"reportDigest": "<canonical digest of this report without reportDigest>"
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The scorer may import `externalQuality.sealExternalQualityEvidence` from
|
|
44
|
+
`taskforce-model-foundry` to compute the canonical `reportDigest`; the
|
|
45
|
+
`contractDigest` can be computed with
|
|
46
|
+
`externalQuality.externalQualityContractDigest(contract)`. These
|
|
47
|
+
digests detect edits and bind the evidence, but are **not signatures**.
|
|
48
|
+
Preserve the raw per-question outputs, blinded comparisons, scorer version
|
|
49
|
+
and human review provenance alongside the report.
|
|
50
|
+
4. Export with `tmf export --job <id> --report <technical.json>
|
|
51
|
+
--quality-report <quality.json>`. Foundry checks the training-time contract,
|
|
52
|
+
both report digests, job ID, suite/scorer hashes, checkpoint pointer hash,
|
|
53
|
+
tuned weight fingerprint and every
|
|
54
|
+
external gate. Missing, stale, edited or failing evidence blocks export;
|
|
55
|
+
passing evidence is copied into the checksummed bundle.
|
|
56
|
+
|
|
57
|
+
An old job created without the external-quality contract cannot be promoted
|
|
58
|
+
retroactively; use a new job ID after freezing the contract. Keep each
|
|
59
|
+
domain-specific recipe in its own project, outside the generic Foundry package.
|
package/docs/integration.md
CHANGED
|
@@ -22,9 +22,9 @@ network.
|
|
|
22
22
|
npm i taskforce-model-foundry
|
|
23
23
|
|
|
24
24
|
# from a local tarball, which is how the install path was verified
|
|
25
|
-
npm pack # -> taskforce-model-foundry-0.
|
|
25
|
+
npm pack # -> taskforce-model-foundry-0.3.0.tgz
|
|
26
26
|
cd /path/to/host
|
|
27
|
-
npm i /path/to/taskforce-model-foundry-0.
|
|
27
|
+
npm i /path/to/taskforce-model-foundry-0.3.0.tgz
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
The install provides one bin, `tmf` (`node_modules/.bin/tmf`), and the
|
|
@@ -178,7 +178,7 @@ when no Python interpreter is on PATH).
|
|
|
178
178
|
|
|
179
179
|
## 4. Action and tool table
|
|
180
180
|
|
|
181
|
-
|
|
181
|
+
Nine actions, nine tools, one table. `compute: true` means the call spends real
|
|
182
182
|
CPU time and writes run artifacts; those are the calls a host should gate.
|
|
183
183
|
|
|
184
184
|
| OpenClaw action | Hermes tool | Compute | Required | Accepted params |
|
|
@@ -186,14 +186,16 @@ CPU time and writes run artifacts; those are the calls a host should gate.
|
|
|
186
186
|
| `doctor` | `tmf_doctor` | no | — | `configFile`, `requireConfig` |
|
|
187
187
|
| `status` | `tmf_status` | no | `jobId` | `jobId`, `configFile`, `auditTail` |
|
|
188
188
|
| `synthesize` | `tmf_synthesize` | yes | — | `outDir`, `seed`, `count`, `profile` |
|
|
189
|
-
| `train` | `tmf_train` | yes | — | `configFile`, `jobId`, `resume`, `resumeCancelled`, `auditEveryStep` |
|
|
189
|
+
| `train` | `tmf_train` | yes | — | `configFile`, `jobId`, `resume`, `resumeCancelled`, `auditEveryStep`, `background`, `retry` |
|
|
190
|
+
| `train_status` | `tmf_train_status` | no | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
|
|
191
|
+
| `train_cancel` | `tmf_train_cancel` | yes | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
|
|
190
192
|
| `evaluate` | `tmf_evaluate` | yes | — | `configFile`, `jobId`, `gates`, `reportFile`, `maxNewTokens`, `background`, `retry` |
|
|
191
193
|
| `evaluate_status` | `tmf_evaluate_status` | no | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
|
|
192
|
-
| `export` | `tmf_export` | yes | — | `configFile`, `jobId`, `evalReport`, `outDir`, `version`, `evaluateIfMissing` |
|
|
194
|
+
| `export` | `tmf_export` | yes | — | `configFile`, `jobId`, `evalReport`, `qualityReport`, `outDir`, `version`, `evaluateIfMissing` |
|
|
193
195
|
|
|
194
196
|
**Read-only mount.** `allowCompute: false` keeps the adapter useful for
|
|
195
|
-
inspection while making compute impossible:
|
|
196
|
-
normally, and all
|
|
197
|
+
inspection while making compute impossible: the four read-only actions answer
|
|
198
|
+
normally, and all five compute actions are refused with
|
|
197
199
|
`compute-not-authorized` *before* any handler runs — nothing is written, no
|
|
198
200
|
partial job appears. Mount read-only wherever the host cannot itself vouch that
|
|
199
201
|
training was authorized.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# v0.3.0 — durable workers and domain-neutral quality gates
|
|
2
|
+
|
|
3
|
+
This release makes long local training and evaluation jobs easier to supervise
|
|
4
|
+
without coupling Foundry to any one task domain.
|
|
5
|
+
|
|
6
|
+
- `tmf train/evaluate --background` return durable request IDs; status,
|
|
7
|
+
cancellation and explicit retry operations expose the worker lifecycle.
|
|
8
|
+
Linux systemd user units isolate workers from the calling CLI/Gateway process
|
|
9
|
+
where available. Direct-detached fallback reports its weaker durability.
|
|
10
|
+
- HF/PEFT evaluation now computes holdout loss, greedy predictions and
|
|
11
|
+
validation loss in one model load per side. Training token usage and
|
|
12
|
+
evaluation resource/device reporting now reflect work actually performed.
|
|
13
|
+
- Projects can freeze an external-quality contract before training and bind a
|
|
14
|
+
project-owned scorer report to the job, technical evaluation and checkpoint.
|
|
15
|
+
Failed or missing external gates block export. Domain suites, rubrics,
|
|
16
|
+
judges and thresholds are deliberately **not** included in Foundry.
|
|
17
|
+
- Model cards no longer imply that all non-synthetic project data is synthetic.
|
|
18
|
+
|
|
19
|
+
Verification: 244 Node tests passed with 0 failures/skips before release prep;
|
|
20
|
+
the same 31B smoke adapter's loss values and 40/40 prediction digests matched
|
|
21
|
+
the previous evaluation while wall time fell from 3487.742s to 1451.132s.
|
|
22
|
+
That smoke candidate still failed one of two predeclared technical gates and
|
|
23
|
+
was **not** exported or accepted as a quality improvement.
|
|
24
|
+
|
|
25
|
+
Limits: no physical power-loss or disk-exhaustion proof, no full business
|
|
26
|
+
benchmark result, and no domain-specific quality acceptance is claimed by
|
|
27
|
+
this release. A project-owned scorer must supply and substantiate its own
|
|
28
|
+
external evidence.
|
|
@@ -20,10 +20,11 @@ export const PARAM_SCHEMA = {
|
|
|
20
20
|
gates: { type: 'string', description: 'Evaluation gate expression.' },
|
|
21
21
|
reportFile: { type: 'string', description: 'Where to write the evaluation report.' },
|
|
22
22
|
maxNewTokens: { type: 'number', description: 'Generation budget per eval sample.' },
|
|
23
|
-
background: { type: 'boolean', description: '
|
|
23
|
+
background: { type: 'boolean', description: 'Run training or evaluation in an independent worker and return a durable request id.' },
|
|
24
24
|
retry: { type: 'boolean', description: 'Retry the same failed or interrupted background request; never duplicates a running request.' },
|
|
25
|
-
requestId: { type: 'string', description: 'Background
|
|
25
|
+
requestId: { type: 'string', description: 'Background request id returned by tmf_train or tmf_evaluate.' },
|
|
26
26
|
evalReport: { type: 'string', description: 'Evaluation report consumed by export.' },
|
|
27
|
+
qualityReport: { type: 'string', description: 'Predeclared external quality evidence report consumed by export.' },
|
|
27
28
|
version: { type: 'string', description: 'Export version label.' },
|
|
28
29
|
evaluateIfMissing: { type: 'boolean', description: 'Run evaluation when no report exists.' },
|
|
29
30
|
};
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "taskforce-model-foundry",
|
|
3
3
|
"name": "Taskforce Model Foundry",
|
|
4
4
|
"description": "Taskforce Model Foundry tools (contract v1).",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.3.0",
|
|
6
6
|
"configSchema": {
|
|
7
7
|
"type": "object",
|
|
8
8
|
"properties": {},
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
"tmf_status",
|
|
18
18
|
"tmf_synthesize",
|
|
19
19
|
"tmf_train",
|
|
20
|
+
"tmf_train_status",
|
|
21
|
+
"tmf_train_cancel",
|
|
20
22
|
"tmf_evaluate",
|
|
21
23
|
"tmf_evaluate_status",
|
|
22
24
|
"tmf_export"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "taskforce-model-foundry",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Taskforce Model Foundry: automated private-data model customization engine for OpenClaw and Hermes. Real post-training (weight/adapter updates), independent holdout evaluation, auditable jobs, and signed export lineage.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/api.mjs
CHANGED
|
@@ -17,6 +17,8 @@ import { encodeRecords } from './train/dataset.mjs';
|
|
|
17
17
|
import { exportModel as packageExport } from './export/package.mjs';
|
|
18
18
|
import { exists, readJson, readJsonl } from './core/fsx.mjs';
|
|
19
19
|
import { VERSION } from './version.mjs';
|
|
20
|
+
import { sha256Json, sha256File } from './core/hash.mjs';
|
|
21
|
+
import { verifyExternalQuality } from './eval/external-quality.mjs';
|
|
20
22
|
|
|
21
23
|
export const PRODUCT = 'taskforce-model-foundry';
|
|
22
24
|
const MIN_NODE_MAJOR = 20;
|
|
@@ -149,6 +151,7 @@ export async function train({
|
|
|
149
151
|
modelConfig: resolved.model,
|
|
150
152
|
hyper: resolved.hyper,
|
|
151
153
|
trainBudget: resolved.trainBudget,
|
|
154
|
+
externalQuality: resolved.eval?.externalQuality ?? null,
|
|
152
155
|
mode: resolved.mode,
|
|
153
156
|
seed: resolved.seed,
|
|
154
157
|
maxVocab: resolved.model.maxVocab,
|
|
@@ -221,7 +224,9 @@ async function resolveArtifacts({ artifacts, config, jobId }) {
|
|
|
221
224
|
const result = Object.fromEntries((state.completedSteps ?? [])
|
|
222
225
|
.filter((step) => step && typeof step === 'object' && step.name)
|
|
223
226
|
.map((step) => [step.name, step.output]));
|
|
224
|
-
|
|
227
|
+
// The finalize step is the durable manifest. It includes the predeclared
|
|
228
|
+
// external-quality contract, which is not a standalone step in the map.
|
|
229
|
+
return trainingArtifacts({ ...state, result: result.finalize ?? result });
|
|
225
230
|
}
|
|
226
231
|
|
|
227
232
|
/**
|
|
@@ -267,6 +272,7 @@ export async function evaluate({
|
|
|
267
272
|
seed: resolved.seed,
|
|
268
273
|
dataDir: resolvedArtifacts.dataDir,
|
|
269
274
|
dataReportFile: resolvedArtifacts.dataReportFile ?? null,
|
|
275
|
+
externalQualityContractDigest: resolvedArtifacts.externalQuality ? sha256Json(resolvedArtifacts.externalQuality) : null,
|
|
270
276
|
},
|
|
271
277
|
reportFile: file,
|
|
272
278
|
maxNewTokens,
|
|
@@ -292,6 +298,24 @@ async function readPinnedReport(file, baseDir) {
|
|
|
292
298
|
return parsed.reportFile ? parsed : { ...parsed, reportFile: abs };
|
|
293
299
|
}
|
|
294
300
|
|
|
301
|
+
/** Bind a project's external scorer to a successful technical evaluation. */
|
|
302
|
+
export async function qualityContext({ configFile = null, baseDir = process.cwd(), jobId, evalReport } = {}) {
|
|
303
|
+
const { config } = await loadConfig({ file: configFile, baseDir });
|
|
304
|
+
const artifacts = await resolveArtifacts({ config, jobId });
|
|
305
|
+
const technical = typeof evalReport === 'string' ? await readPinnedReport(evalReport, config.baseDir) : evalReport;
|
|
306
|
+
assertReportIntegrity(technical, { jobId: artifacts.jobId });
|
|
307
|
+
if (technical.verdict?.status !== 'passed' || !technical.verdict.deliveryEligible) {
|
|
308
|
+
throw new Error('external quality requires a passed technical evaluation');
|
|
309
|
+
}
|
|
310
|
+
const contract = config.eval?.externalQuality;
|
|
311
|
+
if (!contract || !artifacts.externalQuality || sha256Json(contract) !== sha256Json(artifacts.externalQuality) ||
|
|
312
|
+
technical.lineage?.externalQualityContractDigest !== sha256Json(contract)) {
|
|
313
|
+
throw new Error('external quality contract was not frozen into training and technical evaluation');
|
|
314
|
+
}
|
|
315
|
+
const checkpoint = artifacts.adapterCheckpoint ?? artifacts.tunedCheckpoint;
|
|
316
|
+
return { contract, jobId: artifacts.jobId, evalReport: technical, checkpointSha256: await sha256File(checkpoint) };
|
|
317
|
+
}
|
|
318
|
+
|
|
295
319
|
/**
|
|
296
320
|
* Package a deliverable bundle. The gate lives inside exportModel, so a
|
|
297
321
|
* failed or baseline-only evaluation cannot produce an export.
|
|
@@ -303,6 +327,7 @@ export async function exportModel({
|
|
|
303
327
|
jobId = null,
|
|
304
328
|
artifacts = null,
|
|
305
329
|
evalReport = null,
|
|
330
|
+
qualityReport = null,
|
|
306
331
|
outDir = null,
|
|
307
332
|
version = null,
|
|
308
333
|
evaluateIfMissing = true,
|
|
@@ -325,11 +350,30 @@ export async function exportModel({
|
|
|
325
350
|
assertReportIntegrity(report, { jobId });
|
|
326
351
|
resolvedArtifacts = await resolveArtifacts({ artifacts, config: resolved, jobId });
|
|
327
352
|
}
|
|
353
|
+
let externalQuality = null;
|
|
354
|
+
if (resolved.eval?.externalQuality) {
|
|
355
|
+
if (!resolvedArtifacts.externalQuality || sha256Json(resolvedArtifacts.externalQuality) !== sha256Json(resolved.eval.externalQuality)) {
|
|
356
|
+
throw new Error('external quality contract was not frozen into this training job; start a new job with the contract predeclared');
|
|
357
|
+
}
|
|
358
|
+
if (report.lineage?.externalQualityContractDigest !== sha256Json(resolved.eval.externalQuality)) {
|
|
359
|
+
throw new Error('technical evaluation is not bound to the predeclared external quality contract');
|
|
360
|
+
}
|
|
361
|
+
externalQuality = await verifyExternalQuality({
|
|
362
|
+
contract: resolved.eval.externalQuality,
|
|
363
|
+
evidence: qualityReport,
|
|
364
|
+
artifacts: resolvedArtifacts,
|
|
365
|
+
evalReport: report,
|
|
366
|
+
baseDir: resolved.baseDir,
|
|
367
|
+
});
|
|
368
|
+
} else if (qualityReport) {
|
|
369
|
+
throw new Error('qualityReport supplied but eval.externalQuality was not predeclared in the training config');
|
|
370
|
+
}
|
|
328
371
|
const target = path.resolve(resolved.baseDir, outDir ?? path.join(resolved.runRootAbsolute, resolvedArtifacts.jobId, 'export'));
|
|
329
372
|
const bundle = await packageExport({
|
|
330
373
|
outDir: target,
|
|
331
374
|
artifacts: resolvedArtifacts,
|
|
332
375
|
evalReport: report,
|
|
376
|
+
externalQuality,
|
|
333
377
|
config: resolved,
|
|
334
378
|
name: resolved.project,
|
|
335
379
|
version: version ?? VERSION,
|
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,7 +61,7 @@ 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;
|
|
@@ -70,9 +70,9 @@ export async function exactMatchOnRecords(backend, handle, records, { maxNewToke
|
|
|
70
70
|
const predictionDigests = [];
|
|
71
71
|
// Backends that own a large model may load it once and generate each prompt
|
|
72
72
|
// sequentially. The result order and exact-match definition stay identical.
|
|
73
|
-
const generated = scorable.length && typeof backend.generateBatch === 'function'
|
|
73
|
+
const generated = generatedTexts ?? (scorable.length && typeof backend.generateBatch === 'function'
|
|
74
74
|
? await backend.generateBatch({ handle, prompts: scorable.map((record) => record.prompt), maxNewTokens })
|
|
75
|
-
: null;
|
|
75
|
+
: null);
|
|
76
76
|
if (generated && (!Array.isArray(generated) || generated.length !== scorable.length)) {
|
|
77
77
|
throw new Error(`generateBatch returned ${generated?.length ?? 'invalid'} result(s) for ${scorable.length} prompt(s)`);
|
|
78
78
|
}
|
|
@@ -106,6 +106,17 @@ export async function exactMatchOnRecords(backend, handle, records, { maxNewToke
|
|
|
106
106
|
// One model, both splits, plus greedy-decode exact match on holdout.
|
|
107
107
|
export async function evaluateSplitSet(backend, handle, { encoded, records = {}, maxNewTokens = 48 } = {}) {
|
|
108
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
|
+
}
|
|
109
120
|
const holdout = await backend.evaluate({ handle, examples: encoded.holdout });
|
|
110
121
|
const exactMatch = records.holdout?.some(isScorableRecord)
|
|
111
122
|
? await exactMatchOnRecords(backend, handle, records.holdout, { maxNewTokens })
|