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