taskforce-model-foundry 0.2.0 → 0.3.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/README.md +18 -0
- package/bin/tmf.mjs +53 -1
- package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +1 -1
- package/docs/external-quality.md +59 -0
- package/docs/integration.md +9 -7
- package/docs/releases/v0.3.0.md +28 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +1 -1
- package/integrations/openclaw-plugin/tools.mjs +3 -2
- package/openclaw.plugin.json +3 -1
- package/package.json +1 -1
- package/src/api.mjs +45 -1
- package/src/config.mjs +63 -5
- package/src/data/split.mjs +23 -8
- package/src/eval/evaluator.mjs +14 -3
- package/src/eval/external-quality.mjs +52 -0
- package/src/export/package.mjs +24 -6
- package/src/index.mjs +2 -0
- package/src/integrations/async-evaluate-worker.mjs +1 -0
- package/src/integrations/async-evaluate.mjs +14 -9
- package/src/integrations/async-train-worker.mjs +51 -0
- package/src/integrations/async-train.mjs +135 -0
- package/src/integrations/openclaw.mjs +26 -4
- package/src/jobs/train.mjs +38 -14
- package/src/train/backends/hf-peft.mjs +68 -5
- package/src/train/backends/hf_peft_runner.py +145 -8
- package/src/version.mjs +1 -1
|
@@ -135,8 +135,12 @@ async function writeSpec(spec, { outDir, op }) {
|
|
|
135
135
|
}
|
|
136
136
|
|
|
137
137
|
function limitsFrom(budget = {}, overrides = {}) {
|
|
138
|
+
const envMemory = process.env.TMF_HF_MAX_MEMORY_MB;
|
|
139
|
+
if (envMemory !== undefined && (!Number.isInteger(Number(envMemory)) || Number(envMemory) <= 0)) {
|
|
140
|
+
throw new Error('TMF_HF_MAX_MEMORY_MB must be a positive integer');
|
|
141
|
+
}
|
|
138
142
|
return {
|
|
139
|
-
maxMemoryMb: overrides.maxMemoryMb ?? budget.maxMemoryMb ?? DEFAULT_LIMITS.maxMemoryMb,
|
|
143
|
+
maxMemoryMb: overrides.maxMemoryMb ?? budget.maxMemoryMb ?? (envMemory ? Number(envMemory) : DEFAULT_LIMITS.maxMemoryMb),
|
|
140
144
|
maxCpuSeconds: overrides.maxCpuSeconds ?? budget.maxCpuSeconds ?? null,
|
|
141
145
|
threads: overrides.threads ?? budget.threads ?? DEFAULT_LIMITS.threads,
|
|
142
146
|
maxSeqLen: overrides.maxSeqLen ?? DEFAULT_LIMITS.maxSeqLen,
|
|
@@ -165,7 +169,8 @@ async function runOp(op, spec, { outDir, timeoutMs, signal }) {
|
|
|
165
169
|
`hf-peft ${op} failed (exit ${result.code}${result.signal ? `, signal ${result.signal}` : ''})`
|
|
166
170
|
+ `${memoryBound ? ' due to the configured memory limit' : ''}: ${stderr.slice(-500)}`,
|
|
167
171
|
);
|
|
168
|
-
err.code =
|
|
172
|
+
err.code = /TMF_TRAIN_TOKEN_BUDGET_EXCEEDED/.test(stderr) ? 'BACKEND_TOKEN_BUDGET'
|
|
173
|
+
: memoryBound ? 'BACKEND_MEMORY_LIMIT'
|
|
169
174
|
: result.signal === 'SIGKILL' ? 'BACKEND_RESOURCE_LIMIT'
|
|
170
175
|
: result.timedOut ? 'BACKEND_TIMEOUT' : 'BACKEND_FAILED';
|
|
171
176
|
err.specFile = specFile;
|
|
@@ -233,7 +238,7 @@ const backend = {
|
|
|
233
238
|
// network.
|
|
234
239
|
resourceBounds: ['max-steps', 'max-seconds', 'max-memory-mb', 'max-cpu-seconds', 'threads'],
|
|
235
240
|
isolation: 'process-rlimit',
|
|
236
|
-
precision: 'float32',
|
|
241
|
+
precision: 'float32,bfloat16,nf4',
|
|
237
242
|
requiresLocalModelCache: true,
|
|
238
243
|
},
|
|
239
244
|
|
|
@@ -347,6 +352,7 @@ const backend = {
|
|
|
347
352
|
dir: adapterDir,
|
|
348
353
|
adapterDir,
|
|
349
354
|
mode: adapter.mode ?? 'lora',
|
|
355
|
+
modelConfig: adapter.modelConfig ?? payload.modelConfig ?? {},
|
|
350
356
|
meta: { ...(adapter.meta ?? {}), attachedTo: file },
|
|
351
357
|
file: attachAdapter,
|
|
352
358
|
};
|
|
@@ -358,6 +364,7 @@ const backend = {
|
|
|
358
364
|
dir: payload.dir,
|
|
359
365
|
adapterDir: payload.adapterDir ?? payload.dir ?? null,
|
|
360
366
|
mode: payload.mode ?? 'lora',
|
|
367
|
+
modelConfig: payload.modelConfig ?? {},
|
|
361
368
|
meta: payload.meta ?? {},
|
|
362
369
|
file,
|
|
363
370
|
};
|
|
@@ -398,6 +405,7 @@ const backend = {
|
|
|
398
405
|
dir: handle.dir ?? handle.adapterDir ?? null,
|
|
399
406
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
400
407
|
mode: handle.mode ?? 'lora',
|
|
408
|
+
modelConfig: handle.modelConfig ?? {},
|
|
401
409
|
meta,
|
|
402
410
|
};
|
|
403
411
|
await writeFileAtomic(file, `${JSON.stringify(payload)}\n`);
|
|
@@ -409,12 +417,13 @@ const backend = {
|
|
|
409
417
|
// without running it.
|
|
410
418
|
async renderTrainingScript({ handle, examplesFile, hyper = {}, budget = {}, outDir, mode, resumeFrom = null }) {
|
|
411
419
|
await ensureDir(outDir);
|
|
412
|
-
const limits = limitsFrom(budget, hyper);
|
|
420
|
+
const limits = limitsFrom(budget, { ...hyper, maxSeqLen: handle?.modelConfig?.maxSeqLen ?? hyper.maxSeqLen });
|
|
413
421
|
const spec = {
|
|
414
422
|
op: 'train',
|
|
415
423
|
modelId: handle?.modelId ?? 'MODEL_ID',
|
|
416
424
|
adapterDir: handle?.adapterDir ?? null,
|
|
417
425
|
mode: mode ?? handle?.mode ?? 'lora',
|
|
426
|
+
hf: handle?.modelConfig?.hf ?? {},
|
|
418
427
|
examplesFile,
|
|
419
428
|
outDir,
|
|
420
429
|
resumeFrom,
|
|
@@ -424,6 +433,7 @@ const backend = {
|
|
|
424
433
|
lora: hyper.lora ?? { rank: 8, alpha: 16, targets: ['q_proj', 'v_proj'] },
|
|
425
434
|
budget: {
|
|
426
435
|
maxSteps: budget.maxSteps ?? 20,
|
|
436
|
+
maxTokens: budget.maxTokens ?? null,
|
|
427
437
|
maxSeconds: budget.maxSeconds ?? null,
|
|
428
438
|
checkpointEvery: budget.checkpointEvery ?? 0,
|
|
429
439
|
},
|
|
@@ -517,8 +527,13 @@ const backend = {
|
|
|
517
527
|
modelId: handle.modelId,
|
|
518
528
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
519
529
|
mode: handle.mode ?? 'lora',
|
|
530
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
520
531
|
examplesFile: file,
|
|
521
|
-
...limitsFrom(budget,
|
|
532
|
+
...limitsFrom(budget, {
|
|
533
|
+
...hyper,
|
|
534
|
+
maxMemoryMb: handle.modelConfig?.hf?.maxMemoryMb ?? hyper.maxMemoryMb,
|
|
535
|
+
maxSeqLen: handle.modelConfig?.maxSeqLen ?? hyper.maxSeqLen,
|
|
536
|
+
}),
|
|
522
537
|
};
|
|
523
538
|
const { payload } = await runOp('evaluate', spec, {
|
|
524
539
|
outDir: dir, timeoutMs: ((budget.maxSeconds ?? 600) + 120) * 1000, signal,
|
|
@@ -535,6 +550,52 @@ const backend = {
|
|
|
535
550
|
};
|
|
536
551
|
},
|
|
537
552
|
|
|
553
|
+
// One offline model load scores both loss splits and generates the holdout
|
|
554
|
+
// continuations. The evaluator keeps the same exact-match diagnostics and
|
|
555
|
+
// gate logic; only the redundant Python/model startups are removed.
|
|
556
|
+
async evaluateSplitSet({
|
|
557
|
+
handle, holdoutExamples, validationExamples = [], prompts = [], maxNewTokens = 48,
|
|
558
|
+
budget = {}, signal = null, outDir,
|
|
559
|
+
} = {}) {
|
|
560
|
+
const probe = await backend.probe();
|
|
561
|
+
if (!probe.available) throw unavailable('evaluate split set', probe);
|
|
562
|
+
if (!handle?.modelId || !Array.isArray(holdoutExamples) || !holdoutExamples.length) {
|
|
563
|
+
throw new Error('hf-peft evaluateSplitSet needs a model and non-empty holdout examples');
|
|
564
|
+
}
|
|
565
|
+
const dir = outDir ?? path.join(process.cwd(), '.tmf-run', 'hf-peft-eval-bundle');
|
|
566
|
+
await ensureDir(dir);
|
|
567
|
+
const holdoutFile = path.join(dir, 'holdout-examples.jsonl');
|
|
568
|
+
const validationFile = path.join(dir, 'validation-examples.jsonl');
|
|
569
|
+
const promptsFile = path.join(dir, 'prompts.jsonl');
|
|
570
|
+
await writeFileAtomic(holdoutFile, `${holdoutExamples.map((e) => JSON.stringify(e)).join('\n')}\n`);
|
|
571
|
+
await writeFileAtomic(validationFile, `${validationExamples.map((e) => JSON.stringify(e)).join('\n')}${validationExamples.length ? '\n' : ''}`);
|
|
572
|
+
await writeFileAtomic(promptsFile, `${prompts.map((prompt) => JSON.stringify({ prompt })).join('\n')}${prompts.length ? '\n' : ''}`);
|
|
573
|
+
const hf = handle.modelConfig?.hf ?? {};
|
|
574
|
+
const spec = {
|
|
575
|
+
modelId: handle.modelId, adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
576
|
+
mode: handle.mode ?? 'lora', hf, holdoutFile, validationFile, promptsFile, maxNewTokens,
|
|
577
|
+
...limitsFrom(budget, {
|
|
578
|
+
maxMemoryMb: hf.maxMemoryMb,
|
|
579
|
+
maxSeqLen: handle.modelConfig?.maxSeqLen,
|
|
580
|
+
}),
|
|
581
|
+
};
|
|
582
|
+
const maxSeconds = budget.maxSeconds ?? hf.evalMaxSeconds ?? 1800;
|
|
583
|
+
const { payload } = await runOp('evaluate_bundle', spec, {
|
|
584
|
+
outDir: dir, timeoutMs: (maxSeconds + 120) * 1000, signal,
|
|
585
|
+
});
|
|
586
|
+
if (!Array.isArray(payload.texts) || payload.texts.length !== prompts.length) {
|
|
587
|
+
throw new Error(`hf-peft evaluate_bundle returned ${payload.texts?.length ?? 'invalid'} predictions for ${prompts.length} prompts`);
|
|
588
|
+
}
|
|
589
|
+
const metrics = (part) => part && ({
|
|
590
|
+
loss: part.loss, perplexity: part.perplexity, tokens: part.tokens,
|
|
591
|
+
examples: part.examples, adapterLoaded: payload.adapterLoaded,
|
|
592
|
+
device: payload.device, backend: backend.id, limits: payload.limits,
|
|
593
|
+
wallClockSeconds: payload.wallClockSeconds, peakRssMb: payload.peakRssMb,
|
|
594
|
+
peakCudaAllocatedMb: payload.peakCudaAllocatedMb,
|
|
595
|
+
});
|
|
596
|
+
return { holdout: metrics(payload.holdout), validation: metrics(payload.validation), texts: payload.texts };
|
|
597
|
+
},
|
|
598
|
+
|
|
538
599
|
async generate({
|
|
539
600
|
handle, prompt, maxNewTokens = 16, temperature = 0, seed = 1,
|
|
540
601
|
hyper = {}, budget = {}, signal = null, outDir,
|
|
@@ -547,6 +608,7 @@ const backend = {
|
|
|
547
608
|
modelId: handle.modelId,
|
|
548
609
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
549
610
|
mode: handle.mode ?? 'lora',
|
|
611
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
550
612
|
prompt: prompt ?? '',
|
|
551
613
|
maxNewTokens,
|
|
552
614
|
temperature,
|
|
@@ -578,6 +640,7 @@ const backend = {
|
|
|
578
640
|
modelId: handle.modelId,
|
|
579
641
|
adapterDir: handle.adapterDir ?? handle.dir ?? null,
|
|
580
642
|
mode: handle.mode ?? 'lora',
|
|
643
|
+
hf: handle.modelConfig?.hf ?? {},
|
|
581
644
|
promptsFile,
|
|
582
645
|
maxNewTokens,
|
|
583
646
|
temperature,
|
|
@@ -98,10 +98,32 @@ def build_model(spec, torch, want_training):
|
|
|
98
98
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
99
99
|
|
|
100
100
|
model_id = spec["modelId"]
|
|
101
|
+
hf = spec.get("hf") or {}
|
|
101
102
|
tok = AutoTokenizer.from_pretrained(model_id, local_files_only=True)
|
|
102
103
|
if tok.pad_token is None:
|
|
103
104
|
tok.pad_token = tok.eos_token or tok.unk_token
|
|
104
|
-
|
|
105
|
+
load_kwargs = {"local_files_only": True}
|
|
106
|
+
if hf.get("loadIn4Bit"):
|
|
107
|
+
from transformers import BitsAndBytesConfig
|
|
108
|
+
|
|
109
|
+
if os.environ.get("TMF_DEVICE", "cpu") != "cuda":
|
|
110
|
+
raise ValueError("4-bit model execution requires TMF_DEVICE=cuda")
|
|
111
|
+
load_kwargs["quantization_config"] = BitsAndBytesConfig(
|
|
112
|
+
load_in_4bit=True,
|
|
113
|
+
bnb_4bit_quant_type=hf.get("quantType", "nf4"),
|
|
114
|
+
bnb_4bit_use_double_quant=bool(hf.get("doubleQuant", True)),
|
|
115
|
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
|
116
|
+
)
|
|
117
|
+
load_kwargs["device_map"] = {"": 0}
|
|
118
|
+
if hf.get("dtype") == "bfloat16":
|
|
119
|
+
load_kwargs["dtype"] = torch.bfloat16
|
|
120
|
+
model = AutoModelForCausalLM.from_pretrained(model_id, **load_kwargs)
|
|
121
|
+
if want_training and hf.get("loadIn4Bit"):
|
|
122
|
+
from peft import prepare_model_for_kbit_training
|
|
123
|
+
|
|
124
|
+
model = prepare_model_for_kbit_training(
|
|
125
|
+
model, use_gradient_checkpointing=bool(hf.get("gradientCheckpointing", False))
|
|
126
|
+
)
|
|
105
127
|
adapter = spec.get("adapterDir")
|
|
106
128
|
mode = spec.get("mode", "lora")
|
|
107
129
|
peft_info = {"mode": mode, "adapterLoaded": False}
|
|
@@ -125,9 +147,27 @@ def build_model(spec, torch, want_training):
|
|
|
125
147
|
),
|
|
126
148
|
)
|
|
127
149
|
model.config.use_cache = False if want_training else True
|
|
150
|
+
if hasattr(model.config, "text_config"):
|
|
151
|
+
model.config.text_config.use_cache = not want_training
|
|
128
152
|
return tok, model, peft_info
|
|
129
153
|
|
|
130
154
|
|
|
155
|
+
def place_model(model, device, spec):
|
|
156
|
+
# transformers/bitsandbytes dispatches 4-bit modules during loading and
|
|
157
|
+
# deliberately rejects a later .to() on quantized modules.
|
|
158
|
+
if not (spec.get("hf") or {}).get("loadIn4Bit"):
|
|
159
|
+
model.to(device)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def model_inputs(model, ids):
|
|
163
|
+
import torch
|
|
164
|
+
|
|
165
|
+
inputs = {"input_ids": ids}
|
|
166
|
+
if getattr(model.config, "model_type", None) == "gemma4":
|
|
167
|
+
inputs["mm_token_type_ids"] = torch.zeros_like(ids)
|
|
168
|
+
return inputs
|
|
169
|
+
|
|
170
|
+
|
|
131
171
|
def trainable_snapshot(model, torch):
|
|
132
172
|
return {n: p.detach().clone() for n, p in model.named_parameters() if p.requires_grad}
|
|
133
173
|
|
|
@@ -151,6 +191,7 @@ def op_train(spec):
|
|
|
151
191
|
)
|
|
152
192
|
|
|
153
193
|
device = selected_device(torch)
|
|
194
|
+
hf = spec.get("hf") or {}
|
|
154
195
|
torch.set_num_threads(int(spec.get("threads", 1) or 1))
|
|
155
196
|
torch.manual_seed(int(spec.get("seed", 1)))
|
|
156
197
|
started = time.time()
|
|
@@ -190,6 +231,16 @@ def op_train(spec):
|
|
|
190
231
|
dataloader_num_workers=0,
|
|
191
232
|
disable_tqdm=True,
|
|
192
233
|
)
|
|
234
|
+
if hf:
|
|
235
|
+
args_kwargs.update(
|
|
236
|
+
bf16=hf.get("dtype") == "bfloat16" and device.type == "cuda",
|
|
237
|
+
gradient_checkpointing=bool(hf.get("gradientCheckpointing", False)),
|
|
238
|
+
gradient_accumulation_steps=int(hf.get("gradientAccumulationSteps", 1)),
|
|
239
|
+
lr_scheduler_type=hf.get("lrScheduler", "linear"),
|
|
240
|
+
warmup_steps=int(hf.get("warmupSteps", 0)),
|
|
241
|
+
optim=hf.get("optimizer", "adamw_torch"),
|
|
242
|
+
max_grad_norm=float(hf.get("maxGradNorm", 1.0)),
|
|
243
|
+
)
|
|
193
244
|
if save_steps > 0:
|
|
194
245
|
args_kwargs["save_steps"] = save_steps
|
|
195
246
|
# TrainingArguments gains and drops keyword arguments between transformers
|
|
@@ -201,7 +252,19 @@ def op_train(spec):
|
|
|
201
252
|
supported = set(inspect.signature(TrainingArguments.__init__).parameters)
|
|
202
253
|
dropped = sorted(k for k in args_kwargs if k not in supported)
|
|
203
254
|
args = TrainingArguments(**{k: v for k, v in args_kwargs.items() if k in supported})
|
|
204
|
-
|
|
255
|
+
base_collator = DataCollatorForSeq2Seq(tok, model=model, padding=True, label_pad_token_id=-100)
|
|
256
|
+
token_counts = {"input": 0, "supervised": 0}
|
|
257
|
+
|
|
258
|
+
def collator(features):
|
|
259
|
+
batch = base_collator(features)
|
|
260
|
+
batch_tokens = int(batch["attention_mask"].sum())
|
|
261
|
+
if budget.get("maxTokens") is not None and token_counts["input"] + batch_tokens > int(budget["maxTokens"]):
|
|
262
|
+
raise RuntimeError("TMF_TRAIN_TOKEN_BUDGET_EXCEEDED: next batch would exceed maxTokens")
|
|
263
|
+
token_counts["input"] += batch_tokens
|
|
264
|
+
token_counts["supervised"] += int((batch["labels"] != -100).sum())
|
|
265
|
+
if getattr(model.config, "model_type", None) == "gemma4":
|
|
266
|
+
batch["mm_token_type_ids"] = torch.zeros_like(batch["input_ids"])
|
|
267
|
+
return batch
|
|
205
268
|
trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collator, callbacks=[BudgetCallback()])
|
|
206
269
|
|
|
207
270
|
before = trainable_snapshot(model, torch)
|
|
@@ -235,7 +298,11 @@ def op_train(spec):
|
|
|
235
298
|
"trainLossMean": float(result.training_loss) if result and result.training_loss is not None else None,
|
|
236
299
|
"trainableParams": trainable,
|
|
237
300
|
"parameterL2Delta": round(l2_delta(before, after, torch), 8),
|
|
238
|
-
|
|
301
|
+
# The collator runs on each batch actually handed to Trainer, so this
|
|
302
|
+
# is an attempt-level input-token count rather than whole-dataset size.
|
|
303
|
+
"tokensSeen": token_counts["input"],
|
|
304
|
+
"supervisedTokensSeen": token_counts["supervised"],
|
|
305
|
+
"datasetTokens": int(sum(len(r["input_ids"]) for r in ds)),
|
|
239
306
|
"wallClockSeconds": round(time.time() - started, 3),
|
|
240
307
|
"peakRssMb": peak_rss_mb(),
|
|
241
308
|
"stepBudget": int(budget.get("maxSteps", 20)),
|
|
@@ -258,7 +325,7 @@ def op_evaluate(spec):
|
|
|
258
325
|
device = selected_device(torch)
|
|
259
326
|
torch.set_num_threads(int(spec.get("threads", 1) or 1))
|
|
260
327
|
tok, model, peft_info = build_model(spec, torch, want_training=False)
|
|
261
|
-
model
|
|
328
|
+
place_model(model, device, spec)
|
|
262
329
|
model.eval()
|
|
263
330
|
rows = load_rows(spec["examplesFile"])
|
|
264
331
|
if not rows:
|
|
@@ -274,7 +341,7 @@ def op_evaluate(spec):
|
|
|
274
341
|
continue
|
|
275
342
|
ids = torch.tensor([enc["input_ids"]], device=device)
|
|
276
343
|
labels = torch.tensor([enc["labels"]], device=device)
|
|
277
|
-
out = model(
|
|
344
|
+
out = model(**model_inputs(model, ids), labels=labels)
|
|
278
345
|
# Count only supervised positions so the mean is token-weighted.
|
|
279
346
|
counted = int((labels[:, 1:] != -100).sum())
|
|
280
347
|
if counted == 0:
|
|
@@ -298,6 +365,71 @@ def op_evaluate(spec):
|
|
|
298
365
|
})
|
|
299
366
|
|
|
300
367
|
|
|
368
|
+
def op_evaluate_bundle(spec):
|
|
369
|
+
"""Score holdout, generate, then score validation with one model load."""
|
|
370
|
+
import torch
|
|
371
|
+
|
|
372
|
+
started = time.time()
|
|
373
|
+
device = selected_device(torch)
|
|
374
|
+
torch.set_num_threads(int(spec.get("threads", 1) or 1))
|
|
375
|
+
tok, model, peft_info = build_model(spec, torch, want_training=False)
|
|
376
|
+
place_model(model, device, spec)
|
|
377
|
+
model.eval()
|
|
378
|
+
max_len = int(spec.get("maxSeqLen", 128))
|
|
379
|
+
def score(path, required):
|
|
380
|
+
rows = load_rows(path)
|
|
381
|
+
if required and not rows:
|
|
382
|
+
raise ValueError("evaluation needs at least one holdout example")
|
|
383
|
+
if not rows:
|
|
384
|
+
return None
|
|
385
|
+
total_loss = 0.0
|
|
386
|
+
total_tokens = 0
|
|
387
|
+
with torch.no_grad():
|
|
388
|
+
for row in rows:
|
|
389
|
+
enc = encode_row(tok, row, max_len)
|
|
390
|
+
if len(enc["input_ids"]) < 2:
|
|
391
|
+
continue
|
|
392
|
+
ids = torch.tensor([enc["input_ids"]], device=device)
|
|
393
|
+
labels = torch.tensor([enc["labels"]], device=device)
|
|
394
|
+
out = model(**model_inputs(model, ids), labels=labels)
|
|
395
|
+
counted = int((labels[:, 1:] != -100).sum())
|
|
396
|
+
if counted == 0:
|
|
397
|
+
continue
|
|
398
|
+
total_loss += float(out.loss) * counted
|
|
399
|
+
total_tokens += counted
|
|
400
|
+
if total_tokens == 0:
|
|
401
|
+
raise ValueError("no supervised tokens in evaluation split")
|
|
402
|
+
loss = total_loss / total_tokens
|
|
403
|
+
return {"loss": round(loss, 6), "perplexity": round(math.exp(min(loss, 50.0)), 6),
|
|
404
|
+
"tokens": total_tokens, "examples": len(rows)}
|
|
405
|
+
|
|
406
|
+
holdout = score(spec["holdoutFile"], True)
|
|
407
|
+
prompts = load_rows(spec["promptsFile"])
|
|
408
|
+
if any(not isinstance(row.get("prompt"), str) for row in prompts):
|
|
409
|
+
raise ValueError("evaluate_bundle prompts must be strings")
|
|
410
|
+
texts = []
|
|
411
|
+
with torch.no_grad():
|
|
412
|
+
for row in prompts:
|
|
413
|
+
torch.manual_seed(int(spec.get("seed", 1)))
|
|
414
|
+
ids = tok(row["prompt"], return_tensors="pt", add_special_tokens=False).to(device)
|
|
415
|
+
if getattr(model.config, "model_type", None) == "gemma4":
|
|
416
|
+
ids["mm_token_type_ids"] = torch.zeros_like(ids["input_ids"])
|
|
417
|
+
out = model.generate(
|
|
418
|
+
**ids, max_new_tokens=int(spec.get("maxNewTokens", 16)),
|
|
419
|
+
do_sample=False, temperature=None, pad_token_id=tok.pad_token_id,
|
|
420
|
+
)
|
|
421
|
+
new_ids = out[0][ids["input_ids"].shape[1]:]
|
|
422
|
+
texts.append(tok.decode(new_ids, skip_special_tokens=True))
|
|
423
|
+
validation = score(spec["validationFile"], False)
|
|
424
|
+
emit({
|
|
425
|
+
"op": "evaluate_bundle", "holdout": holdout, "validation": validation,
|
|
426
|
+
"texts": texts, "adapterLoaded": peft_info["adapterLoaded"], "device": device.type,
|
|
427
|
+
"wallClockSeconds": round(time.time() - started, 3), "peakRssMb": peak_rss_mb(),
|
|
428
|
+
"peakCudaAllocatedMb": round(torch.cuda.max_memory_allocated() / 1048576, 3) if device.type == "cuda" else None,
|
|
429
|
+
"limits": spec.get("_appliedLimits"),
|
|
430
|
+
})
|
|
431
|
+
|
|
432
|
+
|
|
301
433
|
def op_generate(spec):
|
|
302
434
|
import torch
|
|
303
435
|
|
|
@@ -305,10 +437,12 @@ def op_generate(spec):
|
|
|
305
437
|
torch.set_num_threads(int(spec.get("threads", 1) or 1))
|
|
306
438
|
torch.manual_seed(int(spec.get("seed", 1)))
|
|
307
439
|
tok, model, peft_info = build_model(spec, torch, want_training=False)
|
|
308
|
-
model
|
|
440
|
+
place_model(model, device, spec)
|
|
309
441
|
model.eval()
|
|
310
442
|
prompt = spec.get("prompt", "")
|
|
311
443
|
ids = tok(prompt, return_tensors="pt", add_special_tokens=False).to(device)
|
|
444
|
+
if getattr(model.config, "model_type", None) == "gemma4":
|
|
445
|
+
ids["mm_token_type_ids"] = torch.zeros_like(ids["input_ids"])
|
|
312
446
|
temperature = float(spec.get("temperature", 0.0))
|
|
313
447
|
started = time.time()
|
|
314
448
|
with torch.no_grad():
|
|
@@ -338,7 +472,7 @@ def op_generate_batch(spec):
|
|
|
338
472
|
device = selected_device(torch)
|
|
339
473
|
torch.set_num_threads(int(spec.get("threads", 1) or 1))
|
|
340
474
|
tok, model, peft_info = build_model(spec, torch, want_training=False)
|
|
341
|
-
model
|
|
475
|
+
place_model(model, device, spec)
|
|
342
476
|
model.eval()
|
|
343
477
|
rows = load_rows(spec["promptsFile"])
|
|
344
478
|
if not rows or any(not isinstance(row.get("prompt"), str) for row in rows):
|
|
@@ -353,6 +487,8 @@ def op_generate_batch(spec):
|
|
|
353
487
|
# behavior for sampled generation as well as greedy decoding.
|
|
354
488
|
torch.manual_seed(int(spec.get("seed", 1)))
|
|
355
489
|
ids = tok(row["prompt"], return_tensors="pt", add_special_tokens=False).to(device)
|
|
490
|
+
if getattr(model.config, "model_type", None) == "gemma4":
|
|
491
|
+
ids["mm_token_type_ids"] = torch.zeros_like(ids["input_ids"])
|
|
356
492
|
out = model.generate(
|
|
357
493
|
**ids,
|
|
358
494
|
max_new_tokens=max_new_tokens,
|
|
@@ -375,7 +511,8 @@ def op_generate_batch(spec):
|
|
|
375
511
|
})
|
|
376
512
|
|
|
377
513
|
|
|
378
|
-
OPS = {"train": op_train, "evaluate": op_evaluate, "
|
|
514
|
+
OPS = {"train": op_train, "evaluate": op_evaluate, "evaluate_bundle": op_evaluate_bundle,
|
|
515
|
+
"generate": op_generate, "generate_batch": op_generate_batch}
|
|
379
516
|
|
|
380
517
|
|
|
381
518
|
def main():
|
package/src/version.mjs
CHANGED