taskforce-model-foundry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/tmf.mjs +353 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +227 -0
- package/docs/tutorial.md +336 -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 +70 -0
- package/openclaw.plugin.json +24 -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 +124 -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/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +154 -0
- package/src/jobs/evaluate.mjs +164 -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 +549 -0
- package/src/train/backends/hf_peft_runner.py +326 -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,549 @@
|
|
|
1
|
+
// Second trainer backend: Hugging Face transformers + PEFT via a local Python
|
|
2
|
+
// process.
|
|
3
|
+
//
|
|
4
|
+
// This backend exists to keep the registry interface honest. It is implemented
|
|
5
|
+
// against the same contract as the builtin trainer, discovers its dependencies
|
|
6
|
+
// at runtime, and reports precisely what is missing when they are absent. It
|
|
7
|
+
// never falls back to the builtin trainer and never fabricates metrics: if the
|
|
8
|
+
// environment cannot run it, `probe()` says so and callers record the
|
|
9
|
+
// capability as unverified rather than claiming a result.
|
|
10
|
+
//
|
|
11
|
+
// Execution goes through `hf_peft_runner.py`, a checked-in program, so the code
|
|
12
|
+
// that actually trains is reviewable rather than assembled from strings at call
|
|
13
|
+
// time. `renderTrainingScript()` is retained and now emits the exact spec and
|
|
14
|
+
// command line that will be executed.
|
|
15
|
+
//
|
|
16
|
+
// This is a local-execution backend only. It does not download models and does
|
|
17
|
+
// not call a hosted API, so it stays inside the project's "no paid training,
|
|
18
|
+
// no external data egress" constraints. A caller must point `modelId` at a
|
|
19
|
+
// model already present on local disk; the runner sets HF offline mode so a
|
|
20
|
+
// missing local model fails instead of silently fetching one.
|
|
21
|
+
|
|
22
|
+
import { spawn } from 'node:child_process';
|
|
23
|
+
import fs from 'node:fs';
|
|
24
|
+
import crypto from 'node:crypto';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { fileURLToPath } from 'node:url';
|
|
27
|
+
import { writeFileAtomic, ensureDir, readJson } from '../../core/fsx.mjs';
|
|
28
|
+
import { sha256File } from '../../core/hash.mjs';
|
|
29
|
+
|
|
30
|
+
// `datasets` and `accelerate` are imported by the training path, so a probe
|
|
31
|
+
// that omitted them would report "available" for an environment that cannot
|
|
32
|
+
// train. They are part of the required set.
|
|
33
|
+
export const REQUIRED_PYTHON_PACKAGES = ['torch', 'transformers', 'peft', 'datasets', 'accelerate'];
|
|
34
|
+
|
|
35
|
+
const RUNNER = path.join(path.dirname(fileURLToPath(import.meta.url)), 'hf_peft_runner.py');
|
|
36
|
+
const RESULT_PREFIX = '__TMF_RESULT__';
|
|
37
|
+
|
|
38
|
+
// Defaults kept small on purpose: this backend is expected to run on a CPU box
|
|
39
|
+
// next to the rest of the toolchain, not on a training cluster.
|
|
40
|
+
const DEFAULT_LIMITS = { maxMemoryMb: 4096, threads: 1, maxSeqLen: 128 };
|
|
41
|
+
|
|
42
|
+
function pythonBin() {
|
|
43
|
+
return process.env.TMF_PYTHON || 'python3';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function runPython(args, { timeoutMs = 600000, cwd, signal } = {}) {
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
let child;
|
|
49
|
+
try {
|
|
50
|
+
child = spawn(pythonBin(), args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
51
|
+
} catch (err) {
|
|
52
|
+
resolve({ code: -1, stdout: '', stderr: err.message, spawnFailed: true });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
let stdout = '';
|
|
56
|
+
let stderr = '';
|
|
57
|
+
let cancelled = false;
|
|
58
|
+
let timedOut = false;
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
timedOut = true;
|
|
61
|
+
child.kill('SIGKILL');
|
|
62
|
+
stderr += `\ntimed out after ${timeoutMs}ms`;
|
|
63
|
+
}, timeoutMs);
|
|
64
|
+
// Cancellation is a SIGKILL of the worker process, not a request the
|
|
65
|
+
// worker may ignore: the kernel tears it down. In-flight work is lost,
|
|
66
|
+
// which is why the only recoverable state is the last written checkpoint.
|
|
67
|
+
const onAbort = () => {
|
|
68
|
+
cancelled = true;
|
|
69
|
+
child.kill('SIGKILL');
|
|
70
|
+
};
|
|
71
|
+
if (signal) {
|
|
72
|
+
if (signal.aborted) onAbort();
|
|
73
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
74
|
+
}
|
|
75
|
+
child.stdout.on('data', (c) => { stdout += c; });
|
|
76
|
+
child.stderr.on('data', (c) => { stderr += c; });
|
|
77
|
+
child.on('error', (err) => {
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
signal?.removeEventListener('abort', onAbort);
|
|
80
|
+
resolve({ code: -1, stdout, stderr: `${stderr}${err.message}`, spawnFailed: true });
|
|
81
|
+
});
|
|
82
|
+
child.on('close', (code, closeSignal) => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
signal?.removeEventListener('abort', onAbort);
|
|
85
|
+
resolve({ code, signal: closeSignal, stdout, stderr, cancelled, timedOut });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const PROBE_SCRIPT = `
|
|
91
|
+
import json, importlib
|
|
92
|
+
report = {}
|
|
93
|
+
for name in ${JSON.stringify(REQUIRED_PYTHON_PACKAGES)}:
|
|
94
|
+
try:
|
|
95
|
+
mod = importlib.import_module(name)
|
|
96
|
+
report[name] = getattr(mod, "__version__", "unknown")
|
|
97
|
+
except Exception as exc:
|
|
98
|
+
report[name] = None
|
|
99
|
+
try:
|
|
100
|
+
import torch
|
|
101
|
+
report["_devices"] = ["cuda" if torch.cuda.is_available() else "cpu"]
|
|
102
|
+
except Exception:
|
|
103
|
+
report["_devices"] = []
|
|
104
|
+
print(json.dumps(report))
|
|
105
|
+
`;
|
|
106
|
+
|
|
107
|
+
function unavailable(method, probe) {
|
|
108
|
+
const err = new Error(
|
|
109
|
+
`hf-peft backend cannot ${method}: ${probe?.reason ?? 'environment not available'}. `
|
|
110
|
+
+ 'Install the missing packages locally, or run with backend "builtin-js".',
|
|
111
|
+
);
|
|
112
|
+
err.code = 'BACKEND_UNAVAILABLE';
|
|
113
|
+
err.backendProbe = probe;
|
|
114
|
+
return err;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function parseResult(result, op) {
|
|
118
|
+
const line = result.stdout.split('\n').reverse().find((l) => l.startsWith(RESULT_PREFIX));
|
|
119
|
+
if (!line) {
|
|
120
|
+
throw new Error(
|
|
121
|
+
`hf-peft ${op} produced no result line; last stderr: ${(result.stderr || '').trim().slice(-400)}`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
return JSON.parse(line.slice(RESULT_PREFIX.length).trim());
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function writeSpec(spec, { outDir, op }) {
|
|
128
|
+
await ensureDir(outDir);
|
|
129
|
+
const file = path.join(outDir, `hf-peft-${op}-spec.json`);
|
|
130
|
+
await writeFileAtomic(file, `${JSON.stringify(spec, null, 2)}\n`);
|
|
131
|
+
return file;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function limitsFrom(budget = {}, overrides = {}) {
|
|
135
|
+
return {
|
|
136
|
+
maxMemoryMb: overrides.maxMemoryMb ?? budget.maxMemoryMb ?? DEFAULT_LIMITS.maxMemoryMb,
|
|
137
|
+
maxCpuSeconds: overrides.maxCpuSeconds ?? budget.maxCpuSeconds ?? null,
|
|
138
|
+
threads: overrides.threads ?? budget.threads ?? DEFAULT_LIMITS.threads,
|
|
139
|
+
maxSeqLen: overrides.maxSeqLen ?? DEFAULT_LIMITS.maxSeqLen,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function runOp(op, spec, { outDir, timeoutMs, signal }) {
|
|
144
|
+
const specFile = await writeSpec({ op, ...spec }, { outDir, op });
|
|
145
|
+
const result = await runPython([RUNNER, specFile], { timeoutMs, signal });
|
|
146
|
+
if (result.cancelled) {
|
|
147
|
+
const err = new Error(`hf-peft ${op} was cancelled (worker killed with SIGKILL)`);
|
|
148
|
+
err.code = 'BACKEND_CANCELLED';
|
|
149
|
+
err.specFile = specFile;
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
if (result.code !== 0) {
|
|
153
|
+
// RLIMIT_AS surfaces as a MemoryError / allocation failure inside the
|
|
154
|
+
// worker; RLIMIT_CPU kills it with SIGKILL. Both are reported as the
|
|
155
|
+
// resource failure they are instead of a generic crash.
|
|
156
|
+
const stderr = (result.stderr || '').trim();
|
|
157
|
+
// A too-small RLIMIT_AS can bite before training starts: the framework's
|
|
158
|
+
// own shared objects fail to mmap. That is still the memory bound doing
|
|
159
|
+
// its job, so it is classified as one rather than as a generic crash.
|
|
160
|
+
const memoryBound = /MemoryError|Cannot allocate memory|bad_alloc|DefaultCPUAllocator|failed to map segment|Cannot mmap|OutOfMemoryError/i.test(stderr);
|
|
161
|
+
const err = new Error(
|
|
162
|
+
`hf-peft ${op} failed (exit ${result.code}${result.signal ? `, signal ${result.signal}` : ''})`
|
|
163
|
+
+ `${memoryBound ? ' due to the configured memory limit' : ''}: ${stderr.slice(-500)}`,
|
|
164
|
+
);
|
|
165
|
+
err.code = memoryBound ? 'BACKEND_MEMORY_LIMIT'
|
|
166
|
+
: result.signal === 'SIGKILL' ? 'BACKEND_RESOURCE_LIMIT'
|
|
167
|
+
: result.timedOut ? 'BACKEND_TIMEOUT' : 'BACKEND_FAILED';
|
|
168
|
+
err.specFile = specFile;
|
|
169
|
+
err.stderrTail = stderr.slice(-500);
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
return { payload: parseResult(result, op), specFile, stderr: result.stderr };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Weight/config files a HF model or PEFT adapter directory is made of. Other
|
|
176
|
+
// files (trainer state, logs, tokenizer caches) are deliberately excluded: they
|
|
177
|
+
// move between runs that produce identical weights.
|
|
178
|
+
const FINGERPRINT_EXTENSIONS = ['.safetensors', '.bin', '.pt', '.json', '.model'];
|
|
179
|
+
const FINGERPRINT_MAX_DEPTH = 3;
|
|
180
|
+
|
|
181
|
+
function digestWeightDir(dir, depth = 0) {
|
|
182
|
+
const out = [];
|
|
183
|
+
let entries;
|
|
184
|
+
try {
|
|
185
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
186
|
+
} catch {
|
|
187
|
+
// A missing directory is a real state (a base-only handle), not an error:
|
|
188
|
+
// it contributes nothing, and the modelId still distinguishes the handle.
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
192
|
+
const full = path.join(dir, entry.name);
|
|
193
|
+
if (entry.isDirectory()) {
|
|
194
|
+
if (depth >= FINGERPRINT_MAX_DEPTH) continue;
|
|
195
|
+
for (const nested of digestWeightDir(full, depth + 1)) out.push(`${entry.name}/${nested}`);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (!entry.isFile()) continue;
|
|
199
|
+
if (!FINGERPRINT_EXTENSIONS.includes(path.extname(entry.name))) continue;
|
|
200
|
+
const buf = fs.readFileSync(full);
|
|
201
|
+
out.push(`${entry.name}:${buf.length}:${crypto.createHash('sha256').update(buf).digest('hex')}`);
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const backend = {
|
|
207
|
+
id: 'hf-peft',
|
|
208
|
+
|
|
209
|
+
capabilities: {
|
|
210
|
+
modes: ['lora', 'full-finetune'],
|
|
211
|
+
// The tokenizer belongs to the model, not to the job: ids are produced by
|
|
212
|
+
// the HF tokenizer inside the Python worker. A job-built JS vocabulary
|
|
213
|
+
// would produce ids the model's embedding table cannot interpret, so the
|
|
214
|
+
// job must not encode for this backend. See prepareDataset().
|
|
215
|
+
ownsTokenizer: true,
|
|
216
|
+
frameworks: ['torch', 'transformers', 'peft', 'datasets'],
|
|
217
|
+
devices: ['cpu', 'cuda'],
|
|
218
|
+
// Resume restarts from the last Trainer checkpoint directory written under
|
|
219
|
+
// the run's output dir, which is step-granular only at `checkpointEvery`
|
|
220
|
+
// boundaries. Steps after the last checkpoint are replayed, not recovered.
|
|
221
|
+
supportsResume: true,
|
|
222
|
+
resumeGranularity: 'checkpoint-step',
|
|
223
|
+
// Cancel kills the worker process. It is forced at the process level, but
|
|
224
|
+
// it is not a graceful mid-step save: only already-written checkpoints
|
|
225
|
+
// survive.
|
|
226
|
+
supportsCancel: true,
|
|
227
|
+
cancelSemantics: 'sigkill-worker',
|
|
228
|
+
// Hard, kernel-enforced per-process bounds. This is a bound on the worker
|
|
229
|
+
// process, not a security sandbox: it does not isolate the filesystem or
|
|
230
|
+
// network.
|
|
231
|
+
resourceBounds: ['max-steps', 'max-seconds', 'max-memory-mb', 'max-cpu-seconds', 'threads'],
|
|
232
|
+
isolation: 'process-rlimit',
|
|
233
|
+
precision: 'float32',
|
|
234
|
+
requiresLocalModelCache: true,
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
async probe() {
|
|
238
|
+
const dir = path.join(process.cwd(), '.tmf-run', 'probe');
|
|
239
|
+
await ensureDir(dir);
|
|
240
|
+
const script = path.join(dir, 'hf-peft-probe.py');
|
|
241
|
+
await writeFileAtomic(script, PROBE_SCRIPT);
|
|
242
|
+
const result = await runPython([script], { timeoutMs: 120000 });
|
|
243
|
+
if (result.spawnFailed || result.code !== 0) {
|
|
244
|
+
return {
|
|
245
|
+
available: false,
|
|
246
|
+
reason: `python interpreter unusable (${(result.stderr || '').trim().split('\n').slice(-1)[0] || `exit ${result.code}`})`,
|
|
247
|
+
details: { python: pythonBin(), probeScript: script },
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
let report;
|
|
251
|
+
try {
|
|
252
|
+
report = JSON.parse(result.stdout.trim().split('\n').slice(-1)[0]);
|
|
253
|
+
} catch {
|
|
254
|
+
return { available: false, reason: 'probe output was not valid json', details: { stdout: result.stdout.slice(0, 200) } };
|
|
255
|
+
}
|
|
256
|
+
const missing = REQUIRED_PYTHON_PACKAGES.filter((name) => !report[name]);
|
|
257
|
+
if (missing.length > 0) {
|
|
258
|
+
return {
|
|
259
|
+
available: false,
|
|
260
|
+
reason: `missing python packages: ${missing.join(', ')}`,
|
|
261
|
+
details: { versions: report, missing, installHint: `pip install ${missing.join(' ')}` },
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
available: true,
|
|
266
|
+
reason: 'torch, transformers, peft, datasets and accelerate are importable',
|
|
267
|
+
details: { versions: report, devices: report._devices, runner: RUNNER },
|
|
268
|
+
};
|
|
269
|
+
},
|
|
270
|
+
|
|
271
|
+
// modelId may arrive either directly (direct backend callers) or inside
|
|
272
|
+
// modelConfig (the training job passes one modelConfig through to whichever
|
|
273
|
+
// backend is selected), so both spellings are accepted under one contract.
|
|
274
|
+
async createModel({ modelId, outDir, modelConfig = {} } = {}) {
|
|
275
|
+
const probe = await backend.probe();
|
|
276
|
+
if (!probe.available) throw unavailable('create a model', probe);
|
|
277
|
+
const resolvedId = modelId ?? modelConfig.modelId ?? modelConfig.baseModel ?? null;
|
|
278
|
+
if (!resolvedId) {
|
|
279
|
+
throw new Error('hf-peft requires modelId (or modelConfig.modelId) pointing at a locally cached model');
|
|
280
|
+
}
|
|
281
|
+
return {
|
|
282
|
+
backend: backend.id,
|
|
283
|
+
kind: 'base',
|
|
284
|
+
modelId: resolvedId,
|
|
285
|
+
mode: modelConfig.mode ?? 'lora',
|
|
286
|
+
outDir: outDir ?? modelConfig.outDir ?? null,
|
|
287
|
+
modelConfig,
|
|
288
|
+
python: true,
|
|
289
|
+
};
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
// Counterpart to builtin-js prepareDataset(): this backend keeps the records
|
|
293
|
+
// as text and lets the Python worker tokenize them with the model's own
|
|
294
|
+
// tokenizer. Records are validated and filtered here so an empty or
|
|
295
|
+
// malformed split fails in Node with a readable error instead of inside the
|
|
296
|
+
// worker. `tokens` is null on purpose: a real count needs the HF tokenizer,
|
|
297
|
+
// and the worker reports the actual token count in its training metrics.
|
|
298
|
+
prepareDataset({ records, maxSeqLen = 96 } = {}) {
|
|
299
|
+
const examples = [];
|
|
300
|
+
const skipped = [];
|
|
301
|
+
for (const record of records ?? []) {
|
|
302
|
+
const prompt = typeof record?.prompt === 'string' ? record.prompt : '';
|
|
303
|
+
const completion = typeof record?.completion === 'string' ? record.completion : '';
|
|
304
|
+
const text = typeof record?.text === 'string' ? record.text : '';
|
|
305
|
+
// Whitespace is deliberately preserved. The worker derives the label mask
|
|
306
|
+
// from len(tokenize(prompt)) against tokenize(prompt + completion), so
|
|
307
|
+
// stripping the leading space off " eight" makes the boundary token
|
|
308
|
+
// ("to" + "eight") re-merge, the supervised span collapse to empty, and
|
|
309
|
+
// every step report loss 0 with zero parameter movement.
|
|
310
|
+
if (prompt.trim() && completion.trim()) {
|
|
311
|
+
examples.push({ prompt, completion });
|
|
312
|
+
} else if (text.trim()) {
|
|
313
|
+
examples.push({ text });
|
|
314
|
+
} else {
|
|
315
|
+
skipped.push({ reason: 'record has neither prompt+completion nor text' });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return { examples, skipped, tokens: null, tokenizer: 'model-owned', maxSeqLen, vocabSize: null };
|
|
319
|
+
},
|
|
320
|
+
|
|
321
|
+
// attachAdapter mirrors the builtin backend: the evaluation job loads the
|
|
322
|
+
// base checkpoint and attaches the adapter checkpoint so baseline and tuned
|
|
323
|
+
// are two separate handles over the same base. Without honouring it here the
|
|
324
|
+
// "tuned" handle would silently be the untouched base model.
|
|
325
|
+
async loadModel({ file, attachAdapter = null } = {}) {
|
|
326
|
+
const probe = await backend.probe();
|
|
327
|
+
if (!probe.available) throw unavailable('load a checkpoint', probe);
|
|
328
|
+
const payload = await readJson(file);
|
|
329
|
+
if (payload.backend !== backend.id) throw new Error(`checkpoint backend "${payload.backend}" is not ${backend.id}`);
|
|
330
|
+
if (attachAdapter) {
|
|
331
|
+
const adapter = await readJson(attachAdapter);
|
|
332
|
+
if (adapter.backend !== backend.id) {
|
|
333
|
+
throw new Error(`adapter backend "${adapter.backend}" is not ${backend.id}`);
|
|
334
|
+
}
|
|
335
|
+
if (adapter.modelId !== payload.modelId) {
|
|
336
|
+
throw new Error(`adapter base "${adapter.modelId}" does not match checkpoint base "${payload.modelId}"`);
|
|
337
|
+
}
|
|
338
|
+
const adapterDir = adapter.adapterDir ?? adapter.dir ?? null;
|
|
339
|
+
if (!adapterDir) throw new Error('adapter checkpoint has no adapter directory to attach');
|
|
340
|
+
return {
|
|
341
|
+
backend: backend.id,
|
|
342
|
+
kind: 'adapter',
|
|
343
|
+
modelId: payload.modelId,
|
|
344
|
+
dir: adapterDir,
|
|
345
|
+
adapterDir,
|
|
346
|
+
mode: adapter.mode ?? 'lora',
|
|
347
|
+
meta: { ...(adapter.meta ?? {}), attachedTo: file },
|
|
348
|
+
file: attachAdapter,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
backend: backend.id,
|
|
353
|
+
kind: payload.kind,
|
|
354
|
+
modelId: payload.modelId,
|
|
355
|
+
dir: payload.dir,
|
|
356
|
+
adapterDir: payload.adapterDir ?? payload.dir ?? null,
|
|
357
|
+
mode: payload.mode ?? 'lora',
|
|
358
|
+
meta: payload.meta ?? {},
|
|
359
|
+
file,
|
|
360
|
+
};
|
|
361
|
+
},
|
|
362
|
+
|
|
363
|
+
// Same contract as the builtin backend: a synchronous content digest of the
|
|
364
|
+
// weights this handle points at, so callers can detect "adapter does not
|
|
365
|
+
// belong to this base" without loading Python. Python weights live in
|
|
366
|
+
// directories rather than one JSON file, so the digest is over the sorted
|
|
367
|
+
// (relative path, size, sha256) triples of the weight/config files found
|
|
368
|
+
// there. Directory walking is depth-bounded and extension-filtered so a
|
|
369
|
+
// fingerprint cannot be turned into an unbounded scan of the filesystem.
|
|
370
|
+
fingerprint(handle) {
|
|
371
|
+
if (!handle?.modelId) throw new Error('hf-peft fingerprint() requires a handle with modelId');
|
|
372
|
+
const hash = crypto.createHash('sha256');
|
|
373
|
+
hash.update(`${backend.id}\u0000${handle.modelId}\u0000${handle.mode ?? 'lora'}`);
|
|
374
|
+
const dirs = [];
|
|
375
|
+
for (const dir of [handle.dir, handle.adapterDir]) {
|
|
376
|
+
if (dir && !dirs.includes(dir)) dirs.push(dir);
|
|
377
|
+
}
|
|
378
|
+
// Positional label, not the directory name: identical weights must
|
|
379
|
+
// fingerprint identically after a checkpoint directory is moved or copied.
|
|
380
|
+
for (let i = 0; i < dirs.length; i += 1) {
|
|
381
|
+
hash.update(`\u0000dir${i}`);
|
|
382
|
+
for (const entry of digestWeightDir(dirs[i])) hash.update(`\u0000${entry}`);
|
|
383
|
+
}
|
|
384
|
+
return hash.digest('hex');
|
|
385
|
+
},
|
|
386
|
+
|
|
387
|
+
async saveModel({ handle, file, kind = 'adapter', meta = {} } = {}) {
|
|
388
|
+
const probe = await backend.probe();
|
|
389
|
+
if (!probe.available) throw unavailable('save a checkpoint', probe);
|
|
390
|
+
const payload = {
|
|
391
|
+
format: 'tmf-checkpoint-v1',
|
|
392
|
+
backend: backend.id,
|
|
393
|
+
kind,
|
|
394
|
+
modelId: handle.modelId,
|
|
395
|
+
dir: handle.dir ?? handle.adapterDir ?? null,
|
|
396
|
+
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
397
|
+
mode: handle.mode ?? 'lora',
|
|
398
|
+
meta,
|
|
399
|
+
};
|
|
400
|
+
await writeFileAtomic(file, `${JSON.stringify(payload)}\n`);
|
|
401
|
+
return { file, sha256: await sha256File(file), kind };
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
// The spec and command are written to disk even when the backend is
|
|
405
|
+
// unavailable, so the training recipe this backend would run is reviewable
|
|
406
|
+
// without running it.
|
|
407
|
+
async renderTrainingScript({ handle, examplesFile, hyper = {}, budget = {}, outDir, mode, resumeFrom = null }) {
|
|
408
|
+
await ensureDir(outDir);
|
|
409
|
+
const limits = limitsFrom(budget, hyper);
|
|
410
|
+
const spec = {
|
|
411
|
+
op: 'train',
|
|
412
|
+
modelId: handle?.modelId ?? 'MODEL_ID',
|
|
413
|
+
adapterDir: handle?.adapterDir ?? null,
|
|
414
|
+
mode: mode ?? handle?.mode ?? 'lora',
|
|
415
|
+
examplesFile,
|
|
416
|
+
outDir,
|
|
417
|
+
resumeFrom,
|
|
418
|
+
batchSize: hyper.batchSize ?? 2,
|
|
419
|
+
lr: hyper.lr ?? 1e-3,
|
|
420
|
+
seed: hyper.seed ?? 1,
|
|
421
|
+
lora: hyper.lora ?? { rank: 8, alpha: 16, targets: ['q_proj', 'v_proj'] },
|
|
422
|
+
budget: {
|
|
423
|
+
maxSteps: budget.maxSteps ?? 20,
|
|
424
|
+
maxSeconds: budget.maxSeconds ?? null,
|
|
425
|
+
checkpointEvery: budget.checkpointEvery ?? 0,
|
|
426
|
+
},
|
|
427
|
+
...limits,
|
|
428
|
+
};
|
|
429
|
+
const specFile = path.join(outDir, 'hf-peft-train-spec.json');
|
|
430
|
+
await writeFileAtomic(specFile, `${JSON.stringify(spec, null, 2)}\n`);
|
|
431
|
+
const file = path.join(outDir, 'hf-peft-train.sh');
|
|
432
|
+
await writeFileAtomic(file, `#!/bin/sh\n# exact command executed by the hf-peft backend\n${pythonBin()} ${RUNNER} ${specFile}\n`);
|
|
433
|
+
return { file, specFile, runner: RUNNER, spec, sha256: await sha256File(file) };
|
|
434
|
+
},
|
|
435
|
+
|
|
436
|
+
async train({
|
|
437
|
+
handle,
|
|
438
|
+
examplesFile,
|
|
439
|
+
examples,
|
|
440
|
+
mode,
|
|
441
|
+
hyper = {},
|
|
442
|
+
budget = {},
|
|
443
|
+
resume = null,
|
|
444
|
+
signal = null,
|
|
445
|
+
outDir = path.join(process.cwd(), '.tmf-run', 'hf-peft'),
|
|
446
|
+
} = {}) {
|
|
447
|
+
const probe = await backend.probe();
|
|
448
|
+
// The builtin backend takes in-memory examples; this one needs a file for
|
|
449
|
+
// the Python worker. Accepting both keeps the two backends callable through
|
|
450
|
+
// one parameter contract instead of making every caller branch on backend
|
|
451
|
+
// id. The materialized file is written under the run's own outDir.
|
|
452
|
+
let trainFile = examplesFile;
|
|
453
|
+
if (!trainFile && examples?.length) {
|
|
454
|
+
await ensureDir(outDir);
|
|
455
|
+
trainFile = path.join(outDir, 'train-examples.jsonl');
|
|
456
|
+
await writeFileAtomic(trainFile, `${examples.map((e) => JSON.stringify(e)).join('\n')}\n`);
|
|
457
|
+
}
|
|
458
|
+
const rendered = await backend.renderTrainingScript({
|
|
459
|
+
handle, examplesFile: trainFile, hyper, budget, outDir, mode, resumeFrom: resume,
|
|
460
|
+
});
|
|
461
|
+
if (!probe.available) {
|
|
462
|
+
const err = unavailable('train', probe);
|
|
463
|
+
err.renderedScript = rendered.file;
|
|
464
|
+
err.renderedSpec = rendered.specFile;
|
|
465
|
+
throw err;
|
|
466
|
+
}
|
|
467
|
+
if (!trainFile) throw new Error('hf-peft train() requires examplesFile or examples (prompt/completion records)');
|
|
468
|
+
const { spec } = rendered;
|
|
469
|
+
const timeoutMs = ((budget.maxSeconds ?? 1800) + 120) * 1000;
|
|
470
|
+
const { payload, specFile } = await runOp('train', spec, { outDir, timeoutMs, signal });
|
|
471
|
+
return {
|
|
472
|
+
metrics: payload.metrics,
|
|
473
|
+
history: payload.history,
|
|
474
|
+
stopReason: payload.metrics.stopReason,
|
|
475
|
+
// There is no portable optimizer state to hand back: it lives in the
|
|
476
|
+
// Trainer checkpoint directories, which are what resume consumes.
|
|
477
|
+
optimizerState: null,
|
|
478
|
+
checkpoints: payload.checkpoints,
|
|
479
|
+
handle: { ...handle, mode: spec.mode, dir: payload.adapterDir, adapterDir: payload.adapterDir },
|
|
480
|
+
script: rendered.file,
|
|
481
|
+
specFile,
|
|
482
|
+
limits: payload.limits,
|
|
483
|
+
};
|
|
484
|
+
},
|
|
485
|
+
|
|
486
|
+
// Independent evaluation: this loads the base model (plus the adapter when
|
|
487
|
+
// the handle has one) in a fresh process and scores the given examples. It
|
|
488
|
+
// shares no state with train(), so a baseline and a tuned run are two
|
|
489
|
+
// separate measurements rather than two reads of one training log.
|
|
490
|
+
async evaluate({ handle, examplesFile, examples, hyper = {}, budget = {}, signal = null, outDir } = {}) {
|
|
491
|
+
const probe = await backend.probe();
|
|
492
|
+
if (!probe.available) throw unavailable('evaluate', probe);
|
|
493
|
+
if (!handle?.modelId) throw new Error('hf-peft evaluate() requires a handle with modelId');
|
|
494
|
+
const dir = outDir ?? path.join(process.cwd(), '.tmf-run', 'hf-peft-eval');
|
|
495
|
+
await ensureDir(dir);
|
|
496
|
+
let file = examplesFile;
|
|
497
|
+
if (!file) {
|
|
498
|
+
if (!examples?.length) throw new Error('evaluation needs at least one example');
|
|
499
|
+
file = path.join(dir, 'eval-examples.jsonl');
|
|
500
|
+
await writeFileAtomic(file, `${examples.map((e) => JSON.stringify(e)).join('\n')}\n`);
|
|
501
|
+
}
|
|
502
|
+
const spec = {
|
|
503
|
+
modelId: handle.modelId,
|
|
504
|
+
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
505
|
+
mode: handle.mode ?? 'lora',
|
|
506
|
+
examplesFile: file,
|
|
507
|
+
...limitsFrom(budget, hyper),
|
|
508
|
+
};
|
|
509
|
+
const { payload } = await runOp('evaluate', spec, {
|
|
510
|
+
outDir: dir, timeoutMs: ((budget.maxSeconds ?? 600) + 120) * 1000, signal,
|
|
511
|
+
});
|
|
512
|
+
return {
|
|
513
|
+
loss: payload.loss,
|
|
514
|
+
perplexity: payload.perplexity,
|
|
515
|
+
tokens: payload.tokens,
|
|
516
|
+
examples: payload.examples,
|
|
517
|
+
adapterLoaded: payload.adapterLoaded,
|
|
518
|
+
backend: backend.id,
|
|
519
|
+
limits: payload.limits,
|
|
520
|
+
};
|
|
521
|
+
},
|
|
522
|
+
|
|
523
|
+
async generate({
|
|
524
|
+
handle, prompt, maxNewTokens = 16, temperature = 0, seed = 1,
|
|
525
|
+
hyper = {}, budget = {}, signal = null, outDir,
|
|
526
|
+
} = {}) {
|
|
527
|
+
const probe = await backend.probe();
|
|
528
|
+
if (!probe.available) throw unavailable('generate', probe);
|
|
529
|
+
if (!handle?.modelId) throw new Error('hf-peft generate() requires a handle with modelId');
|
|
530
|
+
const dir = outDir ?? path.join(process.cwd(), '.tmf-run', 'hf-peft-gen');
|
|
531
|
+
const spec = {
|
|
532
|
+
modelId: handle.modelId,
|
|
533
|
+
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
534
|
+
mode: handle.mode ?? 'lora',
|
|
535
|
+
prompt: prompt ?? '',
|
|
536
|
+
maxNewTokens,
|
|
537
|
+
temperature,
|
|
538
|
+
seed,
|
|
539
|
+
...limitsFrom(budget, hyper),
|
|
540
|
+
};
|
|
541
|
+
const { payload } = await runOp('generate', spec, {
|
|
542
|
+
outDir: dir, timeoutMs: ((budget.maxSeconds ?? 300) + 120) * 1000, signal,
|
|
543
|
+
});
|
|
544
|
+
// Same shape as the builtin backend: callers get the decoded continuation.
|
|
545
|
+
return payload.text;
|
|
546
|
+
},
|
|
547
|
+
};
|
|
548
|
+
|
|
549
|
+
export default backend;
|