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,135 @@
|
|
|
1
|
+
"""Read training data from JSONL, JSON, CSV/TSV, TXT, Parquet, folders of text, or `hf://` datasets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from bitstraining.core.errors import DataError
|
|
12
|
+
|
|
13
|
+
_TEXT_EXT = {".txt", ".md"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _read_jsonl(p: Path) -> Iterator[dict[str, Any]]:
|
|
17
|
+
with p.open(encoding="utf-8") as f:
|
|
18
|
+
for i, line in enumerate(f, 1):
|
|
19
|
+
line = line.strip()
|
|
20
|
+
if not line:
|
|
21
|
+
continue
|
|
22
|
+
try:
|
|
23
|
+
obj = json.loads(line)
|
|
24
|
+
except json.JSONDecodeError as e:
|
|
25
|
+
raise DataError(
|
|
26
|
+
f"{p}:{i} is not valid JSON ({e.msg})",
|
|
27
|
+
fix="each line must be one JSON object; run `bitstraining data inspect` to locate bad rows",
|
|
28
|
+
) from e
|
|
29
|
+
if not isinstance(obj, dict):
|
|
30
|
+
raise DataError(f"{p}:{i} must be a JSON object, got {type(obj).__name__}")
|
|
31
|
+
yield obj
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _read_json(p: Path) -> Iterator[dict[str, Any]]:
|
|
35
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
36
|
+
if isinstance(data, dict):
|
|
37
|
+
for key in ("data", "rows", "examples", "train"):
|
|
38
|
+
if isinstance(data.get(key), list):
|
|
39
|
+
data = data[key]
|
|
40
|
+
break
|
|
41
|
+
else:
|
|
42
|
+
raise DataError(f"{p} is a JSON object; expected a list of rows")
|
|
43
|
+
for obj in data:
|
|
44
|
+
if isinstance(obj, dict):
|
|
45
|
+
yield obj
|
|
46
|
+
else:
|
|
47
|
+
raise DataError(f"{p} contains a non-object row: {str(obj)[:60]!r}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read_csv(p: Path, delimiter: str) -> Iterator[dict[str, Any]]:
|
|
51
|
+
with p.open(encoding="utf-8", newline="") as f:
|
|
52
|
+
yield from csv.DictReader(f, delimiter=delimiter)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _read_txt(p: Path) -> Iterator[dict[str, Any]]:
|
|
56
|
+
"""Blank-line separated paragraphs become rows; one-document files become one row."""
|
|
57
|
+
text = p.read_text(encoding="utf-8")
|
|
58
|
+
parts = [t.strip() for t in text.split("\n\n") if t.strip()]
|
|
59
|
+
for part in parts or [text.strip()]:
|
|
60
|
+
if part:
|
|
61
|
+
yield {"text": part}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _read_parquet(p: Path) -> Iterator[dict[str, Any]]:
|
|
65
|
+
try:
|
|
66
|
+
import pyarrow.parquet as pq
|
|
67
|
+
except ImportError as e:
|
|
68
|
+
raise DataError(
|
|
69
|
+
"reading Parquet needs pyarrow", fix="pip install 'bitstraining[parquet]'"
|
|
70
|
+
) from e
|
|
71
|
+
yield from pq.read_table(p).to_pylist()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _read_hf(spec: str) -> Iterator[dict[str, Any]]:
|
|
75
|
+
try:
|
|
76
|
+
from datasets import load_dataset
|
|
77
|
+
except ImportError as e:
|
|
78
|
+
raise DataError(
|
|
79
|
+
"hf:// datasets need the `datasets` package", fix="pip install 'bitstraining[train]'"
|
|
80
|
+
) from e
|
|
81
|
+
name, _, split = spec.partition(":")
|
|
82
|
+
ds = load_dataset(name, split=split or "train")
|
|
83
|
+
yield from (dict(r) for r in ds)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def read_rows(path: str | Path, limit: int | None = None) -> list[dict[str, Any]]:
|
|
87
|
+
"""Load all rows (optionally the first `limit`). Raises DataError with a fix on failure."""
|
|
88
|
+
s = str(path)
|
|
89
|
+
if s.startswith("hf://"):
|
|
90
|
+
it: Iterator[dict[str, Any]] = _read_hf(s[5:])
|
|
91
|
+
else:
|
|
92
|
+
p = Path(s)
|
|
93
|
+
if not p.exists():
|
|
94
|
+
raise DataError(f"data file not found: {p}", fix="check data.train in your config")
|
|
95
|
+
if p.is_dir():
|
|
96
|
+
files = sorted(f for f in p.rglob("*") if f.suffix.lower() in _TEXT_EXT | {".jsonl", ".json", ".csv", ".parquet"})
|
|
97
|
+
if not files:
|
|
98
|
+
raise DataError(f"no readable files in {p}")
|
|
99
|
+
return _concat(files, limit)
|
|
100
|
+
it = _dispatch(p)
|
|
101
|
+
rows: list[dict[str, Any]] = []
|
|
102
|
+
for r in it:
|
|
103
|
+
rows.append(r)
|
|
104
|
+
if limit and len(rows) >= limit:
|
|
105
|
+
break
|
|
106
|
+
return rows
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _dispatch(p: Path) -> Iterator[dict[str, Any]]:
|
|
110
|
+
ext = p.suffix.lower()
|
|
111
|
+
if ext == ".jsonl" or ext == ".ndjson":
|
|
112
|
+
return _read_jsonl(p)
|
|
113
|
+
if ext == ".json":
|
|
114
|
+
return _read_json(p)
|
|
115
|
+
if ext == ".csv":
|
|
116
|
+
return _read_csv(p, ",")
|
|
117
|
+
if ext == ".tsv":
|
|
118
|
+
return _read_csv(p, "\t")
|
|
119
|
+
if ext in _TEXT_EXT:
|
|
120
|
+
return _read_txt(p)
|
|
121
|
+
if ext == ".parquet":
|
|
122
|
+
return _read_parquet(p)
|
|
123
|
+
raise DataError(
|
|
124
|
+
f"unsupported data format '{ext}'", fix="use .jsonl, .json, .csv, .tsv, .txt or .parquet"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _concat(files: list[Path], limit: int | None) -> list[dict[str, Any]]:
|
|
129
|
+
rows: list[dict[str, Any]] = []
|
|
130
|
+
for f in files:
|
|
131
|
+
for r in _dispatch(f):
|
|
132
|
+
rows.append(r)
|
|
133
|
+
if limit and len(rows) >= limit:
|
|
134
|
+
return rows
|
|
135
|
+
return rows
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Sequence packing and padding-waste models.
|
|
2
|
+
|
|
3
|
+
Padding is the largest hidden cost on short-example datasets: if a batch is padded to
|
|
4
|
+
its longest member, every shorter row burns compute on pad tokens. Packing concatenates
|
|
5
|
+
several examples into one fixed-length sequence to avoid that.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import random
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def ffd_pack(lengths: list[int], max_len: int) -> list[list[int]]:
|
|
14
|
+
"""First-fit-decreasing bin packing. Returns bins of indices; sequences longer than
|
|
15
|
+
`max_len` are truncated to it (they occupy a bin alone). O(n log n)."""
|
|
16
|
+
order = sorted(range(len(lengths)), key=lambda i: -lengths[i])
|
|
17
|
+
bins: list[list[int]] = []
|
|
18
|
+
free: list[int] = [] # remaining capacity per bin
|
|
19
|
+
# For FFD we need "first bin with enough room"; a linear scan over open bins is O(n*b),
|
|
20
|
+
# so we keep bins in creation order and scan only bins that can still fit the smallest item.
|
|
21
|
+
smallest = min((min(n, max_len) for n in lengths), default=0)
|
|
22
|
+
open_bins: list[int] = []
|
|
23
|
+
for i in order:
|
|
24
|
+
ln = min(lengths[i], max_len)
|
|
25
|
+
placed = False
|
|
26
|
+
for pos, b in enumerate(open_bins):
|
|
27
|
+
if free[b] >= ln:
|
|
28
|
+
bins[b].append(i)
|
|
29
|
+
free[b] -= ln
|
|
30
|
+
if free[b] < smallest:
|
|
31
|
+
open_bins.pop(pos)
|
|
32
|
+
placed = True
|
|
33
|
+
break
|
|
34
|
+
if not placed:
|
|
35
|
+
bins.append([i])
|
|
36
|
+
free.append(max_len - ln)
|
|
37
|
+
if free[-1] >= smallest:
|
|
38
|
+
open_bins.append(len(bins) - 1)
|
|
39
|
+
return bins
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def packing_efficiency(lengths: list[int], max_len: int) -> float:
|
|
43
|
+
"""Useful tokens / total slots after FFD packing (1.0 = no padding at all)."""
|
|
44
|
+
if not lengths:
|
|
45
|
+
return 1.0
|
|
46
|
+
bins = ffd_pack(lengths, max_len)
|
|
47
|
+
useful = sum(min(n, max_len) for n in lengths)
|
|
48
|
+
return useful / (len(bins) * max_len)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def padding_efficiency(
|
|
52
|
+
lengths: list[int], batch_size: int, grouped: bool = False, max_len: int | None = None,
|
|
53
|
+
seed: int = 0,
|
|
54
|
+
) -> float:
|
|
55
|
+
"""Useful tokens / padded tokens when batches are padded to their longest member.
|
|
56
|
+
|
|
57
|
+
`grouped=True` models length-grouped batching (sort within large mega-chunks), which
|
|
58
|
+
removes most but not all padding.
|
|
59
|
+
"""
|
|
60
|
+
if not lengths:
|
|
61
|
+
return 1.0
|
|
62
|
+
ls = [min(n, max_len) if max_len else n for n in lengths]
|
|
63
|
+
rng = random.Random(seed)
|
|
64
|
+
order = list(range(len(ls)))
|
|
65
|
+
rng.shuffle(order)
|
|
66
|
+
if grouped:
|
|
67
|
+
mega = max(batch_size * 50, batch_size)
|
|
68
|
+
chunks = [sorted(order[i : i + mega], key=lambda k: -ls[k]) for i in range(0, len(order), mega)]
|
|
69
|
+
order = [k for c in chunks for k in c]
|
|
70
|
+
useful = padded = 0
|
|
71
|
+
for i in range(0, len(order), batch_size):
|
|
72
|
+
batch = [ls[k] for k in order[i : i + batch_size]]
|
|
73
|
+
useful += sum(batch)
|
|
74
|
+
padded += max(batch) * len(batch)
|
|
75
|
+
return useful / padded if padded else 1.0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def pack_sequences(
|
|
79
|
+
token_lists: list[list[int]], max_len: int
|
|
80
|
+
) -> list[tuple[list[int], list[int]]]:
|
|
81
|
+
"""Materialize packed sequences. Returns (input_ids, position_ids) per packed row; position
|
|
82
|
+
ids restart at 0 for each member, which flash-attention varlen kernels use as boundaries."""
|
|
83
|
+
lens = [len(t) for t in token_lists]
|
|
84
|
+
out = []
|
|
85
|
+
for b in ffd_pack(lens, max_len):
|
|
86
|
+
ids: list[int] = []
|
|
87
|
+
pos: list[int] = []
|
|
88
|
+
for i in b:
|
|
89
|
+
t = token_lists[i][:max_len]
|
|
90
|
+
ids.extend(t)
|
|
91
|
+
pos.extend(range(len(t)))
|
|
92
|
+
out.append((ids, pos))
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def percentile(sorted_vals: list[int], q: float) -> int:
|
|
97
|
+
"""Nearest-rank percentile of an ascending list (q in [0, 1])."""
|
|
98
|
+
if not sorted_vals:
|
|
99
|
+
return 0
|
|
100
|
+
return sorted_vals[min(len(sorted_vals) - 1, max(0, int(q * (len(sorted_vals) - 1) + 0.5)))]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Detect a dataset's schema and normalize rows into one internal shape.
|
|
2
|
+
|
|
3
|
+
Internal shapes
|
|
4
|
+
sft: {"messages": [{"role": "...", "content": "..."}, ...]}
|
|
5
|
+
text: {"text": "..."} (continued pretraining)
|
|
6
|
+
preference: {"prompt": str, "chosen": str, "rejected": str}
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from bitstraining.core.errors import DataError
|
|
14
|
+
|
|
15
|
+
SCHEMAS = ("messages", "sharegpt", "alpaca", "prompt_completion", "preference", "text")
|
|
16
|
+
|
|
17
|
+
_ROLE_MAP = {"human": "user", "user": "user", "gpt": "assistant", "assistant": "assistant",
|
|
18
|
+
"bot": "assistant", "system": "system", "model": "assistant"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def detect_schema(rows: list[dict[str, Any]], sample: int = 50) -> str:
|
|
22
|
+
"""Return the schema that fits the most sampled rows, or 'unknown'."""
|
|
23
|
+
if not rows:
|
|
24
|
+
return "unknown"
|
|
25
|
+
votes: dict[str, int] = {}
|
|
26
|
+
for r in rows[:sample]:
|
|
27
|
+
s = _row_schema(r)
|
|
28
|
+
votes[s] = votes.get(s, 0) + 1
|
|
29
|
+
best = max(votes, key=lambda k: votes[k])
|
|
30
|
+
return best
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _row_schema(r: dict[str, Any]) -> str:
|
|
34
|
+
keys = set(r)
|
|
35
|
+
if {"chosen", "rejected"} <= keys:
|
|
36
|
+
return "preference"
|
|
37
|
+
if "messages" in keys and isinstance(r["messages"], list):
|
|
38
|
+
return "messages"
|
|
39
|
+
if "conversations" in keys and isinstance(r["conversations"], list):
|
|
40
|
+
return "sharegpt"
|
|
41
|
+
if {"instruction", "output"} <= keys:
|
|
42
|
+
return "alpaca"
|
|
43
|
+
if {"prompt", "completion"} <= keys or {"prompt", "response"} <= keys:
|
|
44
|
+
return "prompt_completion"
|
|
45
|
+
if {"question", "answer"} <= keys:
|
|
46
|
+
return "prompt_completion"
|
|
47
|
+
if "text" in keys:
|
|
48
|
+
return "text"
|
|
49
|
+
return "unknown"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def normalize_row(r: dict[str, Any], schema: str) -> dict[str, Any]:
|
|
53
|
+
"""Convert a raw row to the internal shape. Raises DataError on malformed rows."""
|
|
54
|
+
try:
|
|
55
|
+
if schema == "messages":
|
|
56
|
+
msgs = [{"role": m["role"], "content": str(m["content"])} for m in r["messages"]]
|
|
57
|
+
return {"messages": msgs}
|
|
58
|
+
if schema == "sharegpt":
|
|
59
|
+
msgs = []
|
|
60
|
+
for m in r["conversations"]:
|
|
61
|
+
role = _ROLE_MAP.get(str(m.get("from", m.get("role", ""))).lower())
|
|
62
|
+
if role is None:
|
|
63
|
+
raise DataError(f"unknown role in conversation: {m!r}")
|
|
64
|
+
msgs.append({"role": role, "content": str(m.get("value", m.get("content", "")))})
|
|
65
|
+
return {"messages": msgs}
|
|
66
|
+
if schema == "alpaca":
|
|
67
|
+
instr = str(r["instruction"])
|
|
68
|
+
extra = str(r.get("input") or "")
|
|
69
|
+
user = f"{instr}\n\n{extra}" if extra.strip() else instr
|
|
70
|
+
return {"messages": [{"role": "user", "content": user},
|
|
71
|
+
{"role": "assistant", "content": str(r["output"])}]}
|
|
72
|
+
if schema == "prompt_completion":
|
|
73
|
+
prompt = str(r.get("prompt", r.get("question", "")))
|
|
74
|
+
comp = str(r.get("completion", r.get("response", r.get("answer", ""))))
|
|
75
|
+
return {"messages": [{"role": "user", "content": prompt},
|
|
76
|
+
{"role": "assistant", "content": comp}]}
|
|
77
|
+
if schema == "preference":
|
|
78
|
+
return {"prompt": _as_text(r.get("prompt", r.get("question", ""))),
|
|
79
|
+
"chosen": _as_text(r["chosen"]), "rejected": _as_text(r["rejected"])}
|
|
80
|
+
if schema == "text":
|
|
81
|
+
return {"text": str(r["text"])}
|
|
82
|
+
except (KeyError, TypeError, AttributeError) as e:
|
|
83
|
+
raise DataError(f"row does not match schema '{schema}': missing/invalid {e}") from e
|
|
84
|
+
raise DataError(
|
|
85
|
+
f"cannot interpret rows with schema '{schema}'",
|
|
86
|
+
fix="use columns like instruction/output, prompt/completion, messages, chosen/rejected, or text",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _as_text(v: Any) -> str:
|
|
91
|
+
if isinstance(v, list): # list of messages
|
|
92
|
+
return "\n".join(str(m.get("content", "")) if isinstance(m, dict) else str(m) for m in v)
|
|
93
|
+
return str(v)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def row_sequences(norm: dict[str, Any]) -> list[str]:
|
|
97
|
+
"""Texts that are each processed as one training sequence (preference rows give two)."""
|
|
98
|
+
if "messages" in norm:
|
|
99
|
+
# ~4 tokens of chat-template overhead per message are added by the token counter
|
|
100
|
+
return ["".join(f"<|{m['role']}|>{m['content']}" for m in norm["messages"])]
|
|
101
|
+
if "text" in norm:
|
|
102
|
+
return [norm["text"]]
|
|
103
|
+
if "chosen" in norm:
|
|
104
|
+
return [norm["prompt"] + norm["chosen"], norm["prompt"] + norm["rejected"]]
|
|
105
|
+
return []
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def canonical_text(norm: dict[str, Any]) -> str:
|
|
109
|
+
"""Whitespace/case-normalized text used for duplicate and leakage checks.
|
|
110
|
+
|
|
111
|
+
Normalization is applied per message so stray spaces at message boundaries cannot make two
|
|
112
|
+
otherwise identical rows look different."""
|
|
113
|
+
|
|
114
|
+
def n(s: str) -> str:
|
|
115
|
+
return " ".join(str(s).lower().split())
|
|
116
|
+
|
|
117
|
+
if "messages" in norm:
|
|
118
|
+
return "|".join(f"{m['role']}:{n(m['content'])}" for m in norm["messages"])
|
|
119
|
+
if "text" in norm:
|
|
120
|
+
return n(norm["text"])
|
|
121
|
+
if "chosen" in norm:
|
|
122
|
+
return "|".join(n(norm[k]) for k in ("prompt", "chosen", "rejected"))
|
|
123
|
+
return ""
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Train/eval splitting that cannot leak duplicates across the boundary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import random
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from bitstraining.data.schema import canonical_text
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _key(norm: dict[str, Any]) -> str:
|
|
13
|
+
return hashlib.blake2b(canonical_text(norm).encode(), digest_size=8).hexdigest()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def split_rows(
|
|
17
|
+
rows: list[dict[str, Any]], eval_fraction: float, seed: int = 42
|
|
18
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
19
|
+
"""Deterministic split of *normalized* rows. Rows with identical canonical text always
|
|
20
|
+
land on the same side, so exact duplicates never straddle train and eval."""
|
|
21
|
+
if eval_fraction <= 0 or len(rows) < 2:
|
|
22
|
+
return list(rows), []
|
|
23
|
+
groups: dict[str, list[int]] = {}
|
|
24
|
+
for i, r in enumerate(rows):
|
|
25
|
+
groups.setdefault(_key(r), []).append(i)
|
|
26
|
+
keys = sorted(groups)
|
|
27
|
+
random.Random(seed).shuffle(keys)
|
|
28
|
+
target = max(1, round(len(rows) * eval_fraction))
|
|
29
|
+
eval_idx: set[int] = set()
|
|
30
|
+
for k in keys:
|
|
31
|
+
if len(eval_idx) >= target:
|
|
32
|
+
break
|
|
33
|
+
eval_idx.update(groups[k])
|
|
34
|
+
train = [r for i, r in enumerate(rows) if i not in eval_idx]
|
|
35
|
+
ev = [r for i, r in enumerate(rows) if i in eval_idx]
|
|
36
|
+
return train, ev
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def leakage(train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]]) -> list[int]:
|
|
40
|
+
"""Indices of eval rows whose canonical text also appears in train."""
|
|
41
|
+
train_keys = {_key(r) for r in train_rows}
|
|
42
|
+
return [i for i, r in enumerate(eval_rows) if _key(r) in train_keys]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Dataset statistics that feed the planner, plus the human-readable `inspect` report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from bitstraining.core.schemas import DatasetStats
|
|
12
|
+
from bitstraining.data.clean import clean_rows
|
|
13
|
+
from bitstraining.data.loaders import read_rows
|
|
14
|
+
from bitstraining.data.pack import packing_efficiency, padding_efficiency, percentile
|
|
15
|
+
from bitstraining.data.schema import detect_schema, row_sequences
|
|
16
|
+
|
|
17
|
+
_CHAT_OVERHEAD = 4 # tokens of template framing per sequence segment (rough)
|
|
18
|
+
|
|
19
|
+
TokenCounter = Callable[[str], int]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def estimate_tokens(text: str) -> int:
|
|
23
|
+
"""Dependency-free estimate: ~3.8 characters per token for English-like text.
|
|
24
|
+
|
|
25
|
+
This is an approximation; pass a real tokenizer's counter (see `tokenizer_counter`)
|
|
26
|
+
for exact numbers. It tends to be within roughly 15-25% on English prose and is
|
|
27
|
+
less reliable for code or non-Latin scripts.
|
|
28
|
+
"""
|
|
29
|
+
return max(1, math.ceil(len(text) / 3.8)) if text else 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def tokenizer_counter(name: str) -> TokenCounter | None:
|
|
33
|
+
"""Exact counter backed by a Hugging Face tokenizer, or None if unavailable offline."""
|
|
34
|
+
try:
|
|
35
|
+
from transformers import AutoTokenizer
|
|
36
|
+
|
|
37
|
+
tok = AutoTokenizer.from_pretrained(name)
|
|
38
|
+
except Exception:
|
|
39
|
+
return None
|
|
40
|
+
return lambda t: len(tok(t, add_special_tokens=False)["input_ids"])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def hash_rows(rows: list[dict[str, Any]]) -> str:
|
|
44
|
+
h = hashlib.sha256()
|
|
45
|
+
for r in rows:
|
|
46
|
+
h.update(repr(sorted(r.items())).encode())
|
|
47
|
+
return h.hexdigest()[:16]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def hash_file(path: str | Path) -> str:
|
|
51
|
+
p = Path(path)
|
|
52
|
+
if not p.is_file():
|
|
53
|
+
return ""
|
|
54
|
+
h = hashlib.sha256()
|
|
55
|
+
with p.open("rb") as f:
|
|
56
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
57
|
+
h.update(chunk)
|
|
58
|
+
return h.hexdigest()[:16]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def compute_stats(
|
|
62
|
+
norm_rows: list[dict[str, Any]],
|
|
63
|
+
max_length: int = 2048,
|
|
64
|
+
counter: TokenCounter | None = None,
|
|
65
|
+
schema: str = "unknown",
|
|
66
|
+
data_hash: str = "",
|
|
67
|
+
sample_cap: int = 4000,
|
|
68
|
+
) -> DatasetStats:
|
|
69
|
+
"""Token statistics over *normalized* rows (see data.schema.normalize_row)."""
|
|
70
|
+
count = counter or estimate_tokens
|
|
71
|
+
lengths: list[int] = []
|
|
72
|
+
for r in norm_rows:
|
|
73
|
+
for seq in row_sequences(r):
|
|
74
|
+
lengths.append(count(seq) + _CHAT_OVERHEAD)
|
|
75
|
+
n = len(lengths)
|
|
76
|
+
s = sorted(lengths)
|
|
77
|
+
over = sum(1 for x in lengths if x > max_length)
|
|
78
|
+
step = max(1, n // sample_cap)
|
|
79
|
+
return DatasetStats(
|
|
80
|
+
num_rows=len(norm_rows),
|
|
81
|
+
total_tokens=sum(min(x, max_length) for x in lengths),
|
|
82
|
+
mean_len=(sum(lengths) / n) if n else 0.0,
|
|
83
|
+
p50_len=percentile(s, 0.5),
|
|
84
|
+
p95_len=percentile(s, 0.95),
|
|
85
|
+
max_len=s[-1] if s else 0,
|
|
86
|
+
truncation_rate=(over / n) if n else 0.0,
|
|
87
|
+
schema=schema,
|
|
88
|
+
data_hash=data_hash,
|
|
89
|
+
lengths_sample=lengths[::step][:sample_cap],
|
|
90
|
+
token_counter="tokenizer" if counter else "chars/3.8 estimate",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_and_profile(
|
|
95
|
+
path: str,
|
|
96
|
+
fmt: str = "auto",
|
|
97
|
+
max_length: int = 2048,
|
|
98
|
+
dedup: bool = True,
|
|
99
|
+
counter: TokenCounter | None = None,
|
|
100
|
+
) -> tuple[list[dict[str, Any]], DatasetStats]:
|
|
101
|
+
"""Read, detect schema, clean, and compute stats in one call."""
|
|
102
|
+
raw = read_rows(path)
|
|
103
|
+
schema = detect_schema(raw) if fmt == "auto" else fmt
|
|
104
|
+
kept, rep = clean_rows(raw, schema, dedup=dedup)
|
|
105
|
+
stats = compute_stats(kept, max_length, counter, schema, hash_file(path) or hash_rows(kept))
|
|
106
|
+
n = max(rep.input_rows, 1)
|
|
107
|
+
stats.empty_rate = rep.empty / n
|
|
108
|
+
stats.duplicate_rate = rep.exact_duplicates / n
|
|
109
|
+
return kept, stats
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def inspect_report(path: str, fmt: str = "auto", max_length: int = 2048) -> str:
|
|
113
|
+
"""Plain-text report for `bitstraining data inspect`."""
|
|
114
|
+
raw = read_rows(path)
|
|
115
|
+
schema = detect_schema(raw) if fmt == "auto" else fmt
|
|
116
|
+
kept, rep = clean_rows(raw, schema, dedup=True)
|
|
117
|
+
st = compute_stats(kept, max_length, None, schema, hash_file(path) or hash_rows(kept))
|
|
118
|
+
lens = st.lengths_sample
|
|
119
|
+
lines = [
|
|
120
|
+
f"File: {path}",
|
|
121
|
+
f"Rows read: {rep.input_rows}",
|
|
122
|
+
f"Schema: {schema}",
|
|
123
|
+
f"Usable rows: {rep.kept}",
|
|
124
|
+
f" malformed: {rep.malformed}",
|
|
125
|
+
f" empty: {rep.empty}",
|
|
126
|
+
f" duplicates: {rep.exact_duplicates}",
|
|
127
|
+
f"Tokens (est.): {st.total_tokens:,} total ({st.token_counter})",
|
|
128
|
+
f"Length tokens: mean {st.mean_len:.0f} | p50 {st.p50_len} | p95 {st.p95_len} | max {st.max_len}",
|
|
129
|
+
f"Truncated @{max_length}: {st.truncation_rate:.1%} of sequences",
|
|
130
|
+
f"Content hash: {st.data_hash}",
|
|
131
|
+
]
|
|
132
|
+
if lens:
|
|
133
|
+
ml = max_length
|
|
134
|
+
lines += [
|
|
135
|
+
"Padding waste (batch=8, padded to longest): "
|
|
136
|
+
f"{1 - padding_efficiency(lens, 8, False, ml):.0%}",
|
|
137
|
+
"Padding waste with length grouping: "
|
|
138
|
+
f"{1 - padding_efficiency(lens, 8, True, ml):.0%}",
|
|
139
|
+
f"Padding waste with sequence packing: {1 - packing_efficiency(lens, ml):.0%}",
|
|
140
|
+
]
|
|
141
|
+
if rep.examples:
|
|
142
|
+
lines.append("Examples of dropped rows (0-based index): " + str(rep.examples))
|
|
143
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Auto-generated model card with data hash, plan, results and eval gate outcome."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def render_model_card(run: dict[str, Any], lineage: dict[str, Any]) -> str:
|
|
10
|
+
spec, plan, res = run.get("spec") or {}, run.get("plan") or {}, run.get("result") or {}
|
|
11
|
+
sim = bool(run.get("simulated"))
|
|
12
|
+
lines = [f"# {spec.get('name', run['id'])}", ""]
|
|
13
|
+
if sim:
|
|
14
|
+
lines += ["> **SIMULATED RUN: no model was trained. This card documents a dry run only.**", ""]
|
|
15
|
+
lines += [
|
|
16
|
+
f"- Base model: `{(spec.get('model') or {}).get('base', '?')}`",
|
|
17
|
+
f"- Run id: `{run['id']}` | engine: `{run.get('engine')}` | status: `{run.get('status')}`",
|
|
18
|
+
f"- Training data hash: `{lineage.get('data_hash') or 'n/a'}`",
|
|
19
|
+
f"- Method: {plan.get('method')} ({plan.get('precision')}), micro-batch {plan.get('micro_batch')} x "
|
|
20
|
+
f"accum {plan.get('grad_accum')}, lr {plan.get('learning_rate')}, epochs {plan.get('epochs')}",
|
|
21
|
+
f"- Steps: {res.get('steps')} | final loss: {res.get('final_loss')} | eval loss: {res.get('eval_loss')}",
|
|
22
|
+
]
|
|
23
|
+
if res.get("peak_gb") is not None:
|
|
24
|
+
lines.append(f"- Peak GPU memory: {res['peak_gb']} GB | throughput: {res.get('tokens_per_s')} tok/s")
|
|
25
|
+
if lineage.get("evals"):
|
|
26
|
+
lines += ["", "## Evaluation"]
|
|
27
|
+
for e in lineage["evals"]:
|
|
28
|
+
lines.append(f"- **{e['name']}**: `{e['result']}`")
|
|
29
|
+
if lineage.get("artifacts"):
|
|
30
|
+
lines += ["", "## Artifacts"]
|
|
31
|
+
lines += [f"- {a['kind']}: `{a['path']}` (sha256 {a['sha256']})" for a in lineage["artifacts"]]
|
|
32
|
+
lines += ["", "_Generated by Bitstraining. Reported numbers come from this run's own logs; "
|
|
33
|
+
"they are not benchmarks._"]
|
|
34
|
+
return "\n".join(lines) + "\n"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def write_model_card(run: dict[str, Any], lineage: dict[str, Any], dest: str | Path) -> Path:
|
|
38
|
+
p = Path(dest)
|
|
39
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
p.write_text(render_model_card(run, lineage))
|
|
41
|
+
return p
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Build the command that serves a model with an OpenAI-compatible API (vLLM or llama.cpp).
|
|
2
|
+
|
|
3
|
+
Bitstraining does not reimplement a server; it assembles and (optionally) runs the right one.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def serve_command(model: str, backend: str = "vllm", port: int = 8000, host: str = "127.0.0.1",
|
|
10
|
+
max_len: int | None = None) -> list[str]:
|
|
11
|
+
if backend == "vllm":
|
|
12
|
+
cmd = ["vllm", "serve", model, "--host", host, "--port", str(port)]
|
|
13
|
+
if max_len:
|
|
14
|
+
cmd += ["--max-model-len", str(max_len)]
|
|
15
|
+
return cmd
|
|
16
|
+
if backend == "llamacpp":
|
|
17
|
+
cmd = ["llama-server", "-m", model, "--host", host, "--port", str(port)]
|
|
18
|
+
if max_len:
|
|
19
|
+
cmd += ["-c", str(max_len)]
|
|
20
|
+
return cmd
|
|
21
|
+
raise ValueError(f"unknown backend '{backend}' (use vllm or llamacpp)")
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Training engines: thin adapters around ML libraries behind one narrow interface."""
|
|
2
|
+
|
|
3
|
+
from bitstraining.engines.base import (
|
|
4
|
+
Callbacks,
|
|
5
|
+
Engine,
|
|
6
|
+
ProbeContext,
|
|
7
|
+
ProbeResult,
|
|
8
|
+
RunResult,
|
|
9
|
+
available_engines,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Callbacks",
|
|
14
|
+
"Engine",
|
|
15
|
+
"ProbeContext",
|
|
16
|
+
"ProbeResult",
|
|
17
|
+
"RunResult",
|
|
18
|
+
"available_engines",
|
|
19
|
+
]
|