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,28 @@
1
+ """Bitstraining: Train. Fine-tune. Optimize. Deploy.
2
+
3
+ A hardware-aware orchestration and intelligence layer for model training.
4
+ The core imports no heavy ML library; engines load them lazily.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ from bitstraining.interfaces.api import autotune as tune # noqa: E402 (not `autotune`: that is a subpackage)
10
+ from bitstraining.interfaces.api import ( # noqa: E402
11
+ build_context,
12
+ doctor,
13
+ inspect_data,
14
+ plan,
15
+ profile_hardware,
16
+ train,
17
+ )
18
+
19
+ __all__ = [
20
+ "__version__",
21
+ "build_context",
22
+ "doctor",
23
+ "inspect_data",
24
+ "plan",
25
+ "profile_hardware",
26
+ "train",
27
+ "tune",
28
+ ]
@@ -0,0 +1,7 @@
1
+ """Autotuner: measure, don't guess. Finds the micro-batch that fits and is fastest, learns
2
+ calibration ratios from real probes, and caches results per (hardware, model, strategy)."""
3
+
4
+ from bitstraining.autotune.microbatch import find_max_microbatch
5
+ from bitstraining.autotune.tuner import TuneResult, autotune, bake_off
6
+
7
+ __all__ = ["TuneResult", "autotune", "bake_off", "find_max_microbatch"]
@@ -0,0 +1,39 @@
1
+ """Tuning cache keyed by (hardware, model, strategy) so repeat runs start instantly."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from bitstraining.core import paths
10
+ from bitstraining.core.schemas import ExecutionPlan, HardwareProfile
11
+
12
+
13
+ def cache_key(hw: HardwareProfile, model: str, plan: ExecutionPlan, seq_len: int) -> str:
14
+ return "|".join([
15
+ hw.key, model, plan.engine, plan.method, plan.precision, plan.activation, plan.optimizer,
16
+ f"pack={int(plan.packing)}", f"stream={int(plan.layer_stream)}", f"seq={seq_len}",
17
+ ])
18
+
19
+
20
+ def load(path: Path | None = None) -> dict[str, Any]:
21
+ f = path or paths.tuning_cache()
22
+ if not f.exists():
23
+ return {}
24
+ try:
25
+ return json.loads(f.read_text())
26
+ except (OSError, ValueError):
27
+ return {}
28
+
29
+
30
+ def get(key: str, path: Path | None = None) -> dict[str, Any] | None:
31
+ return load(path).get(key)
32
+
33
+
34
+ def put(key: str, value: dict[str, Any], path: Path | None = None) -> None:
35
+ f = path or paths.tuning_cache()
36
+ data = load(f)
37
+ data[key] = value
38
+ f.parent.mkdir(parents=True, exist_ok=True)
39
+ f.write_text(json.dumps(data, indent=2, sort_keys=True))
@@ -0,0 +1,42 @@
1
+ """OOM-safe search for the largest micro-batch that fits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+
7
+ from bitstraining.engines.base import ProbeResult
8
+
9
+
10
+ def find_max_microbatch(
11
+ probe: Callable[[int], ProbeResult],
12
+ candidates: Sequence[int],
13
+ hint: int | None = None,
14
+ ) -> tuple[int | None, dict[int, ProbeResult]]:
15
+ """Binary search over ascending `candidates`, assuming memory grows monotonically with batch.
16
+
17
+ Returns (largest fitting candidate or None, every probe result obtained). Probing starts at
18
+ `hint` (usually the planner's analytic answer) so a good estimate costs only 2-3 probes.
19
+ """
20
+ cands = sorted(set(candidates))
21
+ results: dict[int, ProbeResult] = {}
22
+
23
+ def fits(mb: int) -> bool:
24
+ if mb not in results:
25
+ results[mb] = probe(mb)
26
+ return results[mb].fits
27
+
28
+ lo, hi = 0, len(cands) - 1
29
+ if hint in cands:
30
+ i = cands.index(hint) # type: ignore[arg-type]
31
+ if fits(cands[i]):
32
+ lo = i + 1
33
+ else:
34
+ hi = i - 1
35
+ while lo <= hi:
36
+ mid = (lo + hi) // 2
37
+ if fits(cands[mid]):
38
+ lo = mid + 1
39
+ else:
40
+ hi = mid - 1
41
+ fitting = [mb for mb, r in results.items() if r.fits]
42
+ return (max(fitting) if fitting else None), results
@@ -0,0 +1,134 @@
1
+ """Autotune a plan against real (or simulated) probes and learn calibration from them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, field, replace
7
+ from pathlib import Path
8
+
9
+ from bitstraining.autotune import cache as cache_mod
10
+ from bitstraining.autotune.microbatch import find_max_microbatch
11
+ from bitstraining.core.schemas import Capabilities, ExecutionPlan
12
+ from bitstraining.engines.base import Engine, ProbeContext, ProbeResult
13
+ from bitstraining.planner import calibration as calib_mod
14
+ from bitstraining.planner.search import MICRO_BATCHES, estimate_plan
15
+ from bitstraining.planner.throughput import device_for
16
+
17
+ SAFETY = 0.95 # never choose a micro-batch whose measured peak exceeds this share of device memory
18
+
19
+
20
+ @dataclass
21
+ class TuneResult:
22
+ plan: ExecutionPlan
23
+ probes: dict[int, ProbeResult] = field(default_factory=dict)
24
+ calibration: dict[str, float] | None = None
25
+ from_cache: bool = False
26
+ notes: list[str] = field(default_factory=list)
27
+
28
+
29
+ def autotune(
30
+ plan: ExecutionPlan,
31
+ ctx: ProbeContext,
32
+ engine: Engine,
33
+ caps: Capabilities | None = None,
34
+ use_cache: bool = True,
35
+ cache_path: Path | None = None,
36
+ calibration_path: Path | None = None,
37
+ ) -> TuneResult:
38
+ """Pick the micro-batch that fits and runs fastest; update calibration from what was measured."""
39
+ hw, g = ctx.hw, ctx.spec.goal
40
+ caps = caps or engine.capabilities(hw)
41
+ vram = device_for(hw).vram_gb
42
+ n_gpus = max(plan.n_gpus, 1)
43
+ cap_mb = max(1, g.global_batch_size // n_gpus)
44
+ cands = [mb for mb in MICRO_BATCHES if mb <= cap_mb] or [1]
45
+ key = cache_mod.cache_key(hw, ctx.model.name, plan, ctx.seq_len)
46
+ notes: list[str] = []
47
+
48
+ cached = cache_mod.get(key, cache_path) if use_cache else None
49
+ if cached and cached.get("micro_batch") in cands:
50
+ mb = int(cached["micro_batch"])
51
+ verify = engine.probe(plan, ctx, mb)
52
+ if verify.fits and (verify.peak_gb or 0) <= vram * SAFETY:
53
+ tuned = _apply(plan, mb, g.global_batch_size, n_gpus)
54
+ tuned.estimate = estimate_plan(tuned, ctx.spec, ctx.model, ctx.stats, hw, caps,
55
+ calibration=calib_mod.load(calibration_path))
56
+ return TuneResult(tuned, {mb: verify}, None, True, ["reused cached tuning (verified with one probe)"])
57
+ notes.append("cached tuning no longer fits; re-tuning")
58
+
59
+ best_mb, probes = find_max_microbatch(lambda mb: engine.probe(plan, ctx, mb), cands, hint=plan.micro_batch)
60
+ if best_mb is None:
61
+ raise_msg = "no micro-batch fits on this device even at 1; plan is infeasible"
62
+ out = replace(plan)
63
+ out.estimate.fits = False
64
+ out.estimate.notes.append(raise_msg)
65
+ return TuneResult(out, probes, None, False, [raise_msg])
66
+
67
+ # Respect the safety margin, then take the fastest measured fitting candidate near the top.
68
+ ok = sorted(
69
+ mb for mb, r in probes.items()
70
+ if r.fits and (r.peak_gb is None or r.peak_gb <= vram * SAFETY)
71
+ )
72
+ if not ok:
73
+ ok = [best_mb]
74
+ notes.append(f"largest fitting batch uses >{SAFETY:.0%} of memory; little headroom for long batches")
75
+ top = ok[-2:] # compare the two largest safe candidates
76
+ for mb in top:
77
+ if mb not in probes:
78
+ probes[mb] = engine.probe(plan, ctx, mb)
79
+ chosen = max(top, key=lambda mb: (probes[mb].tokens_per_s or 0.0, mb))
80
+ tuned = _apply(plan, chosen, g.global_batch_size, n_gpus)
81
+
82
+ # Learn: measured / predicted, using the *uncalibrated* prediction for the chosen batch.
83
+ raw_est = estimate_plan(tuned, ctx.spec, ctx.model, ctx.stats, hw, caps, calibration={})
84
+ pr = probes[chosen]
85
+ cal = None
86
+ if pr.peak_gb and raw_est.peak_gb_per_gpu > 0:
87
+ mem_ratio = pr.peak_gb / raw_est.peak_gb_per_gpu
88
+ speed_ratio = (pr.tokens_per_s / raw_est.raw_tokens_per_s) if pr.tokens_per_s and raw_est.raw_tokens_per_s else None
89
+ cal = calib_mod.update(calib_mod.key(hw.key, plan.engine, plan.method),
90
+ mem_ratio=mem_ratio, speed_ratio=speed_ratio, path=calibration_path)
91
+ notes.append(f"calibration: memory x{cal['mem_ratio']:.2f}, speed x{cal['speed_ratio']:.2f} (n={int(cal['n'])})")
92
+ tuned.estimate = estimate_plan(tuned, ctx.spec, ctx.model, ctx.stats, hw, caps,
93
+ calibration=calib_mod.load(calibration_path))
94
+ cache_mod.put(key, {"micro_batch": chosen, "peak_gb": pr.peak_gb, "tokens_per_s": pr.tokens_per_s}, cache_path)
95
+ if chosen != plan.micro_batch:
96
+ notes.append(f"micro-batch {plan.micro_batch} -> {chosen} (grad_accum {plan.grad_accum} -> {tuned.grad_accum})")
97
+ return TuneResult(tuned, probes, cal, False, notes)
98
+
99
+
100
+ def _apply(plan: ExecutionPlan, mb: int, global_batch: int, n_gpus: int) -> ExecutionPlan:
101
+ return replace(
102
+ plan,
103
+ micro_batch=mb,
104
+ grad_accum=max(1, math.ceil(global_batch / (mb * n_gpus))),
105
+ )
106
+
107
+
108
+ def bake_off(
109
+ plans: list[ExecutionPlan],
110
+ ctx: ProbeContext,
111
+ engines: dict[str, Engine],
112
+ calibration_path: Path | None = None,
113
+ ) -> list[tuple[ExecutionPlan, ProbeResult]]:
114
+ """Probe one plan per engine at its own micro-batch and rank by measured tokens/s.
115
+
116
+ This is how engine claims (e.g. "fused kernels are faster") become measurements on *your*
117
+ hardware: each result also updates that engine's calibration ratios.
118
+ """
119
+ out: list[tuple[ExecutionPlan, ProbeResult]] = []
120
+ for p in plans:
121
+ eng = engines[p.engine]
122
+ caps = eng.capabilities(ctx.hw)
123
+ res = eng.probe(p, ctx, p.micro_batch)
124
+ if res.fits and res.peak_gb:
125
+ raw = estimate_plan(p, ctx.spec, ctx.model, ctx.stats, ctx.hw, caps, calibration={})
126
+ calib_mod.update(
127
+ calib_mod.key(ctx.hw.key, p.engine, p.method),
128
+ mem_ratio=res.peak_gb / raw.peak_gb_per_gpu if raw.peak_gb_per_gpu else None,
129
+ speed_ratio=(res.tokens_per_s / raw.raw_tokens_per_s) if res.tokens_per_s and raw.raw_tokens_per_s else None,
130
+ path=calibration_path,
131
+ )
132
+ out.append((p, res))
133
+ out.sort(key=lambda t: (not t[1].fits, -(t[1].tokens_per_s or 0.0)))
134
+ return out
@@ -0,0 +1,23 @@
1
+ """Unified compute orchestration: one job description, any place to run it."""
2
+
3
+ from bitstraining.compute.base import (
4
+ ComputeProvider,
5
+ Instance,
6
+ JobHandle,
7
+ JobSpec,
8
+ Offer,
9
+ ResourceRequest,
10
+ )
11
+ from bitstraining.compute.bundle import make_bundle
12
+ from bitstraining.compute.orchestrator import run_job
13
+
14
+ __all__ = [
15
+ "ComputeProvider",
16
+ "Instance",
17
+ "JobHandle",
18
+ "JobSpec",
19
+ "Offer",
20
+ "ResourceRequest",
21
+ "make_bundle",
22
+ "run_job",
23
+ ]
@@ -0,0 +1,104 @@
1
+ """Provider interface: the contract every compute backend implements.
2
+
3
+ A job is identical wherever it runs. Providers only move a *bundle* (spec, plan, data, source) to a
4
+ machine, start `python -m bitstraining.runner`, stream its log, and bring the output back.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import abc
10
+ from collections.abc import Iterator
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from bitstraining.core.schemas import HardwareProfile
16
+
17
+
18
+ @dataclass
19
+ class ResourceRequest:
20
+ gpu: str | None = None
21
+ n_gpus: int = 1
22
+ min_vram_gb: float = 0.0
23
+ max_price_per_hour: float | None = None
24
+ spot_ok: bool = True
25
+
26
+
27
+ @dataclass
28
+ class Offer:
29
+ provider: str
30
+ name: str
31
+ gpu: str
32
+ n_gpus: int
33
+ vram_gb: float
34
+ price_per_hour: float | None # whole machine, USD
35
+ spot: bool = False
36
+ region: str = ""
37
+ hardware: HardwareProfile | None = None
38
+ meta: dict[str, Any] = field(default_factory=dict)
39
+
40
+
41
+ @dataclass
42
+ class Instance:
43
+ id: str
44
+ provider: str
45
+ offer: Offer | None = None
46
+ workdir: str = ""
47
+ host: str | None = None
48
+ started: float = 0.0
49
+ meta: dict[str, Any] = field(default_factory=dict)
50
+
51
+
52
+ @dataclass
53
+ class JobSpec:
54
+ name: str
55
+ bundle_dir: str
56
+ command: list[str] = field(default_factory=list) # empty -> provider default runner command
57
+ env: dict[str, str] = field(default_factory=dict)
58
+ max_hours: float | None = None
59
+ resume: bool = False
60
+
61
+
62
+ @dataclass
63
+ class JobHandle:
64
+ id: str
65
+ instance: Instance
66
+ log_path: str = ""
67
+ started: float = 0.0
68
+ meta: dict[str, Any] = field(default_factory=dict)
69
+
70
+
71
+ # Statuses returned by ComputeProvider.status
72
+ RUNNING, SUCCEEDED, FAILED, PREEMPTED, MANUAL = "running", "succeeded", "failed", "preempted", "manual"
73
+
74
+
75
+ class ComputeProvider(abc.ABC):
76
+ name = "provider"
77
+
78
+ @abc.abstractmethod
79
+ def list_offers(self, req: ResourceRequest) -> list[Offer]: ...
80
+
81
+ @abc.abstractmethod
82
+ def provision(self, offer: Offer) -> Instance: ...
83
+
84
+ @abc.abstractmethod
85
+ def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None: ...
86
+
87
+ @abc.abstractmethod
88
+ def launch(self, inst: Instance, job: JobSpec) -> JobHandle: ...
89
+
90
+ @abc.abstractmethod
91
+ def status(self, job: JobHandle) -> str: ...
92
+
93
+ @abc.abstractmethod
94
+ def stream_logs(self, job: JobHandle) -> Iterator[str]:
95
+ """Yield log lines until the job stops."""
96
+
97
+ @abc.abstractmethod
98
+ def fetch_artifacts(self, job: JobHandle, dest: Path) -> None: ...
99
+
100
+ @abc.abstractmethod
101
+ def cancel(self, job: JobHandle) -> None: ...
102
+
103
+ @abc.abstractmethod
104
+ def teardown(self, inst: Instance) -> None: ...
@@ -0,0 +1,64 @@
1
+ """Bundles: a self-contained directory that can run anywhere.
2
+
3
+ bundle/
4
+ spec.yaml RunSpec with data paths rewritten to bundle-relative paths
5
+ plan.json the ExecutionPlan to execute
6
+ data/ copies of the training/eval files
7
+ src/bitstraining/ a copy of this package, so remote machines need no pip install of it
8
+ requirements.txt ML dependencies for the engine
9
+ bootstrap.sh installs requirements and runs the job
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import shutil
15
+ from pathlib import Path
16
+
17
+ import yaml
18
+
19
+ import bitstraining
20
+ from bitstraining.core.config import save_plan
21
+ from bitstraining.core.schemas import ExecutionPlan, RunSpec
22
+
23
+ _REQS = {
24
+ "hf_peft": ["pyyaml", "torch", "transformers>=4.44", "peft>=0.11", "accelerate>=0.30", "datasets"],
25
+ "unsloth": ["pyyaml", "unsloth"],
26
+ "mlx": ["pyyaml", "mlx-lm"],
27
+ "simulate": ["pyyaml"],
28
+ }
29
+
30
+
31
+ def make_bundle(spec: RunSpec, plan: ExecutionPlan, dest: str | Path, include_source: bool = True) -> Path:
32
+ dest = Path(dest)
33
+ if dest.exists():
34
+ shutil.rmtree(dest)
35
+ (dest / "data").mkdir(parents=True)
36
+ d = spec.to_dict()
37
+ for field_name in ("train", "eval"):
38
+ src = d["data"].get(field_name)
39
+ if src and not str(src).startswith("hf://"):
40
+ p = Path(src)
41
+ if p.is_dir():
42
+ shutil.copytree(p, dest / "data" / p.name)
43
+ else:
44
+ shutil.copy2(p, dest / "data" / p.name)
45
+ d["data"][field_name] = f"data/{p.name}"
46
+ d["output"] = "output"
47
+ (dest / "spec.yaml").write_text(yaml.safe_dump(d, sort_keys=False))
48
+ save_plan(plan, dest / "plan.json")
49
+ reqs = list(_REQS.get(plan.engine, ["pyyaml"]))
50
+ if plan.quant == "nf4":
51
+ reqs.append("bitsandbytes>=0.43")
52
+ (dest / "requirements.txt").write_text("\n".join(reqs) + "\n")
53
+ (dest / "bootstrap.sh").write_text(
54
+ "#!/usr/bin/env bash\nset -euo pipefail\n"
55
+ 'cd "$(dirname "$0")"\n'
56
+ "python -m pip install -q -r requirements.txt\n"
57
+ 'PYTHONPATH="$PWD/src${PYTHONPATH:+:$PYTHONPATH}" python -m bitstraining.runner --bundle .\n'
58
+ )
59
+ (dest / "bootstrap.sh").chmod(0o755)
60
+ if include_source:
61
+ pkg = Path(bitstraining.__file__).parent
62
+ shutil.copytree(pkg, dest / "src" / "bitstraining",
63
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
64
+ return dest
@@ -0,0 +1,86 @@
1
+ """Catalog provider: a *planning-only* price list of rentable GPU machines.
2
+
3
+ IMPORTANT: prices below are rough, hand-entered illustrative on-demand USD/hour figures, NOT live quotes
4
+ and NOT tied to any specific vendor's current pricing. Use them to compare options and size a budget;
5
+ check the real price with your provider. Edit `PRICES` or pass `compute.options.prices` to override.
6
+ Real provisioning is not implemented here: `provision` raises. Use `ssh` with a machine you rented.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Iterator
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from bitstraining.compute.base import (
16
+ ComputeProvider,
17
+ Instance,
18
+ JobHandle,
19
+ JobSpec,
20
+ Offer,
21
+ ResourceRequest,
22
+ )
23
+ from bitstraining.core.errors import ComputeError
24
+ from bitstraining.hardware.database import GPU_DB, synthetic_profile
25
+
26
+ # gpu key -> illustrative USD per GPU-hour (order-of-magnitude priors)
27
+ PRICES: dict[str, float] = {
28
+ "t4": 0.35, "l4": 0.70, "a10g": 1.00, "rtx 4090": 0.45, "l40s": 1.50,
29
+ "a100-40gb": 1.80, "a100-80gb": 2.50, "h100": 3.50, "h200": 4.50,
30
+ }
31
+
32
+
33
+ class CatalogProvider(ComputeProvider):
34
+ name = "catalog"
35
+
36
+ def __init__(self, options: dict[str, Any] | None = None):
37
+ self.prices = {**PRICES, **(options or {}).get("prices", {})}
38
+
39
+ def list_offers(self, req: ResourceRequest) -> list[Offer]:
40
+ offers = []
41
+ for gpu, price in sorted(self.prices.items(), key=lambda kv: kv[1]):
42
+ row = GPU_DB.get(gpu)
43
+ if row is None:
44
+ continue
45
+ n = max(req.n_gpus, 1)
46
+ if req.gpu and req.gpu.lower() not in gpu:
47
+ continue
48
+ if row["vram_gb"] < req.min_vram_gb:
49
+ continue
50
+ total = price * n
51
+ if req.max_price_per_hour is not None and total > req.max_price_per_hour:
52
+ continue
53
+ hw = synthetic_profile(gpu, n, total)
54
+ hw.provider = self.name
55
+ offers.append(Offer(provider=self.name, name=f"{n}x {gpu} (illustrative price)", gpu=gpu,
56
+ n_gpus=n, vram_gb=row["vram_gb"], price_per_hour=round(total, 2), hardware=hw,
57
+ meta={"illustrative": True}))
58
+ return offers
59
+
60
+ def _no(self) -> ComputeError:
61
+ return ComputeError("the catalog provider is planning-only and cannot start machines",
62
+ fix="rent a machine from your provider and use compute.provider: ssh")
63
+
64
+ def provision(self, offer: Offer) -> Instance:
65
+ raise self._no()
66
+
67
+ def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None:
68
+ raise self._no()
69
+
70
+ def launch(self, inst: Instance, job: JobSpec) -> JobHandle:
71
+ raise self._no()
72
+
73
+ def status(self, job: JobHandle) -> str:
74
+ raise self._no()
75
+
76
+ def stream_logs(self, job: JobHandle) -> Iterator[str]:
77
+ raise self._no()
78
+
79
+ def fetch_artifacts(self, job: JobHandle, dest: Path) -> None:
80
+ raise self._no()
81
+
82
+ def cancel(self, job: JobHandle) -> None:
83
+ raise self._no()
84
+
85
+ def teardown(self, inst: Instance) -> None:
86
+ pass
@@ -0,0 +1,107 @@
1
+ """Docker provider: run the bundle inside a container (local daemon or DOCKER_HOST).
2
+
3
+ Options: image (default "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime"), gpus ("all" by default;
4
+ set "" for CPU-only), price_per_hour.
5
+
6
+ NOT exercised by CI (needs a Docker daemon). Command construction is unit-tested.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import secrets
12
+ import shutil
13
+ import subprocess
14
+ import time
15
+ from collections.abc import Iterator
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from bitstraining.compute.base import (
20
+ FAILED,
21
+ RUNNING,
22
+ SUCCEEDED,
23
+ ComputeProvider,
24
+ Instance,
25
+ JobHandle,
26
+ JobSpec,
27
+ Offer,
28
+ ResourceRequest,
29
+ )
30
+ from bitstraining.core import paths
31
+ from bitstraining.core.errors import ComputeError
32
+ from bitstraining.hardware.profiler import profile
33
+
34
+ DEFAULT_IMAGE = "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime"
35
+
36
+
37
+ class DockerProvider(ComputeProvider):
38
+ name = "docker"
39
+
40
+ def __init__(self, options: dict[str, Any] | None = None, runner: Any = None):
41
+ self.o = dict(options or {})
42
+ self._run = runner or (lambda cmd: subprocess.run(cmd, capture_output=True, text=True, check=False))
43
+
44
+ def run_command(self, name: str, workdir: str, job: JobSpec) -> list[str]:
45
+ cmd = ["docker", "run", "-d", "--name", name, "-v", f"{workdir}/bundle:/job", "-w", "/job"]
46
+ gpus = self.o.get("gpus", "all")
47
+ if gpus:
48
+ cmd += ["--gpus", str(gpus)]
49
+ for k, v in job.env.items():
50
+ cmd += ["-e", f"{k}={v}"]
51
+ inner = "bash bootstrap.sh" + (" --resume" if job.resume else "")
52
+ return [*cmd, self.o.get("image", DEFAULT_IMAGE), "bash", "-lc", inner]
53
+
54
+ def list_offers(self, req: ResourceRequest) -> list[Offer]:
55
+ hw = profile()
56
+ g = hw.gpus[0] if hw.gpus else None
57
+ return [Offer(provider=self.name, name="docker (local daemon)", gpu=g.name if g else "cpu",
58
+ n_gpus=hw.n_gpus, vram_gb=g.vram_gb if g else 0.0,
59
+ price_per_hour=self.o.get("price_per_hour", 0.0), hardware=hw)]
60
+
61
+ def provision(self, offer: Offer) -> Instance:
62
+ if not shutil.which("docker"):
63
+ raise ComputeError("docker is not installed or not on PATH", fix="install Docker or use provider: local")
64
+ work = paths.home() / "jobs" / f"docker-{secrets.token_hex(3)}"
65
+ work.mkdir(parents=True, exist_ok=True)
66
+ return Instance(id=work.name, provider=self.name, offer=offer, workdir=str(work), started=time.time())
67
+
68
+ def sync_workspace(self, inst: Instance, bundle_dir: Path) -> None:
69
+ target = Path(inst.workdir) / "bundle"
70
+ if target.exists():
71
+ shutil.rmtree(target)
72
+ shutil.copytree(bundle_dir, target)
73
+
74
+ def launch(self, inst: Instance, job: JobSpec) -> JobHandle:
75
+ name = f"bt-{inst.id}"
76
+ r = self._run(self.run_command(name, inst.workdir, job))
77
+ if r.returncode != 0:
78
+ raise ComputeError(f"docker run failed: {r.stderr.strip()[:300]}")
79
+ return JobHandle(id=name, instance=inst, log_path="", started=time.time(), meta={"container": name})
80
+
81
+ def status(self, job: JobHandle) -> str:
82
+ r = self._run(["docker", "inspect", "-f", "{{.State.Status}} {{.State.ExitCode}}", job.id])
83
+ if r.returncode != 0:
84
+ return FAILED
85
+ state, _, code = r.stdout.strip().partition(" ")
86
+ if state in ("running", "created", "restarting"):
87
+ return RUNNING
88
+ return SUCCEEDED if code == "0" else FAILED
89
+
90
+ def stream_logs(self, job: JobHandle) -> Iterator[str]:
91
+ proc = subprocess.Popen(["docker", "logs", "-f", job.id], stdout=subprocess.PIPE,
92
+ stderr=subprocess.STDOUT, text=True)
93
+ assert proc.stdout is not None
94
+ yield from (line.rstrip() for line in proc.stdout)
95
+ proc.wait()
96
+
97
+ def fetch_artifacts(self, job: JobHandle, dest: Path) -> None:
98
+ src = Path(job.instance.workdir) / "bundle" / "output"
99
+ if src.exists():
100
+ dest.mkdir(parents=True, exist_ok=True)
101
+ shutil.copytree(src, dest, dirs_exist_ok=True)
102
+
103
+ def cancel(self, job: JobHandle) -> None:
104
+ self._run(["docker", "stop", job.id])
105
+
106
+ def teardown(self, inst: Instance) -> None:
107
+ self._run(["docker", "rm", "-f", f"bt-{inst.id}"])