ollama2cpp 0.1.1__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.
@@ -0,0 +1,350 @@
1
+ """The ``optimize`` command: pre-flight checks, one isolated optimizer run per model and the before/after report.
2
+
3
+ No CLI parsing lives here (see ``__main__``); :func:`run_optimize` returns the process exit code.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import time
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from rich.text import Text
15
+
16
+ from ollama2cpp import constants, hardware, llamacpp, ollama, optimizer, selector, server, ui, workflow
17
+ from ollama2cpp.commands import find_server, load_config, models_root, pick_device, server_endpoint
18
+ from ollama2cpp.config import Config, Profile
19
+ from ollama2cpp.constants import DEFAULT_CTX, EXIT_INTERRUPTED
20
+ from ollama2cpp.hardware import Device, HostInfo
21
+ from ollama2cpp.optimizer import BenchResult, SeedPlan
22
+ from ollama2cpp.selector import Candidate
23
+ from ollama2cpp.workflow import WorkflowError
24
+
25
+ __all__ = ["OptimizeOptions", "run_optimize"]
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ DEFAULT_TIME_LIMIT = 300.0
30
+ UNLOAD_WAIT_S = 15.0 # how long to wait for Ollama's VRAM to come back after asking it to unload
31
+ UNLOAD_POLL_S = 1.0
32
+ HOLD_TOLERANCE_MIB = 1024 # other processes may hold this much VRAM (a desktop session) without stopping a benchmark
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class OptimizeOptions:
37
+ """Everything the ``optimize`` command accepts.
38
+
39
+ Attributes:
40
+ model: Model name (default: the saved default model, else an automatic choice).
41
+ model_from_env: ``model`` came from ``$OLLAMA_MODEL``; when it is not installed the saved default (or an
42
+ automatic choice) is used with a warning.
43
+ quick: Save the heuristic seed without benchmarking.
44
+ all_models: Optimize every chat model.
45
+ time_limit: Sweep budget per model, in seconds.
46
+ ctx: Context size to optimize for (default 8192).
47
+ allow_kv_quant: Also try a ``q8_0`` KV cache.
48
+ unload_ollama: Ask Ollama to unload its models when they hold the VRAM the model needs.
49
+ stop_server: Stop our own running server first (it holds VRAM).
50
+ assume_yes: Answer yes to questions (first-run installation of llama.cpp).
51
+ """
52
+
53
+ model: str | None = None
54
+ model_from_env: bool = False
55
+ quick: bool = False
56
+ all_models: bool = False
57
+ time_limit: float = DEFAULT_TIME_LIMIT
58
+ ctx: int | None = None
59
+ allow_kv_quant: bool = False
60
+ unload_ollama: bool = False
61
+ stop_server: bool = False
62
+ assume_yes: bool = False
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class _Outcome:
67
+ """The result of optimizing one model: a profile and its seed, or an error."""
68
+
69
+ name: str
70
+ profile: Profile | None = None
71
+ seed: SeedPlan | None = None
72
+ error: str = ""
73
+
74
+
75
+ # --- pre-flight ----------------------------------------------------------------------------------------------------
76
+
77
+
78
+ def _prepare(cfg: Config, opts: OptimizeOptions) -> Path:
79
+ """Check the tools; record discovered paths in ``cfg`` (saved with the profile). Stops and refuses nothing."""
80
+ binary = find_server(cfg)
81
+ if binary is None:
82
+ raise WorkflowError("llama-server was not found; run `ollama2cpp serve` or `ollama2cpp update` first.")
83
+ cfg.llama_server = str(binary)
84
+ cfg.ollama_path = str(models_root(cfg))
85
+ if opts.quick:
86
+ return binary
87
+ bench = llamacpp.find_binary("llama-bench", cfg.llama_bench)
88
+ if bench is None:
89
+ raise WorkflowError(
90
+ "llama-bench was not found. Run `ollama2cpp update` (or `ollama2cpp doctor`), "
91
+ "or use --quick to save the heuristic settings without benchmarking."
92
+ )
93
+ cfg.llama_bench = str(bench)
94
+ return binary
95
+
96
+
97
+ def _release_server(cfg: Config, opts: OptimizeOptions) -> None:
98
+ """Refuse (or, with ``--stop-server``, stop) our own running server: it holds the VRAM a benchmark needs.
99
+
100
+ Runs after the targets are resolved, so a typo never stops the user's server. The server is looked up at the
101
+ address in its pid record (it may have been started with another ``--port``).
102
+ """
103
+ if opts.quick:
104
+ return
105
+ host, port = server_endpoint(cfg)
106
+ state, alias = server.describe_running(host, port, constants.home())
107
+ if state != "ours":
108
+ return
109
+ if not opts.stop_server:
110
+ raise WorkflowError(
111
+ f"ollama2cpp is serving {alias or 'a model'} and that holds VRAM. "
112
+ "Run `ollama2cpp stop` first, or pass --stop-server."
113
+ )
114
+ ui.show_notice("info", "Stopping the running ollama2cpp server.")
115
+ server.stop(constants.home())
116
+
117
+
118
+ def _targets(cfg: Config, opts: OptimizeOptions, ctx: int) -> list[Candidate]:
119
+ """Resolve the models to optimize (chat models only)."""
120
+ if opts.all_models:
121
+ if opts.model:
122
+ raise WorkflowError("Give either a MODEL or --all, not both.")
123
+ cands = [c for c in selector.classify_all(ollama.list_models(models_root(cfg)), ctx) if c.kind == "chat"]
124
+ if not cands:
125
+ raise WorkflowError("No chat models are installed; pull one first, e.g. `ollama pull llama3.2`.")
126
+ return cands
127
+ model = workflow.select_model(cfg, workflow.ServeOptions(model=opts.model, model_from_env=opts.model_from_env))
128
+ cand = selector.classify(model, ctx)
129
+ if cand.kind != "chat":
130
+ why = f": {cand.reason}" if cand.reason else ""
131
+ raise WorkflowError(f"{model.name} is not a chat model ({cand.kind}{why}); only chat models can be optimized.")
132
+ return [cand]
133
+
134
+
135
+ def _wait_for_vram(cand: Candidate, cfg: Config, binary: Path, device: Device | None, wait: float) -> Device | None:
136
+ """Poll the devices until the model fits in free VRAM or ``wait`` seconds pass; return the latest device."""
137
+ deadline = time.monotonic() + wait
138
+ while True:
139
+ fresh = hardware.best_device(hardware.detect_devices(binary), cfg.device) or device
140
+ if optimizer.vram_preflight(cand.need_mib, fresh) <= 0 or time.monotonic() >= deadline:
141
+ return fresh
142
+ time.sleep(UNLOAD_POLL_S)
143
+
144
+
145
+ def _clear_vram(
146
+ cand: Candidate, cfg: Config, binary: Path, device: Device | None, opts: OptimizeOptions
147
+ ) -> Device | None:
148
+ """Decide whether the benchmark can run with the VRAM that is free now; unload Ollama first when asked.
149
+
150
+ The seed budgets the free memory (see ``optimizer.optimize_seed``), so a model that does not fully fit is
151
+ benchmarked with a partial offload. The run is refused only when other processes hold more than
152
+ ``HOLD_TOLERANCE_MIB`` and the model needs memory that is not free.
153
+
154
+ Raises:
155
+ WorkflowError: When the VRAM held by other processes leaves the model short.
156
+ """
157
+ if device is None:
158
+ return device
159
+ name = cand.model.name
160
+ short = optimizer.vram_preflight(cand.need_mib, device)
161
+ if short > 0 and opts.unload_ollama:
162
+ problem = f"{name} needs about {cand.need_mib} MiB of VRAM but only {device.free_mib} MiB are free"
163
+ ui.show_notice("info", f"{problem} (short by {short} MiB); asking Ollama to unload its models.")
164
+ unloaded = optimizer.unload_ollama()
165
+ if not unloaded:
166
+ ui.show_notice("warn", "Ollama did not confirm the unload (is it running?).")
167
+ device = _wait_for_vram(cand, cfg, binary, device, UNLOAD_WAIT_S if unloaded else 0.0) or device
168
+ short = optimizer.vram_preflight(cand.need_mib, device)
169
+ after = " after unloading Ollama"
170
+ else:
171
+ after = ""
172
+ if cand.need_mib > device.total_mib:
173
+ ui.show_notice(
174
+ "info",
175
+ f"{name} does not fit this GPU entirely ({cand.need_mib} MiB needed, {device.total_mib} MiB total); "
176
+ "layers will be offloaded partially.",
177
+ )
178
+ if short <= 0:
179
+ return device
180
+ held = device.total_mib - device.free_mib
181
+ if held <= HOLD_TOLERANCE_MIB:
182
+ ui.show_notice(
183
+ "info", f"Free VRAM is {device.free_mib} MiB of {device.total_mib} MiB; optimizing for what is free."
184
+ )
185
+ return device
186
+ if opts.unload_ollama:
187
+ raise WorkflowError(
188
+ f"{name} is still short by {short} MiB of VRAM{after}: {held} MiB of VRAM is in use by other processes; "
189
+ "close the other GPU users."
190
+ )
191
+ raise WorkflowError(
192
+ f"{name} needs about {cand.need_mib} MiB of VRAM but only {device.free_mib} MiB are free "
193
+ f"(short by {short} MiB): {held} MiB of VRAM is in use by other processes. "
194
+ "Free it (for example `ollama stop MODEL` for Ollama), or pass --unload-ollama."
195
+ )
196
+
197
+
198
+ # --- running -------------------------------------------------------------------------------------------------------
199
+
200
+
201
+ def _speed(result: BenchResult) -> str:
202
+ return f"{result.tg_tps:.1f} t/s" if result.tg_tps is not None else "failed"
203
+
204
+
205
+ def _optimize(cand: Candidate, cfg: Config, host: HostInfo, device: Device | None, opts: OptimizeOptions) -> Profile:
206
+ """Run the optimizer for one model, with a progress display while it benchmarks."""
207
+ name = cand.model.name
208
+
209
+ def run(on_progress: Callable[[BenchResult], None] | None) -> Profile:
210
+ return optimizer.optimize_model(
211
+ cand.model,
212
+ cfg,
213
+ host,
214
+ device,
215
+ ctx=opts.ctx or DEFAULT_CTX,
216
+ quick=opts.quick,
217
+ time_limit=opts.time_limit,
218
+ allow_kv_quant=opts.allow_kv_quant,
219
+ on_progress=on_progress,
220
+ )
221
+
222
+ if opts.quick:
223
+ return run(None)
224
+ with ui.steps_progress() as bar:
225
+ task = bar.add_task(name, total=None)
226
+
227
+ def step(result: BenchResult) -> None:
228
+ bar.update(task, advance=1, description=f"{name} (last: {_speed(result)})")
229
+
230
+ return run(step)
231
+
232
+
233
+ def _optimize_one(
234
+ cand: Candidate, cfg: Config, binary: Path, host: HostInfo, device: Device | None, opts: OptimizeOptions
235
+ ) -> _Outcome:
236
+ """Optimize one model; any failure becomes an error outcome so the other models still run."""
237
+ name = cand.model.name
238
+ try:
239
+ if not opts.quick:
240
+ device = _clear_vram(cand, cfg, binary, device, opts)
241
+ profile = _optimize(cand, cfg, host, device, opts)
242
+ seed = optimizer.optimize_seed(cand.gguf, host, device, opts.ctx or DEFAULT_CTX) if cand.gguf else None
243
+ except Exception as exc:
244
+ logger.warning("Optimizing %s failed: %s", name, exc)
245
+ logger.debug("Optimizing %s failed", name, exc_info=True)
246
+ ui.show_notice("error", f"{name}: {exc}")
247
+ return _Outcome(name, error=str(exc))
248
+ return _Outcome(name, profile, seed)
249
+
250
+
251
+ # --- report --------------------------------------------------------------------------------------------------------
252
+
253
+
254
+ def _rate(value: float | None) -> str:
255
+ return f"{value:.1f}" if value is not None else "-"
256
+
257
+
258
+ def _seed_measurement(profile: Profile) -> tuple[float | None, float | None]:
259
+ """Return the tg and pp speeds of the seed, which the sweep measures first (``(None, None)`` when it failed)."""
260
+ first = profile.bench[0] if profile.bench else {}
261
+ if first.get("error") or first.get("tg_tps") is None:
262
+ return None, None
263
+ return first.get("tg_tps"), first.get("pp_tps")
264
+
265
+
266
+ def _show_outcome(outcome: _Outcome, opts: OptimizeOptions) -> None:
267
+ """Print the before/after table of one successful run."""
268
+ profile, seed = outcome.profile, outcome.seed
269
+ if profile is None:
270
+ return
271
+ seed_args = " ".join(optimizer.seed_to_args(seed)) if seed else "-"
272
+ seed_ctx = str(seed.ctx) if seed else "-"
273
+ rows: list[list[str | Text]]
274
+ if profile.measured:
275
+ seed_tg, seed_pp = _seed_measurement(profile)
276
+ label = "seed (measured)" if seed_tg is not None else "seed (unmeasured)"
277
+ rows = [
278
+ [label, _rate(seed_tg), _rate(seed_pp), seed_ctx, seed_args],
279
+ ["optimized", _rate(profile.tg_tps), _rate(profile.pp_tps), str(profile.ctx), " ".join(profile.args)],
280
+ ]
281
+ if seed_tg and profile.tg_tps:
282
+ gain = (profile.tg_tps / seed_tg - 1) * 100
283
+ ui.show_notice("ok", f"{outcome.name}: generation speed {gain:+.0f}% vs the heuristic seed.")
284
+ else:
285
+ rows = [["seed (unmeasured)", "-", "-", str(profile.ctx), " ".join(profile.args)]]
286
+ if opts.quick:
287
+ ui.show_notice("info", f"{outcome.name}: quick mode saved the heuristic settings (not measured).")
288
+ else:
289
+ ui.show_notice("warn", f"{outcome.name}: benchmark failed - heuristic settings saved (unmeasured).")
290
+ ui.show_table(f"{outcome.name}", ["Settings", "tg t/s", "pp t/s", "ctx", "args"], rows)
291
+ if not profile.validated:
292
+ ui.show_notice(
293
+ "warn",
294
+ f"{outcome.name}: interrupted before validation - the best result so far was saved, not validated "
295
+ "against a real server. Re-run `ollama2cpp optimize` to finish it.",
296
+ )
297
+
298
+
299
+ def _show_summary(outcomes: list[_Outcome]) -> None:
300
+ rows = []
301
+ for o in outcomes:
302
+ if o.profile is None:
303
+ rows.append([o.name, ui.status_text("fail"), "-", o.error])
304
+ elif o.profile.measured:
305
+ rows.append([o.name, ui.status_text("ok"), _rate(o.profile.tg_tps), f"ctx {o.profile.ctx}"])
306
+ else:
307
+ rows.append([o.name, ui.status_text("warn"), "-", "heuristic settings only (unmeasured)"])
308
+ ui.show_table("Optimization summary", ["Model", "Result", "tg t/s", "Detail"], rows)
309
+
310
+
311
+ def run_optimize(opts: OptimizeOptions) -> int:
312
+ """Optimize one model (or every chat model) and save the profiles.
313
+
314
+ Ctrl-C keeps the results so far: the interrupted model keeps its best measurement (saved unvalidated) and the
315
+ remaining models of ``--all`` are not touched.
316
+
317
+ Args:
318
+ opts: The command options.
319
+
320
+ Returns:
321
+ int: 0 when at least one model got a profile, 130 when interrupted before any was saved, else 1.
322
+ """
323
+ cfg = load_config(assume_yes=opts.assume_yes)
324
+ binary = _prepare(cfg, opts)
325
+ ctx = opts.ctx or DEFAULT_CTX
326
+ targets = _targets(cfg, opts, ctx) # validated before anything is stopped
327
+ _release_server(cfg, opts)
328
+ host, device = workflow.probe(binary, cfg.device)
329
+ outcomes: list[_Outcome] = []
330
+ interrupted = False
331
+ for index, cand in enumerate(targets):
332
+ if index and not opts.quick:
333
+ device = pick_device(cfg, binary) or device # free VRAM changes between models
334
+ try:
335
+ outcome = _optimize_one(cand, cfg, binary, host, device, opts)
336
+ except KeyboardInterrupt:
337
+ interrupted = True
338
+ break
339
+ _show_outcome(outcome, opts)
340
+ outcomes.append(outcome)
341
+ if outcome.profile is not None and not outcome.profile.validated:
342
+ interrupted = True
343
+ break
344
+ if interrupted:
345
+ ui.show_notice("warn", "Interrupted - kept the results so far.")
346
+ if len(outcomes) > 1:
347
+ _show_summary(outcomes)
348
+ if any(o.profile is not None for o in outcomes):
349
+ return 0
350
+ return EXIT_INTERRUPTED if interrupted else 1