taskforce-model-foundry 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/tmf.mjs +353 -0
- package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +75 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +228 -0
- package/docs/releases/v0.2.0.md +24 -0
- package/docs/tutorial.md +340 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
- package/integrations/hermes-plugin/tests/test_register.py +230 -0
- package/integrations/openclaw-plugin/index.mjs +27 -0
- package/integrations/openclaw-plugin/tools.mjs +73 -0
- package/openclaw.plugin.json +25 -0
- package/package.json +70 -4
- package/scripts/e2e-demo.sh +56 -0
- package/src/api.mjs +341 -0
- package/src/config.mjs +342 -0
- package/src/core/autograd.mjs +451 -0
- package/src/core/fsx.mjs +65 -0
- package/src/core/hash.mjs +47 -0
- package/src/core/rng.mjs +70 -0
- package/src/data/clean.mjs +115 -0
- package/src/data/dedupe.mjs +125 -0
- package/src/data/ingest.mjs +184 -0
- package/src/data/pii.mjs +142 -0
- package/src/data/pipeline.mjs +183 -0
- package/src/data/provenance.mjs +88 -0
- package/src/data/split.mjs +193 -0
- package/src/data/synth.mjs +198 -0
- package/src/eval/evaluator.mjs +137 -0
- package/src/eval/gates.mjs +114 -0
- package/src/eval/metrics.mjs +90 -0
- package/src/export/package.mjs +365 -0
- package/src/index.mjs +26 -0
- package/src/integrations/async-evaluate-worker.mjs +39 -0
- package/src/integrations/async-evaluate.mjs +125 -0
- package/src/integrations/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +164 -0
- package/src/jobs/evaluate.mjs +172 -0
- package/src/jobs/runner.mjs +323 -0
- package/src/jobs/train.mjs +303 -0
- package/src/model/lora.mjs +53 -0
- package/src/model/tokenizer.mjs +73 -0
- package/src/model/transformer.mjs +276 -0
- package/src/train/backends/builtin-js.mjs +367 -0
- package/src/train/backends/hf-peft.mjs +597 -0
- package/src/train/backends/hf_peft_runner.py +397 -0
- package/src/train/backends/index.mjs +92 -0
- package/src/train/dataset.mjs +56 -0
- package/src/train/optimizer.mjs +99 -0
- package/src/version.mjs +5 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// Auditable job orchestration.
|
|
2
|
+
//
|
|
3
|
+
// Every long-running foundry job (data prep, training, evaluation, export) runs
|
|
4
|
+
// through this runner so the operator gets the same guarantees regardless of
|
|
5
|
+
// which job it is: a durable state machine, an append-only audit log that is
|
|
6
|
+
// safe to hand to a reviewer, resume after a crash, cooperative cancellation,
|
|
7
|
+
// hard budget caps, and replay that does not redo completed side effects.
|
|
8
|
+
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { appendJsonl, ensureDir, readJsonIfExists, readJsonl, writeJson } from '../core/fsx.mjs';
|
|
11
|
+
import { sha256Json } from '../core/hash.mjs';
|
|
12
|
+
import { redactPii } from '../data/pii.mjs';
|
|
13
|
+
|
|
14
|
+
export const JOB_STATES = ['pending', 'running', 'succeeded', 'failed', 'cancelled', 'budget_exceeded'];
|
|
15
|
+
|
|
16
|
+
const TERMINAL_STATES = new Set(['succeeded', 'failed', 'cancelled', 'budget_exceeded']);
|
|
17
|
+
|
|
18
|
+
// Only these transitions are legal. An illegal transition is a bug in a job
|
|
19
|
+
// implementation, so it throws rather than being recorded as job failure.
|
|
20
|
+
const TRANSITIONS = {
|
|
21
|
+
pending: ['running', 'cancelled'],
|
|
22
|
+
running: ['running', 'succeeded', 'failed', 'cancelled', 'budget_exceeded'],
|
|
23
|
+
succeeded: [],
|
|
24
|
+
failed: [],
|
|
25
|
+
// Operator cancellation is a pause, not a verdict: the completed steps are
|
|
26
|
+
// still valid, so an explicit `resumeCancelled` run continues the same job.
|
|
27
|
+
cancelled: ['running'],
|
|
28
|
+
budget_exceeded: [],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Matched against the normalized key, exactly: a budget field named `tokens`
|
|
32
|
+
// or `maxTokens` must stay readable while an `accessToken` must not.
|
|
33
|
+
const SECRET_KEYS = new Set([
|
|
34
|
+
'token', 'accesstoken', 'refreshtoken', 'idtoken', 'authtoken', 'sessiontoken',
|
|
35
|
+
'secret', 'clientsecret', 'password', 'passwd', 'pwd', 'passphrase',
|
|
36
|
+
'apikey', 'apisecret', 'credential', 'credentials', 'authorization', 'auth',
|
|
37
|
+
'cookie', 'bearer', 'privatekey', 'sessionkey', 'signingkey',
|
|
38
|
+
]);
|
|
39
|
+
const REDACTED = '[REDACTED]';
|
|
40
|
+
|
|
41
|
+
export class JobCancelledError extends Error {
|
|
42
|
+
constructor(message = 'job cancelled') {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = 'JobCancelledError';
|
|
45
|
+
this.code = 'JOB_CANCELLED';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class BudgetExceededError extends Error {
|
|
50
|
+
constructor(message, details = {}) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = 'BudgetExceededError';
|
|
53
|
+
this.code = 'JOB_BUDGET_EXCEEDED';
|
|
54
|
+
this.details = details;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function assertTransition(from, to) {
|
|
59
|
+
if (!JOB_STATES.includes(to)) throw new Error(`unknown job state: ${to}`);
|
|
60
|
+
const allowed = TRANSITIONS[from] ?? [];
|
|
61
|
+
if (!allowed.includes(to)) {
|
|
62
|
+
throw new Error(`illegal job state transition: ${from} -> ${to}`);
|
|
63
|
+
}
|
|
64
|
+
return to;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function isTerminal(state) {
|
|
68
|
+
return TERMINAL_STATES.has(state);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Redaction is applied to everything that reaches the audit log. Keys that name
|
|
72
|
+
// a credential are dropped wholesale (the value shape itself can leak); free
|
|
73
|
+
// text goes through the same PII rules the data pipeline uses.
|
|
74
|
+
export function isSecretKey(key) {
|
|
75
|
+
return SECRET_KEYS.has(String(key).replace(/[^a-z0-9]/gi, '').toLowerCase());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function redactForAudit(value, depth = 0) {
|
|
79
|
+
if (depth > 8) return '[TRUNCATED]';
|
|
80
|
+
if (value === null || value === undefined) return value ?? null;
|
|
81
|
+
if (typeof value === 'string') return redactPii(value).text;
|
|
82
|
+
if (typeof value === 'number' || typeof value === 'boolean') return value;
|
|
83
|
+
if (Array.isArray(value)) return value.map((item) => redactForAudit(item, depth + 1));
|
|
84
|
+
if (typeof value === 'object') {
|
|
85
|
+
const out = {};
|
|
86
|
+
for (const [key, item] of Object.entries(value)) {
|
|
87
|
+
out[key] = isSecretKey(key) ? REDACTED : redactForAudit(item, depth + 1);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
return String(value);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class JobBudget {
|
|
95
|
+
constructor({ maxSteps = null, maxWallClockMs = null, maxTokens = null, maxCostUsd = null } = {}) {
|
|
96
|
+
this.limits = { maxSteps, maxWallClockMs, maxTokens, maxCostUsd };
|
|
97
|
+
this.usage = { steps: 0, wallClockMs: 0, tokens: 0, costUsd: 0 };
|
|
98
|
+
this.startedAt = null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
start(now) {
|
|
102
|
+
this.startedAt = now;
|
|
103
|
+
return this;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Charged before a step runs so an over-budget job stops instead of spending.
|
|
107
|
+
charge({ steps = 0, tokens = 0, costUsd = 0 } = {}, now = Date.now()) {
|
|
108
|
+
const next = {
|
|
109
|
+
steps: this.usage.steps + steps,
|
|
110
|
+
tokens: this.usage.tokens + tokens,
|
|
111
|
+
costUsd: this.usage.costUsd + costUsd,
|
|
112
|
+
wallClockMs: this.startedAt === null ? 0 : now - this.startedAt,
|
|
113
|
+
};
|
|
114
|
+
const checks = [
|
|
115
|
+
['maxSteps', next.steps, 'steps'],
|
|
116
|
+
['maxTokens', next.tokens, 'tokens'],
|
|
117
|
+
['maxCostUsd', next.costUsd, 'costUsd'],
|
|
118
|
+
['maxWallClockMs', next.wallClockMs, 'wallClockMs'],
|
|
119
|
+
];
|
|
120
|
+
for (const [limitKey, value, usageKey] of checks) {
|
|
121
|
+
const limit = this.limits[limitKey];
|
|
122
|
+
if (limit !== null && limit !== undefined && value > limit) {
|
|
123
|
+
throw new BudgetExceededError(`budget exceeded: ${usageKey} ${value} > ${limit}`, {
|
|
124
|
+
limit: limitKey,
|
|
125
|
+
limitValue: limit,
|
|
126
|
+
attempted: value,
|
|
127
|
+
usage: { ...this.usage },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
this.usage = next;
|
|
132
|
+
return this.usage;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
snapshot(now = Date.now()) {
|
|
136
|
+
return {
|
|
137
|
+
limits: { ...this.limits },
|
|
138
|
+
usage: { ...this.usage, wallClockMs: this.startedAt === null ? this.usage.wallClockMs : now - this.startedAt },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function jobPaths(root, jobId) {
|
|
144
|
+
const dir = path.join(root, jobId);
|
|
145
|
+
return {
|
|
146
|
+
dir,
|
|
147
|
+
state: path.join(dir, 'state.json'),
|
|
148
|
+
audit: path.join(dir, 'audit.jsonl'),
|
|
149
|
+
result: path.join(dir, 'result.json'),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function readJobState(root, jobId) {
|
|
154
|
+
return readJsonIfExists(jobPaths(root, jobId).state, null);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function readAuditLog(root, jobId) {
|
|
158
|
+
const rows = await readJsonl(jobPaths(root, jobId).audit).catch(() => []);
|
|
159
|
+
return rows;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A job is a declarative list of named steps. Each step's recorded output is the
|
|
163
|
+
// resume unit: on replay a step whose record already exists is skipped and its
|
|
164
|
+
// stored output is reused, so completed side effects are never repeated.
|
|
165
|
+
export async function runJob({
|
|
166
|
+
jobId,
|
|
167
|
+
kind,
|
|
168
|
+
root,
|
|
169
|
+
steps,
|
|
170
|
+
input = {},
|
|
171
|
+
budget = {},
|
|
172
|
+
signal = null,
|
|
173
|
+
now = () => Date.now(),
|
|
174
|
+
resume = true,
|
|
175
|
+
resumeCancelled = false,
|
|
176
|
+
} = {}) {
|
|
177
|
+
if (!jobId) throw new Error('runJob requires jobId');
|
|
178
|
+
if (!kind) throw new Error('runJob requires kind');
|
|
179
|
+
if (!root) throw new Error('runJob requires root');
|
|
180
|
+
if (!Array.isArray(steps) || steps.length === 0) throw new Error('runJob requires at least one step');
|
|
181
|
+
|
|
182
|
+
const paths = jobPaths(root, jobId);
|
|
183
|
+
await ensureDir(paths.dir);
|
|
184
|
+
|
|
185
|
+
const inputDigest = sha256Json(input);
|
|
186
|
+
const planDigest = sha256Json(steps.map((step) => ({ name: step.name, cost: step.cost ?? null })));
|
|
187
|
+
|
|
188
|
+
const prior = resume ? await readJsonIfExists(paths.state, null) : null;
|
|
189
|
+
if (prior) {
|
|
190
|
+
if (prior.inputDigest !== inputDigest || prior.planDigest !== planDigest) {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`job ${jobId} already exists with a different input/plan digest; use a new jobId instead of mutating history`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
// Idempotency: a finished job is returned as-is, not re-executed. The one
|
|
196
|
+
// exception is a cancelled job the caller explicitly asks to continue,
|
|
197
|
+
// which picks up at the first step that never completed.
|
|
198
|
+
const continuable = prior.state === 'cancelled' && resumeCancelled;
|
|
199
|
+
if (isTerminal(prior.state) && !continuable) {
|
|
200
|
+
const result = await readJsonIfExists(paths.result, null);
|
|
201
|
+
return { ...prior, replayed: true, result: result?.result ?? null };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const jobBudget = new JobBudget({ ...(prior?.budget?.limits ?? {}), ...budget });
|
|
206
|
+
jobBudget.usage = { ...jobBudget.usage, ...(prior?.budget?.usage ?? {}) };
|
|
207
|
+
const startedAt = prior?.startedAt ?? new Date(now()).toISOString();
|
|
208
|
+
jobBudget.start(now());
|
|
209
|
+
|
|
210
|
+
let state = {
|
|
211
|
+
version: 1,
|
|
212
|
+
jobId,
|
|
213
|
+
kind,
|
|
214
|
+
state: prior?.state ?? 'pending',
|
|
215
|
+
attempt: (prior?.attempt ?? 0) + 1,
|
|
216
|
+
inputDigest,
|
|
217
|
+
planDigest,
|
|
218
|
+
startedAt,
|
|
219
|
+
updatedAt: startedAt,
|
|
220
|
+
completedSteps: prior?.completedSteps ?? [],
|
|
221
|
+
budget: jobBudget.snapshot(now()),
|
|
222
|
+
error: null,
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const audit = async (event, payload = {}) => {
|
|
226
|
+
await appendJsonl(paths.audit, {
|
|
227
|
+
ts: new Date(now()).toISOString(),
|
|
228
|
+
jobId,
|
|
229
|
+
kind,
|
|
230
|
+
attempt: state.attempt,
|
|
231
|
+
event,
|
|
232
|
+
...redactForAudit(payload),
|
|
233
|
+
});
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const persist = async (nextState, extra = {}) => {
|
|
237
|
+
if (nextState && nextState !== state.state) assertTransition(state.state, nextState);
|
|
238
|
+
state = {
|
|
239
|
+
...state,
|
|
240
|
+
...extra,
|
|
241
|
+
state: nextState ?? state.state,
|
|
242
|
+
budget: jobBudget.snapshot(now()),
|
|
243
|
+
updatedAt: new Date(now()).toISOString(),
|
|
244
|
+
};
|
|
245
|
+
await writeJson(paths.state, state);
|
|
246
|
+
return state;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const checkCancel = async () => {
|
|
250
|
+
if (signal?.aborted) {
|
|
251
|
+
await audit('job.cancelled', { reason: signal.reason ? String(signal.reason) : 'signal aborted' });
|
|
252
|
+
await persist('cancelled', { error: { code: 'JOB_CANCELLED', message: 'job cancelled' } });
|
|
253
|
+
throw new JobCancelledError();
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
await audit(prior ? 'job.resumed' : 'job.started', {
|
|
258
|
+
inputDigest,
|
|
259
|
+
planDigest,
|
|
260
|
+
completedSteps: state.completedSteps.map((s) => s.name),
|
|
261
|
+
budgetLimits: jobBudget.limits,
|
|
262
|
+
});
|
|
263
|
+
await checkCancel();
|
|
264
|
+
await persist('running');
|
|
265
|
+
|
|
266
|
+
const outputs = {};
|
|
267
|
+
for (const done of state.completedSteps) outputs[done.name] = done.output ?? null;
|
|
268
|
+
|
|
269
|
+
for (const step of steps) {
|
|
270
|
+
if (!step?.name || typeof step.run !== 'function') {
|
|
271
|
+
throw new Error('each step requires { name, run }');
|
|
272
|
+
}
|
|
273
|
+
const already = state.completedSteps.find((s) => s.name === step.name);
|
|
274
|
+
if (already) {
|
|
275
|
+
await audit('step.skipped', { step: step.name, reason: 'already completed in a prior attempt' });
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
await checkCancel();
|
|
279
|
+
try {
|
|
280
|
+
jobBudget.charge({ steps: 1, ...(step.cost ?? {}) }, now());
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (error instanceof BudgetExceededError) {
|
|
283
|
+
await audit('job.budget_exceeded', { step: step.name, ...error.details });
|
|
284
|
+
await persist('budget_exceeded', { error: { code: error.code, message: error.message, details: error.details } });
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
await audit('step.started', { step: step.name });
|
|
290
|
+
let output;
|
|
291
|
+
try {
|
|
292
|
+
output = await step.run({ input, outputs, signal, audit, budget: jobBudget });
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (error instanceof JobCancelledError || signal?.aborted) {
|
|
295
|
+
await audit('job.cancelled', { step: step.name, reason: error.message });
|
|
296
|
+
await persist('cancelled', { error: { code: 'JOB_CANCELLED', message: error.message } });
|
|
297
|
+
throw error instanceof JobCancelledError ? error : new JobCancelledError(error.message);
|
|
298
|
+
}
|
|
299
|
+
if (error instanceof BudgetExceededError) {
|
|
300
|
+
await audit('job.budget_exceeded', { step: step.name, ...error.details });
|
|
301
|
+
await persist('budget_exceeded', { error: { code: error.code, message: error.message, details: error.details } });
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
await audit('step.failed', { step: step.name, error: error.message });
|
|
305
|
+
await persist('failed', { error: { code: error.code ?? 'STEP_FAILED', message: error.message, step: step.name } });
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
outputs[step.name] = output ?? null;
|
|
309
|
+
state.completedSteps = [
|
|
310
|
+
...state.completedSteps,
|
|
311
|
+
{ name: step.name, completedAt: new Date(now()).toISOString(), output: output ?? null },
|
|
312
|
+
];
|
|
313
|
+
await audit('step.succeeded', { step: step.name, outputDigest: sha256Json(output ?? null) });
|
|
314
|
+
await persist(null, { completedSteps: state.completedSteps });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
await checkCancel();
|
|
318
|
+
const result = outputs[steps[steps.length - 1].name] ?? null;
|
|
319
|
+
await writeJson(paths.result, { jobId, kind, result, resultDigest: sha256Json(result) });
|
|
320
|
+
await audit('job.succeeded', { resultDigest: sha256Json(result) });
|
|
321
|
+
await persist('succeeded');
|
|
322
|
+
return { ...state, replayed: false, result };
|
|
323
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// Training job: data preparation, base checkpoint, and post-training run as
|
|
2
|
+
// one auditable job.
|
|
3
|
+
//
|
|
4
|
+
// The point of routing training through `runJob` is that the operator gets the
|
|
5
|
+
// same guarantees as every other foundry job -- durable state, a reviewable
|
|
6
|
+
// audit log, resume at step granularity, cooperative cancellation and hard
|
|
7
|
+
// budget caps -- without the training code having to re-implement any of it.
|
|
8
|
+
//
|
|
9
|
+
// Each step persists its real artifacts to disk and returns only small
|
|
10
|
+
// references (paths, digests, counts). That is deliberate: a resumed attempt
|
|
11
|
+
// reloads from those artifacts instead of trusting in-memory trainer state,
|
|
12
|
+
// so "resume" is the same code path as "load a checkpoint someone else wrote".
|
|
13
|
+
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { runJob, JobCancelledError } from './runner.mjs';
|
|
16
|
+
import { runDataPipeline } from '../data/pipeline.mjs';
|
|
17
|
+
import { buildTokenizer, encodeRecords } from '../train/dataset.mjs';
|
|
18
|
+
import { ensureDir, readJsonl, writeJson } from '../core/fsx.mjs';
|
|
19
|
+
import { sha256Json } from '../core/hash.mjs';
|
|
20
|
+
|
|
21
|
+
export const TRAIN_JOB_KIND = 'train';
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_TRAIN_JOB_OPTIONS = {
|
|
24
|
+
mode: 'lora',
|
|
25
|
+
seed: 'tmf-train',
|
|
26
|
+
maxVocab: 256,
|
|
27
|
+
maxSeqLen: 96,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function splitFile(dataDir, name) {
|
|
31
|
+
return path.join(dataDir, `${name}.jsonl`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Charging tokens as they are actually consumed is what makes `maxTokens` a
|
|
35
|
+
// real cap: the throw lands inside the training loop and the runner records
|
|
36
|
+
// state=budget_exceeded instead of discovering the overspend afterwards.
|
|
37
|
+
function makeStepHook({ signal, audit, budget, auditEveryStep }) {
|
|
38
|
+
let lastCharged = 0;
|
|
39
|
+
return async (entry) => {
|
|
40
|
+
if (signal?.aborted) throw new JobCancelledError('cancelled during training step');
|
|
41
|
+
const delta = Math.max(0, entry.tokens - lastCharged);
|
|
42
|
+
lastCharged = entry.tokens;
|
|
43
|
+
budget.charge({ tokens: delta });
|
|
44
|
+
if (auditEveryStep > 0 && entry.step % auditEveryStep === 0) {
|
|
45
|
+
await audit('train.step', { step: entry.step, loss: entry.loss, lr: entry.lr, tokens: entry.tokens });
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Run a full data -> base -> post-training job under the auditable runner.
|
|
52
|
+
*
|
|
53
|
+
* Returns the runner's job record; `result` holds the artifact references the
|
|
54
|
+
* evaluation and export jobs consume (data report, base checkpoint, adapter
|
|
55
|
+
* or tuned checkpoint, and the real training metrics).
|
|
56
|
+
*/
|
|
57
|
+
export async function runTrainingJob({
|
|
58
|
+
jobId,
|
|
59
|
+
root,
|
|
60
|
+
backend,
|
|
61
|
+
datasets,
|
|
62
|
+
baseDir = process.cwd(),
|
|
63
|
+
dataConfig = {},
|
|
64
|
+
modelConfig = {},
|
|
65
|
+
hyper = {},
|
|
66
|
+
trainBudget = {},
|
|
67
|
+
mode = DEFAULT_TRAIN_JOB_OPTIONS.mode,
|
|
68
|
+
seed = DEFAULT_TRAIN_JOB_OPTIONS.seed,
|
|
69
|
+
maxVocab = DEFAULT_TRAIN_JOB_OPTIONS.maxVocab,
|
|
70
|
+
maxSeqLen = DEFAULT_TRAIN_JOB_OPTIONS.maxSeqLen,
|
|
71
|
+
budget = {},
|
|
72
|
+
signal = null,
|
|
73
|
+
auditEveryStep = 1,
|
|
74
|
+
resume = true,
|
|
75
|
+
resumeCancelled = false,
|
|
76
|
+
now = () => Date.now(),
|
|
77
|
+
} = {}) {
|
|
78
|
+
if (!jobId) throw new Error('runTrainingJob requires jobId');
|
|
79
|
+
if (!root) throw new Error('runTrainingJob requires root');
|
|
80
|
+
if (!backend) throw new Error('runTrainingJob requires a backend');
|
|
81
|
+
if (!Array.isArray(datasets) || datasets.length === 0) {
|
|
82
|
+
throw new Error('runTrainingJob requires at least one dataset');
|
|
83
|
+
}
|
|
84
|
+
if (!backend.capabilities?.modes?.includes(mode)) {
|
|
85
|
+
throw new Error(`backend "${backend.id}" does not support mode "${mode}"`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Artifacts live in the same directory the runner uses for this job's state
|
|
89
|
+
// and audit log, so one directory is the whole durable record of the job.
|
|
90
|
+
const jobDir = path.join(root, jobId);
|
|
91
|
+
const dataDir = path.join(jobDir, 'data');
|
|
92
|
+
const modelDir = path.join(jobDir, 'model');
|
|
93
|
+
|
|
94
|
+
// The input digest binds this jobId to its configuration: the runner refuses
|
|
95
|
+
// to resume a job whose inputs changed, which is what stops a "resume" from
|
|
96
|
+
// silently becoming a different experiment.
|
|
97
|
+
const input = {
|
|
98
|
+
kind: TRAIN_JOB_KIND,
|
|
99
|
+
backend: backend.id,
|
|
100
|
+
datasets: datasets.map((d) => ({ name: d.name, path: d.path, format: d.format ?? null })),
|
|
101
|
+
dataConfig,
|
|
102
|
+
modelConfig,
|
|
103
|
+
hyper,
|
|
104
|
+
trainBudget,
|
|
105
|
+
mode,
|
|
106
|
+
seed,
|
|
107
|
+
maxVocab,
|
|
108
|
+
maxSeqLen,
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const steps = [
|
|
112
|
+
{
|
|
113
|
+
name: 'data',
|
|
114
|
+
run: async ({ audit }) => {
|
|
115
|
+
await ensureDir(dataDir);
|
|
116
|
+
const { report, splits, provenance } = await runDataPipeline({
|
|
117
|
+
datasets,
|
|
118
|
+
outDir: dataDir,
|
|
119
|
+
baseDir,
|
|
120
|
+
config: dataConfig,
|
|
121
|
+
});
|
|
122
|
+
const reportFile = path.join(dataDir, 'data-report.json');
|
|
123
|
+
await writeJson(reportFile, { report, provenance });
|
|
124
|
+
await audit('data.prepared', {
|
|
125
|
+
splits: Object.fromEntries(Object.entries(splits).map(([k, v]) => [k, v.length])),
|
|
126
|
+
accepted: report.accepted ?? null,
|
|
127
|
+
});
|
|
128
|
+
return {
|
|
129
|
+
dataDir,
|
|
130
|
+
reportFile,
|
|
131
|
+
reportDigest: sha256Json(report),
|
|
132
|
+
splits: Object.fromEntries(Object.entries(splits).map(([k, v]) => [k, v.length])),
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
name: 'base',
|
|
138
|
+
run: async ({ outputs, audit }) => {
|
|
139
|
+
const trainRecords = await readJsonl(splitFile(outputs.data.dataDir, 'train'));
|
|
140
|
+
if (trainRecords.length === 0) throw new Error('data step produced an empty train split');
|
|
141
|
+
// Tokenizer ownership is a backend capability, not a job assumption: a
|
|
142
|
+
// backend whose model carries its own tokenizer (hf-peft) must not be
|
|
143
|
+
// handed a vocabulary built from this split, because ids from a JS
|
|
144
|
+
// vocabulary mean nothing to that model's embedding table.
|
|
145
|
+
const ownsTokenizer = backend.capabilities?.ownsTokenizer === true;
|
|
146
|
+
const tokenizer = ownsTokenizer ? null : buildTokenizer(trainRecords, { maxVocab });
|
|
147
|
+
const handle = await backend.createModel({
|
|
148
|
+
modelConfig,
|
|
149
|
+
tokenizer,
|
|
150
|
+
seed: 1,
|
|
151
|
+
modelId: modelConfig.modelId ?? modelConfig.baseModel ?? null,
|
|
152
|
+
outDir: modelDir,
|
|
153
|
+
});
|
|
154
|
+
const file = path.join(modelDir, 'base.json');
|
|
155
|
+
const saved = await backend.saveModel({
|
|
156
|
+
handle,
|
|
157
|
+
file,
|
|
158
|
+
kind: 'base',
|
|
159
|
+
meta: { jobId, dataReportDigest: outputs.data.reportDigest },
|
|
160
|
+
});
|
|
161
|
+
const fingerprint = backend.fingerprint(handle);
|
|
162
|
+
const vocabSize = tokenizer ? tokenizer.size : null;
|
|
163
|
+
await audit('base.saved', {
|
|
164
|
+
file: saved.file,
|
|
165
|
+
sha256: saved.sha256,
|
|
166
|
+
vocabSize,
|
|
167
|
+
tokenizerOwner: ownsTokenizer ? 'backend' : 'job',
|
|
168
|
+
fingerprint,
|
|
169
|
+
});
|
|
170
|
+
return { file: saved.file, sha256: saved.sha256, fingerprint, vocabSize, tokenizerOwner: ownsTokenizer ? 'backend' : 'job' };
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
name: 'train',
|
|
175
|
+
run: async ({ outputs, audit, budget: jobBudget }) => {
|
|
176
|
+
const trainRecords = await readJsonl(splitFile(outputs.data.dataDir, 'train'));
|
|
177
|
+
// Reloading the base from disk (rather than reusing the handle built in
|
|
178
|
+
// the previous step) is what makes a resumed attempt equivalent to a
|
|
179
|
+
// fresh process picking the job up.
|
|
180
|
+
const handle = await backend.loadModel({ file: outputs.base.file });
|
|
181
|
+
// One call for both backends: prepareDataset() is the single place that
|
|
182
|
+
// knows whether ids come from a job-built vocabulary or from the
|
|
183
|
+
// model's own tokenizer. The fallback keeps older backends working.
|
|
184
|
+
const prepared = typeof backend.prepareDataset === 'function'
|
|
185
|
+
? await backend.prepareDataset({ handle, records: trainRecords, maxSeqLen, outDir: modelDir })
|
|
186
|
+
: { ...encodeRecords(trainRecords, handle.tokenizer, { maxSeqLen }), tokens: null, tokenizer: 'job-built' };
|
|
187
|
+
const examples = prepared.examples ?? [];
|
|
188
|
+
const skipped = prepared.skipped ?? [];
|
|
189
|
+
if (examples.length === 0) throw new Error('no train examples survived encoding');
|
|
190
|
+
const beforeFingerprint = backend.fingerprint(handle);
|
|
191
|
+
await audit('train.started', {
|
|
192
|
+
mode,
|
|
193
|
+
examples: examples.length,
|
|
194
|
+
skipped: skipped.length,
|
|
195
|
+
tokens: prepared.tokens ?? null,
|
|
196
|
+
tokenizer: prepared.tokenizer ?? 'job-built',
|
|
197
|
+
baseFingerprint: beforeFingerprint,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const trained = await backend.train({
|
|
201
|
+
handle,
|
|
202
|
+
examples,
|
|
203
|
+
examplesFile: prepared.examplesFile ?? null,
|
|
204
|
+
mode,
|
|
205
|
+
hyper,
|
|
206
|
+
budget: trainBudget,
|
|
207
|
+
seed,
|
|
208
|
+
outDir: modelDir,
|
|
209
|
+
signal,
|
|
210
|
+
resume: null,
|
|
211
|
+
hooks: { onStep: makeStepHook({ signal, audit, budget: jobBudget, auditEveryStep }) },
|
|
212
|
+
});
|
|
213
|
+
const { metrics, history, stopReason } = trained;
|
|
214
|
+
// A backend may return a moved handle (hf-peft points it at the adapter
|
|
215
|
+
// directory the worker just wrote); saving the pre-train handle would
|
|
216
|
+
// persist a checkpoint that does not reference the trained weights.
|
|
217
|
+
const trainedHandle = trained.handle ?? handle;
|
|
218
|
+
|
|
219
|
+
const historyFile = path.join(modelDir, 'train-history.json');
|
|
220
|
+
await writeJson(historyFile, { jobId, mode, metrics, history });
|
|
221
|
+
const isAdapter = mode === 'lora';
|
|
222
|
+
const file = path.join(modelDir, isAdapter ? 'adapter.json' : 'tuned.json');
|
|
223
|
+
const saved = await backend.saveModel({
|
|
224
|
+
handle: trainedHandle,
|
|
225
|
+
file,
|
|
226
|
+
kind: isAdapter ? 'adapter' : 'base',
|
|
227
|
+
meta: {
|
|
228
|
+
jobId,
|
|
229
|
+
mode,
|
|
230
|
+
baseCheckpoint: outputs.base.file,
|
|
231
|
+
baseFingerprint: beforeFingerprint,
|
|
232
|
+
metrics,
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
await audit('train.finished', {
|
|
236
|
+
file: saved.file,
|
|
237
|
+
sha256: saved.sha256,
|
|
238
|
+
stopReason,
|
|
239
|
+
steps: metrics.steps,
|
|
240
|
+
finalLoss: metrics.finalLoss,
|
|
241
|
+
parameterL2Delta: metrics.parameterL2Delta,
|
|
242
|
+
});
|
|
243
|
+
if (!(metrics.parameterL2Delta > 0)) {
|
|
244
|
+
throw new Error('training reported zero parameter displacement; weights did not change');
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
checkpoint: saved.file,
|
|
248
|
+
sha256: saved.sha256,
|
|
249
|
+
kind: saved.kind,
|
|
250
|
+
historyFile,
|
|
251
|
+
baseFingerprint: beforeFingerprint,
|
|
252
|
+
metrics,
|
|
253
|
+
stopReason,
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
{
|
|
258
|
+
// The runner's `result` is the last step's output, so the job ends with a
|
|
259
|
+
// step whose only work is to collect the artifact references and write
|
|
260
|
+
// them down as a manifest a downstream job can consume directly.
|
|
261
|
+
name: 'finalize',
|
|
262
|
+
run: async ({ outputs, audit }) => {
|
|
263
|
+
const manifest = {
|
|
264
|
+
jobId,
|
|
265
|
+
kind: TRAIN_JOB_KIND,
|
|
266
|
+
backend: backend.id,
|
|
267
|
+
mode,
|
|
268
|
+
data: outputs.data,
|
|
269
|
+
base: outputs.base,
|
|
270
|
+
train: outputs.train,
|
|
271
|
+
};
|
|
272
|
+
const manifestFile = path.join(jobDir, 'train-manifest.json');
|
|
273
|
+
await writeJson(manifestFile, manifest);
|
|
274
|
+
await audit('train.manifest', { manifestFile, digest: sha256Json(manifest) });
|
|
275
|
+
return { ...manifest, manifestFile };
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
];
|
|
279
|
+
|
|
280
|
+
return runJob({ jobId, kind: TRAIN_JOB_KIND, root, steps, input, budget, signal, resume, resumeCancelled, now });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Artifact references a downstream evaluation or export job needs. Throws when
|
|
285
|
+
* the job did not actually finish, so a caller cannot mistake a cancelled or
|
|
286
|
+
* over-budget job for a trained model.
|
|
287
|
+
*/
|
|
288
|
+
export function trainingArtifacts(job) {
|
|
289
|
+
if (job?.state !== 'succeeded') {
|
|
290
|
+
throw new Error(`training job ${job?.jobId ?? '<unknown>'} is ${job?.state ?? 'missing'}, not succeeded`);
|
|
291
|
+
}
|
|
292
|
+
const { data, base, train } = job.result ?? {};
|
|
293
|
+
if (!data || !base || !train) throw new Error('training job result is missing step outputs');
|
|
294
|
+
return {
|
|
295
|
+
jobId: job.jobId,
|
|
296
|
+
dataDir: data.dataDir,
|
|
297
|
+
dataReportFile: data.reportFile,
|
|
298
|
+
baseCheckpoint: base.file,
|
|
299
|
+
adapterCheckpoint: train.kind === 'adapter' ? train.checkpoint : null,
|
|
300
|
+
tunedCheckpoint: train.kind === 'adapter' ? null : train.checkpoint,
|
|
301
|
+
metrics: train.metrics,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// LoRA adapters: W_eff = W + (A @ B) * (alpha / r).
|
|
2
|
+
//
|
|
3
|
+
// B is zero-initialized so a freshly attached adapter is mathematically a no-op.
|
|
4
|
+
// That property is what makes "the adapter actually changed the model" testable:
|
|
5
|
+
// before training, base and adapted outputs must match exactly.
|
|
6
|
+
|
|
7
|
+
import { matmul, randn, scale, zeros, add } from '../core/autograd.mjs';
|
|
8
|
+
|
|
9
|
+
export class LoraLayer {
|
|
10
|
+
constructor(inDim, outDim, rank, alpha, rng, name) {
|
|
11
|
+
this.inDim = inDim;
|
|
12
|
+
this.outDim = outDim;
|
|
13
|
+
this.rank = rank;
|
|
14
|
+
this.alpha = alpha;
|
|
15
|
+
this.scaling = alpha / rank;
|
|
16
|
+
this.A = randn(inDim, rank, rng, 1 / Math.sqrt(inDim), { requiresGrad: true, name: `${name}.lora_A` });
|
|
17
|
+
this.B = zeros(rank, outDim, { requiresGrad: true, name: `${name}.lora_B` });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
params() {
|
|
21
|
+
return [this.A, this.B];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// delta(x) = (x @ A) @ B * scaling
|
|
25
|
+
apply(x) {
|
|
26
|
+
return scale(matmul(matmul(x, this.A), this.B), this.scaling);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
forward(x, baseOut) {
|
|
30
|
+
return add(baseOut, this.apply(x));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
toJSON() {
|
|
34
|
+
return {
|
|
35
|
+
inDim: this.inDim,
|
|
36
|
+
outDim: this.outDim,
|
|
37
|
+
rank: this.rank,
|
|
38
|
+
alpha: this.alpha,
|
|
39
|
+
A: Array.from(this.A.data),
|
|
40
|
+
B: Array.from(this.B.data),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
loadJSON(json) {
|
|
45
|
+
if (json.inDim !== this.inDim || json.outDim !== this.outDim || json.rank !== this.rank) {
|
|
46
|
+
throw new Error(`lora shape mismatch: expected ${this.inDim}x${this.rank}x${this.outDim}, got ${json.inDim}x${json.rank}x${json.outDim}`);
|
|
47
|
+
}
|
|
48
|
+
this.A.data.set(json.A);
|
|
49
|
+
this.B.data.set(json.B);
|
|
50
|
+
this.alpha = json.alpha;
|
|
51
|
+
this.scaling = json.alpha / json.rank;
|
|
52
|
+
}
|
|
53
|
+
}
|