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,397 @@
1
+ #!/usr/bin/env python3
2
+ """Real local execution runner for the hf-peft backend.
3
+
4
+ This file is the backend's only execution path. It is a checked-in program
5
+ rather than a string rendered at call time so that what runs is what can be
6
+ reviewed. It is driven by a JSON spec file and prints exactly one result line
7
+ prefixed with ``__TMF_RESULT__``; everything else on stdout/stderr is framework
8
+ noise that the Node side keeps as a log artifact.
9
+
10
+ Operations: ``train``, ``evaluate``, ``generate``.
11
+
12
+ Resource bounds are applied in-process before any framework import does real
13
+ work: address-space (RLIMIT_AS) and CPU-seconds (RLIMIT_CPU) are hard kernel
14
+ limits, so exceeding them terminates this process rather than relying on the
15
+ caller noticing. Thread count is pinned so CPU use stays bounded. The step and
16
+ wall-clock budgets are enforced by a Trainer callback, which is cooperative by
17
+ construction and is reported as such.
18
+ """
19
+
20
+ import json
21
+ import math
22
+ import os
23
+ import resource
24
+ import sys
25
+ import time
26
+
27
+ RESULT_PREFIX = "__TMF_RESULT__"
28
+
29
+
30
+ def emit(payload):
31
+ sys.stdout.write(RESULT_PREFIX + " " + json.dumps(payload) + "\n")
32
+ sys.stdout.flush()
33
+
34
+
35
+ def apply_limits(spec):
36
+ applied = {}
37
+ mem_mb = spec.get("maxMemoryMb")
38
+ if mem_mb:
39
+ nbytes = int(mem_mb) * 1024 * 1024
40
+ resource.setrlimit(resource.RLIMIT_AS, (nbytes, nbytes))
41
+ applied["maxMemoryMb"] = int(mem_mb)
42
+ cpu_s = spec.get("maxCpuSeconds")
43
+ if cpu_s:
44
+ resource.setrlimit(resource.RLIMIT_CPU, (int(cpu_s), int(cpu_s)))
45
+ applied["maxCpuSeconds"] = int(cpu_s)
46
+ threads = int(spec.get("threads", 1) or 1)
47
+ for var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "TOKENIZERS_PARALLELISM"):
48
+ os.environ.setdefault(var, "1" if var == "TOKENIZERS_PARALLELISM" else str(threads))
49
+ applied["threads"] = threads
50
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
51
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
52
+ applied["offline"] = True
53
+ return applied
54
+
55
+
56
+ def peak_rss_mb():
57
+ return round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, 3)
58
+
59
+
60
+ def selected_device(torch):
61
+ requested = os.environ.get("TMF_DEVICE", "cpu")
62
+ if requested not in ("cpu", "cuda"):
63
+ raise ValueError(f"unsupported TMF_DEVICE={requested!r}")
64
+ if requested == "cuda" and not torch.cuda.is_available():
65
+ raise RuntimeError("TMF_DEVICE=cuda requested but CUDA is unavailable")
66
+ fraction = os.environ.get("TMF_CUDA_MEMORY_FRACTION")
67
+ if fraction is not None:
68
+ if requested != "cuda" or not (0 < float(fraction) <= 1):
69
+ raise ValueError("TMF_CUDA_MEMORY_FRACTION requires CUDA and a value in (0, 1]")
70
+ torch.cuda.set_per_process_memory_fraction(float(fraction))
71
+ return torch.device(requested)
72
+
73
+
74
+ def load_rows(path):
75
+ rows = []
76
+ with open(path, "r", encoding="utf-8") as fh:
77
+ for line in fh:
78
+ line = line.strip()
79
+ if line:
80
+ rows.append(json.loads(line))
81
+ return rows
82
+
83
+
84
+ def encode_row(tok, row, max_len):
85
+ prompt_ids = tok(row["prompt"], add_special_tokens=False)["input_ids"]
86
+ full_ids = tok(row["prompt"] + row.get("completion", ""), add_special_tokens=False)["input_ids"]
87
+ # A supervised completion needs an end target. Without EOS the model is
88
+ # trained to emit the answer prefix but never to stop, while greedy exact
89
+ # match expects the whole completion and marks every overlong answer wrong.
90
+ if row.get("completion") and tok.eos_token_id is not None and len(full_ids) < max_len:
91
+ full_ids.append(tok.eos_token_id)
92
+ full_ids = full_ids[:max_len]
93
+ labels = [-100] * min(len(prompt_ids), len(full_ids)) + full_ids[min(len(prompt_ids), len(full_ids)):]
94
+ return {"input_ids": full_ids, "labels": labels, "attention_mask": [1] * len(full_ids)}
95
+
96
+
97
+ def build_model(spec, torch, want_training):
98
+ from transformers import AutoModelForCausalLM, AutoTokenizer
99
+
100
+ model_id = spec["modelId"]
101
+ tok = AutoTokenizer.from_pretrained(model_id, local_files_only=True)
102
+ if tok.pad_token is None:
103
+ tok.pad_token = tok.eos_token or tok.unk_token
104
+ model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)
105
+ adapter = spec.get("adapterDir")
106
+ mode = spec.get("mode", "lora")
107
+ peft_info = {"mode": mode, "adapterLoaded": False}
108
+ if adapter and os.path.isdir(adapter):
109
+ from peft import PeftModel
110
+
111
+ model = PeftModel.from_pretrained(model, adapter, is_trainable=want_training)
112
+ peft_info["adapterLoaded"] = True
113
+ elif want_training and mode == "lora":
114
+ from peft import LoraConfig, get_peft_model
115
+
116
+ lora = spec.get("lora") or {}
117
+ model = get_peft_model(
118
+ model,
119
+ LoraConfig(
120
+ r=int(lora.get("rank", 8)),
121
+ lora_alpha=int(lora.get("alpha", 16)),
122
+ lora_dropout=float(lora.get("dropout", 0.0)),
123
+ target_modules=lora.get("targets") or ["q_proj", "v_proj"],
124
+ task_type="CAUSAL_LM",
125
+ ),
126
+ )
127
+ model.config.use_cache = False if want_training else True
128
+ return tok, model, peft_info
129
+
130
+
131
+ def trainable_snapshot(model, torch):
132
+ return {n: p.detach().clone() for n, p in model.named_parameters() if p.requires_grad}
133
+
134
+
135
+ def l2_delta(before, after, torch):
136
+ total = 0.0
137
+ for name, tensor in before.items():
138
+ if name in after:
139
+ total += float(torch.sum((after[name] - tensor) ** 2))
140
+ return math.sqrt(total)
141
+
142
+
143
+ def op_train(spec):
144
+ import torch
145
+ from datasets import Dataset
146
+ from transformers import (
147
+ DataCollatorForSeq2Seq,
148
+ Trainer,
149
+ TrainerCallback,
150
+ TrainingArguments,
151
+ )
152
+
153
+ device = selected_device(torch)
154
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
155
+ torch.manual_seed(int(spec.get("seed", 1)))
156
+ started = time.time()
157
+ tok, model, peft_info = build_model(spec, torch, want_training=True)
158
+ rows = load_rows(spec["examplesFile"])
159
+ if not rows:
160
+ raise ValueError("training needs at least one example")
161
+ max_len = int(spec.get("maxSeqLen", 128))
162
+ ds = Dataset.from_list([encode_row(tok, r, max_len) for r in rows])
163
+
164
+ budget = spec.get("budget") or {}
165
+ max_seconds = budget.get("maxSeconds")
166
+ stop_state = {"reason": None}
167
+
168
+ class BudgetCallback(TrainerCallback):
169
+ """Cooperative stop: checked between steps, never mid-kernel."""
170
+
171
+ def on_step_end(self, args, state, control, **kwargs):
172
+ if max_seconds and (time.time() - started) > float(max_seconds):
173
+ stop_state["reason"] = "time_budget"
174
+ control.should_training_stop = True
175
+ return control
176
+
177
+ out_dir = spec["outDir"]
178
+ os.makedirs(out_dir, exist_ok=True)
179
+ save_steps = int(budget.get("checkpointEvery", 0) or 0)
180
+ args_kwargs = dict(
181
+ output_dir=out_dir,
182
+ per_device_train_batch_size=int(spec.get("batchSize", 2)),
183
+ learning_rate=float(spec.get("lr", 1e-3)),
184
+ max_steps=int(budget.get("maxSteps", 20)),
185
+ logging_steps=1,
186
+ report_to=[],
187
+ save_strategy="steps" if save_steps > 0 else "no",
188
+ seed=int(spec.get("seed", 1)),
189
+ use_cpu=device.type == "cpu",
190
+ dataloader_num_workers=0,
191
+ disable_tqdm=True,
192
+ )
193
+ if save_steps > 0:
194
+ args_kwargs["save_steps"] = save_steps
195
+ # TrainingArguments gains and drops keyword arguments between transformers
196
+ # major versions. Filtering against the real signature keeps this runner
197
+ # working on the installed version instead of pinning one, and the dropped
198
+ # names are reported so a silently ignored budget is visible.
199
+ import inspect
200
+
201
+ supported = set(inspect.signature(TrainingArguments.__init__).parameters)
202
+ dropped = sorted(k for k in args_kwargs if k not in supported)
203
+ args = TrainingArguments(**{k: v for k, v in args_kwargs.items() if k in supported})
204
+ collator = DataCollatorForSeq2Seq(tok, model=model, padding=True, label_pad_token_id=-100)
205
+ trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collator, callbacks=[BudgetCallback()])
206
+
207
+ before = trainable_snapshot(model, torch)
208
+ resume = spec.get("resumeFrom")
209
+ result = trainer.train(resume_from_checkpoint=resume if resume else None)
210
+ after = trainable_snapshot(model, torch)
211
+
212
+ history = [
213
+ {"step": int(e["step"]), "loss": float(e["loss"])}
214
+ for e in trainer.state.log_history
215
+ if "loss" in e and "step" in e
216
+ ]
217
+ adapter_dir = os.path.join(out_dir, "adapter")
218
+ model.save_pretrained(adapter_dir)
219
+ tok.save_pretrained(adapter_dir)
220
+ checkpoints = sorted(
221
+ os.path.join(out_dir, d) for d in os.listdir(out_dir) if d.startswith("checkpoint-")
222
+ )
223
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
224
+ metrics = {
225
+ "backend": "hf-peft",
226
+ "device": device.type,
227
+ "peakCudaAllocatedMb": round(torch.cuda.max_memory_allocated() / 1048576, 3) if device.type == "cuda" else None,
228
+ "mode": peft_info["mode"],
229
+ "resumedFrom": resume or None,
230
+ "steps": int(trainer.state.global_step) - (int(trainer.state.global_step) - len(history) if resume else 0),
231
+ "totalSteps": int(trainer.state.global_step),
232
+ "firstLoss": history[0]["loss"] if history else None,
233
+ "finalLoss": history[-1]["loss"] if history else None,
234
+ "bestLoss": min((h["loss"] for h in history), default=None),
235
+ "trainLossMean": float(result.training_loss) if result and result.training_loss is not None else None,
236
+ "trainableParams": trainable,
237
+ "parameterL2Delta": round(l2_delta(before, after, torch), 8),
238
+ "tokensSeen": int(sum(len(r["input_ids"]) for r in ds)) * max(1, int(trainer.state.global_step) // max(1, len(ds))),
239
+ "wallClockSeconds": round(time.time() - started, 3),
240
+ "peakRssMb": peak_rss_mb(),
241
+ "stepBudget": int(budget.get("maxSteps", 20)),
242
+ "stopReason": stop_state["reason"] or "completed",
243
+ "unsupportedTrainerArgs": dropped,
244
+ }
245
+ emit({
246
+ "op": "train",
247
+ "metrics": metrics,
248
+ "history": history,
249
+ "adapterDir": adapter_dir,
250
+ "checkpoints": checkpoints,
251
+ "limits": spec.get("_appliedLimits"),
252
+ })
253
+
254
+
255
+ def op_evaluate(spec):
256
+ import torch
257
+
258
+ device = selected_device(torch)
259
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
260
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
261
+ model.to(device)
262
+ model.eval()
263
+ rows = load_rows(spec["examplesFile"])
264
+ if not rows:
265
+ raise ValueError("evaluation needs at least one example")
266
+ max_len = int(spec.get("maxSeqLen", 128))
267
+ total_loss = 0.0
268
+ total_tokens = 0
269
+ started = time.time()
270
+ with torch.no_grad():
271
+ for row in rows:
272
+ enc = encode_row(tok, row, max_len)
273
+ if len(enc["input_ids"]) < 2:
274
+ continue
275
+ ids = torch.tensor([enc["input_ids"]], device=device)
276
+ labels = torch.tensor([enc["labels"]], device=device)
277
+ out = model(input_ids=ids, labels=labels)
278
+ # Count only supervised positions so the mean is token-weighted.
279
+ counted = int((labels[:, 1:] != -100).sum())
280
+ if counted == 0:
281
+ continue
282
+ total_loss += float(out.loss) * counted
283
+ total_tokens += counted
284
+ if total_tokens == 0:
285
+ raise ValueError("no supervised tokens in evaluation set")
286
+ loss = total_loss / total_tokens
287
+ emit({
288
+ "op": "evaluate",
289
+ "loss": round(loss, 6),
290
+ "perplexity": round(math.exp(min(loss, 50.0)), 6),
291
+ "tokens": total_tokens,
292
+ "examples": len(rows),
293
+ "adapterLoaded": peft_info["adapterLoaded"],
294
+ "device": device.type,
295
+ "wallClockSeconds": round(time.time() - started, 3),
296
+ "peakRssMb": peak_rss_mb(),
297
+ "limits": spec.get("_appliedLimits"),
298
+ })
299
+
300
+
301
+ def op_generate(spec):
302
+ import torch
303
+
304
+ device = selected_device(torch)
305
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
306
+ torch.manual_seed(int(spec.get("seed", 1)))
307
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
308
+ model.to(device)
309
+ model.eval()
310
+ prompt = spec.get("prompt", "")
311
+ ids = tok(prompt, return_tensors="pt", add_special_tokens=False).to(device)
312
+ temperature = float(spec.get("temperature", 0.0))
313
+ started = time.time()
314
+ with torch.no_grad():
315
+ out = model.generate(
316
+ **ids,
317
+ max_new_tokens=int(spec.get("maxNewTokens", 16)),
318
+ do_sample=temperature > 0,
319
+ temperature=temperature if temperature > 0 else None,
320
+ pad_token_id=tok.pad_token_id,
321
+ )
322
+ new_ids = out[0][ids["input_ids"].shape[1]:]
323
+ emit({
324
+ "op": "generate",
325
+ "text": tok.decode(new_ids, skip_special_tokens=True),
326
+ "newTokens": int(new_ids.shape[0]),
327
+ "adapterLoaded": peft_info["adapterLoaded"],
328
+ "device": device.type,
329
+ "wallClockSeconds": round(time.time() - started, 3),
330
+ "peakRssMb": peak_rss_mb(),
331
+ "limits": spec.get("_appliedLimits"),
332
+ })
333
+
334
+
335
+ def op_generate_batch(spec):
336
+ import torch
337
+
338
+ device = selected_device(torch)
339
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
340
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
341
+ model.to(device)
342
+ model.eval()
343
+ rows = load_rows(spec["promptsFile"])
344
+ if not rows or any(not isinstance(row.get("prompt"), str) for row in rows):
345
+ raise ValueError("generate_batch needs non-empty prompt records")
346
+ temperature = float(spec.get("temperature", 0.0))
347
+ max_new_tokens = int(spec.get("maxNewTokens", 16))
348
+ texts = []
349
+ started = time.time()
350
+ with torch.no_grad():
351
+ for row in rows:
352
+ # A single-prompt subprocess reseeds on every call. Preserve that
353
+ # behavior for sampled generation as well as greedy decoding.
354
+ torch.manual_seed(int(spec.get("seed", 1)))
355
+ ids = tok(row["prompt"], return_tensors="pt", add_special_tokens=False).to(device)
356
+ out = model.generate(
357
+ **ids,
358
+ max_new_tokens=max_new_tokens,
359
+ do_sample=temperature > 0,
360
+ temperature=temperature if temperature > 0 else None,
361
+ pad_token_id=tok.pad_token_id,
362
+ )
363
+ new_ids = out[0][ids["input_ids"].shape[1]:]
364
+ texts.append(tok.decode(new_ids, skip_special_tokens=True))
365
+ emit({
366
+ "op": "generate_batch",
367
+ "texts": texts,
368
+ "count": len(texts),
369
+ "adapterLoaded": peft_info["adapterLoaded"],
370
+ "device": device.type,
371
+ "wallClockSeconds": round(time.time() - started, 3),
372
+ "peakRssMb": peak_rss_mb(),
373
+ "peakCudaAllocatedMb": round(torch.cuda.max_memory_allocated() / 1048576, 3) if device.type == "cuda" else None,
374
+ "limits": spec.get("_appliedLimits"),
375
+ })
376
+
377
+
378
+ OPS = {"train": op_train, "evaluate": op_evaluate, "generate": op_generate, "generate_batch": op_generate_batch}
379
+
380
+
381
+ def main():
382
+ if len(sys.argv) < 2:
383
+ print("usage: hf_peft_runner.py <spec.json>", file=sys.stderr)
384
+ return 2
385
+ with open(sys.argv[1], "r", encoding="utf-8") as fh:
386
+ spec = json.load(fh)
387
+ spec["_appliedLimits"] = apply_limits(spec)
388
+ op = spec.get("op")
389
+ if op not in OPS:
390
+ print(f"unknown op: {op}", file=sys.stderr)
391
+ return 2
392
+ OPS[op](spec)
393
+ return 0
394
+
395
+
396
+ if __name__ == "__main__":
397
+ sys.exit(main())
@@ -0,0 +1,92 @@
1
+ // Trainer backend registry.
2
+ //
3
+ // A backend is the seam between the foundry and whatever actually updates
4
+ // weights. Everything above this layer (jobs, evaluation, export, integrations)
5
+ // talks only to this interface, which is what makes a second backend a drop-in
6
+ // rather than a rewrite.
7
+ //
8
+ // Required surface:
9
+ //
10
+ // id stable identifier used in configs and lineage
11
+ // capabilities { modes, frameworks, devices, supportsResume }
12
+ // probe() -> { available, reason?, details? } must never throw
13
+ // createModel() -> handle for a fresh model
14
+ // loadModel() -> handle restored from a checkpoint
15
+ // saveModel() -> { file, sha256 }
16
+ // train() -> { steps, history, stopReason, metrics }
17
+ // evaluate() -> { loss, perplexity, tokens }
18
+ // generate() -> string
19
+ //
20
+ // `probe` is deliberately total: an unavailable backend is a recorded fact, not
21
+ // an exception, so a job can report "not verified in this environment" instead
22
+ // of failing in a way that looks like a bug.
23
+
24
+ const REQUIRED_METHODS = ['probe', 'createModel', 'loadModel', 'saveModel', 'train', 'evaluate', 'generate'];
25
+
26
+ const registry = new Map();
27
+
28
+ export function registerBackend(backend) {
29
+ if (!backend?.id) throw new Error('a backend must expose an id');
30
+ for (const method of REQUIRED_METHODS) {
31
+ if (typeof backend[method] !== 'function') {
32
+ throw new Error(`backend "${backend.id}" is missing required method ${method}()`);
33
+ }
34
+ }
35
+ if (!backend.capabilities?.modes?.length) {
36
+ throw new Error(`backend "${backend.id}" must declare capabilities.modes`);
37
+ }
38
+ registry.set(backend.id, backend);
39
+ return backend;
40
+ }
41
+
42
+ export function getBackend(id) {
43
+ const backend = registry.get(id);
44
+ if (!backend) {
45
+ throw new Error(`unknown trainer backend "${id}"; registered: ${[...registry.keys()].join(', ') || 'none'}`);
46
+ }
47
+ return backend;
48
+ }
49
+
50
+ export function listBackends() {
51
+ return [...registry.values()].map((b) => ({ id: b.id, capabilities: b.capabilities }));
52
+ }
53
+
54
+ export async function probeBackends() {
55
+ const out = [];
56
+ for (const backend of registry.values()) {
57
+ let result;
58
+ try {
59
+ result = await backend.probe();
60
+ } catch (err) {
61
+ // A throwing probe is itself a availability failure, not a crash.
62
+ result = { available: false, reason: `probe threw: ${err.message}` };
63
+ }
64
+ out.push({ id: backend.id, capabilities: backend.capabilities, ...result });
65
+ }
66
+ return out;
67
+ }
68
+
69
+ export async function resolveBackend(id) {
70
+ const backend = getBackend(id);
71
+ const probe = await backend.probe();
72
+ if (!probe.available) {
73
+ const err = new Error(`trainer backend "${id}" is not available in this environment: ${probe.reason}`);
74
+ err.backendProbe = probe;
75
+ err.code = 'BACKEND_UNAVAILABLE';
76
+ throw err;
77
+ }
78
+ return backend;
79
+ }
80
+
81
+ export function clearBackends() {
82
+ registry.clear();
83
+ }
84
+
85
+ // Side-effecting imports register the built-in backends.
86
+ export async function loadDefaultBackends() {
87
+ const builtin = await import('./builtin-js.mjs');
88
+ const hf = await import('./hf-peft.mjs');
89
+ registerBackend(builtin.default);
90
+ registerBackend(hf.default);
91
+ return listBackends();
92
+ }
@@ -0,0 +1,56 @@
1
+ // Turns pipeline records into token sequences.
2
+ //
3
+ // Instruction records keep a prompt boundary so the loss is only taken on the
4
+ // completion; plain documents train on every position.
5
+
6
+ import { Tokenizer } from '../model/tokenizer.mjs';
7
+
8
+ export function buildTokenizer(records, { maxVocab = 256 } = {}) {
9
+ return Tokenizer.fromTexts(records.map((r) => (r.prompt !== null && r.prompt !== undefined ? `${r.prompt}${r.completion ?? ''}` : r.text)), { maxVocab });
10
+ }
11
+
12
+ export function encodeRecord(record, tokenizer, { maxSeqLen = 96 } = {}) {
13
+ const hasPrompt = record.prompt !== null && record.prompt !== undefined && record.completion !== null && record.completion !== undefined;
14
+ let ids;
15
+ let promptLen = 0;
16
+ if (hasPrompt) {
17
+ const promptIds = tokenizer.encode(record.prompt, { bos: true });
18
+ const completionIds = tokenizer.encode(record.completion, { eos: true });
19
+ ids = [...promptIds, ...completionIds];
20
+ promptLen = promptIds.length;
21
+ } else {
22
+ ids = tokenizer.encode(record.text, { bos: true, eos: true });
23
+ }
24
+ if (ids.length > maxSeqLen) {
25
+ // Keep the prompt and truncate the tail; a truncated completion still
26
+ // teaches the prefix, while dropping the prompt would teach nothing.
27
+ ids = ids.slice(0, maxSeqLen);
28
+ }
29
+ return { id: record.id, ids, promptLen: Math.min(promptLen, ids.length - 1), chars: (record.text ?? '').length };
30
+ }
31
+
32
+ export function encodeRecords(records, tokenizer, options = {}) {
33
+ const out = [];
34
+ const skipped = [];
35
+ for (const record of records) {
36
+ const encoded = encodeRecord(record, tokenizer, options);
37
+ if (encoded.ids.length < 2) {
38
+ skipped.push({ id: record.id, reason: 'too_short_after_encoding' });
39
+ continue;
40
+ }
41
+ out.push(encoded);
42
+ }
43
+ return { examples: out, skipped };
44
+ }
45
+
46
+ export function countTokens(examples) {
47
+ return examples.reduce((n, e) => n + e.ids.length, 0);
48
+ }
49
+
50
+ // Deterministic batches: the rng is seeded per epoch by the caller.
51
+ export function makeBatches(examples, batchSize, rng) {
52
+ const order = rng ? rng.shuffled(examples) : examples;
53
+ const batches = [];
54
+ for (let i = 0; i < order.length; i += batchSize) batches.push(order.slice(i, i + batchSize));
55
+ return batches;
56
+ }
@@ -0,0 +1,99 @@
1
+ // AdamW with decoupled weight decay and global-norm gradient clipping.
2
+ //
3
+ // State is kept per parameter name so an optimizer can be serialized into a job
4
+ // checkpoint and resumed without changing the trajectory.
5
+
6
+ export const DEFAULT_OPTIMIZER_CONFIG = {
7
+ lr: 0.01,
8
+ beta1: 0.9,
9
+ beta2: 0.999,
10
+ eps: 1e-8,
11
+ weightDecay: 0.01,
12
+ clipNorm: 1,
13
+ };
14
+
15
+ export class AdamW {
16
+ constructor(params, config = {}) {
17
+ this.config = { ...DEFAULT_OPTIMIZER_CONFIG, ...config };
18
+ this.params = params;
19
+ this.step = 0;
20
+ this.state = new Map();
21
+ for (const p of params) {
22
+ if (!p.name) throw new Error('every trainable parameter needs a name so optimizer state can be checkpointed');
23
+ this.state.set(p.name, { m: new Float64Array(p.size), v: new Float64Array(p.size) });
24
+ }
25
+ }
26
+
27
+ gradNorm() {
28
+ let total = 0;
29
+ for (const p of this.params) {
30
+ if (!p.grad) continue;
31
+ for (let i = 0; i < p.grad.length; i += 1) total += p.grad[i] * p.grad[i];
32
+ }
33
+ return Math.sqrt(total);
34
+ }
35
+
36
+ applyStep({ lr } = {}) {
37
+ const cfg = this.config;
38
+ const learningRate = lr ?? cfg.lr;
39
+ this.step += 1;
40
+
41
+ let clipScale = 1;
42
+ const norm = this.gradNorm();
43
+ if (cfg.clipNorm && norm > cfg.clipNorm) clipScale = cfg.clipNorm / (norm + 1e-12);
44
+
45
+ const bc1 = 1 - Math.pow(cfg.beta1, this.step);
46
+ const bc2 = 1 - Math.pow(cfg.beta2, this.step);
47
+
48
+ for (const p of this.params) {
49
+ const st = this.state.get(p.name);
50
+ const grad = p.grad;
51
+ if (!grad) continue;
52
+ for (let i = 0; i < p.size; i += 1) {
53
+ const g = grad[i] * clipScale;
54
+ st.m[i] = cfg.beta1 * st.m[i] + (1 - cfg.beta1) * g;
55
+ st.v[i] = cfg.beta2 * st.v[i] + (1 - cfg.beta2) * g * g;
56
+ const mHat = st.m[i] / bc1;
57
+ const vHat = st.v[i] / bc2;
58
+ // Decoupled decay: applied to the weight, not folded into the gradient.
59
+ const decayed = p.data[i] - learningRate * cfg.weightDecay * p.data[i];
60
+ p.data[i] = decayed - learningRate * (mHat / (Math.sqrt(vHat) + cfg.eps));
61
+ }
62
+ }
63
+ return { gradNorm: norm, clipScale, lr: learningRate };
64
+ }
65
+
66
+ zeroGrad() {
67
+ for (const p of this.params) p.zeroGrad();
68
+ }
69
+
70
+ stateDict() {
71
+ const out = { step: this.step, config: this.config, params: {} };
72
+ for (const [name, st] of this.state) {
73
+ out.params[name] = { m: Array.from(st.m), v: Array.from(st.v) };
74
+ }
75
+ return out;
76
+ }
77
+
78
+ loadStateDict(state) {
79
+ this.step = state.step ?? 0;
80
+ for (const [name, st] of this.state) {
81
+ const saved = state.params?.[name];
82
+ if (!saved) throw new Error(`optimizer state is missing parameter "${name}"`);
83
+ if (saved.m.length !== st.m.length) {
84
+ throw new Error(`optimizer state for "${name}" has length ${saved.m.length}, expected ${st.m.length}`);
85
+ }
86
+ st.m.set(saved.m);
87
+ st.v.set(saved.v);
88
+ }
89
+ return this;
90
+ }
91
+ }
92
+
93
+ // Linear warmup then cosine decay; returns the multiplier for the base lr.
94
+ export function lrSchedule(step, totalSteps, { warmupSteps = 0, minRatio = 0.1 } = {}) {
95
+ if (totalSteps <= 0) return 1;
96
+ if (warmupSteps > 0 && step < warmupSteps) return (step + 1) / warmupSteps;
97
+ const progress = Math.min(1, Math.max(0, (step - warmupSteps) / Math.max(1, totalSteps - warmupSteps)));
98
+ return minRatio + (1 - minRatio) * 0.5 * (1 + Math.cos(Math.PI * progress));
99
+ }
@@ -0,0 +1,5 @@
1
+ // Single source of truth for the toolkit version.
2
+ //
3
+ // It lives in its own module so api.mjs can stamp exports with it without
4
+ // importing the package entry point (which imports api.mjs in turn).
5
+ export const VERSION = '0.2.0';