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.
- ollama2cpp/__init__.py +5 -0
- ollama2cpp/__main__.py +263 -0
- ollama2cpp/commands.py +648 -0
- ollama2cpp/config.py +233 -0
- ollama2cpp/constants.py +42 -0
- ollama2cpp/free_cmd.py +179 -0
- ollama2cpp/gguf.py +357 -0
- ollama2cpp/hardware.py +266 -0
- ollama2cpp/llamacpp.py +247 -0
- ollama2cpp/ollama.py +243 -0
- ollama2cpp/optimize_cmd.py +350 -0
- ollama2cpp/optimizer.py +873 -0
- ollama2cpp/proc.py +130 -0
- ollama2cpp/selector.py +150 -0
- ollama2cpp/server.py +640 -0
- ollama2cpp/ui.py +172 -0
- ollama2cpp/workflow.py +678 -0
- ollama2cpp-0.1.1.dist-info/METADATA +210 -0
- ollama2cpp-0.1.1.dist-info/RECORD +23 -0
- ollama2cpp-0.1.1.dist-info/WHEEL +5 -0
- ollama2cpp-0.1.1.dist-info/entry_points.txt +2 -0
- ollama2cpp-0.1.1.dist-info/licenses/LICENSE +21 -0
- ollama2cpp-0.1.1.dist-info/top_level.txt +1 -0
ollama2cpp/workflow.py
ADDED
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
"""Serve orchestration: first-run setup, configuration upkeep, launch planning and starting the server.
|
|
2
|
+
|
|
3
|
+
No CLI parsing lives here (see ``__main__``); every user-facing failure is a :class:`WorkflowError` (or one of the
|
|
4
|
+
domain errors ``LlamaCppError`` / ``ModelNotFoundError``) that the CLI turns into one error line and exit code 1.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass, replace
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from ollama2cpp import config, constants, gguf, hardware, llamacpp, ollama, optimizer, proc, selector, server, ui
|
|
15
|
+
from ollama2cpp.config import Config, Profile
|
|
16
|
+
from ollama2cpp.hardware import Device, HostInfo
|
|
17
|
+
from ollama2cpp.llamacpp import ServeSettings
|
|
18
|
+
from ollama2cpp.ollama import OllamaModel
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"ServeOptions",
|
|
22
|
+
"ServePlan",
|
|
23
|
+
"WorkflowError",
|
|
24
|
+
"ensure_config",
|
|
25
|
+
"first_run",
|
|
26
|
+
"load_saved_config",
|
|
27
|
+
"plan_serve",
|
|
28
|
+
"probe",
|
|
29
|
+
"run_serve",
|
|
30
|
+
"select_model",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
PORT_FREE_TIMEOUT = 15.0
|
|
36
|
+
PORT_POLL_INTERVAL = 0.2
|
|
37
|
+
_MIB = 1024 * 1024
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class WorkflowError(RuntimeError):
|
|
41
|
+
"""A user-facing failure; the message is shown as-is."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class ServeOptions:
|
|
46
|
+
"""Everything the ``serve`` command accepts.
|
|
47
|
+
|
|
48
|
+
Attributes:
|
|
49
|
+
model: Model name for this run (and the stored default on a first run).
|
|
50
|
+
model_from_env: ``model`` came from ``$OLLAMA_MODEL`` rather than the command line: when it is not installed
|
|
51
|
+
the run falls back to the saved default (or an automatic choice) with a warning instead of failing.
|
|
52
|
+
ollama_path: Explicit Ollama models directory.
|
|
53
|
+
host: Listen address override.
|
|
54
|
+
port: Listen port override.
|
|
55
|
+
ctx: Requested context size override.
|
|
56
|
+
detach: Run in the background and return once ready.
|
|
57
|
+
restart: Stop and start our own running server again, also when it already serves this model.
|
|
58
|
+
dry_run: Print the command instead of starting anything.
|
|
59
|
+
vision: Pass the model's multimodal projector (``--mmproj``) when it has one.
|
|
60
|
+
assume_yes: Answer yes to confirmation questions.
|
|
61
|
+
extra_args: Extra ``llama-server`` arguments, appended last.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
model: str | None = None
|
|
65
|
+
model_from_env: bool = False
|
|
66
|
+
ollama_path: Path | None = None
|
|
67
|
+
host: str | None = None
|
|
68
|
+
port: int | None = None
|
|
69
|
+
ctx: int | None = None
|
|
70
|
+
detach: bool = False
|
|
71
|
+
restart: bool = False
|
|
72
|
+
dry_run: bool = False
|
|
73
|
+
vision: bool = False
|
|
74
|
+
assume_yes: bool = False
|
|
75
|
+
extra_args: tuple[str, ...] = ()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class ServePlan:
|
|
80
|
+
"""What to run: the final command plus the facts that explain it.
|
|
81
|
+
|
|
82
|
+
Attributes:
|
|
83
|
+
argv: The full ``llama-server`` command line.
|
|
84
|
+
settings: The settings the command was built from.
|
|
85
|
+
model: The model being served.
|
|
86
|
+
host: Listen address.
|
|
87
|
+
port: Listen port.
|
|
88
|
+
profile_note: One line saying which profile or seed was used.
|
|
89
|
+
warnings: Warnings to show before starting.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
argv: tuple[str, ...]
|
|
93
|
+
settings: ServeSettings
|
|
94
|
+
model: OllamaModel
|
|
95
|
+
host: str
|
|
96
|
+
port: int
|
|
97
|
+
profile_note: str
|
|
98
|
+
warnings: tuple[str, ...] = ()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- hardware and model selection ----------------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def probe(llama_server: Path, override: str | None) -> tuple[HostInfo, Device | None]:
|
|
105
|
+
"""Probe the host and choose the device to run on.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
llama_server: The ``llama-server`` binary (used to list devices).
|
|
109
|
+
override: A device id configured by the user.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
tuple[HostInfo, Device | None]: The host snapshot and the chosen GPU (None for CPU-only).
|
|
113
|
+
"""
|
|
114
|
+
host = hardware.host_info(llama_server)
|
|
115
|
+
return host, hardware.best_device(host.devices, override)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def load_saved_config() -> Config | None:
|
|
119
|
+
"""Load the saved configuration (a corrupt file is backed up and reads as missing).
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
Config | None: The configuration, or None when there is none.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
WorkflowError: When the file exists but cannot be read (nothing is moved or rewritten).
|
|
126
|
+
"""
|
|
127
|
+
try:
|
|
128
|
+
return config.load()
|
|
129
|
+
except OSError as exc:
|
|
130
|
+
raise WorkflowError(f"Cannot read the configuration {config.config_file()}: {exc}") from exc
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _require_server(cfg: Config) -> Path:
|
|
134
|
+
"""Return the configured ``llama-server`` path.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
cfg: The configuration (already completed by :func:`ensure_config`).
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
Path: The binary.
|
|
141
|
+
|
|
142
|
+
Raises:
|
|
143
|
+
WorkflowError: When no binary is configured.
|
|
144
|
+
"""
|
|
145
|
+
if not cfg.llama_server:
|
|
146
|
+
raise WorkflowError("llama-server is not configured; run `ollama2cpp serve` again to set it up")
|
|
147
|
+
return Path(cfg.llama_server)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _require_root(cfg: Config) -> Path:
|
|
151
|
+
"""Return the configured Ollama models directory.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
cfg: The configuration (already completed by :func:`ensure_config`).
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Path: The models directory.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
WorkflowError: When none is configured.
|
|
161
|
+
"""
|
|
162
|
+
if not cfg.ollama_path:
|
|
163
|
+
raise WorkflowError("The Ollama models path is not configured; run `ollama2cpp serve` again to set it up")
|
|
164
|
+
return Path(cfg.ollama_path)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _require_blob(model: OllamaModel) -> tuple[Path, str]:
|
|
168
|
+
"""Return the blob path and digest of a model whose blob is on disk.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
model: The installed model.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
tuple[Path, str]: The GGUF blob and its digest.
|
|
175
|
+
|
|
176
|
+
Raises:
|
|
177
|
+
WorkflowError: For a dangling manifest (no model layer or blob missing).
|
|
178
|
+
"""
|
|
179
|
+
if model.blob_path is None or model.digest is None or not model.blob_exists:
|
|
180
|
+
raise WorkflowError(f"Model blob missing for {model.name}; re-pull it with `ollama pull {model.name}`")
|
|
181
|
+
return model.blob_path, model.digest
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _pick_best(root: Path, host: HostInfo, device: Device | None) -> tuple[selector.Candidate, bool]:
|
|
185
|
+
"""Choose the best installed chat model for the hardware.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
root: The Ollama models directory.
|
|
189
|
+
host: Host snapshot (RAM is the budget on CPU-only hosts).
|
|
190
|
+
device: Chosen GPU (its total VRAM is the budget), or None.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
tuple[selector.Candidate, bool]: The candidate and whether it fits.
|
|
194
|
+
|
|
195
|
+
Raises:
|
|
196
|
+
WorkflowError: When there is no chat model installed.
|
|
197
|
+
"""
|
|
198
|
+
cands = selector.classify_all(ollama.list_models(root))
|
|
199
|
+
best = selector.choose_best(cands, device.total_mib if device else 0, host.ram_total_mib)
|
|
200
|
+
if best is None:
|
|
201
|
+
raise WorkflowError(f"No chat model found in {root}. Pull one first, e.g. `ollama pull llama3.2`.")
|
|
202
|
+
return best
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _hardware_line(host: HostInfo, device: Device | None) -> str:
|
|
206
|
+
"""Describe the hardware for the summary panel."""
|
|
207
|
+
if device is None:
|
|
208
|
+
return f"CPU only ({host.ram_total_mib} MiB RAM)"
|
|
209
|
+
return f"{device.name} ({device.total_mib} MiB VRAM), {host.ram_total_mib} MiB RAM"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _auto_select(cfg: Config, root: Path) -> tuple[OllamaModel, str]:
|
|
213
|
+
"""Choose a model automatically and say why.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
cfg: The configuration (its llama-server and device are used to probe the hardware).
|
|
217
|
+
root: The Ollama models directory.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
tuple[OllamaModel, str]: The model and the reason line.
|
|
221
|
+
"""
|
|
222
|
+
host, device = probe(_require_server(cfg), cfg.device)
|
|
223
|
+
cand, fits = _pick_best(root, host, device)
|
|
224
|
+
hw = _hardware_line(host, device)
|
|
225
|
+
if fits:
|
|
226
|
+
return cand.model, f"largest chat model that fits ({cand.need_mib} MiB needed) on {hw}"
|
|
227
|
+
ui.show_notice("warn", f"No installed chat model fits {hw}; using the smallest one ({cand.model.name}).")
|
|
228
|
+
return cand.model, f"smallest chat model (nothing fits: {cand.need_mib} MiB needed) on {hw}"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# --- configuration and first run -----------------------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _ensure_binaries(cfg: Config, opts: ServeOptions) -> bool:
|
|
235
|
+
"""Make sure ``llama-server`` exists (installing it when needed) and record the binary paths.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
cfg: The configuration, updated in place.
|
|
239
|
+
opts: The serve options (``assume_yes`` is passed to the installer).
|
|
240
|
+
|
|
241
|
+
Returns:
|
|
242
|
+
bool: True when the configuration changed.
|
|
243
|
+
"""
|
|
244
|
+
changed = False
|
|
245
|
+
binary = llamacpp.find_binary("llama-server", cfg.llama_server)
|
|
246
|
+
if binary is None:
|
|
247
|
+
ui.show_notice("info", "llama-server was not found; installing llama.cpp.")
|
|
248
|
+
binary = llamacpp.install(assume_yes=opts.assume_yes)
|
|
249
|
+
if cfg.llama_server != str(binary):
|
|
250
|
+
cfg.llama_server = str(binary)
|
|
251
|
+
changed = True
|
|
252
|
+
bench = llamacpp.find_binary("llama-bench", cfg.llama_bench)
|
|
253
|
+
if bench is not None and cfg.llama_bench != str(bench):
|
|
254
|
+
cfg.llama_bench = str(bench)
|
|
255
|
+
changed = True
|
|
256
|
+
return changed
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _resolve_root(cfg: Config, opts: ServeOptions, *, first: bool) -> tuple[Path, bool]:
|
|
260
|
+
"""Find the Ollama models directory for this run.
|
|
261
|
+
|
|
262
|
+
Order: a valid ``--ollama-path``, the configured path (while it still holds ``manifests/``), then discovery
|
|
263
|
+
(``$OLLAMA_MODELS`` and the common locations). An invalid flag only warns.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
cfg: The configuration (its ``ollama_path`` is the configured candidate).
|
|
267
|
+
opts: The serve options (``ollama_path`` is the flag).
|
|
268
|
+
first: Whether this is a first run, where the flag is saved.
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
tuple[Path, bool]: The directory and whether it must be written to the config (the flag is per-run on a
|
|
272
|
+
regular run; a rediscovered path is saved).
|
|
273
|
+
|
|
274
|
+
Raises:
|
|
275
|
+
WorkflowError: When no Ollama models directory can be found.
|
|
276
|
+
"""
|
|
277
|
+
flag = opts.ollama_path
|
|
278
|
+
if flag is not None:
|
|
279
|
+
if (flag / "manifests").is_dir():
|
|
280
|
+
return flag, first
|
|
281
|
+
ui.show_notice("warn", f"--ollama-path {flag} has no manifests/, ignoring")
|
|
282
|
+
configured = Path(cfg.ollama_path) if cfg.ollama_path else None
|
|
283
|
+
if configured is not None and (configured / "manifests").is_dir():
|
|
284
|
+
return configured, False
|
|
285
|
+
found = ollama.find_ollama_path()
|
|
286
|
+
if found is None:
|
|
287
|
+
raise WorkflowError(
|
|
288
|
+
"Could not find the Ollama models directory. Set OLLAMA_MODELS or pass --ollama-path "
|
|
289
|
+
"(it is the folder that contains `manifests` and `blobs`)."
|
|
290
|
+
)
|
|
291
|
+
if configured is not None:
|
|
292
|
+
ui.show_notice("warn", f"Ollama path {configured} no longer exists; using {found}.")
|
|
293
|
+
return found, True
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def first_run(opts: ServeOptions) -> Config:
|
|
297
|
+
"""Set ollama2cpp up from scratch and save the configuration.
|
|
298
|
+
|
|
299
|
+
Installs llama.cpp when missing, finds the Ollama models directory, chooses the default model (``--model`` or
|
|
300
|
+
the best one for the hardware), saves everything and prints a summary.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
opts: The serve options.
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Config: The saved configuration.
|
|
307
|
+
"""
|
|
308
|
+
ui.show_notice("info", "First run: setting up ollama2cpp.")
|
|
309
|
+
cfg = Config()
|
|
310
|
+
_ensure_binaries(cfg, opts)
|
|
311
|
+
root, _ = _resolve_root(cfg, opts, first=True)
|
|
312
|
+
cfg.ollama_path = str(root)
|
|
313
|
+
model: OllamaModel | None = None
|
|
314
|
+
reason = "requested with --model"
|
|
315
|
+
if opts.model:
|
|
316
|
+
try:
|
|
317
|
+
model = ollama.resolve_model(root, opts.model)
|
|
318
|
+
except ollama.ModelNotFoundError:
|
|
319
|
+
if not opts.model_from_env:
|
|
320
|
+
raise
|
|
321
|
+
else:
|
|
322
|
+
_require_blob(model)
|
|
323
|
+
if model is None:
|
|
324
|
+
model, reason = _auto_select(cfg, root)
|
|
325
|
+
if opts.model:
|
|
326
|
+
_warn_env_model_missing(opts.model, f"the auto-selected model ({model.name})")
|
|
327
|
+
cfg.default_model = model.name
|
|
328
|
+
config.save(cfg)
|
|
329
|
+
ui.panel(
|
|
330
|
+
"ollama2cpp first run",
|
|
331
|
+
"\n".join(
|
|
332
|
+
[
|
|
333
|
+
f"llama-server : {cfg.llama_server}",
|
|
334
|
+
f"Ollama models: {cfg.ollama_path}",
|
|
335
|
+
f"Default model: {model.name}",
|
|
336
|
+
f"Why : {reason}",
|
|
337
|
+
f"Config file : {config.config_file()}",
|
|
338
|
+
]
|
|
339
|
+
),
|
|
340
|
+
)
|
|
341
|
+
return cfg
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _setup(opts: ServeOptions) -> tuple[Config, bool]:
|
|
345
|
+
"""Load or create the configuration and settle the paths for this run.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
opts: The serve options.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
tuple[Config, bool]: The configuration to run with and whether it matches the saved one (False when a
|
|
352
|
+
per-run ``--ollama-path`` replaced the models directory, so nothing derived from it may be saved).
|
|
353
|
+
"""
|
|
354
|
+
cfg = load_saved_config()
|
|
355
|
+
if cfg is None:
|
|
356
|
+
return first_run(opts), True
|
|
357
|
+
changed = _ensure_binaries(cfg, opts)
|
|
358
|
+
root, update = _resolve_root(cfg, opts, first=False)
|
|
359
|
+
if update:
|
|
360
|
+
cfg.ollama_path = str(root)
|
|
361
|
+
changed = True
|
|
362
|
+
if changed:
|
|
363
|
+
config.save(cfg)
|
|
364
|
+
if str(root) != cfg.ollama_path:
|
|
365
|
+
return replace(cfg, ollama_path=str(root)), False
|
|
366
|
+
return cfg, True
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def ensure_config(opts: ServeOptions) -> Config:
|
|
370
|
+
"""Load the configuration, running the first-run setup when there is none, and repair what went stale.
|
|
371
|
+
|
|
372
|
+
A missing or corrupt config file means a first run. Otherwise a vanished ``llama-server`` is reinstalled and a
|
|
373
|
+
vanished Ollama directory is rediscovered (and saved). A valid ``--ollama-path`` on a regular run applies to
|
|
374
|
+
this run only: the returned copy carries it but the saved file keeps the configured path.
|
|
375
|
+
|
|
376
|
+
Args:
|
|
377
|
+
opts: The serve options.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
Config: A configuration with ``llama_server`` and ``ollama_path`` set.
|
|
381
|
+
"""
|
|
382
|
+
return _setup(opts)[0]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _warn_env_model_missing(name: str, fallback: str) -> None:
|
|
386
|
+
"""Tell the user that ``$OLLAMA_MODEL`` names a model that is not installed and what is used instead."""
|
|
387
|
+
ui.show_notice("warn", f"{constants.ENV_OLLAMA_MODEL}={name} is not installed; falling back to {fallback}.")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def select_model(cfg: Config, opts: ServeOptions, *, persist: bool = True) -> OllamaModel:
|
|
391
|
+
"""Resolve the model to serve: ``--model``, else the saved default, else a fresh automatic choice.
|
|
392
|
+
|
|
393
|
+
A saved default that is no longer installed is replaced (with a notice) and the config is updated. A
|
|
394
|
+
``--model`` given on a regular run is not saved. A model that came from ``$OLLAMA_MODEL`` (``model_from_env``)
|
|
395
|
+
and is not installed only warns and falls back to the saved default, then to an automatic choice; a model given
|
|
396
|
+
on the command line that is missing is an error.
|
|
397
|
+
|
|
398
|
+
Args:
|
|
399
|
+
cfg: The configuration.
|
|
400
|
+
opts: The serve options.
|
|
401
|
+
persist: Whether an automatic choice may be saved as the new default (False when the models directory is a
|
|
402
|
+
per-run override).
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
OllamaModel: The model.
|
|
406
|
+
|
|
407
|
+
Raises:
|
|
408
|
+
ModelNotFoundError: A command-line model is not installed.
|
|
409
|
+
"""
|
|
410
|
+
root = _require_root(cfg)
|
|
411
|
+
missing_from_env: str | None = None
|
|
412
|
+
if opts.model:
|
|
413
|
+
try:
|
|
414
|
+
return ollama.resolve_model(root, opts.model)
|
|
415
|
+
except ollama.ModelNotFoundError:
|
|
416
|
+
if not opts.model_from_env:
|
|
417
|
+
raise
|
|
418
|
+
missing_from_env = opts.model
|
|
419
|
+
if cfg.default_model:
|
|
420
|
+
try:
|
|
421
|
+
model = ollama.resolve_model(root, cfg.default_model)
|
|
422
|
+
except ollama.ModelNotFoundError:
|
|
423
|
+
if missing_from_env is None:
|
|
424
|
+
ui.show_notice("warn", f"Default model {cfg.default_model} is no longer installed; choosing another.")
|
|
425
|
+
else:
|
|
426
|
+
if missing_from_env is not None:
|
|
427
|
+
_warn_env_model_missing(missing_from_env, f"the saved default ({model.name})")
|
|
428
|
+
return model
|
|
429
|
+
model, reason = _auto_select(cfg, root)
|
|
430
|
+
if missing_from_env is not None:
|
|
431
|
+
_warn_env_model_missing(missing_from_env, f"the auto-selected model ({model.name})")
|
|
432
|
+
ui.show_notice("info", f"Selected {model.name}: {reason}")
|
|
433
|
+
if persist:
|
|
434
|
+
cfg.default_model = model.name
|
|
435
|
+
config.save(cfg)
|
|
436
|
+
return model
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# --- planning ------------------------------------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _projector(model: OllamaModel, blob: Path) -> Path | None:
|
|
443
|
+
"""Locate the model's multimodal projector blob.
|
|
444
|
+
|
|
445
|
+
Args:
|
|
446
|
+
model: The installed model.
|
|
447
|
+
blob: The model blob (the projector lives in the same directory).
|
|
448
|
+
|
|
449
|
+
Returns:
|
|
450
|
+
Path | None: The projector blob, or None when the model has none or it is not on disk.
|
|
451
|
+
"""
|
|
452
|
+
layer = next((x for x in model.layers if x.media_type == ollama.MEDIA_PROJECTOR), None)
|
|
453
|
+
if layer is None:
|
|
454
|
+
return None
|
|
455
|
+
path = blob.parent / layer.digest.replace(":", "-")
|
|
456
|
+
return path if path.is_file() else None
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _choose_profile(
|
|
460
|
+
cfg: Config, model: OllamaModel, digest: str, blob: Path, requested: int, host: HostInfo, device: Device | None
|
|
461
|
+
) -> tuple[list[str], int, str, list[str]]:
|
|
462
|
+
"""Pick the saved profile for ``(model, ctx)`` or fall back to the heuristic seed.
|
|
463
|
+
|
|
464
|
+
Args:
|
|
465
|
+
cfg: The configuration (profiles and the ``llama-server`` path).
|
|
466
|
+
model: The model being served.
|
|
467
|
+
digest: The model blob digest.
|
|
468
|
+
blob: The model blob.
|
|
469
|
+
requested: The requested context size.
|
|
470
|
+
host: Host snapshot.
|
|
471
|
+
device: Chosen GPU, or None.
|
|
472
|
+
|
|
473
|
+
Returns:
|
|
474
|
+
tuple[list[str], int, str, list[str]]: Profile arguments, the context to use, a one-line description and
|
|
475
|
+
warnings.
|
|
476
|
+
|
|
477
|
+
Raises:
|
|
478
|
+
WorkflowError: When the GGUF header cannot be read.
|
|
479
|
+
"""
|
|
480
|
+
profile: Profile | None = cfg.profiles.get(config.profile_key(digest, requested))
|
|
481
|
+
if profile is not None:
|
|
482
|
+
warnings: list[str] = []
|
|
483
|
+
current = hardware.fingerprint(host, device, llamacpp.version(_require_server(cfg)))
|
|
484
|
+
if profile.fingerprint != current:
|
|
485
|
+
warnings.append("The saved profile is stale (hardware or llama.cpp changed); re-run `ollama2cpp optimize`.")
|
|
486
|
+
if profile.ctx != requested:
|
|
487
|
+
warnings.append(
|
|
488
|
+
f"Using profile context {profile.ctx} instead of requested {requested} "
|
|
489
|
+
f"(re-run `ollama2cpp optimize --ctx {requested}` or pass --ctx {profile.ctx} to silence)."
|
|
490
|
+
)
|
|
491
|
+
if not profile.validated:
|
|
492
|
+
warnings.append(
|
|
493
|
+
"The saved profile was not validated (optimization was interrupted); "
|
|
494
|
+
"re-run `ollama2cpp optimize` to finish it."
|
|
495
|
+
)
|
|
496
|
+
if profile.measured and profile.tg_tps is not None:
|
|
497
|
+
note = f"Using optimized profile (tg {profile.tg_tps:.1f} t/s)"
|
|
498
|
+
else:
|
|
499
|
+
note = "Using unmeasured profile (heuristic settings; run `ollama2cpp optimize` to measure)"
|
|
500
|
+
return list(profile.args), profile.ctx, note, warnings
|
|
501
|
+
try:
|
|
502
|
+
info = gguf.read_gguf(blob)
|
|
503
|
+
except gguf.GgufError as exc:
|
|
504
|
+
raise WorkflowError(f"Cannot read the GGUF header of {model.name}: {exc}") from exc
|
|
505
|
+
seed = optimizer.heuristic_seed(info, host, device, requested)
|
|
506
|
+
warnings = []
|
|
507
|
+
if seed.ctx != requested:
|
|
508
|
+
warnings.append(f"Context reduced from {requested} to {seed.ctx} tokens to fit the available memory.")
|
|
509
|
+
note = "No optimized profile for this model/context; using a heuristic seed (run `ollama2cpp optimize` to tune it)"
|
|
510
|
+
return optimizer.seed_to_args(seed), seed.ctx, note, warnings
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _low_vram_warning(model: OllamaModel, blob: Path, device: Device | None, ctx: int) -> str | None:
|
|
514
|
+
"""Warn when less VRAM is free than the model needs at ``ctx`` (a model larger than the card needs the whole card).
|
|
515
|
+
|
|
516
|
+
Args:
|
|
517
|
+
model: The model being served.
|
|
518
|
+
blob: Its GGUF blob.
|
|
519
|
+
device: Chosen GPU, or None.
|
|
520
|
+
ctx: The context the server will run with.
|
|
521
|
+
|
|
522
|
+
Returns:
|
|
523
|
+
str | None: The warning, or None when there is no GPU, the free figure is unknown, or the model fits.
|
|
524
|
+
"""
|
|
525
|
+
if device is None or device.free_mib <= 0:
|
|
526
|
+
return None
|
|
527
|
+
try:
|
|
528
|
+
need = selector.estimate_need_mib(model, gguf.read_gguf(blob), ctx)
|
|
529
|
+
except gguf.GgufError:
|
|
530
|
+
return None
|
|
531
|
+
if optimizer.vram_preflight(need, device) <= 0:
|
|
532
|
+
return None
|
|
533
|
+
return (
|
|
534
|
+
f"Only {device.free_mib} MiB of VRAM is free but the model needs about {need} MiB at context {ctx}; "
|
|
535
|
+
"another process (e.g. Ollama) may be holding it."
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def plan_serve(cfg: Config, opts: ServeOptions, model: OllamaModel) -> ServePlan:
|
|
540
|
+
"""Work out the exact ``llama-server`` command for ``model``.
|
|
541
|
+
|
|
542
|
+
Args:
|
|
543
|
+
cfg: The configuration.
|
|
544
|
+
opts: The serve options.
|
|
545
|
+
model: The model to serve.
|
|
546
|
+
|
|
547
|
+
Returns:
|
|
548
|
+
ServePlan: The command and the facts behind it.
|
|
549
|
+
"""
|
|
550
|
+
blob, digest = _require_blob(model)
|
|
551
|
+
binary = _require_server(cfg)
|
|
552
|
+
host_addr, port = opts.host or cfg.host, opts.port or cfg.port
|
|
553
|
+
host, device = probe(binary, cfg.device)
|
|
554
|
+
args, ctx, note, warnings = _choose_profile(
|
|
555
|
+
cfg, model, digest, blob, opts.ctx or constants.DEFAULT_CTX, host, device
|
|
556
|
+
)
|
|
557
|
+
pinned = device.id if device is not None and (cfg.device or len(host.devices) > 1) else None
|
|
558
|
+
low_vram = _low_vram_warning(model, blob, device, ctx)
|
|
559
|
+
if low_vram:
|
|
560
|
+
warnings.append(low_vram)
|
|
561
|
+
mmproj = None
|
|
562
|
+
if opts.vision:
|
|
563
|
+
mmproj = _projector(model, blob)
|
|
564
|
+
if mmproj is None:
|
|
565
|
+
warnings.append(f"{model.name} has no usable multimodal projector; continuing without it.")
|
|
566
|
+
settings = ServeSettings(
|
|
567
|
+
model_path=blob,
|
|
568
|
+
alias=model.name,
|
|
569
|
+
host=host_addr,
|
|
570
|
+
port=port,
|
|
571
|
+
ctx=ctx,
|
|
572
|
+
device=pinned,
|
|
573
|
+
mmproj=mmproj,
|
|
574
|
+
profile_args=args,
|
|
575
|
+
extra_args=list(opts.extra_args),
|
|
576
|
+
)
|
|
577
|
+
argv = tuple(llamacpp.build_serve_argv(binary, settings))
|
|
578
|
+
return ServePlan(argv, settings, model, host_addr, port, note, tuple(warnings))
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
# --- running -------------------------------------------------------------------------------------------------------
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _wait_port_free(host: str, port: int) -> None:
|
|
585
|
+
"""Wait until nothing listens on ``host:port``.
|
|
586
|
+
|
|
587
|
+
Args:
|
|
588
|
+
host: Address.
|
|
589
|
+
port: Port.
|
|
590
|
+
|
|
591
|
+
Raises:
|
|
592
|
+
WorkflowError: When the port is still in use after ``PORT_FREE_TIMEOUT`` seconds.
|
|
593
|
+
"""
|
|
594
|
+
deadline = time.monotonic() + PORT_FREE_TIMEOUT
|
|
595
|
+
while server.port_in_use(host, port):
|
|
596
|
+
if time.monotonic() >= deadline:
|
|
597
|
+
raise WorkflowError(f"Port {port} is still in use after stopping the server.")
|
|
598
|
+
time.sleep(PORT_POLL_INTERVAL)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _handle_running(model: OllamaModel, opts: ServeOptions, host: str, port: int) -> int | None:
|
|
602
|
+
"""Deal with a server that already listens on the target port.
|
|
603
|
+
|
|
604
|
+
Args:
|
|
605
|
+
model: The model about to be served.
|
|
606
|
+
opts: The serve options.
|
|
607
|
+
host: Target address.
|
|
608
|
+
port: Target port.
|
|
609
|
+
|
|
610
|
+
Returns:
|
|
611
|
+
int | None: An exit code when the run must end here, None to continue and start the server.
|
|
612
|
+
|
|
613
|
+
Raises:
|
|
614
|
+
WorkflowError: When a foreign process holds the port.
|
|
615
|
+
"""
|
|
616
|
+
state, alias = server.describe_running(host, port, constants.home())
|
|
617
|
+
if state == "none":
|
|
618
|
+
return None
|
|
619
|
+
if state == "foreign":
|
|
620
|
+
raise WorkflowError(
|
|
621
|
+
f"Port {port} on {host} is held by another process (not started by ollama2cpp), "
|
|
622
|
+
"which is never stopped. Pick another port with --port."
|
|
623
|
+
)
|
|
624
|
+
url = f"http://{host}:{port}"
|
|
625
|
+
same = alias is not None and ollama.normalize_name(alias) == model.name
|
|
626
|
+
if not opts.restart:
|
|
627
|
+
if same:
|
|
628
|
+
ui.show_notice("ok", f"llama-server is already running {model.name} at {url}.")
|
|
629
|
+
ui.show_notice(
|
|
630
|
+
"info", "Its settings may differ from the current profile or options; use --restart to apply them."
|
|
631
|
+
)
|
|
632
|
+
return 0
|
|
633
|
+
ui.show_notice(
|
|
634
|
+
"warn",
|
|
635
|
+
f"ollama2cpp is already serving {alias or 'another model'} at {url}; "
|
|
636
|
+
f"use --restart to replace it with {model.name}.",
|
|
637
|
+
)
|
|
638
|
+
return 1
|
|
639
|
+
verb = "Restarting" if same else "Stopping"
|
|
640
|
+
ui.show_notice("info", f"{verb} the running server ({alias}) to start {model.name}.")
|
|
641
|
+
server.stop(constants.home())
|
|
642
|
+
_wait_port_free(host, port)
|
|
643
|
+
return None
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def run_serve(opts: ServeOptions) -> int:
|
|
647
|
+
"""Run the whole ``serve`` flow: setup, already-running check, planning and starting.
|
|
648
|
+
|
|
649
|
+
Args:
|
|
650
|
+
opts: The serve options.
|
|
651
|
+
|
|
652
|
+
Returns:
|
|
653
|
+
int: The process exit code.
|
|
654
|
+
"""
|
|
655
|
+
cfg, persist = _setup(opts)
|
|
656
|
+
model = select_model(cfg, opts, persist=persist)
|
|
657
|
+
host, port = opts.host or cfg.host, opts.port or cfg.port
|
|
658
|
+
if not opts.dry_run:
|
|
659
|
+
early = _handle_running(model, opts, host, port)
|
|
660
|
+
if early is not None:
|
|
661
|
+
return early
|
|
662
|
+
plan = plan_serve(cfg, opts, model)
|
|
663
|
+
for warning in plan.warnings:
|
|
664
|
+
ui.show_notice("warn", warning)
|
|
665
|
+
ui.show_notice("info", plan.profile_note)
|
|
666
|
+
command = proc.format_command(plan.argv)
|
|
667
|
+
if opts.dry_run:
|
|
668
|
+
ui.show_command(command)
|
|
669
|
+
return 0
|
|
670
|
+
url = f"http://{plan.host}:{plan.port}"
|
|
671
|
+
ui.show_notice("info", f"Starting {model.name} at {url} (Ctrl-C to stop).")
|
|
672
|
+
logger.info("Command: %s", command)
|
|
673
|
+
code = server.start(
|
|
674
|
+
plan.argv, base=constants.home(), host=plan.host, port=plan.port, model=model.name, detach=opts.detach
|
|
675
|
+
)
|
|
676
|
+
if opts.detach:
|
|
677
|
+
ui.show_notice("ok", f"{model.name} is ready at {url}")
|
|
678
|
+
return code
|