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,126 @@
1
+ """Analytic GPU-memory model for fine-tuning.
2
+
3
+ Peak memory per device is the sum of:
4
+
5
+ weights base parameters at their storage precision (bf16 = 2 B, NF4 = 0.53 B)
6
+ master fp32 master weights (full fine-tuning under mixed precision only)
7
+ gradients per trainable parameter (adapters are kept in fp32)
8
+ optimizer per trainable parameter: AdamW 8 B, 8-bit Adam 2 B
9
+ activations per Korthikanti et al. (2022): s*b*h*(34 + 5*a*s/h) bytes per layer, where the
10
+ 5*a*s/h attention-score term disappears with fused (flash) attention. The 34 is
11
+ split into an attention part (15) and an MLP part (19, scaled by intermediate/4h).
12
+ Checkpointing keeps only 2*s*b*h per checkpointed layer plus one live layer.
13
+ logits b*s*V*10 B unfused (bf16 logits + fp32 upcast + fp32 grad); chunked fused loss ~1.5 B
14
+ context CUDA context and kernels workspace (~0.8 GB)
15
+
16
+ Sharding (FSDP/ZeRO-3) divides weights, gradients, master and optimizer state by the number of
17
+ GPUs and adds one gathered layer. Layer streaming keeps only embeddings, the LM head, adapters and
18
+ two layer buffers resident; the frozen stack lives in host RAM.
19
+
20
+ These are estimates. `planner.calibration` stores measured/predicted ratios from real probes
21
+ and the planner applies them, and the engine probe verifies the final plan before a long run.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from bitstraining.core.schemas import ExecutionPlan, ModelInfo
27
+ from bitstraining.models.introspect import lora_param_count
28
+ from bitstraining.strategies.catalog import (
29
+ METHODS,
30
+ OPTIMIZER_STATE_BYTES,
31
+ weight_bytes_per_param,
32
+ )
33
+
34
+ GB = 1024**3
35
+ CONTEXT_GB_CUDA = 0.8
36
+ CONTEXT_GB_OTHER = 0.3
37
+ FRAGMENTATION = 1.08
38
+
39
+
40
+ def layer_params(m: ModelInfo) -> int:
41
+ return m.nonembed_params // max(m.num_layers, 1)
42
+
43
+
44
+ def trainable_params(m: ModelInfo, plan: ExecutionPlan) -> int:
45
+ if METHODS[plan.method].full_weights_trainable:
46
+ return m.params
47
+ return lora_param_count(m, plan.lora_r, plan.target_modules)
48
+
49
+
50
+ def activation_bytes(m: ModelInfo, plan: ExecutionPlan, seq_len: int) -> float:
51
+ """Saved-activation bytes for one micro-batch under the plan's checkpointing mode."""
52
+ b, s, h = plan.micro_batch, seq_len, m.hidden_size
53
+ mlp_scale = m.intermediate_size / (4 * h)
54
+ mlp_term = 19 * mlp_scale * (max(m.active_experts, 1) if m.num_experts > 1 else 1)
55
+ per_layer = s * b * h * (15 + mlp_term)
56
+ if plan.attention == "eager":
57
+ per_layer += 5 * m.num_heads * s * s * b # materialized attention scores
58
+ ckpt_layer = 2 * s * b * h # saved layer input only
59
+ if plan.activation == "full":
60
+ return m.num_layers * ckpt_layer + per_layer
61
+ if plan.activation == "selective":
62
+ half = m.num_layers // 2
63
+ return (m.num_layers - half) * per_layer + half * ckpt_layer + per_layer
64
+ return m.num_layers * per_layer
65
+
66
+
67
+ def estimate_memory(
68
+ m: ModelInfo,
69
+ plan: ExecutionPlan,
70
+ seq_len: int,
71
+ device_kind: str = "cuda",
72
+ ) -> tuple[dict[str, float], float]:
73
+ """Return (per-device breakdown in GB including a 'total' key, host RAM needed in GB)."""
74
+ method = METHODS[plan.method]
75
+ n = max(plan.n_gpus, 1)
76
+ shard = n if plan.parallelism == "fsdp" else 1
77
+ wb = weight_bytes_per_param(method.quant, plan.precision)
78
+ layer_stored = layer_params(m) * wb
79
+ n_train = trainable_params(m, plan)
80
+
81
+ notes_host = 0.0
82
+ if plan.layer_stream:
83
+ resident = m.embed_params * (2.0 if method.quant == "nf4" else wb) + 2 * layer_stored
84
+ weights = resident
85
+ notes_host = layer_params(m) * m.num_layers * wb + 2 * GB
86
+ else:
87
+ weights = m.params * wb / shard
88
+ notes_host = m.params * 2.0 + 1 * GB # bf16 staging while loading/quantizing
89
+
90
+ master = 0.0
91
+ if method.full_weights_trainable:
92
+ master = n_train * 4.0 / shard
93
+ grads = n_train * 2.0 / shard
94
+ opt = n_train * OPTIMIZER_STATE_BYTES[plan.optimizer] / shard
95
+ adapters = 0.0
96
+ else:
97
+ adapters = n_train * 4.0 # fp32 adapter weights
98
+ grads = n_train * 4.0
99
+ opt = n_train * OPTIMIZER_STATE_BYTES[plan.optimizer]
100
+
101
+ gathered = layer_stored * 2 if (plan.parallelism == "fsdp" and n > 1) else 0.0
102
+ dequant = layer_params(m) * 2.0 if method.quant == "nf4" else 0.0 # one bf16 layer workspace
103
+
104
+ acts = activation_bytes(m, plan, seq_len)
105
+ logit_bytes_per = 1.5 if plan.fused_ce else 10.0
106
+ logits = plan.micro_batch * seq_len * m.vocab_size * logit_bytes_per
107
+
108
+ context = (CONTEXT_GB_CUDA if device_kind == "cuda" else CONTEXT_GB_OTHER) * GB
109
+ static = weights + master + adapters + grads + opt + gathered + dequant
110
+ dynamic = (acts + logits) * FRAGMENTATION
111
+ parts = {
112
+ "weights": weights + gathered,
113
+ "master_weights": master,
114
+ "adapters": adapters,
115
+ "gradients": grads,
116
+ "optimizer": opt,
117
+ "dequant_workspace": dequant,
118
+ "activations": acts * FRAGMENTATION,
119
+ "logits": logits * FRAGMENTATION,
120
+ "context": context,
121
+ }
122
+ breakdown = {k: v / GB for k, v in parts.items()}
123
+ breakdown["total"] = (static + dynamic + context) / GB
124
+ if plan.optimizer == "paged_adamw8bit":
125
+ notes_host += 0.0 # paging is opportunistic; host usage grows only under pressure
126
+ return breakdown, notes_host / GB
@@ -0,0 +1,368 @@
1
+ """Strategy search: enumerate feasible execution plans, estimate them, rank them.
2
+
3
+ Search space (restricted by each engine's declared Capabilities and by the user's constraints):
4
+ engine x method x layer-streaming x activation checkpointing x optimizer x micro-batch
5
+ x packing x parallelism. Precision, attention kernel and fused loss are chosen per hardware.
6
+
7
+ Ranking: plans inside the user's time/cost budget come first, then by the objective
8
+ (time | cost | memory), then by operational complexity. The result keeps the best plan per
9
+ (engine, method, streaming, parallelism) so the caller sees real alternatives rather than
10
+ five micro-batch variants of the same idea.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from dataclasses import replace
17
+
18
+ from bitstraining.core.errors import PlanningError
19
+ from bitstraining.core.schemas import (
20
+ Capabilities,
21
+ DatasetStats,
22
+ Estimate,
23
+ ExecutionPlan,
24
+ HardwareProfile,
25
+ ModelInfo,
26
+ RunSpec,
27
+ )
28
+ from bitstraining.data.pack import packing_efficiency, padding_efficiency
29
+ from bitstraining.hardware.database import GPU_DB
30
+ from bitstraining.planner import calibration as calib_mod
31
+ from bitstraining.planner.memory import estimate_memory
32
+ from bitstraining.planner.throughput import device_for, estimate_throughput
33
+ from bitstraining.strategies.catalog import METHODS
34
+
35
+ MICRO_BATCHES = (1, 2, 4, 8, 16, 32, 64)
36
+ DEFAULT_HEADROOM = 0.92 # fraction of device memory the plan may use
37
+ _ATTN_PREF = ("flash", "sdpa", "eager")
38
+
39
+
40
+ def device_kind(hw: HardwareProfile) -> str:
41
+ return {"nvidia": "cuda", "amd": "cuda", "apple": "mps"}.get(hw.gpu_vendor, "cpu")
42
+
43
+
44
+ def _pick_attention(caps: Capabilities, hw: HardwareProfile) -> str:
45
+ gpu = device_for(hw)
46
+ for a in _ATTN_PREF:
47
+ if a in caps.attention and (a != "flash" or (gpu.bf16 and device_kind(hw) == "cuda")):
48
+ return a
49
+ return caps.attention[0] if caps.attention else "sdpa"
50
+
51
+
52
+ def _complexity(p: ExecutionPlan) -> float:
53
+ return (
54
+ 3.0 * p.layer_stream
55
+ + (1.0 if p.activation != "none" else 0.0)
56
+ + (1.0 if p.optimizer.startswith("paged") else 0.0)
57
+ + (0.5 if p.optimizer == "adamw8bit" else 0.0)
58
+ + (0.5 if p.parallelism == "fsdp" else 0.0)
59
+ )
60
+
61
+
62
+ def suggest_gpus(peak_gb: float, headroom: float = DEFAULT_HEADROOM, n: int = 3) -> list[str]:
63
+ """Smallest catalog GPUs whose memory could hold `peak_gb`."""
64
+ seen: dict[float, str] = {}
65
+ for name, row in sorted(GPU_DB.items(), key=lambda kv: kv[1]["vram_gb"]):
66
+ if row["vram_gb"] * headroom >= peak_gb and "laptop" not in name and not name.startswith("apple"):
67
+ seen.setdefault(row["vram_gb"], name)
68
+ return [f"{name} ({vram:g} GB)" for vram, name in list(seen.items())[:n]]
69
+
70
+
71
+ def make_plans(
72
+ spec: RunSpec,
73
+ model: ModelInfo,
74
+ stats: DatasetStats,
75
+ hw: HardwareProfile,
76
+ engines: list[Capabilities],
77
+ top_k: int = 5,
78
+ headroom: float = DEFAULT_HEADROOM,
79
+ calibration: dict[str, dict[str, float]] | None = None,
80
+ ) -> list[ExecutionPlan]:
81
+ """Return up to `top_k` ranked, feasible plans or raise PlanningError with advice."""
82
+ g, d = spec.goal, spec.data
83
+ kind = device_kind(hw)
84
+ gpu = device_for(hw)
85
+ n_gpus = max(spec.compute.n_gpus or hw.n_gpus or 1, 1)
86
+ vram = gpu.vram_gb
87
+ ram = hw.ram_gb or float("inf")
88
+ calibration = calibration if calibration is not None else calib_mod.load()
89
+
90
+ seq_len = max(8, min(d.max_length, stats.max_len or d.max_length))
91
+ lengths = stats.lengths_sample
92
+ mean_len = stats.mean_len or float(seq_len)
93
+ mem_precision = "bf16" if gpu.bf16 else "fp16"
94
+
95
+ methods = [m for m in (g.methods or list(METHODS)) if m in METHODS]
96
+ if not g.allow_quantization:
97
+ methods = [m for m in methods if METHODS[m].quant == "none"]
98
+ if not methods:
99
+ raise PlanningError(
100
+ "no methods left after applying goal.methods / allow_quantization",
101
+ fix="allow quantization or list at least one of full, lora, dora",
102
+ )
103
+
104
+ pad_cache: dict[tuple[int, bool], float] = {}
105
+
106
+ def efficiency(mb: int, packing: bool) -> float:
107
+ k = (mb, packing)
108
+ if k not in pad_cache:
109
+ if not lengths:
110
+ pad_cache[k] = 1.0
111
+ elif packing:
112
+ pad_cache[k] = packing_efficiency(lengths, d.max_length)
113
+ else:
114
+ pad_cache[k] = padding_efficiency(lengths, mb, grouped=True, max_len=d.max_length)
115
+ return pad_cache[k]
116
+
117
+ feasible: list[ExecutionPlan] = []
118
+ closest: tuple[float, ExecutionPlan] | None = None
119
+ total_tokens = stats.total_tokens * g.epochs
120
+
121
+ for caps in engines:
122
+ if not caps.available or g.task not in caps.tasks or kind not in caps.platforms:
123
+ continue
124
+ attention = _pick_attention(caps, hw)
125
+ precision = mem_precision if mem_precision in caps.precisions else caps.precisions[0]
126
+ fused = caps.supports_fused_ce
127
+ parallel_opts = ["single"] if n_gpus == 1 else [p for p in ("ddp", "fsdp") if p in caps.parallelism]
128
+ if not parallel_opts:
129
+ parallel_opts = ["single"]
130
+ eff_gpus = 1
131
+ else:
132
+ eff_gpus = n_gpus
133
+ pack_opts = [False]
134
+ if caps.supports_packing and d.packing != "off":
135
+ pack_opts = [True] if d.packing == "on" else [False, True]
136
+
137
+ for method_name in methods:
138
+ if method_name not in caps.methods:
139
+ continue
140
+ method = METHODS[method_name]
141
+ stream_opts = [False] + (
142
+ [True] if caps.supports_layer_stream and not method.full_weights_trainable else []
143
+ )
144
+ for stream in stream_opts:
145
+ for par in parallel_opts:
146
+ if stream and par != "single":
147
+ continue
148
+ for act in caps.activation_modes:
149
+ for opt in caps.optimizers:
150
+ for mb in MICRO_BATCHES:
151
+ if mb * eff_gpus > g.global_batch_size and mb > 1:
152
+ continue
153
+ for pack in pack_opts:
154
+ plan = ExecutionPlan(
155
+ engine=caps.name,
156
+ method=method_name,
157
+ precision=precision,
158
+ quant=method.quant,
159
+ layer_stream=stream,
160
+ activation=act,
161
+ optimizer=opt,
162
+ micro_batch=mb,
163
+ grad_accum=max(1, math.ceil(g.global_batch_size / (mb * eff_gpus))),
164
+ n_gpus=eff_gpus,
165
+ parallelism=par,
166
+ packing=pack,
167
+ max_length=d.max_length,
168
+ attention=attention,
169
+ fused_ce=fused,
170
+ dataloader_workers=max(2, min(8, (hw.cpu_cores or 4) // 2)),
171
+ lora_r=g.lora_r,
172
+ lora_alpha=g.lora_alpha,
173
+ lora_dropout=g.lora_dropout,
174
+ target_modules=g.target_modules,
175
+ epochs=g.epochs,
176
+ learning_rate=g.learning_rate,
177
+ seed=g.seed,
178
+ hardware=hw.name,
179
+ model=model.name,
180
+ )
181
+ est = _estimate(
182
+ plan, model, stats, hw, caps, seq_len, mean_len,
183
+ efficiency(mb, pack), total_tokens, vram, ram, headroom,
184
+ calibration, kind,
185
+ )
186
+ plan.estimate = est
187
+ peak = est.peak_gb_per_gpu
188
+ if closest is None or peak < closest[0]:
189
+ closest = (peak, plan)
190
+ if est.fits:
191
+ plan.total_steps = _total_steps(plan, stats, g.epochs, mean_len, efficiency(mb, pack))
192
+ feasible.append(plan)
193
+
194
+ if not feasible:
195
+ raise _no_plan_error(closest, vram, ram, headroom, model, hw)
196
+
197
+ def violates(p: ExecutionPlan) -> int:
198
+ e = p.estimate
199
+ over_time = g.time_budget_hours is not None and e.total_hours > g.time_budget_hours
200
+ over_cost = g.budget_usd is not None and e.cost_usd is not None and e.cost_usd > g.budget_usd
201
+ return int(over_time or over_cost)
202
+
203
+ def key(p: ExecutionPlan) -> tuple[float, ...]:
204
+ e = p.estimate
205
+ if g.objective == "memory":
206
+ obj = e.peak_gb_per_gpu
207
+ elif g.objective == "cost":
208
+ obj = e.cost_usd if e.cost_usd is not None else e.total_hours
209
+ else:
210
+ obj = e.total_hours
211
+ return (violates(p), obj, _complexity(p), e.peak_gb_per_gpu)
212
+
213
+ feasible.sort(key=key)
214
+ best_per_group: dict[tuple[str, str, bool, str], ExecutionPlan] = {}
215
+ for p in feasible:
216
+ best_per_group.setdefault((p.engine, p.method, p.layer_stream, p.parallelism), p)
217
+ out = sorted(best_per_group.values(), key=key)[:top_k]
218
+ if violates(out[0]):
219
+ out[0].estimate.notes.append(
220
+ "no plan meets the time/cost budget; this is the closest. Consider a faster GPU, fewer epochs or less data"
221
+ )
222
+ return out
223
+
224
+
225
+ def estimate_plan(
226
+ plan: ExecutionPlan,
227
+ spec: RunSpec,
228
+ model: ModelInfo,
229
+ stats: DatasetStats,
230
+ hw: HardwareProfile,
231
+ caps: Capabilities,
232
+ headroom: float = DEFAULT_HEADROOM,
233
+ calibration: dict[str, dict[str, float]] | None = None,
234
+ ) -> Estimate:
235
+ """Re-estimate one (possibly modified) plan, e.g. a different micro-batch during autotune."""
236
+ d = spec.data
237
+ gpu = device_for(hw)
238
+ seq_len = max(8, min(d.max_length, stats.max_len or d.max_length))
239
+ mean_len = stats.mean_len or float(seq_len)
240
+ lengths = stats.lengths_sample
241
+ if not lengths:
242
+ eff = 1.0
243
+ elif plan.packing:
244
+ eff = packing_efficiency(lengths, d.max_length)
245
+ else:
246
+ eff = padding_efficiency(lengths, plan.micro_batch, grouped=True, max_len=d.max_length)
247
+ cal = calibration if calibration is not None else calib_mod.load()
248
+ return _estimate(
249
+ plan, model, stats, hw, caps, seq_len, mean_len, eff,
250
+ stats.total_tokens * plan.epochs, gpu.vram_gb, hw.ram_gb or float("inf"), headroom, cal,
251
+ device_kind(hw),
252
+ )
253
+
254
+
255
+ def _total_steps(plan: ExecutionPlan, stats: DatasetStats, epochs: float, mean_len: float, eff: float) -> int:
256
+ seqs_per_step = plan.micro_batch * plan.grad_accum * plan.n_gpus
257
+ if plan.packing:
258
+ # each packed row holds several examples
259
+ seqs_per_step *= max(1.0, plan.max_length * eff / max(mean_len, 1.0))
260
+ return max(1, math.ceil(stats.num_rows * epochs / seqs_per_step))
261
+
262
+
263
+ def _estimate(
264
+ plan: ExecutionPlan,
265
+ model: ModelInfo,
266
+ stats: DatasetStats,
267
+ hw: HardwareProfile,
268
+ caps: Capabilities,
269
+ seq_len: int,
270
+ mean_len: float,
271
+ eff: float,
272
+ total_tokens: float,
273
+ vram: float,
274
+ ram: float,
275
+ headroom: float,
276
+ calibration: dict[str, dict[str, float]],
277
+ kind: str,
278
+ ) -> Estimate:
279
+ ck = calib_mod.key(hw.key, plan.engine, plan.method)
280
+ cal = calibration.get(ck)
281
+ mem_ratio = cal["mem_ratio"] if cal else 1.0
282
+ speed_ratio = cal["speed_ratio"] if cal else 1.0
283
+
284
+ parts, host_gb = estimate_memory(model, plan, seq_len, kind)
285
+ peak = parts["total"] * mem_ratio
286
+ parts = {k: v * (mem_ratio if k != "total" else 1.0) for k, v in parts.items()}
287
+ parts["total"] = peak
288
+
289
+ tp = estimate_throughput(model, plan, hw, caps, mean_len, eff, speed_ratio)
290
+ hours = total_tokens / max(tp.useful_tokens_per_s, 1e-9) / 3600.0
291
+ cost = hours * hw.price_per_hour if hw.price_per_hour is not None else None
292
+
293
+ fits_mem = peak <= vram * headroom
294
+ fits_host = host_gb <= ram * 0.9
295
+ notes: list[str] = []
296
+ if not fits_mem:
297
+ notes.append(f"needs {peak:.1f} GB > {vram * headroom:.1f} GB usable")
298
+ if not fits_host:
299
+ notes.append(f"needs {host_gb:.1f} GB host RAM > {ram * 0.9:.1f} GB")
300
+ if plan.layer_stream:
301
+ notes.append("layer streaming is modeled only; no bundled real engine implements it yet")
302
+ if tp.bottleneck == "transfer":
303
+ notes.append("layer streaming is transfer-bound: expect a large slowdown vs a resident model")
304
+ if plan.method in ("qlora", "dora"):
305
+ notes.append(f"{plan.method} time overhead is a heuristic until calibrated")
306
+ if not cal and not caps.speed_prior_is_measured and caps.speed_prior != 1.0:
307
+ notes.append(f"{caps.name} speed prior {caps.speed_prior:g}x is unverified; run `bitstraining autotune`")
308
+
309
+ # Honest confidence: without a real probe (calibration) every number is a model prediction,
310
+ # so it is "low". A probe on this hardware earns "medium"; measured hardware, an exactly
311
+ # known architecture and comfortable headroom earn "high".
312
+ gpu = device_for(hw)
313
+ if not cal or gpu.peak_tflops_bf16 <= 0:
314
+ confidence = "low"
315
+ elif hw.measured and model.source != "name-heuristic" and peak / max(vram, 1e-6) <= 0.85:
316
+ confidence = "high"
317
+ else:
318
+ confidence = "medium"
319
+ if confidence == "low":
320
+ notes.append("uncalibrated: run `bitstraining autotune` on this hardware to verify with a real probe")
321
+
322
+ return Estimate(
323
+ fits=fits_mem and fits_host,
324
+ peak_gb_per_gpu=round(peak, 3),
325
+ breakdown_gb={k: round(v, 3) for k, v in parts.items()},
326
+ host_ram_gb=round(host_gb, 2),
327
+ raw_tokens_per_s=round(tp.raw_tokens_per_s, 1),
328
+ useful_tokens_per_s=round(tp.useful_tokens_per_s, 1),
329
+ step_time_s=round(tp.micro_batch_time_s * plan.grad_accum, 3),
330
+ total_hours=round(hours, 4),
331
+ cost_usd=None if cost is None else round(cost, 2),
332
+ confidence=confidence,
333
+ bottleneck=tp.bottleneck,
334
+ notes=notes,
335
+ )
336
+
337
+
338
+ def _no_plan_error(
339
+ closest: tuple[float, ExecutionPlan] | None,
340
+ vram: float,
341
+ ram: float,
342
+ headroom: float,
343
+ model: ModelInfo,
344
+ hw: HardwareProfile,
345
+ ) -> PlanningError:
346
+ if closest is None:
347
+ return PlanningError(
348
+ "no engine can run this task on this hardware",
349
+ fix="install an engine (`pip install 'bitstraining[train]'`) or change goal.task / compute target",
350
+ )
351
+ peak, plan = closest
352
+ gpus = suggest_gpus(peak)
353
+ fixes = [
354
+ f"closest plan ({plan.describe()}) needs {peak:.1f} GB but only {vram * headroom:.1f} GB is usable on {hw.name}",
355
+ "reduce data.max_length or goal.global_batch_size",
356
+ "allow quantization (goal.allow_quantization: true) or use a smaller base model",
357
+ ]
358
+ if gpus:
359
+ fixes.append("or plan for rented hardware: " + ", ".join(gpus) + " (use --gpu)")
360
+ return PlanningError(
361
+ f"no feasible plan for {model.name or 'model'} ({model.params / 1e9:.1f}B params) on {hw.name}",
362
+ fix="; ".join(fixes),
363
+ )
364
+
365
+
366
+ def with_overrides(plan: ExecutionPlan, **kw: object) -> ExecutionPlan:
367
+ """Copy a plan with changes (estimates are NOT recomputed; callers should re-estimate)."""
368
+ return replace(plan, **kw) # type: ignore[arg-type]
@@ -0,0 +1,154 @@
1
+ """Roofline-style throughput model.
2
+
3
+ time per token = FLOPs per token / (peak FLOPs * MFU * batch-saturation) x method overhead
4
+
5
+ FLOPs per token = multiplier * (2 * matmul params + attention) + adapter FLOPs, where the
6
+ multiplier is 3 for full fine-tuning (forward + both backward matmuls) and 2 for frozen-base
7
+ methods (the weight-gradient matmuls are skipped), plus recompute for activation checkpointing.
8
+
9
+ MFU (model FLOPs utilization) is a prior: 0.42 with a fused attention kernel on a modern GPU.
10
+ It is a heuristic, not a measurement; calibration against a real probe replaces it
11
+ (see planner.calibration).
12
+
13
+ Layer streaming adds a transfer bound: every micro-batch re-reads the frozen stack over PCIe
14
+ (forward + backward), so step time = max(compute, transfer).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ from dataclasses import dataclass
21
+
22
+ from bitstraining.core.schemas import (
23
+ Capabilities,
24
+ ExecutionPlan,
25
+ GPUInfo,
26
+ HardwareProfile,
27
+ ModelInfo,
28
+ )
29
+ from bitstraining.models.introspect import lora_param_count
30
+ from bitstraining.planner.memory import layer_params
31
+ from bitstraining.strategies.catalog import METHODS, weight_bytes_per_param
32
+
33
+ BASE_MFU = 0.42
34
+ EAGER_PENALTY = 0.70
35
+ FUSED_CE_BONUS = 1.03
36
+ FP32_PENALTY = 0.25
37
+ H2D_EFFICIENCY = 0.8
38
+ STREAM_OVERLAP_LOSS = 0.30 # heuristic: share of the shorter phase NOT hidden by double-buffering
39
+ SAT_REF_TOKENS = 16384
40
+ UNKNOWN_RAM_GB = 8.0 # assumed when system RAM could not be detected (the doctor warns)
41
+ FALLBACK_PEAK_TFLOPS = 20.0 # used when the GPU is not in the database
42
+
43
+ _SCALE_EFF = { # per doubling of GPUs: (nvlink, pcie)
44
+ "ddp": (0.96, 0.90),
45
+ "fsdp": (0.92, 0.80),
46
+ }
47
+
48
+
49
+ @dataclass
50
+ class Throughput:
51
+ raw_tokens_per_s: float # includes padding tokens
52
+ useful_tokens_per_s: float
53
+ micro_batch_time_s: float
54
+ bottleneck: str # compute | transfer
55
+ mfu: float
56
+ used_peak_tflops: float
57
+
58
+
59
+ def matmul_params(m: ModelInfo) -> int:
60
+ """Parameters that participate in per-token matmuls (active experts only, plus LM head)."""
61
+ p = m.nonembed_params
62
+ if m.num_experts > 1:
63
+ mats = 3 if m.gated_mlp else 2
64
+ per_expert = mats * m.hidden_size * m.intermediate_size
65
+ p -= m.num_layers * per_expert * (m.num_experts - max(m.active_experts, 1))
66
+ return p + m.hidden_size * m.vocab_size
67
+
68
+
69
+ def flops_per_token(m: ModelInfo, plan: ExecutionPlan, attn_len: float) -> float:
70
+ method = METHODS[plan.method]
71
+ attn_fwd = 2.0 * m.num_layers * attn_len * m.num_heads * m.head_dim # causal
72
+ fwd = 2.0 * matmul_params(m) + attn_fwd
73
+ mult = method.compute_multiplier
74
+ if plan.activation == "full":
75
+ mult += 1.0
76
+ elif plan.activation == "selective":
77
+ mult += 0.5
78
+ adapter = 0.0
79
+ if not method.full_weights_trainable:
80
+ adapter = 6.0 * lora_param_count(m, plan.lora_r, plan.target_modules)
81
+ return mult * fwd + adapter
82
+
83
+
84
+ def device_for(hw: HardwareProfile) -> GPUInfo:
85
+ """The device the planner models: GPU 0, or a CPU stand-in for GPU-less machines."""
86
+ if hw.gpus:
87
+ return hw.gpus[0]
88
+ ram = hw.ram_gb if hw.ram_gb > 0 else UNKNOWN_RAM_GB # undetected RAM must not mean "0 GB fits nothing"
89
+ return GPUInfo(
90
+ name="cpu", vram_gb=round(ram * 0.6, 2), peak_tflops_bf16=max(hw.cpu_cores * 0.04, 0.1),
91
+ mem_bw_gbs=40.0, bf16=False, h2d_gbs=20.0, source="database",
92
+ )
93
+
94
+
95
+ def estimate_throughput(
96
+ m: ModelInfo,
97
+ plan: ExecutionPlan,
98
+ hw: HardwareProfile,
99
+ caps: Capabilities,
100
+ mean_len: float,
101
+ pad_eff: float,
102
+ speed_ratio: float = 1.0,
103
+ ) -> Throughput:
104
+ gpu = device_for(hw)
105
+ peak = gpu.peak_tflops_bf16 or FALLBACK_PEAK_TFLOPS
106
+ mfu = BASE_MFU
107
+ if hw.gpu_vendor == "apple":
108
+ mfu = 0.25
109
+ if plan.attention == "eager":
110
+ mfu *= EAGER_PENALTY
111
+ if plan.fused_ce:
112
+ mfu *= FUSED_CE_BONUS
113
+ if plan.precision == "fp32":
114
+ mfu *= FP32_PENALTY
115
+
116
+ # Tokens actually computed per micro-batch (padding included unless packed).
117
+ tokens_mb = plan.micro_batch * (plan.max_length if plan.packing else max(mean_len / max(pad_eff, 1e-3), 1))
118
+ k_sat = max(64.0, 8.0 * peak)
119
+ sat = (tokens_mb / (tokens_mb + k_sat)) / (SAT_REF_TOKENS / (SAT_REF_TOKENS + k_sat))
120
+ sat = min(sat, 1.0)
121
+
122
+ fpt = flops_per_token(m, plan, attn_len=mean_len)
123
+ method = METHODS[plan.method]
124
+ eff_flops = peak * 1e12 * mfu * sat
125
+ tps_single = eff_flops / (fpt * method.time_overhead) * caps.speed_prior * speed_ratio
126
+
127
+ n = max(plan.n_gpus, 1)
128
+ scale = 1.0
129
+ if n > 1:
130
+ nv, pcie = _SCALE_EFF.get(plan.parallelism, _SCALE_EFF["ddp"])
131
+ scale = n * (nv if gpu.nvlink else pcie) ** math.log2(n)
132
+ t_compute = tokens_mb / tps_single
133
+
134
+ bottleneck = "compute"
135
+ t_mb = t_compute
136
+ if plan.layer_stream:
137
+ wb = weight_bytes_per_param(method.quant, plan.precision)
138
+ stack_bytes = layer_params(m) * m.num_layers * wb
139
+ h2d = (gpu.h2d_gbs or 12.0) * 1e9 * H2D_EFFICIENCY
140
+ t_transfer = 2.0 * stack_bytes / h2d # forward + backward pass over the stack
141
+ # Perfect overlap would give max(compute, transfer). Real double-buffering never hides
142
+ # everything, so a fraction of the shorter phase is added back (heuristic, see constant).
143
+ t_mb = max(t_compute, t_transfer) + STREAM_OVERLAP_LOSS * min(t_compute, t_transfer)
144
+ if t_transfer > t_compute:
145
+ bottleneck = "transfer"
146
+ raw = tokens_mb / t_mb * scale
147
+ return Throughput(
148
+ raw_tokens_per_s=raw,
149
+ useful_tokens_per_s=raw * pad_eff, # pad_eff = useful / computed tokens for this batching mode
150
+ micro_batch_time_s=t_mb,
151
+ bottleneck=bottleneck,
152
+ mfu=mfu * sat,
153
+ used_peak_tflops=peak,
154
+ )
bitstraining/py.typed ADDED
File without changes