quantprobe 1.24.0__tar.gz → 1.25.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 (37) hide show
  1. {quantprobe-1.24.0/quantprobe.egg-info → quantprobe-1.25.0}/PKG-INFO +1 -1
  2. {quantprobe-1.24.0 → quantprobe-1.25.0}/pyproject.toml +1 -1
  3. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/__init__.py +1 -1
  4. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/auto.py +52 -3
  5. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/cli.py +9 -0
  6. quantprobe-1.25.0/quantprobe/ollama.py +314 -0
  7. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/plan.py +41 -22
  8. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/runtime.py +258 -258
  9. quantprobe-1.25.0/quantprobe/smoke.py +2507 -0
  10. {quantprobe-1.24.0 → quantprobe-1.25.0/quantprobe.egg-info}/PKG-INFO +1 -1
  11. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe.egg-info/SOURCES.txt +2 -0
  12. {quantprobe-1.24.0 → quantprobe-1.25.0}/LICENSE +0 -0
  13. {quantprobe-1.24.0 → quantprobe-1.25.0}/README.md +0 -0
  14. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/__main__.py +0 -0
  15. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/branding.py +0 -0
  16. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/calibrate.py +0 -0
  17. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/dashboard.py +0 -0
  18. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/detect.py +0 -0
  19. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/fetch.py +0 -0
  20. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/optimize.py +0 -0
  21. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/probe.py +0 -0
  22. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/recipes/mistral-7b.json +0 -0
  23. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/recipes/qwen2.5-7b.json +0 -0
  24. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/recipes/qwen3-30b.json +0 -0
  25. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/recipes/qwen3.5-35b.json +0 -0
  26. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/recipes.py +0 -0
  27. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/spec.py +0 -0
  28. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe/target.py +0 -0
  29. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe.egg-info/dependency_links.txt +0 -0
  30. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe.egg-info/entry_points.txt +0 -0
  31. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe.egg-info/requires.txt +0 -0
  32. {quantprobe-1.24.0 → quantprobe-1.25.0}/quantprobe.egg-info/top_level.txt +0 -0
  33. {quantprobe-1.24.0 → quantprobe-1.25.0}/setup.cfg +0 -0
  34. {quantprobe-1.24.0 → quantprobe-1.25.0}/tests/test_engine.py +0 -0
  35. {quantprobe-1.24.0 → quantprobe-1.25.0}/tests/test_evaluator.py +0 -0
  36. {quantprobe-1.24.0 → quantprobe-1.25.0}/tests/test_pipeline.py +0 -0
  37. {quantprobe-1.24.0 → quantprobe-1.25.0}/tests/test_transforms.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantprobe
3
- Version: 1.24.0
3
+ Version: 1.25.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.24.0"
7
+ version = "1.25.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.24.0"
11
+ __version__ = "1.25.0"
@@ -189,6 +189,45 @@ def apply_to(spec, a):
189
189
  return spec
190
190
 
191
191
 
192
+
193
+ def local_spec_or_none(local, expected_size, n_parts):
194
+ """Read a downloaded GGUF's header - but ONLY if the file is actually complete.
195
+
196
+ Returns (spec_or_None, note_or_None). Split out of `run` so the decision is testable
197
+ against a real truncated file rather than asserted on by reading source text - the first
198
+ guard written for this was a source-inspection test, and disabling the size check left it
199
+ green, which is the decorative-test pattern this suite exists to catch.
200
+
201
+ "Already on disk" is not "complete". An interrupted `fetch` leaves a partial GGUF at exactly
202
+ the path `auto` probes, and there are two failure modes:
203
+
204
+ LOUD from_gguf RAISES. Reproduced: a 200 KB slice of a 531 MB GGUF gives ValueError out
205
+ of the tensor-shape reader. Unguarded, that killed the whole `auto` command with a
206
+ traceback instead of falling back to the estimate it had already computed.
207
+ QUIET from_gguf SUCCEEDS on a truncated file and returns a plausible-but-wrong spec, so
208
+ `auto` prints a confident number for a model that is not there. This is the worse
209
+ one, and only the size check catches it. A crash is recoverable; a confident wrong
210
+ answer is the defect class this project exists to remove.
211
+ """
212
+ if not os.path.isfile(local):
213
+ return None, None
214
+ have = os.path.getsize(local)
215
+ # multi-part repos: `expected_size` is the total while `local` is one shard, so the
216
+ # comparison does not apply and is skipped rather than made to look meaningful.
217
+ if n_parts == 1 and expected_size and have != expected_size:
218
+ return None, (f"{os.path.basename(local)} is on disk but INCOMPLETE - {have/1e9:.2f} GB "
219
+ f"of {expected_size/1e9:.2f} GB ({have/expected_size*100:.1f}%). Its header "
220
+ f"is not trusted; using the pre-download estimate instead. Finish it with "
221
+ f"`quantprobe fetch --force` before quoting a number from this file.")
222
+ from . import spec as specmod
223
+ try:
224
+ return specmod.from_gguf(local), None
225
+ except Exception as e:
226
+ return None, (f"{os.path.basename(local)} is on disk but its header could not be read "
227
+ f"({type(e).__name__}). Falling back to the pre-download estimate. If the "
228
+ f"download was interrupted, `quantprobe fetch --force` will replace it.")
229
+
230
+
192
231
  def run(a):
193
232
  if a.target is None:
194
233
  _wizard(a)
@@ -302,10 +341,20 @@ def run(a):
302
341
  # Measured divergence on the flagship: auto 26.2 vs plan 19.5 for the SAME file. If the file
303
342
  # is already on disk, use the real thing; otherwise say plainly that it is a pre-download
304
343
  # estimate and which command is authoritative.
344
+ # "already on disk" is not the same as "complete". An interrupted `fetch` leaves a partial
345
+ # file at exactly this path, and there are TWO failure modes, the quieter one being worse:
346
+ # (a) from_gguf RAISES - reproduced on a 200 KB slice of a 531 MB GGUF, ValueError out of
347
+ # the tensor-shape reader. Unguarded, that killed the whole `auto` command with a
348
+ # traceback instead of falling back to the estimate it had already computed.
349
+ # (b) from_gguf SUCCEEDS on a truncated file and returns a plausible-but-wrong spec, so
350
+ # `auto` confidently prints a number derived from a model that is not there. A crash
351
+ # is recoverable; a confident wrong answer is the defect class this project exists to
352
+ # remove. The size check below is what catches (b), and it is the more important half.
305
353
  _local = os.path.join(getattr(a, "dir", None) or "./models", os.path.basename(path))
306
- if os.path.isfile(_local):
307
- from . import spec as specmod
308
- _s = specmod.from_gguf(_local)
354
+ _s, _why = local_spec_or_none(_local, size, len(parts))
355
+ if _why:
356
+ print(" NOTE: " + _why)
357
+ if _s:
309
358
  _, _, _c = planmod.evaluate(_s["t"], _s["a"], _s["ne"], _s["moe"], _s["bits"], vc, vb,
310
359
  rc, rb, db, geta, 1.0, gl, ctx=ctx, kvp=_s["kvp"],
311
360
  n_layer=_s["n_layer"], true_size_gb=size / 1e9,
@@ -78,6 +78,12 @@ def main():
78
78
  d.add_argument("--port", type=int, default=8077); d.add_argument("--server-port", type=int, default=8090)
79
79
  d.add_argument("--no-open", action="store_true")
80
80
 
81
+ o = sub.add_parser("audit-ollama", help="price the models already in your ollama store, on this machine")
82
+ hwargs(o)
83
+ o.add_argument("--store", default=None, help="ollama models dir (default: $OLLAMA_MODELS or ~/.ollama/models)")
84
+ o.add_argument("--measure", action="store_true",
85
+ help="also RUN ollama and report its measured eval rate beside the prediction")
86
+
81
87
  g = sub.add_parser("target", help="INVERSE planning: give a tok/s target, get the smartest feasible model + the speed-intelligence ladder")
82
88
  g.add_argument("--tps", type=float, required=True, help="minimum tok/s you need")
83
89
  hwargs(g)
@@ -172,6 +178,9 @@ def main():
172
178
  elif a.cmd == "quantize":
173
179
  from . import probe
174
180
  probe.quantize(a)
181
+ elif a.cmd == "audit-ollama":
182
+ from . import ollama as ollamamod
183
+ ollamamod.run(a)
175
184
  else:
176
185
  from . import fetch
177
186
  fetch.run(a)
@@ -0,0 +1,314 @@
1
+ """quantprobe audit-ollama - price the models you already have, on the machine you already have.
2
+
3
+ quantprobe audit-ollama # read the store, predict, print the flags
4
+ quantprobe audit-ollama --measure # also RUN ollama and compare against the prediction
5
+
6
+ WHY THIS IS DIFFERENT FROM `plan`. `plan` needs you to know which file you want. This needs
7
+ nothing: ollama's blobs ARE GGUFs, so the real header is already on your disk. Params come from
8
+ the file, not from parsing a name - which matters because ollama tags say "7b" and the header
9
+ here says 7.615616512B total with 4.92 effective bits.
10
+
11
+ WHAT IT WILL NOT DO. It will not tell you "you are leaving X% on the table" unless you pass
12
+ --measure, because without measuring ollama we would be comparing our prediction against our
13
+ own assumption about a runtime we did not run. That is the shape of every defect this project
14
+ has published: a confident number with nothing behind it. --measure runs both sides and reports
15
+ what actually happened, including when the prediction is the thing that was wrong.
16
+ """
17
+ from __future__ import annotations
18
+ import json, os, glob, shutil, subprocess, time
19
+
20
+ MODEL_MEDIA = "application/vnd.ollama.image.model"
21
+
22
+
23
+ def store_root(explicit=None):
24
+ """Where ollama keeps its blobs. OLLAMA_MODELS wins, then the per-OS default."""
25
+ if explicit:
26
+ return explicit
27
+ env = os.environ.get("OLLAMA_MODELS")
28
+ if env:
29
+ return env
30
+ return os.path.expanduser(os.path.join("~", ".ollama", "models"))
31
+
32
+
33
+ def installed(root=None):
34
+ """[(name, blob_path, size_bytes)] for every model in the store.
35
+
36
+ Walks manifests/ rather than calling `ollama list`, so it works when the daemon is not
37
+ running and it gives the blob path directly. The manifest name is its path under
38
+ manifests/<registry>/<namespace>/<model>/<tag>, which is how ollama itself addresses it.
39
+ """
40
+ root = store_root(root)
41
+ mdir = os.path.join(root, "manifests")
42
+ out = []
43
+ if not os.path.isdir(mdir):
44
+ return out
45
+ for f in glob.glob(os.path.join(mdir, "**"), recursive=True):
46
+ if not os.path.isfile(f):
47
+ continue
48
+ try:
49
+ m = json.load(open(f, encoding="utf-8"))
50
+ except Exception:
51
+ continue # not a manifest; skip rather than guess
52
+ layers = [l for l in m.get("layers", []) if l.get("mediaType") == MODEL_MEDIA]
53
+ if not layers:
54
+ continue
55
+ rel = os.path.relpath(f, mdir).replace(os.sep, "/").split("/")
56
+ name = f"{rel[-2]}:{rel[-1]}" if len(rel) >= 2 else "/".join(rel)
57
+ digest = layers[0]["digest"].split(":")[-1]
58
+ blob = os.path.join(root, "blobs", f"sha256-{digest}")
59
+ if os.path.isfile(blob):
60
+ out.append((name, blob, os.path.getsize(blob)))
61
+ return sorted(set(out))
62
+
63
+
64
+ def ollama_bin():
65
+ return shutil.which("ollama") or shutil.which("ollama.exe")
66
+
67
+
68
+ def loaded_placement(name):
69
+ """What ollama ACTUALLY chose: (gpu_percent, ctx) from `ollama ps`, or (None, None).
70
+
71
+ This is the difference between an honest audit and a misleading one. quantprobe prices
72
+ all-in-VRAM; if ollama split the model instead, the two numbers describe DIFFERENT
73
+ placements and comparing them would look like a speed claim while actually being a
74
+ category error. Measured here on a 6 GB card: ollama loaded qwen2.5:7b as 16%/84% CPU/GPU
75
+ even though the model fits, so the gap was never evidence about anyone's prediction.
76
+ """
77
+ b = ollama_bin()
78
+ if not b:
79
+ return None, None
80
+ try:
81
+ out = subprocess.run([b, "ps"], capture_output=True, text=True, timeout=30).stdout
82
+ except Exception:
83
+ return None, None
84
+ import re
85
+ for line in out.splitlines():
86
+ if not line.startswith(name.split(":")[0]):
87
+ continue
88
+ m = re.search(r"(\d+)%/(\d+)%\s*CPU/GPU", line)
89
+ gpu = int(m.group(2)) if m else (100 if "100% GPU" in line else None)
90
+ c = re.search(r"\b(\d{3,6})\b\s*$", line.replace("from now", "").strip())
91
+ ctxm = re.search(r"\s(\d{3,6})\s+\d+\s*(?:minutes?|seconds?|hours?)", line)
92
+ return gpu, int(ctxm.group(1)) if ctxm else None
93
+ return None, None
94
+
95
+
96
+ def bench_blob(blob, ngl, ctx, bench_bin, n=64, reps=3, timeout=900):
97
+ """Time ONE placement of the ollama blob with llama-bench. Returns tok/s or None.
98
+
99
+ Both sides of the comparison go through this, at the SAME context depth, on the SAME
100
+ file - so the number that comes out is a placement difference and nothing else.
101
+ """
102
+ cmd = [bench_bin, "-m", blob, "-ngl", str(ngl), "-n", str(n), "-p", "0", "-r", str(reps),
103
+ "-o", "json"]
104
+ if ctx:
105
+ cmd += ["-d", str(ctx)]
106
+ try:
107
+ p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=timeout)
108
+ except subprocess.TimeoutExpired:
109
+ return None
110
+ out = p.stdout + p.stderr
111
+ try:
112
+ return json.loads(out[out.index("["):out.rindex("]") + 1])[0].get("avg_ts")
113
+ except Exception:
114
+ return None
115
+
116
+
117
+ def find_llamabench():
118
+ for name in ("llama-bench", "llama-bench.exe"):
119
+ w = shutil.which(name)
120
+ if w:
121
+ return w
122
+ env = os.environ.get("QP_LLAMACPP")
123
+ if env and os.path.isfile(os.path.join(env, "llama-bench.exe")):
124
+ return os.path.join(env, "llama-bench.exe")
125
+ here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
126
+ for _ in range(8):
127
+ c = os.path.join(here, "tools", "llamacpp-b10098", "llama-bench.exe")
128
+ if os.path.isfile(c):
129
+ return c
130
+ nh = os.path.dirname(here)
131
+ if nh == here:
132
+ break
133
+ here = nh
134
+ return None
135
+
136
+
137
+ def measure(name, prompt="Count from 1 to 40, one number per line.", timeout=300):
138
+ """Actually run ollama and read ITS OWN reported eval rate.
139
+
140
+ Parsed from `--verbose` rather than timed by us: ollama reports eval_count and
141
+ eval_duration, which excludes prompt processing and model load. Timing the wall clock
142
+ ourselves would fold load time into a decode number and flatter or damage it depending on
143
+ whether the model happened to be resident.
144
+ """
145
+ b = ollama_bin()
146
+ if not b:
147
+ return None, "ollama not on PATH"
148
+ try:
149
+ p = subprocess.run([b, "run", name, "--verbose", prompt],
150
+ capture_output=True, text=True, errors="replace", timeout=timeout)
151
+ except subprocess.TimeoutExpired:
152
+ return None, f"timed out after {timeout}s"
153
+ r = _parse_rate(p.stdout + p.stderr)
154
+ if r is None:
155
+ return None, "could not parse a generation eval rate from ollama --verbose"
156
+ return r, None
157
+
158
+
159
+ def _parse_rate(out):
160
+ """ollama's GENERATION rate from --verbose output, or None. Split out to be testable.
161
+
162
+ MUST NOT match "prompt eval rate:", which ollama prints FIRST. A bare re.search for
163
+ "eval rate" takes that one, and prompt throughput is a different quantity an order of
164
+ magnitude larger - measured on real output, 186.59 against a true generation rate of
165
+ 19.92. That misread is not obviously wrong on sight: it looks like a plausible tok/s, and
166
+ it made audit-ollama report ollama as already faster than anything worth recommending.
167
+ Anchoring at line start is the fix.
168
+ """
169
+ import re
170
+ m = re.search(r"^\s*eval rate:\s*([0-9.]+)\s*tokens/s", out, re.M)
171
+ if m:
172
+ return float(m.group(1))
173
+ ec = re.search(r"^\s*eval count:\s*(\d+)", out, re.M)
174
+ ed = re.search(r"^\s*eval duration:\s*([0-9.]+)\s*(ms|s|m)\b", out, re.M)
175
+ if ec and ed:
176
+ v = float(ed.group(1)) * {"ms": 1e-3, "s": 1.0, "m": 60.0}[ed.group(2)]
177
+ return (int(ec.group(1)) / v) if v else None
178
+ return None
179
+
180
+
181
+ def unload(name, need_free_mib=4500, tries=20):
182
+ """Make ollama release the GPU before we time anything else on it.
183
+
184
+ Without this the audit contaminates its own comparison. ollama keeps a model resident for
185
+ ~5 minutes after a run: measured here, 5209 MiB of a 6144 MiB card still held. llama-bench
186
+ then cannot fit all layers, silently spills to CPU, and the tool reports the recommended
187
+ config as SLOWER than the one it is meant to beat - confidently, and backwards. Measured
188
+ contaminated: -ngl 99 scored 4.56 tok/s; clean, the same command scores 18.83.
189
+
190
+ Returns True only when the GPU is actually free. The caller must refuse to compare
191
+ otherwise - a contaminated comparison that produces advice is worse than no comparison.
192
+ """
193
+ b = ollama_bin()
194
+ if b:
195
+ try:
196
+ subprocess.run([b, "stop", name], capture_output=True, text=True, timeout=60)
197
+ except Exception:
198
+ pass
199
+ for _ in range(tries):
200
+ try:
201
+ r = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,memory.total",
202
+ "--format=csv,noheader,nounits"],
203
+ capture_output=True, text=True, timeout=20).stdout.strip()
204
+ used, total = [int(x) for x in r.splitlines()[0].split(",")]
205
+ if (total - used) >= need_free_mib:
206
+ return True, total - used
207
+ except Exception:
208
+ return None, None # no nvidia-smi: cannot verify, so do not claim clean
209
+ time.sleep(3)
210
+ return False, None
211
+
212
+
213
+ def run(a):
214
+ from . import plan as planmod, spec as specmod
215
+ root = store_root(getattr(a, "store", None))
216
+ models = installed(root)
217
+ print(f"quantprobe audit-ollama - store: {root}")
218
+ if not models:
219
+ print("\n no ollama models found. Pull one first: ollama pull qwen2.5:7b")
220
+ print(" (or point at a different store with --store, or set OLLAMA_MODELS)")
221
+ return
222
+ vc, vb, rc, rb, db, geta, gl, hw = planmod.resolve_hw(a, announce=False)
223
+ print(f" this machine: vram {vc:g} GB @ {vb:g} | ram {rc:g} GB @ {rb:g} | disk {db:g} GB/s"
224
+ + (f" [{hw['hint']}]" if hw.get("hint") else ""))
225
+ print(f" {len(models)} model(s) on disk\n")
226
+
227
+ for name, blob, size in models:
228
+ print(f" {name} ({size/1e9:.2f} GB)")
229
+ try:
230
+ s = specmod.from_gguf(blob)
231
+ except Exception as e:
232
+ print(f" header unreadable ({type(e).__name__}) - skipped, not guessed\n")
233
+ continue
234
+ print(f" from the file's own header: {s['t']:.2f}B total, {s['a']:.2f}B active, "
235
+ f"{s['bits']:.2f} effective bits, {s['n_layer']} layers"
236
+ + (", MoE" if s["moe"] else ", dense"))
237
+ # Same evaluate() the `plan` command calls, with hardware from the same resolver, so
238
+ # the two commands cannot quote different numbers for one file on one box.
239
+ _, _, allrows = planmod.evaluate(
240
+ s["t"], s["a"], s["ne"], s["moe"], s["bits"], vc, vb, rc, rb, db, geta,
241
+ 1.0, gl, ctx=getattr(a, "ctx", 0) or 0, kvp=s["kvp"], n_layer=s["n_layer"],
242
+ true_size_gb=size / 1e9, codebook_share=s.get("codebook_share", 0.0))
243
+ # only rows a user can actually execute: the expert-cache and layer-streaming rows
244
+ # need runtimes ollama does not ship, so recommending them here would be a non-command
245
+ rows = [r for r in allrows if getattr(r, "runnable", True)]
246
+ if rows:
247
+ best = rows[0]
248
+ print(f" quantprobe predicts: {best[1]:.1f} tok/s ({best[0]})")
249
+ if best[3]:
250
+ print(f" flags: {best[3]}")
251
+ if getattr(a, "measure", False):
252
+ print(" running ollama to see what it actually does...", flush=True)
253
+ got, err = measure(name)
254
+ gpu_pct, octx = loaded_placement(name)
255
+ if err:
256
+ print(f" ollama measurement FAILED: {err} - no comparison made")
257
+ print("")
258
+ continue
259
+ print(f" ollama MEASURED: {got:.1f} tok/s (its own eval rate)")
260
+ if gpu_pct is not None:
261
+ print(f" ollama's PLACEMENT: {100-gpu_pct}%/{gpu_pct}% CPU/GPU"
262
+ + (f" at ctx {octx}" if octx else ""))
263
+ # The comparison that means something: BOTH placements timed by the same tool, on
264
+ # the SAME blob, at the SAME depth. Prediction-vs-ollama would compare different
265
+ # placements and read as a speed claim while being a category error.
266
+ bb = find_llamabench()
267
+ if bb and gpu_pct is not None and gpu_pct < 100:
268
+ nl = s["n_layer"] or 32
269
+ theirs_ngl = max(0, round(nl * gpu_pct / 100))
270
+ print(" unloading ollama so it stops holding the GPU...", flush=True)
271
+ clean, freed = unload(name)
272
+ if clean is None:
273
+ print(" cannot read GPU memory (no nvidia-smi), so a clean comparison")
274
+ print(" cannot be VERIFIED. Refusing to compare rather than guess.")
275
+ print("")
276
+ continue
277
+ if not clean:
278
+ print(" ollama is still holding the GPU. REFUSING to compare - a")
279
+ print(" contaminated bench reports the right config as slower and would")
280
+ print(" hand you exactly the wrong advice. Retry in a minute.")
281
+ print("")
282
+ continue
283
+ print(f" GPU free: {freed} MiB. Timing BOTH placements at ctx {octx or 0}...",
284
+ flush=True)
285
+ mine = bench_blob(blob, 99, octx or 0, bb)
286
+ thrs = bench_blob(blob, theirs_ngl, octx or 0, bb)
287
+ if mine and thrs:
288
+ print(f" ollama's split (-ngl {theirs_ngl}): {thrs:.2f} tok/s")
289
+ print(f" all layers (-ngl 99): {mine:.2f} tok/s")
290
+ if mine > thrs:
291
+ print(f" >> {mine/thrs:.2f}x AVAILABLE by forcing all layers onto the "
292
+ f"GPU. It fits - no OOM at ctx {octx or 0}.")
293
+ print(f" In ollama: PARAMETER num_gpu {nl} (Modelfile), or set "
294
+ f"OLLAMA_NUM_GPU={nl}")
295
+ else:
296
+ print(f" >> ollama's split is FASTER here ({thrs/mine:.2f}x). Its "
297
+ f"conservatism is correct on this box; no change recommended.")
298
+ print(f" Both timed by llama-bench on the same blob at the same depth, "
299
+ f"so this is a\n placement difference and nothing else. ollama's "
300
+ f"own {got:.1f} sits below both - the\n remainder is its server "
301
+ f"and sampling overhead, which this does not measure.")
302
+ else:
303
+ print(" could not time both placements - no comparison claimed")
304
+ elif gpu_pct == 100:
305
+ print(" ollama already has every layer on the GPU - nothing to recommend")
306
+ elif not bb:
307
+ print(" llama-bench not found, so no measured comparison was made. The")
308
+ print(" prediction above is NOT a substitute for one.")
309
+ print("")
310
+
311
+ if not getattr(a, "measure", False):
312
+ print(" No speed comparison was made. Numbers above are PREDICTIONS for this machine;")
313
+ print(" `--measure` runs ollama and reports what it actually does, including when the")
314
+ print(" prediction is what turns out to be wrong.")
@@ -1766,6 +1766,46 @@ def binding_report(bc, bits=None, placement=None):
1766
1766
  return lines
1767
1767
 
1768
1768
 
1769
+
1770
+ def resolve_hw(args, announce=True):
1771
+ """The one place hardware inputs are resolved: preset -> auto-detect -> calibration -> flags.
1772
+
1773
+ Extracted from `run` so `audit-ollama` cannot drift from `plan`. Two commands quoting
1774
+ different tok/s for the same file on the same box would be worse than either being wrong,
1775
+ because a user would have no way to tell which to believe - the C-15 auto-vs-plan
1776
+ divergence (26.2 vs 19.5 on one model) is exactly that failure, and it took a measurement
1777
+ to notice. Returns the same tuple `run` used to build inline, plus the hw dict for its hint.
1778
+
1779
+ `announce=False` suppresses the auto-detect banner for callers that print their own header.
1780
+ """
1781
+ hw = dict(MACHINES[args.machine]) if getattr(args, "machine", None) in MACHINES else {}
1782
+ if not hw and all(getattr(args, k, None) is None
1783
+ for k in ("vram", "vram_bw", "ram", "ram_bw", "disk_bw")):
1784
+ from . import detect as detmod
1785
+ auto, _ = detmod.detect()
1786
+ hw = dict(vc=auto["vram"], vb=auto["vram_bw"], rc=auto["ram"], rb=auto["ram_bw"],
1787
+ db=auto["disk_bw"], geta=auto.get("geta", 0.45), gl=auto.get("gl"),
1788
+ hint="THIS machine [auto-detected - run `quantprobe hw` for details]")
1789
+ if announce:
1790
+ print("[quantprobe] no hardware flags: auto-detected this machine "
1791
+ f"(vram {hw['vc']:g}GB@{hw['vb']:g} | ram {hw['rc']:g}GB@{hw['rb']:g} | "
1792
+ f"disk {hw['db']:g} GB/s). Pass --machine/flags to estimate a different box.")
1793
+ apply_calibration_overrides(hw, args)
1794
+ vc = hw.get("vc", getattr(args, "vram", None)); vb = hw.get("vb", getattr(args, "vram_bw", None))
1795
+ rc = hw.get("rc", getattr(args, "ram", None)); rb = hw.get("rb", getattr(args, "ram_bw", None))
1796
+ db = hw.get("db", getattr(args, "disk_bw", None))
1797
+ geta = hw.get("geta", 0.45); gl = hw.get("gl", None)
1798
+ if getattr(args, "vram", None) is not None: vc = args.vram
1799
+ if getattr(args, "vram_bw", None) is not None: vb = args.vram_bw
1800
+ if getattr(args, "ram", None) is not None: rc = args.ram
1801
+ if getattr(args, "ram_bw", None) is not None: rb = args.ram_bw
1802
+ if getattr(args, "disk_bw", None) is not None: db = args.disk_bw
1803
+ vc = agg_cap(vc) or 0; vb = agg_bw(vb, 0.85) or 0
1804
+ rc = rc or 16; rb = rb or 40
1805
+ db = agg_bw(db, 0.75) or 0.5
1806
+ return vc, vb, rc, rb, db, geta, gl, hw
1807
+
1808
+
1769
1809
  def run(args):
1770
1810
  from . import spec as specmod
1771
1811
  specmod.apply(args)
@@ -1777,28 +1817,7 @@ def run(args):
1777
1817
  a = args.active or m.get("a") or t
1778
1818
  ne = args.always_active or m.get("ne") or (a if a >= t * 0.9 else a * 0.35)
1779
1819
  moe = m.get("moe", a < t * 0.9)
1780
- hw = dict(MACHINES[args.machine]) if args.machine in MACHINES else {}
1781
- if not hw and all(getattr(args, k, None) is None for k in ("vram", "vram_bw", "ram", "ram_bw", "disk_bw")):
1782
- from . import detect as detmod
1783
- auto, _ = detmod.detect()
1784
- hw = dict(vc=auto["vram"], vb=auto["vram_bw"], rc=auto["ram"], rb=auto["ram_bw"],
1785
- db=auto["disk_bw"], geta=auto.get("geta", 0.45), gl=auto.get("gl"),
1786
- hint="THIS machine [auto-detected - run `quantprobe hw` for details]")
1787
- print("[quantprobe] no hardware flags: auto-detected this machine "
1788
- f"(vram {hw['vc']:g}GB@{hw['vb']:g} | ram {hw['rc']:g}GB@{hw['rb']:g} | disk {hw['db']:g} GB/s). "
1789
- "Pass --machine/flags to estimate a different box.")
1790
- apply_calibration_overrides(hw, args)
1791
- vc = hw.get("vc", args.vram); vb = hw.get("vb", args.vram_bw)
1792
- rc = hw.get("rc", args.ram); rb = hw.get("rb", args.ram_bw)
1793
- db = hw.get("db", args.disk_bw); geta = hw.get("geta", 0.45); gl = hw.get("gl", None)
1794
- if args.vram is not None: vc = args.vram
1795
- if args.vram_bw is not None: vb = args.vram_bw
1796
- if args.ram is not None: rc = args.ram
1797
- if args.ram_bw is not None: rb = args.ram_bw
1798
- if args.disk_bw is not None: db = args.disk_bw
1799
- vc = agg_cap(vc) or 0; vb = agg_bw(vb, 0.85) or 0
1800
- rc = rc or 16; rb = rb or 40
1801
- db = agg_bw(db, 0.75) or 0.5
1820
+ vc, vb, rc, rb, db, geta, gl, hw = resolve_hw(args)
1802
1821
  ctx = getattr(args, "ctx", 0) or 0
1803
1822
  kvp = (args.kv_per_pos * 1024 if getattr(args, "kv_per_pos", None)
1804
1823
  else m.get("kvp", DEFAULT_KVP))