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
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Durable CLI/host training request, outside the caller's process lifetime.
|
|
2
|
+
import { mkdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { loadConfig } from '../config.mjs';
|
|
6
|
+
import { ensureDir, exists, readJsonIfExists, writeJson } from '../core/fsx.mjs';
|
|
7
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
8
|
+
import { status as trainingStatus } from '../api.mjs';
|
|
9
|
+
import { launchBackgroundWorker, requireJobId } from './async-evaluate.mjs';
|
|
10
|
+
|
|
11
|
+
const workerFile = fileURLToPath(new URL('./async-train-worker.mjs', import.meta.url));
|
|
12
|
+
|
|
13
|
+
async function location({ baseDir, configFile, jobId, requestId }) {
|
|
14
|
+
const { file, config } = await loadConfig({ file: configFile, baseDir });
|
|
15
|
+
const root = path.join(config.runRootAbsolute, requireJobId(jobId), 'background-training');
|
|
16
|
+
const dir = path.join(root, requestId);
|
|
17
|
+
return { file, root, dir, statusFile: path.join(dir, 'status.json') };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function startBackgroundTraining({
|
|
21
|
+
baseDir, configFile, jobId, resume = true, resumeCancelled = false, auditEveryStep = 10, retry = false,
|
|
22
|
+
} = {}) {
|
|
23
|
+
requireJobId(jobId);
|
|
24
|
+
const { file } = await loadConfig({ file: configFile, baseDir });
|
|
25
|
+
const device = process.env.TMF_DEVICE ?? 'cpu';
|
|
26
|
+
if (!['cpu', 'cuda'].includes(device)) throw new Error('unsupported TMF_DEVICE=' + device);
|
|
27
|
+
const request = {
|
|
28
|
+
kind: 'train', configFile: file, configDigest: await sha256File(file), jobId,
|
|
29
|
+
resume, resumeCancelled, auditEveryStep, device, pythonBin: process.env.TMF_PYTHON ?? 'python3',
|
|
30
|
+
hfMaxMemoryMb: process.env.TMF_HF_MAX_MEMORY_MB ?? null,
|
|
31
|
+
};
|
|
32
|
+
// Resume-cancelled changes the next attempt, not the identity of the job.
|
|
33
|
+
// Otherwise the job-level ownership lock would reject a legitimate resume.
|
|
34
|
+
const requestId = sha256Json({ ...request, resumeCancelled: undefined }).slice(0, 24);
|
|
35
|
+
const loc = await location({ baseDir, configFile: file, jobId, requestId });
|
|
36
|
+
await ensureDir(loc.root);
|
|
37
|
+
// A jobId is immutable, so it belongs to one background request for its
|
|
38
|
+
// lifetime. mkdir is atomic across concurrent callers; changed config or
|
|
39
|
+
// device needs a new jobId rather than racing two workers on the same state.
|
|
40
|
+
const activeDir = path.join(loc.root, 'active.lock');
|
|
41
|
+
const activeFile = path.join(activeDir, 'request.json');
|
|
42
|
+
try {
|
|
43
|
+
await mkdir(activeDir);
|
|
44
|
+
await writeJson(activeFile, { requestId });
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err.code !== 'EEXIST') throw err;
|
|
47
|
+
const active = await readJsonIfExists(activeFile);
|
|
48
|
+
if (!active?.requestId) throw new Error('background training job launch is initializing; retry status shortly');
|
|
49
|
+
if (active.requestId !== requestId) throw new Error(`training job ${jobId} is bound to request ${active.requestId}; use a new jobId for changed inputs`);
|
|
50
|
+
}
|
|
51
|
+
let attempt = 1;
|
|
52
|
+
try {
|
|
53
|
+
await mkdir(loc.dir);
|
|
54
|
+
} catch (err) {
|
|
55
|
+
if (err.code !== 'EEXIST') throw err;
|
|
56
|
+
const prior = await backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
|
|
57
|
+
const canResumeCancelled = prior.state === 'cancelled' && resumeCancelled;
|
|
58
|
+
if (!canResumeCancelled && (!retry || !['failed', 'interrupted'].includes(prior.state))) return prior;
|
|
59
|
+
attempt = (prior.attempt ?? 1) + 1;
|
|
60
|
+
}
|
|
61
|
+
const attemptDir = path.join(loc.dir, `attempt-${attempt}`);
|
|
62
|
+
try {
|
|
63
|
+
await mkdir(attemptDir);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (err.code !== 'EEXIST') throw err;
|
|
66
|
+
return backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
|
|
67
|
+
}
|
|
68
|
+
const requestFile = path.join(attemptDir, 'request.json');
|
|
69
|
+
await writeJson(requestFile, { ...request, requestId, attempt });
|
|
70
|
+
const status = {
|
|
71
|
+
requestId, jobId, state: 'queued', attempt, createdAt: new Date().toISOString(), device,
|
|
72
|
+
logFile: path.join(attemptDir, 'worker.log'),
|
|
73
|
+
};
|
|
74
|
+
await writeJson(loc.statusFile, status);
|
|
75
|
+
try {
|
|
76
|
+
const launch = await launchBackgroundWorker(workerFile, requestFile, loc.statusFile,
|
|
77
|
+
`tmf-train-${requestId}-${attempt}`, status.logFile);
|
|
78
|
+
await writeJson(path.join(attemptDir, 'launch.json'), launch);
|
|
79
|
+
const now = await readJsonIfExists(loc.statusFile);
|
|
80
|
+
if (now?.state === 'queued' && now.attempt === attempt) await writeJson(loc.statusFile, { ...now, ...launch });
|
|
81
|
+
} catch (err) {
|
|
82
|
+
await writeJson(loc.statusFile, {
|
|
83
|
+
...status, state: 'failed', finishedAt: new Date().toISOString(),
|
|
84
|
+
error: { code: 'WORKER_LAUNCH_FAILED', message: err.message },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function backgroundTrainingStatus({ baseDir, configFile, jobId, requestId }) {
|
|
91
|
+
requireJobId(jobId);
|
|
92
|
+
if (typeof requestId !== 'string' || !/^[a-f0-9]{24}$/.test(requestId)) throw new Error('requestId must be a 24-character hex digest');
|
|
93
|
+
const loc = await location({ baseDir, configFile, jobId, requestId });
|
|
94
|
+
const status = await readJsonIfExists(loc.statusFile);
|
|
95
|
+
if (!status) {
|
|
96
|
+
if (!(await exists(loc.dir))) throw new Error('background training not found: ' + requestId);
|
|
97
|
+
return { requestId, jobId, state: 'initializing', statusFile: loc.statusFile };
|
|
98
|
+
}
|
|
99
|
+
const launch = await readJsonIfExists(path.join(loc.dir, `attempt-${status.attempt}`, 'launch.json'));
|
|
100
|
+
const withLaunch = launch ? { ...status, ...launch } : status;
|
|
101
|
+
if (status.state === 'running' && status.pid) {
|
|
102
|
+
try {
|
|
103
|
+
process.kill(status.pid, 0);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (err.code === 'ESRCH') {
|
|
106
|
+
const durable = await trainingStatus({ baseDir, configFile: loc.file, jobId });
|
|
107
|
+
const fresh = durable.found && durable.state?.updatedAt >= status.startedAt;
|
|
108
|
+
const state = fresh && durable.state?.state === 'succeeded' ? 'succeeded'
|
|
109
|
+
: fresh && durable.state?.state === 'cancelled' ? 'cancelled' : 'interrupted';
|
|
110
|
+
const result = {
|
|
111
|
+
...withLaunch, state, finishedAt: new Date().toISOString(),
|
|
112
|
+
jobState: fresh ? durable.state?.state : null,
|
|
113
|
+
};
|
|
114
|
+
if (state === 'interrupted') result.error = { code: 'WORKER_EXITED', message: 'worker exited without a matching durable job result; retry explicitly' };
|
|
115
|
+
await writeJson(loc.statusFile, result);
|
|
116
|
+
return { ...result, statusFile: loc.statusFile };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { ...withLaunch, statusFile: loc.statusFile };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function cancelBackgroundTraining({ baseDir, configFile, jobId, requestId }) {
|
|
124
|
+
const status = await backgroundTrainingStatus({ baseDir, configFile, jobId, requestId });
|
|
125
|
+
if (!['queued', 'running'].includes(status.state)) return status;
|
|
126
|
+
const loc = await location({ baseDir, configFile, jobId, requestId });
|
|
127
|
+
await writeJson(path.join(loc.dir, `attempt-${status.attempt}`, 'cancel.json'), { requestedAt: new Date().toISOString() });
|
|
128
|
+
const latest = await readJsonIfExists(status.statusFile);
|
|
129
|
+
if (latest?.state === 'running' && latest.pid) {
|
|
130
|
+
try { process.kill(latest.pid, 'SIGTERM'); } catch (err) { if (err.code !== 'ESRCH') throw err; }
|
|
131
|
+
} else if (latest?.state === 'queued') {
|
|
132
|
+
await writeJson(status.statusFile, { ...latest, state: 'cancel_requested' });
|
|
133
|
+
}
|
|
134
|
+
return backgroundTrainingStatus({ baseDir, configFile, jobId, requestId });
|
|
135
|
+
}
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
// * No config value is echoed back verbatim; results are the API records.
|
|
18
18
|
|
|
19
19
|
import * as api from '../api.mjs';
|
|
20
|
+
import { startBackgroundEvaluation, backgroundEvaluationStatus } from './async-evaluate.mjs';
|
|
21
|
+
import { startBackgroundTraining, backgroundTrainingStatus, cancelBackgroundTraining } from './async-train.mjs';
|
|
20
22
|
import { VERSION } from '../version.mjs';
|
|
21
23
|
|
|
22
24
|
/** Bumped only on a breaking change to the action set or envelope shape. */
|
|
@@ -49,21 +51,51 @@ const ACTIONS = {
|
|
|
49
51
|
},
|
|
50
52
|
train: {
|
|
51
53
|
summary: 'Run a post-training job that updates real weights or an adapter.',
|
|
52
|
-
params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep'],
|
|
54
|
+
params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep', 'background', 'retry'],
|
|
53
55
|
compute: true,
|
|
54
|
-
handler: (ctx, p) =>
|
|
56
|
+
handler: (ctx, p) => {
|
|
57
|
+
if (p.retry && !p.background) throw new Error('train retry requires background=true');
|
|
58
|
+
if (p.background && p.resume === false) throw new Error('background training requires resume=true');
|
|
59
|
+
if (p.background && !p.jobId) throw new Error('background training requires jobId');
|
|
60
|
+
return p.background
|
|
61
|
+
? startBackgroundTraining({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10, retry: p.retry ?? false })
|
|
62
|
+
: api.train({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, resume: p.resume ?? true, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10 });
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
train_status: {
|
|
66
|
+
summary: 'Read a durable background training receipt without consuming compute.',
|
|
67
|
+
params: ['configFile', 'jobId', 'requestId'],
|
|
68
|
+
required: ['jobId', 'requestId'],
|
|
69
|
+
compute: false,
|
|
70
|
+
handler: (ctx, p) => backgroundTrainingStatus({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
|
|
71
|
+
},
|
|
72
|
+
train_cancel: {
|
|
73
|
+
summary: 'Cancel a background training request while preserving completed checkpoints.',
|
|
74
|
+
params: ['configFile', 'jobId', 'requestId'],
|
|
75
|
+
required: ['jobId', 'requestId'],
|
|
76
|
+
compute: true,
|
|
77
|
+
handler: (ctx, p) => cancelBackgroundTraining({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
|
|
55
78
|
},
|
|
56
79
|
evaluate: {
|
|
57
80
|
summary: 'Score base vs trained model on the independent holdout and apply gates.',
|
|
58
|
-
params: ['configFile', 'jobId', 'gates', 'reportFile', 'maxNewTokens'],
|
|
81
|
+
params: ['configFile', 'jobId', 'gates', 'reportFile', 'maxNewTokens', 'background', 'retry'],
|
|
59
82
|
compute: true,
|
|
60
|
-
handler: (ctx, p) =>
|
|
83
|
+
handler: (ctx, p) => p.background
|
|
84
|
+
? startBackgroundEvaluation({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, gates: p.gates ?? null, reportFile: p.reportFile ?? null, maxNewTokens: p.maxNewTokens ?? 48, retry: p.retry ?? false })
|
|
85
|
+
: api.evaluate({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, gates: p.gates ?? null, reportFile: p.reportFile ?? null, maxNewTokens: p.maxNewTokens ?? 48 }),
|
|
86
|
+
},
|
|
87
|
+
evaluate_status: {
|
|
88
|
+
summary: 'Read a durable background evaluation receipt without consuming compute.',
|
|
89
|
+
params: ['configFile', 'jobId', 'requestId'],
|
|
90
|
+
required: ['jobId', 'requestId'],
|
|
91
|
+
compute: false,
|
|
92
|
+
handler: (ctx, p) => backgroundEvaluationStatus({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
|
|
61
93
|
},
|
|
62
94
|
export: {
|
|
63
95
|
summary: 'Package weights/adapter with lineage, model card and checksums.',
|
|
64
|
-
params: ['configFile', 'jobId', 'evalReport', 'outDir', 'version', 'evaluateIfMissing'],
|
|
96
|
+
params: ['configFile', 'jobId', 'evalReport', 'qualityReport', 'outDir', 'version', 'evaluateIfMissing'],
|
|
65
97
|
compute: true,
|
|
66
|
-
handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
|
|
98
|
+
handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, qualityReport: p.qualityReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
|
|
67
99
|
},
|
|
68
100
|
};
|
|
69
101
|
|
package/src/jobs/evaluate.mjs
CHANGED
|
@@ -87,11 +87,13 @@ export async function runEvaluationJob({
|
|
|
87
87
|
|
|
88
88
|
let tuned = null;
|
|
89
89
|
let tunedFingerprint = null;
|
|
90
|
+
let adapterBaseFingerprint = null;
|
|
90
91
|
if (adapterCheckpoint || tunedCheckpoint) {
|
|
91
92
|
const tunedHandle = adapterCheckpoint
|
|
92
93
|
? await backend.loadModel({ file: baseCheckpoint, attachAdapter: adapterCheckpoint })
|
|
93
94
|
: await backend.loadModel({ file: tunedCheckpoint });
|
|
94
95
|
tunedFingerprint = backend.fingerprint(tunedHandle);
|
|
96
|
+
adapterBaseFingerprint = tunedHandle.meta?.baseFingerprint ?? null;
|
|
95
97
|
tuned = await evaluateSplitSet(backend, tunedHandle, { encoded, records, maxNewTokens });
|
|
96
98
|
}
|
|
97
99
|
|
|
@@ -105,6 +107,10 @@ export async function runEvaluationJob({
|
|
|
105
107
|
startedAt,
|
|
106
108
|
finishedAt: clock(),
|
|
107
109
|
backend: { id: backend.id, label: backend.label ?? null },
|
|
110
|
+
execution: {
|
|
111
|
+
device: baseline.holdout.device ?? null,
|
|
112
|
+
tunedDevice: tuned?.holdout.device ?? null,
|
|
113
|
+
},
|
|
108
114
|
inputs: {
|
|
109
115
|
baseCheckpoint: baseRef,
|
|
110
116
|
adapterCheckpoint: adapterRef,
|
|
@@ -130,16 +136,18 @@ export async function runEvaluationJob({
|
|
|
130
136
|
},
|
|
131
137
|
lineage: {
|
|
132
138
|
...lineage,
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
//
|
|
139
|
+
// Some backends fingerprint the composed base+adapter handle, so its
|
|
140
|
+
// digest must differ from the base. Prefer the base fingerprint recorded
|
|
141
|
+
// in the adapter checkpoint; older backends with no recorded base digest
|
|
142
|
+
// retain the original shared-fingerprint comparison.
|
|
137
143
|
baseFingerprint: baselineFingerprint,
|
|
138
144
|
tunedFingerprint,
|
|
139
145
|
// Only an adapter run can be "bound to base". A full-parameter tuned
|
|
140
146
|
// checkpoint has no adapter, so reporting false there would read as a
|
|
141
147
|
// broken binding instead of "not applicable".
|
|
142
|
-
adapterBoundToBase: adapterCheckpoint
|
|
148
|
+
adapterBoundToBase: adapterCheckpoint
|
|
149
|
+
? (adapterBaseFingerprint ?? tunedFingerprint) === baselineFingerprint
|
|
150
|
+
: null,
|
|
143
151
|
gateDefinitions: gates.map((g) => ({ id: g.id, metric: g.metric, comparator: g.comparator, threshold: g.threshold })),
|
|
144
152
|
gateDefinitionsDigest: sha256Json(gates),
|
|
145
153
|
},
|
package/src/jobs/train.mjs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// so "resume" is the same code path as "load a checkpoint someone else wrote".
|
|
13
13
|
|
|
14
14
|
import path from 'node:path';
|
|
15
|
-
import { runJob, JobCancelledError } from './runner.mjs';
|
|
15
|
+
import { runJob, JobCancelledError, BudgetExceededError } from './runner.mjs';
|
|
16
16
|
import { runDataPipeline } from '../data/pipeline.mjs';
|
|
17
17
|
import { buildTokenizer, encodeRecords } from '../train/dataset.mjs';
|
|
18
18
|
import { ensureDir, readJsonl, writeJson } from '../core/fsx.mjs';
|
|
@@ -64,6 +64,7 @@ export async function runTrainingJob({
|
|
|
64
64
|
modelConfig = {},
|
|
65
65
|
hyper = {},
|
|
66
66
|
trainBudget = {},
|
|
67
|
+
externalQuality = null,
|
|
67
68
|
mode = DEFAULT_TRAIN_JOB_OPTIONS.mode,
|
|
68
69
|
seed = DEFAULT_TRAIN_JOB_OPTIONS.seed,
|
|
69
70
|
maxVocab = DEFAULT_TRAIN_JOB_OPTIONS.maxVocab,
|
|
@@ -106,6 +107,7 @@ export async function runTrainingJob({
|
|
|
106
107
|
seed,
|
|
107
108
|
maxVocab,
|
|
108
109
|
maxSeqLen,
|
|
110
|
+
...(externalQuality ? { externalQuality } : {}),
|
|
109
111
|
};
|
|
110
112
|
|
|
111
113
|
const steps = [
|
|
@@ -197,20 +199,40 @@ export async function runTrainingJob({
|
|
|
197
199
|
baseFingerprint: beforeFingerprint,
|
|
198
200
|
});
|
|
199
201
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
202
|
+
let trained;
|
|
203
|
+
try {
|
|
204
|
+
trained = await backend.train({
|
|
205
|
+
handle,
|
|
206
|
+
examples,
|
|
207
|
+
examplesFile: prepared.examplesFile ?? null,
|
|
208
|
+
mode,
|
|
209
|
+
hyper,
|
|
210
|
+
budget: backend.id === 'hf-peft' ? {
|
|
211
|
+
...trainBudget,
|
|
212
|
+
maxTokens: jobBudget.limits.maxTokens == null ? null : jobBudget.limits.maxTokens - jobBudget.usage.tokens,
|
|
213
|
+
} : trainBudget,
|
|
214
|
+
seed,
|
|
215
|
+
outDir: modelDir,
|
|
216
|
+
signal,
|
|
217
|
+
resume: null,
|
|
218
|
+
hooks: { onStep: makeStepHook({ signal, audit, budget: jobBudget, auditEveryStep }) },
|
|
219
|
+
});
|
|
220
|
+
} catch (err) {
|
|
221
|
+
if (err?.code === 'BACKEND_TOKEN_BUDGET') {
|
|
222
|
+
throw new BudgetExceededError(err.message, { limit: 'maxTokens', limitValue: jobBudget.limits.maxTokens });
|
|
223
|
+
}
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
213
226
|
const { metrics, history, stopReason } = trained;
|
|
227
|
+
// HF runs outside Node, so its per-batch count returns at job-step end.
|
|
228
|
+
// The Python collator already stops before a batch that would exceed
|
|
229
|
+
// the cap; charging here records the verified consumption durably.
|
|
230
|
+
if (backend.id === 'hf-peft') {
|
|
231
|
+
if (!Number.isSafeInteger(metrics.tokensSeen) || metrics.tokensSeen < 0) {
|
|
232
|
+
throw new Error('hf-peft did not report a valid consumed-token count');
|
|
233
|
+
}
|
|
234
|
+
jobBudget.charge({ tokens: metrics.tokensSeen });
|
|
235
|
+
}
|
|
214
236
|
// A backend may return a moved handle (hf-peft points it at the adapter
|
|
215
237
|
// directory the worker just wrote); saving the pre-train handle would
|
|
216
238
|
// persist a checkpoint that does not reference the trained weights.
|
|
@@ -268,6 +290,7 @@ export async function runTrainingJob({
|
|
|
268
290
|
data: outputs.data,
|
|
269
291
|
base: outputs.base,
|
|
270
292
|
train: outputs.train,
|
|
293
|
+
...(externalQuality ? { externalQuality } : {}),
|
|
271
294
|
};
|
|
272
295
|
const manifestFile = path.join(jobDir, 'train-manifest.json');
|
|
273
296
|
await writeJson(manifestFile, manifest);
|
|
@@ -299,5 +322,6 @@ export function trainingArtifacts(job) {
|
|
|
299
322
|
adapterCheckpoint: train.kind === 'adapter' ? train.checkpoint : null,
|
|
300
323
|
tunedCheckpoint: train.kind === 'adapter' ? null : train.checkpoint,
|
|
301
324
|
metrics: train.metrics,
|
|
325
|
+
externalQuality: job.result.externalQuality ?? null,
|
|
302
326
|
};
|
|
303
327
|
}
|
|
@@ -37,7 +37,10 @@ const RESULT_PREFIX = '__TMF_RESULT__';
|
|
|
37
37
|
|
|
38
38
|
// Defaults kept small on purpose: this backend is expected to run on a CPU box
|
|
39
39
|
// next to the rest of the toolchain, not on a training cluster.
|
|
40
|
-
|
|
40
|
+
// This is a virtual-address-space cap, not resident RAM. Importing CUDA-enabled
|
|
41
|
+
// PyTorch can reserve more than 4 GiB of address space before model loading;
|
|
42
|
+
// keep the explicit caller override for tighter bounded jobs.
|
|
43
|
+
const DEFAULT_LIMITS = { maxMemoryMb: 65536, threads: 1, maxSeqLen: 128 };
|
|
41
44
|
|
|
42
45
|
function pythonBin() {
|
|
43
46
|
return process.env.TMF_PYTHON || 'python3';
|
|
@@ -132,8 +135,12 @@ async function writeSpec(spec, { outDir, op }) {
|
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
function limitsFrom(budget = {}, overrides = {}) {
|
|
138
|
+
const envMemory = process.env.TMF_HF_MAX_MEMORY_MB;
|
|
139
|
+
if (envMemory !== undefined && (!Number.isInteger(Number(envMemory)) || Number(envMemory) <= 0)) {
|
|
140
|
+
throw new Error('TMF_HF_MAX_MEMORY_MB must be a positive integer');
|
|
141
|
+
}
|
|
135
142
|
return {
|
|
136
|
-
maxMemoryMb: overrides.maxMemoryMb ?? budget.maxMemoryMb ?? DEFAULT_LIMITS.maxMemoryMb,
|
|
143
|
+
maxMemoryMb: overrides.maxMemoryMb ?? budget.maxMemoryMb ?? (envMemory ? Number(envMemory) : DEFAULT_LIMITS.maxMemoryMb),
|
|
137
144
|
maxCpuSeconds: overrides.maxCpuSeconds ?? budget.maxCpuSeconds ?? null,
|
|
138
145
|
threads: overrides.threads ?? budget.threads ?? DEFAULT_LIMITS.threads,
|
|
139
146
|
maxSeqLen: overrides.maxSeqLen ?? DEFAULT_LIMITS.maxSeqLen,
|
|
@@ -162,7 +169,8 @@ async function runOp(op, spec, { outDir, timeoutMs, signal }) {
|
|
|
162
169
|
`hf-peft ${op} failed (exit ${result.code}${result.signal ? `, signal ${result.signal}` : ''})`
|
|
163
170
|
+ `${memoryBound ? ' due to the configured memory limit' : ''}: ${stderr.slice(-500)}`,
|
|
164
171
|
);
|
|
165
|
-
err.code =
|
|
172
|
+
err.code = /TMF_TRAIN_TOKEN_BUDGET_EXCEEDED/.test(stderr) ? 'BACKEND_TOKEN_BUDGET'
|
|
173
|
+
: memoryBound ? 'BACKEND_MEMORY_LIMIT'
|
|
166
174
|
: result.signal === 'SIGKILL' ? 'BACKEND_RESOURCE_LIMIT'
|
|
167
175
|
: result.timedOut ? 'BACKEND_TIMEOUT' : 'BACKEND_FAILED';
|
|
168
176
|
err.specFile = specFile;
|
|
@@ -230,7 +238,7 @@ const backend = {
|
|
|
230
238
|
// network.
|
|
231
239
|
resourceBounds: ['max-steps', 'max-seconds', 'max-memory-mb', 'max-cpu-seconds', 'threads'],
|
|
232
240
|
isolation: 'process-rlimit',
|
|
233
|
-
precision: 'float32',
|
|
241
|
+
precision: 'float32,bfloat16,nf4',
|
|
234
242
|
requiresLocalModelCache: true,
|
|
235
243
|
},
|
|
236
244
|
|
|
@@ -344,6 +352,7 @@ const backend = {
|
|
|
344
352
|
dir: adapterDir,
|
|
345
353
|
adapterDir,
|
|
346
354
|
mode: adapter.mode ?? 'lora',
|
|
355
|
+
modelConfig: adapter.modelConfig ?? payload.modelConfig ?? {},
|
|
347
356
|
meta: { ...(adapter.meta ?? {}), attachedTo: file },
|
|
348
357
|
file: attachAdapter,
|
|
349
358
|
};
|
|
@@ -355,6 +364,7 @@ const backend = {
|
|
|
355
364
|
dir: payload.dir,
|
|
356
365
|
adapterDir: payload.adapterDir ?? payload.dir ?? null,
|
|
357
366
|
mode: payload.mode ?? 'lora',
|
|
367
|
+
modelConfig: payload.modelConfig ?? {},
|
|
358
368
|
meta: payload.meta ?? {},
|
|
359
369
|
file,
|
|
360
370
|
};
|
|
@@ -395,6 +405,7 @@ const backend = {
|
|
|
395
405
|
dir: handle.dir ?? handle.adapterDir ?? null,
|
|
396
406
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
397
407
|
mode: handle.mode ?? 'lora',
|
|
408
|
+
modelConfig: handle.modelConfig ?? {},
|
|
398
409
|
meta,
|
|
399
410
|
};
|
|
400
411
|
await writeFileAtomic(file, `${JSON.stringify(payload)}\n`);
|
|
@@ -406,12 +417,13 @@ const backend = {
|
|
|
406
417
|
// without running it.
|
|
407
418
|
async renderTrainingScript({ handle, examplesFile, hyper = {}, budget = {}, outDir, mode, resumeFrom = null }) {
|
|
408
419
|
await ensureDir(outDir);
|
|
409
|
-
const limits = limitsFrom(budget, hyper);
|
|
420
|
+
const limits = limitsFrom(budget, { ...hyper, maxSeqLen: handle?.modelConfig?.maxSeqLen ?? hyper.maxSeqLen });
|
|
410
421
|
const spec = {
|
|
411
422
|
op: 'train',
|
|
412
423
|
modelId: handle?.modelId ?? 'MODEL_ID',
|
|
413
424
|
adapterDir: handle?.adapterDir ?? null,
|
|
414
425
|
mode: mode ?? handle?.mode ?? 'lora',
|
|
426
|
+
hf: handle?.modelConfig?.hf ?? {},
|
|
415
427
|
examplesFile,
|
|
416
428
|
outDir,
|
|
417
429
|
resumeFrom,
|
|
@@ -421,6 +433,7 @@ const backend = {
|
|
|
421
433
|
lora: hyper.lora ?? { rank: 8, alpha: 16, targets: ['q_proj', 'v_proj'] },
|
|
422
434
|
budget: {
|
|
423
435
|
maxSteps: budget.maxSteps ?? 20,
|
|
436
|
+
maxTokens: budget.maxTokens ?? null,
|
|
424
437
|
maxSeconds: budget.maxSeconds ?? null,
|
|
425
438
|
checkpointEvery: budget.checkpointEvery ?? 0,
|
|
426
439
|
},
|
|
@@ -455,6 +468,17 @@ const backend = {
|
|
|
455
468
|
trainFile = path.join(outDir, 'train-examples.jsonl');
|
|
456
469
|
await writeFileAtomic(trainFile, `${examples.map((e) => JSON.stringify(e)).join('\n')}\n`);
|
|
457
470
|
}
|
|
471
|
+
// A cancelled CLI job re-enters the train job-step without an explicit
|
|
472
|
+
// backend resume argument. Recover only a complete Trainer checkpoint;
|
|
473
|
+
// anything after that checkpoint is deliberately replayed.
|
|
474
|
+
if (!resume && fs.existsSync(outDir)) {
|
|
475
|
+
const checkpoints = fs.readdirSync(outDir, { withFileTypes: true })
|
|
476
|
+
.filter((entry) => entry.isDirectory() && /^checkpoint-\d+$/.test(entry.name))
|
|
477
|
+
.map((entry) => ({ step: Number(entry.name.slice('checkpoint-'.length)), path: path.join(outDir, entry.name) }))
|
|
478
|
+
.filter((entry) => fs.existsSync(path.join(entry.path, 'trainer_state.json')))
|
|
479
|
+
.sort((a, b) => b.step - a.step);
|
|
480
|
+
resume = checkpoints[0]?.path ?? null;
|
|
481
|
+
}
|
|
458
482
|
const rendered = await backend.renderTrainingScript({
|
|
459
483
|
handle, examplesFile: trainFile, hyper, budget, outDir, mode, resumeFrom: resume,
|
|
460
484
|
});
|
|
@@ -503,8 +527,13 @@ const backend = {
|
|
|
503
527
|
modelId: handle.modelId,
|
|
504
528
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
505
529
|
mode: handle.mode ?? 'lora',
|
|
530
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
506
531
|
examplesFile: file,
|
|
507
|
-
...limitsFrom(budget,
|
|
532
|
+
...limitsFrom(budget, {
|
|
533
|
+
...hyper,
|
|
534
|
+
maxMemoryMb: handle.modelConfig?.hf?.maxMemoryMb ?? hyper.maxMemoryMb,
|
|
535
|
+
maxSeqLen: handle.modelConfig?.maxSeqLen ?? hyper.maxSeqLen,
|
|
536
|
+
}),
|
|
508
537
|
};
|
|
509
538
|
const { payload } = await runOp('evaluate', spec, {
|
|
510
539
|
outDir: dir, timeoutMs: ((budget.maxSeconds ?? 600) + 120) * 1000, signal,
|
|
@@ -515,11 +544,58 @@ const backend = {
|
|
|
515
544
|
tokens: payload.tokens,
|
|
516
545
|
examples: payload.examples,
|
|
517
546
|
adapterLoaded: payload.adapterLoaded,
|
|
547
|
+
device: payload.device,
|
|
518
548
|
backend: backend.id,
|
|
519
549
|
limits: payload.limits,
|
|
520
550
|
};
|
|
521
551
|
},
|
|
522
552
|
|
|
553
|
+
// One offline model load scores both loss splits and generates the holdout
|
|
554
|
+
// continuations. The evaluator keeps the same exact-match diagnostics and
|
|
555
|
+
// gate logic; only the redundant Python/model startups are removed.
|
|
556
|
+
async evaluateSplitSet({
|
|
557
|
+
handle, holdoutExamples, validationExamples = [], prompts = [], maxNewTokens = 48,
|
|
558
|
+
budget = {}, signal = null, outDir,
|
|
559
|
+
} = {}) {
|
|
560
|
+
const probe = await backend.probe();
|
|
561
|
+
if (!probe.available) throw unavailable('evaluate split set', probe);
|
|
562
|
+
if (!handle?.modelId || !Array.isArray(holdoutExamples) || !holdoutExamples.length) {
|
|
563
|
+
throw new Error('hf-peft evaluateSplitSet needs a model and non-empty holdout examples');
|
|
564
|
+
}
|
|
565
|
+
const dir = outDir ?? path.join(process.cwd(), '.tmf-run', 'hf-peft-eval-bundle');
|
|
566
|
+
await ensureDir(dir);
|
|
567
|
+
const holdoutFile = path.join(dir, 'holdout-examples.jsonl');
|
|
568
|
+
const validationFile = path.join(dir, 'validation-examples.jsonl');
|
|
569
|
+
const promptsFile = path.join(dir, 'prompts.jsonl');
|
|
570
|
+
await writeFileAtomic(holdoutFile, `${holdoutExamples.map((e) => JSON.stringify(e)).join('\n')}\n`);
|
|
571
|
+
await writeFileAtomic(validationFile, `${validationExamples.map((e) => JSON.stringify(e)).join('\n')}${validationExamples.length ? '\n' : ''}`);
|
|
572
|
+
await writeFileAtomic(promptsFile, `${prompts.map((prompt) => JSON.stringify({ prompt })).join('\n')}${prompts.length ? '\n' : ''}`);
|
|
573
|
+
const hf = handle.modelConfig?.hf ?? {};
|
|
574
|
+
const spec = {
|
|
575
|
+
modelId: handle.modelId, adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
576
|
+
mode: handle.mode ?? 'lora', hf, holdoutFile, validationFile, promptsFile, maxNewTokens,
|
|
577
|
+
...limitsFrom(budget, {
|
|
578
|
+
maxMemoryMb: hf.maxMemoryMb,
|
|
579
|
+
maxSeqLen: handle.modelConfig?.maxSeqLen,
|
|
580
|
+
}),
|
|
581
|
+
};
|
|
582
|
+
const maxSeconds = budget.maxSeconds ?? hf.evalMaxSeconds ?? 1800;
|
|
583
|
+
const { payload } = await runOp('evaluate_bundle', spec, {
|
|
584
|
+
outDir: dir, timeoutMs: (maxSeconds + 120) * 1000, signal,
|
|
585
|
+
});
|
|
586
|
+
if (!Array.isArray(payload.texts) || payload.texts.length !== prompts.length) {
|
|
587
|
+
throw new Error(`hf-peft evaluate_bundle returned ${payload.texts?.length ?? 'invalid'} predictions for ${prompts.length} prompts`);
|
|
588
|
+
}
|
|
589
|
+
const metrics = (part) => part && ({
|
|
590
|
+
loss: part.loss, perplexity: part.perplexity, tokens: part.tokens,
|
|
591
|
+
examples: part.examples, adapterLoaded: payload.adapterLoaded,
|
|
592
|
+
device: payload.device, backend: backend.id, limits: payload.limits,
|
|
593
|
+
wallClockSeconds: payload.wallClockSeconds, peakRssMb: payload.peakRssMb,
|
|
594
|
+
peakCudaAllocatedMb: payload.peakCudaAllocatedMb,
|
|
595
|
+
});
|
|
596
|
+
return { holdout: metrics(payload.holdout), validation: metrics(payload.validation), texts: payload.texts };
|
|
597
|
+
},
|
|
598
|
+
|
|
523
599
|
async generate({
|
|
524
600
|
handle, prompt, maxNewTokens = 16, temperature = 0, seed = 1,
|
|
525
601
|
hyper = {}, budget = {}, signal = null, outDir,
|
|
@@ -532,6 +608,7 @@ const backend = {
|
|
|
532
608
|
modelId: handle.modelId,
|
|
533
609
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
534
610
|
mode: handle.mode ?? 'lora',
|
|
611
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
535
612
|
prompt: prompt ?? '',
|
|
536
613
|
maxNewTokens,
|
|
537
614
|
temperature,
|
|
@@ -544,6 +621,40 @@ const backend = {
|
|
|
544
621
|
// Same shape as the builtin backend: callers get the decoded continuation.
|
|
545
622
|
return payload.text;
|
|
546
623
|
},
|
|
624
|
+
|
|
625
|
+
async generateBatch({
|
|
626
|
+
handle, prompts, maxNewTokens = 16, temperature = 0, seed = 1,
|
|
627
|
+
hyper = {}, budget = {}, signal = null, outDir,
|
|
628
|
+
} = {}) {
|
|
629
|
+
const probe = await backend.probe();
|
|
630
|
+
if (!probe.available) throw unavailable('generate a batch', probe);
|
|
631
|
+
if (!handle?.modelId) throw new Error('hf-peft generateBatch() requires a handle with modelId');
|
|
632
|
+
if (!Array.isArray(prompts) || prompts.length === 0 || prompts.some((prompt) => typeof prompt !== 'string')) {
|
|
633
|
+
throw new Error('hf-peft generateBatch() requires a non-empty array of string prompts');
|
|
634
|
+
}
|
|
635
|
+
const dir = outDir ?? path.join(process.cwd(), '.tmf-run', 'hf-peft-gen-batch');
|
|
636
|
+
await ensureDir(dir);
|
|
637
|
+
const promptsFile = path.join(dir, 'prompts.jsonl');
|
|
638
|
+
await writeFileAtomic(promptsFile, `${prompts.map((prompt) => JSON.stringify({ prompt })).join('\n')}\n`);
|
|
639
|
+
const spec = {
|
|
640
|
+
modelId: handle.modelId,
|
|
641
|
+
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
642
|
+
mode: handle.mode ?? 'lora',
|
|
643
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
644
|
+
promptsFile,
|
|
645
|
+
maxNewTokens,
|
|
646
|
+
temperature,
|
|
647
|
+
seed,
|
|
648
|
+
...limitsFrom(budget, hyper),
|
|
649
|
+
};
|
|
650
|
+
const { payload } = await runOp('generate_batch', spec, {
|
|
651
|
+
outDir: dir, timeoutMs: ((budget.maxSeconds ?? 600) + 120) * 1000, signal,
|
|
652
|
+
});
|
|
653
|
+
if (!Array.isArray(payload.texts) || payload.texts.length !== prompts.length) {
|
|
654
|
+
throw new Error(`hf-peft generateBatch returned ${payload.texts?.length ?? 'invalid'} result(s) for ${prompts.length} prompt(s)`);
|
|
655
|
+
}
|
|
656
|
+
return payload.texts;
|
|
657
|
+
},
|
|
547
658
|
};
|
|
548
659
|
|
|
549
660
|
export default backend;
|