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
+ """Filesystem locations. Override the root with BITSTRAINING_HOME."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ def home() -> Path:
10
+ root = Path(os.environ.get("BITSTRAINING_HOME", Path.home() / ".bitstraining"))
11
+ root.mkdir(parents=True, exist_ok=True)
12
+ return root
13
+
14
+
15
+ def registry_db() -> Path:
16
+ return home() / "registry.sqlite"
17
+
18
+
19
+ def tuning_cache() -> Path:
20
+ return home() / "tuning_cache.json"
21
+
22
+
23
+ def calibration_file() -> Path:
24
+ return home() / "calibration.json"
25
+
26
+
27
+ def hardware_cache() -> Path:
28
+ return home() / "hardware_profile.json"
@@ -0,0 +1,87 @@
1
+ """Plugin registry. Engines and compute providers are plugins.
2
+
3
+ Resolution order for a name in a group:
4
+ 1. objects registered at runtime with `register()`
5
+ 2. entry points declared by installed packages (group `bitstraining.<group>`)
6
+ 3. the built-in table below (so a source checkout works without `pip install`)
7
+
8
+ Targets are stored as "module:Attr" strings and imported lazily, so listing plugins
9
+ never imports torch, transformers or any other heavy dependency.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import importlib
15
+ from importlib import metadata
16
+ from typing import Any
17
+
18
+ from bitstraining.core.errors import BitstrainingError
19
+
20
+ BUILTIN: dict[str, dict[str, str]] = {
21
+ "engines": {
22
+ "simulate": "bitstraining.engines.simulate:SimulateEngine",
23
+ "hf_peft": "bitstraining.engines.hf_peft:HFPeftEngine",
24
+ "unsloth": "bitstraining.engines.unsloth:UnslothEngine",
25
+ "mlx": "bitstraining.engines.mlx:MLXEngine",
26
+ "deepspeed": "bitstraining.engines.deepspeed:DeepSpeedEngine",
27
+ },
28
+ "providers": {
29
+ "local": "bitstraining.compute.local:LocalProvider",
30
+ "ssh": "bitstraining.compute.ssh:SSHProvider",
31
+ "docker": "bitstraining.compute.docker:DockerProvider",
32
+ "notebook": "bitstraining.compute.notebook:NotebookProvider",
33
+ "catalog": "bitstraining.compute.catalog:CatalogProvider",
34
+ },
35
+ }
36
+
37
+ _runtime: dict[str, dict[str, Any]] = {}
38
+
39
+
40
+ def register(group: str, name: str, target: Any) -> None:
41
+ """Register a class/object (or a "module:Attr" string) under group/name."""
42
+ _runtime.setdefault(group, {})[name] = target
43
+
44
+
45
+ def _entry_points(group: str) -> dict[str, str]:
46
+ found: dict[str, str] = {}
47
+ try:
48
+ eps = metadata.entry_points(group=f"bitstraining.{group}")
49
+ except Exception: # pragma: no cover - metadata backends differ
50
+ return found
51
+ for ep in eps:
52
+ found[ep.name] = ep.value
53
+ return found
54
+
55
+
56
+ def names(group: str) -> list[str]:
57
+ out = dict.fromkeys(BUILTIN.get(group, {}))
58
+ out.update(dict.fromkeys(_entry_points(group)))
59
+ out.update(dict.fromkeys(_runtime.get(group, {})))
60
+ return sorted(out)
61
+
62
+
63
+ def _resolve(target: Any) -> Any:
64
+ if isinstance(target, str):
65
+ module, _, attr = target.partition(":")
66
+ return getattr(importlib.import_module(module), attr)
67
+ return target
68
+
69
+
70
+ def get(group: str, name: str) -> Any:
71
+ """Return the plugin class/object. Raises with the list of known names."""
72
+ if name in _runtime.get(group, {}):
73
+ return _resolve(_runtime[group][name])
74
+ eps = _entry_points(group)
75
+ if name in eps:
76
+ return _resolve(eps[name])
77
+ if name in BUILTIN.get(group, {}):
78
+ return _resolve(BUILTIN[group][name])
79
+ raise BitstrainingError(
80
+ f"no {group[:-1]} named '{name}'",
81
+ fix=f"available: {', '.join(names(group)) or '(none)'}",
82
+ )
83
+
84
+
85
+ def create(group: str, name: str, *args: Any, **kwargs: Any) -> Any:
86
+ """Instantiate a plugin."""
87
+ return get(group, name)(*args, **kwargs)
@@ -0,0 +1,358 @@
1
+ """Typed, serializable schemas shared by every layer.
2
+
3
+ Everything the planner produces is plain data (`ExecutionPlan`), so plans can be
4
+ inspected, diffed, saved, shipped to a remote machine and replayed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import types
14
+ import typing
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, TypeVar, Union, get_type_hints
17
+
18
+ from bitstraining.core.errors import ConfigError
19
+
20
+ T = TypeVar("T")
21
+
22
+
23
+ # --------------------------------------------------------------------------- helpers
24
+ def _build(tp: Any, value: Any, path: str) -> Any:
25
+ """Recursively coerce `value` into annotation `tp` (dataclasses, lists, dicts, Optional)."""
26
+ origin = typing.get_origin(tp)
27
+ args = typing.get_args(tp)
28
+ if value is None:
29
+ return None
30
+ if origin in (Union, types.UnionType):
31
+ non_none = [a for a in args if a is not type(None)]
32
+ if len(non_none) == 1:
33
+ return _build(non_none[0], value, path)
34
+ return value
35
+ if dataclasses.is_dataclass(tp):
36
+ if not isinstance(value, dict):
37
+ raise ConfigError(f"'{path}' must be a mapping, got {type(value).__name__}")
38
+ return from_dict(tp, value, path)
39
+ if origin is list:
40
+ if not isinstance(value, list):
41
+ raise ConfigError(f"'{path}' must be a list, got {type(value).__name__}")
42
+ return [_build(args[0], v, f"{path}[{i}]") for i, v in enumerate(value)] if args else value
43
+ if origin is dict:
44
+ if not isinstance(value, dict):
45
+ raise ConfigError(f"'{path}' must be a mapping, got {type(value).__name__}")
46
+ return dict(value)
47
+ if tp is float:
48
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
49
+ raise ConfigError(
50
+ f"'{path}' must be a number, got {value!r}",
51
+ fix="remove quotes / booleans from numeric fields",
52
+ )
53
+ if isinstance(value, float) and not math.isfinite(value):
54
+ raise ConfigError(f"'{path}' must be finite, got {value}")
55
+ return float(value)
56
+ if tp is int:
57
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
58
+ raise ConfigError(f"'{path}' must be an integer, got {value!r}")
59
+ if isinstance(value, float):
60
+ if not value.is_integer():
61
+ raise ConfigError(f"'{path}' must be an integer, got {value}")
62
+ return int(value)
63
+ return value
64
+ if tp is bool:
65
+ if not isinstance(value, bool):
66
+ raise ConfigError(f"'{path}' must be true/false, got {value!r}")
67
+ return value
68
+ if tp is str:
69
+ if not isinstance(value, str):
70
+ raise ConfigError(f"'{path}' must be a string, got {value!r}")
71
+ return value
72
+ return value
73
+
74
+
75
+ def from_dict(cls: type[T], data: dict[str, Any], path: str = "") -> T:
76
+ """Build dataclass `cls` from a dict, rejecting unknown keys with a suggestion."""
77
+ hints = get_type_hints(cls)
78
+ names = {f.name for f in dataclasses.fields(cls) if f.init}
79
+ unknown = set(data) - names
80
+ if unknown:
81
+ import difflib
82
+
83
+ key = sorted(unknown)[0]
84
+ close = difflib.get_close_matches(key, sorted(names), n=1)
85
+ where = f"{path}." if path else ""
86
+ raise ConfigError(
87
+ f"unknown field '{where}{key}'",
88
+ fix=f"did you mean '{close[0]}'?" if close else f"valid fields: {sorted(names)}",
89
+ )
90
+ kwargs = {}
91
+ for name in names:
92
+ if name in data:
93
+ kwargs[name] = _build(hints[name], data[name], f"{path}.{name}" if path else name)
94
+ return cls(**kwargs) # type: ignore[arg-type]
95
+
96
+
97
+ class Serializable:
98
+ """Mixin: dict/json round-tripping and stable content hashing."""
99
+
100
+ def to_dict(self) -> dict[str, Any]:
101
+ return dataclasses.asdict(self) # type: ignore[call-overload]
102
+
103
+ @classmethod
104
+ def from_dict(cls: type[T], data: dict[str, Any]) -> T:
105
+ return from_dict(cls, data)
106
+
107
+ def to_json(self, **kw: Any) -> str:
108
+ return json.dumps(self.to_dict(), sort_keys=True, **kw)
109
+
110
+ def content_hash(self) -> str:
111
+ return hashlib.sha256(self.to_json().encode()).hexdigest()[:16]
112
+
113
+
114
+ # --------------------------------------------------------------------------- hardware
115
+ @dataclass
116
+ class GPUInfo(Serializable):
117
+ name: str = "unknown"
118
+ vram_gb: float = 0.0
119
+ compute_capability: str | None = None
120
+ bf16: bool = False
121
+ fp8: bool = False
122
+ peak_tflops_bf16: float = 0.0 # dense tensor-core peak
123
+ mem_bw_gbs: float = 0.0
124
+ h2d_gbs: float = 12.0 # measured/assumed host<->device bandwidth
125
+ nvlink: bool = False
126
+ source: str = "database" # detected | database | measured
127
+
128
+
129
+ @dataclass
130
+ class HardwareProfile(Serializable):
131
+ name: str = "local"
132
+ os: str = ""
133
+ cpu_model: str = ""
134
+ cpu_cores: int = 1
135
+ ram_gb: float = 0.0
136
+ disk_free_gb: float = 0.0
137
+ disk_read_gbs: float | None = None
138
+ gpu_vendor: str = "none" # nvidia | apple | amd | none
139
+ unified_memory: bool = False
140
+ gpus: list[GPUInfo] = field(default_factory=list)
141
+ price_per_hour: float | None = None # for the whole machine
142
+ provider: str = "local"
143
+ measured: bool = False
144
+
145
+ @property
146
+ def n_gpus(self) -> int:
147
+ return len(self.gpus)
148
+
149
+ @property
150
+ def vram_gb(self) -> float:
151
+ """Usable device memory per GPU (min across devices). Unified memory shares RAM."""
152
+ if not self.gpus:
153
+ return 0.0
154
+ return min(g.vram_gb for g in self.gpus)
155
+
156
+ @property
157
+ def key(self) -> str:
158
+ """Stable key for caches and calibration."""
159
+ if self.gpus:
160
+ return f"{self.gpus[0].name}x{self.n_gpus}".lower().replace(" ", "-")
161
+ return f"cpu-{self.cpu_cores}c"
162
+
163
+
164
+ # --------------------------------------------------------------------------- model / data
165
+ @dataclass
166
+ class ModelInfo(Serializable):
167
+ name: str = ""
168
+ architecture: str = "llama"
169
+ params: int = 0
170
+ hidden_size: int = 0
171
+ num_layers: int = 0
172
+ num_heads: int = 0
173
+ num_kv_heads: int = 0
174
+ intermediate_size: int = 0
175
+ vocab_size: int = 0
176
+ tie_embeddings: bool = False
177
+ max_position: int = 4096
178
+ num_experts: int = 1
179
+ active_experts: int = 1
180
+ gated_mlp: bool = True # SwiGLU-style (3 matrices) vs plain 2-matrix MLP
181
+ head_dim_override: int = 0 # for architectures where head_dim != hidden/heads
182
+ source: str = "preset" # config | preset | name-heuristic | hub
183
+
184
+ @property
185
+ def head_dim(self) -> int:
186
+ return self.head_dim_override or self.hidden_size // max(self.num_heads, 1)
187
+
188
+ @property
189
+ def embed_params(self) -> int:
190
+ n = self.vocab_size * self.hidden_size
191
+ return n if self.tie_embeddings else 2 * n
192
+
193
+ @property
194
+ def nonembed_params(self) -> int:
195
+ return max(self.params - self.embed_params, 0)
196
+
197
+
198
+ @dataclass
199
+ class DatasetStats(Serializable):
200
+ num_rows: int = 0
201
+ total_tokens: int = 0
202
+ mean_len: float = 0.0
203
+ p50_len: int = 0
204
+ p95_len: int = 0
205
+ max_len: int = 0
206
+ truncation_rate: float = 0.0
207
+ empty_rate: float = 0.0
208
+ duplicate_rate: float = 0.0
209
+ schema: str = "unknown"
210
+ data_hash: str = ""
211
+ lengths_sample: list[int] = field(default_factory=list)
212
+ token_counter: str = "chars/4 estimate"
213
+
214
+
215
+ # --------------------------------------------------------------------------- run spec
216
+ @dataclass
217
+ class ModelSpec(Serializable):
218
+ base: str = ""
219
+ trust_remote_code: bool = False
220
+ revision: str | None = None
221
+
222
+
223
+ @dataclass
224
+ class DataSpec(Serializable):
225
+ train: str = ""
226
+ eval: str | None = None
227
+ format: str = "auto"
228
+ max_length: int = 2048
229
+ eval_split: float = 0.0
230
+ packing: str = "auto" # auto | on | off
231
+ dedup: bool = True
232
+
233
+
234
+ @dataclass
235
+ class GoalSpec(Serializable):
236
+ task: str = "sft" # sft | dpo | orpo | kto | pretrain
237
+ objective: str = "time" # time | cost | memory
238
+ epochs: float = 3.0
239
+ global_batch_size: int = 16
240
+ learning_rate: float = 2e-4
241
+ time_budget_hours: float | None = None
242
+ budget_usd: float | None = None
243
+ allow_quantization: bool = True
244
+ methods: list[str] | None = None # restrict: full | lora | qlora | dora
245
+ lora_r: int = 16
246
+ lora_alpha: int = 32
247
+ lora_dropout: float = 0.05
248
+ target_modules: str = "all-linear"
249
+ seed: int = 42
250
+
251
+
252
+ @dataclass
253
+ class ComputeSpec(Serializable):
254
+ provider: str = "local"
255
+ gpu: str | None = None # plan for named hardware, e.g. "a100-80gb"
256
+ n_gpus: int | None = None
257
+ max_price_per_hour: float | None = None
258
+ options: dict[str, Any] = field(default_factory=dict)
259
+
260
+
261
+ @dataclass
262
+ class RunSpec(Serializable):
263
+ """What the user asks for: a goal plus constraints, not a hand-tuned config."""
264
+
265
+ name: str = "run"
266
+ model: ModelSpec = field(default_factory=ModelSpec)
267
+ data: DataSpec = field(default_factory=DataSpec)
268
+ goal: GoalSpec = field(default_factory=GoalSpec)
269
+ compute: ComputeSpec = field(default_factory=ComputeSpec)
270
+ output: str = "./output"
271
+ engine: str = "auto"
272
+ extras: dict[str, Any] = field(default_factory=dict)
273
+
274
+
275
+ # --------------------------------------------------------------------------- plan
276
+ @dataclass
277
+ class Estimate(Serializable):
278
+ fits: bool = True
279
+ peak_gb_per_gpu: float = 0.0
280
+ breakdown_gb: dict[str, float] = field(default_factory=dict)
281
+ host_ram_gb: float = 0.0
282
+ raw_tokens_per_s: float = 0.0
283
+ useful_tokens_per_s: float = 0.0
284
+ step_time_s: float = 0.0
285
+ total_hours: float = 0.0
286
+ cost_usd: float | None = None
287
+ confidence: str = "low" # low | medium | high
288
+ bottleneck: str = "compute" # compute | transfer
289
+ notes: list[str] = field(default_factory=list)
290
+
291
+
292
+ @dataclass
293
+ class ExecutionPlan(Serializable):
294
+ engine: str = "hf_peft"
295
+ method: str = "lora" # full | lora | qlora | dora
296
+ precision: str = "bf16" # bf16 | fp16 | fp32
297
+ quant: str = "none" # none | nf4
298
+ layer_stream: bool = False
299
+ activation: str = "none" # none | selective | full
300
+ optimizer: str = "adamw" # adamw | adamw8bit | paged_adamw8bit
301
+ micro_batch: int = 1
302
+ grad_accum: int = 1
303
+ n_gpus: int = 1
304
+ parallelism: str = "single" # single | ddp | fsdp
305
+ packing: bool = False
306
+ max_length: int = 2048
307
+ attention: str = "sdpa" # flash | sdpa | eager
308
+ fused_ce: bool = False
309
+ compile: bool = False
310
+ dataloader_workers: int = 2
311
+ lora_r: int = 16
312
+ lora_alpha: int = 32
313
+ lora_dropout: float = 0.05
314
+ target_modules: str = "all-linear"
315
+ epochs: float = 3.0
316
+ total_steps: int = 0
317
+ learning_rate: float = 2e-4
318
+ seed: int = 42
319
+ hardware: str = ""
320
+ model: str = ""
321
+ estimate: Estimate = field(default_factory=Estimate)
322
+
323
+ def describe(self) -> str:
324
+ bits = [
325
+ f"{self.engine}",
326
+ f"{self.method}{'+stream' if self.layer_stream else ''}",
327
+ self.precision,
328
+ f"ckpt={self.activation}",
329
+ f"opt={self.optimizer}",
330
+ f"mb={self.micro_batch}x{self.grad_accum}",
331
+ f"gpus={self.n_gpus}/{self.parallelism}",
332
+ f"pack={'on' if self.packing else 'off'}",
333
+ f"attn={self.attention}",
334
+ ]
335
+ return " ".join(bits)
336
+
337
+
338
+ @dataclass
339
+ class Capabilities(Serializable):
340
+ """What an engine can do on given hardware; the planner only searches inside this."""
341
+
342
+ name: str = ""
343
+ available: bool = True
344
+ reason: str = "" # why unavailable
345
+ methods: list[str] = field(default_factory=lambda: ["lora"])
346
+ precisions: list[str] = field(default_factory=lambda: ["bf16", "fp16"])
347
+ activation_modes: list[str] = field(default_factory=lambda: ["none", "full"])
348
+ optimizers: list[str] = field(default_factory=lambda: ["adamw"])
349
+ attention: list[str] = field(default_factory=lambda: ["sdpa"])
350
+ parallelism: list[str] = field(default_factory=lambda: ["single"])
351
+ supports_packing: bool = False
352
+ supports_layer_stream: bool = False
353
+ supports_fused_ce: bool = False
354
+ supports_compile: bool = False
355
+ tasks: list[str] = field(default_factory=lambda: ["sft"])
356
+ platforms: list[str] = field(default_factory=lambda: ["cuda"])
357
+ speed_prior: float = 1.0 # relative throughput prior; replaced by calibration when probed
358
+ speed_prior_is_measured: bool = False
@@ -0,0 +1,25 @@
1
+ """Dataset pipeline: ingest, schema detection, cleaning, dedup, splitting, packing, statistics."""
2
+
3
+ from bitstraining.data.clean import CleanReport, clean_rows, near_duplicate_groups
4
+ from bitstraining.data.loaders import read_rows
5
+ from bitstraining.data.pack import ffd_pack, packing_efficiency, padding_efficiency
6
+ from bitstraining.data.schema import detect_schema, normalize_row, row_sequences
7
+ from bitstraining.data.split import leakage, split_rows
8
+ from bitstraining.data.stats import compute_stats, inspect_report
9
+
10
+ __all__ = [
11
+ "CleanReport",
12
+ "clean_rows",
13
+ "compute_stats",
14
+ "detect_schema",
15
+ "ffd_pack",
16
+ "inspect_report",
17
+ "leakage",
18
+ "near_duplicate_groups",
19
+ "normalize_row",
20
+ "packing_efficiency",
21
+ "padding_efficiency",
22
+ "read_rows",
23
+ "row_sequences",
24
+ "split_rows",
25
+ ]
@@ -0,0 +1,147 @@
1
+ """Cleaning: malformed/empty/oversized rows, exact duplicates, optional MinHash near-duplicates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import random
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from bitstraining.core.errors import DataError
11
+ from bitstraining.core.schemas import Serializable
12
+ from bitstraining.data.schema import canonical_text, normalize_row, row_sequences
13
+
14
+
15
+ @dataclass
16
+ class CleanReport(Serializable):
17
+ input_rows: int = 0
18
+ kept: int = 0
19
+ malformed: int = 0
20
+ empty: int = 0
21
+ too_long: int = 0
22
+ exact_duplicates: int = 0
23
+ near_duplicates: int = 0
24
+ examples: dict[str, list[int]] = field(default_factory=dict) # reason -> first row indices
25
+
26
+ def note(self, reason: str, idx: int) -> None:
27
+ lst = self.examples.setdefault(reason, [])
28
+ if len(lst) < 5:
29
+ lst.append(idx)
30
+
31
+
32
+ def _is_empty(norm: dict[str, Any]) -> bool:
33
+ if "messages" in norm:
34
+ msgs = norm["messages"]
35
+ return not msgs or not any(m["role"] == "assistant" and m["content"].strip() for m in msgs)
36
+ if "text" in norm:
37
+ return not norm["text"].strip()
38
+ return not (norm["chosen"].strip() and norm["rejected"].strip() and norm["prompt"].strip())
39
+
40
+
41
+ def clean_rows(
42
+ rows: list[dict[str, Any]],
43
+ schema: str,
44
+ max_chars: int | None = None,
45
+ dedup: bool = True,
46
+ near_dup_threshold: float | None = None,
47
+ ) -> tuple[list[dict[str, Any]], CleanReport]:
48
+ """Return (normalized kept rows, report). Never mutates input."""
49
+ rep = CleanReport(input_rows=len(rows))
50
+ kept: list[dict[str, Any]] = []
51
+ seen: set[str] = set()
52
+ for i, raw in enumerate(rows):
53
+ try:
54
+ norm = normalize_row(raw, schema)
55
+ except DataError:
56
+ rep.malformed += 1
57
+ rep.note("malformed", i)
58
+ continue
59
+ if _is_empty(norm):
60
+ rep.empty += 1
61
+ rep.note("empty", i)
62
+ continue
63
+ if max_chars and sum(len(s) for s in row_sequences(norm)) > max_chars:
64
+ rep.too_long += 1
65
+ rep.note("too_long", i)
66
+ continue
67
+ if dedup:
68
+ h = hashlib.blake2b(canonical_text(norm).encode(), digest_size=16).hexdigest()
69
+ if h in seen:
70
+ rep.exact_duplicates += 1
71
+ rep.note("exact_duplicate", i)
72
+ continue
73
+ seen.add(h)
74
+ kept.append(norm)
75
+ if near_dup_threshold and len(kept) > 1:
76
+ groups = near_duplicate_groups([canonical_text(r) for r in kept], near_dup_threshold)
77
+ drop = {idx for g in groups for idx in g[1:]} # keep the first of each group
78
+ rep.near_duplicates = len(drop)
79
+ kept = [r for i, r in enumerate(kept) if i not in drop]
80
+ rep.kept = len(kept)
81
+ return kept, rep
82
+
83
+
84
+ # ----------------------------------------------------------------------------- near-duplicates
85
+ _P = (1 << 61) - 1
86
+
87
+
88
+ def _shingles(text: str, k: int = 3) -> set[int]:
89
+ words = text.split()
90
+ if len(words) <= k:
91
+ grams = [" ".join(words)] if words else []
92
+ else:
93
+ grams = [" ".join(words[i : i + k]) for i in range(len(words) - k + 1)]
94
+ return {int.from_bytes(hashlib.blake2b(g.encode(), digest_size=8).digest(), "big") for g in grams}
95
+
96
+
97
+ def near_duplicate_groups(
98
+ texts: list[str], threshold: float = 0.8, num_perm: int = 64, bands: int = 16, seed: int = 1
99
+ ) -> list[list[int]]:
100
+ """MinHash + LSH. Returns groups (sorted index lists, size >= 2) of likely near-duplicates.
101
+
102
+ Candidate pairs come from band collisions and are confirmed by the estimated Jaccard
103
+ similarity of their signatures, so `threshold` is the minimum estimated similarity.
104
+ """
105
+ if num_perm % bands:
106
+ raise ValueError("num_perm must be divisible by bands")
107
+ rows_per_band = num_perm // bands
108
+ rng = random.Random(seed)
109
+ coeffs = [(rng.randrange(1, _P), rng.randrange(0, _P)) for _ in range(num_perm)]
110
+ sigs: list[tuple[int, ...] | None] = []
111
+ for t in texts:
112
+ sh = _shingles(t)
113
+ sigs.append(tuple(min((a * x + b) % _P for x in sh) for a, b in coeffs) if sh else None)
114
+
115
+ parent = list(range(len(texts)))
116
+
117
+ def find(x: int) -> int:
118
+ while parent[x] != x:
119
+ parent[x] = parent[parent[x]]
120
+ x = parent[x]
121
+ return x
122
+
123
+ buckets: dict[tuple[int, tuple[int, ...]], list[int]] = {}
124
+ for i, s in enumerate(sigs):
125
+ if s is None:
126
+ continue
127
+ for b in range(bands):
128
+ buckets.setdefault((b, s[b * rows_per_band : (b + 1) * rows_per_band]), []).append(i)
129
+ checked: set[tuple[int, int]] = set()
130
+ for members in buckets.values():
131
+ if len(members) < 2:
132
+ continue
133
+ for ai in range(len(members)):
134
+ for bi in range(ai + 1, len(members)):
135
+ i, j = members[ai], members[bi]
136
+ if (i, j) in checked:
137
+ continue
138
+ checked.add((i, j))
139
+ si, sj = sigs[i], sigs[j]
140
+ assert si is not None and sj is not None
141
+ est = sum(1 for x, y in zip(si, sj, strict=True) if x == y) / num_perm
142
+ if est >= threshold:
143
+ parent[find(i)] = find(j)
144
+ groups: dict[int, list[int]] = {}
145
+ for i in range(len(texts)):
146
+ groups.setdefault(find(i), []).append(i)
147
+ return [sorted(g) for g in groups.values() if len(g) > 1]