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/proc.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Subprocess seam: the only module that launches external processes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shlex
|
|
6
|
+
import subprocess # ruff: ignore[suspicious-subprocess-import]
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
__all__ = ["Handle", "ProcResult", "format_command", "run", "spawn"]
|
|
13
|
+
|
|
14
|
+
Handle = subprocess.Popen[str] # running-process handle, re-exported so other modules need not import subprocess
|
|
15
|
+
|
|
16
|
+
RC_NOT_FOUND = 127
|
|
17
|
+
RC_TIMEOUT = 124
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ProcResult:
|
|
22
|
+
"""Outcome of a finished process.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
returncode: Exit code (127 = executable missing, 124 = timed out).
|
|
26
|
+
stdout: Captured standard output.
|
|
27
|
+
stderr: Captured standard error.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
returncode: int
|
|
31
|
+
stdout: str
|
|
32
|
+
stderr: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _text(value: str | bytes | None) -> str:
|
|
36
|
+
"""Normalise captured output (``TimeoutExpired`` may carry bytes or None).
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
value: Raw captured output.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
str: Decoded text, empty when nothing was captured.
|
|
43
|
+
"""
|
|
44
|
+
if value is None:
|
|
45
|
+
return ""
|
|
46
|
+
return value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def run(argv: Sequence[str], *, timeout: float | None = None) -> ProcResult:
|
|
50
|
+
"""Run a command to completion without ever raising.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
argv: Command and arguments (never passed through a shell).
|
|
54
|
+
timeout: Seconds before the process is killed.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
ProcResult: Captured output; ``returncode`` is 127 if the executable is missing, 124 on timeout.
|
|
58
|
+
"""
|
|
59
|
+
try:
|
|
60
|
+
# argv list, shell=False, caller-controlled executable
|
|
61
|
+
done = subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true]
|
|
62
|
+
list(argv),
|
|
63
|
+
capture_output=True,
|
|
64
|
+
text=True,
|
|
65
|
+
encoding="utf-8",
|
|
66
|
+
errors="replace",
|
|
67
|
+
timeout=timeout,
|
|
68
|
+
check=False,
|
|
69
|
+
)
|
|
70
|
+
except FileNotFoundError as exc:
|
|
71
|
+
return ProcResult(RC_NOT_FOUND, "", str(exc))
|
|
72
|
+
except subprocess.TimeoutExpired as exc:
|
|
73
|
+
return ProcResult(RC_TIMEOUT, _text(exc.stdout), _text(exc.stderr))
|
|
74
|
+
except OSError as exc:
|
|
75
|
+
return ProcResult(RC_NOT_FOUND, "", str(exc))
|
|
76
|
+
return ProcResult(done.returncode, done.stdout, done.stderr)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def spawn(argv: Sequence[str], *, log_path: Path | None = None, detach: bool = False) -> subprocess.Popen[str]:
|
|
80
|
+
"""Start a long-running process without waiting for it.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
argv: Command and arguments (never passed through a shell).
|
|
84
|
+
log_path: When given, stdout and stderr are appended to this file (parent dirs are created).
|
|
85
|
+
detach: Start in a new session / process group so it outlives the parent.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
subprocess.Popen[str]: The running process handle.
|
|
89
|
+
"""
|
|
90
|
+
stdout = stderr = subprocess.DEVNULL
|
|
91
|
+
log_file = None
|
|
92
|
+
if log_path is not None:
|
|
93
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
log_file = log_path.open("a", encoding="utf-8")
|
|
95
|
+
stdout, stderr = log_file, subprocess.STDOUT
|
|
96
|
+
flags = 0
|
|
97
|
+
new_session = False
|
|
98
|
+
if detach:
|
|
99
|
+
if sys.platform == "win32":
|
|
100
|
+
flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
|
|
101
|
+
else:
|
|
102
|
+
new_session = True
|
|
103
|
+
try:
|
|
104
|
+
# argv list, shell=False, caller-controlled executable
|
|
105
|
+
return subprocess.Popen( # ruff: ignore[subprocess-without-shell-equals-true]
|
|
106
|
+
list(argv),
|
|
107
|
+
stdin=subprocess.DEVNULL,
|
|
108
|
+
stdout=stdout,
|
|
109
|
+
stderr=stderr,
|
|
110
|
+
text=True,
|
|
111
|
+
creationflags=flags,
|
|
112
|
+
start_new_session=new_session,
|
|
113
|
+
)
|
|
114
|
+
finally:
|
|
115
|
+
if log_file is not None:
|
|
116
|
+
log_file.close()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def format_command(argv: Sequence[str]) -> str:
|
|
120
|
+
"""Render ``argv`` as a copy-pasteable command line for the host shell.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
argv: Command and arguments.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
str: Windows quoting (``list2cmdline``) on Windows, POSIX quoting (``shlex.join``) elsewhere.
|
|
127
|
+
"""
|
|
128
|
+
if sys.platform == "win32":
|
|
129
|
+
return subprocess.list2cmdline(list(argv))
|
|
130
|
+
return shlex.join(argv)
|
ollama2cpp/selector.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Classify installed Ollama models and pick the best one for the available memory.
|
|
2
|
+
|
|
3
|
+
Memory estimate (``need_mib``): ``ceil((weights + kv_cache) * HEADROOM_FACTOR / MiB + OVERHEAD_MIB)``.
|
|
4
|
+
|
|
5
|
+
``weights`` is the manifest's model-layer size (:attr:`OllamaModel.size`), a single deliberate choice: it is the real
|
|
6
|
+
model size even when the blob on disk is not that large (tests use tiny blobs); the GGUF header only supplies the
|
|
7
|
+
layer and head counts for the KV-cache estimate.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Literal
|
|
18
|
+
|
|
19
|
+
from ollama2cpp.constants import DEFAULT_CTX
|
|
20
|
+
from ollama2cpp.gguf import GgufError, GgufInfo, kv_cache_bytes, read_gguf
|
|
21
|
+
from ollama2cpp.ollama import OllamaModel
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
HEADROOM_FACTOR = 1.10 # compute buffers and fragmentation on top of weights + KV cache
|
|
26
|
+
OVERHEAD_MIB = 512 # fixed runtime overhead (CUDA/Vulkan context, scratch buffers)
|
|
27
|
+
# GGUF ``general.architecture`` values that are not text LLMs and so are never chat candidates:
|
|
28
|
+
# clip - vision/projector encoders (CLIP, multimodal projector GGUFs)
|
|
29
|
+
# mmproj - llama.cpp's name for multimodal projector files
|
|
30
|
+
# whisper - speech-to-text models
|
|
31
|
+
# The real store's audio model (lfm3-audio) reports the text backbone arch ``lfm3``, so it is caught by name instead.
|
|
32
|
+
NON_LLM_ARCHITECTURES = frozenset({"clip", "mmproj", "whisper"})
|
|
33
|
+
# Whole-token match (tokens split on any non-alphanumeric: ``-``, ``_``, ``.``, ``:``, ``/``) for names of speech/audio
|
|
34
|
+
# models that llama-server cannot serve as text chat. Whole tokens, not substrings, so ``watts-chat`` or
|
|
35
|
+
# ``chat:audiophile`` are not caught. Trade-off: a glued name such as ``kokorotts`` is no longer detected by name.
|
|
36
|
+
NON_TEXT_NAME_RE = re.compile(r"(?<![a-z0-9])(?:audio|whisper|tts|speech)(?![a-z0-9])")
|
|
37
|
+
_MIB = 1024 * 1024
|
|
38
|
+
|
|
39
|
+
Kind = Literal["chat", "embedding", "unsupported"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Candidate:
|
|
44
|
+
"""An installed model with its classification and estimated memory need."""
|
|
45
|
+
|
|
46
|
+
model: OllamaModel
|
|
47
|
+
gguf: GgufInfo | None
|
|
48
|
+
kind: Kind
|
|
49
|
+
need_mib: int
|
|
50
|
+
reason: str = ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _unsupported(model: OllamaModel, reason: str, info: GgufInfo | None = None) -> Candidate:
|
|
54
|
+
"""Build an ``unsupported`` candidate (``need_mib`` is ``0``: nothing was estimated)."""
|
|
55
|
+
return Candidate(model, info, "unsupported", 0, reason)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def estimate_need_mib(model: OllamaModel, info: GgufInfo, ctx: int) -> int:
|
|
59
|
+
"""Estimate the memory needed to run ``model`` at ``ctx`` tokens.
|
|
60
|
+
|
|
61
|
+
Known limitation: the KV-cache term ignores sliding-window attention, so it over-estimates such models (the
|
|
62
|
+
selector is conservative; ``choose_best`` falls back to the smallest chat model with ``fits=False``).
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
model: The installed model (its manifest size is the weight size).
|
|
66
|
+
info: Parsed GGUF facts.
|
|
67
|
+
ctx: Context length in tokens.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
int: Estimated MiB, rounded up.
|
|
71
|
+
"""
|
|
72
|
+
total = model.size + kv_cache_bytes(info, ctx)
|
|
73
|
+
return math.ceil(total * HEADROOM_FACTOR / _MIB + OVERHEAD_MIB)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _classify(model: OllamaModel, ctx: int) -> Candidate:
|
|
77
|
+
"""Classify one model; may raise (see :func:`classify`)."""
|
|
78
|
+
if model.blob_path is None:
|
|
79
|
+
return _unsupported(model, "no model layer")
|
|
80
|
+
if not model.blob_exists:
|
|
81
|
+
return _unsupported(model, "missing blob")
|
|
82
|
+
info = read_gguf(model.blob_path)
|
|
83
|
+
need = estimate_need_mib(model, info, ctx)
|
|
84
|
+
name = model.name.lower()
|
|
85
|
+
if info.is_embedding or "embed" in name: # embedding wins over the non-text rules below
|
|
86
|
+
return Candidate(model, info, "embedding", need)
|
|
87
|
+
if info.architecture in NON_LLM_ARCHITECTURES:
|
|
88
|
+
return _unsupported(model, f"non-LLM architecture {info.architecture!r} (not a text chat model)", info)
|
|
89
|
+
if NON_TEXT_NAME_RE.search(name):
|
|
90
|
+
return _unsupported(model, "audio model (not a text chat model)", info)
|
|
91
|
+
return Candidate(model, info, "chat", need)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def classify(model: OllamaModel, ctx: int = DEFAULT_CTX) -> Candidate:
|
|
95
|
+
"""Classify a model as chat, embedding or unsupported and estimate its memory need.
|
|
96
|
+
|
|
97
|
+
Never raises: any failure yields an ``unsupported`` candidate whose ``reason`` carries the message.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
model: The installed model.
|
|
101
|
+
ctx: Context length in tokens used for the KV-cache estimate.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Candidate: The classification.
|
|
105
|
+
"""
|
|
106
|
+
try:
|
|
107
|
+
return _classify(model, ctx)
|
|
108
|
+
except (GgufError, OSError) as exc:
|
|
109
|
+
log.warning("Cannot read model %s: %s", model.name, exc)
|
|
110
|
+
return _unsupported(model, str(exc))
|
|
111
|
+
except Exception as exc:
|
|
112
|
+
log.warning("Unexpected error classifying model %s: %s", model.name, exc)
|
|
113
|
+
return _unsupported(model, f"unexpected error: {exc}")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def classify_all(models: Sequence[OllamaModel], ctx: int = DEFAULT_CTX) -> list[Candidate]:
|
|
117
|
+
"""Classify every model; one bad model becomes an ``unsupported`` row instead of raising.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
models: Installed models.
|
|
121
|
+
ctx: Context length in tokens used for the KV-cache estimate.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
list[Candidate]: One candidate per model, in input order.
|
|
125
|
+
"""
|
|
126
|
+
return [classify(model, ctx) for model in models]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def choose_best(cands: Sequence[Candidate], vram_mib: int, ram_mib: int = 0) -> tuple[Candidate, bool] | None:
|
|
130
|
+
"""Pick the largest chat model that fits, else the smallest chat model.
|
|
131
|
+
|
|
132
|
+
The memory budget is ``vram_mib``, or ``ram_mib`` on a CPU-only host (``vram_mib == 0``). Ties are broken by
|
|
133
|
+
model name so the choice is deterministic.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
cands: Classified candidates; only ``kind == "chat"`` is eligible.
|
|
137
|
+
vram_mib: Free GPU memory in MiB (``0`` when there is no GPU).
|
|
138
|
+
ram_mib: Available system RAM in MiB, used as the budget when ``vram_mib`` is ``0``.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
tuple[Candidate, bool] | None: ``(candidate, fits)``, or ``None`` when there is no chat model.
|
|
142
|
+
"""
|
|
143
|
+
chats = [c for c in cands if c.kind == "chat"]
|
|
144
|
+
if not chats:
|
|
145
|
+
return None
|
|
146
|
+
budget = vram_mib if vram_mib > 0 else ram_mib
|
|
147
|
+
fitting = [c for c in chats if c.need_mib <= budget]
|
|
148
|
+
if fitting:
|
|
149
|
+
return min(fitting, key=lambda c: (-c.need_mib, c.model.name)), True
|
|
150
|
+
return min(chats, key=lambda c: (c.need_mib, c.model.name)), False
|