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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  5. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  6. package/docs/integration.md +227 -0
  7. package/docs/tutorial.md +336 -0
  8. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  9. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  11. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  12. package/integrations/openclaw-plugin/index.mjs +27 -0
  13. package/integrations/openclaw-plugin/tools.mjs +70 -0
  14. package/openclaw.plugin.json +24 -0
  15. package/package.json +70 -4
  16. package/scripts/e2e-demo.sh +56 -0
  17. package/src/api.mjs +341 -0
  18. package/src/config.mjs +342 -0
  19. package/src/core/autograd.mjs +451 -0
  20. package/src/core/fsx.mjs +65 -0
  21. package/src/core/hash.mjs +47 -0
  22. package/src/core/rng.mjs +70 -0
  23. package/src/data/clean.mjs +115 -0
  24. package/src/data/dedupe.mjs +125 -0
  25. package/src/data/ingest.mjs +184 -0
  26. package/src/data/pii.mjs +142 -0
  27. package/src/data/pipeline.mjs +183 -0
  28. package/src/data/provenance.mjs +88 -0
  29. package/src/data/split.mjs +193 -0
  30. package/src/data/synth.mjs +198 -0
  31. package/src/eval/evaluator.mjs +124 -0
  32. package/src/eval/gates.mjs +114 -0
  33. package/src/eval/metrics.mjs +90 -0
  34. package/src/export/package.mjs +365 -0
  35. package/src/index.mjs +26 -0
  36. package/src/integrations/hermes.mjs +177 -0
  37. package/src/integrations/openclaw.mjs +154 -0
  38. package/src/jobs/evaluate.mjs +164 -0
  39. package/src/jobs/runner.mjs +323 -0
  40. package/src/jobs/train.mjs +303 -0
  41. package/src/model/lora.mjs +53 -0
  42. package/src/model/tokenizer.mjs +73 -0
  43. package/src/model/transformer.mjs +276 -0
  44. package/src/train/backends/builtin-js.mjs +367 -0
  45. package/src/train/backends/hf-peft.mjs +549 -0
  46. package/src/train/backends/hf_peft_runner.py +326 -0
  47. package/src/train/backends/index.mjs +92 -0
  48. package/src/train/dataset.mjs +56 -0
  49. package/src/train/optimizer.mjs +99 -0
  50. package/src/version.mjs +5 -0
@@ -0,0 +1,326 @@
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 load_rows(path):
61
+ rows = []
62
+ with open(path, "r", encoding="utf-8") as fh:
63
+ for line in fh:
64
+ line = line.strip()
65
+ if line:
66
+ rows.append(json.loads(line))
67
+ return rows
68
+
69
+
70
+ def encode_row(tok, row, max_len):
71
+ prompt_ids = tok(row["prompt"], add_special_tokens=False)["input_ids"]
72
+ full_ids = tok(row["prompt"] + row.get("completion", ""), add_special_tokens=False)["input_ids"]
73
+ full_ids = full_ids[:max_len]
74
+ labels = [-100] * min(len(prompt_ids), len(full_ids)) + full_ids[min(len(prompt_ids), len(full_ids)):]
75
+ return {"input_ids": full_ids, "labels": labels, "attention_mask": [1] * len(full_ids)}
76
+
77
+
78
+ def build_model(spec, torch, want_training):
79
+ from transformers import AutoModelForCausalLM, AutoTokenizer
80
+
81
+ model_id = spec["modelId"]
82
+ tok = AutoTokenizer.from_pretrained(model_id, local_files_only=True)
83
+ if tok.pad_token is None:
84
+ tok.pad_token = tok.eos_token or tok.unk_token
85
+ model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)
86
+ adapter = spec.get("adapterDir")
87
+ mode = spec.get("mode", "lora")
88
+ peft_info = {"mode": mode, "adapterLoaded": False}
89
+ if adapter and os.path.isdir(adapter):
90
+ from peft import PeftModel
91
+
92
+ model = PeftModel.from_pretrained(model, adapter, is_trainable=want_training)
93
+ peft_info["adapterLoaded"] = True
94
+ elif want_training and mode == "lora":
95
+ from peft import LoraConfig, get_peft_model
96
+
97
+ lora = spec.get("lora") or {}
98
+ model = get_peft_model(
99
+ model,
100
+ LoraConfig(
101
+ r=int(lora.get("rank", 8)),
102
+ lora_alpha=int(lora.get("alpha", 16)),
103
+ lora_dropout=float(lora.get("dropout", 0.0)),
104
+ target_modules=lora.get("targets") or ["q_proj", "v_proj"],
105
+ task_type="CAUSAL_LM",
106
+ ),
107
+ )
108
+ model.config.use_cache = False if want_training else True
109
+ return tok, model, peft_info
110
+
111
+
112
+ def trainable_snapshot(model, torch):
113
+ return {n: p.detach().clone() for n, p in model.named_parameters() if p.requires_grad}
114
+
115
+
116
+ def l2_delta(before, after, torch):
117
+ total = 0.0
118
+ for name, tensor in before.items():
119
+ if name in after:
120
+ total += float(torch.sum((after[name] - tensor) ** 2))
121
+ return math.sqrt(total)
122
+
123
+
124
+ def op_train(spec):
125
+ import torch
126
+ from datasets import Dataset
127
+ from transformers import (
128
+ DataCollatorForSeq2Seq,
129
+ Trainer,
130
+ TrainerCallback,
131
+ TrainingArguments,
132
+ )
133
+
134
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
135
+ torch.manual_seed(int(spec.get("seed", 1)))
136
+ started = time.time()
137
+ tok, model, peft_info = build_model(spec, torch, want_training=True)
138
+ rows = load_rows(spec["examplesFile"])
139
+ if not rows:
140
+ raise ValueError("training needs at least one example")
141
+ max_len = int(spec.get("maxSeqLen", 128))
142
+ ds = Dataset.from_list([encode_row(tok, r, max_len) for r in rows])
143
+
144
+ budget = spec.get("budget") or {}
145
+ max_seconds = budget.get("maxSeconds")
146
+ stop_state = {"reason": None}
147
+
148
+ class BudgetCallback(TrainerCallback):
149
+ """Cooperative stop: checked between steps, never mid-kernel."""
150
+
151
+ def on_step_end(self, args, state, control, **kwargs):
152
+ if max_seconds and (time.time() - started) > float(max_seconds):
153
+ stop_state["reason"] = "time_budget"
154
+ control.should_training_stop = True
155
+ return control
156
+
157
+ out_dir = spec["outDir"]
158
+ os.makedirs(out_dir, exist_ok=True)
159
+ save_steps = int(budget.get("checkpointEvery", 0) or 0)
160
+ args_kwargs = dict(
161
+ output_dir=out_dir,
162
+ per_device_train_batch_size=int(spec.get("batchSize", 2)),
163
+ learning_rate=float(spec.get("lr", 1e-3)),
164
+ max_steps=int(budget.get("maxSteps", 20)),
165
+ logging_steps=1,
166
+ report_to=[],
167
+ save_strategy="steps" if save_steps > 0 else "no",
168
+ seed=int(spec.get("seed", 1)),
169
+ use_cpu=True,
170
+ dataloader_num_workers=0,
171
+ disable_tqdm=True,
172
+ )
173
+ if save_steps > 0:
174
+ args_kwargs["save_steps"] = save_steps
175
+ # TrainingArguments gains and drops keyword arguments between transformers
176
+ # major versions. Filtering against the real signature keeps this runner
177
+ # working on the installed version instead of pinning one, and the dropped
178
+ # names are reported so a silently ignored budget is visible.
179
+ import inspect
180
+
181
+ supported = set(inspect.signature(TrainingArguments.__init__).parameters)
182
+ dropped = sorted(k for k in args_kwargs if k not in supported)
183
+ args = TrainingArguments(**{k: v for k, v in args_kwargs.items() if k in supported})
184
+ collator = DataCollatorForSeq2Seq(tok, model=model, padding=True, label_pad_token_id=-100)
185
+ trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collator, callbacks=[BudgetCallback()])
186
+
187
+ before = trainable_snapshot(model, torch)
188
+ resume = spec.get("resumeFrom")
189
+ result = trainer.train(resume_from_checkpoint=resume if resume else None)
190
+ after = trainable_snapshot(model, torch)
191
+
192
+ history = [
193
+ {"step": int(e["step"]), "loss": float(e["loss"])}
194
+ for e in trainer.state.log_history
195
+ if "loss" in e and "step" in e
196
+ ]
197
+ adapter_dir = os.path.join(out_dir, "adapter")
198
+ model.save_pretrained(adapter_dir)
199
+ tok.save_pretrained(adapter_dir)
200
+ checkpoints = sorted(
201
+ os.path.join(out_dir, d) for d in os.listdir(out_dir) if d.startswith("checkpoint-")
202
+ )
203
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
204
+ metrics = {
205
+ "backend": "hf-peft",
206
+ "mode": peft_info["mode"],
207
+ "resumedFrom": resume or None,
208
+ "steps": int(trainer.state.global_step) - (int(trainer.state.global_step) - len(history) if resume else 0),
209
+ "totalSteps": int(trainer.state.global_step),
210
+ "firstLoss": history[0]["loss"] if history else None,
211
+ "finalLoss": history[-1]["loss"] if history else None,
212
+ "bestLoss": min((h["loss"] for h in history), default=None),
213
+ "trainLossMean": float(result.training_loss) if result and result.training_loss is not None else None,
214
+ "trainableParams": trainable,
215
+ "parameterL2Delta": round(l2_delta(before, after, torch), 8),
216
+ "tokensSeen": int(sum(len(r["input_ids"]) for r in ds)) * max(1, int(trainer.state.global_step) // max(1, len(ds))),
217
+ "wallClockSeconds": round(time.time() - started, 3),
218
+ "peakRssMb": peak_rss_mb(),
219
+ "stepBudget": int(budget.get("maxSteps", 20)),
220
+ "stopReason": stop_state["reason"] or "completed",
221
+ "unsupportedTrainerArgs": dropped,
222
+ }
223
+ emit({
224
+ "op": "train",
225
+ "metrics": metrics,
226
+ "history": history,
227
+ "adapterDir": adapter_dir,
228
+ "checkpoints": checkpoints,
229
+ "limits": spec.get("_appliedLimits"),
230
+ })
231
+
232
+
233
+ def op_evaluate(spec):
234
+ import torch
235
+
236
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
237
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
238
+ model.eval()
239
+ rows = load_rows(spec["examplesFile"])
240
+ if not rows:
241
+ raise ValueError("evaluation needs at least one example")
242
+ max_len = int(spec.get("maxSeqLen", 128))
243
+ total_loss = 0.0
244
+ total_tokens = 0
245
+ started = time.time()
246
+ with torch.no_grad():
247
+ for row in rows:
248
+ enc = encode_row(tok, row, max_len)
249
+ if len(enc["input_ids"]) < 2:
250
+ continue
251
+ ids = torch.tensor([enc["input_ids"]])
252
+ labels = torch.tensor([enc["labels"]])
253
+ out = model(input_ids=ids, labels=labels)
254
+ # Count only supervised positions so the mean is token-weighted.
255
+ counted = int((labels[:, 1:] != -100).sum())
256
+ if counted == 0:
257
+ continue
258
+ total_loss += float(out.loss) * counted
259
+ total_tokens += counted
260
+ if total_tokens == 0:
261
+ raise ValueError("no supervised tokens in evaluation set")
262
+ loss = total_loss / total_tokens
263
+ emit({
264
+ "op": "evaluate",
265
+ "loss": round(loss, 6),
266
+ "perplexity": round(math.exp(min(loss, 50.0)), 6),
267
+ "tokens": total_tokens,
268
+ "examples": len(rows),
269
+ "adapterLoaded": peft_info["adapterLoaded"],
270
+ "wallClockSeconds": round(time.time() - started, 3),
271
+ "peakRssMb": peak_rss_mb(),
272
+ "limits": spec.get("_appliedLimits"),
273
+ })
274
+
275
+
276
+ def op_generate(spec):
277
+ import torch
278
+
279
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
280
+ torch.manual_seed(int(spec.get("seed", 1)))
281
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
282
+ model.eval()
283
+ prompt = spec.get("prompt", "")
284
+ ids = tok(prompt, return_tensors="pt", add_special_tokens=False)
285
+ temperature = float(spec.get("temperature", 0.0))
286
+ started = time.time()
287
+ with torch.no_grad():
288
+ out = model.generate(
289
+ **ids,
290
+ max_new_tokens=int(spec.get("maxNewTokens", 16)),
291
+ do_sample=temperature > 0,
292
+ temperature=temperature if temperature > 0 else None,
293
+ pad_token_id=tok.pad_token_id,
294
+ )
295
+ new_ids = out[0][ids["input_ids"].shape[1]:]
296
+ emit({
297
+ "op": "generate",
298
+ "text": tok.decode(new_ids, skip_special_tokens=True),
299
+ "newTokens": int(new_ids.shape[0]),
300
+ "adapterLoaded": peft_info["adapterLoaded"],
301
+ "wallClockSeconds": round(time.time() - started, 3),
302
+ "peakRssMb": peak_rss_mb(),
303
+ "limits": spec.get("_appliedLimits"),
304
+ })
305
+
306
+
307
+ OPS = {"train": op_train, "evaluate": op_evaluate, "generate": op_generate}
308
+
309
+
310
+ def main():
311
+ if len(sys.argv) < 2:
312
+ print("usage: hf_peft_runner.py <spec.json>", file=sys.stderr)
313
+ return 2
314
+ with open(sys.argv[1], "r", encoding="utf-8") as fh:
315
+ spec = json.load(fh)
316
+ spec["_appliedLimits"] = apply_limits(spec)
317
+ op = spec.get("op")
318
+ if op not in OPS:
319
+ print(f"unknown op: {op}", file=sys.stderr)
320
+ return 2
321
+ OPS[op](spec)
322
+ return 0
323
+
324
+
325
+ if __name__ == "__main__":
326
+ 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.1.0';