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/config.py ADDED
@@ -0,0 +1,233 @@
1
+ """Persistent configuration store (JSON, atomic writes, never crashes on bad files)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import logging
8
+ import os
9
+ import tempfile
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ollama2cpp.constants import CONFIG_FILENAME, DEFAULT_HOST, DEFAULT_PORT, home
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ BACKUP_SUFFIX = ".bak"
19
+
20
+
21
+ class _InvalidConfigError(ValueError):
22
+ """Raised internally when the parsed JSON does not match the config schema."""
23
+
24
+
25
+ @dataclass
26
+ class Profile:
27
+ """Saved llama-server settings for one model at one context size."""
28
+
29
+ args: list[str]
30
+ ctx: int
31
+ tg_tps: float | None = None
32
+ pp_tps: float | None = None
33
+ measured: bool = False
34
+ fingerprint: dict[str, str] = field(default_factory=dict)
35
+ timestamp: str = ""
36
+ bench: list[dict[str, Any]] = field(default_factory=list)
37
+ validated: bool = True # False when the optimizer was interrupted before launching a real server with it
38
+
39
+
40
+ @dataclass
41
+ class Config:
42
+ """The whole persisted configuration.
43
+
44
+ ``extra`` holds unknown top-level keys so they survive a load/save round trip.
45
+ """
46
+
47
+ ollama_path: str | None = None
48
+ default_model: str | None = None
49
+ llama_server: str | None = None
50
+ llama_bench: str | None = None
51
+ host: str = DEFAULT_HOST
52
+ port: int = DEFAULT_PORT
53
+ device: str | None = None
54
+ profiles: dict[str, Profile] = field(default_factory=dict)
55
+ extra: dict[str, Any] = field(default_factory=dict)
56
+
57
+
58
+ _KNOWN_KEYS = frozenset(Config.__dataclass_fields__) - {"extra"}
59
+
60
+
61
+ def config_file(base: Path | None = None) -> Path:
62
+ """Return the config file path.
63
+
64
+ Args:
65
+ base: Storage directory; ``None`` resolves ``constants.home()`` at call time.
66
+
67
+ Returns:
68
+ Path: ``<base>/config.json``.
69
+ """
70
+ return (home() if base is None else base) / CONFIG_FILENAME
71
+
72
+
73
+ def profile_key(digest: str, ctx: int) -> str:
74
+ """Build the key under which a model profile is stored.
75
+
76
+ Args:
77
+ digest: Model blob digest.
78
+ ctx: Context size.
79
+
80
+ Returns:
81
+ str: ``"<digest>:<ctx>"``.
82
+ """
83
+ return f"{digest}:{ctx}"
84
+
85
+
86
+ def _str_or_none(data: dict[str, Any], key: str) -> str | None:
87
+ value = data.get(key)
88
+ if value is not None and not isinstance(value, str):
89
+ raise _InvalidConfigError(key)
90
+ return value
91
+
92
+
93
+ def _number_or_none(data: dict[str, Any], key: str) -> float | None:
94
+ value = data.get(key)
95
+ if value is None:
96
+ return None
97
+ if isinstance(value, bool) or not isinstance(value, int | float):
98
+ raise _InvalidConfigError(key)
99
+ return float(value)
100
+
101
+
102
+ def _int(data: dict[str, Any], key: str, default: int | None = None) -> int:
103
+ value = data.get(key, default)
104
+ if isinstance(value, bool) or not isinstance(value, int):
105
+ raise _InvalidConfigError(key)
106
+ return value
107
+
108
+
109
+ def _profile_from_dict(data: object) -> Profile:
110
+ if not isinstance(data, dict):
111
+ raise _InvalidConfigError("profile")
112
+ args = data.get("args")
113
+ if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
114
+ raise _InvalidConfigError("args")
115
+ fingerprint = data.get("fingerprint", {})
116
+ if not isinstance(fingerprint, dict) or not all(
117
+ isinstance(k, str) and isinstance(v, str) for k, v in fingerprint.items()
118
+ ):
119
+ raise _InvalidConfigError("fingerprint")
120
+ bench = data.get("bench", [])
121
+ if not isinstance(bench, list) or not all(isinstance(b, dict) for b in bench):
122
+ raise _InvalidConfigError("bench")
123
+ measured = data.get("measured", False)
124
+ if not isinstance(measured, bool):
125
+ raise _InvalidConfigError("measured")
126
+ timestamp = data.get("timestamp", "")
127
+ if not isinstance(timestamp, str):
128
+ raise _InvalidConfigError("timestamp")
129
+ validated = data.get("validated", True) # files written before this field existed were validated
130
+ if not isinstance(validated, bool):
131
+ raise _InvalidConfigError("validated")
132
+ return Profile(
133
+ args=list(args),
134
+ ctx=_int(data, "ctx"),
135
+ tg_tps=_number_or_none(data, "tg_tps"),
136
+ pp_tps=_number_or_none(data, "pp_tps"),
137
+ measured=measured,
138
+ fingerprint=dict(fingerprint),
139
+ timestamp=timestamp,
140
+ bench=list(bench),
141
+ validated=validated,
142
+ )
143
+
144
+
145
+ def _config_from_dict(data: object) -> Config:
146
+ if not isinstance(data, dict):
147
+ raise _InvalidConfigError("top level")
148
+ host = data.get("host", DEFAULT_HOST)
149
+ if not isinstance(host, str):
150
+ raise _InvalidConfigError("host")
151
+ raw_profiles = data.get("profiles", {})
152
+ if not isinstance(raw_profiles, dict):
153
+ raise _InvalidConfigError("profiles")
154
+ return Config(
155
+ ollama_path=_str_or_none(data, "ollama_path"),
156
+ default_model=_str_or_none(data, "default_model"),
157
+ llama_server=_str_or_none(data, "llama_server"),
158
+ llama_bench=_str_or_none(data, "llama_bench"),
159
+ host=host,
160
+ port=_int(data, "port", DEFAULT_PORT),
161
+ device=_str_or_none(data, "device"),
162
+ profiles={str(k): _profile_from_dict(v) for k, v in raw_profiles.items()},
163
+ extra={k: v for k, v in data.items() if k not in _KNOWN_KEYS},
164
+ )
165
+
166
+
167
+ def _to_dict(cfg: Config) -> dict[str, Any]:
168
+ data: dict[str, Any] = dict(cfg.extra)
169
+ for name in _KNOWN_KEYS:
170
+ value = getattr(cfg, name)
171
+ if name == "profiles":
172
+ value = {k: vars(p).copy() for k, p in value.items()}
173
+ data[name] = value
174
+ return data
175
+
176
+
177
+ def _back_up(path: Path) -> None:
178
+ backup = path.with_name(path.name + BACKUP_SUFFIX)
179
+ try:
180
+ Path(path).replace(backup)
181
+ except OSError:
182
+ log.warning("Could not back up corrupt config %s", path)
183
+ log.debug("Backup failure details", exc_info=True)
184
+ else:
185
+ log.warning("Corrupt config moved to %s; starting fresh", backup)
186
+
187
+
188
+ def load(base: Path | None = None) -> Config | None:
189
+ """Load the config.
190
+
191
+ A corrupt or schema-invalid file is moved to ``config.json.bak`` and treated as absent. A failure to *read* the
192
+ file (permissions, a locked file...) says nothing about its content, so the ``OSError`` propagates and the file
193
+ stays put.
194
+
195
+ Args:
196
+ base: Storage directory; ``None`` resolves ``constants.home()`` at call time.
197
+
198
+ Returns:
199
+ Config | None: The config, or ``None`` on first run (or after a corrupt-file backup).
200
+ """
201
+ path = config_file(base)
202
+ if not path.exists():
203
+ return None
204
+ try:
205
+ cfg = _config_from_dict(json.loads(path.read_text(encoding="utf-8")))
206
+ except ValueError as exc: # JSON, unicode and schema errors (a read OSError is not corruption and propagates)
207
+ log.warning("Config %s is unreadable or invalid (%s)", path, exc)
208
+ log.debug("Config load failure details", exc_info=True)
209
+ if path.is_file():
210
+ _back_up(path)
211
+ return None
212
+ return cfg
213
+
214
+
215
+ def save(cfg: Config, base: Path | None = None) -> None:
216
+ """Atomically write the config (temp file in the same directory, then ``os.replace``).
217
+
218
+ Args:
219
+ cfg: The configuration to persist.
220
+ base: Storage directory; ``None`` resolves ``constants.home()`` at call time.
221
+ """
222
+ path = config_file(base)
223
+ path.parent.mkdir(parents=True, exist_ok=True)
224
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
225
+ try:
226
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
227
+ json.dump(_to_dict(cfg), fh, indent=2)
228
+ fh.write("\n")
229
+ Path(tmp_name).replace(path)
230
+ except BaseException:
231
+ with contextlib.suppress(OSError):
232
+ Path(tmp_name).unlink()
233
+ raise
@@ -0,0 +1,42 @@
1
+ """Default configuration constants for ollama2cpp.
2
+
3
+ Every value can be overridden by a CLI option or an environment variable.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from pathlib import Path
10
+
11
+ # --- Local storage -----------------------------------------------------------
12
+ DEFAULT_PATH = Path.home() / ".ollama2cpp"
13
+ CONFIG_FILENAME = "config.json"
14
+ PID_FILENAME = "server.pid"
15
+
16
+ # --- llama-server defaults ---------------------------------------------------
17
+ DEFAULT_HOST = "127.0.0.1"
18
+ DEFAULT_PORT = 8080
19
+ DEFAULT_CTX = 8192
20
+
21
+ # --- Process exit codes ------------------------------------------------------
22
+ EXIT_INTERRUPTED = 130 # the conventional exit code of a process ended by Ctrl-C
23
+
24
+ # --- Environment variable names ----------------------------------------------
25
+ ENV_OLLAMA_MODELS = "OLLAMA_MODELS"
26
+ ENV_OLLAMA_MODEL = "OLLAMA_MODEL"
27
+ ENV_HOME = "OLLAMA2CPP_HOME"
28
+
29
+ # --- Installation ------------------------------------------------------------
30
+ WINGET_ID = "ggml.llamacpp"
31
+
32
+
33
+ def home() -> Path:
34
+ """Return the ollama2cpp storage directory.
35
+
36
+ The environment is read at call time, so tests and callers can override it.
37
+
38
+ Returns:
39
+ Path: ``$OLLAMA2CPP_HOME`` when set and non-empty, else ``DEFAULT_PATH``.
40
+ """
41
+ override = os.environ.get(ENV_HOME)
42
+ return Path(override) if override else DEFAULT_PATH
ollama2cpp/free_cmd.py ADDED
@@ -0,0 +1,179 @@
1
+ """The ``free`` command: stop Ollama and our own server so the GPU memory they hold is released.
2
+
3
+ No CLI parsing lives here (see ``__main__``); :func:`run_free` returns the process exit code. Only Ollama's own
4
+ processes (matched by exact executable name) and the server recorded in our pid file are ever stopped.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import time
11
+ from collections.abc import Sequence
12
+
13
+ import psutil
14
+
15
+ from ollama2cpp import constants, optimizer, server, ui
16
+ from ollama2cpp.commands import find_server, peek_config, pick_device, server_endpoint
17
+ from ollama2cpp.config import Config
18
+ from ollama2cpp.hardware import Device
19
+
20
+ __all__ = ["OLLAMA_PROCESS_NAMES", "find_ollama_processes", "run_free", "stop_processes"]
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ OLLAMA_PROCESS_NAMES = frozenset(
25
+ {"ollama", "ollama.exe", "ollama app.exe", "ollama_llama_server", "ollama_llama_server.exe"}
26
+ )
27
+ _TRAY_PREFIX = "ollama app" # the Windows tray app restarts the server, so it must be stopped first
28
+ KILL_GRACE = 3.0
29
+ FREE_WAIT_S = 10.0 # how long to wait for the driver to hand the VRAM back
30
+ FREE_POLL_S = 0.5
31
+ HOLD_TOLERANCE_MIB = 1024 # other processes may hold this much VRAM (a desktop session) without a warning
32
+
33
+
34
+ def find_ollama_processes() -> list[psutil.Process]:
35
+ """List the running Ollama processes (server, runners and the Windows tray app).
36
+
37
+ Returns:
38
+ list[psutil.Process]: Matching processes, the tray app first so it cannot respawn the server.
39
+ """
40
+ found: list[tuple[bool, psutil.Process]] = []
41
+ for process in psutil.process_iter():
42
+ try:
43
+ name = process.name().lower()
44
+ except psutil.Error:
45
+ continue
46
+ if name in OLLAMA_PROCESS_NAMES:
47
+ found.append((not name.startswith(_TRAY_PREFIX), process))
48
+ found.sort(key=lambda item: item[0]) # stable: only the tray app moves
49
+ return [process for _, process in found]
50
+
51
+
52
+ def stop_processes(procs: Sequence[psutil.Process], timeout: float = 10.0) -> list[psutil.Process]:
53
+ """Terminate processes in the given order, then kill the ones still alive after ``timeout``.
54
+
55
+ Args:
56
+ procs: Processes to stop (already verified as Ollama's).
57
+ timeout: Seconds to wait after terminate before killing.
58
+
59
+ Returns:
60
+ list[psutil.Process]: The processes that could not be stopped (empty on success).
61
+ """
62
+ survivors: list[psutil.Process] = []
63
+ pending: list[psutil.Process] = []
64
+ for process in procs:
65
+ try:
66
+ process.terminate()
67
+ except psutil.NoSuchProcess:
68
+ continue
69
+ except psutil.AccessDenied:
70
+ logger.warning("Access denied stopping pid %s", process.pid)
71
+ survivors.append(process)
72
+ continue
73
+ pending.append(process)
74
+ _gone, alive = psutil.wait_procs(pending, timeout=timeout)
75
+ killed: list[psutil.Process] = []
76
+ for process in alive:
77
+ try:
78
+ process.kill()
79
+ except psutil.NoSuchProcess:
80
+ continue
81
+ except psutil.AccessDenied:
82
+ survivors.append(process)
83
+ continue
84
+ killed.append(process)
85
+ _gone, still_alive = psutil.wait_procs(killed, timeout=KILL_GRACE)
86
+ return [*survivors, *still_alive]
87
+
88
+
89
+ # --- run -----------------------------------------------------------------------------------------------------------
90
+
91
+
92
+ def _settled_device(cfg: Config | None) -> Device | None:
93
+ """Read the device until its free memory stops changing (or ``FREE_WAIT_S`` passes); None when there is no GPU."""
94
+ deadline = time.monotonic() + FREE_WAIT_S
95
+ previous: Device | None = None
96
+ while True:
97
+ device = pick_device(cfg, find_server(cfg))
98
+ if device is None or device.free_mib <= 0 or (previous is not None and device.free_mib == previous.free_mib):
99
+ return device
100
+ if time.monotonic() >= deadline:
101
+ return device
102
+ previous = device
103
+ time.sleep(FREE_POLL_S)
104
+
105
+
106
+ def _show_vram(before: Device | None, after: Device | None, *, ollama_running: bool = False) -> None:
107
+ """Print free VRAM before and after, and say who still holds a lot of it.
108
+
109
+ Args:
110
+ before: The device before anything was stopped.
111
+ after: The device once the memory settled.
112
+ ollama_running: Ollama is still running (declined or could not be stopped), so it is the likely holder.
113
+ """
114
+ if before is None or after is None:
115
+ ui.show_notice("info", "No GPU detected; nothing to measure.")
116
+ return
117
+ if before.free_mib <= 0 or after.free_mib <= 0: # 0 means the backend does not report free memory
118
+ ui.show_notice("info", f"Free VRAM is unknown (the backend does not report it); {after.total_mib} MiB total.")
119
+ return
120
+ freed = f"{before.free_mib} -> {after.free_mib}" if before.free_mib != after.free_mib else str(after.free_mib)
121
+ ui.show_notice("info", f"VRAM free: {freed} MiB of {after.total_mib} MiB ({after.name}).")
122
+ held = after.total_mib - after.free_mib
123
+ if held <= HOLD_TOLERANCE_MIB:
124
+ return
125
+ if ollama_running:
126
+ ui.show_notice("info", f"{held} MiB of VRAM is still in use; Ollama is still running.")
127
+ else:
128
+ ui.show_notice(
129
+ "warn",
130
+ f"{held} MiB of VRAM is still in use by other processes (not Ollama or ollama2cpp); they were left alone.",
131
+ )
132
+
133
+
134
+ def _describe(process: psutil.Process) -> str:
135
+ try:
136
+ return f"{process.name()} ({process.pid})"
137
+ except psutil.Error:
138
+ return f"pid {process.pid}"
139
+
140
+
141
+ def run_free(*, assume_yes: bool = False) -> int:
142
+ """Unload Ollama's models, stop Ollama and our own server, and report the VRAM that came back.
143
+
144
+ Declining the question leaves Ollama running; our own server is stopped regardless. Processes that are not
145
+ Ollama's or ours are never touched.
146
+
147
+ Args:
148
+ assume_yes: Do not ask before stopping Ollama.
149
+
150
+ Returns:
151
+ int: 0 on success or when there was nothing to stop, 1 when an Ollama process could not be stopped.
152
+ """
153
+ cfg, _state = peek_config()
154
+ before = pick_device(cfg, find_server(cfg))
155
+ procs = find_ollama_processes()
156
+ ours = server.describe_running(*server_endpoint(cfg), constants.home())[0] == "ours"
157
+ if not procs and not ours:
158
+ ui.show_notice("info", "Nothing to stop: Ollama and the ollama2cpp server are not running.")
159
+ _show_vram(before, before)
160
+ return 0
161
+ survivors: list[psutil.Process] = []
162
+ ollama_left = False
163
+ if procs:
164
+ if ui.confirm(f"Stop Ollama ({len(procs)} processes)?", assume_yes=assume_yes, default=False):
165
+ optimizer.unload_ollama() # False only means Ollama is unreachable; its processes are stopped anyway
166
+ survivors = stop_processes(procs)
167
+ if not survivors:
168
+ ui.show_notice("ok", "Stopped Ollama.")
169
+ else:
170
+ ollama_left = True
171
+ ui.show_notice("info", "Left Ollama running.")
172
+ if ours:
173
+ server.stop(constants.home())
174
+ ui.show_notice("ok", "Stopped the ollama2cpp server.")
175
+ if survivors:
176
+ names = ", ".join(_describe(p) for p in survivors)
177
+ ui.show_notice("warn", f"Could not stop: {names}. Close them yourself.")
178
+ _show_vram(before, _settled_device(cfg), ollama_running=ollama_left or bool(survivors))
179
+ return 1 if survivors else 0