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/gguf.py ADDED
@@ -0,0 +1,357 @@
1
+ """Minimal GGUF metadata reader (no dependencies).
2
+
3
+ Only the header's key/value metadata is parsed (little-endian GGUF v2/v3); tensor info is never read. Arrays are
4
+ skipped without materialising them, except short integer arrays (per-layer head counts), which are kept.
5
+
6
+ Metadata keys are looked up under the architecture prefix, e.g. ``llama.block_count`` or ``gemma4.block_count``.
7
+ Every malformed input raises :class:`GgufError`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import struct
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import IO, Any
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ GGUF_MAGIC = b"GGUF"
21
+ SUPPORTED_VERSIONS = frozenset({2, 3})
22
+ EMBEDDING_ARCHITECTURES = frozenset({"bert", "nomic-bert", "modern-bert", "jina-bert-v2"})
23
+
24
+ _T_STRING = 8
25
+ _T_ARRAY = 9
26
+ _MAX_DEPTH = 4
27
+ _MAX_KEPT_ARRAY = 4096 # per-layer arrays are far shorter than this
28
+ _CHUNK = 1 << 20
29
+ _MAX_STRING_BYTES = 64 << 20 # no real metadata string (chat template, name) is anywhere near this
30
+ _U64 = struct.Struct("<Q")
31
+ _MIN_KV_BYTES = 12 # key length (8) + value type (4)
32
+
33
+ # value type id -> struct format of the fixed-size scalar
34
+ _SCALAR_FORMATS: dict[int, str] = {
35
+ 0: "<B",
36
+ 1: "<b",
37
+ 2: "<H",
38
+ 3: "<h",
39
+ 4: "<I",
40
+ 5: "<i",
41
+ 6: "<f",
42
+ 7: "<?",
43
+ 10: "<Q",
44
+ 11: "<q",
45
+ 12: "<d",
46
+ }
47
+ _SCALAR_SIZES = {t: struct.calcsize(fmt) for t, fmt in _SCALAR_FORMATS.items()}
48
+ _INT_TYPES = frozenset({0, 1, 2, 3, 4, 5, 10, 11})
49
+
50
+ _REQUIRED_SUFFIXES = (
51
+ "block_count",
52
+ "context_length",
53
+ "embedding_length",
54
+ "attention.head_count",
55
+ )
56
+
57
+
58
+ class GgufError(ValueError):
59
+ """Raised when a file is not a readable GGUF file."""
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class GgufInfo:
64
+ """Facts about a GGUF model needed to plan a llama-server launch.
65
+
66
+ ``head_count`` and ``head_count_kv`` are single ints. Newer architectures store them as per-layer arrays; in that
67
+ case the maximum is used, which over-estimates (never under-estimates) the KV cache.
68
+ """
69
+
70
+ architecture: str
71
+ block_count: int
72
+ context_length: int
73
+ embedding_length: int
74
+ head_count: int
75
+ head_count_kv: int
76
+ key_length: int | None
77
+ file_type: int | None
78
+ is_embedding: bool
79
+ file_size: int
80
+
81
+
82
+ class _Reader:
83
+ """Bounded little-endian reader over a binary file."""
84
+
85
+ def __init__(self, fh: IO[bytes], size: int) -> None:
86
+ self._fh = fh
87
+ self.size = size
88
+
89
+ def remaining(self) -> int:
90
+ """Return the number of bytes left in the file."""
91
+ return self.size - self._fh.tell()
92
+
93
+ def read(self, n: int) -> bytes:
94
+ """Read exactly ``n`` bytes.
95
+
96
+ Args:
97
+ n: Byte count.
98
+
99
+ Returns:
100
+ The bytes read.
101
+
102
+ Raises:
103
+ GgufError: If fewer than ``n`` bytes remain.
104
+ """
105
+ if n < 0 or n > self.remaining():
106
+ raise GgufError("truncated GGUF file")
107
+ return self._fh.read(n)
108
+
109
+ def skip(self, n: int) -> None:
110
+ """Skip ``n`` bytes.
111
+
112
+ Args:
113
+ n: Byte count.
114
+
115
+ Raises:
116
+ GgufError: If fewer than ``n`` bytes remain.
117
+ """
118
+ if n < 0 or n > self.remaining():
119
+ raise GgufError("truncated GGUF file")
120
+ self._fh.seek(n, 1)
121
+
122
+ def unpack(self, fmt: str) -> Any:
123
+ """Unpack one value of struct format ``fmt``.
124
+
125
+ Args:
126
+ fmt: A little-endian struct format with a single item.
127
+
128
+ Returns:
129
+ The unpacked value.
130
+ """
131
+ return struct.unpack(fmt, self.read(struct.calcsize(fmt)))[0]
132
+
133
+ def string(self) -> str:
134
+ """Read a length-prefixed UTF-8 string.
135
+
136
+ Returns:
137
+ The decoded string.
138
+
139
+ Raises:
140
+ GgufError: On a length above the cap, truncation or invalid UTF-8.
141
+ """
142
+ length = self.unpack("<Q")
143
+ if length > _MAX_STRING_BYTES:
144
+ raise GgufError(f"GGUF string of {length} bytes exceeds the {_MAX_STRING_BYTES} byte limit")
145
+ raw = self.read(length)
146
+ try:
147
+ return raw.decode("utf-8")
148
+ except UnicodeDecodeError as exc:
149
+ raise GgufError("invalid UTF-8 in GGUF string") from exc
150
+
151
+ def skip_strings(self, count: int) -> None:
152
+ """Skip ``count`` consecutive length-prefixed strings using buffered reads (fast for token tables).
153
+
154
+ Args:
155
+ count: Number of strings to skip.
156
+
157
+ Raises:
158
+ GgufError: If a string runs past the end of the file.
159
+ """
160
+ fh = self._fh
161
+ buf = b""
162
+ off = 0
163
+ done = 0
164
+ while done < count:
165
+ if len(buf) - off < _U64.size:
166
+ fh.seek(off - len(buf), 1) # drop the unread tail of the buffer
167
+ buf = fh.read(_CHUNK)
168
+ off = 0
169
+ if len(buf) < _U64.size:
170
+ raise GgufError("truncated GGUF file")
171
+ end = off + _U64.size + _U64.unpack_from(buf, off)[0]
172
+ done += 1
173
+ if end <= len(buf):
174
+ off = end
175
+ continue
176
+ overshoot = end - len(buf) # the string extends past the buffer
177
+ if overshoot > self.remaining():
178
+ raise GgufError("truncated GGUF file")
179
+ fh.seek(overshoot, 1)
180
+ buf = b""
181
+ off = 0
182
+ fh.seek(off - len(buf), 1)
183
+
184
+
185
+ def _skip_array(rd: _Reader, depth: int) -> None:
186
+ """Skip an array whose element type and count are next in the stream."""
187
+ _skip_elements(rd, rd.unpack("<I"), rd.unpack("<Q"), depth)
188
+
189
+
190
+ def _skip_elements(rd: _Reader, elem_type: int, count: int, depth: int) -> None:
191
+ """Skip ``count`` array elements of ``elem_type``."""
192
+ if depth > _MAX_DEPTH:
193
+ raise GgufError("GGUF arrays nested too deeply")
194
+ if elem_type in _SCALAR_SIZES:
195
+ rd.skip(count * _SCALAR_SIZES[elem_type])
196
+ return
197
+ if elem_type not in {_T_STRING, _T_ARRAY}:
198
+ raise GgufError(f"unknown GGUF value type {elem_type}")
199
+ if count > rd.remaining() // 8: # every string / nested array costs at least 8 bytes
200
+ raise GgufError("GGUF array count exceeds file size")
201
+ if elem_type == _T_STRING:
202
+ rd.skip_strings(count)
203
+ return
204
+ for _ in range(count):
205
+ _skip_array(rd, depth + 1)
206
+
207
+
208
+ def _read_value(rd: _Reader, vtype: int) -> Any:
209
+ """Read one metadata value; arrays come back as short numeric lists, otherwise ``None`` (skipped)."""
210
+ if vtype in _SCALAR_FORMATS:
211
+ return rd.unpack(_SCALAR_FORMATS[vtype])
212
+ if vtype == _T_STRING:
213
+ return rd.string()
214
+ if vtype != _T_ARRAY:
215
+ raise GgufError(f"unknown GGUF value type {vtype}")
216
+ elem_type = rd.unpack("<I")
217
+ count = rd.unpack("<Q")
218
+ if elem_type in _INT_TYPES and count <= _MAX_KEPT_ARRAY:
219
+ if count * _SCALAR_SIZES[elem_type] > rd.remaining():
220
+ raise GgufError("GGUF array count exceeds file size")
221
+ fmt = _SCALAR_FORMATS[elem_type]
222
+ return [rd.unpack(fmt) for _ in range(count)]
223
+ _skip_elements(rd, elem_type, count, 1)
224
+ return None
225
+
226
+
227
+ def _as_int(info: dict[str, Any], key: str) -> int | None:
228
+ """Return ``info[key]`` as an int (max of a non-empty int array), or ``None`` when absent."""
229
+ if key not in info:
230
+ return None
231
+ value = info[key]
232
+ if isinstance(value, list) and value:
233
+ value = max(value)
234
+ if isinstance(value, bool) or not isinstance(value, int):
235
+ raise GgufError(f"GGUF key {key!r} is not an integer")
236
+ return value
237
+
238
+
239
+ def _read_metadata(rd: _Reader) -> dict[str, Any]:
240
+ """Read the header and return every metadata key/value pair (large arrays are skipped, not kept).
241
+
242
+ The whole KV section is scanned: ``general.file_type`` follows the tokenizer tables in real files. String
243
+ arrays are skipped with buffered reads, so a 260k-token vocabulary costs roughly 0.1 s.
244
+ """
245
+ if rd.read(4) != GGUF_MAGIC:
246
+ raise GgufError("bad GGUF magic")
247
+ version = rd.unpack("<I")
248
+ if version not in SUPPORTED_VERSIONS:
249
+ raise GgufError(f"unsupported GGUF version {version}")
250
+ rd.unpack("<Q") # tensor count: tensor info is not read
251
+ kv_count = rd.unpack("<Q")
252
+ if kv_count > rd.remaining() // _MIN_KV_BYTES:
253
+ raise GgufError("GGUF key/value count exceeds file size")
254
+ kv: dict[str, Any] = {}
255
+ for _ in range(kv_count):
256
+ key = rd.string()
257
+ kv[key] = _read_value(rd, rd.unpack("<I"))
258
+ return kv
259
+
260
+
261
+ def _build_info(kv: dict[str, Any], file_size: int) -> GgufInfo:
262
+ """Turn raw metadata into a :class:`GgufInfo`."""
263
+ arch = kv.get("general.architecture")
264
+ if not isinstance(arch, str) or not arch:
265
+ raise GgufError("GGUF is missing general.architecture")
266
+ ints: dict[str, int] = {}
267
+ for suffix in _REQUIRED_SUFFIXES:
268
+ value = _as_int(kv, f"{arch}.{suffix}")
269
+ if value is None:
270
+ raise GgufError(f"GGUF is missing {arch}.{suffix}")
271
+ ints[suffix] = value
272
+ if ints["attention.head_count"] < 1:
273
+ raise GgufError(f"GGUF {arch}.attention.head_count must be positive")
274
+ head_count = ints["attention.head_count"]
275
+ head_count_kv = _as_int(kv, f"{arch}.attention.head_count_kv")
276
+ return GgufInfo(
277
+ architecture=arch,
278
+ block_count=ints["block_count"],
279
+ context_length=ints["context_length"],
280
+ embedding_length=ints["embedding_length"],
281
+ head_count=head_count,
282
+ head_count_kv=head_count_kv if head_count_kv and head_count_kv > 0 else head_count,
283
+ key_length=_as_int(kv, f"{arch}.attention.key_length"),
284
+ file_type=_as_int(kv, "general.file_type"),
285
+ is_embedding=f"{arch}.pooling_type" in kv or arch in EMBEDDING_ARCHITECTURES,
286
+ file_size=file_size,
287
+ )
288
+
289
+
290
+ def read_gguf(path: Path) -> GgufInfo:
291
+ """Read the metadata header of a GGUF file.
292
+
293
+ Args:
294
+ path: Path to the GGUF file (opened read-only).
295
+
296
+ Returns:
297
+ The parsed model facts.
298
+
299
+ Raises:
300
+ GgufError: If the file is missing, malformed, truncated or lacks required keys.
301
+ """
302
+ try:
303
+ size = path.stat().st_size
304
+ with path.open("rb") as fh:
305
+ kv = _read_metadata(_Reader(fh, size))
306
+ except OSError as exc:
307
+ raise GgufError(f"cannot read {path}: {exc}") from exc
308
+ return _build_info(kv, size)
309
+
310
+
311
+ def head_dim(info: GgufInfo) -> int:
312
+ """Return the attention head dimension.
313
+
314
+ Args:
315
+ info: Parsed GGUF facts.
316
+
317
+ Returns:
318
+ ``key_length`` when present, else ``embedding_length // head_count``.
319
+ """
320
+ return info.key_length or info.embedding_length // info.head_count
321
+
322
+
323
+ def kv_cache_bytes(info: GgufInfo, ctx: int, bytes_per_elem: float = 2.0) -> int:
324
+ """Estimate the KV cache size.
325
+
326
+ Args:
327
+ info: Parsed GGUF facts.
328
+ ctx: Context length in tokens.
329
+ bytes_per_elem: Bytes per cached element (2.0 for f16).
330
+
331
+ Returns:
332
+ ``block_count * 2 * ctx * head_count_kv * head_dim * bytes_per_elem`` as an int.
333
+ """
334
+ return int(info.block_count * 2 * ctx * info.head_count_kv * head_dim(info) * bytes_per_elem)
335
+
336
+
337
+ # llama.cpp ``llama_ftype`` names by value; "-" marks retired numbers.
338
+ _FTYPES = (
339
+ "F32 F16 Q4_0 Q4_1 - - - Q8_0 Q5_0 Q5_1 Q2_K Q3_K_S Q3_K_M Q3_K_L Q4_K_S Q4_K_M Q5_K_S Q5_K_M Q6_K "
340
+ "IQ2_XXS IQ2_XS Q2_K_S IQ3_XS IQ3_XXS IQ1_S IQ4_NL IQ3_S IQ3_M IQ2_S IQ2_M IQ4_XS IQ1_M BF16 "
341
+ "- - - TQ1_0 TQ2_0 MXFP4"
342
+ )
343
+ _FILE_TYPE_NAMES = {n: name for n, name in enumerate(_FTYPES.split()) if name != "-"}
344
+
345
+
346
+ def file_type_name(file_type: int | None) -> str:
347
+ """Name a ``general.file_type`` value (the dominant quantisation of the file).
348
+
349
+ Args:
350
+ file_type: The value from the GGUF header, or None when the file has none.
351
+
352
+ Returns:
353
+ str: ``Q4_K_M``-style name, ``ftype N`` for an unknown value, ``?`` when absent.
354
+ """
355
+ if file_type is None:
356
+ return "?"
357
+ return _FILE_TYPE_NAMES.get(file_type, f"ftype {file_type}")
ollama2cpp/hardware.py ADDED
@@ -0,0 +1,266 @@
1
+ """Hardware probe: GPU devices (via ``llama-server --list-devices`` or ``nvidia-smi``) and host RAM / cores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ import psutil
12
+
13
+ from ollama2cpp import proc
14
+
15
+ __all__ = [
16
+ "Device",
17
+ "HostInfo",
18
+ "best_device",
19
+ "detect_devices",
20
+ "fingerprint",
21
+ "host_info",
22
+ "is_integrated",
23
+ "parse_list_devices",
24
+ "parse_nvidia_smi",
25
+ ]
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ PROBE_TIMEOUT_S = 30.0
30
+ _BYTES_PER_MIB = 1024 * 1024
31
+ _CPU_ID_PREFIX = "CPU"
32
+
33
+ # Conservative integrated-GPU name heuristics (shared system memory, not VRAM). Apple/Metal is deliberately absent.
34
+ _INTEGRATED_NAME_PATTERNS = (
35
+ # AMD: "Radeon(TM) Graphics", "Radeon Graphics", "Radeon(TM) Vega 8 Graphics", "Radeon 780M Graphics".
36
+ re.compile(r"\bRadeon(?:\(TM\))?\s+(?:(?:Vega\s+\d+|\d{3,4}M)\s+)?Graphics\b", re.IGNORECASE),
37
+ # Intel: "UHD Graphics", "Iris(R) Xe Graphics", "HD Graphics".
38
+ re.compile(r"\bIntel\b.*\b(?:UHD|Iris|HD)\b.*\bGraphics\b", re.IGNORECASE),
39
+ # Intel Core Ultra: "Intel(R) Graphics", "Intel(R) Arc(TM) Graphics", "Intel(R) Arc(TM) 140V GPU" (no A/B model).
40
+ re.compile(r"\bIntel(?:\(R\))?\s+Graphics\b", re.IGNORECASE),
41
+ re.compile(r"\bArc(?:\(TM\))?\s+(?:Graphics\b|\d{3}V\b)", re.IGNORECASE),
42
+ )
43
+ # Discrete Intel Arc names carry a model number: "Arc(TM) A770", "Arc(TM) B580", "Arc(TM) A370M", "Arc(TM) Pro A60".
44
+ _DISCRETE_NAME_PATTERN = re.compile(r"\bArc(?:\(TM\))?\s+(?:Pro\s+)?[A-Z]\d{2,3}M?\b", re.IGNORECASE)
45
+
46
+ # " Vulkan0: NVIDIA GeForce RTX 5060 Ti (7891 MiB, 5198 MiB free)"; the free figure is optional.
47
+ _DEVICE_LINE = re.compile(
48
+ r"^\s*(?P<id>[A-Za-z][A-Za-z0-9_]*):\s+(?P<name>.+?)\s+\((?P<total>\d+) MiB(?:, (?P<free>\d+) MiB free)?\)\s*$"
49
+ )
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Device:
54
+ """A compute device that ``llama-server --device`` can target.
55
+
56
+ Attributes:
57
+ id: Device id exactly as ``--device`` accepts it (e.g. ``Vulkan0``, ``CUDA0``).
58
+ name: Human-readable device name.
59
+ total_mib: Total device memory in MiB.
60
+ free_mib: Free device memory in MiB at probe time (0 when unknown).
61
+ """
62
+
63
+ id: str
64
+ name: str
65
+ total_mib: int
66
+ free_mib: int
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class HostInfo:
71
+ """Snapshot of the host's compute resources.
72
+
73
+ Attributes:
74
+ devices: Detected GPU devices (empty on a CPU-only host).
75
+ ram_total_mib: Total system RAM in MiB.
76
+ ram_free_mib: Available system RAM in MiB.
77
+ physical_cores: Physical CPU cores (falls back to the logical count when unknown).
78
+ logical_cores: Logical CPU cores.
79
+ """
80
+
81
+ devices: tuple[Device, ...]
82
+ ram_total_mib: int
83
+ ram_free_mib: int
84
+ physical_cores: int
85
+ logical_cores: int
86
+
87
+
88
+ def _is_cpu(device: Device) -> bool:
89
+ """Tell whether a device is the CPU pseudo-device.
90
+
91
+ Args:
92
+ device: Device to test.
93
+
94
+ Returns:
95
+ bool: True when the id denotes the CPU backend.
96
+ """
97
+ return device.id.upper().startswith(_CPU_ID_PREFIX)
98
+
99
+
100
+ def is_integrated(device: Device) -> bool:
101
+ """Guess whether a device is an integrated GPU that borrows system RAM instead of having its own VRAM.
102
+
103
+ The guess is name-based and conservative. It flags AMD ``Radeon(TM) Graphics`` / ``Radeon Graphics`` /
104
+ ``Radeon(TM) Vega N Graphics`` / ``Radeon 780M Graphics`` style names (no discrete model number) and Intel
105
+ ``UHD`` / ``Iris`` / ``HD`` Graphics, plus the Core Ultra iGPU names (``Intel(R) Graphics``,
106
+ ``Arc(TM) Graphics``, ``Arc(TM) 140V GPU``). Intel Arc names with a model number (``A770``, ``B580``,
107
+ ``Pro A60``), NVIDIA, discrete Radeon (``RX ...``) and Apple/Metal GPUs are never flagged.
108
+ ``llama-server --list-devices`` prints no explicit integrated/UMA marker, so none is read.
109
+
110
+ Args:
111
+ device: Device to classify.
112
+
113
+ Returns:
114
+ bool: True when the name looks like an integrated GPU.
115
+ """
116
+ if _DISCRETE_NAME_PATTERN.search(device.name):
117
+ return False
118
+ return any(pattern.search(device.name) for pattern in _INTEGRATED_NAME_PATTERNS)
119
+
120
+
121
+ def parse_list_devices(text: str) -> list[Device]:
122
+ """Parse the output of ``llama-server --list-devices``.
123
+
124
+ Backend-loading noise and the ``Available devices:`` header are ignored, as is the CPU pseudo-device.
125
+ Never raises: unparseable text yields ``[]``.
126
+
127
+ Args:
128
+ text: Combined stdout and stderr of the command.
129
+
130
+ Returns:
131
+ list[Device]: GPU devices in the order printed.
132
+ """
133
+ devices: list[Device] = []
134
+ for line in text.splitlines():
135
+ match = _DEVICE_LINE.match(line)
136
+ if match is None:
137
+ continue
138
+ free = match["free"]
139
+ device = Device(match["id"], match["name"], int(match["total"]), int(free) if free else 0)
140
+ if not _is_cpu(device):
141
+ devices.append(device)
142
+ return devices
143
+
144
+
145
+ def parse_nvidia_smi(text: str) -> list[Device]:
146
+ """Parse ``nvidia-smi --query-gpu=name,memory.total,memory.free --format=csv,noheader,nounits`` output.
147
+
148
+ Devices get ids ``CUDA0``, ``CUDA1``, ... by row position (best-effort id, only used when ``--list-devices``
149
+ finds no GPU). Never raises: unparseable rows are skipped.
150
+
151
+ Args:
152
+ text: Command output, one ``name, total, free`` row per GPU.
153
+
154
+ Returns:
155
+ list[Device]: One device per valid row.
156
+ """
157
+ devices: list[Device] = []
158
+ for line in text.splitlines():
159
+ parts = [p.strip() for p in line.rsplit(",", 2)]
160
+ if len(parts) != 3 or not parts[0] or not parts[1].isdigit() or not parts[2].isdigit():
161
+ continue
162
+ devices.append(Device(f"CUDA{len(devices)}", parts[0], int(parts[1]), int(parts[2])))
163
+ return devices
164
+
165
+
166
+ def _list_devices(llama_server: Path) -> list[Device]:
167
+ """Ask ``llama-server`` which devices it sees.
168
+
169
+ Args:
170
+ llama_server: Path to the ``llama-server`` executable.
171
+
172
+ Returns:
173
+ list[Device]: Devices found, ``[]`` when the command fails.
174
+ """
175
+ result = proc.run([str(llama_server), "--list-devices"], timeout=PROBE_TIMEOUT_S)
176
+ if result.returncode != 0:
177
+ log.debug("llama-server --list-devices failed (rc=%s)", result.returncode)
178
+ return []
179
+ return parse_list_devices(result.stdout + "\n" + result.stderr)
180
+
181
+
182
+ def _nvidia_smi() -> list[Device]:
183
+ """Query ``nvidia-smi`` for NVIDIA GPUs.
184
+
185
+ Returns:
186
+ list[Device]: Devices found, ``[]`` when the tool is missing or fails.
187
+ """
188
+ argv = ["nvidia-smi", "--query-gpu=name,memory.total,memory.free", "--format=csv,noheader,nounits"]
189
+ result = proc.run(argv, timeout=PROBE_TIMEOUT_S)
190
+ if result.returncode != 0:
191
+ log.debug("nvidia-smi failed (rc=%s)", result.returncode)
192
+ return []
193
+ return parse_nvidia_smi(result.stdout)
194
+
195
+
196
+ def detect_devices(llama_server: Path | None) -> list[Device]:
197
+ """Detect GPU devices, preferring ``llama-server --list-devices`` over ``nvidia-smi``.
198
+
199
+ Args:
200
+ llama_server: Path to ``llama-server``, or None when it is not installed.
201
+
202
+ Returns:
203
+ list[Device]: Detected GPUs; ``[]`` on a CPU-only host or when no probe works.
204
+ """
205
+ devices = _list_devices(llama_server) if llama_server is not None else []
206
+ return devices or _nvidia_smi()
207
+
208
+
209
+ def best_device(devices: Sequence[Device], override: str | None = None) -> Device | None:
210
+ """Choose the device to run on.
211
+
212
+ Args:
213
+ devices: Candidate devices.
214
+ override: A device id that wins when it matches a non-CPU candidate (even an integrated GPU).
215
+
216
+ Returns:
217
+ Device | None: The override match, else the discrete GPU with the most memory. An integrated GPU is chosen
218
+ (largest first) only when it is the sole kind of GPU; None when there is no GPU.
219
+ """
220
+ gpus = [d for d in devices if not _is_cpu(d)]
221
+ if override is not None:
222
+ for device in gpus:
223
+ if device.id == override:
224
+ return device
225
+ return max(gpus, key=lambda d: (not is_integrated(d), d.total_mib), default=None)
226
+
227
+
228
+ def host_info(llama_server: Path | None) -> HostInfo:
229
+ """Probe the host's GPUs, RAM and CPU cores.
230
+
231
+ Args:
232
+ llama_server: Path to ``llama-server``, or None when it is not installed.
233
+
234
+ Returns:
235
+ HostInfo: Snapshot of the host.
236
+ """
237
+ memory = psutil.virtual_memory()
238
+ logical = psutil.cpu_count(logical=True) or 1
239
+ physical = psutil.cpu_count(logical=False) or logical
240
+ return HostInfo(
241
+ devices=tuple(detect_devices(llama_server)),
242
+ ram_total_mib=memory.total // _BYTES_PER_MIB,
243
+ ram_free_mib=memory.available // _BYTES_PER_MIB,
244
+ physical_cores=physical,
245
+ logical_cores=logical,
246
+ )
247
+
248
+
249
+ def fingerprint(host: HostInfo, device: Device | None, llama_build: str) -> dict[str, str]:
250
+ """Summarise the hardware for cache keys (tuned-setting invalidation).
251
+
252
+ Args:
253
+ host: Host snapshot.
254
+ device: Chosen GPU, or None for CPU-only.
255
+ llama_build: ``llama-server`` build identifier.
256
+
257
+ Returns:
258
+ dict[str, str]: Exactly the keys ``gpu``, ``vram_mib``, ``ram_mib``, ``cores`` and ``llama_build``.
259
+ """
260
+ return {
261
+ "gpu": device.name if device is not None else "cpu",
262
+ "vram_mib": str(device.total_mib if device is not None else 0),
263
+ "ram_mib": str(host.ram_total_mib),
264
+ "cores": str(host.physical_cores),
265
+ "llama_build": llama_build,
266
+ }