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,496 @@
1
+ """Command line: `bitstraining <command>` (alias `bt`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+ from bitstraining import __version__
14
+ from bitstraining.core import registry
15
+ from bitstraining.core.config import load_spec
16
+ from bitstraining.core.errors import BitstrainingError
17
+
18
+ TEMPLATES: dict[str, dict[str, Any]] = {
19
+ "chat": {
20
+ "name": "chat-assistant",
21
+ "model": {"base": "Qwen/Qwen2.5-0.5B-Instruct"},
22
+ "data": {"train": "./data/train.jsonl", "max_length": 1024, "eval_split": 0.05},
23
+ "goal": {"task": "sft", "epochs": 3, "global_batch_size": 16, "learning_rate": 2e-4, "lora_r": 16},
24
+ "output": "./output",
25
+ },
26
+ "code": {
27
+ "name": "code-assistant",
28
+ "model": {"base": "Qwen/Qwen2.5-1.5B-Instruct"},
29
+ "data": {"train": "./data/train.jsonl", "max_length": 2048, "eval_split": 0.05},
30
+ "goal": {"task": "sft", "epochs": 2, "global_batch_size": 32, "learning_rate": 1e-4, "lora_r": 32},
31
+ "output": "./output",
32
+ },
33
+ "preference": {
34
+ "name": "preference-tuning",
35
+ "model": {"base": "Qwen/Qwen2.5-0.5B-Instruct"},
36
+ "data": {"train": "./data/prefs.jsonl", "max_length": 1024},
37
+ "goal": {"task": "dpo", "epochs": 1, "global_batch_size": 16, "learning_rate": 5e-6},
38
+ "output": "./output",
39
+ },
40
+ "full-finetune": {
41
+ "name": "full-finetune",
42
+ "model": {"base": "Qwen/Qwen2.5-0.5B-Instruct"},
43
+ "data": {"train": "./data/train.jsonl", "max_length": 1024},
44
+ "goal": {"task": "sft", "epochs": 2, "global_batch_size": 16, "learning_rate": 2e-5, "methods": ["full"]},
45
+ "output": "./output",
46
+ },
47
+ }
48
+
49
+ _DEMO = [
50
+ ("Translate to Spanish: Good morning", "Buenos días"),
51
+ ("Translate to Spanish: Thank you very much", "Muchas gracias"),
52
+ ("What is the capital of France?", "Paris"),
53
+ ("What is 12 times 12?", "144"),
54
+ ("Name a primary color.", "Red"),
55
+ ("Summarize: The cat sat on the mat.", "A cat sat on a mat."),
56
+ ]
57
+
58
+
59
+ def _demo_rows(n: int) -> list[dict[str, str]]:
60
+ rows = []
61
+ for i in range(n):
62
+ q, a = _DEMO[i % len(_DEMO)]
63
+ rows.append({"instruction": q if i < len(_DEMO) else f"{q} (variant {i})", "input": "", "output": a})
64
+ return rows
65
+
66
+
67
+ def _spec(args: argparse.Namespace):
68
+ spec = load_spec(args.config)
69
+ if getattr(args, "engine", None):
70
+ spec.engine = args.engine
71
+ return spec
72
+
73
+
74
+ def _add_hw(p: argparse.ArgumentParser) -> None:
75
+ p.add_argument("--gpu", help="plan for a named GPU instead of this machine, e.g. a100-80gb")
76
+ p.add_argument("--n-gpus", type=int)
77
+ p.add_argument("--price", type=float, help="USD per hour for the whole machine")
78
+
79
+
80
+ def cmd_init(a: argparse.Namespace) -> int:
81
+ if a.template not in TEMPLATES:
82
+ print(f"unknown template '{a.template}'. choose from: {', '.join(TEMPLATES)}", file=sys.stderr)
83
+ return 2
84
+ dest = Path(a.output)
85
+ if dest.exists() and not a.force:
86
+ print(f"{dest} exists; use --force to overwrite", file=sys.stderr)
87
+ return 2
88
+ dest.write_text(yaml.safe_dump(TEMPLATES[a.template], sort_keys=False))
89
+ print(f"wrote {dest} (template: {a.template})\nnext: bitstraining plan --config {dest}")
90
+ return 0
91
+
92
+
93
+ def cmd_profile(a: argparse.Namespace) -> int:
94
+ from bitstraining import profile_hardware
95
+
96
+ hw = profile_hardware(a.benchmark, a.gpu, a.n_gpus, a.price)
97
+ print(f"Machine: {hw.name} ({hw.os})")
98
+ print(f"CPU: {hw.cpu_model} x{hw.cpu_cores}")
99
+ print(f"RAM: {hw.ram_gb:.1f} GB Disk free: {hw.disk_free_gb:.0f} GB"
100
+ + (f" Disk read: {hw.disk_read_gbs} GB/s" if hw.disk_read_gbs else ""))
101
+ if not hw.gpus:
102
+ print("GPU: none detected (CPU only)")
103
+ for i, g in enumerate(hw.gpus):
104
+ print(f"GPU {i}: {g.name} {g.vram_gb:g} GB bf16={g.bf16} peak~{g.peak_tflops_bf16:g} TFLOPs [{g.source}]")
105
+ if a.json:
106
+ print(json.dumps(hw.to_dict(), indent=2))
107
+ return 0
108
+
109
+
110
+ def cmd_data(a: argparse.Namespace) -> int:
111
+ from bitstraining.data import clean_rows, detect_schema, read_rows
112
+
113
+ if a.data_cmd == "inspect":
114
+ from bitstraining import inspect_data
115
+
116
+ print(inspect_data(a.path, a.format, a.max_length))
117
+ elif a.data_cmd == "demo":
118
+ dest = Path(a.output)
119
+ dest.parent.mkdir(parents=True, exist_ok=True)
120
+ with dest.open("w") as f:
121
+ for r in _demo_rows(a.rows):
122
+ f.write(json.dumps(r) + "\n")
123
+ print(f"wrote {a.rows} demo rows to {dest}")
124
+ elif a.data_cmd == "clean":
125
+ raw = read_rows(a.path)
126
+ schema = detect_schema(raw)
127
+ kept, rep = clean_rows(raw, schema, dedup=True, near_dup_threshold=a.near_dup)
128
+ with Path(a.output).open("w") as f:
129
+ for r in kept:
130
+ f.write(json.dumps(r) + "\n")
131
+ print(f"kept {rep.kept}/{rep.input_rows} (malformed {rep.malformed}, empty {rep.empty}, "
132
+ f"duplicates {rep.exact_duplicates}, near-duplicates {rep.near_duplicates}) -> {a.output}")
133
+ elif a.data_cmd == "split":
134
+ from bitstraining.data import split_rows
135
+
136
+ raw = read_rows(a.path)
137
+ kept, _ = clean_rows(raw, detect_schema(raw), dedup=True)
138
+ tr, ev = split_rows(kept, a.eval_fraction, a.seed)
139
+ for name, rows in (("train", tr), ("eval", ev)):
140
+ with Path(f"{a.prefix}.{name}.jsonl").open("w") as f:
141
+ for r in rows:
142
+ f.write(json.dumps(r) + "\n")
143
+ print(f"train {len(tr)} rows, eval {len(ev)} rows (duplicates kept on one side)")
144
+ return 0
145
+
146
+
147
+ def cmd_doctor(a: argparse.Namespace) -> int:
148
+ from bitstraining import doctor
149
+
150
+ rep = doctor(_spec(a), gpu=a.gpu, n_gpus=a.n_gpus, price=a.price)
151
+ print(rep.render())
152
+ return 0 if rep.ok else 1
153
+
154
+
155
+ def _print_plan(i: int, p) -> None:
156
+ e = p.estimate
157
+ cost = f" ${e.cost_usd:.2f}" if e.cost_usd is not None else ""
158
+ print(f"#{i} {p.describe()}")
159
+ print(f" {e.peak_gb_per_gpu:.1f} GB/GPU | {e.useful_tokens_per_s:,.0f} useful tok/s | "
160
+ f"{e.total_hours:.2f} h{cost} | confidence {e.confidence} | steps {p.total_steps}")
161
+ for n in e.notes:
162
+ print(f" note: {n}")
163
+
164
+
165
+ def cmd_plan(a: argparse.Namespace) -> int:
166
+ from bitstraining import plan
167
+ from bitstraining.core.config import save_plan
168
+
169
+ plans = plan(_spec(a), top_k=a.top, gpu=a.gpu, n_gpus=a.n_gpus, price=a.price)
170
+ for i, p in enumerate(plans, 1):
171
+ _print_plan(i, p)
172
+ if a.verbose:
173
+ print(" memory GB: " + ", ".join(f"{k}={v}" for k, v in p.estimate.breakdown_gb.items()))
174
+ if a.save:
175
+ save_plan(plans[0], a.save)
176
+ print(f"saved plan #1 to {a.save}")
177
+ print("\nThese are model-based estimates. `bitstraining autotune` verifies them with a real probe.")
178
+ return 0
179
+
180
+
181
+ def cmd_autotune(a: argparse.Namespace) -> int:
182
+ from bitstraining import tune
183
+
184
+ tr = tune(_spec(a), use_cache=not a.no_cache, gpu=a.gpu, n_gpus=a.n_gpus, price=a.price)
185
+ _print_plan(1, tr.plan)
186
+ for n in tr.notes:
187
+ print(f"autotune: {n}")
188
+ for mb, r in sorted(tr.probes.items()):
189
+ print(f" probe mb={mb}: fits={r.fits} peak={r.peak_gb} GB tok/s={r.tokens_per_s} ({r.note})")
190
+ return 0
191
+
192
+
193
+ def cmd_train(a: argparse.Namespace) -> int:
194
+ from bitstraining import train
195
+
196
+ res = train(_spec(a), gpu=a.gpu, resume=a.resume, force=a.force, tune=a.tune, dry_run=a.dry_run)
197
+ r = res.get("result")
198
+ if r:
199
+ print(f"run {res['run_id']}: {r['status']} steps={r['steps']} loss={r['final_loss']}")
200
+ return 0
201
+
202
+
203
+ def cmd_runs(a: argparse.Namespace) -> int:
204
+ from bitstraining.tracking import Registry
205
+
206
+ with Registry() as reg:
207
+ if a.runs_cmd == "list":
208
+ for r in reg.list_runs(a.limit):
209
+ sim = " [simulated]" if r["simulated"] else ""
210
+ print(f"{r['id']} {r['status']:<9} {r['engine']:<9} {r['name']}{sim}")
211
+ elif a.runs_cmd == "lineage":
212
+ print(json.dumps(reg.lineage(a.run or reg.latest_run_id() or ""), indent=2))
213
+ elif a.runs_cmd == "spikes":
214
+ rid = a.run or reg.latest_run_id()
215
+ if not rid:
216
+ print("no runs recorded")
217
+ return 1
218
+ run = reg.get_run(rid)
219
+ rows_file = Path((run["spec"] or {}).get("output", "./output")) / "train_normalized.jsonl"
220
+ lines = rows_file.read_text().splitlines() if rows_file.exists() else []
221
+ spikes = reg.loss_spikes(rid, a.window, a.z)
222
+ if not spikes:
223
+ print("no loss spikes detected")
224
+ for s in spikes:
225
+ print(f"step {s['step']}: loss {s['loss']:.3f} (score {s['score']}) rows {s['rows']}")
226
+ for ri in s["rows"][:3]:
227
+ if ri < len(lines):
228
+ print(f" row {ri}: {lines[ri][:120]}")
229
+ return 0
230
+
231
+
232
+ def cmd_eval(a: argparse.Namespace) -> int:
233
+ from bitstraining.eval import GateCriteria, audit_rows, evaluate_gate
234
+
235
+ def load(p: str) -> list[dict[str, Any]]:
236
+ return [json.loads(x) for x in Path(p).read_text().splitlines() if x.strip()]
237
+
238
+ task = load(a.task) # each: {"reference":..,"base":..,"tuned":..,"prompt":..}
239
+ rep = audit_rows([r["reference"] for r in task], [r["base"] for r in task], [r["tuned"] for r in task],
240
+ a.metric, [r.get("prompt", "") for r in task])
241
+ print("task: " + rep.summary())
242
+ if a.audit_out:
243
+ rep.write(a.audit_out)
244
+ print(f"per-row audit written to {a.audit_out}")
245
+ gen = None
246
+ if a.general:
247
+ g = load(a.general)
248
+ gen = audit_rows([r["reference"] for r in g], [r["base"] for r in g], [r["tuned"] for r in g], a.metric)
249
+ print("general: " + gen.summary())
250
+ res = evaluate_gate(rep, gen, GateCriteria(a.min_gain, a.max_forgetting, a.max_worse))
251
+ print(res.render())
252
+ return 0 if res.passed else 1
253
+
254
+
255
+ def cmd_card(a: argparse.Namespace) -> int:
256
+ from bitstraining.deploy import write_model_card
257
+ from bitstraining.tracking import Registry
258
+
259
+ with Registry() as reg:
260
+ rid = a.run or reg.latest_run_id()
261
+ if not rid:
262
+ print("no runs recorded", file=sys.stderr)
263
+ return 1
264
+ run = reg.get_run(rid)
265
+ p = write_model_card(run, reg.lineage(rid), a.output)
266
+ print(f"wrote {p}")
267
+ return 0
268
+
269
+
270
+ def cmd_serve(a: argparse.Namespace) -> int:
271
+ import shlex
272
+ import subprocess
273
+
274
+ from bitstraining.deploy import serve_command
275
+
276
+ cmd = serve_command(a.model, a.backend, a.port, a.host, a.max_len)
277
+ print(" ".join(shlex.quote(c) for c in cmd))
278
+ if a.run:
279
+ return subprocess.call(cmd)
280
+ print("(add --run to start it)")
281
+ return 0
282
+
283
+
284
+ def cmd_compute(a: argparse.Namespace) -> int:
285
+ from bitstraining.compute.base import ResourceRequest
286
+
287
+ if a.compute_cmd == "offers":
288
+ prov = registry.create("providers", a.provider, {})
289
+ for o in prov.list_offers(ResourceRequest(gpu=a.gpu, n_gpus=a.n_gpus, min_vram_gb=a.min_vram,
290
+ max_price_per_hour=a.max_price)):
291
+ price = f"${o.price_per_hour:.2f}/h" if o.price_per_hour is not None else "n/a"
292
+ note = " (illustrative price)" if o.meta.get("illustrative") else ""
293
+ print(f"{o.provider:<9} {o.name:<34} {o.vram_gb:>5g} GB {price}{note}")
294
+ elif a.compute_cmd == "fetch":
295
+ from bitstraining.compute.base import Instance, JobHandle
296
+ from bitstraining.compute.notebook import NotebookProvider
297
+
298
+ h = JobHandle(id="manual", instance=Instance("manual", "notebook"), meta={"result_zip": a.zip})
299
+ NotebookProvider().fetch_artifacts(h, Path(a.dest))
300
+ print(f"extracted {a.zip} to {a.dest}")
301
+ return 0
302
+
303
+
304
+ def cmd_notebook(a: argparse.Namespace) -> int:
305
+ """Build a self-running Colab/Kaggle notebook for a run."""
306
+ import json as _json
307
+
308
+ from bitstraining import plan
309
+ from bitstraining.compute.bundle import make_bundle
310
+ from bitstraining.compute.notebook import build_notebook
311
+ from bitstraining.core import paths
312
+
313
+ spec = _spec(a)
314
+ best = plan(spec, top_k=1, gpu="t4")[0]
315
+ bundle = make_bundle(spec, best, paths.home() / "jobs" / "notebook-bundle")
316
+ Path(a.output).write_text(_json.dumps(build_notebook(bundle)))
317
+ print(f"wrote {a.output}; upload it to {a.target}, pick a GPU runtime, Run all, download output.zip")
318
+ return 0
319
+
320
+
321
+ def cmd_plugins(a: argparse.Namespace) -> int:
322
+ for group in ("engines", "providers"):
323
+ print(f"{group}: {', '.join(registry.names(group))}")
324
+ return 0
325
+
326
+
327
+ def cmd_quickstart(a: argparse.Namespace) -> int:
328
+ """End-to-end smoke run with the simulation engine: no GPU, no downloads, no model trained."""
329
+ import os
330
+ import tempfile
331
+
332
+ from bitstraining import train
333
+
334
+ root = Path(tempfile.mkdtemp(prefix="bt-quickstart-"))
335
+ data = root / "train.jsonl"
336
+ with data.open("w") as f:
337
+ for r in _demo_rows(200):
338
+ f.write(json.dumps(r) + "\n")
339
+ spec_d = dict(TEMPLATES["chat"])
340
+ spec_d.update(engine="simulate", output=str(root / "out"), extras={"max_steps": 30})
341
+ spec_d["data"] = {**spec_d["data"], "train": str(data)}
342
+ os.environ.setdefault("BITSTRAINING_OFFLINE", "1")
343
+ from bitstraining.core.config import spec_from_dict
344
+
345
+ res = train(spec_from_dict(spec_d))
346
+ print(f"\nquickstart finished in {root}. The simulation engine trains nothing; "
347
+ f"see `bitstraining init` for a real config.")
348
+ return 0 if res.get("result", {}).get("status") == "completed" else 1
349
+
350
+
351
+ def build_parser() -> argparse.ArgumentParser:
352
+ p = argparse.ArgumentParser(prog="bitstraining", description="Train. Fine-tune. Optimize. Deploy.")
353
+ p.add_argument("--version", action="version", version=f"bitstraining {__version__}")
354
+ sub = p.add_subparsers(dest="cmd", required=True)
355
+
356
+ def cfg(sp: argparse.ArgumentParser) -> None:
357
+ sp.add_argument("--config", "-c", default="bitstraining.yaml")
358
+ sp.add_argument("--engine", help="force an engine (hf_peft, unsloth, mlx, simulate)")
359
+
360
+ s = sub.add_parser("init", help="write a starter config")
361
+ s.add_argument("--template", default="chat", help=f"one of: {', '.join(TEMPLATES)}")
362
+ s.add_argument("--output", "-o", default="bitstraining.yaml")
363
+ s.add_argument("--force", action="store_true")
364
+ s.set_defaults(fn=cmd_init)
365
+
366
+ s = sub.add_parser("profile", help="detect hardware (or describe a named GPU)")
367
+ s.add_argument("--benchmark", action="store_true", help="measure TFLOPs/bandwidth (needs PyTorch+CUDA)")
368
+ s.add_argument("--json", action="store_true")
369
+ _add_hw(s)
370
+ s.set_defaults(fn=cmd_profile)
371
+
372
+ s = sub.add_parser("data", help="inspect, clean, split, demo data")
373
+ ds = s.add_subparsers(dest="data_cmd", required=True)
374
+ x = ds.add_parser("inspect")
375
+ x.add_argument("path")
376
+ x.add_argument("--format", default="auto")
377
+ x.add_argument("--max-length", type=int, default=2048)
378
+ x = ds.add_parser("clean")
379
+ x.add_argument("path")
380
+ x.add_argument("--output", "-o", required=True)
381
+ x.add_argument("--near-dup", type=float, default=None, help="MinHash similarity threshold, e.g. 0.8")
382
+ x = ds.add_parser("split")
383
+ x.add_argument("path")
384
+ x.add_argument("--eval-fraction", type=float, default=0.1)
385
+ x.add_argument("--prefix", default="data")
386
+ x.add_argument("--seed", type=int, default=42)
387
+ x = ds.add_parser("demo")
388
+ x.add_argument("--output", "-o", default="data/train.jsonl")
389
+ x.add_argument("--rows", type=int, default=100)
390
+ s.set_defaults(fn=cmd_data)
391
+
392
+ s = sub.add_parser("doctor", help="pre-flight checks")
393
+ cfg(s)
394
+ _add_hw(s)
395
+ s.set_defaults(fn=cmd_doctor)
396
+
397
+ s = sub.add_parser("plan", help="rank execution plans with predicted memory/speed/cost")
398
+ cfg(s)
399
+ _add_hw(s)
400
+ s.add_argument("--top", type=int, default=5)
401
+ s.add_argument("--save", help="write the best plan to a JSON file")
402
+ s.add_argument("--verbose", "-v", action="store_true")
403
+ s.set_defaults(fn=cmd_plan)
404
+
405
+ s = sub.add_parser("autotune", help="probe the best plan and learn calibration")
406
+ cfg(s)
407
+ _add_hw(s)
408
+ s.add_argument("--no-cache", action="store_true")
409
+ s.set_defaults(fn=cmd_autotune)
410
+
411
+ s = sub.add_parser("train", help="plan, check, run, track")
412
+ cfg(s)
413
+ s.add_argument("--gpu", help="(planning only) named GPU; combine with compute.provider in the config")
414
+ s.add_argument("--resume", action="store_true")
415
+ s.add_argument("--force", action="store_true", help="run even if doctor reports errors")
416
+ s.add_argument("--tune", action="store_true", help="autotune before training")
417
+ s.add_argument("--dry-run", action="store_true")
418
+ s.set_defaults(fn=cmd_train)
419
+
420
+ s = sub.add_parser("runs", help="run history, lineage, loss-spike tracing")
421
+ rs = s.add_subparsers(dest="runs_cmd", required=True)
422
+ x = rs.add_parser("list")
423
+ x.add_argument("--limit", type=int, default=20)
424
+ x = rs.add_parser("lineage")
425
+ x.add_argument("run", nargs="?")
426
+ x = rs.add_parser("spikes")
427
+ x.add_argument("run", nargs="?")
428
+ x.add_argument("--window", type=int, default=20)
429
+ x.add_argument("--z", type=float, default=4.0)
430
+ s.set_defaults(fn=cmd_runs)
431
+
432
+ s = sub.add_parser("eval", help="per-row audit + forgetting check + gate over prediction files")
433
+ s.add_argument("--task", required=True, help="JSONL rows: reference, base, tuned [, prompt]")
434
+ s.add_argument("--general", help="JSONL of the same shape on general-capability prompts")
435
+ s.add_argument("--metric", default="token_f1", choices=["exact_match", "contains", "token_f1"])
436
+ s.add_argument("--min-gain", type=float, default=0.0)
437
+ s.add_argument("--max-forgetting", type=float, default=0.05)
438
+ s.add_argument("--max-worse", type=float, default=None, help="max fraction of task rows allowed to regress")
439
+ s.add_argument("--audit-out")
440
+ s.set_defaults(fn=cmd_eval)
441
+
442
+ s = sub.add_parser("card", help="write a model card for a run")
443
+ s.add_argument("run", nargs="?")
444
+ s.add_argument("--output", "-o", default="MODEL_CARD.md")
445
+ s.set_defaults(fn=cmd_card)
446
+
447
+ s = sub.add_parser("serve", help="print/run the command that serves a model (vLLM or llama.cpp)")
448
+ s.add_argument("--model", required=True)
449
+ s.add_argument("--backend", default="vllm", choices=["vllm", "llamacpp"])
450
+ s.add_argument("--port", type=int, default=8000)
451
+ s.add_argument("--host", default="127.0.0.1")
452
+ s.add_argument("--max-len", type=int)
453
+ s.add_argument("--run", action="store_true")
454
+ s.set_defaults(fn=cmd_serve)
455
+
456
+ s = sub.add_parser("compute", help="providers and offers")
457
+ cs = s.add_subparsers(dest="compute_cmd", required=True)
458
+ x = cs.add_parser("offers")
459
+ x.add_argument("--provider", default="catalog")
460
+ x.add_argument("--gpu")
461
+ x.add_argument("--n-gpus", type=int, default=1)
462
+ x.add_argument("--min-vram", type=float, default=0.0)
463
+ x.add_argument("--max-price", type=float)
464
+ x = cs.add_parser("fetch")
465
+ x.add_argument("--zip", required=True)
466
+ x.add_argument("--dest", default="./output")
467
+ s.set_defaults(fn=cmd_compute)
468
+
469
+ s = sub.add_parser("notebook", help="build a self-running Colab/Kaggle notebook")
470
+ cfg(s)
471
+ s.add_argument("--target", default="colab", choices=["colab", "kaggle"])
472
+ s.add_argument("--output", "-o", default="bitstraining_job.ipynb")
473
+ s.set_defaults(fn=cmd_notebook)
474
+
475
+ s = sub.add_parser("plugins", help="list engines and providers")
476
+ s.set_defaults(fn=cmd_plugins)
477
+
478
+ s = sub.add_parser("quickstart", help="no-GPU smoke run with the simulation engine")
479
+ s.set_defaults(fn=cmd_quickstart)
480
+ return p
481
+
482
+
483
+ def main(argv: list[str] | None = None) -> int:
484
+ args = build_parser().parse_args(argv)
485
+ try:
486
+ return int(args.fn(args) or 0)
487
+ except BitstrainingError as e:
488
+ print(f"error: {e}", file=sys.stderr)
489
+ return 2
490
+ except KeyboardInterrupt:
491
+ print("interrupted", file=sys.stderr)
492
+ return 130
493
+
494
+
495
+ if __name__ == "__main__":
496
+ sys.exit(main())
@@ -0,0 +1,10 @@
1
+ """Model introspection without loading weights."""
2
+
3
+ from bitstraining.models.introspect import (
4
+ compute_params,
5
+ from_hf_config,
6
+ load_model_info,
7
+ lora_param_count,
8
+ )
9
+
10
+ __all__ = ["compute_params", "from_hf_config", "load_model_info", "lora_param_count"]