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,873 @@
1
+ """Tune llama-server launch settings for maximum generation speed.
2
+
3
+ Two halves: a pure, deterministic heuristic seed (no I/O), then a ``llama-bench`` coordinate-descent sweep around it,
4
+ a real ``llama-server`` validation of the winner, and persistence of the resulting profile.
5
+
6
+ Flag spellings verified against ``llama-server --help`` and ``llama-bench --help`` (build 12721, Windows): ``-ngl``,
7
+ ``-fa on|off|auto`` (takes a value, not a bare switch), ``-t``, ``-b``, ``-ub``, ``-ctk``/``-ctv``, and ``-dev <id>``
8
+ (bench only; the server uses ``--device``). ``llama-bench`` sweeps comma-separated value lists, but this module always
9
+ passes a single value per flag so every run measures exactly one candidate.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import http.client
15
+ import json
16
+ import logging
17
+ import math
18
+ import os
19
+ import re
20
+ import socket
21
+ import time
22
+ import urllib.error
23
+ import urllib.request
24
+ from collections.abc import Callable, Sequence
25
+ from dataclasses import dataclass, replace
26
+ from datetime import UTC, datetime
27
+ from pathlib import Path
28
+ from typing import Any
29
+ from urllib.parse import urlsplit
30
+
31
+ from ollama2cpp import config, constants, hardware, llamacpp, proc, server as server_runtime
32
+ from ollama2cpp.config import Config, Profile, profile_key
33
+ from ollama2cpp.constants import DEFAULT_CTX
34
+ from ollama2cpp.gguf import GgufInfo, kv_cache_bytes, read_gguf
35
+ from ollama2cpp.hardware import Device, HostInfo
36
+ from ollama2cpp.llamacpp import LlamaCppError, ServeSettings
37
+ from ollama2cpp.ollama import OllamaModel
38
+ from ollama2cpp.selector import HEADROOM_FACTOR, OVERHEAD_MIB
39
+
40
+ log = logging.getLogger(__name__)
41
+
42
+ MIN_CTX = 2048 # the seed never shrinks the context below this
43
+ SEED_BATCH = 2048
44
+ SEED_UBATCH = 512
45
+ SEED_CACHE_TYPE = "f16"
46
+ _MIB = 1024 * 1024
47
+
48
+ BENCH_PROMPT_TOKENS = 512
49
+ BENCH_GEN_TOKENS = 128
50
+ BENCH_TIMEOUT = 300.0 # per candidate (the seed always gets all of it)
51
+ MIN_BENCH_TIMEOUT = 60.0
52
+ MAX_ERROR_CHARS = 200
53
+ UBATCH_VALUES = (256, 512, 1024, 2048)
54
+ NGL_DELTAS = (2, -2, 4, -4)
55
+ KV_QUANT_TYPE = "q8_0"
56
+ TIE_TOLERANCE = 0.02 # speeds within this fraction are benchmark noise: only a clear gain replaces the incumbent
57
+ VALIDATE_DIRNAME = "validate" # scratch storage so validation never touches the user's own server record
58
+ VALIDATE_PROMPT = "Hello"
59
+ VALIDATE_TOKENS = 8
60
+ COMPLETION_TIMEOUT = 120.0
61
+ OLLAMA_DEFAULT_PORT = 11434
62
+ OLLAMA_PS_TIMEOUT = 5.0
63
+ HTTP_OK = 200
64
+ _OOM_MARKERS = ("out of memory", "failed to allocate", "outofdevicememory", "outofhostmemory")
65
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class SeedPlan:
70
+ """Starting launch settings for the sweep.
71
+
72
+ Attributes:
73
+ ngl: GPU layers (``block_count + 1`` is a full offload including the output layer; 0 is CPU-only).
74
+ ctx: Context length in tokens.
75
+ flash_attn: Whether to enable flash attention.
76
+ threads: CPU threads for generation.
77
+ batch: Logical batch size.
78
+ ubatch: Physical batch size.
79
+ cache_type: KV cache element type, used for both K and V.
80
+ """
81
+
82
+ ngl: int
83
+ ctx: int
84
+ flash_attn: bool
85
+ threads: int
86
+ batch: int
87
+ ubatch: int
88
+ cache_type: str
89
+
90
+
91
+ def _need_mib(weights: float, kv: float) -> int:
92
+ """Estimate MiB for ``weights`` + ``kv`` bytes, using the selector's headroom and overhead model."""
93
+ return math.ceil((weights + kv) * HEADROOM_FACTOR / _MIB + OVERHEAD_MIB)
94
+
95
+
96
+ def _fit_ctx(info: GgufInfo, budget_mib: int, ctx: int) -> tuple[int, bool]:
97
+ """Halve ``ctx`` (floor ``MIN_CTX``) until the whole model fits ``budget_mib``.
98
+
99
+ Args:
100
+ info: Parsed GGUF facts.
101
+ budget_mib: Memory budget in MiB.
102
+ ctx: Requested context length.
103
+
104
+ Returns:
105
+ tuple[int, bool]: The chosen context and whether the whole model fits at it.
106
+ """
107
+ while _need_mib(info.file_size, kv_cache_bytes(info, ctx)) > budget_mib:
108
+ if ctx <= MIN_CTX:
109
+ return ctx, False
110
+ ctx = max(MIN_CTX, ctx // 2)
111
+ return ctx, True
112
+
113
+
114
+ def _largest_layer_count(info: GgufInfo, budget_mib: int, ctx: int) -> int:
115
+ """Return the largest layer count (``0..block_count``) whose weights and KV shares fit ``budget_mib``."""
116
+ kv = kv_cache_bytes(info, ctx)
117
+ blocks = max(info.block_count, 1)
118
+ total_layers = info.block_count + 1
119
+ best = 0
120
+ for layers in range(info.block_count + 1):
121
+ weights = info.file_size * layers / total_layers
122
+ if _need_mib(weights, kv * layers / blocks) > budget_mib:
123
+ break
124
+ best = layers
125
+ return best
126
+
127
+
128
+ def heuristic_seed(info: GgufInfo, host: HostInfo, device: Device | None, ctx: int = DEFAULT_CTX) -> SeedPlan:
129
+ """Pick a starting plan from the model and hardware facts alone (pure, no I/O).
130
+
131
+ With a device the budget is its *total* VRAM. The context is halved (floor ``MIN_CTX``) before any layer is left on
132
+ the CPU; only when the whole model still does not fit at the floor is the layer count reduced. Without a device
133
+ the plan is CPU-only and the context is reduced only to fit total RAM.
134
+
135
+ Args:
136
+ info: Parsed GGUF facts (``info.file_size`` is the weight size).
137
+ host: Host snapshot (physical core count and RAM).
138
+ device: Chosen GPU, or None for a CPU-only run.
139
+ ctx: Requested context length in tokens.
140
+
141
+ Returns:
142
+ SeedPlan: The starting settings.
143
+ """
144
+ threads = max(1, host.physical_cores)
145
+ if device is None:
146
+ fitted, _ = _fit_ctx(info, host.ram_total_mib, ctx)
147
+ return SeedPlan(0, fitted, False, threads, SEED_BATCH, SEED_UBATCH, SEED_CACHE_TYPE)
148
+ fitted, fits = _fit_ctx(info, device.total_mib, ctx)
149
+ ngl = info.block_count + 1 if fits else _largest_layer_count(info, device.total_mib, fitted)
150
+ log.debug("Seed for %s: ngl=%d ctx=%d (requested ctx=%d)", device.id, ngl, fitted, ctx)
151
+ return SeedPlan(ngl, fitted, True, threads, SEED_BATCH, SEED_UBATCH, SEED_CACHE_TYPE)
152
+
153
+
154
+ def optimize_seed(info: GgufInfo, host: HostInfo, device: Device | None, ctx: int = DEFAULT_CTX) -> SeedPlan:
155
+ """Pick the starting plan of an ``optimize`` run: like :func:`heuristic_seed`, but budgeting the FREE memory.
156
+
157
+ ``serve`` without a profile seeds from the card's *total* VRAM (it assumes nothing else needs the GPU), while a
158
+ benchmark runs now with whatever is free: a model that does not fully fit in the free memory starts as a partial
159
+ offload (so the ``-ngl`` dimension is swept) instead of running out of memory on every candidate.
160
+
161
+ Args:
162
+ info: Parsed GGUF facts.
163
+ host: Host snapshot.
164
+ device: Chosen GPU, or None for a CPU-only run.
165
+ ctx: Requested context length in tokens.
166
+
167
+ Returns:
168
+ SeedPlan: The starting settings for the sweep.
169
+ """
170
+ if device is not None:
171
+ device = replace(device, total_mib=min(device.total_mib, available_mib(device)))
172
+ return heuristic_seed(info, host, device, ctx)
173
+
174
+
175
+ def seed_to_args(plan: SeedPlan) -> list[str]:
176
+ """Render ``plan`` as ``llama-server`` arguments (the context is passed separately by the caller).
177
+
178
+ Args:
179
+ plan: The launch settings.
180
+
181
+ Returns:
182
+ list[str]: Argument vector fragment using the spellings verified against ``llama-server --help``.
183
+ """
184
+ return [
185
+ "-ngl",
186
+ str(plan.ngl),
187
+ "-fa",
188
+ "on" if plan.flash_attn else "off",
189
+ "-t",
190
+ str(plan.threads),
191
+ "-b",
192
+ str(plan.batch),
193
+ "-ub",
194
+ str(plan.ubatch),
195
+ "-ctk",
196
+ plan.cache_type,
197
+ "-ctv",
198
+ plan.cache_type,
199
+ ]
200
+
201
+
202
+ # --- benchmark -----------------------------------------------------------------------------------------------------
203
+
204
+
205
+ @dataclass(frozen=True)
206
+ class BenchResult:
207
+ """One measured (or failed) benchmark candidate.
208
+
209
+ Attributes:
210
+ args: The ``llama-bench`` arguments that were measured.
211
+ tg_tps: Generation speed in tokens/s, or None when the run failed.
212
+ pp_tps: Prompt-processing speed in tokens/s, or None when unavailable.
213
+ error: Short sanitised failure reason; empty on success.
214
+ """
215
+
216
+ args: tuple[str, ...]
217
+ tg_tps: float | None
218
+ pp_tps: float | None
219
+ error: str = ""
220
+
221
+
222
+ def plan_to_bench_args(plan: SeedPlan, device: str | None = None) -> list[str]:
223
+ """Render ``plan`` as ``llama-bench`` arguments (same spellings as ``llama-server``; ``-dev`` selects a GPU).
224
+
225
+ Args:
226
+ plan: The launch settings.
227
+ device: Device id (``Vulkan0``...) to pin the run to, or None for llama.cpp's default.
228
+
229
+ Returns:
230
+ list[str]: Argument vector fragment.
231
+ """
232
+ args = seed_to_args(plan)
233
+ return [*args, "-dev", device] if device else args
234
+
235
+
236
+ def _decode_rows(text: str) -> list[Any]:
237
+ """Decode ``llama-bench -o json`` output (an array, a single object, or JSON lines) without raising.
238
+
239
+ Args:
240
+ text: Raw stdout, possibly with noise around the JSON.
241
+
242
+ Returns:
243
+ list[Any]: The decoded rows (not yet validated).
244
+ """
245
+ text = text.strip()
246
+ start, end = text.find("["), text.rfind("]")
247
+ for attempt in (text, text[start : end + 1] if 0 <= start < end else ""):
248
+ try:
249
+ data = json.loads(attempt)
250
+ except ValueError:
251
+ continue
252
+ return data if isinstance(data, list) else [data]
253
+ rows: list[Any] = []
254
+ for line in text.splitlines():
255
+ try:
256
+ rows.append(json.loads(line))
257
+ except ValueError:
258
+ continue
259
+ return rows
260
+
261
+
262
+ def _number(value: object) -> float | None:
263
+ """Return ``value`` as a finite float, or None for non-numbers, booleans and NaN/inf."""
264
+ if isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value):
265
+ return None
266
+ return float(value)
267
+
268
+
269
+ def parse_bench_json(text: str) -> tuple[float | None, float | None]:
270
+ """Extract prompt-processing and generation speed from ``llama-bench -o json`` output.
271
+
272
+ Prompt rows have ``n_prompt > 0`` and ``n_gen == 0``; generation rows have ``n_gen > 0`` and ``n_prompt == 0``;
273
+ the speed is ``avg_ts``. Total function: anything unusable yields ``None`` for the missing figure.
274
+
275
+ Args:
276
+ text: Raw stdout of ``llama-bench``.
277
+
278
+ Returns:
279
+ tuple[float | None, float | None]: ``(pp_tps, tg_tps)``.
280
+ """
281
+ pp: float | None = None
282
+ tg: float | None = None
283
+ for row in _decode_rows(text):
284
+ if not isinstance(row, dict):
285
+ continue
286
+ speed, n_prompt, n_gen = _number(row.get("avg_ts")), _number(row.get("n_prompt")), _number(row.get("n_gen"))
287
+ if speed is None or speed <= 0 or n_prompt is None or n_gen is None:
288
+ continue
289
+ if n_prompt > 0 and n_gen == 0 and pp is None:
290
+ pp = speed
291
+ elif n_gen > 0 and n_prompt == 0 and tg is None:
292
+ tg = speed
293
+ return pp, tg
294
+
295
+
296
+ def _sanitize(text: str) -> str:
297
+ """Make ``text`` safe for one-line display: no escape codes or control characters, bounded length."""
298
+ text = _ANSI_RE.sub("", text)
299
+ text = "".join(ch if ch.isprintable() else " " for ch in text)
300
+ return " ".join(text.split())[:MAX_ERROR_CHARS]
301
+
302
+
303
+ def _bench_error(result: proc.ProcResult, timeout: float) -> str:
304
+ """Explain why a ``llama-bench`` run produced no generation figure.
305
+
306
+ Args:
307
+ result: The finished (or failed) process.
308
+ timeout: The timeout that was applied, in seconds.
309
+
310
+ Returns:
311
+ str: A short, sanitised reason.
312
+ """
313
+ if result.returncode == proc.RC_NOT_FOUND:
314
+ return "llama-bench not found"
315
+ if result.returncode == proc.RC_TIMEOUT:
316
+ return f"timed out after {timeout:g}s"
317
+ output = f"{result.stderr}\n{result.stdout}"
318
+ if any(marker in output.lower() for marker in _OOM_MARKERS):
319
+ return "out of memory"
320
+ if result.returncode != 0:
321
+ lines = [line for line in output.splitlines() if line.strip()]
322
+ return _sanitize(f"exit code {result.returncode}: {lines[-1] if lines else ''}")
323
+ return "no generation result in llama-bench output"
324
+
325
+
326
+ def run_bench(bench: Path, model: Path, args: Sequence[str], *, timeout: float, repetitions: int = 3) -> BenchResult:
327
+ """Run ``llama-bench`` once for one candidate; never raises.
328
+
329
+ Args:
330
+ bench: The ``llama-bench`` executable.
331
+ model: GGUF file to measure.
332
+ args: Candidate arguments (see ``plan_to_bench_args``).
333
+ timeout: Seconds before the run is killed.
334
+ repetitions: Repetitions per test (``-r``).
335
+
336
+ Returns:
337
+ BenchResult: The measurement, or ``error`` set (out of memory, timeout, bad exit, unparseable output).
338
+ """
339
+ argv = [str(bench), "-m", str(model), "-o", "json", "-r", str(repetitions)]
340
+ argv += ["-p", str(BENCH_PROMPT_TOKENS), "-n", str(BENCH_GEN_TOKENS), *args]
341
+ result = proc.run(argv, timeout=timeout)
342
+ pp, tg = parse_bench_json(result.stdout) if result.returncode == 0 else (None, None)
343
+ if tg is not None:
344
+ return BenchResult(tuple(args), tg, pp)
345
+ return BenchResult(tuple(args), None, pp, _bench_error(result, timeout))
346
+
347
+
348
+ # --- sweep ---------------------------------------------------------------------------------------------------------
349
+
350
+
351
+ def _thread_values(host: HostInfo) -> list[int]:
352
+ """Thread counts to try: ``cores - 2``, ``cores``, ``min(logical, cores + 2)``; deduplicated, at least 1."""
353
+ cores = max(1, host.physical_cores)
354
+ wanted = (max(1, cores - 2), cores, max(1, min(host.logical_cores, cores + 2)))
355
+ return list(dict.fromkeys(wanted))
356
+
357
+
358
+ def _ngl_values(seed_ngl: int, block_count: int) -> list[int]:
359
+ """Layer counts around a partial offload: ``seed +-2`` and ``+-4``, clamped to ``0..block_count + 1``."""
360
+ values = [min(block_count + 1, max(0, seed_ngl + delta)) for delta in NGL_DELTAS]
361
+ return list(dict.fromkeys(v for v in values if v != seed_ngl))
362
+
363
+
364
+ def candidate_steps(
365
+ seed: SeedPlan, host: HostInfo, *, allow_kv_quant: bool, block_count: int | None = None
366
+ ) -> list[tuple[str, list[SeedPlan]]]:
367
+ """List the coordinate-descent dimensions in sweep order.
368
+
369
+ Each step is ``(field_name, candidates)`` where every candidate is ``seed`` with only that field changed; the sweep
370
+ re-applies the field to the best plan found so far.
371
+
372
+ Args:
373
+ seed: The starting plan.
374
+ host: Host snapshot (core counts bound the thread candidates).
375
+ allow_kv_quant: Include the ``q8_0`` KV-cache candidate (opt-in because it affects quality).
376
+ block_count: Layers in the model; the ``ngl`` step needs it and is skipped when None.
377
+
378
+ Returns:
379
+ list[tuple[str, list[SeedPlan]]]: ``flash_attn``, ``ubatch``, ``threads``, ``ngl`` (only when the seed is a
380
+ partial offload), ``cache_type`` (only when ``allow_kv_quant``), in that order.
381
+ """
382
+ steps = [
383
+ ("flash_attn", [replace(seed, flash_attn=v) for v in (False, True)]),
384
+ ("ubatch", [replace(seed, ubatch=v) for v in UBATCH_VALUES]),
385
+ ("threads", [replace(seed, threads=v) for v in _thread_values(host)]),
386
+ ]
387
+ if block_count is not None and seed.ngl < block_count + 1:
388
+ steps.append(("ngl", [replace(seed, ngl=v) for v in _ngl_values(seed.ngl, block_count)]))
389
+ if allow_kv_quant:
390
+ steps.append(("cache_type", [replace(seed, cache_type=KV_QUANT_TYPE)]))
391
+ return steps
392
+
393
+
394
+ def _beats(new: BenchResult, best: BenchResult | None) -> bool:
395
+ """Tell whether ``new`` replaces ``best``, treating differences within ``TIE_TOLERANCE`` as noise.
396
+
397
+ ``new`` wins with a generation speed more than ``TIE_TOLERANCE`` above ``best``. When the two are within that
398
+ tolerance on generation speed (either way), it wins only with a prompt speed more than ``TIE_TOLERANCE`` above
399
+ ``best``'s. Otherwise the incumbent stays, so batch/thread steps are not decided by measurement noise.
400
+ """
401
+ if new.tg_tps is None:
402
+ return False
403
+ if best is None or best.tg_tps is None:
404
+ return True
405
+ if new.tg_tps > best.tg_tps * (1 + TIE_TOLERANCE):
406
+ return True
407
+ if new.tg_tps >= best.tg_tps * (1 - TIE_TOLERANCE):
408
+ return (new.pp_tps or 0.0) > (best.pp_tps or 0.0) * (1 + TIE_TOLERANCE)
409
+ return False
410
+
411
+
412
+ class _Sweep:
413
+ """State of one coordinate-descent run (results, cache, best plan)."""
414
+
415
+ def __init__(
416
+ self,
417
+ bench: Path,
418
+ model: Path,
419
+ seed: SeedPlan,
420
+ host: HostInfo,
421
+ *,
422
+ time_limit: float,
423
+ block_count: int | None,
424
+ allow_kv_quant: bool,
425
+ device: str | None,
426
+ on_progress: Callable[[BenchResult], None] | None,
427
+ clock: Callable[[], float],
428
+ ) -> None:
429
+ """Store the run's inputs; nothing is measured until ``run``."""
430
+ self._bench, self._model, self._seed, self._host = bench, model, seed, host
431
+ self._time_limit, self._block_count, self._allow_kv_quant = time_limit, block_count, allow_kv_quant
432
+ self._device, self._on_progress, self._clock = device, on_progress, clock
433
+ self._started = 0.0
434
+ self._cache: dict[tuple[str, ...], BenchResult] = {}
435
+ self.results: list[BenchResult] = []
436
+ self.best: BenchResult | None = None
437
+ self.best_plan = seed
438
+ self.interrupted = False
439
+
440
+ def measured(self, plan: SeedPlan) -> BenchResult | None:
441
+ """Return the result already measured for ``plan``, if any."""
442
+ return self._cache.get(tuple(plan_to_bench_args(plan, self._device)))
443
+
444
+ def _remaining(self) -> float:
445
+ return self._time_limit - (self._clock() - self._started)
446
+
447
+ def _measure(self, plan: SeedPlan) -> None:
448
+ """Measure ``plan`` unless an identical candidate was already measured; track the best."""
449
+ args = tuple(plan_to_bench_args(plan, self._device))
450
+ if args in self._cache:
451
+ return
452
+ timeout = min(BENCH_TIMEOUT, max(MIN_BENCH_TIMEOUT, self._remaining())) if self.results else BENCH_TIMEOUT
453
+ result = run_bench(self._bench, self._model, args, timeout=timeout)
454
+ self._cache[args] = result
455
+ self.results.append(result)
456
+ if result.error:
457
+ log.info("Candidate %s failed: %s", " ".join(args), result.error)
458
+ if _beats(result, self.best):
459
+ self.best, self.best_plan = result, plan
460
+ if self._on_progress is not None:
461
+ self._on_progress(result)
462
+
463
+ def _step(self, field: str, candidates: Sequence[SeedPlan]) -> None:
464
+ """Try every value of one dimension on top of the best plan so far."""
465
+ base = self.best_plan
466
+ for candidate in candidates:
467
+ if self._remaining() <= 0:
468
+ return
469
+ plan = replace(base, **{field: getattr(candidate, field)})
470
+ if field == "cache_type" and not plan.flash_attn:
471
+ continue # a quantised V cache needs flash attention
472
+ self._measure(plan)
473
+
474
+ def run(self) -> list[BenchResult]:
475
+ """Measure the seed, then each dimension in turn until the budget is spent or the user interrupts.
476
+
477
+ Ctrl-C ends the sweep early and sets ``interrupted``; what was measured so far is kept.
478
+
479
+ Returns:
480
+ list[BenchResult]: Every measured candidate in order (failures included).
481
+ """
482
+ self._started = self._clock()
483
+ steps = candidate_steps(
484
+ self._seed, self._host, allow_kv_quant=self._allow_kv_quant, block_count=self._block_count
485
+ )
486
+ try:
487
+ self._measure(self._seed)
488
+ for field, candidates in steps:
489
+ self._step(field, candidates)
490
+ except KeyboardInterrupt:
491
+ self.interrupted = True
492
+ log.warning("Sweep interrupted; keeping the best result so far")
493
+ return self.results
494
+
495
+
496
+ def sweep(
497
+ bench: Path,
498
+ model: Path,
499
+ seed: SeedPlan,
500
+ host: HostInfo,
501
+ *,
502
+ time_limit: float,
503
+ allow_kv_quant: bool = False,
504
+ block_count: int | None = None,
505
+ device: str | None = None,
506
+ on_progress: Callable[[BenchResult], None] | None = None,
507
+ clock: Callable[[], float] = time.monotonic,
508
+ ) -> list[BenchResult]:
509
+ """Coordinate-descent over launch settings, one dimension at a time, keeping the best after each.
510
+
511
+ The seed is always measured; ``time_limit`` seconds bound the rest (0 measures only the seed). Failed candidates
512
+ are recorded and skipped, identical candidates are never re-measured, and Ctrl-C returns what was measured.
513
+
514
+ Args:
515
+ bench: The ``llama-bench`` executable.
516
+ model: GGUF file to measure.
517
+ seed: Starting plan.
518
+ host: Host snapshot.
519
+ time_limit: Budget in seconds, measured with ``clock``.
520
+ allow_kv_quant: Also try a ``q8_0`` KV cache.
521
+ block_count: Model layer count (enables the ``ngl`` dimension for partial offloads).
522
+ device: Device id to pin ``llama-bench`` to (``-dev``).
523
+ on_progress: Called with every new result.
524
+ clock: Monotonic time source (injectable for tests).
525
+
526
+ Returns:
527
+ list[BenchResult]: All measured candidates in order.
528
+ """
529
+ return _Sweep(
530
+ bench,
531
+ model,
532
+ seed,
533
+ host,
534
+ time_limit=time_limit,
535
+ block_count=block_count,
536
+ allow_kv_quant=allow_kv_quant,
537
+ device=device,
538
+ on_progress=on_progress,
539
+ clock=clock,
540
+ ).run()
541
+
542
+
543
+ # --- HTTP ----------------------------------------------------------------------------------------------------------
544
+
545
+
546
+ def _decode_body(raw: bytes) -> Any:
547
+ """Parse a JSON body, returning None when it is empty or not JSON."""
548
+ try:
549
+ return json.loads(raw)
550
+ except ValueError:
551
+ return None
552
+
553
+
554
+ def _http_json(method: str, url: str, payload: Any, timeout: float) -> tuple[int, Any] | None:
555
+ """Send one JSON request to a local service, bypassing proxies.
556
+
557
+ Args:
558
+ method: ``GET`` or ``POST``.
559
+ url: Absolute ``http(s)`` URL.
560
+ payload: JSON-serialisable body, or None for no body.
561
+ timeout: Socket timeout in seconds.
562
+
563
+ Returns:
564
+ tuple[int, Any] | None: ``(status, parsed JSON or None)``, or None when nothing answered.
565
+ """
566
+ if not url.startswith(("http://", "https://")):
567
+ return None
568
+ body = None if payload is None else json.dumps(payload).encode()
569
+ headers = {"Content-Type": "application/json"} if body is not None else {}
570
+ # the scheme was restricted to http(s) above
571
+ request = urllib.request.Request(url, data=body, headers=headers, method=method) # ruff: ignore[suspicious-url-open-usage]
572
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
573
+ try:
574
+ with opener.open(request, timeout=timeout) as resp:
575
+ return resp.status, _decode_body(resp.read())
576
+ except urllib.error.HTTPError as exc:
577
+ try:
578
+ return exc.code, _decode_body(exc.read())
579
+ except OSError:
580
+ return exc.code, None
581
+ except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError):
582
+ return None
583
+
584
+
585
+ def _free_port() -> int:
586
+ """Return a free ephemeral loopback port (never the default serve port)."""
587
+ with socket.socket() as sock:
588
+ sock.bind((constants.DEFAULT_HOST, 0))
589
+ return int(sock.getsockname()[1])
590
+
591
+
592
+ # --- validation ----------------------------------------------------------------------------------------------------
593
+
594
+
595
+ def _completes(host: str, port: int, timeout: float) -> bool:
596
+ """Ask the server for a few tokens; True when it answers 200 with a ``content`` string."""
597
+ payload = {"prompt": VALIDATE_PROMPT, "n_predict": VALIDATE_TOKENS}
598
+ answer = _http_json("POST", f"http://{host}:{port}/completion", payload, min(timeout, COMPLETION_TIMEOUT))
599
+ return (
600
+ answer is not None
601
+ and answer[0] == HTTP_OK
602
+ and isinstance(answer[1], dict)
603
+ and isinstance(answer[1].get("content"), str)
604
+ )
605
+
606
+
607
+ def validate(server: Path, settings: ServeSettings, *, base: Path | None = None, timeout: float = 180.0) -> bool:
608
+ """Launch the real ``llama-server`` with ``settings`` and check that it generates; never raises.
609
+
610
+ The probe listens on a free ephemeral loopback port and keeps its pid file and log in ``<base>/validate``, so it
611
+ cannot collide with, or ever stop, the user's own server. The probe is always stopped, also on Ctrl-C (a
612
+ ``KeyboardInterrupt`` is not swallowed: the caller decides what to keep).
613
+
614
+ Args:
615
+ server: The ``llama-server`` executable.
616
+ settings: Launch settings to verify (host and port are replaced by the probe's).
617
+ base: Storage directory (None resolves ``constants.home()`` at call time).
618
+ timeout: Seconds to wait for readiness (the completion has its own, shorter limit).
619
+
620
+ Returns:
621
+ bool: True when the server became ready and completed a short generation.
622
+ """
623
+ scratch = (base if base is not None else constants.home()) / VALIDATE_DIRNAME
624
+ try:
625
+ port = _free_port()
626
+ probe = replace(settings, host=constants.DEFAULT_HOST, port=port)
627
+ argv = llamacpp.build_serve_argv(server, probe)
628
+ server_runtime.start(
629
+ argv, base=scratch, host=probe.host, port=port, model=probe.alias, detach=True, ready_timeout=timeout
630
+ )
631
+ return _completes(probe.host, port, timeout)
632
+ except (LlamaCppError, OSError) as exc:
633
+ log.warning("Validation launch failed: %s", exc)
634
+ return False
635
+ finally:
636
+ server_runtime.stop(scratch)
637
+
638
+
639
+ # --- Ollama / VRAM -------------------------------------------------------------------------------------------------
640
+
641
+
642
+ def available_mib(device: Device) -> int:
643
+ """Return the memory a run can use on ``device`` now: its free memory (the total when that is unknown)."""
644
+ return device.free_mib if device.free_mib > 0 else device.total_mib
645
+
646
+
647
+ def vram_preflight(model_need_mib: int, device: Device | None) -> int:
648
+ """Return how many MiB the model is short of on ``device`` (0 when it fits or there is no device).
649
+
650
+ A model larger than the card can only ever use the whole card, so its need is capped at ``device.total_mib``;
651
+ the shortfall is then just the memory other processes hold. An unknown free figure (0) is no shortfall.
652
+
653
+ Args:
654
+ model_need_mib: Memory the model needs, in MiB.
655
+ device: The chosen GPU, or None for CPU-only.
656
+
657
+ Returns:
658
+ int: Shortfall in MiB computed from ``device.free_mib``.
659
+ """
660
+ if device is None or device.free_mib <= 0:
661
+ return 0
662
+ return max(0, min(model_need_mib, device.total_mib) - device.free_mib)
663
+
664
+
665
+ def _ollama_base_url() -> str:
666
+ """Resolve Ollama's API base URL from ``OLLAMA_HOST`` (``host[:port]`` or a URL); default ``127.0.0.1:11434``."""
667
+ default = f"http://127.0.0.1:{OLLAMA_DEFAULT_PORT}"
668
+ raw = os.environ.get("OLLAMA_HOST", "").strip()
669
+ if not raw:
670
+ return default
671
+ scheme, _, rest = raw.rpartition("://")
672
+ parts = urlsplit(f"//{rest.split('/', 1)[0]}")
673
+ try:
674
+ port = parts.port or OLLAMA_DEFAULT_PORT
675
+ except ValueError:
676
+ return default
677
+ host = parts.hostname or constants.DEFAULT_HOST
678
+ host = constants.DEFAULT_HOST if host in {"0.0.0.0", "::"} else host # a bind-all address is not connectable
679
+ return f"{scheme or 'http'}://{f'[{host}]' if ':' in host else host}:{port}"
680
+
681
+
682
+ def _loaded_models(data: Any) -> list[str]:
683
+ """Extract model names from an ``/api/ps`` document, tolerating unexpected shapes."""
684
+ models = data.get("models") if isinstance(data, dict) else None
685
+ if not isinstance(models, list):
686
+ return []
687
+ names = (m.get("name") or m.get("model") for m in models if isinstance(m, dict))
688
+ return [n for n in names if isinstance(n, str) and n]
689
+
690
+
691
+ def unload_ollama(timeout: float = 30.0) -> bool:
692
+ """Ask a local Ollama to unload every loaded model (``keep_alive: 0``) to free VRAM.
693
+
694
+ Args:
695
+ timeout: Seconds allowed for each unload request.
696
+
697
+ Returns:
698
+ bool: True when Ollama answered and every loaded model was unloaded (also when none were loaded); False when
699
+ Ollama is unreachable or an unload failed.
700
+ """
701
+ base = _ollama_base_url()
702
+ answer = _http_json("GET", f"{base}/api/ps", None, min(timeout, OLLAMA_PS_TIMEOUT))
703
+ if answer is None or answer[0] != HTTP_OK:
704
+ log.info("Ollama is not reachable at %s", base)
705
+ return False
706
+ unloaded = True
707
+ for name in _loaded_models(answer[1]):
708
+ reply = _http_json("POST", f"{base}/api/generate", {"model": name, "keep_alive": 0}, timeout)
709
+ if reply is None or reply[0] != HTTP_OK:
710
+ log.warning("Could not unload Ollama model %s", name)
711
+ unloaded = False
712
+ return unloaded
713
+
714
+
715
+ # --- optimize ------------------------------------------------------------------------------------------------------
716
+
717
+
718
+ def _step_down(plan: SeedPlan) -> SeedPlan | None:
719
+ """Return a more conservative plan: ctx halved (floor ``MIN_CTX``), then ``ngl`` lowered by 4; None if exhausted."""
720
+ if plan.ctx > MIN_CTX:
721
+ return replace(plan, ctx=max(MIN_CTX, plan.ctx // 2))
722
+ if plan.ngl > 0:
723
+ return replace(plan, ngl=max(0, plan.ngl - 4))
724
+ return None
725
+
726
+
727
+ def _validated(
728
+ server_bin: Path, model: OllamaModel, cfg: Config, device: Device | None, plan: SeedPlan, base: Path | None
729
+ ) -> SeedPlan | None:
730
+ """Validate ``plan`` with the real server; on failure step down once and re-validate.
731
+
732
+ Args:
733
+ server_bin: The ``llama-server`` executable.
734
+ model: The model being tuned.
735
+ cfg: Configuration (host and port defaults).
736
+ device: Chosen GPU, or None.
737
+ plan: The plan to verify.
738
+ base: Storage directory.
739
+
740
+ Returns:
741
+ SeedPlan | None: The plan that generated successfully, or None when both attempts failed.
742
+ """
743
+
744
+ def works(candidate: SeedPlan) -> bool:
745
+ settings = ServeSettings(
746
+ model_path=model.blob_path or Path(),
747
+ alias=model.name,
748
+ host=cfg.host,
749
+ port=cfg.port,
750
+ ctx=candidate.ctx,
751
+ device=device.id if device else None,
752
+ profile_args=seed_to_args(candidate),
753
+ )
754
+ return validate(server_bin, settings, base=base)
755
+
756
+ if works(plan):
757
+ return plan
758
+ lower = _step_down(plan)
759
+ return lower if lower is not None and works(lower) else None
760
+
761
+
762
+ def _bench_table(results: Sequence[BenchResult]) -> list[dict[str, Any]]:
763
+ """Convert results to the JSON-friendly rows stored in ``Profile.bench``."""
764
+ return [{"args": list(r.args), "tg_tps": r.tg_tps, "pp_tps": r.pp_tps, "error": r.error} for r in results]
765
+
766
+
767
+ def _store(cfg: Config, base: Path | None, keys: Sequence[str], profile: Profile) -> Profile:
768
+ """Record ``profile`` under every key in ``keys`` and persist the config; a failed save is logged, never raised."""
769
+ for key in keys:
770
+ cfg.profiles[key] = profile
771
+ try:
772
+ config.save(cfg, base)
773
+ except Exception:
774
+ log.warning("Could not save the profile for %s", ", ".join(keys), exc_info=True)
775
+ return profile
776
+
777
+
778
+ def optimize_model(
779
+ model: OllamaModel,
780
+ cfg: Config,
781
+ host: HostInfo,
782
+ device: Device | None,
783
+ *,
784
+ ctx: int,
785
+ quick: bool,
786
+ time_limit: float,
787
+ allow_kv_quant: bool,
788
+ base: Path | None = None,
789
+ on_progress: Callable[[BenchResult], None] | None = None,
790
+ ) -> Profile:
791
+ """Find, validate and save the fastest launch settings for ``model``.
792
+
793
+ Seed from the GGUF and hardware; unless ``quick``, sweep with ``llama-bench``, then launch the winner as a real
794
+ server. A failed validation steps down once (ctx, then ``ngl``); if that fails too the unmeasured seed is saved.
795
+ Ctrl-C (during the sweep or the validation) skips or abandons the validation and saves the best result so far with
796
+ ``validated=False``. The seed budgets the free VRAM (see :func:`optimize_seed`). ``quick`` saves the unmeasured
797
+ seed without launching anything. The profile is stored in ``cfg`` under ``profile_key(digest, final_ctx)`` (and
798
+ also under the requested ctx when that differs, so a lookup by the requested ctx finds it); the config is
799
+ written (a write failure is logged, never raised).
800
+
801
+ Args:
802
+ model: The installed Ollama model.
803
+ cfg: Configuration to update (other profiles are preserved).
804
+ host: Host snapshot.
805
+ device: Chosen GPU, or None for CPU-only.
806
+ ctx: Requested context length.
807
+ quick: Skip benchmarking and validation; save the heuristic seed.
808
+ time_limit: Sweep budget in seconds.
809
+ allow_kv_quant: Also try a ``q8_0`` KV cache.
810
+ base: Storage directory (None resolves ``constants.home()`` at call time).
811
+ on_progress: Called with every benchmark result.
812
+
813
+ Returns:
814
+ Profile: The saved profile.
815
+
816
+ Raises:
817
+ LlamaCppError: ``llama-server`` cannot be found.
818
+ ValueError: The model has no GGUF layer.
819
+ """
820
+ server_bin = llamacpp.find_binary("llama-server", cfg.llama_server)
821
+ if server_bin is None:
822
+ raise LlamaCppError("llama-server was not found; install llama.cpp first")
823
+ if model.blob_path is None or model.digest is None:
824
+ raise ValueError(f"{model.name} has no model layer")
825
+ info = read_gguf(model.blob_path)
826
+ seed = optimize_seed(info, host, device, ctx) # budgets the free VRAM; the fingerprint keeps describing the card
827
+ fingerprint = hardware.fingerprint(host, device, llamacpp.version(server_bin))
828
+ profile = Profile(args=seed_to_args(seed), ctx=seed.ctx, fingerprint=fingerprint, timestamp=_now())
829
+ if not quick:
830
+ bench_bin = llamacpp.find_binary("llama-bench", cfg.llama_bench)
831
+ run = None
832
+ if bench_bin is None:
833
+ log.warning("llama-bench not found; validating the heuristic seed without benchmarking")
834
+ else:
835
+ run = _Sweep(
836
+ bench_bin,
837
+ model.blob_path,
838
+ seed,
839
+ host,
840
+ time_limit=time_limit,
841
+ block_count=info.block_count if device else None, # no ngl sweep without a GPU
842
+ allow_kv_quant=allow_kv_quant,
843
+ device=device.id if device else None,
844
+ on_progress=on_progress,
845
+ clock=time.monotonic,
846
+ )
847
+ run.run()
848
+ profile.bench = _bench_table(run.results)
849
+ winner = run.best_plan if run is not None and run.best is not None else seed
850
+ interrupted = run is not None and run.interrupted
851
+ final: SeedPlan | None = winner # an interrupted run launches nothing: the measured winner is kept as is
852
+ if not interrupted:
853
+ try:
854
+ final = _validated(server_bin, model, cfg, device, winner, base)
855
+ except KeyboardInterrupt:
856
+ interrupted = True
857
+ log.warning("Validation interrupted; keeping the measured winner without validating it")
858
+ final = winner
859
+ if final is not None:
860
+ result = run.measured(final) if run is not None else None
861
+ profile.args, profile.ctx = seed_to_args(final), final.ctx
862
+ if result is not None and result.tg_tps is not None:
863
+ profile.tg_tps, profile.pp_tps, profile.measured = result.tg_tps, result.pp_tps, True
864
+ profile.validated = not interrupted
865
+ # The same profile is also reachable by the requested ctx, so `serve --ctx <requested>` finds it even when the
866
+ # actual ctx (``profile.ctx``) was reduced to fit or by validation step-down.
867
+ keys = list(dict.fromkeys([profile_key(model.digest, profile.ctx), profile_key(model.digest, ctx)]))
868
+ return _store(cfg, base, keys, profile)
869
+
870
+
871
+ def _now() -> str:
872
+ """Return the current UTC time as an ISO-8601 string."""
873
+ return datetime.now(UTC).isoformat(timespec="seconds")