modelmap 0.1.0__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.
- modelmap/__init__.py +3 -0
- modelmap/__main__.py +7 -0
- modelmap/cli.py +430 -0
- modelmap/headers.py +462 -0
- modelmap/mapdata.py +74 -0
- modelmap/palette.py +79 -0
- modelmap/providers/__init__.py +11 -0
- modelmap/providers/base.py +247 -0
- modelmap/providers/describe.py +209 -0
- modelmap/providers/generic.py +250 -0
- modelmap/providers/hf.py +219 -0
- modelmap/providers/ollama.py +235 -0
- modelmap/providers/omlx.py +66 -0
- modelmap/providers/stores.py +160 -0
- modelmap/records.py +187 -0
- modelmap/removal.py +365 -0
- modelmap/render_html.py +686 -0
- modelmap/render_svg.py +330 -0
- modelmap/scanner.py +245 -0
- modelmap/sizing.py +103 -0
- modelmap/treemap.py +196 -0
- modelmap/units.py +62 -0
- modelmap-0.1.0.dist-info/METADATA +126 -0
- modelmap-0.1.0.dist-info/RECORD +27 -0
- modelmap-0.1.0.dist-info/WHEEL +4 -0
- modelmap-0.1.0.dist-info/entry_points.txt +3 -0
- modelmap-0.1.0.dist-info/licenses/LICENSE +29 -0
modelmap/headers.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"""Read GGUF and safetensors headers without reading any weights.
|
|
2
|
+
|
|
3
|
+
Both readers return an info object and never raise on a bad file: a
|
|
4
|
+
truncated file, a header that declares more than the file holds, or an
|
|
5
|
+
unreadable path becomes an entry in ``issues``. A reader consumes at most
|
|
6
|
+
``HEADER_CAP`` bytes, in chunks, and checks every declared length and count
|
|
7
|
+
against the file size before acting on it.
|
|
8
|
+
|
|
9
|
+
GGUF layout and enums follow llama.cpp's ``gguf-py/gguf/constants.py`` and
|
|
10
|
+
``gguf_reader.py``. Safetensors layout: an 8-byte little-endian header
|
|
11
|
+
length, then a JSON object mapping tensor names to ``dtype``, ``shape`` and
|
|
12
|
+
``data_offsets``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import math
|
|
19
|
+
import os
|
|
20
|
+
import struct
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Any, BinaryIO
|
|
24
|
+
|
|
25
|
+
HEADER_CAP = 64 * 1024 * 1024
|
|
26
|
+
_CHUNK = 1024 * 1024
|
|
27
|
+
|
|
28
|
+
GGUF_MAGIC = b"GGUF"
|
|
29
|
+
_GGUF_VERSIONS = (2, 3)
|
|
30
|
+
# GGUFValueType: struct codes for the fixed-size types.
|
|
31
|
+
_SCALARS = {
|
|
32
|
+
0: "B",
|
|
33
|
+
1: "b",
|
|
34
|
+
2: "H",
|
|
35
|
+
3: "h",
|
|
36
|
+
4: "I",
|
|
37
|
+
5: "i",
|
|
38
|
+
6: "f",
|
|
39
|
+
7: "?",
|
|
40
|
+
10: "Q",
|
|
41
|
+
11: "q",
|
|
42
|
+
12: "d",
|
|
43
|
+
}
|
|
44
|
+
_STRING = 8
|
|
45
|
+
_ARRAY = 9
|
|
46
|
+
_MAX_ARRAY_DEPTH = 4
|
|
47
|
+
_MAX_DIMS = 8 # GGML allows 4; anything above 8 is a corrupt header
|
|
48
|
+
|
|
49
|
+
# LlamaFileType, with the MOSTLY_/ALL_ prefix dropped.
|
|
50
|
+
FILE_TYPES = {
|
|
51
|
+
0: "F32",
|
|
52
|
+
1: "F16",
|
|
53
|
+
2: "Q4_0",
|
|
54
|
+
3: "Q4_1",
|
|
55
|
+
7: "Q8_0",
|
|
56
|
+
8: "Q5_0",
|
|
57
|
+
9: "Q5_1",
|
|
58
|
+
10: "Q2_K",
|
|
59
|
+
11: "Q3_K_S",
|
|
60
|
+
12: "Q3_K_M",
|
|
61
|
+
13: "Q3_K_L",
|
|
62
|
+
14: "Q4_K_S",
|
|
63
|
+
15: "Q4_K_M",
|
|
64
|
+
16: "Q5_K_S",
|
|
65
|
+
17: "Q5_K_M",
|
|
66
|
+
18: "Q6_K",
|
|
67
|
+
19: "IQ2_XXS",
|
|
68
|
+
20: "IQ2_XS",
|
|
69
|
+
21: "Q2_K_S",
|
|
70
|
+
22: "IQ3_XS",
|
|
71
|
+
23: "IQ3_XXS",
|
|
72
|
+
24: "IQ1_S",
|
|
73
|
+
25: "IQ4_NL",
|
|
74
|
+
26: "IQ3_S",
|
|
75
|
+
27: "IQ3_M",
|
|
76
|
+
28: "IQ2_S",
|
|
77
|
+
29: "IQ2_M",
|
|
78
|
+
30: "IQ4_XS",
|
|
79
|
+
31: "IQ1_M",
|
|
80
|
+
32: "BF16",
|
|
81
|
+
36: "TQ1_0",
|
|
82
|
+
37: "TQ2_0",
|
|
83
|
+
38: "MXFP4_MOE",
|
|
84
|
+
39: "NVFP4",
|
|
85
|
+
40: "Q1_0",
|
|
86
|
+
41: "Q2_0",
|
|
87
|
+
42: "F8_E4M3",
|
|
88
|
+
}
|
|
89
|
+
_FILE_TYPE_GUESSED = 1024 # LlamaFileType.GUESSED: not specified in the file
|
|
90
|
+
|
|
91
|
+
# Bit width of the unsigned safetensors dtypes MLX packs quantized weights into.
|
|
92
|
+
_PACKED_DTYPES = {"U8": 8, "U16": 16, "U32": 32, "U64": 64}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# macOS sys/stat.h SF_DATALESS: the content is in the cloud, not on disk.
|
|
96
|
+
_SF_DATALESS = 0x40000000
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def open_local(path: str | os.PathLike[str]) -> BinaryIO:
|
|
100
|
+
"""Open a file for reading, unless reading would download it.
|
|
101
|
+
|
|
102
|
+
iCloud Drive and other file providers leave placeholders that report
|
|
103
|
+
their full size and fetch the content when opened. A scan must not
|
|
104
|
+
start downloads, so such a file is refused.
|
|
105
|
+
|
|
106
|
+
:raises OSError: If the file is a placeholder or cannot be opened.
|
|
107
|
+
"""
|
|
108
|
+
if getattr(os.stat(path), "st_flags", 0) & _SF_DATALESS:
|
|
109
|
+
raise OSError("not downloaded: the file is a cloud placeholder")
|
|
110
|
+
return open(path, "rb")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _HeaderError(Exception):
|
|
114
|
+
"""A header that cannot be parsed; its message becomes an issue."""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class GGUFInfo:
|
|
119
|
+
"""What a GGUF header says about its file.
|
|
120
|
+
|
|
121
|
+
:param version: GGUF version, or None when the file is too short to say.
|
|
122
|
+
:param tensor_count: Declared number of tensors.
|
|
123
|
+
:param metadata: Scalar and string key-value pairs. Arrays are skipped.
|
|
124
|
+
:param param_count: Sum of tensor element counts, exact for any
|
|
125
|
+
quantization. None unless every tensor info was read.
|
|
126
|
+
:param issues: Problems found; empty for a well-formed header.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
version: int | None = None
|
|
130
|
+
tensor_count: int | None = None
|
|
131
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
132
|
+
param_count: int | None = None
|
|
133
|
+
issues: list[str] = field(default_factory=list)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def architecture(self) -> str | None:
|
|
137
|
+
return self.metadata.get("general.architecture")
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def name(self) -> str | None:
|
|
141
|
+
return self.metadata.get("general.name")
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def quant(self) -> str | None:
|
|
145
|
+
"""Quantization label from ``general.file_type``, or None when absent."""
|
|
146
|
+
file_type = self.metadata.get("general.file_type")
|
|
147
|
+
if file_type is None or file_type == _FILE_TYPE_GUESSED:
|
|
148
|
+
return None
|
|
149
|
+
return FILE_TYPES.get(file_type, f"file_type {file_type}")
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def is_vocab_only(self) -> bool:
|
|
153
|
+
"""True for a tokenizer-only stub such as llama.cpp's ggml-vocab files."""
|
|
154
|
+
return self.tensor_count == 0
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass
|
|
158
|
+
class SafetensorsInfo:
|
|
159
|
+
"""What a safetensors header says about its file.
|
|
160
|
+
|
|
161
|
+
:param tensor_count: Number of tensors in the header.
|
|
162
|
+
:param metadata: The ``__metadata__`` object, if any.
|
|
163
|
+
:param param_count: Parameter count, or None when it cannot be known
|
|
164
|
+
(a packed weight with no bit width given, or a bad header).
|
|
165
|
+
:param params_exact: False when the count was derived from packed
|
|
166
|
+
quantized weights and their configured bit widths.
|
|
167
|
+
:param packed: True when the file holds MLX-style packed integer weights.
|
|
168
|
+
:param issues: Problems found; empty for a well-formed header.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
tensor_count: int = 0
|
|
172
|
+
metadata: dict[str, str] = field(default_factory=dict)
|
|
173
|
+
param_count: int | None = None
|
|
174
|
+
params_exact: bool = True
|
|
175
|
+
packed: bool = False
|
|
176
|
+
issues: list[str] = field(default_factory=list)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class _Reader:
|
|
180
|
+
"""Chunked forward reader that refuses to pass the file size or the cap."""
|
|
181
|
+
|
|
182
|
+
def __init__(self, fh: BinaryIO, size: int, cap: int) -> None:
|
|
183
|
+
self._fh = fh
|
|
184
|
+
self._data = bytearray()
|
|
185
|
+
self._size = size
|
|
186
|
+
self._cap = cap
|
|
187
|
+
self.pos = 0
|
|
188
|
+
self.set_endian("<")
|
|
189
|
+
|
|
190
|
+
def set_endian(self, endian: str) -> None:
|
|
191
|
+
self.endian = endian
|
|
192
|
+
self._u32 = struct.Struct(endian + "I")
|
|
193
|
+
self._u64 = struct.Struct(endian + "Q")
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def remaining(self) -> int:
|
|
197
|
+
"""Bytes between the read position and the end of the file."""
|
|
198
|
+
return self._size - self.pos
|
|
199
|
+
|
|
200
|
+
def _need(self, n: int) -> None:
|
|
201
|
+
end = self.pos + n
|
|
202
|
+
if end <= len(self._data):
|
|
203
|
+
return
|
|
204
|
+
if end > self._size:
|
|
205
|
+
raise _HeaderError(
|
|
206
|
+
f"truncated: header needs {n} bytes at offset {self.pos}, "
|
|
207
|
+
f"file is {self._size} bytes"
|
|
208
|
+
)
|
|
209
|
+
if end > self._cap:
|
|
210
|
+
raise _HeaderError(f"header is larger than the {self._cap} byte cap")
|
|
211
|
+
limit = min(self._size, self._cap)
|
|
212
|
+
while len(self._data) < end:
|
|
213
|
+
want = min(max(end - len(self._data), _CHUNK), limit - len(self._data))
|
|
214
|
+
chunk = self._fh.read(want)
|
|
215
|
+
if not chunk:
|
|
216
|
+
raise _HeaderError(f"truncated: file ended at offset {len(self._data)}")
|
|
217
|
+
self._data += chunk
|
|
218
|
+
|
|
219
|
+
def u32(self) -> int:
|
|
220
|
+
self._need(4)
|
|
221
|
+
(value,) = self._u32.unpack_from(self._data, self.pos)
|
|
222
|
+
self.pos += 4
|
|
223
|
+
return value
|
|
224
|
+
|
|
225
|
+
def u64(self) -> int:
|
|
226
|
+
self._need(8)
|
|
227
|
+
(value,) = self._u64.unpack_from(self._data, self.pos)
|
|
228
|
+
self.pos += 8
|
|
229
|
+
return value
|
|
230
|
+
|
|
231
|
+
def scalar(self, code: str) -> Any:
|
|
232
|
+
fmt = struct.Struct(self.endian + code)
|
|
233
|
+
self._need(fmt.size)
|
|
234
|
+
(value,) = fmt.unpack_from(self._data, self.pos)
|
|
235
|
+
self.pos += fmt.size
|
|
236
|
+
return value
|
|
237
|
+
|
|
238
|
+
def skip(self, n: int) -> None:
|
|
239
|
+
self._need(n)
|
|
240
|
+
self.pos += n
|
|
241
|
+
|
|
242
|
+
def string(self) -> str:
|
|
243
|
+
n = self.u64()
|
|
244
|
+
self._need(n)
|
|
245
|
+
raw = bytes(self._data[self.pos : self.pos + n])
|
|
246
|
+
self.pos += n
|
|
247
|
+
return raw.decode("utf-8", "replace")
|
|
248
|
+
|
|
249
|
+
def check_count(self, count: int, min_item_bytes: int, what: str) -> None:
|
|
250
|
+
"""Reject a declared count the rest of the file cannot hold."""
|
|
251
|
+
if count * min_item_bytes > self.remaining:
|
|
252
|
+
raise _HeaderError(
|
|
253
|
+
f"declared {count} {what}, more than the remaining {self.remaining} bytes can hold"
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _skip_array(r: _Reader, depth: int) -> None:
|
|
258
|
+
item_type = r.u32()
|
|
259
|
+
count = r.u64()
|
|
260
|
+
if item_type in _SCALARS:
|
|
261
|
+
r.skip(count * struct.calcsize(_SCALARS[item_type]))
|
|
262
|
+
elif item_type == _STRING:
|
|
263
|
+
r.check_count(count, 8, "array strings")
|
|
264
|
+
for _ in range(count):
|
|
265
|
+
r.skip(r.u64())
|
|
266
|
+
elif item_type == _ARRAY:
|
|
267
|
+
if depth >= _MAX_ARRAY_DEPTH:
|
|
268
|
+
raise _HeaderError("arrays nested too deeply")
|
|
269
|
+
r.check_count(count, 12, "nested arrays")
|
|
270
|
+
for _ in range(count):
|
|
271
|
+
_skip_array(r, depth + 1)
|
|
272
|
+
else:
|
|
273
|
+
raise _HeaderError(f"unknown array item type {item_type}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _parse_gguf(r: _Reader, info: GGUFInfo) -> None:
|
|
277
|
+
r._need(4)
|
|
278
|
+
if bytes(r._data[:4]) != GGUF_MAGIC:
|
|
279
|
+
raise _HeaderError("not a GGUF file: bad magic")
|
|
280
|
+
r.pos = 4
|
|
281
|
+
version = r.u32()
|
|
282
|
+
if version & 0xFFFF == 0:
|
|
283
|
+
# A big-endian file read as little-endian has an empty low word.
|
|
284
|
+
r.set_endian(">")
|
|
285
|
+
r.pos = 4
|
|
286
|
+
version = r.u32()
|
|
287
|
+
info.version = version
|
|
288
|
+
if version not in _GGUF_VERSIONS:
|
|
289
|
+
raise _HeaderError(f"unsupported GGUF version {version}")
|
|
290
|
+
|
|
291
|
+
tensor_count = r.u64()
|
|
292
|
+
kv_count = r.u64()
|
|
293
|
+
info.tensor_count = tensor_count
|
|
294
|
+
r.check_count(kv_count, 13, "metadata entries")
|
|
295
|
+
|
|
296
|
+
for _ in range(kv_count):
|
|
297
|
+
key = r.string()
|
|
298
|
+
value_type = r.u32()
|
|
299
|
+
if value_type in _SCALARS:
|
|
300
|
+
info.metadata[key] = r.scalar(_SCALARS[value_type])
|
|
301
|
+
elif value_type == _STRING:
|
|
302
|
+
info.metadata[key] = r.string()
|
|
303
|
+
elif value_type == _ARRAY:
|
|
304
|
+
_skip_array(r, 1)
|
|
305
|
+
else:
|
|
306
|
+
raise _HeaderError(f"unknown value type {value_type} for key {key!r}")
|
|
307
|
+
|
|
308
|
+
r.check_count(tensor_count, 24, "tensors")
|
|
309
|
+
params = 0
|
|
310
|
+
for _ in range(tensor_count):
|
|
311
|
+
r.skip(r.u64()) # name
|
|
312
|
+
n_dims = r.u32()
|
|
313
|
+
if n_dims > _MAX_DIMS:
|
|
314
|
+
raise _HeaderError(f"tensor declares {n_dims} dimensions")
|
|
315
|
+
elements = 1
|
|
316
|
+
for _ in range(n_dims):
|
|
317
|
+
elements *= r.u64()
|
|
318
|
+
r.skip(12) # dtype (u32) and data offset (u64)
|
|
319
|
+
params += elements
|
|
320
|
+
info.param_count = params
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def read_gguf(path: str | os.PathLike[str], *, cap: int = HEADER_CAP) -> GGUFInfo:
|
|
324
|
+
"""Read a GGUF header.
|
|
325
|
+
|
|
326
|
+
:param path: File to read.
|
|
327
|
+
:param cap: Most bytes to consume from the file.
|
|
328
|
+
:return: Header facts; ``issues`` is non-empty when the header is bad.
|
|
329
|
+
"""
|
|
330
|
+
info = GGUFInfo()
|
|
331
|
+
try:
|
|
332
|
+
with open_local(path) as fh:
|
|
333
|
+
size = os.fstat(fh.fileno()).st_size
|
|
334
|
+
_parse_gguf(_Reader(fh, size, cap), info)
|
|
335
|
+
except (OSError, _HeaderError) as exc:
|
|
336
|
+
info.issues.append(str(exc))
|
|
337
|
+
return info
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _tensor_elements(name: str, entry: Any) -> int:
|
|
341
|
+
shape = entry.get("shape") if isinstance(entry, dict) else None
|
|
342
|
+
if not isinstance(shape, list) or not all(isinstance(d, int) and d >= 0 for d in shape):
|
|
343
|
+
raise _HeaderError(f"tensor {name!r} has no valid shape")
|
|
344
|
+
return math.prod(shape)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _layer_bits(quantization: Mapping[str, Any] | None, stem: str) -> int | None:
|
|
348
|
+
"""Bit width of one packed layer: its own entry, else the model default."""
|
|
349
|
+
if not quantization:
|
|
350
|
+
return None
|
|
351
|
+
layer = quantization.get(stem)
|
|
352
|
+
bits = layer.get("bits") if isinstance(layer, Mapping) else None
|
|
353
|
+
if bits is None:
|
|
354
|
+
bits = quantization.get("bits")
|
|
355
|
+
return bits if isinstance(bits, int) and bits > 0 else None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _count_safetensors(
|
|
359
|
+
tensors: dict[str, Any], quantization: Mapping[str, Any] | None, info: SafetensorsInfo
|
|
360
|
+
) -> None:
|
|
361
|
+
"""Fill the parameter fields of ``info`` from the tensor table.
|
|
362
|
+
|
|
363
|
+
MLX stores a quantized weight as a packed unsigned-integer tensor named
|
|
364
|
+
``<stem>.weight`` beside float tensors ``<stem>.scales`` and
|
|
365
|
+
``<stem>.biases``. The packed tensor's shape is not the weight's shape:
|
|
366
|
+
each element holds ``width / bits`` weights. The scales and biases are
|
|
367
|
+
quantization data, not parameters. Mixed-precision models give some
|
|
368
|
+
layers their own bit width, keyed by ``<stem>`` in ``quantization``.
|
|
369
|
+
"""
|
|
370
|
+
packed_stems = set()
|
|
371
|
+
for name, entry in tensors.items():
|
|
372
|
+
stem, dot, leaf = name.rpartition(".")
|
|
373
|
+
if (
|
|
374
|
+
dot
|
|
375
|
+
and leaf == "weight"
|
|
376
|
+
and isinstance(entry, dict)
|
|
377
|
+
and entry.get("dtype") in _PACKED_DTYPES
|
|
378
|
+
and f"{stem}.scales" in tensors
|
|
379
|
+
):
|
|
380
|
+
packed_stems.add(stem)
|
|
381
|
+
info.packed = bool(packed_stems)
|
|
382
|
+
|
|
383
|
+
params = 0
|
|
384
|
+
bits_known = True
|
|
385
|
+
for name, entry in tensors.items():
|
|
386
|
+
stem, _, leaf = name.rpartition(".")
|
|
387
|
+
elements = _tensor_elements(name, entry)
|
|
388
|
+
if stem not in packed_stems:
|
|
389
|
+
params += elements
|
|
390
|
+
elif leaf == "weight":
|
|
391
|
+
bits = _layer_bits(quantization, stem)
|
|
392
|
+
if bits is None:
|
|
393
|
+
bits_known = False
|
|
394
|
+
else:
|
|
395
|
+
params += elements * _PACKED_DTYPES[entry["dtype"]] // bits
|
|
396
|
+
elif leaf not in ("scales", "biases"):
|
|
397
|
+
params += elements
|
|
398
|
+
info.params_exact = not info.packed
|
|
399
|
+
info.param_count = params if bits_known else None
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def read_safetensors(
|
|
403
|
+
path: str | os.PathLike[str],
|
|
404
|
+
*,
|
|
405
|
+
quantization: Mapping[str, Any] | None = None,
|
|
406
|
+
cap: int = HEADER_CAP,
|
|
407
|
+
) -> SafetensorsInfo:
|
|
408
|
+
"""Read a safetensors header.
|
|
409
|
+
|
|
410
|
+
:param path: File to read.
|
|
411
|
+
:param quantization: The ``quantization`` object from the model's
|
|
412
|
+
``config.json``: a default ``bits`` plus optional per-layer entries.
|
|
413
|
+
Needed to count the parameters of MLX packed weights.
|
|
414
|
+
:param cap: Largest header to accept, in bytes.
|
|
415
|
+
:return: Header facts; ``issues`` is non-empty when the header is bad.
|
|
416
|
+
"""
|
|
417
|
+
info = SafetensorsInfo()
|
|
418
|
+
try:
|
|
419
|
+
with open_local(path) as fh:
|
|
420
|
+
size = os.fstat(fh.fileno()).st_size
|
|
421
|
+
prefix = fh.read(8)
|
|
422
|
+
if len(prefix) < 8:
|
|
423
|
+
raise _HeaderError("truncated: file is shorter than the 8-byte length prefix")
|
|
424
|
+
(length,) = struct.unpack("<Q", prefix)
|
|
425
|
+
if length > size - 8:
|
|
426
|
+
raise _HeaderError(f"declared header length {length} exceeds the file size {size}")
|
|
427
|
+
if length > cap:
|
|
428
|
+
raise _HeaderError(f"header is larger than the {cap} byte cap")
|
|
429
|
+
raw = fh.read(length)
|
|
430
|
+
header = json.loads(raw)
|
|
431
|
+
if not isinstance(header, dict):
|
|
432
|
+
raise _HeaderError("header is not a JSON object")
|
|
433
|
+
metadata = header.pop("__metadata__", None)
|
|
434
|
+
if isinstance(metadata, dict):
|
|
435
|
+
info.metadata = metadata
|
|
436
|
+
info.tensor_count = len(header)
|
|
437
|
+
_count_safetensors(header, quantization, info)
|
|
438
|
+
except (OSError, _HeaderError, ValueError, RecursionError) as exc:
|
|
439
|
+
info.issues.append(str(exc))
|
|
440
|
+
return info
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def sniff(path: str | os.PathLike[str]) -> str | None:
|
|
444
|
+
"""Identify a model file by its first bytes.
|
|
445
|
+
|
|
446
|
+
:param path: File to inspect.
|
|
447
|
+
:return: ``"gguf"``, ``"safetensors"``, or None for anything else,
|
|
448
|
+
including a file that cannot be opened.
|
|
449
|
+
"""
|
|
450
|
+
try:
|
|
451
|
+
with open_local(path) as fh:
|
|
452
|
+
size = os.fstat(fh.fileno()).st_size
|
|
453
|
+
head = fh.read(9)
|
|
454
|
+
except OSError:
|
|
455
|
+
return None
|
|
456
|
+
if head[:4] == GGUF_MAGIC:
|
|
457
|
+
return "gguf"
|
|
458
|
+
if len(head) == 9 and head[8:9] == b"{":
|
|
459
|
+
(length,) = struct.unpack("<Q", head[:8])
|
|
460
|
+
if 2 <= length <= size - 8:
|
|
461
|
+
return "safetensors"
|
|
462
|
+
return None
|
modelmap/mapdata.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Decide what each record becomes on the map.
|
|
2
|
+
|
|
3
|
+
Every record ends up in exactly one place:
|
|
4
|
+
|
|
5
|
+
- a tile of its own, when it has a size;
|
|
6
|
+
- a note on another record's tile, when all its files were charged to that
|
|
7
|
+
record (a second name for the same weights);
|
|
8
|
+
- the list of records not drawn, when it has no size and no record to
|
|
9
|
+
attach to (weights that were never downloaded, for example).
|
|
10
|
+
|
|
11
|
+
Nothing is dropped silently: the three counts add up to the number of
|
|
12
|
+
records.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
from modelmap.records import ModelRecord, Scan
|
|
20
|
+
from modelmap.treemap import Item
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class MapData:
|
|
25
|
+
"""What to draw.
|
|
26
|
+
|
|
27
|
+
:param records: The scan's records; items refer to them by index.
|
|
28
|
+
:param items: One per record that gets a tile; ``key`` is the index.
|
|
29
|
+
:param attached: For a tile's record index, the indexes of the records
|
|
30
|
+
noted on it.
|
|
31
|
+
:param not_drawn: Indexes of records with nothing to draw.
|
|
32
|
+
:param total: Sum of the sizes of the items.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
records: list[ModelRecord]
|
|
36
|
+
items: list[Item] = field(default_factory=list)
|
|
37
|
+
attached: dict[int, list[int]] = field(default_factory=dict)
|
|
38
|
+
not_drawn: list[int] = field(default_factory=list)
|
|
39
|
+
total: int = 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def build(scan: Scan, *, use_disk: bool = False) -> MapData:
|
|
43
|
+
"""Sort a scan's records into tiles, notes and records not drawn.
|
|
44
|
+
|
|
45
|
+
:param scan: The scan to draw.
|
|
46
|
+
:param use_disk: Size tiles by bytes allocated on disk, not by apparent
|
|
47
|
+
size.
|
|
48
|
+
"""
|
|
49
|
+
data = MapData(records=scan.records)
|
|
50
|
+
owners: dict[str, list[int]] = {}
|
|
51
|
+
for index, record in enumerate(scan.records):
|
|
52
|
+
owners.setdefault(f"{record.provider}:{record.name}", []).append(index)
|
|
53
|
+
|
|
54
|
+
for index, record in enumerate(scan.records):
|
|
55
|
+
size = record.disk_bytes if use_disk else record.size_bytes
|
|
56
|
+
if size > 0:
|
|
57
|
+
data.items.append(Item(str(index), record.provider, size, record.name))
|
|
58
|
+
data.total += size
|
|
59
|
+
continue
|
|
60
|
+
# Owner names are not unique, and the owner may not be in this scan
|
|
61
|
+
# at all. Attach only when exactly one record answers to the name.
|
|
62
|
+
candidates = {i for owner in record.shared_with for i in owners.get(owner, ())}
|
|
63
|
+
candidates.discard(index)
|
|
64
|
+
if len(candidates) == 1:
|
|
65
|
+
data.attached.setdefault(candidates.pop(), []).append(index)
|
|
66
|
+
else:
|
|
67
|
+
data.not_drawn.append(index)
|
|
68
|
+
|
|
69
|
+
# A note belongs on a tile; if its owner has no tile either, it is not drawn.
|
|
70
|
+
drawn = {int(item.key) for item in data.items}
|
|
71
|
+
for owner in [o for o in data.attached if o not in drawn]:
|
|
72
|
+
data.not_drawn += data.attached.pop(owner)
|
|
73
|
+
data.not_drawn.sort()
|
|
74
|
+
return data
|
modelmap/palette.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Colors for the map, in a light and a dark mode.
|
|
2
|
+
|
|
3
|
+
Each provider has one hue, fixed by name, so a store keeps its color
|
|
4
|
+
whatever else is on the machine. The hues and their order come from a
|
|
5
|
+
palette validated for color-vision deficiency; only its first three slots
|
|
6
|
+
stay distinguishable in every pairing, and a treemap can put any two
|
|
7
|
+
groups side by side. Color is therefore never the only cue: every group
|
|
8
|
+
has a row in the legend, every tooltip names its provider, and a block
|
|
9
|
+
wide enough carries a name tag on the map.
|
|
10
|
+
|
|
11
|
+
Loose files take a neutral that is much darker than every hue in light
|
|
12
|
+
mode and much lighter in dark mode. A mid gray would not do: measured with
|
|
13
|
+
the palette's validator, it is hard to tell from the aqua under red-green
|
|
14
|
+
color blindness.
|
|
15
|
+
|
|
16
|
+
Text inside a tile is white or black, whichever contrasts more with the
|
|
17
|
+
fill. The two ratios multiply to 21 for any fill, so the better one is at
|
|
18
|
+
least 4.58 and always clears the WCAG AA ratio of 4.5. A softer near-black
|
|
19
|
+
ink does not: on the light-mode blue it reaches only 4.46.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
MODES = ("light", "dark")
|
|
25
|
+
|
|
26
|
+
SURFACE = {"light": "#fcfcfb", "dark": "#1a1a19"}
|
|
27
|
+
TEXT_PRIMARY = {"light": "#0b0b0b", "dark": "#f0efec"}
|
|
28
|
+
TEXT_SECONDARY = {"light": "#52514e", "dark": "#c3c2b7"}
|
|
29
|
+
INK_LIGHT = "#ffffff"
|
|
30
|
+
INK_DARK = "#000000"
|
|
31
|
+
|
|
32
|
+
# (light, dark) fills. The three stores most often found together take the
|
|
33
|
+
# three slots that are distinguishable in every pairing.
|
|
34
|
+
PROVIDER_COLORS = {
|
|
35
|
+
"hf": ("#2a78d6", "#3987e5"), # blue
|
|
36
|
+
"ollama": ("#eb6834", "#d95926"), # orange
|
|
37
|
+
"omlx": ("#1baf7a", "#199e70"), # aqua
|
|
38
|
+
"lmstudio": ("#eda100", "#c98500"), # yellow
|
|
39
|
+
"llamacpp": ("#e87ba4", "#d55181"), # magenta
|
|
40
|
+
"gpt4all": ("#008300", "#0ca30c"), # green
|
|
41
|
+
"jan": ("#6250d6", "#9085e9"), # violet
|
|
42
|
+
"whisper": ("#e34948", "#e66767"), # red
|
|
43
|
+
}
|
|
44
|
+
# Loose files and any provider without a hue of its own: a neutral, not a
|
|
45
|
+
# ninth hue. Against all eight hues these measure at least 13 (color-blind
|
|
46
|
+
# simulation) and 21 (normal vision) on the validator's scale, where the
|
|
47
|
+
# floors are 8 and 15.
|
|
48
|
+
OTHER_COLOR = ("#484842", "#c8c8c2")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fill(group: str, mode: str) -> str:
|
|
52
|
+
"""The fill color of a group in a mode."""
|
|
53
|
+
return PROVIDER_COLORS.get(group, OTHER_COLOR)[MODES.index(mode)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _channels(color: str) -> tuple[int, int, int]:
|
|
57
|
+
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def luminance(color: str) -> float:
|
|
61
|
+
"""WCAG relative luminance of an ``#rrggbb`` color."""
|
|
62
|
+
|
|
63
|
+
def linear(channel: int) -> float:
|
|
64
|
+
value = channel / 255
|
|
65
|
+
return value / 12.92 if value <= 0.03928 else ((value + 0.055) / 1.055) ** 2.4
|
|
66
|
+
|
|
67
|
+
r, g, b = (linear(c) for c in _channels(color))
|
|
68
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def contrast(a: str, b: str) -> float:
|
|
72
|
+
"""WCAG contrast ratio of two colors, from 1 to 21."""
|
|
73
|
+
lighter, darker = sorted((luminance(a), luminance(b)), reverse=True)
|
|
74
|
+
return (lighter + 0.05) / (darker + 0.05)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def ink_on(background: str) -> str:
|
|
78
|
+
"""White or black, whichever reads better on a background."""
|
|
79
|
+
return max((INK_LIGHT, INK_DARK), key=lambda ink: contrast(ink, background))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""One provider per tool that stores models, plus the generic tree scanner.
|
|
2
|
+
|
|
3
|
+
A provider has a ``NAME``, ``roots(ctx)`` and ``scan(root, ctx)``.
|
|
4
|
+
:data:`PROVIDERS` is the order they run in. The order matters: a file
|
|
5
|
+
reachable from two stores is charged to the first provider that claims it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from modelmap.providers import hf, ollama, omlx
|
|
9
|
+
from modelmap.providers.stores import gpt4all, jan, llamacpp, lmstudio, whisper
|
|
10
|
+
|
|
11
|
+
PROVIDERS = (hf, ollama, omlx, lmstudio, llamacpp, gpt4all, jan, whisper)
|