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,228 @@
|
|
|
1
|
+
"""Derive exact parameter counts and layer shapes from a model's config, never its weights.
|
|
2
|
+
|
|
3
|
+
Resolution order for `load_model_info(name_or_path)`:
|
|
4
|
+
1. a local directory containing config.json
|
|
5
|
+
2. a built-in preset table (public architecture hyper-parameters)
|
|
6
|
+
3. the Hugging Face Hub's config.json (small download; skipped when offline)
|
|
7
|
+
4. a size parsed from the name ("...-7b"), mapped onto the nearest preset's shape
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from bitstraining.core.errors import ConfigError
|
|
21
|
+
from bitstraining.core.schemas import ModelInfo
|
|
22
|
+
|
|
23
|
+
# name-fragment -> hyper-parameters
|
|
24
|
+
_PRESETS: dict[str, dict[str, Any]] = {
|
|
25
|
+
"smollm2-135m": dict(h=576, L=30, heads=9, kv=3, inter=1536, vocab=49152, tied=True),
|
|
26
|
+
"gpt2": dict(h=768, L=12, heads=12, kv=12, inter=3072, vocab=50257, tied=True, gated=False, arch="gpt2", max_pos=1024),
|
|
27
|
+
"qwen2.5-0.5b": dict(h=896, L=24, heads=14, kv=2, inter=4864, vocab=151936, tied=True, arch="qwen2"),
|
|
28
|
+
"tinyllama-1.1b": dict(h=2048, L=22, heads=32, kv=4, inter=5632, vocab=32000, tied=False),
|
|
29
|
+
"llama-3.2-1b": dict(h=2048, L=16, heads=32, kv=8, inter=8192, vocab=128256, tied=True),
|
|
30
|
+
"qwen2.5-1.5b": dict(h=1536, L=28, heads=12, kv=2, inter=8960, vocab=151936, tied=True, arch="qwen2"),
|
|
31
|
+
"llama-3.2-3b": dict(h=3072, L=28, heads=24, kv=8, inter=8192, vocab=128256, tied=True),
|
|
32
|
+
"qwen2.5-3b": dict(h=2048, L=36, heads=16, kv=2, inter=11008, vocab=151936, tied=True, arch="qwen2"),
|
|
33
|
+
"phi-3-mini": dict(h=3072, L=32, heads=32, kv=32, inter=8192, vocab=32064, tied=False, arch="phi3"),
|
|
34
|
+
"mistral-7b": dict(h=4096, L=32, heads=32, kv=8, inter=14336, vocab=32000, tied=False, arch="mistral"),
|
|
35
|
+
"qwen2.5-7b": dict(h=3584, L=28, heads=28, kv=4, inter=18944, vocab=152064, tied=False, arch="qwen2"),
|
|
36
|
+
"llama-3.1-8b": dict(h=4096, L=32, heads=32, kv=8, inter=14336, vocab=128256, tied=False, max_pos=131072),
|
|
37
|
+
"llama-3-8b": dict(h=4096, L=32, heads=32, kv=8, inter=14336, vocab=128256, tied=False, max_pos=8192),
|
|
38
|
+
"qwen2.5-14b": dict(h=5120, L=48, heads=40, kv=8, inter=13824, vocab=152064, tied=False, arch="qwen2"),
|
|
39
|
+
"llama-3.1-70b": dict(h=8192, L=80, heads=64, kv=8, inter=28672, vocab=128256, tied=False, max_pos=131072),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
_STRIP = re.compile(r"-(instruct|chat|it|base|hf|bnb-4bit|4bit|awq|gptq|v\d+(\.\d+)*)$")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def compute_params(
|
|
46
|
+
h: int,
|
|
47
|
+
L: int,
|
|
48
|
+
heads: int,
|
|
49
|
+
kv: int,
|
|
50
|
+
inter: int,
|
|
51
|
+
vocab: int,
|
|
52
|
+
tied: bool,
|
|
53
|
+
head_dim: int | None = None,
|
|
54
|
+
gated: bool = True,
|
|
55
|
+
experts: int = 1,
|
|
56
|
+
) -> int:
|
|
57
|
+
"""Exact parameter count of a decoder-only transformer from its shape (biases ignored)."""
|
|
58
|
+
hd = head_dim or h // heads
|
|
59
|
+
attn = h * heads * hd + 2 * h * kv * hd + heads * hd * h
|
|
60
|
+
mlp_mats = 3 if gated else 2
|
|
61
|
+
mlp = mlp_mats * h * inter * experts + (h * experts if experts > 1 else 0)
|
|
62
|
+
per_layer = attn + mlp + 2 * h
|
|
63
|
+
embed = vocab * h * (1 if tied else 2)
|
|
64
|
+
return L * per_layer + h + embed
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _info(name: str, source: str, **p: Any) -> ModelInfo:
|
|
68
|
+
experts = p.get("experts", 1)
|
|
69
|
+
params = compute_params(
|
|
70
|
+
p["h"], p["L"], p["heads"], p["kv"], p["inter"], p["vocab"], p["tied"],
|
|
71
|
+
head_dim=p.get("head_dim"), gated=p.get("gated", True), experts=experts,
|
|
72
|
+
)
|
|
73
|
+
return ModelInfo(
|
|
74
|
+
name=name,
|
|
75
|
+
architecture=p.get("arch", "llama"),
|
|
76
|
+
params=params,
|
|
77
|
+
hidden_size=p["h"],
|
|
78
|
+
num_layers=p["L"],
|
|
79
|
+
num_heads=p["heads"],
|
|
80
|
+
num_kv_heads=p["kv"],
|
|
81
|
+
intermediate_size=p["inter"],
|
|
82
|
+
vocab_size=p["vocab"],
|
|
83
|
+
tie_embeddings=p["tied"],
|
|
84
|
+
max_position=p.get("max_pos", 4096),
|
|
85
|
+
num_experts=experts,
|
|
86
|
+
active_experts=p.get("active", 1),
|
|
87
|
+
gated_mlp=p.get("gated", True),
|
|
88
|
+
head_dim_override=p.get("head_dim") or 0,
|
|
89
|
+
source=source,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def from_hf_config(cfg: dict[str, Any], name: str = "", source: str = "config") -> ModelInfo:
|
|
94
|
+
"""Build ModelInfo from a Hugging Face `config.json` dictionary."""
|
|
95
|
+
mtype = cfg.get("model_type", "llama")
|
|
96
|
+
if mtype == "gpt2":
|
|
97
|
+
return _info(
|
|
98
|
+
name, source, h=cfg["n_embd"], L=cfg["n_layer"], heads=cfg["n_head"], kv=cfg["n_head"],
|
|
99
|
+
inter=cfg.get("n_inner") or 4 * cfg["n_embd"], vocab=cfg["vocab_size"],
|
|
100
|
+
tied=True, gated=False, arch="gpt2", max_pos=cfg.get("n_positions", 1024),
|
|
101
|
+
)
|
|
102
|
+
try:
|
|
103
|
+
h = cfg["hidden_size"]
|
|
104
|
+
heads = cfg["num_attention_heads"]
|
|
105
|
+
p = dict(
|
|
106
|
+
h=h,
|
|
107
|
+
L=cfg["num_hidden_layers"],
|
|
108
|
+
heads=heads,
|
|
109
|
+
kv=cfg.get("num_key_value_heads") or heads,
|
|
110
|
+
inter=cfg.get("intermediate_size") or 4 * h,
|
|
111
|
+
vocab=cfg["vocab_size"],
|
|
112
|
+
tied=bool(cfg.get("tie_word_embeddings", False)),
|
|
113
|
+
arch=mtype,
|
|
114
|
+
max_pos=cfg.get("max_position_embeddings", 4096),
|
|
115
|
+
)
|
|
116
|
+
except KeyError as e:
|
|
117
|
+
raise ConfigError(
|
|
118
|
+
f"config.json for '{name}' lacks {e}", fix="is this a decoder-only transformer config?"
|
|
119
|
+
) from e
|
|
120
|
+
if cfg.get("head_dim"):
|
|
121
|
+
p["head_dim"] = int(cfg["head_dim"])
|
|
122
|
+
experts = cfg.get("num_local_experts") or cfg.get("num_experts") or 1
|
|
123
|
+
if experts and experts > 1:
|
|
124
|
+
p["experts"] = int(experts)
|
|
125
|
+
p["active"] = int(cfg.get("num_experts_per_tok", 2))
|
|
126
|
+
p["inter"] = cfg.get("moe_intermediate_size", p["inter"])
|
|
127
|
+
return _info(name, source, **p)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _normalize(name: str) -> str:
|
|
131
|
+
base = name.rstrip("/").split("/")[-1].lower().replace("_", "-")
|
|
132
|
+
prev = None
|
|
133
|
+
while prev != base:
|
|
134
|
+
prev = base
|
|
135
|
+
base = _STRIP.sub("", base)
|
|
136
|
+
return base.replace("meta-llama-", "llama-")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _preset_for(name: str) -> ModelInfo | None:
|
|
140
|
+
norm = _normalize(name)
|
|
141
|
+
for key in sorted(_PRESETS, key=len, reverse=True):
|
|
142
|
+
if key in norm:
|
|
143
|
+
return _info(name, "preset", **_PRESETS[key])
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _size_from_name(name: str) -> float | None:
|
|
148
|
+
m = re.search(r"(\d+(?:\.\d+)?)\s*([bBmM])(?![a-zA-Z])", name.split("/")[-1])
|
|
149
|
+
if not m:
|
|
150
|
+
return None
|
|
151
|
+
val = float(m.group(1))
|
|
152
|
+
return val * 1e9 if m.group(2).lower() == "b" else val * 1e6
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _heuristic(name: str) -> ModelInfo | None:
|
|
156
|
+
size = _size_from_name(name)
|
|
157
|
+
if size is None:
|
|
158
|
+
return None
|
|
159
|
+
nearest = min(_PRESETS, key=lambda k: abs(_info(k, "x", **_PRESETS[k]).params - size))
|
|
160
|
+
info = _info(name, "name-heuristic", **_PRESETS[nearest])
|
|
161
|
+
info.params = int(size) # trust the advertised size; shape comes from the nearest preset
|
|
162
|
+
return info
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _hub_config(name: str, timeout: float = 5.0) -> dict[str, Any] | None:
|
|
166
|
+
if os.environ.get("BITSTRAINING_OFFLINE") == "1" or os.environ.get("HF_HUB_OFFLINE") == "1":
|
|
167
|
+
return None
|
|
168
|
+
if "/" not in name:
|
|
169
|
+
return None
|
|
170
|
+
req = urllib.request.Request(f"https://huggingface.co/{name}/raw/main/config.json")
|
|
171
|
+
token = os.environ.get("HF_TOKEN")
|
|
172
|
+
if token:
|
|
173
|
+
req.add_header("Authorization", f"Bearer {token}")
|
|
174
|
+
try:
|
|
175
|
+
with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310
|
|
176
|
+
return json.loads(r.read().decode())
|
|
177
|
+
except (urllib.error.URLError, TimeoutError, ValueError, OSError):
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def load_model_info(name_or_path: str, allow_network: bool = True) -> ModelInfo:
|
|
182
|
+
p = Path(name_or_path)
|
|
183
|
+
if p.is_dir() and (p / "config.json").exists():
|
|
184
|
+
return from_hf_config(json.loads((p / "config.json").read_text()), name_or_path, "config")
|
|
185
|
+
info = _preset_for(name_or_path)
|
|
186
|
+
if info:
|
|
187
|
+
return info
|
|
188
|
+
if allow_network:
|
|
189
|
+
cfg = _hub_config(name_or_path)
|
|
190
|
+
if cfg:
|
|
191
|
+
try:
|
|
192
|
+
return from_hf_config(cfg, name_or_path, "hub")
|
|
193
|
+
except ConfigError:
|
|
194
|
+
pass
|
|
195
|
+
info = _heuristic(name_or_path)
|
|
196
|
+
if info:
|
|
197
|
+
return info
|
|
198
|
+
raise ConfigError(
|
|
199
|
+
f"cannot determine the architecture of '{name_or_path}'",
|
|
200
|
+
fix="use a local directory with config.json, a known model, or a name containing the size (e.g. '-7b')",
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def lora_param_count(m: ModelInfo, r: int, target: str = "all-linear") -> int:
|
|
205
|
+
"""Trainable LoRA parameters: r * (in + out) for each targeted linear layer."""
|
|
206
|
+
hd = m.head_dim
|
|
207
|
+
h, q_out, kv_out = m.hidden_size, m.num_heads * hd, m.num_kv_heads * hd
|
|
208
|
+
attn = {
|
|
209
|
+
"q_proj": h + q_out,
|
|
210
|
+
"k_proj": h + kv_out,
|
|
211
|
+
"v_proj": h + kv_out,
|
|
212
|
+
"o_proj": q_out + h,
|
|
213
|
+
}
|
|
214
|
+
mlp_dim = h + m.intermediate_size
|
|
215
|
+
mlp = {"up_proj": mlp_dim, "down_proj": mlp_dim}
|
|
216
|
+
if m.gated_mlp:
|
|
217
|
+
mlp["gate_proj"] = mlp_dim
|
|
218
|
+
experts = max(m.num_experts, 1)
|
|
219
|
+
if target == "all-linear":
|
|
220
|
+
per_layer = sum(attn.values()) + sum(mlp.values()) * experts
|
|
221
|
+
elif target == "attention":
|
|
222
|
+
per_layer = sum(attn.values())
|
|
223
|
+
elif target == "qv":
|
|
224
|
+
per_layer = attn["q_proj"] + attn["v_proj"]
|
|
225
|
+
else:
|
|
226
|
+
names = [t.strip() for t in target.split(",")]
|
|
227
|
+
per_layer = sum(attn.get(n, 0) + mlp.get(n, 0) * experts for n in names)
|
|
228
|
+
return r * per_layer * m.num_layers
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Post-training optimization: merge adapters, quantize. Heavy libraries are imported lazily."""
|
|
2
|
+
|
|
3
|
+
from bitstraining.optimize.merge import merge_adapter
|
|
4
|
+
from bitstraining.optimize.quantize import gguf_command, quantize_gguf
|
|
5
|
+
|
|
6
|
+
__all__ = ["gguf_command", "merge_adapter", "quantize_gguf"]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Merge a LoRA adapter into its base model and save a standalone checkpoint (needs torch+peft).
|
|
2
|
+
|
|
3
|
+
NOT exercised by CI. Merging into a quantized base is lossy and is refused: merge into the bf16 base.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from bitstraining.core.errors import EngineUnavailable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def merge_adapter(base: str, adapter: str, dest: str | Path, dtype: str = "bfloat16") -> Path:
|
|
14
|
+
try:
|
|
15
|
+
import torch
|
|
16
|
+
from peft import PeftModel
|
|
17
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
18
|
+
except ImportError as e:
|
|
19
|
+
raise EngineUnavailable("merging needs torch, transformers and peft", fix="pip install 'bitstraining[train]'") from e
|
|
20
|
+
model = AutoModelForCausalLM.from_pretrained(base, torch_dtype=getattr(torch, dtype))
|
|
21
|
+
merged = PeftModel.from_pretrained(model, adapter).merge_and_unload()
|
|
22
|
+
dest = Path(dest)
|
|
23
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
merged.save_pretrained(dest, safe_serialization=True)
|
|
25
|
+
AutoTokenizer.from_pretrained(base).save_pretrained(dest)
|
|
26
|
+
return dest
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""GGUF export through llama.cpp's own tools (this module only builds and runs the commands).
|
|
2
|
+
|
|
3
|
+
Requires a llama.cpp checkout (set LLAMA_CPP_DIR) with `convert_hf_to_gguf.py` and a built `llama-quantize`.
|
|
4
|
+
NOT exercised by CI; `gguf_command` is a pure function and is unit-tested.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from bitstraining.core.errors import EngineUnavailable
|
|
15
|
+
|
|
16
|
+
QUANTS = {"f16", "q8_0", "q6_k", "q5_k_m", "q4_k_m", "q4_0", "q3_k_m", "q2_k"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def gguf_command(model_dir: str, out_file: str, quant: str, llama_cpp: str) -> list[list[str]]:
|
|
20
|
+
"""The commands (convert to f16 GGUF, then quantize) for a merged model directory."""
|
|
21
|
+
if quant not in QUANTS:
|
|
22
|
+
raise ValueError(f"unknown quant '{quant}'; choose from {sorted(QUANTS)}")
|
|
23
|
+
f16 = str(Path(out_file).with_suffix("")) + ".f16.gguf"
|
|
24
|
+
convert = [sys.executable, str(Path(llama_cpp) / "convert_hf_to_gguf.py"), model_dir, "--outfile",
|
|
25
|
+
f16, "--outtype", "f16"]
|
|
26
|
+
if quant == "f16":
|
|
27
|
+
return [convert[:-2] + ["--outfile", out_file, "--outtype", "f16"]]
|
|
28
|
+
return [convert, [str(Path(llama_cpp) / "build" / "bin" / "llama-quantize"), f16, out_file, quant.upper()]]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def quantize_gguf(model_dir: str, out_file: str, quant: str = "q4_k_m") -> Path:
|
|
32
|
+
root = os.environ.get("LLAMA_CPP_DIR")
|
|
33
|
+
if not root or not (Path(root) / "convert_hf_to_gguf.py").exists():
|
|
34
|
+
raise EngineUnavailable("llama.cpp not found", fix="clone llama.cpp, build it, and set LLAMA_CPP_DIR")
|
|
35
|
+
for cmd in gguf_command(model_dir, out_file, quant, root):
|
|
36
|
+
subprocess.run(cmd, check=True)
|
|
37
|
+
return Path(out_file)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""The intelligence layer: memory and throughput cost models, plan search, doctor."""
|
|
2
|
+
|
|
3
|
+
from bitstraining.planner.doctor import DoctorReport, Finding, run_doctor
|
|
4
|
+
from bitstraining.planner.memory import estimate_memory
|
|
5
|
+
from bitstraining.planner.search import make_plans
|
|
6
|
+
from bitstraining.planner.throughput import estimate_throughput
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"DoctorReport",
|
|
10
|
+
"Finding",
|
|
11
|
+
"estimate_memory",
|
|
12
|
+
"estimate_throughput",
|
|
13
|
+
"make_plans",
|
|
14
|
+
"run_doctor",
|
|
15
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Calibration store: measured/predicted ratios learned from real probe runs.
|
|
2
|
+
|
|
3
|
+
Keyed by "<hardware key>|<engine>|<method>". The planner multiplies its memory estimate and
|
|
4
|
+
throughput estimate by these ratios, so predictions improve with use on a given machine.
|
|
5
|
+
Ratios are smoothed with an exponential moving average and clamped to a sane range so a single
|
|
6
|
+
bad probe cannot poison later plans.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from bitstraining.core import paths
|
|
15
|
+
|
|
16
|
+
_LO, _HI = 0.4, 2.5
|
|
17
|
+
_ALPHA = 0.5
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _file(path: Path | None) -> Path:
|
|
21
|
+
return path or paths.calibration_file()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load(path: Path | None = None) -> dict[str, dict[str, float]]:
|
|
25
|
+
f = _file(path)
|
|
26
|
+
if not f.exists():
|
|
27
|
+
return {}
|
|
28
|
+
try:
|
|
29
|
+
return json.loads(f.read_text())
|
|
30
|
+
except (OSError, ValueError):
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def key(hw_key: str, engine: str, method: str) -> str:
|
|
35
|
+
return f"{hw_key}|{engine}|{method}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get(k: str, path: Path | None = None) -> dict[str, float] | None:
|
|
39
|
+
return load(path).get(k)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def update(
|
|
43
|
+
k: str,
|
|
44
|
+
mem_ratio: float | None = None,
|
|
45
|
+
speed_ratio: float | None = None,
|
|
46
|
+
path: Path | None = None,
|
|
47
|
+
) -> dict[str, float]:
|
|
48
|
+
"""Fold a new observation (measured / predicted) into the stored ratios."""
|
|
49
|
+
data = load(path)
|
|
50
|
+
cur = data.get(k, {"mem_ratio": 1.0, "speed_ratio": 1.0, "n": 0})
|
|
51
|
+
n = cur.get("n", 0)
|
|
52
|
+
for name, val in (("mem_ratio", mem_ratio), ("speed_ratio", speed_ratio)):
|
|
53
|
+
if val is None or val <= 0:
|
|
54
|
+
continue
|
|
55
|
+
val = min(max(val, _LO), _HI)
|
|
56
|
+
cur[name] = val if n == 0 else (1 - _ALPHA) * cur.get(name, 1.0) + _ALPHA * val
|
|
57
|
+
cur["n"] = n + 1
|
|
58
|
+
data[k] = cur
|
|
59
|
+
f = _file(path)
|
|
60
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
f.write_text(json.dumps(data, indent=2, sort_keys=True))
|
|
62
|
+
return cur
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Pre-flight doctor: catch problems before any GPU time is spent.
|
|
2
|
+
|
|
3
|
+
Every finding carries a fix suggestion. `errors` block a run; `warnings` should be read.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import importlib.util
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from bitstraining.core.schemas import (
|
|
15
|
+
DatasetStats,
|
|
16
|
+
ExecutionPlan,
|
|
17
|
+
HardwareProfile,
|
|
18
|
+
ModelInfo,
|
|
19
|
+
RunSpec,
|
|
20
|
+
)
|
|
21
|
+
from bitstraining.data.schema import row_sequences
|
|
22
|
+
from bitstraining.planner.throughput import device_for
|
|
23
|
+
from bitstraining.strategies.catalog import METHODS
|
|
24
|
+
|
|
25
|
+
ERROR, WARN, INFO = "error", "warning", "info"
|
|
26
|
+
_VALID_ROLES = {"system", "user", "assistant", "tool"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Finding:
|
|
31
|
+
level: str
|
|
32
|
+
code: str
|
|
33
|
+
message: str
|
|
34
|
+
fix: str = ""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class DoctorReport:
|
|
39
|
+
findings: list[Finding] = field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
def add(self, level: str, code: str, message: str, fix: str = "") -> None:
|
|
42
|
+
self.findings.append(Finding(level, code, message, fix))
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def errors(self) -> list[Finding]:
|
|
46
|
+
return [f for f in self.findings if f.level == ERROR]
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def warnings(self) -> list[Finding]:
|
|
50
|
+
return [f for f in self.findings if f.level == WARN]
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def ok(self) -> bool:
|
|
54
|
+
return not self.errors
|
|
55
|
+
|
|
56
|
+
def render(self) -> str:
|
|
57
|
+
if not self.findings:
|
|
58
|
+
return "doctor: all checks passed"
|
|
59
|
+
mark = {ERROR: "ERROR", WARN: "WARN ", INFO: "info "}
|
|
60
|
+
lines = []
|
|
61
|
+
for f in sorted(self.findings, key=lambda x: (x.level != ERROR, x.level != WARN, x.code)):
|
|
62
|
+
lines.append(f"[{mark[f.level]}] {f.code}: {f.message}")
|
|
63
|
+
if f.fix:
|
|
64
|
+
lines.append(f" fix: {f.fix}")
|
|
65
|
+
lines.append(f"doctor: {len(self.errors)} error(s), {len(self.warnings)} warning(s)")
|
|
66
|
+
return "\n".join(lines)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _have(mod: str) -> bool:
|
|
70
|
+
return importlib.util.find_spec(mod) is not None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def run_doctor(
|
|
74
|
+
spec: RunSpec,
|
|
75
|
+
hw: HardwareProfile | None = None,
|
|
76
|
+
model: ModelInfo | None = None,
|
|
77
|
+
stats: DatasetStats | None = None,
|
|
78
|
+
plans: list[ExecutionPlan] | None = None,
|
|
79
|
+
plan_error: str | None = None,
|
|
80
|
+
train_rows: list[dict[str, Any]] | None = None,
|
|
81
|
+
eval_rows: list[dict[str, Any]] | None = None,
|
|
82
|
+
check_imports: bool = True,
|
|
83
|
+
) -> DoctorReport:
|
|
84
|
+
rep = DoctorReport()
|
|
85
|
+
g, d = spec.goal, spec.data
|
|
86
|
+
|
|
87
|
+
# --- config sanity -----------------------------------------------------------------
|
|
88
|
+
if g.learning_rate > 1e-3:
|
|
89
|
+
rep.add(WARN, "DR010", f"learning_rate {g.learning_rate:g} is very high for fine-tuning",
|
|
90
|
+
"typical values: 1e-4 to 3e-4 for LoRA, 1e-5 to 5e-5 for full fine-tuning")
|
|
91
|
+
methods = g.methods or []
|
|
92
|
+
if methods == ["full"] and g.learning_rate > 1e-4:
|
|
93
|
+
rep.add(WARN, "DR011", f"learning_rate {g.learning_rate:g} is high for full fine-tuning",
|
|
94
|
+
"use <= 5e-5")
|
|
95
|
+
if g.learning_rate < 1e-6:
|
|
96
|
+
rep.add(WARN, "DR012", f"learning_rate {g.learning_rate:g} is extremely low; the model may not change",
|
|
97
|
+
"raise it or check for a unit mistake")
|
|
98
|
+
if g.lora_r > 256:
|
|
99
|
+
rep.add(WARN, "DR013", f"lora_r {g.lora_r} is unusually large", "r of 8-64 covers most tasks")
|
|
100
|
+
if g.lora_alpha < g.lora_r / 4:
|
|
101
|
+
rep.add(WARN, "DR014", "lora_alpha is much smaller than lora_r, which scales the adapter down",
|
|
102
|
+
"common choice: lora_alpha = 2 * lora_r")
|
|
103
|
+
if Path(spec.output).resolve() == Path(d.train).resolve():
|
|
104
|
+
rep.add(ERROR, "DR015", "output path equals the training data path", "choose a different output directory")
|
|
105
|
+
|
|
106
|
+
# --- data --------------------------------------------------------------------------
|
|
107
|
+
if not (d.train.startswith("hf://") or Path(d.train).exists()):
|
|
108
|
+
rep.add(ERROR, "DR001", f"training data not found: {d.train}", "check data.train")
|
|
109
|
+
if d.eval and not (d.eval.startswith("hf://") or Path(d.eval).exists()):
|
|
110
|
+
rep.add(ERROR, "DR016", f"eval data not found: {d.eval}", "check data.eval")
|
|
111
|
+
if stats is not None:
|
|
112
|
+
if stats.num_rows == 0:
|
|
113
|
+
rep.add(ERROR, "DR002", "no usable rows after cleaning", "run `bitstraining data inspect`")
|
|
114
|
+
elif stats.num_rows < 50:
|
|
115
|
+
rep.add(WARN, "DR003", f"only {stats.num_rows} usable rows", "expect overfitting; 500+ is a safer floor")
|
|
116
|
+
if stats.schema == "unknown":
|
|
117
|
+
rep.add(ERROR, "DR004", "dataset schema not recognized",
|
|
118
|
+
"use columns: instruction/output, prompt/completion, messages, chosen/rejected or text")
|
|
119
|
+
if g.task in ("dpo", "orpo", "kto") and stats.schema != "preference":
|
|
120
|
+
rep.add(ERROR, "DR017", f"task '{g.task}' needs preference data (prompt, chosen, rejected) but found '{stats.schema}'",
|
|
121
|
+
"provide chosen/rejected columns or use task: sft")
|
|
122
|
+
if g.task == "sft" and stats.schema == "preference":
|
|
123
|
+
rep.add(ERROR, "DR018", "task 'sft' selected but the data is preference pairs", "set goal.task to dpo, or convert the data")
|
|
124
|
+
if stats.empty_rate > 0.02:
|
|
125
|
+
rep.add(WARN, "DR005", f"{stats.empty_rate:.1%} of rows are empty or lack an assistant reply", "clean the source data")
|
|
126
|
+
if stats.duplicate_rate > 0.05:
|
|
127
|
+
rep.add(WARN, "DR006", f"{stats.duplicate_rate:.1%} of rows are exact duplicates", "keep data.dedup: true")
|
|
128
|
+
if stats.truncation_rate > 0.05:
|
|
129
|
+
sev = ERROR if stats.truncation_rate > 0.5 else WARN
|
|
130
|
+
rep.add(sev, "DR007", f"{stats.truncation_rate:.0%} of sequences exceed max_length {d.max_length} and will be cut",
|
|
131
|
+
f"raise data.max_length (p95 is {stats.p95_len} tokens) or shorten examples")
|
|
132
|
+
if stats.num_rows and g.global_batch_size > stats.num_rows:
|
|
133
|
+
rep.add(ERROR, "DR019", f"global_batch_size {g.global_batch_size} exceeds the {stats.num_rows} rows available",
|
|
134
|
+
"lower goal.global_batch_size")
|
|
135
|
+
elif stats.num_rows:
|
|
136
|
+
steps = stats.num_rows * g.epochs / g.global_batch_size
|
|
137
|
+
if steps < 10:
|
|
138
|
+
rep.add(WARN, "DR020", f"only ~{steps:.0f} optimizer steps in total", "add data, epochs, or lower the batch size")
|
|
139
|
+
|
|
140
|
+
if train_rows and eval_rows:
|
|
141
|
+
from bitstraining.data.split import leakage
|
|
142
|
+
|
|
143
|
+
leak = leakage(train_rows, eval_rows)
|
|
144
|
+
if leak:
|
|
145
|
+
frac = len(leak) / len(eval_rows)
|
|
146
|
+
rep.add(ERROR if frac > 0.01 else WARN, "DR008",
|
|
147
|
+
f"{len(leak)} eval rows ({frac:.1%}) also appear in the training data",
|
|
148
|
+
"re-split with `bitstraining data split`, which keeps duplicates on one side")
|
|
149
|
+
if train_rows:
|
|
150
|
+
bad = 0
|
|
151
|
+
for r in train_rows[:500]:
|
|
152
|
+
msgs = r.get("messages")
|
|
153
|
+
if msgs and (any(m["role"] not in _VALID_ROLES for m in msgs) or msgs[-1]["role"] != "assistant"):
|
|
154
|
+
bad += 1
|
|
155
|
+
if bad:
|
|
156
|
+
rep.add(WARN, "DR021", f"{bad} sampled conversations have unknown roles or do not end with an assistant turn",
|
|
157
|
+
"end each conversation with the reply the model should learn")
|
|
158
|
+
if not any(row_sequences(r) for r in train_rows[:5]):
|
|
159
|
+
rep.add(WARN, "DR022", "rows contain no trainable text", "check column mapping")
|
|
160
|
+
|
|
161
|
+
# --- model -------------------------------------------------------------------------
|
|
162
|
+
if model is not None:
|
|
163
|
+
if model.source == "name-heuristic":
|
|
164
|
+
rep.add(WARN, "DR030", f"architecture of '{model.name}' was guessed from its name",
|
|
165
|
+
"point model.base at a local directory with config.json for exact estimates")
|
|
166
|
+
if "meta-llama" in spec.model.base.lower() and not os.environ.get("HF_TOKEN") and not Path(spec.model.base).exists():
|
|
167
|
+
rep.add(WARN, "DR031", "this looks like a gated Hugging Face model and HF_TOKEN is not set",
|
|
168
|
+
"export HF_TOKEN=... and accept the model license on the Hub")
|
|
169
|
+
|
|
170
|
+
# --- hardware / plan ---------------------------------------------------------------
|
|
171
|
+
if hw is not None:
|
|
172
|
+
gpu = device_for(hw)
|
|
173
|
+
if hw.ram_gb <= 0:
|
|
174
|
+
rep.add(WARN, "DR050", "could not detect system RAM on this platform; assuming 8 GB for planning",
|
|
175
|
+
"report your OS to the project, or plan with --gpu <name> for a specific machine")
|
|
176
|
+
if not hw.gpus and spec.compute.gpu is None and (model is None or model.params > 1.5e9):
|
|
177
|
+
rep.add(WARN, "DR040", "no GPU detected; fine-tuning an LLM on CPU is impractically slow",
|
|
178
|
+
"use `--gpu <name>` to plan for rented hardware or `bitstraining notebook` for Colab/Kaggle")
|
|
179
|
+
free = hw.disk_free_gb
|
|
180
|
+
if model is not None and free:
|
|
181
|
+
full = bool(methods) and methods == ["full"]
|
|
182
|
+
need = (model.params * 2 * 2 / 1024**3) if full else 1.0 # ~2 checkpoints for full FT
|
|
183
|
+
if full and free < need:
|
|
184
|
+
rep.add(ERROR, "DR041", f"checkpoints may need ~{need:.0f} GB but only {free:.0f} GB is free",
|
|
185
|
+
"free disk space or point output at a larger volume")
|
|
186
|
+
if gpu.peak_tflops_bf16 == 0 and hw.gpus:
|
|
187
|
+
rep.add(INFO, "DR042", f"'{gpu.name}' is not in the GPU database; speed estimates use a generic prior",
|
|
188
|
+
"run `bitstraining profile --benchmark` to measure it")
|
|
189
|
+
if plans:
|
|
190
|
+
best = plans[0]
|
|
191
|
+
vram = device_for(hw).vram_gb if hw else 0
|
|
192
|
+
if vram and best.estimate.peak_gb_per_gpu / vram > 0.9:
|
|
193
|
+
rep.add(WARN, "DR043", f"best plan uses {best.estimate.peak_gb_per_gpu / vram:.0%} of device memory",
|
|
194
|
+
"long or unusual batches may run out of memory; consider max_length or QLoRA")
|
|
195
|
+
if g.time_budget_hours and best.estimate.total_hours > g.time_budget_hours:
|
|
196
|
+
rep.add(WARN, "DR044", f"predicted {best.estimate.total_hours:.1f} h exceeds the {g.time_budget_hours:g} h budget",
|
|
197
|
+
"reduce epochs/data or choose faster hardware")
|
|
198
|
+
if g.budget_usd and best.estimate.cost_usd and best.estimate.cost_usd > g.budget_usd:
|
|
199
|
+
rep.add(WARN, "DR045", f"predicted ${best.estimate.cost_usd:.2f} exceeds the ${g.budget_usd:g} budget", "choose cheaper compute")
|
|
200
|
+
if d.packing == "on" and best.attention != "flash":
|
|
201
|
+
rep.add(WARN, "DR046", "packing is on but the attention kernel is not flash; packed examples may attend across boundaries",
|
|
202
|
+
"use an engine/GPU with flash attention or set data.packing: off")
|
|
203
|
+
if check_imports:
|
|
204
|
+
engine = best.engine
|
|
205
|
+
need = {"hf_peft": ["torch", "transformers", "peft"], "unsloth": ["unsloth"],
|
|
206
|
+
"mlx": ["mlx_lm"], "deepspeed": ["deepspeed"]}.get(engine, [])
|
|
207
|
+
missing = [m for m in need if not _have(m)]
|
|
208
|
+
if missing:
|
|
209
|
+
rep.add(WARN, "DR047", f"engine '{engine}' needs missing packages: {', '.join(missing)}",
|
|
210
|
+
"pip install 'bitstraining[train]'")
|
|
211
|
+
if METHODS[best.method].quant == "nf4" and not _have("bitsandbytes"):
|
|
212
|
+
rep.add(WARN, "DR048", "QLoRA needs bitsandbytes", "pip install 'bitstraining[quant]'")
|
|
213
|
+
elif plan_error:
|
|
214
|
+
rep.add(ERROR, "DR049", plan_error.split("\n")[0], plan_error.split("fix:", 1)[1].strip() if "fix:" in plan_error else "")
|
|
215
|
+
return rep
|