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
bitstraining/runner.py ADDED
@@ -0,0 +1,71 @@
1
+ """Entry point executed on the compute target: `python -m bitstraining.runner --bundle DIR`.
2
+
3
+ Reads spec.yaml + plan.json from the bundle, loads and cleans the data, runs the chosen engine and writes
4
+ results into DIR/output. Progress is printed as `BT_METRIC {json}` lines, which the orchestrator relays.
5
+ It deliberately imports nothing heavy until the engine needs it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+
16
+
17
+ def _latest_checkpoint(out: Path) -> str | None:
18
+ cks = [p for p in out.glob("checkpoint-*") if p.is_dir()]
19
+ if not cks:
20
+ return None
21
+ return str(max(cks, key=lambda p: int(p.name.split("-")[-1])))
22
+
23
+
24
+ def main(argv: list[str] | None = None) -> int:
25
+ ap = argparse.ArgumentParser(prog="bitstraining.runner")
26
+ ap.add_argument("--bundle", required=True)
27
+ ap.add_argument("--resume", action="store_true")
28
+ a = ap.parse_args(argv)
29
+
30
+ from bitstraining.core import registry
31
+ from bitstraining.core.config import load_plan, load_spec
32
+ from bitstraining.data.clean import clean_rows
33
+ from bitstraining.data.loaders import read_rows
34
+ from bitstraining.data.schema import detect_schema
35
+ from bitstraining.data.split import split_rows
36
+ from bitstraining.engines.base import Callbacks
37
+
38
+ bundle = Path(a.bundle).resolve()
39
+ spec = load_spec(bundle / "spec.yaml")
40
+ plan = load_plan(bundle / "plan.json")
41
+ out = (bundle / spec.output).resolve()
42
+ out.mkdir(parents=True, exist_ok=True)
43
+
44
+ raw = read_rows(bundle / spec.data.train)
45
+ schema = detect_schema(raw) if spec.data.format == "auto" else spec.data.format
46
+ rows, rep = clean_rows(raw, schema, dedup=spec.data.dedup)
47
+ eval_rows = None
48
+ if spec.data.eval:
49
+ eval_rows, _ = clean_rows(read_rows(bundle / spec.data.eval), schema, dedup=False)
50
+ elif spec.data.eval_split > 0:
51
+ rows, eval_rows = split_rows(rows, spec.data.eval_split, spec.goal.seed)
52
+ print(f"runner: {len(rows)} train rows ({rep.malformed} malformed, {rep.empty} empty, "
53
+ f"{rep.exact_duplicates} duplicates dropped); engine={plan.engine}", flush=True)
54
+
55
+ def on_step(step: int, m: dict[str, float]) -> None:
56
+ print("BT_METRIC " + json.dumps({"step": step, **m}), flush=True)
57
+
58
+ cb = Callbacks(on_step=on_step, log=lambda s: print(s, flush=True))
59
+ engine = registry.create("engines", plan.engine)
60
+ resume = _latest_checkpoint(out) if a.resume else None
61
+ if resume:
62
+ print(f"runner: resuming from {resume}", flush=True)
63
+ t0 = time.time()
64
+ res = engine.train(plan, spec, rows, eval_rows, cb, out, resume_from=resume)
65
+ (out / "result.json").write_text(json.dumps({**res.to_dict(), "wall_seconds": time.time() - t0}, indent=2))
66
+ print(f"runner: {res.status} steps={res.steps} loss={res.final_loss}", flush=True)
67
+ return 0 if res.status in ("completed", "stopped") else 1
68
+
69
+
70
+ if __name__ == "__main__":
71
+ sys.exit(main())
@@ -0,0 +1,10 @@
1
+ """Training strategies: method definitions shared by every engine (portable across backends)."""
2
+
3
+ from bitstraining.strategies.catalog import (
4
+ METHODS,
5
+ OPTIMIZER_STATE_BYTES,
6
+ Method,
7
+ weight_bytes_per_param,
8
+ )
9
+
10
+ __all__ = ["METHODS", "OPTIMIZER_STATE_BYTES", "Method", "weight_bytes_per_param"]
@@ -0,0 +1,42 @@
1
+ """Method catalog: how each fine-tuning method changes memory and compute.
2
+
3
+ These are *modeling constants*, documented so they can be audited and corrected by the
4
+ calibration loop. Values marked (heuristic) are engineering estimates, not measurements.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Method:
14
+ name: str
15
+ full_weights_trainable: bool # all base weights receive gradients
16
+ quant: str # "none" | "nf4"
17
+ compute_multiplier: float # x forward FLOPs for fwd+bwd (frozen base skips weight-grad matmuls)
18
+ time_overhead: float # extra wall-time factor (dequantization etc.) (heuristic)
19
+ description: str
20
+
21
+
22
+ METHODS: dict[str, Method] = {
23
+ "full": Method("full", True, "none", 3.0, 1.0, "Update every weight. Highest memory, no adapter."),
24
+ "lora": Method("lora", False, "none", 2.0, 1.0, "Low-rank adapters on a frozen bf16 base."),
25
+ "qlora": Method("qlora", False, "nf4", 2.0, 1.20, "LoRA on a 4-bit NF4-quantized frozen base. (overhead: heuristic)"),
26
+ "dora": Method("dora", False, "none", 2.0, 1.25, "Weight-decomposed LoRA. (overhead: heuristic)"),
27
+ }
28
+
29
+ # Bytes of optimizer state per *trainable* parameter.
30
+ OPTIMIZER_STATE_BYTES: dict[str, float] = {
31
+ "adamw": 8.0, # fp32 m and v
32
+ "adamw8bit": 2.0, # 8-bit m and v
33
+ "paged_adamw8bit": 2.0, # same, and pages to host memory under pressure
34
+ }
35
+
36
+ NF4_BYTES_PER_PARAM = 0.53 # 4 bits + per-block constants (double quantization ~0.516)
37
+
38
+
39
+ def weight_bytes_per_param(quant: str, precision: str) -> float:
40
+ if quant == "nf4":
41
+ return NF4_BYTES_PER_PARAM
42
+ return {"bf16": 2.0, "fp16": 2.0, "fp32": 4.0}[precision]
@@ -0,0 +1,5 @@
1
+ """Run registry, metrics, lineage."""
2
+
3
+ from bitstraining.tracking.registry import Registry, find_loss_spikes
4
+
5
+ __all__ = ["Registry", "find_loss_spikes"]
@@ -0,0 +1,208 @@
1
+ """Local SQLite registry of runs, plans, metrics, artifacts and lineage.
2
+
3
+ Lineage chain: data content hash -> run -> artifacts (adapter, exports) -> eval results.
4
+ Optional per-step batch row ids let a loss spike be traced back to the rows that caused it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import secrets
12
+ import sqlite3
13
+ import statistics
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from bitstraining.core import paths
19
+
20
+ _SCHEMA = """
21
+ CREATE TABLE IF NOT EXISTS runs (
22
+ id TEXT PRIMARY KEY, name TEXT, created REAL, finished REAL, status TEXT,
23
+ engine TEXT, simulated INTEGER, data_hash TEXT,
24
+ spec_json TEXT, plan_json TEXT, hardware_json TEXT, result_json TEXT
25
+ );
26
+ CREATE TABLE IF NOT EXISTS metrics (
27
+ run_id TEXT, step INTEGER, key TEXT, value REAL
28
+ );
29
+ CREATE INDEX IF NOT EXISTS idx_metrics ON metrics (run_id, key, step);
30
+ CREATE TABLE IF NOT EXISTS batches (run_id TEXT, step INTEGER, rows_json TEXT);
31
+ CREATE INDEX IF NOT EXISTS idx_batches ON batches (run_id, step);
32
+ CREATE TABLE IF NOT EXISTS artifacts (
33
+ run_id TEXT, kind TEXT, path TEXT, sha256 TEXT, created REAL
34
+ );
35
+ CREATE TABLE IF NOT EXISTS evals (
36
+ run_id TEXT, name TEXT, created REAL, result_json TEXT
37
+ );
38
+ """
39
+
40
+
41
+ def _sha256_path(p: Path) -> str:
42
+ h = hashlib.sha256()
43
+ if p.is_file():
44
+ with p.open("rb") as f:
45
+ for chunk in iter(lambda: f.read(1 << 20), b""):
46
+ h.update(chunk)
47
+ elif p.is_dir():
48
+ for f in sorted(p.rglob("*")):
49
+ if f.is_file():
50
+ h.update(str(f.relative_to(p)).encode())
51
+ h.update(str(f.stat().st_size).encode())
52
+ return h.hexdigest()[:16]
53
+
54
+
55
+ def find_loss_spikes(
56
+ steps: list[int], losses: list[float], window: int = 20, z: float = 4.0
57
+ ) -> list[tuple[int, float, float]]:
58
+ """Robust spike detector: a loss is a spike if it exceeds the trailing median by `z` robust
59
+ standard deviations (1.4826 * MAD). Returns (step, loss, score) tuples."""
60
+ out: list[tuple[int, float, float]] = []
61
+ for i in range(len(losses)):
62
+ prev = losses[max(0, i - window) : i]
63
+ if len(prev) < 5:
64
+ continue
65
+ med = statistics.median(prev)
66
+ mad = statistics.median([abs(x - med) for x in prev])
67
+ scale = max(1.4826 * mad, 0.02 * max(abs(med), 1e-6), 1e-6)
68
+ score = (losses[i] - med) / scale
69
+ if score > z:
70
+ out.append((steps[i], losses[i], round(score, 2)))
71
+ return out
72
+
73
+
74
+ class Registry:
75
+ def __init__(self, path: str | Path | None = None):
76
+ self.path = Path(path) if path else paths.registry_db()
77
+ self.path.parent.mkdir(parents=True, exist_ok=True)
78
+ self._db = sqlite3.connect(self.path)
79
+ self._db.row_factory = sqlite3.Row
80
+ with self._db:
81
+ self._db.executescript(_SCHEMA)
82
+
83
+ def close(self) -> None:
84
+ self._db.close()
85
+
86
+ def __enter__(self) -> Registry:
87
+ return self
88
+
89
+ def __exit__(self, *a: object) -> None:
90
+ self.close()
91
+
92
+ # ---------------------------------------------------------------- runs
93
+ def create_run(
94
+ self,
95
+ name: str,
96
+ spec: dict[str, Any],
97
+ plan: dict[str, Any],
98
+ hardware: dict[str, Any],
99
+ data_hash: str,
100
+ engine: str,
101
+ simulated: bool = False,
102
+ ) -> str:
103
+ run_id = f"run-{time.strftime('%Y%m%d-%H%M%S')}-{secrets.token_hex(2)}"
104
+ with self._db:
105
+ self._db.execute(
106
+ "INSERT INTO runs (id,name,created,status,engine,simulated,data_hash,spec_json,plan_json,hardware_json)"
107
+ " VALUES (?,?,?,?,?,?,?,?,?,?)",
108
+ (run_id, name, time.time(), "running", engine, int(simulated), data_hash,
109
+ json.dumps(spec), json.dumps(plan), json.dumps(hardware)),
110
+ )
111
+ return run_id
112
+
113
+ def finish_run(self, run_id: str, status: str, result: dict[str, Any] | None = None) -> None:
114
+ with self._db:
115
+ self._db.execute(
116
+ "UPDATE runs SET status=?, finished=?, result_json=? WHERE id=?",
117
+ (status, time.time(), json.dumps(result or {}), run_id),
118
+ )
119
+
120
+ def get_run(self, run_id: str) -> dict[str, Any] | None:
121
+ row = self._db.execute("SELECT * FROM runs WHERE id=?", (run_id,)).fetchone()
122
+ if not row:
123
+ return None
124
+ d = dict(row)
125
+ for k in ("spec_json", "plan_json", "hardware_json", "result_json"):
126
+ d[k[:-5]] = json.loads(d.pop(k) or "null")
127
+ return d
128
+
129
+ def list_runs(self, limit: int = 20) -> list[dict[str, Any]]:
130
+ rows = self._db.execute(
131
+ "SELECT id,name,created,status,engine,simulated,data_hash FROM runs ORDER BY created DESC LIMIT ?",
132
+ (limit,),
133
+ ).fetchall()
134
+ return [dict(r) for r in rows]
135
+
136
+ def latest_run_id(self) -> str | None:
137
+ r = self._db.execute("SELECT id FROM runs ORDER BY created DESC LIMIT 1").fetchone()
138
+ return r["id"] if r else None
139
+
140
+ # ---------------------------------------------------------------- metrics
141
+ def log_metrics(self, run_id: str, step: int, metrics: dict[str, float]) -> None:
142
+ with self._db:
143
+ self._db.executemany(
144
+ "INSERT INTO metrics (run_id,step,key,value) VALUES (?,?,?,?)",
145
+ [(run_id, step, k, float(v)) for k, v in metrics.items()],
146
+ )
147
+
148
+ def metric(self, run_id: str, key: str) -> list[tuple[int, float]]:
149
+ rows = self._db.execute(
150
+ "SELECT step,value FROM metrics WHERE run_id=? AND key=? ORDER BY step", (run_id, key)
151
+ ).fetchall()
152
+ return [(r["step"], r["value"]) for r in rows]
153
+
154
+ def log_batch(self, run_id: str, step: int, row_ids: list[int]) -> None:
155
+ with self._db:
156
+ self._db.execute(
157
+ "INSERT INTO batches (run_id,step,rows_json) VALUES (?,?,?)",
158
+ (run_id, step, json.dumps(row_ids)),
159
+ )
160
+
161
+ def rows_for_steps(self, run_id: str, steps: list[int]) -> dict[int, list[int]]:
162
+ if not steps:
163
+ return {}
164
+ q = ",".join("?" * len(steps))
165
+ rows = self._db.execute(
166
+ f"SELECT step,rows_json FROM batches WHERE run_id=? AND step IN ({q})", [run_id, *steps]
167
+ ).fetchall()
168
+ return {r["step"]: json.loads(r["rows_json"]) for r in rows}
169
+
170
+ def loss_spikes(self, run_id: str, window: int = 20, z: float = 4.0) -> list[dict[str, Any]]:
171
+ series = self.metric(run_id, "loss")
172
+ spikes = find_loss_spikes([s for s, _ in series], [v for _, v in series], window, z)
173
+ rows = self.rows_for_steps(run_id, [s for s, _, _ in spikes])
174
+ return [{"step": s, "loss": v, "score": sc, "rows": rows.get(s, [])} for s, v, sc in spikes]
175
+
176
+ # ---------------------------------------------------------------- artifacts / evals / lineage
177
+ def add_artifact(self, run_id: str, kind: str, path: str | Path) -> str:
178
+ p = Path(path)
179
+ digest = _sha256_path(p)
180
+ with self._db:
181
+ self._db.execute(
182
+ "INSERT INTO artifacts (run_id,kind,path,sha256,created) VALUES (?,?,?,?,?)",
183
+ (run_id, kind, str(p), digest, time.time()),
184
+ )
185
+ return digest
186
+
187
+ def add_eval(self, run_id: str, name: str, result: dict[str, Any]) -> None:
188
+ with self._db:
189
+ self._db.execute(
190
+ "INSERT INTO evals (run_id,name,created,result_json) VALUES (?,?,?,?)",
191
+ (run_id, name, time.time(), json.dumps(result)),
192
+ )
193
+
194
+ def lineage(self, run_id: str) -> dict[str, Any]:
195
+ run = self.get_run(run_id)
196
+ if not run:
197
+ raise KeyError(run_id)
198
+ arts = [dict(r) for r in self._db.execute(
199
+ "SELECT kind,path,sha256 FROM artifacts WHERE run_id=? ORDER BY created", (run_id,))]
200
+ evals = [{"name": r["name"], "result": json.loads(r["result_json"])} for r in self._db.execute(
201
+ "SELECT name,result_json FROM evals WHERE run_id=? ORDER BY created", (run_id,))]
202
+ siblings = [r["id"] for r in self._db.execute(
203
+ "SELECT id FROM runs WHERE data_hash=? AND id<>? ORDER BY created", (run["data_hash"], run_id))]
204
+ return {
205
+ "data_hash": run["data_hash"], "run": run_id, "base": (run["spec"] or {}).get("model", {}).get("base"),
206
+ "engine": run["engine"], "simulated": bool(run["simulated"]), "artifacts": arts,
207
+ "evals": evals, "other_runs_on_same_data": siblings,
208
+ }
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: bitstraining
3
+ Version: 0.1.0
4
+ Summary: Hardware-aware AI model training, fine-tuning, optimization and deployment framework.
5
+ Author: Bitstraining contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Sudharsansm/bitstraining
8
+ Project-URL: Repository, https://github.com/Sudharsansm/bitstraining
9
+ Project-URL: Issues, https://github.com/Sudharsansm/bitstraining/issues
10
+ Project-URL: Changelog, https://github.com/Sudharsansm/bitstraining/blob/main/CHANGELOG.md
11
+ Keywords: llm,fine-tuning,training,planner,lora,qlora,gpu
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: pyyaml>=6.0
24
+ Provides-Extra: train
25
+ Requires-Dist: torch>=2.3; extra == "train"
26
+ Requires-Dist: transformers>=4.44; extra == "train"
27
+ Requires-Dist: peft>=0.11; extra == "train"
28
+ Requires-Dist: datasets>=2.19; extra == "train"
29
+ Requires-Dist: accelerate>=0.30; extra == "train"
30
+ Provides-Extra: quant
31
+ Requires-Dist: bitsandbytes>=0.43; extra == "quant"
32
+ Provides-Extra: fast
33
+ Requires-Dist: unsloth; extra == "fast"
34
+ Provides-Extra: mlx
35
+ Requires-Dist: mlx-lm; extra == "mlx"
36
+ Provides-Extra: parquet
37
+ Requires-Dist: pyarrow>=14; extra == "parquet"
38
+ Provides-Extra: numpy
39
+ Requires-Dist: numpy>=1.26; extra == "numpy"
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=8; extra == "dev"
42
+ Requires-Dist: ruff>=0.5; extra == "dev"
43
+ Requires-Dist: mypy>=1.10; extra == "dev"
44
+ Requires-Dist: types-PyYAML; extra == "dev"
45
+ Dynamic: license-file
46
+
47
+ <div align="center">
48
+
49
+ <a href="docs/bitstraining.png"><img src="docs/bitstraining.png" alt="Bitstraining" width="200"></a>
50
+
51
+ # Bitstraining
52
+
53
+ <a href="https://pypi.org/project/bitstraining/"><img src="https://img.shields.io/pypi/v/bitstraining.svg" alt="PyPI version"></a>
54
+ <a href="https://pypi.org/project/bitstraining/"><img src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue.svg" alt="Python versions"></a>
55
+ <a href="https://github.com/Sudharsansm/bitstraining/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Sudharsansm/bitstraining.svg" alt="License"></a>
56
+
57
+ **Train. Fine-tune. Optimize. Deploy.**
58
+
59
+ </div>
60
+
61
+ Bitstraining is a hardware-aware orchestration layer for fine-tuning language models. You describe a
62
+ *goal and constraints* (model, data, time or budget); it profiles the hardware, **predicts memory,
63
+ speed and cost for many candidate strategies, ranks them**, checks your setup before any GPU time is
64
+ spent, verifies the winner with a short real probe, runs it locally or on other compute, and tracks
65
+ everything that happened.
66
+
67
+ It does not reimplement training. PyTorch / Transformers / PEFT, Unsloth and MLX stay swappable
68
+ engines behind one small interface. The part that is Bitstraining's own is the planner, the compute
69
+ orchestration, the data tooling, evaluation gate, and run tracking.
70
+
71
+ > **Read [Status & honesty](#status--honesty) before relying on any number.** The planner's
72
+ > predictions are model-based estimates that have **not** been validated against real GPU runs yet, and
73
+ > nothing here has been benchmarked against other tools. The mechanism is built to make that
74
+ > measurement easy (`bitstraining autotune`), not to assume the answer.
75
+
76
+ ```
77
+ goal + constraints ─► hardware profile ─► cost model ─► ranked plans ─► doctor ─► probe/autotune
78
+ │
79
+ model card ◄─ eval gate ◄─ tracked run ◄─ engine (HF/PEFT, Unsloth, MLX) ◄─ compute (local/ssh/docker/notebook)
80
+ ```
81
+
82
+ ## Install
83
+
84
+ ```bash
85
+ pip install bitstraining # core: planner, data tools, tracking, orchestration, eval. Needs only PyYAML.
86
+ pip install "bitstraining[train]" # + torch, transformers, peft, datasets, accelerate (real training)
87
+ pip install "bitstraining[train,quant]" # + bitsandbytes (QLoRA, 8-bit optimizers)
88
+ pip install "bitstraining[fast]" # + unsloth | "[mlx]" for Apple Silicon | "[parquet]"
89
+ ```
90
+
91
+ (From a source checkout, use `pip install .` and `pip install ".[train]"` instead. Docker is never
92
+ required; the optional `docker` compute provider is only used if you select it.)
93
+
94
+ Python 3.10+ (the CPU test suite passes on 3.10, 3.11, 3.12 and 3.13 on Linux).
95
+
96
+ With [uv](https://docs.astral.sh/uv/) (verified: `uv venv`, `uv pip install -e ".[dev]"`, `uv run`, `uv tool install`):
97
+
98
+ ```bash
99
+ uv venv && uv pip install -e ".[dev]"
100
+ uv run pytest
101
+ uv tool install . # puts `bitstraining` and `bt` on your PATH
102
+ ```
103
+
104
+ **Platforms:** developed and tested on Linux. A run on Windows 11 found and fixed a RAM-detection bug (see
105
+ CHANGELOG); Windows has not been re-verified since, and macOS has not been tested. Please report problems.
106
+
107
+ ## Try it in 30 seconds, no GPU needed
108
+
109
+ ```bash
110
+ bitstraining quickstart
111
+ ```
112
+
113
+ This runs the whole pipeline (load data, plan, doctor, run, track) with the **simulation engine**,
114
+ which trains nothing and labels every artifact `simulated`. It exists so you can see the system work
115
+ and so CI can test orchestration without hardware.
116
+
117
+ ## A real workflow
118
+
119
+ ```bash
120
+ bitstraining init --template chat -o run.yaml # starter config; edit model.base and data.train
121
+ bitstraining data inspect data/train.jsonl # schema, token stats, truncation, padding waste
122
+ bitstraining profile # what hardware you actually have
123
+
124
+ bitstraining plan -c run.yaml # ranked plans for THIS machine
125
+ bitstraining plan -c run.yaml --gpu a100-80gb --price 2.5 # what-if for rented hardware, with cost
126
+ bitstraining doctor -c run.yaml # pre-flight: errors come with fixes
127
+ bitstraining autotune -c run.yaml # real probe: finds the micro-batch, calibrates the model
128
+ bitstraining train -c run.yaml --tune # plan -> check -> run -> track
129
+
130
+ bitstraining runs list # history
131
+ bitstraining runs spikes # trace a loss spike back to the training rows
132
+ bitstraining eval --task preds.jsonl --general general.jsonl # per-row audit + forgetting gate
133
+ bitstraining card # model card with data hash and lineage
134
+ bitstraining serve --model ./output --backend vllm # prints/starts an OpenAI-compatible server
135
+ ```
136
+
137
+ `run.yaml`:
138
+
139
+ ```yaml
140
+ name: support-bot
141
+ model: { base: meta-llama/Llama-3.1-8B-Instruct }
142
+ data: { train: ./data/train.jsonl, max_length: 1024, eval_split: 0.05 }
143
+ goal: { task: sft, epochs: 3, global_batch_size: 16, objective: time, budget_usd: 20 }
144
+ compute: { provider: local } # or ssh / docker / notebook (see below)
145
+ output: ./output
146
+ ```
147
+
148
+ ## What it does
149
+
150
+ | Area | Capability |
151
+ |---|---|
152
+ | **Planner** | Analytic GPU-memory model (weights, adapters, gradients, optimizer, activations, logits, context) and roofline throughput model. Searches method (full / LoRA / QLoRA / DoRA), activation checkpointing, optimizer (AdamW / 8-bit / paged), micro-batch, packing, attention kernel, FSDP/DDP. Ranks by time, cost or memory and respects budgets. |
153
+ | **Honest uncertainty** | Every plan carries a confidence level. It is `low` until a real probe has calibrated the model on your hardware. |
154
+ | **Doctor** | ~30 pre-flight checks (config sanity, schema/task mismatch, truncation, duplicates, train/eval leakage, resource fit, missing packages) each with a concrete fix. |
155
+ | **Autotune** | OOM-safe binary search for the largest micro-batch (a good hint costs 2-3 probes); learns measured/predicted ratios per hardware+engine+method; caches results. |
156
+ | **Data** | JSONL/JSON/CSV/TSV/TXT/Parquet/HF; auto schema detection (alpaca, chat, ShareGPT, prompt/completion, preference, raw text); cleaning; exact + MinHash near-duplicate removal; leakage-safe splits; packing and padding-waste analysis. |
157
+ | **Compute** | One job description, many places: `local` (subprocess), `ssh` (any GPU box), `docker`, `notebook` (self-running Colab/Kaggle notebook), `catalog` (illustrative price list for planning). Hard budget cap, wall-clock cap, auto-resume after preemption, guaranteed teardown. |
158
+ | **Tracking** | SQLite registry: runs, plans, metrics, artifacts with hashes, lineage from data hash to model. Per-step batch row ids let a loss spike be traced to the rows behind it. |
159
+ | **Eval** | Metrics, per-row better/worse/same audit, forgetting check, and a gate that blocks export on regressions. Pluggable judge: any `(prediction, reference) -> float`. |
160
+ | **Deploy** | Model cards, merge LoRA into base, GGUF export via llama.cpp, serve via vLLM or llama.cpp. |
161
+
162
+ ## Compute targets
163
+
164
+ ```yaml
165
+ compute: { provider: ssh, options: { host: ubuntu@203.0.113.7, gpu: a100-80gb, price_per_hour: 1.9 } }
166
+ compute: { provider: docker, options: { image: pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime } }
167
+ compute: { provider: notebook, options: { target: colab } } # writes a notebook; you press Run all
168
+ ```
169
+
170
+ The runner ships inside a *bundle* (spec, plan, data, a copy of this package), so remote machines
171
+ don't need Bitstraining installed. Colab and Kaggle cannot be driven unattended, so the notebook provider is
172
+ deliberately manual: it embeds the bundle in one notebook and you download `output.zip` afterwards
173
+ (`bitstraining compute fetch --zip output.zip`).
174
+
175
+ ## Extending
176
+
177
+ Engines and providers are plugins, discovered through Python entry points (or `registry.register(...)`
178
+ at runtime). See [docs/plugins.md](docs/plugins.md) and `examples/custom_provider.py`.
179
+
180
+ ## Status & honesty
181
+
182
+ This table is the source of truth. "Verified" means exercised by the automated test suite
183
+ (the CPU-only test suite, including real subprocess jobs); it does **not** mean validated on GPUs.
184
+
185
+ | Component | State |
186
+ |---|---|
187
+ | Planner (memory, throughput, search, doctor), calibration, autotune loop | **Verified** logic; parameter counts checked against published sizes (<1% error for 7 models). **Not validated** against real GPU measurements. |
188
+ | Data pipeline, tracking, eval/gate, model cards, orchestrator, bundle, local subprocess provider, notebook builder | **Verified** by tests, including mutation checks on the critical logic. |
189
+ | `hf_peft` engine | **Written, never run** against real torch/GPU in this repo (no GPU available during development). Prompt masking and tokenization logic is unit-tested with a stub tokenizer. Treat first use as a smoke test. |
190
+ | `unsloth`, `mlx` engines | **Written, never run.** Experimental. |
191
+ | `ssh`, `docker` providers | Command construction **unit-tested**; **never run** against a real host/daemon. |
192
+ | Layer streaming, FSDP/DeepSpeed, DPO/ORPO/KTO/GRPO training, pruning, distillation | **Not implemented.** The planner can *model* streaming and FSDP; no bundled real engine executes them. Preference tasks are rejected cleanly at planning time. |
193
+ | Web UI, MCP server, real cloud provisioning (RunPod, Lambda, AWS...) | **Not implemented.** `catalog` is a planning-only price list with illustrative numbers. |
194
+
195
+ **On "faster and more efficient".** The efficiency mechanisms that exist are: choosing QLoRA/LoRA vs full
196
+ fine-tuning by what fits, activation checkpointing only when memory demands it, 8-bit optimizers,
197
+ packing/length-grouping to cut padding waste, largest-safe micro-batch search, and cost-aware hardware
198
+ comparison. The planner quantifies their *predicted* effect. **No benchmark here shows Bitstraining
199
+ trains faster than Axolotl, LLaMA-Factory, Unsloth or plain Transformers**, and none should be assumed.
200
+ Speed-ups quoted by other libraries are theirs, not ours; use `bitstraining autotune` to measure on
201
+ your hardware.
202
+
203
+ Model constants that are heuristics, not measurements (all in one place, all tunable by calibration):
204
+ base MFU 0.42, QLoRA time overhead 1.20, DoRA 1.25, layer-streaming overlap loss 0.30, token
205
+ estimate of 3.8 characters per token when no tokenizer is available, and the GPU table's peak-FLOP
206
+ figures.
207
+
208
+ ## Documentation
209
+
210
+ * [Architecture](docs/architecture.md): how the planner, engines, compute providers and tracking fit together
211
+ * [Writing plugins](docs/plugins.md): custom engines and compute providers (`examples/custom_provider.py`)
212
+ * [Releasing](RELEASING.md): publishing to PyPI from GitHub
213
+ * [Changelog](CHANGELOG.md): includes which earlier *results* a fix could have affected
214
+
215
+ ## Development
216
+
217
+ ```bash
218
+ pip install -e ".[dev]"
219
+ pytest # a few seconds, no GPU
220
+ ruff check bitstraining tests
221
+ ```
222
+
223
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
224
+
225
+ ## License
226
+
227
+ Apache-2.0. Bitstraining was inspired by the single-config, pre-flight-check, measured-numbers ethos of
228
+ projects such as Soup CLI (trysoup.dev); it shares no code with them.
@@ -0,0 +1,71 @@
1
+ bitstraining/__init__.py,sha256=R4P8TvBZXEKL3cMJh-NBKauw7olLv4ZHvdPTnrxxuEg,631
2
+ bitstraining/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ bitstraining/runner.py,sha256=KNDe4sZnIX_PydoRtfdpISgZELqsEKd58v49tusfQD4,2954
4
+ bitstraining/autotune/__init__.py,sha256=4EQ3Ic7_xur9-__4gXIwHmxG-5I2rCeNi0P-SHd0kfo,393
5
+ bitstraining/autotune/cache.py,sha256=IlwQSxy-xrzebfiDnmRSPW6oXyr2gzzadLablD6Qypk,1205
6
+ bitstraining/autotune/microbatch.py,sha256=sX9g2IIWOqWcC8gmaEzrjWAF_8NBAC9TZWghzlZ0t0c,1328
7
+ bitstraining/autotune/tuner.py,sha256=9Mb53jJ2NUOChV9g6QRGBNipcuoLqFsTHBxEWytQIyA,6220
8
+ bitstraining/compute/__init__.py,sha256=r9JkM553y6vsHJrt_B7fsI5gRqnTudQpLTQCysiQyp0,479
9
+ bitstraining/compute/base.py,sha256=PC56uXajhVp6LDmHf7HmxCaq3Zze-ozIziNFrLFDvas,2675
10
+ bitstraining/compute/bundle.py,sha256=mpR81p95nchwQre_T0OYjovY47YCo8Y1yhCGo0CNbRA,2418
11
+ bitstraining/compute/catalog.py,sha256=4V8YDC4WnoeaJ4VRi4c4Oq35yD4086dfyB43Yp97keE,3154
12
+ bitstraining/compute/docker.py,sha256=B0EGrj822nbxTyd7-U7JglJIyk3WTQJ7BPqjjA9Zl14,4308
13
+ bitstraining/compute/local.py,sha256=xZyaQqWFyncwQMakwLZ0vAfwX9uD3FyQDCv8oXJ-laE,4365
14
+ bitstraining/compute/notebook.py,sha256=iyhsT-5tNaunwRLaGDhekx0jEO-m_Gzlm5PRsaLlONM,5813
15
+ bitstraining/compute/orchestrator.py,sha256=c9X0JA-uJifUGgFPwcofnVK8TFrZota1l5bCJHmYR3w,4448
16
+ bitstraining/compute/ssh.py,sha256=WMTFnRe5RqWyy00WeRehsc_dqd5Ld7qASNqvOR8tts8,6805
17
+ bitstraining/core/__init__.py,sha256=dp-EgNoL1_7LueYW3XjvJfO-iJzRF7koVWPWc4rzwsc,75
18
+ bitstraining/core/config.py,sha256=t-CL_51pa6mk8RIXWhKQ5pZ7VD5OYbyd2kEqwj5AOWM,3233
19
+ bitstraining/core/errors.py,sha256=b8yHLma2h2tU1XSZhYf-gGTTL9ENp1JxoLVrygPjVdc,1209
20
+ bitstraining/core/paths.py,sha256=fAJGpcSykarAwtocTw23tcrA9uen8jmRMDhJBBGB5lQ,594
21
+ bitstraining/core/registry.py,sha256=jRYNBzFPg0lokWIsRrlcLWp2e5RHT71QId4xS-KMwJc,2991
22
+ bitstraining/core/schemas.py,sha256=Ex-6m71b36nOXqAWOOUmnL4-InoKvHzC_NLg5KWCTr4,12240
23
+ bitstraining/data/__init__.py,sha256=KoK14mNxm_6XoPc45DzBLngrpkwALPSH12yfp2AM2gI,823
24
+ bitstraining/data/clean.py,sha256=87X-a0tPBmt4lFrIuB6CdGrdOge4dFXJfZMnJeQ-cKQ,5384
25
+ bitstraining/data/loaders.py,sha256=yfVLbFoWExeViw7o9dLwe7fH4q0oEg7_0zVz4Xb-i1Y,4555
26
+ bitstraining/data/pack.py,sha256=0us63rz1FPbe3O-lkkjIFXmIpxJ-kOljmMVtdOVg_s4,3781
27
+ bitstraining/data/schema.py,sha256=GYPXphXOrlHgpoyoemDJG2v-YslNVQUaw2jwdmRnUWU,5080
28
+ bitstraining/data/split.py,sha256=kGErzacumNdp2H3-5Oh5yp7sC5370p7-r8CGRoKUoiI,1544
29
+ bitstraining/data/stats.py,sha256=Jf58iAyQzNyAJIpxvL8QiP4JWrEA0uYF95YGmlrCH5o,5248
30
+ bitstraining/deploy/__init__.py,sha256=KZQSFwvEQQ5VTxdzkQ_MuJscPjt825Ow0zONEZ4CpfY,227
31
+ bitstraining/deploy/modelcard.py,sha256=Gavdndjvp3kj4sfYi7-rAKhKDyyYdoVK-KjAyivJFKU,2036
32
+ bitstraining/deploy/serve.py,sha256=wDTZYvwIwRDrk15v-4UH4gyQUB8Ksm2bD0evgpBi7uQ,845
33
+ bitstraining/engines/__init__.py,sha256=Bfzh5YPzfCrLtQi2myQSzj3g4dB3SvEe1_ywBF2LRpA,357
34
+ bitstraining/engines/base.py,sha256=yA8QTbFsu4CQaYOADlPUnniy8P6QmvomosrejmpcKQo,3709
35
+ bitstraining/engines/deepspeed.py,sha256=9NBVTTMHtIniWwT-xhx0mEU8UpRJn3FzGzwmBOxglzk,1689
36
+ bitstraining/engines/hf_peft.py,sha256=D2l0eD-SCyNlFLf51mASPYF1ppcXIXmny_DQ5Dganq8,14632
37
+ bitstraining/engines/mlx.py,sha256=9FLqV9J5jVHlUfWKLlyUIek1Bs90Tpk3EYLG7lFEWG8,4491
38
+ bitstraining/engines/simulate.py,sha256=4p2kpbLDKxllLjlrHN1mVeTWVyRniwvrLRZk17UXfek,5722
39
+ bitstraining/engines/unsloth.py,sha256=MhU4hRCeQudO11cx79PWuVj-ja5oISW22kLGhYDwvxk,2659
40
+ bitstraining/eval/__init__.py,sha256=2OqgJ2ONWXcJRyZY8PeTalvx_ga-5Zs9QbLFZjV2248,474
41
+ bitstraining/eval/audit.py,sha256=qTCRVjJJ9oU8g0LUIjUMWNtptcPI1TA-UOoGv-iw410,2288
42
+ bitstraining/eval/gate.py,sha256=1OUnD2H0hBBHnbq285UDSKz40Sg2sDSskUyQZr-Dup4,2601
43
+ bitstraining/eval/generate.py,sha256=5x6YKgoekc2tgNUBi_hwqvgnbLQI309uIYgbYsbORxY,2123
44
+ bitstraining/eval/metrics.py,sha256=U2qCIMuOuUG5CSX_-j2M0jrIOmksnPwfeHBuIDe1k4s,1419
45
+ bitstraining/hardware/__init__.py,sha256=yIM4Za1uo4ZlHaAjG18oRyVzV9cBpbFeGP3uO5HBX8A,286
46
+ bitstraining/hardware/database.py,sha256=YXiWitpJr8nneFkoyxbY3ZvtIL-XlpmPITGooyZAxMs,5252
47
+ bitstraining/hardware/profiler.py,sha256=Uyz-9NIIVdbz37zcgApISlYP24dggUfst3RvNRElc_Q,8291
48
+ bitstraining/interfaces/__init__.py,sha256=aUoQqMMsehX9m0YxQrHbYfCpOOoh0syf4D1DKm9U8oE,67
49
+ bitstraining/interfaces/api.py,sha256=p6JC6PJYjpSh8pOv4Cl-xtEAnp-0z9OM1lZCz8mBSIM,11425
50
+ bitstraining/interfaces/cli.py,sha256=s4-nJjLbHq9LmOnf9mPO_IcQp-N6IbCp4IgmV3vfWTs,20068
51
+ bitstraining/models/__init__.py,sha256=BoN4Lcx9KztlLX6GFC97OLEZC47tYAWA_m0qV__rLHA,269
52
+ bitstraining/models/introspect.py,sha256=c4tCaC6uPOkYveL1nKYDYRNOc6cJ4PLBmJyHJDTsr3Q,9101
53
+ bitstraining/optimize/__init__.py,sha256=Cw7GpJ1bpIYnvJkYMQ0sQct-8T3PjvIhyWQnykXd8bk,285
54
+ bitstraining/optimize/merge.py,sha256=_uIBHQQjH8-WyKzEY5WJL-SvNLNtkHmC_p1m03iVBdc,1074
55
+ bitstraining/optimize/quantize.py,sha256=L2IZQBIx7X1oZ6QV_sGkI8hIP87fBEkfD8csO-M-a9c,1671
56
+ bitstraining/planner/__init__.py,sha256=bmzPYJ_i4Hdk-qXgiX1W_xNAItR7Zzc09RcSgDMN3dQ,468
57
+ bitstraining/planner/calibration.py,sha256=euCP5ur6-bUFs1ra5eXMuWIJFsLwh9o6g_46lzM7ENM,1850
58
+ bitstraining/planner/doctor.py,sha256=gCTP78Ugh35XuRDVNeZ5un1UWJ9MZO4eBa8-OH_pZUs,11364
59
+ bitstraining/planner/memory.py,sha256=l16payx98dTiOlL3m7AuLpqEoAvA-Al3keoTzFZWvXc,5321
60
+ bitstraining/planner/search.py,sha256=rRjukLfUQ54j1CUcOwDR2ciKX2iOyGisZS7Hezuc_wQ,15761
61
+ bitstraining/planner/throughput.py,sha256=XkW9RnTpkijohkFTO7DbXRudIvuq7Qht9g7inbetfdo,5720
62
+ bitstraining/strategies/__init__.py,sha256=Hc8-5_BKjzNILO9HSbjb0DFoIrBBj9OKD65g1zzeguo,310
63
+ bitstraining/strategies/catalog.py,sha256=cNrXT8OOhUiQ0z-eBivFzB7vxTmI06oixcfrthOM00o,1682
64
+ bitstraining/tracking/__init__.py,sha256=x8pJDSefw-GplEWiWYWctO_UpbCm_EiAHmuEb9dvGAQ,153
65
+ bitstraining/tracking/registry.py,sha256=LiIaWeUTMZwkhvH51r47yp-s3BiNkzINFuGPx0HqC8c,8452
66
+ bitstraining-0.1.0.dist-info/licenses/LICENSE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
67
+ bitstraining-0.1.0.dist-info/METADATA,sha256=ZBkN20oadJCcZtpewfyQou6oqa3QDyPdYKbJuFhJDSg,13120
68
+ bitstraining-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
69
+ bitstraining-0.1.0.dist-info/entry_points.txt,sha256=1gCV29Rn0eGMZRgoPOM0C9873724yBlJkDo9BAJ4YYs,672
70
+ bitstraining-0.1.0.dist-info/top_level.txt,sha256=tmnUFQiZmhXThQWVydXWRpWzE5HXwOHau6RAym9toDI,13
71
+ bitstraining-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,17 @@
1
+ [bitstraining.engines]
2
+ deepspeed = bitstraining.engines.deepspeed:DeepSpeedEngine
3
+ hf_peft = bitstraining.engines.hf_peft:HFPeftEngine
4
+ mlx = bitstraining.engines.mlx:MLXEngine
5
+ simulate = bitstraining.engines.simulate:SimulateEngine
6
+ unsloth = bitstraining.engines.unsloth:UnslothEngine
7
+
8
+ [bitstraining.providers]
9
+ catalog = bitstraining.compute.catalog:CatalogProvider
10
+ docker = bitstraining.compute.docker:DockerProvider
11
+ local = bitstraining.compute.local:LocalProvider
12
+ notebook = bitstraining.compute.notebook:NotebookProvider
13
+ ssh = bitstraining.compute.ssh:SSHProvider
14
+
15
+ [console_scripts]
16
+ bitstraining = bitstraining.interfaces.cli:main
17
+ bt = bitstraining.interfaces.cli:main