quantprobe 1.18.0__tar.gz → 1.20.0__tar.gz

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 (34) hide show
  1. {quantprobe-1.18.0/quantprobe.egg-info → quantprobe-1.20.0}/PKG-INFO +1 -1
  2. {quantprobe-1.18.0 → quantprobe-1.20.0}/pyproject.toml +1 -1
  3. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/__init__.py +1 -1
  4. quantprobe-1.20.0/quantprobe/calibrate.py +255 -0
  5. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/cli.py +175 -163
  6. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/detect.py +183 -167
  7. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/plan.py +119 -7
  8. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/runtime.py +6 -0
  9. {quantprobe-1.18.0 → quantprobe-1.20.0/quantprobe.egg-info}/PKG-INFO +1 -1
  10. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe.egg-info/SOURCES.txt +1 -0
  11. {quantprobe-1.18.0 → quantprobe-1.20.0}/LICENSE +0 -0
  12. {quantprobe-1.18.0 → quantprobe-1.20.0}/README.md +0 -0
  13. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/__main__.py +0 -0
  14. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/auto.py +0 -0
  15. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/dashboard.py +0 -0
  16. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/fetch.py +0 -0
  17. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/optimize.py +0 -0
  18. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/probe.py +0 -0
  19. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/recipes/mistral-7b.json +0 -0
  20. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/recipes/qwen2.5-7b.json +0 -0
  21. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/recipes/qwen3-30b.json +0 -0
  22. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/recipes/qwen3.5-35b.json +0 -0
  23. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/recipes.py +0 -0
  24. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/spec.py +0 -0
  25. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe/target.py +0 -0
  26. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe.egg-info/dependency_links.txt +0 -0
  27. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe.egg-info/entry_points.txt +0 -0
  28. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe.egg-info/requires.txt +0 -0
  29. {quantprobe-1.18.0 → quantprobe-1.20.0}/quantprobe.egg-info/top_level.txt +0 -0
  30. {quantprobe-1.18.0 → quantprobe-1.20.0}/setup.cfg +0 -0
  31. {quantprobe-1.18.0 → quantprobe-1.20.0}/tests/test_engine.py +0 -0
  32. {quantprobe-1.18.0 → quantprobe-1.20.0}/tests/test_evaluator.py +0 -0
  33. {quantprobe-1.18.0 → quantprobe-1.20.0}/tests/test_pipeline.py +0 -0
  34. {quantprobe-1.18.0 → quantprobe-1.20.0}/tests/test_transforms.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantprobe
3
- Version: 1.18.0
3
+ Version: 1.20.0
4
4
  Summary: Probe-then-quantize for LLMs: measure a model's fragility curve, plan bit/tier placement by the tiered decode law, and emit ready-to-run llama.cpp recipes.
5
5
  Author: Federico Sciuca
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quantprobe"
7
- version = "1.18.0"
7
+ version = "1.20.0"
8
8
  description = "Probe-then-quantize for LLMs: measure a model's fragility curve, plan bit/tier placement by the tiered decode law, and emit ready-to-run llama.cpp recipes."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -8,4 +8,4 @@ Three commands, all grounded in measured laws (see LAWS.md in the repo):
8
8
  Every constant in `plan` is fitted from measurements published in the repo, including two
9
9
  pre-registered hardware predictions confirmed within 8%.
10
10
  """
11
- __version__ = "1.18.0"
11
+ __version__ = "1.20.0"
@@ -0,0 +1,255 @@
1
+ """quantprobe calibrate - measure THIS machine's constants instead of assuming ours.
2
+
3
+ Why this command exists: every constant this tool ships was measured on one reference box, and
4
+ pre-registration #59 proved that even on that box, fitted constants do not transfer across
5
+ models - let alone across machines. The law FORMS travel; the numbers do not. So on your
6
+ machine the honest move is to measure, not assume.
7
+
8
+ What it measures (each value tagged, nothing sent anywhere):
9
+ [measured] RAM stream bandwidth - a real sequential read, the pattern CPU decode is bound by.
10
+ Spec-sheet MT/s overstates what decode gets by 30-60%.
11
+ [measured] disk sequential read - only with --model FILE (reads the file's tail region).
12
+ [measured] GPU clock health - idle + max clocks now; sustained-under-load if an anchor
13
+ runs. Catches the STUCK BOOST STATE failure mode we
14
+ diagnosed on the reference box (SM locked ~18% low at cool
15
+ temps after hours of GPU churn; only a reboot clears it -
16
+ pre-registrations #60/#61).
17
+ [measured] pure-CPU anchor - only with --model: llama-bench -ngl 0 on your file, stored
18
+ as a reference point for plan's predicted-vs-measured line.
19
+
20
+ Results persist to ~/.quantprobe/calibration.json. `plan` (and everything built on it) uses the
21
+ measured RAM/disk numbers automatically whenever it would otherwise auto-detect, and labels them
22
+ [calibrated] instead of [table]/[default]. Delete the file to go back to detection.
23
+ """
24
+ from __future__ import annotations
25
+ import json, os, platform, subprocess, threading, time
26
+
27
+ CAL_DIR = os.path.join(os.path.expanduser("~"), ".quantprobe")
28
+ CAL_PATH = os.path.join(CAL_DIR, "calibration.json")
29
+ STALE_DAYS = 60 # hardware does not drift, but drivers and RAM configs do
30
+
31
+
32
+ def _run(cmd, timeout=30):
33
+ try:
34
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
35
+ except Exception:
36
+ return ""
37
+
38
+
39
+ def measure_ram_stream(gb=1.0, passes=3):
40
+ """Sequential read bandwidth of main memory, GB/s. Best of `passes`.
41
+
42
+ numpy sum over a float32 array bigger than any cache: the same access pattern the CPU
43
+ expert path is bound by. Falls back to None (with the reason) if numpy is missing or
44
+ allocation fails - a partial calibration is still a calibration.
45
+ """
46
+ try:
47
+ import numpy as np
48
+ except ImportError:
49
+ return None, "numpy not installed - RAM stream skipped (pip install numpy)"
50
+ n = int(gb * 1e9 / 4)
51
+ try:
52
+ a = np.ones(n, dtype=np.float32)
53
+ except MemoryError:
54
+ return None, f"could not allocate {gb:g} GB - RAM stream skipped"
55
+ # int64-view max, not float sum: float reductions in numpy can be COMPUTE-bound (measured
56
+ # 9.3 GB/s on the reference box where the memory delivers 26) and would silently calibrate
57
+ # numpy's ALU instead of the memory bus. Integer max is one SIMD pass, one read per byte -
58
+ # it reproduces the reference box's independently measured 26.1 GB/s stream.
59
+ v = a.view(np.int64)
60
+ best = 0.0
61
+ for _ in range(passes):
62
+ t0 = time.perf_counter()
63
+ v.max()
64
+ dt = time.perf_counter() - t0
65
+ best = max(best, (n * 4) / 1e9 / dt)
66
+ del a
67
+ return round(best, 2), None
68
+
69
+
70
+ def gpu_state():
71
+ """Current + max clocks and temperature via nvidia-smi; None if no NVIDIA GPU."""
72
+ out = _run(["nvidia-smi", "--query-gpu=name,clocks.sm,clocks.max.sm,clocks.mem,temperature.gpu",
73
+ "--format=csv,noheader,nounits"])
74
+ line = out.strip().splitlines()[0] if out.strip() else ""
75
+ if "," not in line:
76
+ return None
77
+ try:
78
+ name, sm, sm_max, mem, temp = [v.strip() for v in line.rsplit(",", 4)]
79
+ return dict(name=name, sm=int(sm), sm_max=int(sm_max), mem=int(mem), temp=int(temp))
80
+ except ValueError:
81
+ return None
82
+
83
+
84
+ class ClockSampler:
85
+ """Samples clocks.sm in a thread while a benchmark runs - the boost-state instrument."""
86
+
87
+ def __init__(self, every=1.0):
88
+ self.every, self.samples, self._stop = every, [], threading.Event()
89
+ self._t = threading.Thread(target=self._loop, daemon=True)
90
+
91
+ def _loop(self):
92
+ while not self._stop.is_set():
93
+ st = gpu_state()
94
+ if st:
95
+ self.samples.append((st["sm"], st["temp"]))
96
+ self._stop.wait(self.every)
97
+
98
+ def __enter__(self):
99
+ self._t.start()
100
+ return self
101
+
102
+ def __exit__(self, *exc):
103
+ self._stop.set()
104
+ self._t.join(timeout=5)
105
+
106
+ def sustained(self):
107
+ """Median SM MHz over loaded samples (>1000 MHz); None below 3 samples.
108
+
109
+ The minimum matters: a short benchmark gives the sampler only the model-LOAD phase,
110
+ where clocks sit mid-ramp - measured on the reference box as a false STUCK-BOOST verdict
111
+ (1506 read during load; the very next real benchmarks sustained 1873-1898). One or two
112
+ samples are a coin flip, not a diagnosis.
113
+ """
114
+ loaded = sorted(s for s, _ in self.samples if s > 1000)
115
+ return loaded[len(loaded) // 2] if len(loaded) >= 3 else None
116
+
117
+
118
+ def boost_verdict(sustained, sm_max, temp):
119
+ """The #60/#61 diagnostic as a one-line verdict."""
120
+ if sustained is None or not sm_max:
121
+ return None
122
+ frac = sustained / sm_max
123
+ if frac >= 0.87:
124
+ return f"healthy: sustained {sustained} of {sm_max} MHz max [measured]"
125
+ hot = temp is not None and temp >= 80
126
+ if hot:
127
+ return (f"THROTTLED: sustained {sustained} of {sm_max} MHz at {temp} C - thermal; "
128
+ "check cooling")
129
+ return (f"STUCK BOOST STATE: sustained {sustained} of {sm_max} MHz at cool temps - the "
130
+ "failure mode measured in preregistrations #60/#61 (-25-30%% real speed). Consumer "
131
+ "cards cannot reset it live: REBOOT, then re-run calibrate")
132
+
133
+
134
+ def _bench_anchor(model_path, ngl, metric_tokens, llama_dir=None):
135
+ """One llama-bench arm on the user's own file, clocks sampled. Returns (dict, err)."""
136
+ from .runtime import find_llama
137
+ try:
138
+ binp = find_llama(llama_dir, "llama-bench")
139
+ except SystemExit:
140
+ return None, "llama-bench not found - anchor skipped (pass --llama-dir)"
141
+ tag = f"tg{metric_tokens}"
142
+ with ClockSampler() as clk:
143
+ out = _run([binp, "-m", model_path, "-ngl", str(ngl), "-n", str(metric_tokens),
144
+ "-p", "0", "-r", "1"], timeout=1800)
145
+ for line in out.splitlines():
146
+ if tag in line and "|" in line:
147
+ try:
148
+ toks = float(line.split("|")[-2].strip().split()[0])
149
+ return dict(placement=("pure CPU (-ngl 0)" if ngl == 0 else "all-in-VRAM (-ngl 99)"),
150
+ metric=tag, tok_s=toks,
151
+ model=os.path.basename(model_path),
152
+ model_gb=round(os.path.getsize(model_path) / 1e9, 3),
153
+ sustained_sm=clk.sustained()), None
154
+ except (ValueError, IndexError):
155
+ break
156
+ return None, "could not parse llama-bench output - anchor skipped"
157
+
158
+
159
+ def cpu_anchor(model_path, llama_dir=None):
160
+ """Pure-CPU tg32 on the user's own file: a real measured reference point.
161
+
162
+ Placement chosen because it needs no VRAM-fit logic and no MoE byte accounting - it is the
163
+ one arm that runs identically on every machine that can load the file at all.
164
+ """
165
+ return _bench_anchor(model_path, 0, 32, llama_dir)
166
+
167
+
168
+ def gpu_anchor(model_path, vram_gb, llama_dir=None):
169
+ """All-in-VRAM tg128 on the user's own file - the GPU-tier anchor. Only offered when the file
170
+ clearly fits (80% of detected VRAM), because an OOM teaches nothing and wastes minutes.
171
+ tg128 rather than tg64: the run must outlast the model-load phase by enough for the clock
172
+ sampler to collect real loaded samples (see ClockSampler.sustained)."""
173
+ gb = os.path.getsize(model_path) / 1e9
174
+ if not vram_gb or gb > 0.8 * vram_gb:
175
+ return None, f"model {gb:.1f} GB does not clearly fit {vram_gb or 0:.0f} GB VRAM - GPU anchor skipped"
176
+ return _bench_anchor(model_path, 99, 128, llama_dir)
177
+
178
+
179
+ def load():
180
+ """Return (calibration dict, age_days) or (None, None). Used by plan."""
181
+ try:
182
+ with open(CAL_PATH, encoding="utf-8") as f:
183
+ cal = json.load(f)
184
+ age = (time.time() - cal.get("ts", 0)) / 86400
185
+ return cal, age
186
+ except (OSError, ValueError):
187
+ return None, None
188
+
189
+
190
+ def run(a):
191
+ print("quantprobe calibrate - measuring THIS machine (nothing is sent anywhere)\n")
192
+ cal = dict(ts=time.time(), date=time.strftime("%Y-%m-%d"), host=platform.node(),
193
+ tool_version=__import__("quantprobe").__version__)
194
+
195
+ ram_bw, why = measure_ram_stream()
196
+ if ram_bw:
197
+ cal["ram_bw_measured"] = ram_bw
198
+ print(f" RAM stream: {ram_bw:.2f} GB/s [measured] - this replaces the spec-sheet "
199
+ "number, which overstates what decode gets")
200
+ else:
201
+ print(f" RAM stream: {why}")
202
+
203
+ st = gpu_state()
204
+ if st:
205
+ cal["gpu"] = st
206
+ print(f" GPU: {st['name']}, idle {st['sm']} MHz (max {st['sm_max']}), {st['temp']} C [os]")
207
+ else:
208
+ print(" GPU: none detected (nvidia-smi absent/empty)")
209
+
210
+ model = getattr(a, "model", None)
211
+ if model and os.path.isfile(model):
212
+ from .detect import measure_disk
213
+ cal["disk_bw_measured"] = round(measure_disk(model), 2)
214
+ print(f" disk: {cal['disk_bw_measured']:.2f} GB/s sequential on your file [measured]")
215
+ if not getattr(a, "skip_bench", False):
216
+ cal["anchors"] = []
217
+ print(" anchor: running llama-bench -ngl 0 tg32 on your file (1-10 min on big models)...")
218
+ anchor, why = cpu_anchor(model, getattr(a, "llama_dir", None))
219
+ if anchor:
220
+ cal["anchors"].append(anchor)
221
+ print(f" anchor: {anchor['tok_s']:.2f} tok/s pure-CPU on "
222
+ f"{anchor['model']} ({anchor['model_gb']:g} GB) [measured]")
223
+ else:
224
+ print(f" anchor: {why}")
225
+ vram_gb = None
226
+ if st:
227
+ out = _run(["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"])
228
+ try:
229
+ vram_gb = float(out.strip().splitlines()[0]) / 1024
230
+ except (ValueError, IndexError):
231
+ pass
232
+ ganchor, gwhy = gpu_anchor(model, vram_gb, getattr(a, "llama_dir", None))
233
+ if ganchor:
234
+ cal["anchors"].append(ganchor)
235
+ print(f" anchor: {ganchor['tok_s']:.2f} tok/s all-in-VRAM on "
236
+ f"{ganchor['model']} [measured]")
237
+ v = boost_verdict(ganchor.get("sustained_sm"), st and st.get("sm_max"),
238
+ st and st.get("temp"))
239
+ if v:
240
+ cal["boost_verdict"] = v
241
+ print(f" GPU under load: {v}")
242
+ else:
243
+ print(f" anchor: {gwhy}")
244
+ elif model:
245
+ print(f" --model: file not found: {model}")
246
+ else:
247
+ print(" (pass --model your.gguf to also measure disk + a real decode anchor)")
248
+
249
+ os.makedirs(CAL_DIR, exist_ok=True)
250
+ with open(CAL_PATH, "w", encoding="utf-8") as f:
251
+ json.dump(cal, f, indent=1)
252
+ print(f"\n saved: {CAL_PATH}")
253
+ print(" plan/optimize/auto now use the measured values automatically (tagged [calibrated]).")
254
+ print(" Delete the file to return to auto-detection. Re-run after RAM/driver changes.")
255
+ return cal