taskforce-model-foundry 0.1.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.
@@ -57,6 +57,20 @@ def peak_rss_mb():
57
57
  return round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, 3)
58
58
 
59
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
+
60
74
  def load_rows(path):
61
75
  rows = []
62
76
  with open(path, "r", encoding="utf-8") as fh:
@@ -70,6 +84,11 @@ def load_rows(path):
70
84
  def encode_row(tok, row, max_len):
71
85
  prompt_ids = tok(row["prompt"], add_special_tokens=False)["input_ids"]
72
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)
73
92
  full_ids = full_ids[:max_len]
74
93
  labels = [-100] * min(len(prompt_ids), len(full_ids)) + full_ids[min(len(prompt_ids), len(full_ids)):]
75
94
  return {"input_ids": full_ids, "labels": labels, "attention_mask": [1] * len(full_ids)}
@@ -79,10 +98,32 @@ def build_model(spec, torch, want_training):
79
98
  from transformers import AutoModelForCausalLM, AutoTokenizer
80
99
 
81
100
  model_id = spec["modelId"]
101
+ hf = spec.get("hf") or {}
82
102
  tok = AutoTokenizer.from_pretrained(model_id, local_files_only=True)
83
103
  if tok.pad_token is None:
84
104
  tok.pad_token = tok.eos_token or tok.unk_token
85
- model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)
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
+ )
86
127
  adapter = spec.get("adapterDir")
87
128
  mode = spec.get("mode", "lora")
88
129
  peft_info = {"mode": mode, "adapterLoaded": False}
@@ -106,9 +147,27 @@ def build_model(spec, torch, want_training):
106
147
  ),
107
148
  )
108
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
109
152
  return tok, model, peft_info
110
153
 
111
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
+
112
171
  def trainable_snapshot(model, torch):
113
172
  return {n: p.detach().clone() for n, p in model.named_parameters() if p.requires_grad}
114
173
 
@@ -131,6 +190,8 @@ def op_train(spec):
131
190
  TrainingArguments,
132
191
  )
133
192
 
193
+ device = selected_device(torch)
194
+ hf = spec.get("hf") or {}
134
195
  torch.set_num_threads(int(spec.get("threads", 1) or 1))
135
196
  torch.manual_seed(int(spec.get("seed", 1)))
136
197
  started = time.time()
@@ -166,10 +227,20 @@ def op_train(spec):
166
227
  report_to=[],
167
228
  save_strategy="steps" if save_steps > 0 else "no",
168
229
  seed=int(spec.get("seed", 1)),
169
- use_cpu=True,
230
+ use_cpu=device.type == "cpu",
170
231
  dataloader_num_workers=0,
171
232
  disable_tqdm=True,
172
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
+ )
173
244
  if save_steps > 0:
174
245
  args_kwargs["save_steps"] = save_steps
175
246
  # TrainingArguments gains and drops keyword arguments between transformers
@@ -181,7 +252,19 @@ def op_train(spec):
181
252
  supported = set(inspect.signature(TrainingArguments.__init__).parameters)
182
253
  dropped = sorted(k for k in args_kwargs if k not in supported)
183
254
  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)
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
185
268
  trainer = Trainer(model=model, args=args, train_dataset=ds, data_collator=collator, callbacks=[BudgetCallback()])
186
269
 
187
270
  before = trainable_snapshot(model, torch)
@@ -203,6 +286,8 @@ def op_train(spec):
203
286
  trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
204
287
  metrics = {
205
288
  "backend": "hf-peft",
289
+ "device": device.type,
290
+ "peakCudaAllocatedMb": round(torch.cuda.max_memory_allocated() / 1048576, 3) if device.type == "cuda" else None,
206
291
  "mode": peft_info["mode"],
207
292
  "resumedFrom": resume or None,
208
293
  "steps": int(trainer.state.global_step) - (int(trainer.state.global_step) - len(history) if resume else 0),
@@ -213,7 +298,11 @@ def op_train(spec):
213
298
  "trainLossMean": float(result.training_loss) if result and result.training_loss is not None else None,
214
299
  "trainableParams": trainable,
215
300
  "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))),
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)),
217
306
  "wallClockSeconds": round(time.time() - started, 3),
218
307
  "peakRssMb": peak_rss_mb(),
219
308
  "stepBudget": int(budget.get("maxSteps", 20)),
@@ -233,8 +322,10 @@ def op_train(spec):
233
322
  def op_evaluate(spec):
234
323
  import torch
235
324
 
325
+ device = selected_device(torch)
236
326
  torch.set_num_threads(int(spec.get("threads", 1) or 1))
237
327
  tok, model, peft_info = build_model(spec, torch, want_training=False)
328
+ place_model(model, device, spec)
238
329
  model.eval()
239
330
  rows = load_rows(spec["examplesFile"])
240
331
  if not rows:
@@ -248,9 +339,9 @@ def op_evaluate(spec):
248
339
  enc = encode_row(tok, row, max_len)
249
340
  if len(enc["input_ids"]) < 2:
250
341
  continue
251
- ids = torch.tensor([enc["input_ids"]])
252
- labels = torch.tensor([enc["labels"]])
253
- out = model(input_ids=ids, labels=labels)
342
+ ids = torch.tensor([enc["input_ids"]], device=device)
343
+ labels = torch.tensor([enc["labels"]], device=device)
344
+ out = model(**model_inputs(model, ids), labels=labels)
254
345
  # Count only supervised positions so the mean is token-weighted.
255
346
  counted = int((labels[:, 1:] != -100).sum())
256
347
  if counted == 0:
@@ -267,21 +358,91 @@ def op_evaluate(spec):
267
358
  "tokens": total_tokens,
268
359
  "examples": len(rows),
269
360
  "adapterLoaded": peft_info["adapterLoaded"],
361
+ "device": device.type,
270
362
  "wallClockSeconds": round(time.time() - started, 3),
271
363
  "peakRssMb": peak_rss_mb(),
272
364
  "limits": spec.get("_appliedLimits"),
273
365
  })
274
366
 
275
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
+
276
433
  def op_generate(spec):
277
434
  import torch
278
435
 
436
+ device = selected_device(torch)
279
437
  torch.set_num_threads(int(spec.get("threads", 1) or 1))
280
438
  torch.manual_seed(int(spec.get("seed", 1)))
281
439
  tok, model, peft_info = build_model(spec, torch, want_training=False)
440
+ place_model(model, device, spec)
282
441
  model.eval()
283
442
  prompt = spec.get("prompt", "")
284
- ids = tok(prompt, return_tensors="pt", add_special_tokens=False)
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"])
285
446
  temperature = float(spec.get("temperature", 0.0))
286
447
  started = time.time()
287
448
  with torch.no_grad():
@@ -298,13 +459,60 @@ def op_generate(spec):
298
459
  "text": tok.decode(new_ids, skip_special_tokens=True),
299
460
  "newTokens": int(new_ids.shape[0]),
300
461
  "adapterLoaded": peft_info["adapterLoaded"],
462
+ "device": device.type,
463
+ "wallClockSeconds": round(time.time() - started, 3),
464
+ "peakRssMb": peak_rss_mb(),
465
+ "limits": spec.get("_appliedLimits"),
466
+ })
467
+
468
+
469
+ def op_generate_batch(spec):
470
+ import torch
471
+
472
+ device = selected_device(torch)
473
+ torch.set_num_threads(int(spec.get("threads", 1) or 1))
474
+ tok, model, peft_info = build_model(spec, torch, want_training=False)
475
+ place_model(model, device, spec)
476
+ model.eval()
477
+ rows = load_rows(spec["promptsFile"])
478
+ if not rows or any(not isinstance(row.get("prompt"), str) for row in rows):
479
+ raise ValueError("generate_batch needs non-empty prompt records")
480
+ temperature = float(spec.get("temperature", 0.0))
481
+ max_new_tokens = int(spec.get("maxNewTokens", 16))
482
+ texts = []
483
+ started = time.time()
484
+ with torch.no_grad():
485
+ for row in rows:
486
+ # A single-prompt subprocess reseeds on every call. Preserve that
487
+ # behavior for sampled generation as well as greedy decoding.
488
+ torch.manual_seed(int(spec.get("seed", 1)))
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"])
492
+ out = model.generate(
493
+ **ids,
494
+ max_new_tokens=max_new_tokens,
495
+ do_sample=temperature > 0,
496
+ temperature=temperature if temperature > 0 else None,
497
+ pad_token_id=tok.pad_token_id,
498
+ )
499
+ new_ids = out[0][ids["input_ids"].shape[1]:]
500
+ texts.append(tok.decode(new_ids, skip_special_tokens=True))
501
+ emit({
502
+ "op": "generate_batch",
503
+ "texts": texts,
504
+ "count": len(texts),
505
+ "adapterLoaded": peft_info["adapterLoaded"],
506
+ "device": device.type,
301
507
  "wallClockSeconds": round(time.time() - started, 3),
302
508
  "peakRssMb": peak_rss_mb(),
509
+ "peakCudaAllocatedMb": round(torch.cuda.max_memory_allocated() / 1048576, 3) if device.type == "cuda" else None,
303
510
  "limits": spec.get("_appliedLimits"),
304
511
  })
305
512
 
306
513
 
307
- OPS = {"train": op_train, "evaluate": op_evaluate, "generate": op_generate}
514
+ OPS = {"train": op_train, "evaluate": op_evaluate, "evaluate_bundle": op_evaluate_bundle,
515
+ "generate": op_generate, "generate_batch": op_generate_batch}
308
516
 
309
517
 
310
518
  def main():
package/src/version.mjs CHANGED
@@ -2,4 +2,4 @@
2
2
  //
3
3
  // It lives in its own module so api.mjs can stamp exports with it without
4
4
  // importing the package entry point (which imports api.mjs in turn).
5
- export const VERSION = '0.1.0';
5
+ export const VERSION = '0.3.0';