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,243 @@
1
+ """Detect the local machine and optionally benchmark it.
2
+
3
+ Detection uses only the standard library (`nvidia-smi`, `/proc`, `sysctl`). The matmul
4
+ microbenchmark needs PyTorch and is skipped (with a note) when torch is absent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import platform
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from bitstraining.core.schemas import GPUInfo, HardwareProfile
18
+ from bitstraining.hardware.database import lookup_gpu
19
+
20
+
21
+ def _run(cmd: list[str], timeout: float = 10.0) -> str | None:
22
+ try:
23
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
24
+ except (OSError, subprocess.SubprocessError):
25
+ return None
26
+ return out.stdout.strip() if out.returncode == 0 else None
27
+
28
+
29
+ def _cpu_model() -> str:
30
+ if Path("/proc/cpuinfo").exists():
31
+ for line in Path("/proc/cpuinfo").read_text(errors="ignore").splitlines():
32
+ if line.lower().startswith("model name"):
33
+ return line.split(":", 1)[1].strip()
34
+ return platform.processor() or platform.machine()
35
+
36
+
37
+ def _ram_from_proc() -> float | None:
38
+ meminfo = Path("/proc/meminfo")
39
+ if meminfo.exists():
40
+ for line in meminfo.read_text().splitlines():
41
+ if line.startswith("MemTotal:"):
42
+ return int(line.split()[1]) / 1024 / 1024
43
+ return None
44
+
45
+
46
+ def _ram_from_sysctl() -> float | None:
47
+ out = _run(["sysctl", "-n", "hw.memsize"]) # macOS / BSD
48
+ return int(out) / 1024**3 if out and out.isdigit() else None
49
+
50
+
51
+ def _ram_from_windows() -> float | None:
52
+ if platform.system() != "Windows":
53
+ return None
54
+ try:
55
+ import ctypes
56
+
57
+ class _MemStatus(ctypes.Structure):
58
+ _fields_ = [
59
+ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
60
+ ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
61
+ ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
62
+ ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
63
+ ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
64
+ ]
65
+
66
+ st = _MemStatus()
67
+ st.dwLength = ctypes.sizeof(_MemStatus)
68
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)): # type: ignore[attr-defined]
69
+ return st.ullTotalPhys / 1024**3
70
+ except (AttributeError, OSError, ImportError):
71
+ pass
72
+ return None
73
+
74
+
75
+ def _ram_from_sysconf() -> float | None:
76
+ try:
77
+ return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 1024**3 # type: ignore[attr-defined]
78
+ except (AttributeError, ValueError, OSError):
79
+ return None
80
+
81
+
82
+ _RAM_PROBES = (_ram_from_proc, _ram_from_sysctl, _ram_from_windows, _ram_from_sysconf)
83
+
84
+
85
+ def _ram_gb() -> float:
86
+ """Total system RAM in GB, or 0.0 if no platform probe works (callers must handle that)."""
87
+ for probe in _RAM_PROBES:
88
+ try:
89
+ v = probe()
90
+ except Exception: # a broken probe must not stop profiling
91
+ v = None
92
+ if v and v > 0:
93
+ return round(v, 2)
94
+ return 0.0
95
+
96
+
97
+ def _nvidia_gpus() -> list[GPUInfo]:
98
+ if not shutil.which("nvidia-smi"):
99
+ return []
100
+ out = _run(
101
+ [
102
+ "nvidia-smi",
103
+ "--query-gpu=name,memory.total,compute_cap",
104
+ "--format=csv,noheader,nounits",
105
+ ]
106
+ )
107
+ if not out:
108
+ return []
109
+ gpus: list[GPUInfo] = []
110
+ for line in out.splitlines():
111
+ parts = [p.strip() for p in line.split(",")]
112
+ if len(parts) < 2:
113
+ continue
114
+ name = parts[0]
115
+ try:
116
+ vram = round(float(parts[1]) / 1024, 2)
117
+ except ValueError:
118
+ continue
119
+ info = lookup_gpu(name, vram_gb=vram)
120
+ if len(parts) > 2 and parts[2]:
121
+ info.compute_capability = parts[2]
122
+ try:
123
+ major = int(parts[2].split(".")[0])
124
+ info.bf16 = info.bf16 or major >= 8
125
+ info.fp8 = info.fp8 or major >= 9
126
+ except ValueError:
127
+ pass
128
+ info.source = "detected" if info.peak_tflops_bf16 == 0 else "database"
129
+ gpus.append(info)
130
+ topo = _run(["nvidia-smi", "topo", "-m"])
131
+ if topo and len(gpus) > 1 and "NV" in topo:
132
+ for g in gpus:
133
+ g.nvlink = True
134
+ return gpus
135
+
136
+
137
+ def _apple_gpu(ram_gb: float) -> list[GPUInfo]:
138
+ if platform.system() != "Darwin" or platform.machine() not in {"arm64", "aarch64"}:
139
+ return []
140
+ if ram_gb <= 0: # unknown RAM: don't invent a 0 GB GPU; the planner uses its CPU stand-in + doctor warns
141
+ return []
142
+ brand = _run(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple Silicon"
143
+ info = lookup_gpu(brand)
144
+ info.name = brand
145
+ info.vram_gb = round(ram_gb * 0.66, 2) # default Metal working-set cap is about 2/3 of RAM
146
+ info.source = "database"
147
+ return [info]
148
+
149
+
150
+ def _disk_free_gb(path: str) -> float:
151
+ try:
152
+ return round(shutil.disk_usage(path).free / 1024**3, 2)
153
+ except OSError:
154
+ return 0.0
155
+
156
+
157
+ def _disk_read_gbs(directory: str, size_mb: int = 64) -> float | None:
158
+ """Sequential read speed of the filesystem holding `directory` (page cache may inflate it)."""
159
+ try:
160
+ with tempfile.NamedTemporaryFile(dir=directory, delete=True) as f:
161
+ chunk = os.urandom(1024 * 1024)
162
+ for _ in range(size_mb):
163
+ f.write(chunk)
164
+ f.flush()
165
+ os.fsync(f.fileno())
166
+ f.seek(0)
167
+ t0 = time.perf_counter()
168
+ while f.read(8 * 1024 * 1024):
169
+ pass
170
+ dt = max(time.perf_counter() - t0, 1e-6)
171
+ return round(size_mb / 1024 / dt, 2)
172
+ except OSError:
173
+ return None
174
+
175
+
176
+ def _torch_benchmark(gpus: list[GPUInfo]) -> list[str]:
177
+ """Measure matmul TFLOPs and host->device bandwidth with torch. Returns notes."""
178
+ notes: list[str] = []
179
+ try:
180
+ import torch
181
+ except ImportError:
182
+ return ["benchmark skipped: PyTorch not installed (pip install 'bitstraining[train]')"]
183
+ if not torch.cuda.is_available():
184
+ return ["benchmark skipped: no CUDA device visible to PyTorch"]
185
+ dev = torch.device("cuda:0")
186
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
187
+ n = 8192
188
+ a = torch.randn(n, n, device=dev, dtype=dtype)
189
+ b = torch.randn(n, n, device=dev, dtype=dtype)
190
+ for _ in range(3):
191
+ a @ b
192
+ torch.cuda.synchronize()
193
+ iters = 20
194
+ t0 = time.perf_counter()
195
+ for _ in range(iters):
196
+ a @ b
197
+ torch.cuda.synchronize()
198
+ dt = time.perf_counter() - t0
199
+ tflops = 2 * n**3 * iters / dt / 1e12
200
+ host = torch.empty(256 * 1024 * 1024, dtype=torch.uint8).pin_memory()
201
+ t0 = time.perf_counter()
202
+ for _ in range(4):
203
+ host.to(dev, non_blocking=True)
204
+ torch.cuda.synchronize()
205
+ h2d = 4 * host.numel() / (time.perf_counter() - t0) / 1e9
206
+ g = gpus[0]
207
+ # Measured matmul is what the planner calls "peak"; MFU is applied on top.
208
+ g.peak_tflops_bf16 = round(tflops, 1)
209
+ g.h2d_gbs = round(h2d, 1)
210
+ g.source = "measured"
211
+ notes.append(f"measured {tflops:.0f} TFLOPs ({dtype}) and {h2d:.1f} GB/s host->device")
212
+ return notes
213
+
214
+
215
+ def profile(benchmark: bool = False, workdir: str | None = None) -> HardwareProfile:
216
+ """Profile this machine. `benchmark=True` runs the (short) microbenchmarks."""
217
+ ram = _ram_gb()
218
+ gpus = _nvidia_gpus()
219
+ vendor = "nvidia" if gpus else "none"
220
+ unified = False
221
+ if not gpus:
222
+ gpus = _apple_gpu(ram)
223
+ if gpus:
224
+ vendor, unified = "apple", True
225
+ workdir = workdir or os.getcwd()
226
+ hp = HardwareProfile(
227
+ name=platform.node() or "local",
228
+ os=f"{platform.system()} {platform.release()}",
229
+ cpu_model=_cpu_model(),
230
+ cpu_cores=os.cpu_count() or 1,
231
+ ram_gb=ram,
232
+ disk_free_gb=_disk_free_gb(workdir),
233
+ gpu_vendor=vendor,
234
+ unified_memory=unified,
235
+ gpus=gpus,
236
+ provider="local",
237
+ )
238
+ if benchmark:
239
+ hp.disk_read_gbs = _disk_read_gbs(workdir)
240
+ if gpus and vendor == "nvidia":
241
+ _torch_benchmark(gpus)
242
+ hp.measured = any(g.source == "measured" for g in gpus)
243
+ return hp
@@ -0,0 +1 @@
1
+ """User-facing interfaces: the Python API and the command line."""
@@ -0,0 +1,266 @@
1
+ """Python API. The CLI is a thin layer over these functions, so notebooks and pipelines get the same power.
2
+
3
+ import bitstraining as bt
4
+ spec = bt.core.config.load_spec("run.yaml")
5
+ plans = bt.plan(spec) # ranked ExecutionPlans with predicted memory/speed/cost
6
+ report = bt.doctor(spec) # pre-flight checks with fix suggestions
7
+ result = bt.train(spec) # profile -> plan -> doctor -> run -> track
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from bitstraining.autotune import TuneResult
20
+ from bitstraining.autotune import autotune as _autotune
21
+ from bitstraining.compute.base import ResourceRequest
22
+ from bitstraining.compute.bundle import make_bundle
23
+ from bitstraining.compute.orchestrator import run_job
24
+ from bitstraining.core import paths, registry
25
+ from bitstraining.core.errors import BitstrainingError, ConfigError, PlanningError
26
+ from bitstraining.core.schemas import (
27
+ Capabilities,
28
+ DatasetStats,
29
+ ExecutionPlan,
30
+ HardwareProfile,
31
+ ModelInfo,
32
+ RunSpec,
33
+ )
34
+ from bitstraining.data.clean import clean_rows
35
+ from bitstraining.data.loaders import read_rows
36
+ from bitstraining.data.schema import detect_schema
37
+ from bitstraining.data.split import split_rows
38
+ from bitstraining.data.stats import compute_stats, hash_file, hash_rows
39
+ from bitstraining.engines.base import Callbacks, ProbeContext, RunResult, available_engines
40
+ from bitstraining.hardware.database import synthetic_profile
41
+ from bitstraining.hardware.profiler import profile as _detect
42
+ from bitstraining.models.introspect import load_model_info
43
+ from bitstraining.planner.doctor import DoctorReport, run_doctor
44
+ from bitstraining.planner.search import make_plans
45
+ from bitstraining.tracking.registry import Registry
46
+
47
+
48
+ @dataclass
49
+ class Context:
50
+ """Everything the planner needs, gathered once."""
51
+
52
+ spec: RunSpec
53
+ hw: HardwareProfile
54
+ model: ModelInfo
55
+ stats: DatasetStats
56
+ train_rows: list[dict[str, Any]]
57
+ eval_rows: list[dict[str, Any]] | None
58
+ caps: list[Capabilities]
59
+ remote_hw: bool = False
60
+ notes: list[str] = field(default_factory=list)
61
+
62
+
63
+ def profile_hardware(
64
+ benchmark: bool = False, gpu: str | None = None, n_gpus: int | None = None, price: float | None = None
65
+ ) -> HardwareProfile:
66
+ """Profile this machine, or build a profile for a named GPU (`gpu="a100-80gb"`) to plan ahead."""
67
+ if gpu:
68
+ return synthetic_profile(gpu, n_gpus or 1, price)
69
+ hw = _detect(benchmark=benchmark)
70
+ if price is not None:
71
+ hw.price_per_hour = price
72
+ return hw
73
+
74
+
75
+ def inspect_data(path: str, fmt: str = "auto", max_length: int = 2048) -> str:
76
+ from bitstraining.data.stats import inspect_report
77
+
78
+ return inspect_report(path, fmt, max_length)
79
+
80
+
81
+ def build_context(
82
+ spec: RunSpec,
83
+ gpu: str | None = None,
84
+ n_gpus: int | None = None,
85
+ price: float | None = None,
86
+ benchmark: bool = False,
87
+ ) -> Context:
88
+ gpu = gpu or spec.compute.gpu
89
+ n_gpus = n_gpus or spec.compute.n_gpus
90
+ price = price if price is not None else spec.compute.options.get("price_per_hour")
91
+ hw = profile_hardware(benchmark, gpu, n_gpus, price)
92
+ remote = gpu is not None
93
+ offline = os.environ.get("BITSTRAINING_OFFLINE") == "1"
94
+ model = load_model_info(spec.model.base, allow_network=not offline)
95
+
96
+ raw = read_rows(spec.data.train)
97
+ schema = detect_schema(raw) if spec.data.format == "auto" else spec.data.format
98
+ rows, rep = clean_rows(raw, schema, dedup=spec.data.dedup)
99
+ eval_rows = None
100
+ if spec.data.eval:
101
+ eval_rows, _ = clean_rows(read_rows(spec.data.eval), schema, dedup=False)
102
+ elif spec.data.eval_split > 0:
103
+ rows, eval_rows = split_rows(rows, spec.data.eval_split, spec.goal.seed)
104
+ stats = compute_stats(rows, spec.data.max_length, None, schema,
105
+ hash_file(spec.data.train) or hash_rows(rows))
106
+ n = max(rep.input_rows, 1)
107
+ stats.empty_rate = rep.empty / n
108
+ stats.duplicate_rate = rep.exact_duplicates / n
109
+ caps = available_engines(hw, spec.engine, assume_installed=remote)
110
+ return Context(spec, hw, model, stats, rows, eval_rows, caps, remote)
111
+
112
+
113
+ def plan(spec: RunSpec, top_k: int = 5, ctx: Context | None = None, **kw: Any) -> list[ExecutionPlan]:
114
+ """Ranked, feasible execution plans for this run on this (or the named) hardware."""
115
+ ctx = ctx or build_context(spec, **kw)
116
+ return make_plans(ctx.spec, ctx.model, ctx.stats, ctx.hw, ctx.caps, top_k=top_k)
117
+
118
+
119
+ def doctor(spec: RunSpec, ctx: Context | None = None, **kw: Any) -> DoctorReport:
120
+ try:
121
+ ctx = ctx or build_context(spec, **kw)
122
+ except BitstrainingError as e: # still report data/model problems as findings
123
+ rep = DoctorReport()
124
+ rep.add("error", "DR000", e.message, e.fix or "")
125
+ return rep
126
+ try:
127
+ plans, err = plan(spec, ctx=ctx), None
128
+ except PlanningError as e:
129
+ plans, err = None, str(e)
130
+ return run_doctor(spec, ctx.hw, ctx.model, ctx.stats, plans, err, ctx.train_rows, ctx.eval_rows,
131
+ check_imports=not ctx.remote_hw)
132
+
133
+
134
+ def autotune(spec: RunSpec, ctx: Context | None = None, use_cache: bool = True, **kw: Any) -> TuneResult:
135
+ """Probe the top plan on the real device (or simulate) and return a measured, tuned plan."""
136
+ ctx = ctx or build_context(spec, **kw)
137
+ best = plan(spec, ctx=ctx, top_k=1)[0]
138
+ engine = registry.create("engines", best.engine)
139
+ seq = max(8, min(spec.data.max_length, ctx.stats.max_len or spec.data.max_length))
140
+ pctx = ProbeContext(spec, ctx.model, ctx.hw, ctx.stats, seq)
141
+ caps = next(c for c in ctx.caps if c.name == best.engine)
142
+ return _autotune(best, pctx, engine, caps, use_cache=use_cache)
143
+
144
+
145
+ def train(
146
+ spec: RunSpec,
147
+ gpu: str | None = None,
148
+ resume: bool = False,
149
+ force: bool = False,
150
+ tune: bool = False,
151
+ dry_run: bool = False,
152
+ log: Callable[[str], None] = print,
153
+ chosen_plan: ExecutionPlan | None = None,
154
+ ) -> dict[str, Any]:
155
+ """Profile -> plan -> doctor -> (autotune) -> run -> track. Returns a summary dict."""
156
+ ctx = build_context(spec, gpu=gpu)
157
+ plans = plan(spec, ctx=ctx) if chosen_plan is None else [chosen_plan]
158
+ best = plans[0]
159
+ report = run_doctor(spec, ctx.hw, ctx.model, ctx.stats, plans, None, ctx.train_rows, ctx.eval_rows,
160
+ check_imports=not ctx.remote_hw)
161
+ log(report.render())
162
+ if not report.ok and not force:
163
+ raise ConfigError("pre-flight checks failed", fix="fix the errors above or pass force=True / --force")
164
+ if tune and chosen_plan is None:
165
+ tr = autotune(spec, ctx=ctx)
166
+ best = tr.plan
167
+ for n in tr.notes:
168
+ log(f"autotune: {n}")
169
+ if ctx.remote_hw and spec.compute.provider == "local":
170
+ raise ConfigError(
171
+ "a hardware profile was named (--gpu) but compute.provider is 'local'",
172
+ fix="--gpu is for planning ahead; to run elsewhere set compute.provider (ssh, docker, notebook)",
173
+ )
174
+ e = best.estimate
175
+ log(f"plan: {best.describe()}")
176
+ log(f"predicted: {e.peak_gb_per_gpu:.1f} GB/GPU, {e.useful_tokens_per_s:,.0f} tok/s, "
177
+ f"{e.total_hours:.2f} h, confidence {e.confidence}")
178
+ out = Path(spec.output)
179
+ summary: dict[str, Any] = {"plan": best.to_dict(), "doctor_ok": report.ok, "dry_run": dry_run}
180
+ if dry_run:
181
+ return summary
182
+
183
+ out.mkdir(parents=True, exist_ok=True)
184
+ with (out / "train_normalized.jsonl").open("w") as f: # lets `spikes` show the offending rows
185
+ for r in ctx.train_rows:
186
+ f.write(json.dumps(r) + "\n")
187
+ reg = Registry()
188
+ simulated = best.engine == "simulate"
189
+ run_id = reg.create_run(spec.name, spec.to_dict(), best.to_dict(), ctx.hw.to_dict(),
190
+ ctx.stats.data_hash, best.engine, simulated)
191
+ summary["run_id"] = run_id
192
+ try:
193
+ if spec.compute.provider == "local":
194
+ result = _run_local(spec, best, ctx, reg, run_id, out, resume, log)
195
+ else:
196
+ result = _run_remote(spec, best, ctx, reg, run_id, out, resume, log)
197
+ reg.finish_run(run_id, result.status, result.to_dict())
198
+ if result.adapter_path:
199
+ reg.add_artifact(run_id, "adapter", result.adapter_path)
200
+ summary["result"] = result.to_dict()
201
+ if simulated:
202
+ log("NOTE: simulated run. No model was trained.")
203
+ return summary
204
+ except BaseException as ex:
205
+ reg.finish_run(run_id, "failed", {"error": str(ex)})
206
+ raise
207
+ finally:
208
+ reg.close()
209
+
210
+
211
+ def _run_local(spec: RunSpec, plan_: ExecutionPlan, ctx: Context, reg: Registry, run_id: str,
212
+ out: Path, resume: bool, log: Callable[[str], None]) -> RunResult:
213
+ engine = registry.create("engines", plan_.engine)
214
+ every = max(1, plan_.total_steps // 20)
215
+
216
+ def on_step(step: int, metrics: dict[str, float]) -> None:
217
+ reg.log_metrics(run_id, step, metrics)
218
+ if step <= 3 or step % every == 0:
219
+ log(f"step {step}: " + " ".join(f"{k}={v:.4g}" for k, v in metrics.items()))
220
+
221
+ cb = Callbacks(on_step=on_step, on_batch=lambda s, ids: reg.log_batch(run_id, s, ids), log=log)
222
+ resume_from = None
223
+ if resume:
224
+ cks = sorted((p for p in out.glob("checkpoint-*") if p.is_dir()), key=lambda p: int(p.name.split("-")[-1]))
225
+ resume_from = str(cks[-1]) if cks else None
226
+ return engine.train(plan_, spec, ctx.train_rows, ctx.eval_rows, cb, out, resume_from)
227
+
228
+
229
+ def _run_remote(spec: RunSpec, plan_: ExecutionPlan, ctx: Context, reg: Registry, run_id: str,
230
+ out: Path, resume: bool, log: Callable[[str], None]) -> RunResult:
231
+ from bitstraining.compute.base import JobSpec
232
+
233
+ provider = registry.create("providers", spec.compute.provider, spec.compute.options)
234
+ offers = provider.list_offers(ResourceRequest(gpu=spec.compute.gpu, n_gpus=spec.compute.n_gpus or 1))
235
+ if not offers:
236
+ raise ConfigError("the provider returned no offers", fix="relax compute constraints")
237
+ offer = offers[0]
238
+ bundle = make_bundle(spec, plan_, paths.home() / "jobs" / f"bundle-{run_id}")
239
+ steps_seen = {"n": 0}
240
+
241
+ def relay(line: str) -> None:
242
+ if line.startswith("BT_METRIC "):
243
+ try:
244
+ m = json.loads(line[len("BT_METRIC "):])
245
+ step = int(m.pop("step"))
246
+ reg.log_metrics(run_id, step, {k: float(v) for k, v in m.items()})
247
+ steps_seen["n"] = step
248
+ except (ValueError, KeyError):
249
+ pass
250
+ log(line)
251
+
252
+ outcome = run_job(provider, offer, bundle, JobSpec(name=spec.name, bundle_dir=str(bundle), resume=resume),
253
+ out, budget_usd=spec.goal.budget_usd, log=relay)
254
+ log(f"job {outcome.status}; {outcome.hours:.3f} h" + (f", ${outcome.cost_usd:.2f}" if outcome.cost_usd is not None else ""))
255
+ res_file = out / "result.json"
256
+ if res_file.exists():
257
+ d = json.loads(res_file.read_text())
258
+ d.pop("wall_seconds", None)
259
+ res = RunResult(**d)
260
+ else:
261
+ res = RunResult(status="stopped" if outcome.status == "manual" else "failed", steps=steps_seen["n"],
262
+ message=f"job ended with status {outcome.status}")
263
+ if outcome.status in ("budget_exceeded", "timeout"):
264
+ res.status = "stopped"
265
+ res.message = outcome.status
266
+ return res