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.
@@ -0,0 +1,247 @@
1
+ """What every provider shares: the scan context, roots and charging.
2
+
3
+ A provider is a module with two functions. ``roots(ctx)`` returns the
4
+ directories the tool stores models in on this machine. ``scan(root, ctx)``
5
+ returns the records found under one of them. Nothing here reads the real
6
+ environment: the home directory, environment variables and platform come
7
+ in through :class:`Context`, so tests can describe any machine.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from collections.abc import Iterable, Mapping
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from modelmap.records import FileEntry, ModelRecord, ScanRoot, ScanWarning
20
+ from modelmap.sizing import SizeLedger
21
+
22
+ # A file smaller than this that two records share is not worth a note:
23
+ # license and template blobs are shared by unrelated models.
24
+ SHARE_NOTE_MIN = 1_000_000
25
+
26
+ # Directory names never worth descending into.
27
+ PRUNE = frozenset(
28
+ {
29
+ ".git",
30
+ "node_modules",
31
+ "site-packages",
32
+ ".venv",
33
+ "venv",
34
+ "__pycache__",
35
+ ".mypy_cache",
36
+ ".pytest_cache",
37
+ ".ruff_cache",
38
+ ".Trash",
39
+ }
40
+ )
41
+
42
+
43
+ @dataclass
44
+ class Context:
45
+ """The machine being scanned and the state of the scan.
46
+
47
+ :param home: The user's home directory.
48
+ :param env: Environment variables.
49
+ :param platform: ``sys.platform`` value: ``darwin``, ``linux``, ``win32``.
50
+ :param ledger: Charges each file once across every provider.
51
+ :param warnings: Paths that could not be read.
52
+ :param uses: For each file, every record that uses it, in scan order.
53
+ """
54
+
55
+ home: Path
56
+ env: Mapping[str, str]
57
+ platform: str
58
+ ledger: SizeLedger = field(default_factory=SizeLedger)
59
+ warnings: list[ScanWarning] = field(default_factory=list)
60
+ uses: dict[tuple[int, int], list[str]] = field(default_factory=dict)
61
+
62
+ @classmethod
63
+ def current(cls) -> Context:
64
+ """The context of the running process."""
65
+ return cls(home=Path.home(), env=os.environ, platform=sys.platform)
66
+
67
+ def warn(self, path: str | os.PathLike[str], message: str) -> None:
68
+ self.warnings.append(ScanWarning(str(path), message))
69
+
70
+ def expand(self, value: str) -> Path:
71
+ """Turn a configured path into a Path, expanding a leading ``~``."""
72
+ if value == "~" or value.startswith(("~/", "~\\")):
73
+ return self.home / value[2:]
74
+ return Path(value)
75
+
76
+ def first_env(self, *names: str) -> tuple[str, str] | None:
77
+ """The first of ``names`` that is set and non-empty, with its value."""
78
+ for name in names:
79
+ value = self.env.get(name)
80
+ if value:
81
+ return name, value
82
+ return None
83
+
84
+ def root(self, provider: str, path: str | os.PathLike[str], source: str) -> ScanRoot:
85
+ """Describe a root, resolving it even when it is itself a symlink."""
86
+ resolved = os.path.realpath(path)
87
+ return ScanRoot(
88
+ provider=provider,
89
+ path=str(path),
90
+ resolved=resolved,
91
+ source=source,
92
+ exists=os.path.isdir(resolved),
93
+ )
94
+
95
+
96
+ @dataclass
97
+ class Tally:
98
+ """Sizes of one record's files as they are charged to the ledger."""
99
+
100
+ size: int = 0
101
+ disk: int = 0
102
+ files: int = 0
103
+ mtime: float | None = None
104
+ shared_with: list[str] = field(default_factory=list)
105
+ issues: list[str] = field(default_factory=list)
106
+ entries: list[FileEntry] = field(default_factory=list)
107
+
108
+ def charge(
109
+ self,
110
+ ctx: Context,
111
+ owner: str,
112
+ paths: Iterable[str | os.PathLike[str]],
113
+ labels: Mapping[str, tuple[str, str]] | None = None,
114
+ ) -> None:
115
+ """Charge files to ``owner``, noting sharing and unreadable files.
116
+
117
+ :param ctx: The scan context, whose ledger decides who pays.
118
+ :param owner: Name of the record the files belong to.
119
+ :param paths: Files to charge. Symlinks are followed.
120
+ :param labels: For a path, its ``(label, note)`` in the file list;
121
+ a path not listed is labeled with its file name.
122
+ """
123
+ for path in paths:
124
+ try:
125
+ charge = ctx.ledger.charge(path, owner)
126
+ except OSError as exc:
127
+ kind = "broken link" if os.path.islink(path) else "unreadable"
128
+ self.issues.append(f"{kind}: {os.path.basename(path)}")
129
+ if kind == "unreadable":
130
+ ctx.warn(path, exc.strerror or str(exc))
131
+ continue
132
+ file = charge.file
133
+ assert file is not None
134
+ self.size += charge.apparent
135
+ self.disk += charge.disk
136
+ self.files += 1
137
+ if self.mtime is None or file.mtime > self.mtime:
138
+ self.mtime = file.mtime
139
+ other = charge.shared_with
140
+ if other and file.apparent >= SHARE_NOTE_MIN and other not in self.shared_with:
141
+ self.shared_with.append(other)
142
+ users = ctx.uses.setdefault(file.key, [])
143
+ if owner not in users:
144
+ users.append(owner)
145
+ label, note = (labels or {}).get(str(path), (os.path.basename(path), ""))
146
+ self.entries.append(
147
+ FileEntry(
148
+ path=os.path.realpath(path),
149
+ label=label,
150
+ size_bytes=file.apparent,
151
+ disk_bytes=file.disk,
152
+ charged=other is None,
153
+ note=note,
154
+ # The shared list: complete only when the scan ends.
155
+ used_by=users,
156
+ )
157
+ )
158
+
159
+ def record(self, issues: Iterable[str] = (), **fields: Any) -> ModelRecord:
160
+ """Build a record from the tally plus the given fields.
161
+
162
+ :param issues: Issues found outside charging, listed first.
163
+ :param fields: The remaining :class:`ModelRecord` fields.
164
+ """
165
+ return ModelRecord(
166
+ size_bytes=self.size,
167
+ disk_bytes=self.disk,
168
+ files=self.files,
169
+ file_list=self.entries,
170
+ mtime=self.mtime,
171
+ shared_with=self.shared_with,
172
+ issues=[*issues, *self.issues],
173
+ **fields,
174
+ )
175
+
176
+
177
+ def finish(records: Iterable[ModelRecord]) -> None:
178
+ """Complete the file lists once every record has been scanned.
179
+
180
+ While a scan runs, each file entry points at one shared list of the
181
+ records using that file. Give each entry its own list, without the
182
+ record it belongs to. A file may be the first one charged and still be
183
+ used by a record scanned later; only now is that known.
184
+ """
185
+ for record in records:
186
+ owner = f"{record.provider}:{record.name}"
187
+ for entry in record.file_list:
188
+ entry.used_by = [user for user in entry.used_by if user != owner]
189
+
190
+
191
+ def is_file(entry: os.DirEntry[str]) -> bool:
192
+ """``entry.is_file()``, false when the entry cannot be examined."""
193
+ try:
194
+ return entry.is_file()
195
+ except OSError:
196
+ return False
197
+
198
+
199
+ def is_dir(entry: os.DirEntry[str], *, follow_symlinks: bool = True) -> bool:
200
+ """``entry.is_dir()``, false when the entry cannot be examined."""
201
+ try:
202
+ return entry.is_dir(follow_symlinks=follow_symlinks)
203
+ except OSError:
204
+ return False
205
+
206
+
207
+ def file_size(path: str) -> int | None:
208
+ """Size of a file, or None when it cannot be examined.
209
+
210
+ A directory that may be listed but not searched yields names whose
211
+ files cannot be stat'ed.
212
+ """
213
+ try:
214
+ return os.path.getsize(path)
215
+ except OSError:
216
+ return None
217
+
218
+
219
+ def listdir(ctx: Context, path: str | os.PathLike[str]) -> list[os.DirEntry[str]]:
220
+ """Entries of a directory in name order; a warning and nothing on error."""
221
+ try:
222
+ with os.scandir(path) as it:
223
+ return sorted(it, key=lambda entry: entry.name)
224
+ except OSError as exc:
225
+ ctx.warn(path, exc.strerror or str(exc))
226
+ return []
227
+
228
+
229
+ def files_under(ctx: Context, path: str | os.PathLike[str]) -> list[str]:
230
+ """Every file below a directory, in a fixed order.
231
+
232
+ Symlinked files are included, since a store may link to its blobs;
233
+ symlinked directories are not followed, so a loop cannot trap the walk.
234
+ """
235
+ found: list[str] = []
236
+ stack = [str(path)]
237
+ while stack:
238
+ current = stack.pop()
239
+ subdirs = []
240
+ for entry in listdir(ctx, current):
241
+ if is_dir(entry, follow_symlinks=False):
242
+ if entry.name not in PRUNE:
243
+ subdirs.append(entry.path)
244
+ elif not entry.is_symlink() or not os.path.isdir(entry.path):
245
+ found.append(entry.path)
246
+ stack.extend(reversed(subdirs))
247
+ return found
@@ -0,0 +1,209 @@
1
+ """Work out what a set of model files is: format, quantization, size class.
2
+
3
+ Used by every provider once it knows which files make up one model.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ from collections.abc import Iterable, Mapping
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from modelmap.headers import open_local, read_gguf, read_safetensors
16
+
17
+ # Extensions that mark a weights file when no header can confirm it.
18
+ PICKLE_EXTENSIONS = frozenset({".bin", ".pt", ".pth", ".ckpt"})
19
+ _OTHER_FORMATS = {
20
+ ".onnx": "onnx",
21
+ ".mlmodel": "coreml",
22
+ ".mlpackage": "coreml",
23
+ ".tflite": "tflite",
24
+ }
25
+ # model-00001-of-00004.safetensors, name-00001-of-00003.gguf
26
+ _SHARD = re.compile(r"^(?P<base>.*?)-\d{5}-of-\d{5}$")
27
+
28
+ # First match wins, so more specific names come first.
29
+ _FAMILIES = (
30
+ ("qwen", "qwen"),
31
+ ("deepseek", "deepseek"),
32
+ ("codellama", "llama"),
33
+ ("llama", "llama"),
34
+ ("mixtral", "mistral"),
35
+ ("mistral", "mistral"),
36
+ ("gemma", "gemma"),
37
+ ("phi-", "phi"),
38
+ ("phi3", "phi"),
39
+ ("phi4", "phi"),
40
+ ("falcon", "falcon"),
41
+ ("granite", "granite"),
42
+ ("smollm", "smollm"),
43
+ ("lfm", "lfm"),
44
+ ("whisper", "whisper"),
45
+ ("parakeet", "parakeet"),
46
+ ("stable-diffusion", "stable-diffusion"),
47
+ ("sdxl", "stable-diffusion"),
48
+ ("flux", "flux"),
49
+ ("nomic", "nomic"),
50
+ ("bge", "bge"),
51
+ ("minilm", "minilm"),
52
+ ("mxbai", "mxbai"),
53
+ ("jina", "jina"),
54
+ ("e5-", "e5"),
55
+ ("t5", "t5"),
56
+ ("clip", "clip"),
57
+ ("bert", "bert"),
58
+ )
59
+
60
+
61
+ @dataclass
62
+ class Description:
63
+ """What the weight files of one model say about it.
64
+
65
+ :param format: ``gguf``, ``safetensors``, ``mlx``, ``pytorch`` and so on;
66
+ ``unknown`` when no weight file was recognized.
67
+ :param quant: Quantization label, or None.
68
+ :param params: Parameter count, or None when unknown or ambiguous.
69
+ :param params_exact: False when ``params`` is derived, not read.
70
+ :param architecture: ``general.architecture`` of a GGUF file, if any.
71
+ :param vocab_only: True for a GGUF tokenizer stub with no tensors.
72
+ :param issues: Problems found in the headers.
73
+ """
74
+
75
+ format: str = "unknown"
76
+ quant: str | None = None
77
+ params: int | None = None
78
+ params_exact: bool = True
79
+ architecture: str | None = None
80
+ vocab_only: bool = False
81
+ issues: list[str] = field(default_factory=list)
82
+
83
+
84
+ def guess_family(name: str, architecture: str | None = None) -> str | None:
85
+ """Guess a model family from its name, else from its GGUF architecture.
86
+
87
+ :param name: Model name such as ``mlx-community/Qwen3-8B-4bit``.
88
+ :param architecture: ``general.architecture`` from a GGUF header.
89
+ :return: A short family name such as ``qwen``, or None.
90
+ """
91
+ for text in (name.lower(), (architecture or "").lower()):
92
+ for needle, family in _FAMILIES:
93
+ if needle in text:
94
+ return family
95
+ return architecture or None
96
+
97
+
98
+ def shard_base(filename: str) -> str:
99
+ """File name without its extension and any ``-00001-of-00004`` suffix."""
100
+ stem = os.path.splitext(filename)[0]
101
+ match = _SHARD.match(stem)
102
+ return match.group("base") if match else stem
103
+
104
+
105
+ def is_projector(filename: str) -> bool:
106
+ """True for a multimodal projector file, which cannot run alone."""
107
+ return "mmproj" in filename.lower()
108
+
109
+
110
+ def describe_gguf(paths: Iterable[str]) -> Description:
111
+ """Describe one GGUF model stored as one file or as several shards.
112
+
113
+ :param paths: The file, or every shard of one split model.
114
+ """
115
+ out = Description(format="gguf", vocab_only=True)
116
+ params: int | None = 0
117
+ for path in sorted(paths):
118
+ info = read_gguf(path)
119
+ out.vocab_only = out.vocab_only and info.is_vocab_only and not info.issues
120
+ out.issues += [f"{os.path.basename(path)}: {issue}" for issue in info.issues]
121
+ out.quant = out.quant or info.quant
122
+ out.architecture = out.architecture or info.architecture
123
+ params = None if params is None or info.param_count is None else params + info.param_count
124
+ out.params = params
125
+ return out
126
+
127
+
128
+ def read_quantization(directory: str) -> Mapping[str, Any] | None:
129
+ """The ``quantization`` object of a model directory's ``config.json``."""
130
+ try:
131
+ with open_local(os.path.join(directory, "config.json")) as fh:
132
+ config = json.load(fh)
133
+ except (OSError, ValueError):
134
+ return None
135
+ quantization = config.get("quantization") if isinstance(config, dict) else None
136
+ return quantization if isinstance(quantization, dict) else None
137
+
138
+
139
+ def _quant_label(quantization: Mapping[str, Any] | None) -> str | None:
140
+ if not quantization or not isinstance(quantization.get("bits"), int):
141
+ return None
142
+ default = quantization["bits"]
143
+ layer_bits = {v.get("bits") for v in quantization.values() if isinstance(v, dict)}
144
+ mixed = bool(layer_bits - {default, None})
145
+ return f"{default}-bit mixed" if mixed else f"{default}-bit"
146
+
147
+
148
+ def describe_directory(directory: str, files: Iterable[str]) -> Description:
149
+ """Describe a model stored as a directory of files.
150
+
151
+ Parameters are counted only when the top-level weight files are plainly
152
+ one model: a single file, or a set of numbered shards. A directory that
153
+ holds several variants or components (a diffusers pipeline, a repo with
154
+ five quantizations) gets no count, because a sum would be wrong.
155
+
156
+ :param directory: The model directory, where ``config.json`` lives.
157
+ :param files: Every file of the model, at any depth.
158
+ """
159
+ files = sorted(files)
160
+ by_ext: dict[str, list[str]] = {}
161
+ for path in files:
162
+ by_ext.setdefault(os.path.splitext(path)[1].lower(), []).append(path)
163
+ safetensors = by_ext.get(".safetensors", [])
164
+ ggufs = [p for p in by_ext.get(".gguf", []) if not is_projector(os.path.basename(p))]
165
+
166
+ if safetensors:
167
+ return _describe_safetensors(directory, safetensors)
168
+ if ggufs:
169
+ if len({shard_base(os.path.basename(p)) for p in ggufs}) == 1:
170
+ return describe_gguf(ggufs)
171
+ each = [describe_gguf([p]) for p in ggufs]
172
+ quants = sorted({d.quant for d in each if d.quant})
173
+ counts = {d.params for d in each}
174
+ return Description(
175
+ format="gguf",
176
+ quant=", ".join(quants) or None,
177
+ params=counts.pop() if len(counts) == 1 else None,
178
+ architecture=next((d.architecture for d in each if d.architecture), None),
179
+ issues=[issue for d in each for issue in d.issues],
180
+ )
181
+ for ext, name in _OTHER_FORMATS.items():
182
+ if ext in by_ext:
183
+ return Description(format=name)
184
+ if any(ext in by_ext for ext in PICKLE_EXTENSIONS):
185
+ return Description(format="pytorch")
186
+ return Description(issues=["no weight files"])
187
+
188
+
189
+ def _describe_safetensors(directory: str, safetensors: list[str]) -> Description:
190
+ quantization = read_quantization(directory)
191
+ out = Description(format="safetensors", quant=_quant_label(quantization))
192
+ top = [p for p in safetensors if os.path.dirname(p) == directory]
193
+ stems = [os.path.splitext(os.path.basename(p))[0] for p in top]
194
+ # One file, one set of shards, or several sets of shards (a language
195
+ # model plus its vision tower). Differently named whole files are
196
+ # variants of one another, and adding them up would double count.
197
+ one_model = len({shard_base(os.path.basename(p)) for p in top}) == 1 or (
198
+ bool(stems) and all(_SHARD.match(s) for s in stems)
199
+ )
200
+ params: int | None = 0 if one_model else None
201
+ for path in top if one_model else safetensors[:1]:
202
+ info = read_safetensors(path, quantization=quantization)
203
+ out.issues += [f"{os.path.basename(path)}: {issue}" for issue in info.issues]
204
+ if info.packed or info.metadata.get("format") == "mlx":
205
+ out.format = "mlx"
206
+ out.params_exact = out.params_exact and info.params_exact
207
+ params = None if params is None or info.param_count is None else params + info.param_count
208
+ out.params = params
209
+ return out