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.
- bitstraining/__init__.py +28 -0
- bitstraining/autotune/__init__.py +7 -0
- bitstraining/autotune/cache.py +39 -0
- bitstraining/autotune/microbatch.py +42 -0
- bitstraining/autotune/tuner.py +134 -0
- bitstraining/compute/__init__.py +23 -0
- bitstraining/compute/base.py +104 -0
- bitstraining/compute/bundle.py +64 -0
- bitstraining/compute/catalog.py +86 -0
- bitstraining/compute/docker.py +107 -0
- bitstraining/compute/local.py +121 -0
- bitstraining/compute/notebook.py +132 -0
- bitstraining/compute/orchestrator.py +126 -0
- bitstraining/compute/ssh.py +157 -0
- bitstraining/core/__init__.py +1 -0
- bitstraining/core/config.py +85 -0
- bitstraining/core/errors.py +43 -0
- bitstraining/core/paths.py +28 -0
- bitstraining/core/registry.py +87 -0
- bitstraining/core/schemas.py +358 -0
- bitstraining/data/__init__.py +25 -0
- bitstraining/data/clean.py +147 -0
- bitstraining/data/loaders.py +135 -0
- bitstraining/data/pack.py +100 -0
- bitstraining/data/schema.py +123 -0
- bitstraining/data/split.py +42 -0
- bitstraining/data/stats.py +143 -0
- bitstraining/deploy/__init__.py +6 -0
- bitstraining/deploy/modelcard.py +41 -0
- bitstraining/deploy/serve.py +21 -0
- bitstraining/engines/__init__.py +19 -0
- bitstraining/engines/base.py +120 -0
- bitstraining/engines/deepspeed.py +44 -0
- bitstraining/engines/hf_peft.py +325 -0
- bitstraining/engines/mlx.py +100 -0
- bitstraining/engines/simulate.py +138 -0
- bitstraining/engines/unsloth.py +66 -0
- bitstraining/eval/__init__.py +17 -0
- bitstraining/eval/audit.py +63 -0
- bitstraining/eval/gate.py +69 -0
- bitstraining/eval/generate.py +51 -0
- bitstraining/eval/metrics.py +48 -0
- bitstraining/hardware/__init__.py +6 -0
- bitstraining/hardware/database.py +125 -0
- bitstraining/hardware/profiler.py +243 -0
- bitstraining/interfaces/__init__.py +1 -0
- bitstraining/interfaces/api.py +266 -0
- bitstraining/interfaces/cli.py +496 -0
- bitstraining/models/__init__.py +10 -0
- bitstraining/models/introspect.py +228 -0
- bitstraining/optimize/__init__.py +6 -0
- bitstraining/optimize/merge.py +26 -0
- bitstraining/optimize/quantize.py +37 -0
- bitstraining/planner/__init__.py +15 -0
- bitstraining/planner/calibration.py +62 -0
- bitstraining/planner/doctor.py +215 -0
- bitstraining/planner/memory.py +126 -0
- bitstraining/planner/search.py +368 -0
- bitstraining/planner/throughput.py +154 -0
- bitstraining/py.typed +0 -0
- bitstraining/runner.py +71 -0
- bitstraining/strategies/__init__.py +10 -0
- bitstraining/strategies/catalog.py +42 -0
- bitstraining/tracking/__init__.py +5 -0
- bitstraining/tracking/registry.py +208 -0
- bitstraining-0.1.0.dist-info/METADATA +228 -0
- bitstraining-0.1.0.dist-info/RECORD +71 -0
- bitstraining-0.1.0.dist-info/WHEEL +5 -0
- bitstraining-0.1.0.dist-info/entry_points.txt +17 -0
- bitstraining-0.1.0.dist-info/licenses/LICENSE +177 -0
- bitstraining-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Local provider: run the bundle as a subprocess on this machine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import shutil
|
|
8
|
+
import signal
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Iterator
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from bitstraining.compute.base import (
|
|
16
|
+
FAILED,
|
|
17
|
+
RUNNING,
|
|
18
|
+
SUCCEEDED,
|
|
19
|
+
ComputeProvider,
|
|
20
|
+
Instance,
|
|
21
|
+
JobHandle,
|
|
22
|
+
JobSpec,
|
|
23
|
+
Offer,
|
|
24
|
+
ResourceRequest,
|
|
25
|
+
)
|
|
26
|
+
from bitstraining.core import paths
|
|
27
|
+
from bitstraining.hardware.profiler import profile
|
|
28
|
+
|
|
29
|
+
_PROCS: dict[str, subprocess.Popen[bytes]] = {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LocalProvider(ComputeProvider):
|
|
33
|
+
name = "local"
|
|
34
|
+
|
|
35
|
+
def __init__(self, options: dict | None = None):
|
|
36
|
+
self.o = dict(options or {})
|
|
37
|
+
|
|
38
|
+
def list_offers(self, req: ResourceRequest) -> list[Offer]:
|
|
39
|
+
hw = profile()
|
|
40
|
+
g = hw.gpus[0] if hw.gpus else None
|
|
41
|
+
return [Offer(
|
|
42
|
+
provider=self.name, name="this machine", gpu=g.name if g else "cpu",
|
|
43
|
+
n_gpus=hw.n_gpus, vram_gb=g.vram_gb if g else 0.0, price_per_hour=0.0, hardware=hw,
|
|
44
|
+
)]
|
|
45
|
+
|
|
46
|
+
def provision(self, offer: Offer) -> Instance:
|
|
47
|
+
work = paths.home() / "jobs" / f"local-{secrets.token_hex(3)}"
|
|
48
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
return Instance(id=work.name, provider=self.name, offer=offer, workdir=str(work), started=time.time())
|
|
50
|
+
|
|
51
|
+
def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None:
|
|
52
|
+
target = Path(inst.workdir) / "bundle"
|
|
53
|
+
if target.exists():
|
|
54
|
+
shutil.rmtree(target)
|
|
55
|
+
shutil.copytree(bundle_dir, target)
|
|
56
|
+
|
|
57
|
+
def launch(self, inst: Instance, job: JobSpec) -> JobHandle:
|
|
58
|
+
bundle = Path(inst.workdir) / "bundle"
|
|
59
|
+
log = Path(inst.workdir) / "job.log"
|
|
60
|
+
cmd = job.command or [sys.executable, "-m", "bitstraining.runner", "--bundle", str(bundle)]
|
|
61
|
+
if job.resume:
|
|
62
|
+
cmd = [*cmd, "--resume"]
|
|
63
|
+
env = {**os.environ, **job.env}
|
|
64
|
+
src = bundle / "src"
|
|
65
|
+
env["PYTHONPATH"] = f"{src}{os.pathsep}{env['PYTHONPATH']}" if env.get("PYTHONPATH") else str(src)
|
|
66
|
+
fh = log.open("ab")
|
|
67
|
+
extra = {"start_new_session": True} if os.name == "posix" else {} # new process group (POSIX only)
|
|
68
|
+
proc = subprocess.Popen(cmd, cwd=bundle, stdout=fh, stderr=subprocess.STDOUT, env=env, **extra)
|
|
69
|
+
h = JobHandle(id=f"{inst.id}-{proc.pid}", instance=inst, log_path=str(log), started=time.time())
|
|
70
|
+
_PROCS[h.id] = proc
|
|
71
|
+
return h
|
|
72
|
+
|
|
73
|
+
def status(self, job: JobHandle) -> str:
|
|
74
|
+
proc = _PROCS.get(job.id)
|
|
75
|
+
if proc is None:
|
|
76
|
+
return FAILED
|
|
77
|
+
rc = proc.poll()
|
|
78
|
+
if rc is None:
|
|
79
|
+
return RUNNING
|
|
80
|
+
return SUCCEEDED if rc == 0 else FAILED
|
|
81
|
+
|
|
82
|
+
def stream_logs(self, job: JobHandle) -> Iterator[str]:
|
|
83
|
+
log = Path(job.log_path)
|
|
84
|
+
pos = 0
|
|
85
|
+
while True:
|
|
86
|
+
if log.exists():
|
|
87
|
+
with log.open("rb") as f:
|
|
88
|
+
f.seek(pos)
|
|
89
|
+
chunk = f.read()
|
|
90
|
+
pos = f.tell()
|
|
91
|
+
if chunk:
|
|
92
|
+
yield from chunk.decode(errors="replace").splitlines()
|
|
93
|
+
if self.status(job) != RUNNING:
|
|
94
|
+
if log.exists(): # drain what was written after the last read
|
|
95
|
+
with log.open("rb") as f:
|
|
96
|
+
f.seek(pos)
|
|
97
|
+
tail = f.read()
|
|
98
|
+
if tail:
|
|
99
|
+
yield from tail.decode(errors="replace").splitlines()
|
|
100
|
+
return
|
|
101
|
+
time.sleep(0.2)
|
|
102
|
+
|
|
103
|
+
def fetch_artifacts(self, job: JobHandle, dest: Path) -> None:
|
|
104
|
+
src = Path(job.instance.workdir) / "bundle" / "output"
|
|
105
|
+
if src.exists():
|
|
106
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
shutil.copytree(src, dest, dirs_exist_ok=True)
|
|
108
|
+
|
|
109
|
+
def cancel(self, job: JobHandle) -> None:
|
|
110
|
+
proc = _PROCS.get(job.id)
|
|
111
|
+
if proc and proc.poll() is None:
|
|
112
|
+
try:
|
|
113
|
+
if hasattr(os, "killpg"): # POSIX: stop the whole process group
|
|
114
|
+
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
|
|
115
|
+
else: # Windows
|
|
116
|
+
proc.terminate()
|
|
117
|
+
except (ProcessLookupError, PermissionError):
|
|
118
|
+
proc.terminate()
|
|
119
|
+
|
|
120
|
+
def teardown(self, inst: Instance) -> None:
|
|
121
|
+
pass # keep the workdir: it holds logs and checkpoints for resume
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Notebook provider: Google Colab, Kaggle, or any hosted Jupyter.
|
|
2
|
+
|
|
3
|
+
Honest scope: Bitstraining cannot log into or drive Colab/Kaggle for you (their terms and APIs do not
|
|
4
|
+
allow unattended GPU sessions). Instead this provider produces a *self-running notebook*: it embeds the
|
|
5
|
+
whole bundle (base64 zip) so you upload ONE file, press Run All, and download `output.zip` when done.
|
|
6
|
+
Then `bitstraining compute fetch --zip output.zip` (or `fetch_artifacts`) brings the result home.
|
|
7
|
+
|
|
8
|
+
Status is always MANUAL: the orchestrator prints the instructions and stops instead of polling.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import io
|
|
15
|
+
import json
|
|
16
|
+
import secrets
|
|
17
|
+
import time
|
|
18
|
+
import zipfile
|
|
19
|
+
from collections.abc import Iterator
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from bitstraining.compute.base import (
|
|
24
|
+
MANUAL,
|
|
25
|
+
ComputeProvider,
|
|
26
|
+
Instance,
|
|
27
|
+
JobHandle,
|
|
28
|
+
JobSpec,
|
|
29
|
+
Offer,
|
|
30
|
+
ResourceRequest,
|
|
31
|
+
)
|
|
32
|
+
from bitstraining.core import paths
|
|
33
|
+
from bitstraining.core.errors import ComputeError
|
|
34
|
+
from bitstraining.hardware.database import synthetic_profile
|
|
35
|
+
|
|
36
|
+
_TARGETS = {
|
|
37
|
+
"colab": ("T4 16 GB (free tier, availability varies)", "t4"),
|
|
38
|
+
"kaggle": ("T4 x2 or P100 (free weekly quota, availability varies)", "t4"),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def build_notebook(bundle_dir: Path) -> dict[str, Any]:
|
|
43
|
+
"""An .ipynb (nbformat 4) dict that unpacks the embedded bundle, trains, and zips the output."""
|
|
44
|
+
buf = io.BytesIO()
|
|
45
|
+
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
|
46
|
+
for f in sorted(Path(bundle_dir).rglob("*")):
|
|
47
|
+
if f.is_file():
|
|
48
|
+
z.write(f, f.relative_to(bundle_dir))
|
|
49
|
+
payload = base64.b64encode(buf.getvalue()).decode()
|
|
50
|
+
if len(payload) > 40_000_000:
|
|
51
|
+
raise ComputeError("bundle is too large to embed in a notebook (>40 MB base64)",
|
|
52
|
+
fix="shrink the dataset, or upload it separately and edit spec.yaml")
|
|
53
|
+
|
|
54
|
+
def code(src: str) -> dict[str, Any]:
|
|
55
|
+
return {"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [],
|
|
56
|
+
"source": src.splitlines(keepends=True)}
|
|
57
|
+
|
|
58
|
+
md = {"cell_type": "markdown", "metadata": {},
|
|
59
|
+
"source": ["# Bitstraining job\n", "Runtime > Change runtime type > pick a GPU, then **Run all**. "
|
|
60
|
+
"When it finishes, download `output.zip` from the file browser."]}
|
|
61
|
+
return {
|
|
62
|
+
"nbformat": 4, "nbformat_minor": 5,
|
|
63
|
+
"metadata": {"accelerator": "GPU", "kernelspec": {"name": "python3", "display_name": "Python 3"}},
|
|
64
|
+
"cells": [
|
|
65
|
+
md,
|
|
66
|
+
code(f'import base64, io, zipfile, os\nPAYLOAD = "{payload}"\n'
|
|
67
|
+
'os.makedirs("job", exist_ok=True)\n'
|
|
68
|
+
'zipfile.ZipFile(io.BytesIO(base64.b64decode(PAYLOAD))).extractall("job")\n'
|
|
69
|
+
'print("bundle unpacked")'),
|
|
70
|
+
code("!pip install -q -r job/requirements.txt"),
|
|
71
|
+
code("import subprocess, sys\n"
|
|
72
|
+
"env = dict(os.environ, PYTHONPATH=os.path.abspath('job/src'))\n"
|
|
73
|
+
"subprocess.run([sys.executable, '-m', 'bitstraining.runner', '--bundle', 'job'], env=env, check=True)"),
|
|
74
|
+
code("import shutil\nshutil.make_archive('output', 'zip', 'job/output')\nprint('now download output.zip')"),
|
|
75
|
+
],
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class NotebookProvider(ComputeProvider):
|
|
80
|
+
name = "notebook"
|
|
81
|
+
|
|
82
|
+
def __init__(self, options: dict[str, Any] | None = None):
|
|
83
|
+
self.o = dict(options or {})
|
|
84
|
+
self.target = self.o.get("target", "colab")
|
|
85
|
+
|
|
86
|
+
def list_offers(self, req: ResourceRequest) -> list[Offer]:
|
|
87
|
+
label, gpu = _TARGETS.get(self.target, _TARGETS["colab"])
|
|
88
|
+
hw = synthetic_profile(gpu, 1, 0.0)
|
|
89
|
+
hw.provider = self.name
|
|
90
|
+
return [Offer(provider=self.name, name=f"{self.target}: {label}", gpu=gpu, n_gpus=1,
|
|
91
|
+
vram_gb=hw.vram_gb, price_per_hour=0.0, hardware=hw, meta={"manual": True})]
|
|
92
|
+
|
|
93
|
+
def provision(self, offer: Offer) -> Instance:
|
|
94
|
+
work = paths.home() / "jobs" / f"notebook-{secrets.token_hex(3)}"
|
|
95
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
return Instance(id=work.name, provider=self.name, offer=offer, workdir=str(work), started=time.time())
|
|
97
|
+
|
|
98
|
+
def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None:
|
|
99
|
+
nb = build_notebook(Path(bundle_dir))
|
|
100
|
+
out = Path(inst.workdir) / "bitstraining_job.ipynb"
|
|
101
|
+
out.write_text(json.dumps(nb))
|
|
102
|
+
inst.meta["notebook"] = str(out)
|
|
103
|
+
|
|
104
|
+
def launch(self, inst: Instance, job: JobSpec) -> JobHandle:
|
|
105
|
+
return JobHandle(id=inst.id, instance=inst, started=time.time(), meta={"notebook": inst.meta["notebook"]})
|
|
106
|
+
|
|
107
|
+
def status(self, job: JobHandle) -> str:
|
|
108
|
+
return MANUAL
|
|
109
|
+
|
|
110
|
+
def stream_logs(self, job: JobHandle) -> Iterator[str]:
|
|
111
|
+
nb = job.meta["notebook"]
|
|
112
|
+
yield f"Notebook written: {nb}"
|
|
113
|
+
yield f"1. Upload it to {'colab.research.google.com' if self.target == 'colab' else 'kaggle.com (New Notebook > File > Import)'}"
|
|
114
|
+
yield "2. Choose a GPU runtime and press Run all."
|
|
115
|
+
yield "3. Download output.zip, then run: bitstraining compute fetch --zip output.zip --dest ./output"
|
|
116
|
+
|
|
117
|
+
def fetch_artifacts(self, job: JobHandle, dest: Path) -> None:
|
|
118
|
+
z = job.meta.get("result_zip")
|
|
119
|
+
if not z:
|
|
120
|
+
raise ComputeError("no result zip registered", fix="pass the downloaded output.zip via `compute fetch --zip`")
|
|
121
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
with zipfile.ZipFile(z) as zf:
|
|
123
|
+
for member in zf.namelist(): # refuse path traversal
|
|
124
|
+
if Path(member).is_absolute() or ".." in Path(member).parts:
|
|
125
|
+
raise ComputeError(f"unsafe path in archive: {member}")
|
|
126
|
+
zf.extractall(dest)
|
|
127
|
+
|
|
128
|
+
def cancel(self, job: JobHandle) -> None:
|
|
129
|
+
pass
|
|
130
|
+
|
|
131
|
+
def teardown(self, inst: Instance) -> None:
|
|
132
|
+
pass
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Job lifecycle: provision -> sync -> launch -> monitor -> (resume on preemption) -> fetch -> teardown.
|
|
2
|
+
|
|
3
|
+
Guarantees
|
|
4
|
+
* hard budget cap: the job is cancelled when elapsed_hours * price_per_hour exceeds `budget_usd`
|
|
5
|
+
* wall-clock cap: cancelled after `max_hours`
|
|
6
|
+
* preemption/host loss: relaunched with --resume up to `max_resumes` times
|
|
7
|
+
* the instance is always torn down, even on error (unless `keep_instance`)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from bitstraining.compute.base import (
|
|
18
|
+
MANUAL,
|
|
19
|
+
PREEMPTED,
|
|
20
|
+
SUCCEEDED,
|
|
21
|
+
ComputeProvider,
|
|
22
|
+
JobHandle,
|
|
23
|
+
JobSpec,
|
|
24
|
+
Offer,
|
|
25
|
+
)
|
|
26
|
+
from bitstraining.core.errors import BudgetExceeded
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class JobOutcome:
|
|
31
|
+
status: str # succeeded | failed | manual | budget_exceeded | timeout
|
|
32
|
+
resumes: int = 0
|
|
33
|
+
cost_usd: float | None = None
|
|
34
|
+
hours: float = 0.0
|
|
35
|
+
handle: JobHandle | None = None
|
|
36
|
+
log_tail: list[str] = field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def run_job(
|
|
40
|
+
provider: ComputeProvider,
|
|
41
|
+
offer: Offer,
|
|
42
|
+
bundle_dir: Path,
|
|
43
|
+
job: JobSpec,
|
|
44
|
+
dest: Path,
|
|
45
|
+
budget_usd: float | None = None,
|
|
46
|
+
max_resumes: int = 2,
|
|
47
|
+
poll_s: float = 1.0,
|
|
48
|
+
log: Callable[[str], None] = print,
|
|
49
|
+
keep_instance: bool = False,
|
|
50
|
+
) -> JobOutcome:
|
|
51
|
+
price = offer.price_per_hour
|
|
52
|
+
if budget_usd is not None and price is not None and price > 0:
|
|
53
|
+
# Refuse to start a job that cannot even run a minimal 5 minutes inside the budget.
|
|
54
|
+
if price * (5 / 60) > budget_usd:
|
|
55
|
+
raise BudgetExceeded(
|
|
56
|
+
f"budget ${budget_usd:.2f} cannot cover 5 minutes at ${price:.2f}/h",
|
|
57
|
+
fix="raise the budget or choose cheaper compute",
|
|
58
|
+
)
|
|
59
|
+
inst = provider.provision(offer)
|
|
60
|
+
t0 = time.time()
|
|
61
|
+
resumes = 0
|
|
62
|
+
outcome = JobOutcome(status="failed")
|
|
63
|
+
try:
|
|
64
|
+
provider.sync_workspace(inst, bundle_dir)
|
|
65
|
+
handle = provider.launch(inst, job)
|
|
66
|
+
outcome.handle = handle
|
|
67
|
+
while True:
|
|
68
|
+
# Stream whatever is available, then decide what to do based on status.
|
|
69
|
+
killed = None
|
|
70
|
+
for line in _stream_with_limits(provider, handle, t0, price, budget_usd, job.max_hours):
|
|
71
|
+
if isinstance(line, tuple):
|
|
72
|
+
killed = line[0]
|
|
73
|
+
break
|
|
74
|
+
outcome.log_tail = (outcome.log_tail + [line])[-50:]
|
|
75
|
+
log(line)
|
|
76
|
+
if killed:
|
|
77
|
+
provider.cancel(handle)
|
|
78
|
+
outcome.status = killed
|
|
79
|
+
break
|
|
80
|
+
st = provider.status(handle)
|
|
81
|
+
if st == MANUAL:
|
|
82
|
+
outcome.status = "manual"
|
|
83
|
+
break
|
|
84
|
+
if st == SUCCEEDED:
|
|
85
|
+
outcome.status = "succeeded"
|
|
86
|
+
break
|
|
87
|
+
if st == PREEMPTED and resumes < max_resumes:
|
|
88
|
+
resumes += 1
|
|
89
|
+
log(f"[orchestrator] host lost; resuming (attempt {resumes}/{max_resumes})")
|
|
90
|
+
handle = provider.launch(inst, JobSpec(**{**job.__dict__, "resume": True}))
|
|
91
|
+
outcome.handle = handle
|
|
92
|
+
continue
|
|
93
|
+
outcome.status = "failed"
|
|
94
|
+
break
|
|
95
|
+
if outcome.status in ("succeeded", "budget_exceeded", "timeout"):
|
|
96
|
+
try:
|
|
97
|
+
provider.fetch_artifacts(handle, dest)
|
|
98
|
+
except Exception as e: # keep the real outcome; surface fetch trouble in the log
|
|
99
|
+
log(f"[orchestrator] could not fetch artifacts: {e}")
|
|
100
|
+
finally:
|
|
101
|
+
outcome.hours = (time.time() - t0) / 3600
|
|
102
|
+
outcome.resumes = resumes
|
|
103
|
+
outcome.cost_usd = round(outcome.hours * price, 4) if price is not None else None
|
|
104
|
+
if not keep_instance and outcome.status != "manual":
|
|
105
|
+
provider.teardown(inst)
|
|
106
|
+
return outcome
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _stream_with_limits(
|
|
110
|
+
provider: ComputeProvider,
|
|
111
|
+
handle: JobHandle,
|
|
112
|
+
t0: float,
|
|
113
|
+
price: float | None,
|
|
114
|
+
budget_usd: float | None,
|
|
115
|
+
max_hours: float | None,
|
|
116
|
+
):
|
|
117
|
+
"""Yield log lines; yield a ("budget_exceeded"|"timeout",) tuple when a cap is hit."""
|
|
118
|
+
for line in provider.stream_logs(handle):
|
|
119
|
+
yield line
|
|
120
|
+
hours = (time.time() - t0) / 3600
|
|
121
|
+
if budget_usd is not None and price and hours * price >= budget_usd:
|
|
122
|
+
yield ("budget_exceeded",)
|
|
123
|
+
return
|
|
124
|
+
if max_hours is not None and hours >= max_hours:
|
|
125
|
+
yield ("timeout",)
|
|
126
|
+
return
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""SSH provider: any GPU box you can reach with `ssh` (your own server, a rented VM, a pod).
|
|
2
|
+
|
|
3
|
+
Uses the system `ssh`/`rsync`/`scp` binaries, so your ~/.ssh/config, keys and agents just work.
|
|
4
|
+
No credentials are ever stored or logged by Bitstraining.
|
|
5
|
+
|
|
6
|
+
Options (compute.options in the run spec):
|
|
7
|
+
host (required) e.g. "ubuntu@203.0.113.7" or an ssh-config alias
|
|
8
|
+
port ssh port
|
|
9
|
+
identity_file path to a private key
|
|
10
|
+
remote_root default "~/bitstraining"
|
|
11
|
+
python remote python executable, default "python3"
|
|
12
|
+
price_per_hour USD/hour for the whole machine, for cost estimates and budget caps
|
|
13
|
+
gpu, n_gpus what is installed there (used for planning without logging in)
|
|
14
|
+
|
|
15
|
+
NOT exercised by CI (needs a real remote host). The command construction is unit-tested.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import secrets
|
|
21
|
+
import shlex
|
|
22
|
+
import subprocess
|
|
23
|
+
import time
|
|
24
|
+
from collections.abc import Iterator
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from bitstraining.compute.base import (
|
|
29
|
+
FAILED,
|
|
30
|
+
RUNNING,
|
|
31
|
+
SUCCEEDED,
|
|
32
|
+
ComputeProvider,
|
|
33
|
+
Instance,
|
|
34
|
+
JobHandle,
|
|
35
|
+
JobSpec,
|
|
36
|
+
Offer,
|
|
37
|
+
ResourceRequest,
|
|
38
|
+
)
|
|
39
|
+
from bitstraining.core.errors import ComputeError
|
|
40
|
+
from bitstraining.hardware.database import synthetic_profile
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class SSHProvider(ComputeProvider):
|
|
44
|
+
name = "ssh"
|
|
45
|
+
|
|
46
|
+
def __init__(self, options: dict[str, Any] | None = None, runner: Any = None):
|
|
47
|
+
self.o = dict(options or {})
|
|
48
|
+
self._run = runner or self._subprocess_run # injectable for tests
|
|
49
|
+
|
|
50
|
+
# ---- command builders (pure, unit-tested) -------------------------------------------
|
|
51
|
+
def _ssh_base(self) -> list[str]:
|
|
52
|
+
host = self.o.get("host")
|
|
53
|
+
if not host:
|
|
54
|
+
raise ComputeError("ssh provider needs compute.options.host", fix="e.g. host: ubuntu@203.0.113.7")
|
|
55
|
+
cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=30"]
|
|
56
|
+
if self.o.get("port"):
|
|
57
|
+
cmd += ["-p", str(self.o["port"])]
|
|
58
|
+
if self.o.get("identity_file"):
|
|
59
|
+
cmd += ["-i", str(self.o["identity_file"])]
|
|
60
|
+
return [*cmd, host]
|
|
61
|
+
|
|
62
|
+
def ssh_command(self, remote_cmd: str) -> list[str]:
|
|
63
|
+
return [*self._ssh_base(), remote_cmd]
|
|
64
|
+
|
|
65
|
+
def rsync_command(self, src: str, dst: str, to_remote: bool) -> list[str]:
|
|
66
|
+
ssh = ["ssh", "-o", "BatchMode=yes"]
|
|
67
|
+
if self.o.get("port"):
|
|
68
|
+
ssh += ["-p", str(self.o["port"])]
|
|
69
|
+
if self.o.get("identity_file"):
|
|
70
|
+
ssh += ["-i", str(self.o["identity_file"])]
|
|
71
|
+
host = self.o["host"]
|
|
72
|
+
a, b = (src, f"{host}:{dst}") if to_remote else (f"{host}:{src}", dst)
|
|
73
|
+
return ["rsync", "-az", "-e", " ".join(shlex.quote(x) for x in ssh), a, b]
|
|
74
|
+
|
|
75
|
+
def remote_launch_script(self, workdir: str, job: JobSpec) -> str:
|
|
76
|
+
py = self.o.get("python", "python3")
|
|
77
|
+
resume = " --resume" if job.resume else ""
|
|
78
|
+
env = " ".join(f"{k}={shlex.quote(v)}" for k, v in job.env.items())
|
|
79
|
+
inner = (
|
|
80
|
+
f"cd {shlex.quote(workdir)}/bundle && "
|
|
81
|
+
f"{env} {py} -m pip install -q -r requirements.txt && "
|
|
82
|
+
f"PYTHONPATH=$PWD/src {py} -m bitstraining.runner --bundle .{resume}; "
|
|
83
|
+
f"echo $? > {shlex.quote(workdir)}/exit_code"
|
|
84
|
+
)
|
|
85
|
+
return (
|
|
86
|
+
f"nohup bash -c {shlex.quote(inner)} > {shlex.quote(workdir)}/job.log 2>&1 & echo $!"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# ---- execution ---------------------------------------------------------------------
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _subprocess_run(cmd: list[str], timeout: float = 600.0) -> subprocess.CompletedProcess[str]:
|
|
92
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
|
93
|
+
|
|
94
|
+
def _ok(self, cmd: list[str], what: str) -> str:
|
|
95
|
+
r = self._run(cmd)
|
|
96
|
+
if r.returncode != 0:
|
|
97
|
+
raise ComputeError(f"{what} failed: {r.stderr.strip()[:300]}", fix="check ssh access with `ssh <host> true`")
|
|
98
|
+
return r.stdout.strip()
|
|
99
|
+
|
|
100
|
+
def list_offers(self, req: ResourceRequest) -> list[Offer]:
|
|
101
|
+
gpu, n = self.o.get("gpu"), int(self.o.get("n_gpus", 1))
|
|
102
|
+
hw = synthetic_profile(gpu, n, self.o.get("price_per_hour")) if gpu else None
|
|
103
|
+
if hw:
|
|
104
|
+
hw.provider = self.name
|
|
105
|
+
return [Offer(
|
|
106
|
+
provider=self.name, name=str(self.o.get("host", "ssh")), gpu=gpu or "unknown", n_gpus=n,
|
|
107
|
+
vram_gb=hw.vram_gb if hw else 0.0, price_per_hour=self.o.get("price_per_hour"), hardware=hw,
|
|
108
|
+
)]
|
|
109
|
+
|
|
110
|
+
def provision(self, offer: Offer) -> Instance:
|
|
111
|
+
root = self.o.get("remote_root", "~/bitstraining")
|
|
112
|
+
wd = f"{root}/job-{secrets.token_hex(3)}"
|
|
113
|
+
self._ok(self.ssh_command(f"mkdir -p {shlex.quote(wd)}"), "creating remote workdir")
|
|
114
|
+
return Instance(id=wd.rsplit("/", 1)[-1], provider=self.name, offer=offer, workdir=wd,
|
|
115
|
+
host=self.o["host"], started=time.time())
|
|
116
|
+
|
|
117
|
+
def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None:
|
|
118
|
+
self._ok(self.rsync_command(f"{bundle_dir}/", f"{inst.workdir}/bundle/", True), "uploading bundle")
|
|
119
|
+
|
|
120
|
+
def launch(self, inst: Instance, job: JobSpec) -> JobHandle:
|
|
121
|
+
pid = self._ok(self.ssh_command(self.remote_launch_script(inst.workdir, job)), "starting job")
|
|
122
|
+
return JobHandle(id=f"{inst.id}-{pid}", instance=inst, log_path=f"{inst.workdir}/job.log",
|
|
123
|
+
started=time.time(), meta={"pid": pid})
|
|
124
|
+
|
|
125
|
+
def status(self, job: JobHandle) -> str:
|
|
126
|
+
wd = job.instance.workdir
|
|
127
|
+
r = self._run(self.ssh_command(f"cat {shlex.quote(wd)}/exit_code 2>/dev/null || echo RUNNING"))
|
|
128
|
+
if r.returncode != 0:
|
|
129
|
+
return "preempted" # host unreachable: spot reclaim or network loss
|
|
130
|
+
out = r.stdout.strip()
|
|
131
|
+
if out == "RUNNING":
|
|
132
|
+
return RUNNING
|
|
133
|
+
return SUCCEEDED if out == "0" else FAILED
|
|
134
|
+
|
|
135
|
+
def stream_logs(self, job: JobHandle) -> Iterator[str]:
|
|
136
|
+
seen = 0
|
|
137
|
+
while True:
|
|
138
|
+
r = self._run(self.ssh_command(f"tail -n +{seen + 1} {shlex.quote(job.log_path)} 2>/dev/null"))
|
|
139
|
+
if r.returncode == 0 and r.stdout:
|
|
140
|
+
lines = r.stdout.splitlines()
|
|
141
|
+
seen += len(lines)
|
|
142
|
+
yield from lines
|
|
143
|
+
if self.status(job) != RUNNING:
|
|
144
|
+
return
|
|
145
|
+
time.sleep(3)
|
|
146
|
+
|
|
147
|
+
def fetch_artifacts(self, job: JobHandle, dest: Path) -> None:
|
|
148
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
149
|
+
self._ok(self.rsync_command(f"{job.instance.workdir}/bundle/output/", f"{dest}/", False), "downloading artifacts")
|
|
150
|
+
|
|
151
|
+
def cancel(self, job: JobHandle) -> None:
|
|
152
|
+
pid = job.meta.get("pid")
|
|
153
|
+
if pid:
|
|
154
|
+
self._run(self.ssh_command(f"kill -TERM -{int(pid)} 2>/dev/null || kill -TERM {int(pid)}"))
|
|
155
|
+
|
|
156
|
+
def teardown(self, inst: Instance) -> None:
|
|
157
|
+
pass # the machine is yours; we leave it running
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core types: schemas, errors, plugin registry, config loading, paths."""
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Loading, validating and saving RunSpec YAML files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
from bitstraining.core.errors import ConfigError
|
|
11
|
+
from bitstraining.core.schemas import ExecutionPlan, RunSpec, from_dict
|
|
12
|
+
|
|
13
|
+
_TASKS = {"sft", "dpo", "orpo", "kto", "pretrain"}
|
|
14
|
+
_OBJECTIVES = {"time", "cost", "memory"}
|
|
15
|
+
_METHODS = {"full", "lora", "qlora", "dora"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_spec(path: str | Path) -> RunSpec:
|
|
19
|
+
p = Path(path)
|
|
20
|
+
if not p.exists():
|
|
21
|
+
raise ConfigError(f"config file not found: {p}", fix="run `bitstraining init` first")
|
|
22
|
+
try:
|
|
23
|
+
raw = yaml.safe_load(p.read_text()) or {}
|
|
24
|
+
except yaml.YAMLError as e:
|
|
25
|
+
raise ConfigError(f"{p} is not valid YAML: {e}") from e
|
|
26
|
+
if not isinstance(raw, dict):
|
|
27
|
+
raise ConfigError(f"{p} must contain a mapping at the top level")
|
|
28
|
+
return spec_from_dict(raw)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def spec_from_dict(raw: dict[str, Any]) -> RunSpec:
|
|
32
|
+
spec = from_dict(RunSpec, raw)
|
|
33
|
+
validate_spec(spec)
|
|
34
|
+
return spec
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_spec(spec: RunSpec) -> None:
|
|
38
|
+
"""Hard validation: raises ConfigError. Softer advice lives in the doctor."""
|
|
39
|
+
g = spec.goal
|
|
40
|
+
if not spec.model.base:
|
|
41
|
+
raise ConfigError("model.base is required", fix="set model.base to a Hugging Face id")
|
|
42
|
+
if not spec.data.train:
|
|
43
|
+
raise ConfigError("data.train is required", fix="point data.train at a JSONL/CSV file")
|
|
44
|
+
if g.task not in _TASKS:
|
|
45
|
+
raise ConfigError(f"goal.task '{g.task}' unsupported", fix=f"use one of {sorted(_TASKS)}")
|
|
46
|
+
if g.objective not in _OBJECTIVES:
|
|
47
|
+
raise ConfigError(f"goal.objective '{g.objective}' unsupported", fix=f"use {sorted(_OBJECTIVES)}")
|
|
48
|
+
if g.methods:
|
|
49
|
+
bad = [m for m in g.methods if m not in _METHODS]
|
|
50
|
+
if bad:
|
|
51
|
+
raise ConfigError(f"unknown methods {bad}", fix=f"use {sorted(_METHODS)}")
|
|
52
|
+
if g.epochs <= 0:
|
|
53
|
+
raise ConfigError("goal.epochs must be > 0")
|
|
54
|
+
if g.global_batch_size < 1:
|
|
55
|
+
raise ConfigError("goal.global_batch_size must be >= 1")
|
|
56
|
+
if not 0 < g.learning_rate < 1:
|
|
57
|
+
raise ConfigError(f"goal.learning_rate {g.learning_rate} is outside (0, 1)")
|
|
58
|
+
if g.lora_r < 1:
|
|
59
|
+
raise ConfigError("goal.lora_r must be >= 1")
|
|
60
|
+
if spec.data.max_length < 8:
|
|
61
|
+
raise ConfigError("data.max_length must be >= 8")
|
|
62
|
+
if spec.data.packing not in {"auto", "on", "off"}:
|
|
63
|
+
raise ConfigError("data.packing must be auto, on or off")
|
|
64
|
+
if not 0 <= spec.data.eval_split < 0.5:
|
|
65
|
+
raise ConfigError("data.eval_split must be in [0, 0.5)")
|
|
66
|
+
if g.budget_usd is not None and g.budget_usd <= 0:
|
|
67
|
+
raise ConfigError("goal.budget_usd must be > 0")
|
|
68
|
+
if g.time_budget_hours is not None and g.time_budget_hours <= 0:
|
|
69
|
+
raise ConfigError("goal.time_budget_hours must be > 0")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def dump_spec(spec: RunSpec, path: str | Path) -> None:
|
|
73
|
+
Path(path).write_text(yaml.safe_dump(spec.to_dict(), sort_keys=False))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def load_plan(path: str | Path) -> ExecutionPlan:
|
|
77
|
+
import json
|
|
78
|
+
|
|
79
|
+
return from_dict(ExecutionPlan, json.loads(Path(path).read_text()))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def save_plan(plan: ExecutionPlan, path: str | Path) -> None:
|
|
83
|
+
import json
|
|
84
|
+
|
|
85
|
+
Path(path).write_text(json.dumps(plan.to_dict(), indent=2, sort_keys=True))
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Exception hierarchy. Every error can carry a human-readable fix suggestion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BitstrainingError(Exception):
|
|
7
|
+
"""Base class. `fix` is shown to the user after the message."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, fix: str | None = None):
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
self.message = message
|
|
12
|
+
self.fix = fix
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
return self.message if not self.fix else f"{self.message}\n fix: {self.fix}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConfigError(BitstrainingError):
|
|
19
|
+
"""The run configuration is invalid."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DataError(BitstrainingError):
|
|
23
|
+
"""A dataset could not be read or is unusable."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PlanningError(BitstrainingError):
|
|
27
|
+
"""No feasible execution plan exists for the request."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class EngineUnavailable(BitstrainingError):
|
|
31
|
+
"""A training engine's library is not installed or the engine is not implemented."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ComputeError(BitstrainingError):
|
|
35
|
+
"""A compute provider failed."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class BudgetExceeded(ComputeError):
|
|
39
|
+
"""A run would exceed (or has exceeded) its hard budget cap."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class OutOfMemory(BitstrainingError):
|
|
43
|
+
"""Raised by probes when a configuration does not fit in device memory."""
|