datahub-cli 0.2.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.
datahub/py.typed ADDED
File without changes
datahub/scoring.py ADDED
@@ -0,0 +1,172 @@
1
+ """Estimate inference memory, throughput, and fit across seven quantization tiers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ from .hardware import GIB, HardwareProfile
9
+
10
+ # Bytes include typical block scale and mixed-precision overhead.
11
+ QUANT_LADDER = (
12
+ ("FP16/BF16", 2.0, 100),
13
+ ("Q8_0", 1.063, 99),
14
+ ("Q6_K", 0.82, 98),
15
+ ("Q5_K_M", 0.70, 96),
16
+ ("Q4_K_M", 0.60, 93),
17
+ ("Q3_K_M", 0.49, 87),
18
+ ("Q2_K", 0.39, 78),
19
+ )
20
+ ENCODER_TASKS = {
21
+ "depth-estimation", "object-detection", "image-segmentation",
22
+ "zero-shot-image-classification", "image-feature-extraction", "feature-extraction",
23
+ "sentence-similarity", "text-ranking", "token-classification", "text-classification",
24
+ "image-classification", "audio-classification", "tabular-classification",
25
+ }
26
+ FITS = {"FAST", "GOOD", "OK(CPU)"}
27
+ _AMOUNT = r"(\d+(?:\.\d+)?)([bBmM])"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ModelSpec:
32
+ id: str
33
+ params: int | None
34
+ active_params: int | None = None
35
+ task: str = ""
36
+ tags: tuple[str, ...] = ()
37
+ disk_bytes: int | None = None
38
+ quantization: str = ""
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class QuantTier:
43
+ quant: str
44
+ weights_gb: float | None
45
+ total_gb: float | None
46
+ tok_s: float | None
47
+ quality: int
48
+ verdict: str
49
+ dimensions: dict[str, int]
50
+ score: int
51
+
52
+
53
+ def _count(amount: str, suffix: str) -> int:
54
+ return round(float(amount) * (1e9 if suffix.lower() == "b" else 1e6))
55
+
56
+
57
+ def parse_parameters(repo_id: str, safetensors: dict | None = None) -> tuple[int | None, int | None]:
58
+ name = repo_id.rsplit("/", 1)[-1]
59
+ explicit = re.search(rf"(?<![A-Za-z0-9.]){_AMOUNT}[-_]A{_AMOUNT}(?![A-Za-z0-9])", name, re.IGNORECASE)
60
+ experts = re.search(rf"(?<![A-Za-z0-9.])(\d+)x{_AMOUNT}(?![A-Za-z0-9])", name, re.IGNORECASE)
61
+ standard = re.search(rf"(?<![A-Za-z0-9.]){_AMOUNT}(?![A-Za-z0-9])", name)
62
+ total = active = None
63
+ if explicit:
64
+ total, active = _count(*explicit.groups()[:2]), _count(*explicit.groups()[2:])
65
+ elif experts:
66
+ per_expert = _count(*experts.groups()[1:])
67
+ total, active = int(experts[1]) * per_expert, min(2, int(experts[1])) * per_expert
68
+ elif standard:
69
+ total = _count(*standard.groups())
70
+
71
+ metadata = safetensors or {}
72
+ measured = metadata.get("total")
73
+ if not measured:
74
+ measured = sum(v for v in (metadata.get("parameters") or {}).values()
75
+ if isinstance(v, int) and v > 0)
76
+ if isinstance(measured, int) and measured > 0:
77
+ total = measured
78
+ active_metadata = metadata.get("active") or metadata.get("active_parameters")
79
+ if isinstance(active_metadata, int) and active_metadata > 0:
80
+ active = active_metadata
81
+ return total or None, min(active, total) if active and total else total
82
+
83
+
84
+ def fixed_quant(repo_id: str) -> str | None:
85
+ name = repo_id.rsplit("/", 1)[-1]
86
+ match = re.search(
87
+ r"(?<![a-z0-9])(?:i?q([2-8])(?:_[a-z0-9]+)*|([2-8])[-_ ]?bits?|(?:b|f)p?16|float16)(?![a-z0-9])",
88
+ name, re.IGNORECASE,
89
+ )
90
+ if not match:
91
+ return None
92
+ bits = match[1] or match[2]
93
+ if not bits:
94
+ return QUANT_LADDER[0][0]
95
+ return {"8": "Q8_0", "7": "Q8_0", "6": "Q6_K", "5": "Q5_K_M",
96
+ "4": "Q4_K_M", "3": "Q3_K_M", "2": "Q2_K"}[bits]
97
+
98
+
99
+ def _tier(spec: ModelSpec, hw: HardwareProfile, max_context: int, quant: tuple,
100
+ *, fixed: bool = False) -> QuantTier:
101
+ label, bytes_per_param, quality = quant
102
+ if not spec.params and not (fixed and spec.disk_bytes):
103
+ return QuantTier(label, None, None, None, quality, "UNKNOWN",
104
+ {"fit": 0, "speed": 0, "quality": quality, "context": 0}, 0)
105
+ weights = (spec.disk_bytes if fixed and spec.disk_bytes else spec.params * bytes_per_param) / GIB
106
+ encoder = spec.task in ENCODER_TASKS
107
+ # Estimate a GQA KV cache from active model scale. Architecture-specific caches vary.
108
+ active = spec.active_params or spec.params
109
+ scale = ((active or 1e9) / 7e9) ** 0.5
110
+ kv_per_token_gb = 0 if encoder else 128 * 1024 / GIB * max(0.1, scale)
111
+ overhead = max(0.12, weights * (0.30 if encoder else 0.12))
112
+ total = weights + overhead + max_context * kv_per_token_gb
113
+ comfortable = hw.comfortable_gb or hw.vram_gb
114
+ active_fraction = active / spec.params if active and spec.params else 1
115
+ efficiency = {"apple_silicon": 0.62, "cuda": 0.52, "cpu": 0.36}.get(hw.accelerator, 0.36)
116
+ speed = None
117
+ if not encoder:
118
+ speed = hw.bandwidth_gb_s * efficiency / max(weights * GIB / 1e9 * active_fraction, 0.01)
119
+ apple_only = any(tag.lower() in {"mlx", "coreml", "core-ml"} for tag in spec.tags)
120
+ apple_only |= bool(re.search(r"(?:^|[/_-])(?:mlx|coreml)(?:$|[/_-])", spec.id, re.IGNORECASE))
121
+ if apple_only and hw.accelerator != "apple_silicon":
122
+ verdict = "MAC-ONLY"
123
+ elif not hw.vram_gb:
124
+ verdict = "UNKNOWN"
125
+ elif total > hw.vram_gb:
126
+ verdict = "TOO-BIG"
127
+ elif hw.accelerator == "cpu":
128
+ verdict = "OK(CPU)" if total <= comfortable and (encoder or speed >= 8) else "SLOW(CPU)"
129
+ elif total > comfortable:
130
+ verdict = "TIGHT"
131
+ else:
132
+ verdict = "FAST" if (speed is not None and speed >= 30) or (encoder and total <= comfortable * 0.5) else "GOOD"
133
+
134
+ def points(value: float) -> int:
135
+ return round(max(0, min(100, value)))
136
+
137
+ fit = points(115 - 55 * total / comfortable) if comfortable else 0
138
+ speed_points = points(speed / 45 * 100) if speed is not None else fit
139
+ context = 100 if encoder else points(
140
+ (comfortable - weights - overhead) / (kv_per_token_gb * max_context) * 70
141
+ )
142
+ dimensions = {"fit": fit, "speed": speed_points, "quality": quality, "context": context}
143
+ score = round(fit * 0.40 + speed_points * 0.25 + quality * 0.25 + context * 0.10)
144
+ if verdict in {"TOO-BIG", "MAC-ONLY", "UNKNOWN"}:
145
+ score = min(score, 35) if verdict == "TOO-BIG" else 0
146
+ return QuantTier(label, round(weights, 3), round(total, 3),
147
+ round(speed, 1) if speed is not None else None, quality, verdict, dimensions, score)
148
+
149
+
150
+ def build_quant_plan(spec: ModelSpec, hw: HardwareProfile, max_context: int = 8192) -> list[QuantTier]:
151
+ if max_context <= 0:
152
+ raise ValueError("max_context must be greater than zero")
153
+ fixed = fixed_quant(spec.id) or fixed_quant(spec.quantization)
154
+ return [_tier(spec, hw, max_context, tier, fixed=tier[0] == fixed)
155
+ for tier in QUANT_LADDER]
156
+
157
+
158
+ def score_model(spec: ModelSpec, hw: HardwareProfile, max_context: int = 8192) -> QuantTier:
159
+ plan = build_quant_plan(spec, hw, max_context)
160
+ fixed = fixed_quant(spec.id) or fixed_quant(spec.quantization)
161
+ if fixed:
162
+ return next(tier for tier in plan if tier.quant == fixed)
163
+ if spec.task in ENCODER_TASKS:
164
+ return plan[0]
165
+ return next((tier for tier in plan if tier.total_gb is not None
166
+ and tier.total_gb <= (hw.comfortable_gb or hw.vram_gb)), plan[-1] if spec.params else plan[0])
167
+
168
+
169
+ def fmt_params(params: int | None) -> str:
170
+ if not params:
171
+ return "—"
172
+ return f"{params / 1e9:.2f}B" if params >= 1e9 else f"{params / 1e6:.1f}M"