bitstraining 0.1.0__py3-none-any.whl

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 (71) hide show
  1. bitstraining/__init__.py +28 -0
  2. bitstraining/autotune/__init__.py +7 -0
  3. bitstraining/autotune/cache.py +39 -0
  4. bitstraining/autotune/microbatch.py +42 -0
  5. bitstraining/autotune/tuner.py +134 -0
  6. bitstraining/compute/__init__.py +23 -0
  7. bitstraining/compute/base.py +104 -0
  8. bitstraining/compute/bundle.py +64 -0
  9. bitstraining/compute/catalog.py +86 -0
  10. bitstraining/compute/docker.py +107 -0
  11. bitstraining/compute/local.py +121 -0
  12. bitstraining/compute/notebook.py +132 -0
  13. bitstraining/compute/orchestrator.py +126 -0
  14. bitstraining/compute/ssh.py +157 -0
  15. bitstraining/core/__init__.py +1 -0
  16. bitstraining/core/config.py +85 -0
  17. bitstraining/core/errors.py +43 -0
  18. bitstraining/core/paths.py +28 -0
  19. bitstraining/core/registry.py +87 -0
  20. bitstraining/core/schemas.py +358 -0
  21. bitstraining/data/__init__.py +25 -0
  22. bitstraining/data/clean.py +147 -0
  23. bitstraining/data/loaders.py +135 -0
  24. bitstraining/data/pack.py +100 -0
  25. bitstraining/data/schema.py +123 -0
  26. bitstraining/data/split.py +42 -0
  27. bitstraining/data/stats.py +143 -0
  28. bitstraining/deploy/__init__.py +6 -0
  29. bitstraining/deploy/modelcard.py +41 -0
  30. bitstraining/deploy/serve.py +21 -0
  31. bitstraining/engines/__init__.py +19 -0
  32. bitstraining/engines/base.py +120 -0
  33. bitstraining/engines/deepspeed.py +44 -0
  34. bitstraining/engines/hf_peft.py +325 -0
  35. bitstraining/engines/mlx.py +100 -0
  36. bitstraining/engines/simulate.py +138 -0
  37. bitstraining/engines/unsloth.py +66 -0
  38. bitstraining/eval/__init__.py +17 -0
  39. bitstraining/eval/audit.py +63 -0
  40. bitstraining/eval/gate.py +69 -0
  41. bitstraining/eval/generate.py +51 -0
  42. bitstraining/eval/metrics.py +48 -0
  43. bitstraining/hardware/__init__.py +6 -0
  44. bitstraining/hardware/database.py +125 -0
  45. bitstraining/hardware/profiler.py +243 -0
  46. bitstraining/interfaces/__init__.py +1 -0
  47. bitstraining/interfaces/api.py +266 -0
  48. bitstraining/interfaces/cli.py +496 -0
  49. bitstraining/models/__init__.py +10 -0
  50. bitstraining/models/introspect.py +228 -0
  51. bitstraining/optimize/__init__.py +6 -0
  52. bitstraining/optimize/merge.py +26 -0
  53. bitstraining/optimize/quantize.py +37 -0
  54. bitstraining/planner/__init__.py +15 -0
  55. bitstraining/planner/calibration.py +62 -0
  56. bitstraining/planner/doctor.py +215 -0
  57. bitstraining/planner/memory.py +126 -0
  58. bitstraining/planner/search.py +368 -0
  59. bitstraining/planner/throughput.py +154 -0
  60. bitstraining/py.typed +0 -0
  61. bitstraining/runner.py +71 -0
  62. bitstraining/strategies/__init__.py +10 -0
  63. bitstraining/strategies/catalog.py +42 -0
  64. bitstraining/tracking/__init__.py +5 -0
  65. bitstraining/tracking/registry.py +208 -0
  66. bitstraining-0.1.0.dist-info/METADATA +228 -0
  67. bitstraining-0.1.0.dist-info/RECORD +71 -0
  68. bitstraining-0.1.0.dist-info/WHEEL +5 -0
  69. bitstraining-0.1.0.dist-info/entry_points.txt +17 -0
  70. bitstraining-0.1.0.dist-info/licenses/LICENSE +177 -0
  71. bitstraining-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,120 @@
1
+ """The Engine interface every training backend implements.
2
+
3
+ Core code depends only on this interface, never on torch/transformers/mlx. An engine reports
4
+ what it can do on given hardware (`capabilities`), can verify a plan with a short real run
5
+ (`probe`), and can execute it (`train`). Engines are discovered through the plugin registry.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import abc
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from bitstraining.core import registry
17
+ from bitstraining.core.schemas import (
18
+ Capabilities,
19
+ DatasetStats,
20
+ ExecutionPlan,
21
+ HardwareProfile,
22
+ ModelInfo,
23
+ RunSpec,
24
+ Serializable,
25
+ )
26
+
27
+
28
+ @dataclass
29
+ class ProbeContext:
30
+ """Everything a probe needs to size a realistic batch."""
31
+
32
+ spec: RunSpec
33
+ model: ModelInfo
34
+ hw: HardwareProfile
35
+ stats: DatasetStats
36
+ seq_len: int
37
+
38
+
39
+ @dataclass
40
+ class ProbeResult(Serializable):
41
+ fits: bool = True
42
+ peak_gb: float | None = None
43
+ tokens_per_s: float | None = None
44
+ steps: int = 0
45
+ note: str = ""
46
+
47
+
48
+ @dataclass
49
+ class RunResult(Serializable):
50
+ status: str = "completed" # completed | stopped | failed
51
+ steps: int = 0
52
+ final_loss: float | None = None
53
+ eval_loss: float | None = None
54
+ seconds: float = 0.0
55
+ peak_gb: float | None = None
56
+ tokens_per_s: float | None = None
57
+ adapter_path: str | None = None
58
+ simulated: bool = False
59
+ message: str = ""
60
+ extra: dict[str, Any] = field(default_factory=dict)
61
+
62
+
63
+ @dataclass
64
+ class Callbacks:
65
+ """Hooks the orchestrator gives an engine. All optional."""
66
+
67
+ on_step: Callable[[int, dict[str, float]], None] | None = None
68
+ on_batch: Callable[[int, list[int]], None] | None = None # step -> training row indices
69
+ on_checkpoint: Callable[[str], None] | None = None
70
+ should_stop: Callable[[], bool] | None = None
71
+ log: Callable[[str], None] = print
72
+
73
+ def step(self, step: int, metrics: dict[str, float]) -> None:
74
+ if self.on_step:
75
+ self.on_step(step, metrics)
76
+
77
+ def stop_requested(self) -> bool:
78
+ return bool(self.should_stop and self.should_stop())
79
+
80
+
81
+ class Engine(abc.ABC):
82
+ name: str = "engine"
83
+
84
+ @abc.abstractmethod
85
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
86
+ """What this engine can do on `hw`. With `assume_installed` (planning for remote
87
+ hardware) library availability is assumed rather than checked locally."""
88
+
89
+ @abc.abstractmethod
90
+ def probe(self, plan: ExecutionPlan, ctx: ProbeContext, micro_batch: int | None = None) -> ProbeResult:
91
+ """Run a few real (or simulated) steps to measure peak memory and throughput."""
92
+
93
+ @abc.abstractmethod
94
+ def train(
95
+ self,
96
+ plan: ExecutionPlan,
97
+ spec: RunSpec,
98
+ train_rows: list[dict[str, Any]],
99
+ eval_rows: list[dict[str, Any]] | None,
100
+ callbacks: Callbacks,
101
+ output_dir: Path,
102
+ resume_from: str | None = None,
103
+ ) -> RunResult:
104
+ """Execute the plan on normalized rows (see bitstraining.data.schema)."""
105
+
106
+
107
+ REAL_ENGINES = ("hf_peft", "unsloth", "mlx", "deepspeed")
108
+
109
+
110
+ def available_engines(
111
+ hw: HardwareProfile, which: str = "auto", assume_installed: bool = False
112
+ ) -> list[Capabilities]:
113
+ """Capabilities of the engines the planner may use. `auto` = real engines only; the
114
+ `simulate` engine must be asked for by name so it never competes with real backends."""
115
+ names = [which] if which != "auto" else list(REAL_ENGINES)
116
+ out = []
117
+ for n in names:
118
+ eng: Engine = registry.create("engines", n)
119
+ out.append(eng.capabilities(hw, assume_installed))
120
+ return out
@@ -0,0 +1,44 @@
1
+ """DeepSpeed / FSDP engine placeholder.
2
+
3
+ Not implemented. It is registered so the plugin surface and capability reporting are visible, but it
4
+ always reports `available=False`, so the planner never selects it. Multi-GPU data parallelism is
5
+ available today through `hf_peft` under torchrun; sharded (ZeRO-3/FSDP) training is roadmap Phase 4.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from bitstraining.core.errors import EngineUnavailable
14
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan, HardwareProfile, RunSpec
15
+ from bitstraining.engines.base import Callbacks, Engine, ProbeContext, ProbeResult, RunResult
16
+
17
+
18
+ class DeepSpeedEngine(Engine):
19
+ name = "deepspeed"
20
+
21
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
22
+ return Capabilities(
23
+ name=self.name,
24
+ available=False,
25
+ reason="not implemented yet (roadmap Phase 4: sharded multi-GPU training)",
26
+ methods=["full", "lora"],
27
+ parallelism=["ddp", "fsdp"],
28
+ tasks=["sft"],
29
+ )
30
+
31
+ def probe(self, plan: ExecutionPlan, ctx: ProbeContext, micro_batch: int | None = None) -> ProbeResult:
32
+ raise EngineUnavailable("deepspeed engine is not implemented yet")
33
+
34
+ def train(
35
+ self,
36
+ plan: ExecutionPlan,
37
+ spec: RunSpec,
38
+ train_rows: list[dict[str, Any]],
39
+ eval_rows: list[dict[str, Any]] | None,
40
+ callbacks: Callbacks,
41
+ output_dir: Path,
42
+ resume_from: str | None = None,
43
+ ) -> RunResult:
44
+ raise EngineUnavailable("deepspeed engine is not implemented yet", fix="use engine: hf_peft")
@@ -0,0 +1,325 @@
1
+ """Baseline engine: Hugging Face Transformers + PEFT (+ bitsandbytes for QLoRA).
2
+
3
+ All heavy imports happen inside methods, so importing this module is free and the core works
4
+ without PyTorch installed.
5
+
6
+ STATUS: this adapter is written against the public Transformers/PEFT APIs but is NOT exercised by
7
+ this repository's CI (which has no GPU/torch). Run `bitstraining autotune --engine hf_peft` and a
8
+ short real run on your hardware before trusting it; report breakage as an issue.
9
+
10
+ Scope today: single process, one GPU per process; multi-GPU data parallelism by launching under
11
+ `torchrun` (the runner does this when plan.n_gpus > 1). Only the final assistant turn of each
12
+ conversation is trained (prompt tokens are masked). Layer streaming and FSDP are not implemented.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import json
19
+ import os
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from bitstraining.core.errors import EngineUnavailable
25
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan, HardwareProfile, RunSpec
26
+ from bitstraining.engines.base import Callbacks, Engine, ProbeContext, ProbeResult, RunResult
27
+
28
+ GB = 1024**3
29
+ _OPTIM = {"adamw": "adamw_torch_fused", "adamw8bit": "adamw_bnb_8bit",
30
+ "paged_adamw8bit": "paged_adamw_8bit"}
31
+ _ATTN = {"flash": "flash_attention_2", "sdpa": "sdpa", "eager": "eager"}
32
+ _FALLBACK_TEMPLATE = "### User:\n{user}\n\n### Assistant:\n"
33
+
34
+
35
+ def _have(mod: str) -> bool:
36
+ return importlib.util.find_spec(mod) is not None
37
+
38
+
39
+ def _require() -> None:
40
+ missing = [m for m in ("torch", "transformers", "peft") if not _have(m)]
41
+ if missing:
42
+ raise EngineUnavailable(
43
+ f"hf_peft engine needs: {', '.join(missing)}",
44
+ fix="pip install 'bitstraining[train]' (and 'bitstraining[quant]' for QLoRA)",
45
+ )
46
+
47
+
48
+ class HFPeftEngine(Engine):
49
+ name = "hf_peft"
50
+
51
+ # ------------------------------------------------------------------ capabilities
52
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
53
+ core = all(_have(m) for m in ("torch", "transformers", "peft"))
54
+ cuda = hw.gpu_vendor == "nvidia"
55
+ bnb = assume_installed or _have("bitsandbytes")
56
+ flash = (assume_installed and cuda) or _have("flash_attn")
57
+ available = assume_installed or core
58
+ methods = ["full", "lora", "dora"] + (["qlora"] if cuda and bnb else [])
59
+ optimizers = ["adamw"] + (["adamw8bit", "paged_adamw8bit"] if cuda and bnb else [])
60
+ return Capabilities(
61
+ name=self.name,
62
+ available=available,
63
+ reason="" if available else "torch/transformers/peft not installed",
64
+ methods=methods,
65
+ precisions=["bf16", "fp16"],
66
+ activation_modes=["none", "full"],
67
+ optimizers=optimizers,
68
+ attention=(["flash"] if flash else []) + ["sdpa", "eager"],
69
+ parallelism=["single", "ddp"] if cuda else ["single"],
70
+ supports_packing=flash, # padding-free collator needs flash-attention varlen
71
+ supports_layer_stream=False,
72
+ supports_fused_ce=False,
73
+ supports_compile=False,
74
+ tasks=["sft", "pretrain"],
75
+ platforms=["cuda", "mps", "cpu"],
76
+ speed_prior=1.0,
77
+ speed_prior_is_measured=True, # the baseline other engines are compared against
78
+ )
79
+
80
+ # ------------------------------------------------------------------ model loading
81
+ def _load_model(self, plan: ExecutionPlan, spec: RunSpec) -> Any:
82
+ import torch
83
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
84
+
85
+ dtype = torch.bfloat16 if plan.precision == "bf16" else torch.float16
86
+ kwargs: dict[str, Any] = dict(
87
+ torch_dtype=dtype,
88
+ attn_implementation=_ATTN.get(plan.attention, "sdpa"),
89
+ trust_remote_code=spec.model.trust_remote_code,
90
+ revision=spec.model.revision,
91
+ )
92
+ if torch.cuda.is_available():
93
+ kwargs["device_map"] = {"": int(os.environ.get("LOCAL_RANK", 0))}
94
+ if plan.quant == "nf4":
95
+ kwargs["quantization_config"] = BitsAndBytesConfig(
96
+ load_in_4bit=True, bnb_4bit_quant_type="nf4",
97
+ bnb_4bit_compute_dtype=dtype, bnb_4bit_use_double_quant=True,
98
+ )
99
+ model = AutoModelForCausalLM.from_pretrained(spec.model.base, **kwargs)
100
+ model.config.use_cache = False
101
+ return self._wrap(model, plan)
102
+
103
+ def _wrap(self, model: Any, plan: ExecutionPlan) -> Any:
104
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
105
+
106
+ ckpt = plan.activation == "full"
107
+ if plan.quant == "nf4":
108
+ model = prepare_model_for_kbit_training(
109
+ model, use_gradient_checkpointing=ckpt,
110
+ gradient_checkpointing_kwargs={"use_reentrant": False},
111
+ )
112
+ elif ckpt:
113
+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
114
+ if plan.method != "full":
115
+ cfg = LoraConfig(
116
+ r=plan.lora_r, lora_alpha=plan.lora_alpha, lora_dropout=plan.lora_dropout,
117
+ target_modules=plan.target_modules, task_type="CAUSAL_LM",
118
+ use_dora=plan.method == "dora",
119
+ )
120
+ if ckpt:
121
+ model.enable_input_require_grads()
122
+ model = get_peft_model(model, cfg)
123
+ return model
124
+
125
+ # ------------------------------------------------------------------ data
126
+ @staticmethod
127
+ def _encode(tok: Any, row: dict[str, Any], max_len: int) -> dict[str, list[int]] | None:
128
+ if "text" in row:
129
+ ids = tok(row["text"], truncation=True, max_length=max_len)["input_ids"]
130
+ return {"input_ids": ids, "labels": list(ids), "attention_mask": [1] * len(ids)}
131
+ msgs = row["messages"]
132
+ if not msgs or msgs[-1]["role"] != "assistant":
133
+ return None
134
+ if getattr(tok, "chat_template", None):
135
+ prefix = tok.apply_chat_template(msgs[:-1], tokenize=False, add_generation_prompt=True)
136
+ full = tok.apply_chat_template(msgs, tokenize=False)
137
+ else:
138
+ user = "\n".join(m["content"] for m in msgs[:-1])
139
+ prefix = _FALLBACK_TEMPLATE.format(user=user)
140
+ full = prefix + msgs[-1]["content"] + (tok.eos_token or "")
141
+ if not full.startswith(prefix): # template does not nest; train on everything
142
+ prefix = ""
143
+ p_ids = tok(prefix, add_special_tokens=False)["input_ids"] if prefix else []
144
+ f_ids = tok(full, add_special_tokens=False)["input_ids"]
145
+ labels = [-100] * len(p_ids) + f_ids[len(p_ids):]
146
+ f_ids, labels = f_ids[:max_len], labels[:max_len]
147
+ if all(x == -100 for x in labels):
148
+ return None
149
+ return {"input_ids": f_ids, "labels": labels, "attention_mask": [1] * len(f_ids)}
150
+
151
+ def _dataset(self, tok: Any, rows: list[dict[str, Any]], max_len: int) -> Any:
152
+ from torch.utils.data import Dataset
153
+
154
+ enc = [e for r in rows if (e := self._encode(tok, r, max_len)) is not None]
155
+
156
+ class _DS(Dataset): # type: ignore[type-arg]
157
+ def __len__(self) -> int:
158
+ return len(enc)
159
+
160
+ def __getitem__(self, i: int) -> dict[str, list[int]]:
161
+ return enc[i]
162
+
163
+ return _DS()
164
+
165
+ # ------------------------------------------------------------------ probe
166
+ def probe(self, plan: ExecutionPlan, ctx: ProbeContext, micro_batch: int | None = None) -> ProbeResult:
167
+ _require()
168
+ import torch
169
+
170
+ mb = micro_batch or plan.micro_batch
171
+ if not torch.cuda.is_available():
172
+ return ProbeResult(fits=True, note="no CUDA device: probe skipped")
173
+ torch.cuda.empty_cache()
174
+ torch.cuda.reset_peak_memory_stats()
175
+ model = None
176
+ try:
177
+ model = self._load_model(plan, ctx.spec)
178
+ params = [p for p in model.parameters() if p.requires_grad]
179
+ opt = torch.optim.AdamW(params, lr=1e-5)
180
+ vocab = ctx.model.vocab_size or 32000
181
+ x = torch.randint(0, vocab, (mb, ctx.seq_len), device="cuda")
182
+ steps, t0 = 3, None
183
+ for i in range(steps + 1):
184
+ if i == 1: # step 0 is warmup
185
+ torch.cuda.synchronize()
186
+ t0 = time.perf_counter()
187
+ out = model(input_ids=x, labels=x)
188
+ out.loss.backward()
189
+ opt.step()
190
+ opt.zero_grad(set_to_none=True)
191
+ torch.cuda.synchronize()
192
+ dt = time.perf_counter() - (t0 or time.perf_counter())
193
+ return ProbeResult(
194
+ fits=True,
195
+ peak_gb=round(torch.cuda.max_memory_allocated() / GB, 3),
196
+ tokens_per_s=round(steps * mb * ctx.seq_len / max(dt, 1e-9), 1),
197
+ steps=steps,
198
+ note="measured",
199
+ )
200
+ except torch.cuda.OutOfMemoryError:
201
+ return ProbeResult(fits=False, note="CUDA out of memory")
202
+ finally:
203
+ del model
204
+ torch.cuda.empty_cache()
205
+
206
+ # ------------------------------------------------------------------ train
207
+ def train(
208
+ self,
209
+ plan: ExecutionPlan,
210
+ spec: RunSpec,
211
+ train_rows: list[dict[str, Any]],
212
+ eval_rows: list[dict[str, Any]] | None,
213
+ callbacks: Callbacks,
214
+ output_dir: Path,
215
+ resume_from: str | None = None,
216
+ ) -> RunResult:
217
+ _require()
218
+ import torch
219
+ from transformers import (
220
+ AutoTokenizer,
221
+ DataCollatorForSeq2Seq,
222
+ Trainer,
223
+ TrainerCallback,
224
+ TrainingArguments,
225
+ set_seed,
226
+ )
227
+
228
+ set_seed(plan.seed)
229
+ output_dir.mkdir(parents=True, exist_ok=True)
230
+ tok = AutoTokenizer.from_pretrained(spec.model.base, trust_remote_code=spec.model.trust_remote_code)
231
+ if tok.pad_token is None:
232
+ tok.pad_token = tok.eos_token
233
+ train_ds = self._dataset(tok, train_rows, plan.max_length)
234
+ if len(train_ds) == 0: # type: ignore[arg-type]
235
+ raise EngineUnavailable("no trainable rows after tokenization", fix="check the data format")
236
+ eval_ds = self._dataset(tok, eval_rows, plan.max_length) if eval_rows else None
237
+
238
+ collator: Any = DataCollatorForSeq2Seq(tok, padding=True, label_pad_token_id=-100)
239
+ packing_ok = False
240
+ if plan.packing:
241
+ try:
242
+ from transformers import DataCollatorWithFlattening
243
+
244
+ collator, packing_ok = DataCollatorWithFlattening(), True
245
+ except ImportError:
246
+ callbacks.log("packing requested but DataCollatorWithFlattening is unavailable; using padding")
247
+
248
+ model = self._load_model(plan, spec)
249
+ total_steps = plan.total_steps or 0
250
+ args = TrainingArguments(
251
+ output_dir=str(output_dir),
252
+ per_device_train_batch_size=plan.micro_batch,
253
+ per_device_eval_batch_size=plan.micro_batch,
254
+ gradient_accumulation_steps=plan.grad_accum,
255
+ num_train_epochs=plan.epochs,
256
+ learning_rate=plan.learning_rate,
257
+ lr_scheduler_type="cosine",
258
+ warmup_ratio=0.03,
259
+ logging_steps=1,
260
+ save_strategy="steps",
261
+ save_steps=int(spec.extras.get("save_steps") or max(50, total_steps // 5 or 50)),
262
+ save_total_limit=2,
263
+ bf16=plan.precision == "bf16",
264
+ fp16=plan.precision == "fp16",
265
+ optim=_OPTIM.get(plan.optimizer, "adamw_torch"),
266
+ group_by_length=not packing_ok and plan.micro_batch > 1,
267
+ dataloader_num_workers=plan.dataloader_workers,
268
+ report_to="none",
269
+ seed=plan.seed,
270
+ remove_unused_columns=False,
271
+ eval_strategy="epoch" if eval_ds is not None else "no",
272
+ ddp_find_unused_parameters=False,
273
+ max_steps=int(spec.extras["max_steps"]) if spec.extras.get("max_steps") else -1,
274
+ )
275
+
276
+ t_start = time.perf_counter()
277
+ tokens_seen = {"n": 0}
278
+
279
+ class _Hook(TrainerCallback):
280
+ def on_log(self, a: Any, state: Any, control: Any, logs: dict[str, float] | None = None, **kw: Any) -> None:
281
+ if not logs or "loss" not in logs:
282
+ return
283
+ elapsed = max(time.perf_counter() - t_start, 1e-9)
284
+ m = {k: float(v) for k, v in logs.items() if isinstance(v, (int, float))}
285
+ m["tokens_per_s"] = tokens_seen["n"] / elapsed
286
+ callbacks.step(int(state.global_step), m)
287
+ if callbacks.stop_requested():
288
+ control.should_training_stop = True
289
+
290
+ def on_step_end(self, a: Any, state: Any, control: Any, **kw: Any) -> None:
291
+ tokens_seen["n"] += a.per_device_train_batch_size * a.gradient_accumulation_steps * plan.max_length
292
+
293
+ def on_save(self, a: Any, state: Any, control: Any, **kw: Any) -> None:
294
+ if callbacks.on_checkpoint:
295
+ callbacks.on_checkpoint(str(output_dir / f"checkpoint-{state.global_step}"))
296
+
297
+ trainer = Trainer(
298
+ model=model, args=args, train_dataset=train_ds, eval_dataset=eval_ds,
299
+ data_collator=collator, callbacks=[_Hook()],
300
+ )
301
+ if torch.cuda.is_available():
302
+ torch.cuda.reset_peak_memory_stats()
303
+ trainer.train(resume_from_checkpoint=resume_from)
304
+ trainer.save_model(str(output_dir))
305
+ tok.save_pretrained(str(output_dir))
306
+
307
+ hist = trainer.state.log_history
308
+ losses = [h["loss"] for h in hist if "loss" in h]
309
+ eval_losses = [h["eval_loss"] for h in hist if "eval_loss" in h]
310
+ seconds = time.perf_counter() - t_start
311
+ peak = torch.cuda.max_memory_allocated() / GB if torch.cuda.is_available() else None
312
+ (output_dir / "bitstraining_run.json").write_text(
313
+ json.dumps({"base": spec.model.base, "plan": plan.to_dict(), "steps": trainer.state.global_step}, indent=2)
314
+ )
315
+ return RunResult(
316
+ status="stopped" if callbacks.stop_requested() else "completed",
317
+ steps=int(trainer.state.global_step),
318
+ final_loss=losses[-1] if losses else None,
319
+ eval_loss=eval_losses[-1] if eval_losses else None,
320
+ seconds=round(seconds, 1),
321
+ peak_gb=round(peak, 3) if peak else None,
322
+ tokens_per_s=round(tokens_seen["n"] / max(seconds, 1e-9), 1),
323
+ adapter_path=str(output_dir),
324
+ simulated=False,
325
+ )
@@ -0,0 +1,100 @@
1
+ """Apple Silicon engine: drives the official `mlx_lm.lora` trainer.
2
+
3
+ EXPERIMENTAL and not exercised by CI (needs macOS + mlx-lm). The adapter writes the dataset in
4
+ mlx-lm's directory layout (train.jsonl / valid.jsonl), runs the trainer as a subprocess, and parses
5
+ its "Iter N: Train loss X" lines into callbacks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib.util
11
+ import json
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from bitstraining.core.errors import EngineUnavailable
19
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan, HardwareProfile, RunSpec
20
+ from bitstraining.engines.base import Callbacks, Engine, ProbeContext, ProbeResult, RunResult
21
+
22
+ _LOSS = re.compile(r"Iter\s+(\d+):\s+Train loss\s+([0-9.]+)")
23
+ _PEAK = re.compile(r"Peak mem\s+([0-9.]+)\s*GB", re.I)
24
+
25
+
26
+ class MLXEngine(Engine):
27
+ name = "mlx"
28
+
29
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
30
+ apple = hw.gpu_vendor == "apple"
31
+ have = assume_installed or importlib.util.find_spec("mlx_lm") is not None
32
+ ok = apple and have
33
+ return Capabilities(
34
+ name=self.name,
35
+ available=ok,
36
+ reason="" if ok else ("needs Apple Silicon" if not apple else "mlx-lm not installed (pip install 'bitstraining[mlx]')"),
37
+ methods=["lora", "qlora"], # qlora = LoRA over a pre-quantized MLX model
38
+ precisions=["bf16", "fp16"],
39
+ activation_modes=["none", "full"],
40
+ optimizers=["adamw"],
41
+ attention=["sdpa"],
42
+ parallelism=["single"],
43
+ tasks=["sft"],
44
+ platforms=["mps"],
45
+ speed_prior=1.0,
46
+ speed_prior_is_measured=False,
47
+ )
48
+
49
+ def probe(self, plan: ExecutionPlan, ctx: ProbeContext, micro_batch: int | None = None) -> ProbeResult:
50
+ return ProbeResult(fits=True, note="probe not implemented for MLX; plan estimate is unverified")
51
+
52
+ def train(
53
+ self,
54
+ plan: ExecutionPlan,
55
+ spec: RunSpec,
56
+ train_rows: list[dict[str, Any]],
57
+ eval_rows: list[dict[str, Any]] | None,
58
+ callbacks: Callbacks,
59
+ output_dir: Path,
60
+ resume_from: str | None = None,
61
+ ) -> RunResult:
62
+ if importlib.util.find_spec("mlx_lm") is None:
63
+ raise EngineUnavailable("mlx-lm is not installed", fix="pip install 'bitstraining[mlx]'")
64
+ output_dir.mkdir(parents=True, exist_ok=True)
65
+ data_dir = output_dir / "mlx_data"
66
+ data_dir.mkdir(exist_ok=True)
67
+ valid = eval_rows or train_rows[: max(1, len(train_rows) // 20)]
68
+ for name, rows in (("train", train_rows), ("valid", valid)):
69
+ with (data_dir / f"{name}.jsonl").open("w") as f:
70
+ for r in rows:
71
+ f.write(json.dumps(r) + "\n")
72
+ iters = int(spec.extras.get("max_steps") or plan.total_steps * plan.grad_accum or 100)
73
+ cmd = [
74
+ sys.executable, "-m", "mlx_lm.lora", "--model", spec.model.base, "--train",
75
+ "--data", str(data_dir), "--iters", str(iters),
76
+ "--batch-size", str(plan.micro_batch), "--learning-rate", str(plan.learning_rate),
77
+ "--max-seq-length", str(plan.max_length), "--adapter-path", str(output_dir),
78
+ "--grad-accumulation-steps", str(plan.grad_accum),
79
+ ]
80
+ if plan.activation == "full":
81
+ cmd.append("--grad-checkpoint")
82
+ callbacks.log("running: " + " ".join(cmd))
83
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
84
+ last_loss, last_step, peak = None, 0, None
85
+ assert proc.stdout is not None
86
+ for line in proc.stdout:
87
+ callbacks.log(line.rstrip())
88
+ if m := _LOSS.search(line):
89
+ last_step, last_loss = int(m.group(1)), float(m.group(2))
90
+ callbacks.step(last_step, {"loss": last_loss})
91
+ if m := _PEAK.search(line):
92
+ peak = float(m.group(1))
93
+ if callbacks.stop_requested():
94
+ proc.terminate()
95
+ break
96
+ rc = proc.wait()
97
+ status = "completed" if rc == 0 else ("stopped" if callbacks.stop_requested() else "failed")
98
+ return RunResult(status=status, steps=last_step, final_loss=last_loss, peak_gb=peak,
99
+ adapter_path=str(output_dir) if rc == 0 else None,
100
+ message="" if rc == 0 else f"mlx_lm.lora exited with code {rc}")