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,138 @@
1
+ """Simulation engine: no model is trained.
2
+
3
+ Purpose: exercise the whole pipeline (planning, orchestration, tracking, eval gates, CLI) on any
4
+ machine without a GPU, and give CI deterministic runs. It produces a synthetic loss curve and
5
+ measurements that deviate from the planner's analytic model by a fixed hidden bias per
6
+ hardware/method, which lets the calibration loop be tested end to end.
7
+
8
+ Everything it writes is labeled `simulated: true`. It must never be used to claim results.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import random
17
+ from dataclasses import replace
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan, HardwareProfile, RunSpec
22
+ from bitstraining.engines.base import Callbacks, Engine, ProbeContext, ProbeResult, RunResult
23
+ from bitstraining.planner.search import estimate_plan
24
+ from bitstraining.planner.throughput import device_for
25
+
26
+
27
+ def _bias(key: str, lo: float, hi: float) -> float:
28
+ h = int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "big") / 2**64
29
+ return lo + (hi - lo) * h
30
+
31
+
32
+ class SimulateEngine(Engine):
33
+ name = "simulate"
34
+
35
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
36
+ return Capabilities(
37
+ name=self.name,
38
+ methods=["full", "lora", "qlora", "dora"],
39
+ precisions=["bf16", "fp16"],
40
+ activation_modes=["none", "selective", "full"],
41
+ optimizers=["adamw", "adamw8bit", "paged_adamw8bit"],
42
+ attention=["flash", "sdpa", "eager"],
43
+ parallelism=["single", "ddp", "fsdp"],
44
+ supports_packing=True,
45
+ supports_layer_stream=True,
46
+ supports_fused_ce=True,
47
+ supports_compile=True,
48
+ tasks=["sft", "dpo", "orpo", "kto", "pretrain"],
49
+ platforms=["cuda", "mps", "cpu"],
50
+ speed_prior=1.0,
51
+ speed_prior_is_measured=True,
52
+ )
53
+
54
+ def probe(self, plan: ExecutionPlan, ctx: ProbeContext, micro_batch: int | None = None) -> ProbeResult:
55
+ p = replace(plan, micro_batch=micro_batch or plan.micro_batch)
56
+ est = estimate_plan(p, ctx.spec, ctx.model, ctx.stats, ctx.hw,
57
+ self.capabilities(ctx.hw), calibration={})
58
+ hk = ctx.hw.key
59
+ peak = est.peak_gb_per_gpu * (1 + _bias(f"{hk}|{p.method}|mem", -0.06, 0.10))
60
+ tps = est.raw_tokens_per_s * (1 + _bias(f"{hk}|{p.method}|speed", -0.20, 0.10))
61
+ vram = device_for(ctx.hw).vram_gb
62
+ fits = peak <= vram
63
+ return ProbeResult(
64
+ fits=fits,
65
+ peak_gb=round(peak, 3),
66
+ tokens_per_s=round(tps, 1) if fits else None,
67
+ steps=3,
68
+ note="simulated measurement",
69
+ )
70
+
71
+ def train(
72
+ self,
73
+ plan: ExecutionPlan,
74
+ spec: RunSpec,
75
+ train_rows: list[dict[str, Any]],
76
+ eval_rows: list[dict[str, Any]] | None,
77
+ callbacks: Callbacks,
78
+ output_dir: Path,
79
+ resume_from: str | None = None,
80
+ ) -> RunResult:
81
+ output_dir.mkdir(parents=True, exist_ok=True)
82
+ total = int(spec.extras.get("max_steps") or plan.total_steps or 100)
83
+ start = 0
84
+ if resume_from and Path(resume_from, "state.json").exists():
85
+ start = int(json.loads(Path(resume_from, "state.json").read_text())["step"])
86
+ rng = random.Random(plan.seed)
87
+ n_rows = max(len(train_rows), 1)
88
+ per_step = max(1, plan.micro_batch * plan.grad_accum * plan.n_gpus)
89
+ order = list(range(n_rows))
90
+ rng.shuffle(order)
91
+ spike_at = spec.extras.get("inject_spike_step")
92
+ tau = max(total / 4, 1.0)
93
+ loss = 0.0
94
+ sim_seconds = 0.0
95
+ stopped = False
96
+ step = start
97
+ for step in range(start + 1, total + 1):
98
+ if callbacks.stop_requested():
99
+ stopped = True
100
+ break
101
+ base = 0.9 + (2.8 - 0.9) * math.exp(-step / tau)
102
+ loss = base + rng.gauss(0, 0.03)
103
+ if spike_at and step == int(spike_at):
104
+ loss += 1.5
105
+ i0 = ((step - 1) * per_step) % n_rows
106
+ batch = [order[(i0 + k) % n_rows] for k in range(per_step)]
107
+ if callbacks.on_batch:
108
+ callbacks.on_batch(step, batch)
109
+ sim_seconds += plan.estimate.step_time_s or 0.0
110
+ callbacks.step(step, {"loss": round(loss, 4), "lr": plan.learning_rate})
111
+ if step % max(total // 5, 1) == 0:
112
+ ck = output_dir / f"checkpoint-{step}"
113
+ ck.mkdir(exist_ok=True)
114
+ (ck / "state.json").write_text(json.dumps({"step": step, "simulated": True}))
115
+ if callbacks.on_checkpoint:
116
+ callbacks.on_checkpoint(str(ck))
117
+ done = step if not stopped else step - 1
118
+ eval_loss = round(loss + 0.08, 4) if eval_rows else None
119
+ summary = {
120
+ "simulated": True,
121
+ "warning": "No model was trained. This directory contains a simulation record only.",
122
+ "steps": done,
123
+ "final_loss": round(loss, 4),
124
+ "plan": plan.to_dict(),
125
+ }
126
+ (output_dir / "run_summary.json").write_text(json.dumps(summary, indent=2))
127
+ return RunResult(
128
+ status="stopped" if stopped else "completed",
129
+ steps=done,
130
+ final_loss=round(loss, 4),
131
+ eval_loss=eval_loss,
132
+ seconds=round(sim_seconds, 2),
133
+ peak_gb=plan.estimate.peak_gb_per_gpu,
134
+ tokens_per_s=plan.estimate.useful_tokens_per_s,
135
+ adapter_path=None,
136
+ simulated=True,
137
+ message="simulated run (no model trained)",
138
+ )
@@ -0,0 +1,66 @@
1
+ """Unsloth adapter (single-GPU fast path).
2
+
3
+ EXPERIMENTAL and not exercised by CI. Reuses the baseline engine's data handling and Trainer loop;
4
+ only model loading differs. Whether it is actually faster on *your* GPU is not assumed: Bitstraining
5
+ gives it the same speed prior as the baseline (1.0) and relies on `bitstraining autotune --bake-off`
6
+ to measure both engines before the planner prefers one.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib.util
12
+ from typing import Any
13
+
14
+ from bitstraining.core.errors import EngineUnavailable
15
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan, HardwareProfile, RunSpec
16
+ from bitstraining.engines.hf_peft import HFPeftEngine
17
+
18
+ _TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
19
+
20
+
21
+ class UnslothEngine(HFPeftEngine):
22
+ name = "unsloth"
23
+
24
+ def capabilities(self, hw: HardwareProfile, assume_installed: bool = False) -> Capabilities:
25
+ cuda = hw.gpu_vendor == "nvidia"
26
+ have = assume_installed or importlib.util.find_spec("unsloth") is not None
27
+ ok = cuda and have
28
+ return Capabilities(
29
+ name=self.name,
30
+ available=ok,
31
+ reason="" if ok else ("needs an NVIDIA GPU" if not cuda else "unsloth not installed (pip install 'bitstraining[fast]')"),
32
+ methods=["lora", "qlora"],
33
+ precisions=["bf16", "fp16"],
34
+ activation_modes=["none", "full"],
35
+ optimizers=["adamw", "adamw8bit"],
36
+ attention=["flash", "sdpa"],
37
+ parallelism=["single"],
38
+ supports_packing=False,
39
+ supports_layer_stream=False,
40
+ supports_fused_ce=True,
41
+ tasks=["sft"],
42
+ platforms=["cuda"],
43
+ speed_prior=1.0,
44
+ speed_prior_is_measured=False,
45
+ )
46
+
47
+ def _load_model(self, plan: ExecutionPlan, spec: RunSpec) -> Any:
48
+ try:
49
+ from unsloth import FastLanguageModel
50
+ except ImportError as e:
51
+ raise EngineUnavailable("unsloth is not installed", fix="pip install 'bitstraining[fast]'") from e
52
+ model, _tok = FastLanguageModel.from_pretrained(
53
+ model_name=spec.model.base,
54
+ max_seq_length=plan.max_length,
55
+ dtype=None,
56
+ load_in_4bit=plan.quant == "nf4",
57
+ )
58
+ return FastLanguageModel.get_peft_model(
59
+ model,
60
+ r=plan.lora_r,
61
+ target_modules=_TARGETS,
62
+ lora_alpha=plan.lora_alpha,
63
+ lora_dropout=plan.lora_dropout,
64
+ use_gradient_checkpointing="unsloth" if plan.activation == "full" else False,
65
+ random_state=plan.seed,
66
+ )
@@ -0,0 +1,17 @@
1
+ """Evaluation: metrics, per-row audit, forgetting check and a pre-deploy gate."""
2
+
3
+ from bitstraining.eval.audit import AuditReport, audit_rows
4
+ from bitstraining.eval.gate import GateCriteria, GateResult, evaluate_gate
5
+ from bitstraining.eval.metrics import METRICS, contains, exact_match, token_f1
6
+
7
+ __all__ = [
8
+ "METRICS",
9
+ "AuditReport",
10
+ "GateCriteria",
11
+ "GateResult",
12
+ "audit_rows",
13
+ "contains",
14
+ "evaluate_gate",
15
+ "exact_match",
16
+ "token_f1",
17
+ ]
@@ -0,0 +1,63 @@
1
+ """Per-row audit: which examples got better, worse, or stayed the same between two models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from bitstraining.core.schemas import Serializable
10
+ from bitstraining.eval.metrics import METRICS, Metric
11
+
12
+
13
+ @dataclass
14
+ class AuditReport(Serializable):
15
+ n: int = 0
16
+ base_mean: float = 0.0
17
+ tuned_mean: float = 0.0
18
+ improved: int = 0
19
+ worse: int = 0
20
+ same: int = 0
21
+ rows: list[dict[str, object]] = field(default_factory=list)
22
+
23
+ @property
24
+ def delta(self) -> float:
25
+ return self.tuned_mean - self.base_mean
26
+
27
+ def summary(self) -> str:
28
+ return (f"{self.n} rows | base {self.base_mean:.3f} -> tuned {self.tuned_mean:.3f} "
29
+ f"({self.delta:+.3f}) | better {self.improved}, worse {self.worse}, same {self.same}")
30
+
31
+ def write(self, path: str | Path) -> None:
32
+ with Path(path).open("w") as f:
33
+ for r in self.rows:
34
+ f.write(json.dumps(r) + "\n")
35
+
36
+
37
+ def audit_rows(
38
+ references: list[str],
39
+ base_preds: list[str],
40
+ tuned_preds: list[str],
41
+ metric: str | Metric = "token_f1",
42
+ prompts: list[str] | None = None,
43
+ tol: float = 1e-9,
44
+ ) -> AuditReport:
45
+ """Score both models on every row and classify each as improved / worse / same."""
46
+ if not (len(references) == len(base_preds) == len(tuned_preds)):
47
+ raise ValueError("references, base_preds and tuned_preds must have equal length")
48
+ fn: Metric = METRICS[metric] if isinstance(metric, str) else metric
49
+ rep = AuditReport(n=len(references))
50
+ if not references:
51
+ return rep
52
+ for i, (ref, b, t) in enumerate(zip(references, base_preds, tuned_preds, strict=True)):
53
+ sb, st = fn(b, ref), fn(t, ref)
54
+ verdict = "improved" if st > sb + tol else "worse" if st < sb - tol else "same"
55
+ setattr(rep, {"improved": "improved", "worse": "worse", "same": "same"}[verdict],
56
+ getattr(rep, verdict) + 1)
57
+ rep.rows.append({"row": i, "prompt": prompts[i] if prompts else None, "base": sb, "tuned": st,
58
+ "verdict": verdict})
59
+ rep.base_mean += sb
60
+ rep.tuned_mean += st
61
+ rep.base_mean /= rep.n
62
+ rep.tuned_mean /= rep.n
63
+ return rep
@@ -0,0 +1,69 @@
1
+ """Pre-deploy gate: block export unless the tuned model wins on the task AND did not forget.
2
+
3
+ Two legs, as in the plan:
4
+ leg 1 task quality: tuned must beat base by at least `min_task_gain` on the task set
5
+ leg 2 forgetting: on a general-capability set the tuned score may drop at most `max_forgetting`
6
+ Optionally a `max_worse_fraction` caps how many individual task rows regressed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+ from bitstraining.core.schemas import Serializable
14
+ from bitstraining.eval.audit import AuditReport
15
+
16
+
17
+ @dataclass
18
+ class GateCriteria(Serializable):
19
+ min_task_gain: float = 0.0
20
+ max_forgetting: float = 0.05
21
+ max_worse_fraction: float | None = None
22
+ require_forgetting_check: bool = True
23
+
24
+
25
+ @dataclass
26
+ class GateResult(Serializable):
27
+ passed: bool = False
28
+ reasons: list[str] = field(default_factory=list)
29
+ task_delta: float | None = None
30
+ forgetting_delta: float | None = None
31
+
32
+ def render(self) -> str:
33
+ head = "GATE PASSED" if self.passed else "GATE FAILED"
34
+ return head + "".join(f"\n - {r}" for r in self.reasons)
35
+
36
+
37
+ def evaluate_gate(
38
+ task: AuditReport,
39
+ general: AuditReport | None = None,
40
+ criteria: GateCriteria | None = None,
41
+ ) -> GateResult:
42
+ c = criteria or GateCriteria()
43
+ res = GateResult(passed=True, task_delta=task.delta)
44
+ if task.n == 0:
45
+ res.passed = False
46
+ res.reasons.append("task set is empty; nothing was measured")
47
+ return res
48
+ if task.delta < c.min_task_gain:
49
+ res.passed = False
50
+ res.reasons.append(f"task gain {task.delta:+.3f} is below the required {c.min_task_gain:+.3f}")
51
+ else:
52
+ res.reasons.append(f"task gain {task.delta:+.3f} meets the required {c.min_task_gain:+.3f}")
53
+ if c.max_worse_fraction is not None:
54
+ frac = task.worse / task.n
55
+ if frac > c.max_worse_fraction:
56
+ res.passed = False
57
+ res.reasons.append(f"{frac:.1%} of task rows got worse (limit {c.max_worse_fraction:.1%})")
58
+ if general is None:
59
+ if c.require_forgetting_check:
60
+ res.passed = False
61
+ res.reasons.append("no general-capability set supplied, so forgetting was not checked")
62
+ else:
63
+ res.forgetting_delta = general.delta
64
+ if general.delta < -c.max_forgetting:
65
+ res.passed = False
66
+ res.reasons.append(f"general capability dropped {general.delta:+.3f} (limit -{c.max_forgetting:.3f})")
67
+ else:
68
+ res.reasons.append(f"general capability change {general.delta:+.3f} is within tolerance")
69
+ return res
@@ -0,0 +1,51 @@
1
+ """Text generation for evaluation. Lazy: needs torch + transformers (+ peft for adapters).
2
+
3
+ Returns a callable `list[str] prompts -> list[str] completions`, which is all the audit needs. Tests and
4
+ custom backends can pass any function with this signature instead.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+
11
+ from bitstraining.core.errors import EngineUnavailable
12
+
13
+ Generator = Callable[[list[str]], list[str]]
14
+
15
+
16
+ def hf_generator(base: str, adapter: str | None = None, max_new_tokens: int = 128, batch_size: int = 8) -> Generator:
17
+ try:
18
+ import torch
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+ except ImportError as e:
21
+ raise EngineUnavailable("generation needs torch and transformers", fix="pip install 'bitstraining[train]'") from e
22
+ tok = AutoTokenizer.from_pretrained(base)
23
+ tok.padding_side = "left"
24
+ if tok.pad_token is None:
25
+ tok.pad_token = tok.eos_token
26
+ model = AutoModelForCausalLM.from_pretrained(
27
+ base, torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
28
+ device_map="auto" if torch.cuda.is_available() else None)
29
+ if adapter:
30
+ from peft import PeftModel
31
+
32
+ model = PeftModel.from_pretrained(model, adapter)
33
+ model.eval()
34
+
35
+ def gen(prompts: list[str]) -> list[str]:
36
+ out: list[str] = []
37
+ for i in range(0, len(prompts), batch_size):
38
+ chunk = prompts[i : i + batch_size]
39
+ texts = [
40
+ tok.apply_chat_template([{"role": "user", "content": p}], tokenize=False, add_generation_prompt=True)
41
+ if getattr(tok, "chat_template", None) else p
42
+ for p in chunk
43
+ ]
44
+ enc = tok(texts, return_tensors="pt", padding=True).to(model.device)
45
+ with torch.no_grad():
46
+ ids = model.generate(**enc, max_new_tokens=max_new_tokens, do_sample=False,
47
+ pad_token_id=tok.pad_token_id)
48
+ out += tok.batch_decode(ids[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
49
+ return out
50
+
51
+ return gen
@@ -0,0 +1,48 @@
1
+ """Reference-based metrics. Each maps (prediction, reference) -> score in [0, 1].
2
+
3
+ For open-ended quality, plug an LLM judge in as any callable with the same signature
4
+ (see `bitstraining.eval.audit.audit_rows(metric=...)`). Judges are not bundled, because a judge model is
5
+ a deployment choice; treat their scores as noisy and audit per row.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import string
12
+ from collections import Counter
13
+ from collections.abc import Callable
14
+
15
+ Metric = Callable[[str, str], float]
16
+
17
+ _ARTICLES = re.compile(r"\b(a|an|the)\b")
18
+
19
+
20
+ def normalize(s: str) -> str:
21
+ s = s.lower()
22
+ s = "".join(ch for ch in s if ch not in set(string.punctuation))
23
+ s = _ARTICLES.sub(" ", s)
24
+ return " ".join(s.split())
25
+
26
+
27
+ def exact_match(pred: str, ref: str) -> float:
28
+ return 1.0 if normalize(pred) == normalize(ref) else 0.0
29
+
30
+
31
+ def contains(pred: str, ref: str) -> float:
32
+ r = normalize(ref)
33
+ return 1.0 if r and r in normalize(pred) else 0.0
34
+
35
+
36
+ def token_f1(pred: str, ref: str) -> float:
37
+ p, r = normalize(pred).split(), normalize(ref).split()
38
+ if not p or not r:
39
+ return 1.0 if p == r else 0.0
40
+ common = Counter(p) & Counter(r)
41
+ n = sum(common.values())
42
+ if n == 0:
43
+ return 0.0
44
+ prec, rec = n / len(p), n / len(r)
45
+ return 2 * prec * rec / (prec + rec)
46
+
47
+
48
+ METRICS: dict[str, Metric] = {"exact_match": exact_match, "contains": contains, "token_f1": token_f1}
@@ -0,0 +1,6 @@
1
+ """Hardware detection, a GPU capability database, and (optional) microbenchmarks."""
2
+
3
+ from bitstraining.hardware.database import GPU_DB, lookup_gpu, synthetic_profile
4
+ from bitstraining.hardware.profiler import profile
5
+
6
+ __all__ = ["GPU_DB", "lookup_gpu", "profile", "synthetic_profile"]
@@ -0,0 +1,125 @@
1
+ """GPU capability table used when a device cannot be benchmarked (or is remote).
2
+
3
+ Numbers are public *dense* bf16/fp16 tensor-core peaks and memory bandwidths, rounded.
4
+ They are priors: the planner treats database-sourced hardware as lower confidence than
5
+ hardware that was measured by `bitstraining profile --benchmark`.
6
+ Add or correct entries freely; names are matched case-insensitively by substring.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from bitstraining.core.schemas import GPUInfo, HardwareProfile
12
+
13
+ # name -> (vram_gb, peak_tflops_bf16, mem_bw_gbs, compute_capability, bf16, fp8, nvlink, h2d_gbs)
14
+ _ROWS: dict[str, tuple[float, float, float, str, bool, bool, bool, float]] = {
15
+ "rtx 3050 laptop 4gb": (4, 18, 192, "8.6", True, False, False, 12),
16
+ "rtx 3050": (8, 36, 224, "8.6", True, False, False, 12),
17
+ "rtx 3060": (12, 51, 360, "8.6", True, False, False, 12),
18
+ "rtx 3070": (8, 81, 448, "8.6", True, False, False, 12),
19
+ "rtx 3080": (10, 119, 760, "8.6", True, False, False, 12),
20
+ "rtx 3090": (24, 142, 936, "8.6", True, False, False, 12),
21
+ "rtx 4060": (8, 60, 272, "8.9", True, True, False, 12),
22
+ "rtx 4070": (12, 117, 504, "8.9", True, True, False, 12),
23
+ "rtx 4080": (16, 195, 717, "8.9", True, True, False, 12),
24
+ "rtx 4090": (24, 330, 1008, "8.9", True, True, False, 12),
25
+ "rtx 5090": (32, 420, 1790, "12.0", True, True, False, 24),
26
+ "t4": (16, 65, 320, "7.5", False, False, False, 12),
27
+ "v100": (32, 112, 900, "7.0", False, False, True, 12),
28
+ "l4": (24, 121, 300, "8.9", True, True, False, 12),
29
+ "a10g": (24, 125, 600, "8.6", True, False, False, 12),
30
+ "a10": (24, 125, 600, "8.6", True, False, False, 12),
31
+ "l40s": (48, 362, 864, "8.9", True, True, False, 24),
32
+ "a100-40gb": (40, 312, 1555, "8.0", True, False, True, 24),
33
+ "a100-80gb": (80, 312, 2039, "8.0", True, False, True, 24),
34
+ "a100": (40, 312, 1555, "8.0", True, False, True, 24),
35
+ "h100": (80, 990, 3350, "9.0", True, True, True, 48),
36
+ "h200": (141, 990, 4800, "9.0", True, True, True, 48),
37
+ "b200": (180, 2250, 8000, "10.0", True, True, True, 48),
38
+ "mi300x": (192, 1307, 5300, "gfx942", True, True, True, 48),
39
+ # Apple Silicon (unified memory; vram_gb is a usable share of system memory)
40
+ "apple m1": (10, 2.6, 68, "mps", False, False, False, 60),
41
+ "apple m2": (12, 3.6, 100, "mps", False, False, False, 80),
42
+ "apple m3": (12, 4.1, 100, "mps", False, False, False, 80),
43
+ "apple m4": (12, 4.6, 120, "mps", False, False, False, 90),
44
+ }
45
+
46
+ GPU_DB = {
47
+ k: dict(
48
+ vram_gb=v[0],
49
+ peak_tflops_bf16=v[1],
50
+ mem_bw_gbs=v[2],
51
+ compute_capability=v[3],
52
+ bf16=v[4],
53
+ fp8=v[5],
54
+ nvlink=v[6],
55
+ h2d_gbs=v[7],
56
+ )
57
+ for k, v in _ROWS.items()
58
+ }
59
+
60
+
61
+ def lookup_gpu(name: str, vram_gb: float | None = None) -> GPUInfo:
62
+ """Best-effort match of a device name to the database.
63
+
64
+ Longest key contained in `name` wins ("rtx 3050 laptop 4gb" beats "rtx 3050").
65
+ Unknown devices get conservative numbers and `source="database"` with zero peak
66
+ so the planner reports low confidence.
67
+ """
68
+ low = name.lower().replace("nvidia", "").replace("geforce", "").strip()
69
+ low = " ".join(low.split())
70
+ best = None
71
+ for key in sorted(GPU_DB, key=len, reverse=True):
72
+ if key in low or key.replace("-", " ") in low.replace("-", " "):
73
+ best = key
74
+ break
75
+ if best is not None and vram_gb is None:
76
+ # Names like "A100-SXM4-80GB" carry the memory size: prefer the family variant that matches it.
77
+ import re
78
+
79
+ m = re.search(r"(\d+)\s*gb", low)
80
+ if m:
81
+ family = best.split("-")[0].split(" ")[0]
82
+ for key, row in GPU_DB.items():
83
+ if key.split("-")[0].split(" ")[0] == family and row["vram_gb"] == float(m.group(1)):
84
+ best = key
85
+ break
86
+ if best is None and vram_gb is not None:
87
+ # Pick by closest VRAM as a very rough prior.
88
+ return GPUInfo(
89
+ name=name,
90
+ vram_gb=vram_gb,
91
+ peak_tflops_bf16=0.0,
92
+ mem_bw_gbs=0.0,
93
+ bf16=False,
94
+ source="database",
95
+ )
96
+ if best is None:
97
+ return GPUInfo(name=name, source="database")
98
+ row = dict(GPU_DB[best])
99
+ if vram_gb:
100
+ row["vram_gb"] = vram_gb # trust the detected size over the table
101
+ return GPUInfo(name=name, source="database", **row) # type: ignore[arg-type]
102
+
103
+
104
+ def synthetic_profile(
105
+ gpu: str, n_gpus: int = 1, price_per_hour: float | None = None
106
+ ) -> HardwareProfile:
107
+ """A hardware profile for machines we cannot touch (rented GPUs, what-if planning)."""
108
+ g = lookup_gpu(gpu)
109
+ if g.peak_tflops_bf16 == 0:
110
+ raise ValueError(f"unknown GPU '{gpu}'. Known: {', '.join(sorted(GPU_DB))}")
111
+ g.name = gpu
112
+ return HardwareProfile(
113
+ name=f"{gpu} x{n_gpus} (planned)",
114
+ os="linux",
115
+ cpu_model="planned",
116
+ cpu_cores=max(8, 8 * n_gpus),
117
+ ram_gb=max(64.0, 64.0 * n_gpus),
118
+ disk_free_gb=500.0,
119
+ disk_read_gbs=2.0,
120
+ gpu_vendor="nvidia",
121
+ gpus=[GPUInfo(**g.to_dict()) for _ in range(n_gpus)],
122
+ price_per_hour=price_per_hour,
123
+ provider="planned",
124
+ measured=False,
125
+ )