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,250 @@
1
+ """Find models in any directory tree by what the files are.
2
+
3
+ Used for paths the user names, for the home sweep, and by providers whose
4
+ store is a plain tree of model files (oMLX, LM Studio, llama.cpp).
5
+
6
+ Three shapes are recognized:
7
+
8
+ - a model directory: ``config.json`` beside ``*.safetensors``, or a
9
+ diffusers ``model_index.json``. The whole directory is one record.
10
+ - a GGUF or safetensors file on its own. One record per file, with
11
+ numbered shards (``-00001-of-00004``) joined. A multimodal projector
12
+ (``mmproj``) is kind ``auxiliary``; a GGUF with no tensors is a
13
+ tokenizer stub and is skipped.
14
+ - a large checkpoint known only by its extension (``.pt``, ``.bin``...).
15
+ It is listed with an issue saying it was not verified.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from collections.abc import Callable, Collection, Sequence
22
+ from fnmatch import fnmatch
23
+
24
+ from modelmap.headers import open_local, sniff
25
+ from modelmap.providers.base import (
26
+ PRUNE,
27
+ Context,
28
+ Tally,
29
+ file_size,
30
+ files_under,
31
+ is_dir,
32
+ is_file,
33
+ listdir,
34
+ )
35
+ from modelmap.providers.describe import (
36
+ _OTHER_FORMATS,
37
+ PICKLE_EXTENSIONS,
38
+ Description,
39
+ describe_directory,
40
+ describe_gguf,
41
+ guess_family,
42
+ is_projector,
43
+ shard_base,
44
+ )
45
+ from modelmap.records import ModelRecord
46
+
47
+ NAME = "generic"
48
+ MIN_UNVERIFIED_SIZE = 50_000_000
49
+ # With sniff_all, a file with an unknown extension is opened only above this.
50
+ _SNIFF_MIN_SIZE = 16_000_000
51
+
52
+
53
+ def _name(provider: str, root: str, path: str) -> str:
54
+ """Path under the root for a tool's store; parent and name for a loose file.
55
+
56
+ A sweep finds many files called ``last`` or ``model``; the parent
57
+ directory tells them apart without printing a whole path.
58
+ """
59
+ if provider == NAME:
60
+ return "/".join(path.split(os.sep)[-2:])
61
+ if path == root:
62
+ return os.path.basename(path)
63
+ return os.path.relpath(path, root).replace(os.sep, "/")
64
+
65
+
66
+ def _is_torch_file(path: str) -> bool:
67
+ """True for a zip archive or a pickle stream, the two ``torch.save`` forms."""
68
+ try:
69
+ with open_local(path) as fh:
70
+ head = fh.read(4)
71
+ except OSError:
72
+ return False
73
+ return head == b"PK\x03\x04" or head[:1] == b"\x80"
74
+
75
+
76
+ def _record(
77
+ ctx: Context,
78
+ provider: str,
79
+ name: str,
80
+ path: str,
81
+ files: list[str],
82
+ description: Description,
83
+ kind: str = "model",
84
+ ) -> ModelRecord:
85
+ tally = Tally()
86
+ base = path if os.path.isdir(path) else os.path.dirname(path)
87
+ labels = {f: (os.path.relpath(f, base), "") for f in files}
88
+ tally.charge(ctx, f"{provider}:{name}", files, labels)
89
+ return tally.record(
90
+ issues=description.issues,
91
+ name=name,
92
+ provider=provider,
93
+ format=description.format,
94
+ path=path,
95
+ kind=kind,
96
+ family=guess_family(name, description.architecture),
97
+ quant=description.quant,
98
+ params=description.params,
99
+ params_exact=description.params_exact,
100
+ )
101
+
102
+
103
+ def _scan_files(
104
+ ctx: Context,
105
+ provider: str,
106
+ root: str,
107
+ directory: str,
108
+ files: list[str],
109
+ min_size: int,
110
+ sniff_all: bool,
111
+ ) -> list[ModelRecord]:
112
+ """Records for the loose model files directly inside one directory."""
113
+ groups: dict[tuple[str, str], list[str]] = {}
114
+ records = []
115
+ unreadable = 0
116
+ for path in files:
117
+ base_name = os.path.basename(path)
118
+ ext = os.path.splitext(base_name)[1].lower()
119
+ kind = {".gguf": "gguf", ".safetensors": "safetensors"}.get(ext)
120
+ by_extension = ext in PICKLE_EXTENSIONS or ext in _OTHER_FORMATS
121
+ size = None
122
+ if kind is None and (by_extension or sniff_all):
123
+ size = file_size(path)
124
+ if size is None:
125
+ unreadable += 1
126
+ continue
127
+ if kind is None and by_extension:
128
+ if size is not None and size >= min_size:
129
+ # Inside a tool's own store the location vouches for the file;
130
+ # elsewhere a checkpoint must at least start like one.
131
+ unverified = (
132
+ ext in PICKLE_EXTENSIONS and provider == NAME and not _is_torch_file(path)
133
+ )
134
+ description = Description(
135
+ format=_OTHER_FORMATS.get(ext, "pytorch"),
136
+ issues=["unverified: identified by extension only"] if unverified else [],
137
+ )
138
+ name = _name(provider, root, os.path.splitext(path)[0])
139
+ records.append(_record(ctx, provider, name, path, [path], description))
140
+ continue
141
+ if kind is None and sniff_all and size is not None and size >= _SNIFF_MIN_SIZE:
142
+ kind = sniff(path)
143
+ if kind:
144
+ groups.setdefault((kind, shard_base(base_name)), []).append(path)
145
+
146
+ if unreadable:
147
+ # One warning for the directory, not one per file.
148
+ ctx.warn(directory, f"{unreadable} files could not be examined")
149
+ for (kind, base), paths in sorted(groups.items()):
150
+ name = _name(provider, root, os.path.join(directory, base))
151
+ if kind == "gguf":
152
+ description = describe_gguf(paths)
153
+ if description.vocab_only:
154
+ continue
155
+ else:
156
+ description = describe_directory(directory, paths)
157
+ role = "auxiliary" if is_projector(base) else "model"
158
+ path = paths[0] if len(paths) == 1 else directory
159
+ records.append(_record(ctx, provider, name, path, paths, description, role))
160
+ return records
161
+
162
+
163
+ def scan_tree(
164
+ root: str,
165
+ ctx: Context,
166
+ *,
167
+ provider: str = NAME,
168
+ max_depth: int | None = None,
169
+ claimed: Collection[str] = (),
170
+ min_size: int = MIN_UNVERIFIED_SIZE,
171
+ config_marks_model: bool = False,
172
+ sniff_all: bool = False,
173
+ excludes: Sequence[str] = (),
174
+ claim: Callable[[str, set[str]], list[ModelRecord] | None] | None = None,
175
+ root_may_be_model: bool = False,
176
+ ) -> list[ModelRecord]:
177
+ """Find every model under a directory.
178
+
179
+ :param root: Directory to walk; pass a resolved path.
180
+ :param ctx: The scan context.
181
+ :param provider: Provider name to put on the records.
182
+ :param max_depth: Levels below ``root`` to descend; None for no limit.
183
+ :param claimed: Resolved directories another provider owns; not entered.
184
+ :param min_size: Smallest file to list when only its extension says it
185
+ is a model.
186
+ :param config_marks_model: Treat a directory holding ``config.json`` as
187
+ a model even with no weight files in it. True inside a tool's own
188
+ store, where such a directory is a broken download; false in a
189
+ sweep, where ``config.json`` is everywhere.
190
+ :param sniff_all: Open large files with unknown extensions to check for
191
+ a GGUF or safetensors header.
192
+ :param excludes: Glob patterns; a file or directory whose name or full
193
+ path matches one is skipped.
194
+ :param claim: Called with each directory and the names in it. If it
195
+ returns records, the directory is some tool's store: the records
196
+ are kept and the walk does not enter it.
197
+ :param root_may_be_model: Let ``root`` itself be one model directory.
198
+ True for a path the user named; false for a store or a sweep.
199
+ :return: Records in directory order.
200
+ """
201
+
202
+ def excluded(entry: os.DirEntry[str]) -> bool:
203
+ return any(fnmatch(entry.name, p) or fnmatch(entry.path, p) for p in excludes)
204
+
205
+ records: list[ModelRecord] = []
206
+ stack = [(root, 0)]
207
+ while stack:
208
+ directory, depth = stack.pop()
209
+ entries = [e for e in listdir(ctx, directory) if not excluded(e)]
210
+ names = {e.name for e in entries}
211
+ if claim:
212
+ found = claim(directory, names)
213
+ if found is not None:
214
+ records += found
215
+ continue
216
+ files = [e.path for e in entries if is_file(e)]
217
+ has_safetensors = any(f.endswith(".safetensors") for f in files)
218
+ is_model_dir = "model_index.json" in names or (
219
+ "config.json" in names and (has_safetensors or config_marks_model)
220
+ )
221
+ if is_model_dir and (directory != root or root_may_be_model):
222
+ contents = files_under(ctx, directory)
223
+ present = [f for f in contents if os.path.exists(f)]
224
+ description = describe_directory(directory, present)
225
+ name = _name(provider, root, directory)
226
+ records.append(_record(ctx, provider, name, directory, contents, description))
227
+ continue
228
+
229
+ records += _scan_files(ctx, provider, root, directory, files, min_size, sniff_all)
230
+ if max_depth is not None and depth >= max_depth:
231
+ continue
232
+ subdirs = [
233
+ e.path
234
+ for e in entries
235
+ if is_dir(e, follow_symlinks=False) and e.name not in PRUNE and e.path not in claimed
236
+ ]
237
+ stack.extend((path, depth + 1) for path in reversed(subdirs))
238
+ return records
239
+
240
+
241
+ def scan_file(path: str, ctx: Context, *, min_size: int = 0) -> list[ModelRecord]:
242
+ """Describe one file the user named.
243
+
244
+ :param path: Resolved path of a file.
245
+ :param ctx: The scan context.
246
+ :param min_size: Floor for a file known only by its extension.
247
+ :return: One record, or none if the file is not a model.
248
+ """
249
+ directory = os.path.dirname(path)
250
+ return _scan_files(ctx, NAME, directory, directory, [path], min_size, sniff_all=True)
@@ -0,0 +1,219 @@
1
+ """The Hugging Face hub cache and the Xet cache beside it.
2
+
3
+ Layout (``huggingface_hub`` ``constants.py``, the manage-cache guide, and a
4
+ real cache):
5
+
6
+ - ``<hub>/models--org--name/`` per repository, also ``datasets--`` and
7
+ ``spaces--``. Inside: ``blobs/<hash>`` holds the content,
8
+ ``snapshots/<revision>/<path>`` are symlinks into ``blobs``, ``refs/main``
9
+ names the current revision, and ``.no_exist/`` holds empty markers for
10
+ files the Hub does not have.
11
+ - ``<hub>/blobs/<2 hex>/<xet hash>`` is a store shared between
12
+ repositories (``huggingface_hub`` 1.32 and later). A repository's
13
+ ``blobs/<hash>`` is then itself a symlink into it. Each shared blob has
14
+ ``.refs`` and ``.lock`` files beside it.
15
+ - ``<HF_HOME>/xet`` holds Xet shards and upload staging, not model files.
16
+ It can be deleted and is rebuilt.
17
+
18
+ A repository is charged through its ``blobs`` entries, following links, so
19
+ content in the shared store is attributed to the repositories that use it.
20
+ Snapshots give the file names and headers only.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+
27
+ from modelmap.headers import sniff
28
+ from modelmap.providers.base import Context, Tally, files_under, is_dir, listdir
29
+ from modelmap.providers.describe import describe_directory, describe_gguf, guess_family
30
+ from modelmap.records import ModelRecord, ScanRoot
31
+
32
+ NAME = "hf"
33
+ _XET = "hf-xet"
34
+ _KINDS = {"models": "model", "datasets": "dataset", "spaces": "other"}
35
+ _SHARED_BOOKKEEPING = (".refs", ".lock")
36
+
37
+
38
+ def roots(ctx: Context) -> list[ScanRoot]:
39
+ """The hub cache and the Xet cache.
40
+
41
+ Hub precedence: ``HF_HUB_CACHE``, ``HUGGINGFACE_HUB_CACHE``,
42
+ ``HF_HOME/hub``, ``XDG_CACHE_HOME/huggingface/hub``,
43
+ ``~/.cache/huggingface/hub``. Xet: ``HF_XET_CACHE``, else ``HF_HOME/xet``.
44
+ """
45
+ home_var = ctx.first_env("HF_HOME")
46
+ xdg = ctx.first_env("XDG_CACHE_HOME")
47
+ if home_var:
48
+ hf_home, home_source = ctx.expand(home_var[1]), "HF_HOME"
49
+ elif xdg:
50
+ hf_home, home_source = ctx.expand(xdg[1]) / "huggingface", "XDG_CACHE_HOME"
51
+ else:
52
+ hf_home, home_source = ctx.home / ".cache" / "huggingface", "default"
53
+
54
+ direct = ctx.first_env("HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE")
55
+ if direct:
56
+ hub = ctx.root(NAME, ctx.expand(direct[1]), direct[0])
57
+ else:
58
+ hub = ctx.root(NAME, hf_home / "hub", home_source)
59
+ xet_var = ctx.first_env("HF_XET_CACHE")
60
+ if xet_var:
61
+ xet = ctx.root(_XET, ctx.expand(xet_var[1]), xet_var[0])
62
+ else:
63
+ xet = ctx.root(_XET, hf_home / "xet", home_source)
64
+ return [hub, xet]
65
+
66
+
67
+ def _current_snapshot(ctx: Context, repo: str) -> str | None:
68
+ """The snapshot ``refs/main`` names, else the newest one."""
69
+ snapshots = os.path.join(repo, "snapshots")
70
+ try:
71
+ with open(os.path.join(repo, "refs", "main"), encoding="utf-8") as fh:
72
+ named = os.path.join(snapshots, fh.read().strip())
73
+ if os.path.isdir(named):
74
+ return named
75
+ except OSError:
76
+ pass
77
+ if not os.path.isdir(snapshots):
78
+ return None
79
+ dated = []
80
+ for entry in listdir(ctx, snapshots):
81
+ try:
82
+ if entry.is_dir():
83
+ dated.append((entry.stat().st_mtime, entry.name, entry.path))
84
+ except OSError:
85
+ continue
86
+ return max(dated)[2] if dated else None
87
+
88
+
89
+ def _scan_repo(ctx: Context, repo: os.DirEntry[str], provider: str) -> ModelRecord | None:
90
+ prefix, _, rest = repo.name.partition("--")
91
+ name = rest.replace("--", "/")
92
+ snapshot = _current_snapshot(ctx, repo.path)
93
+ files = files_under(ctx, snapshot) if snapshot else []
94
+ present = [f for f in files if os.path.exists(f)]
95
+ # Blobs are named by hash; the current snapshot gives them their names.
96
+ named = {os.path.realpath(f): os.path.relpath(f, snapshot) for f in present} if snapshot else {}
97
+
98
+ tally = Tally()
99
+ blobs = os.path.join(repo.path, "blobs")
100
+ if os.path.isdir(blobs):
101
+ entries = listdir(ctx, blobs)
102
+ labels = {}
103
+ for entry in entries:
104
+ label = named.get(os.path.realpath(entry.path))
105
+ if entry.name.endswith(".incomplete"):
106
+ labels[entry.path] = (entry.name[:16], "incomplete download")
107
+ elif label is None:
108
+ labels[entry.path] = (entry.name[:16], "not in the current revision")
109
+ else:
110
+ labels[entry.path] = (label, "")
111
+ tally.charge(ctx, f"{provider}:{name}", [e.path for e in entries], labels)
112
+ if any(e.name.endswith(".incomplete") for e in entries):
113
+ tally.issues.append("incomplete download")
114
+ if not tally.files:
115
+ # Only refs or .no_exist markers: the Hub was asked, nothing is stored.
116
+ return None
117
+
118
+ kind = _KINDS[prefix]
119
+ issues: list[str] = []
120
+ if snapshot:
121
+ issues += [
122
+ f"broken link: {os.path.relpath(f, snapshot)}" for f in files if f not in present
123
+ ]
124
+ description = describe_directory(snapshot or repo.path, present)
125
+ if description.format == "unknown":
126
+ # Config and tokenizer files only, or a dataset: nothing to describe.
127
+ description.format, description.issues = "files", []
128
+ if kind == "model":
129
+ kind = "other"
130
+ return tally.record(
131
+ issues=issues + description.issues,
132
+ name=name,
133
+ provider=provider,
134
+ format=description.format,
135
+ path=repo.path,
136
+ kind=kind,
137
+ family=guess_family(name, description.architecture) if kind == "model" else None,
138
+ quant=description.quant,
139
+ params=description.params,
140
+ params_exact=description.params_exact,
141
+ )
142
+
143
+
144
+ def _scan_shared(ctx: Context, hub: str, provider: str) -> list[ModelRecord]:
145
+ """Shared blobs that no repository links to."""
146
+ shared = os.path.join(hub, "blobs")
147
+ if not os.path.isdir(shared):
148
+ return []
149
+ records = []
150
+ rest = Tally()
151
+ for path in files_under(ctx, shared):
152
+ base = os.path.basename(path)
153
+ if path.endswith(_SHARED_BOOKKEEPING) or base.startswith("."):
154
+ continue
155
+ if ctx.ledger.owner(path) is not None:
156
+ continue
157
+ if sniff(path) == "gguf":
158
+ description = describe_gguf([path])
159
+ name = f"shared blob {base[:12]}"
160
+ tally = Tally()
161
+ tally.charge(ctx, f"{provider}:{name}", [path])
162
+ records.append(
163
+ tally.record(
164
+ issues=["no repository refers to this blob", *description.issues],
165
+ name=name,
166
+ provider=provider,
167
+ format="gguf",
168
+ path=path,
169
+ family=guess_family(name, description.architecture),
170
+ quant=description.quant,
171
+ params=description.params,
172
+ )
173
+ )
174
+ else:
175
+ rest.charge(ctx, f"{provider}:unreferenced shared blobs", [path])
176
+ if rest.files:
177
+ records.append(
178
+ rest.record(
179
+ name="unreferenced shared blobs",
180
+ provider=provider,
181
+ format="files",
182
+ path=shared,
183
+ kind="unattributed",
184
+ )
185
+ )
186
+ return records
187
+
188
+
189
+ def scan_hub(hub: str, ctx: Context, provider: str = NAME) -> list[ModelRecord]:
190
+ """Every repository in a hub-layout cache, plus unreferenced shared blobs.
191
+
192
+ :param hub: Resolved cache directory.
193
+ :param ctx: The scan context.
194
+ :param provider: Provider name for the records; llama.cpp uses the same
195
+ layout under ``LLAMA_CACHE``.
196
+ """
197
+ records = []
198
+ for entry in listdir(ctx, hub):
199
+ prefix = entry.name.partition("--")[0]
200
+ if prefix in _KINDS and "--" in entry.name and is_dir(entry):
201
+ record = _scan_repo(ctx, entry, provider)
202
+ if record:
203
+ records.append(record)
204
+ return records + _scan_shared(ctx, hub, provider)
205
+
206
+
207
+ def scan(root: ScanRoot, ctx: Context) -> list[ModelRecord]:
208
+ """The hub cache, or one ``cache`` record for the Xet directory."""
209
+ if root.provider != _XET:
210
+ return scan_hub(root.resolved, ctx)
211
+ tally = Tally()
212
+ tally.charge(ctx, f"{NAME}:xet cache", files_under(ctx, root.resolved))
213
+ if not tally.files:
214
+ return []
215
+ return [
216
+ tally.record(
217
+ name="xet cache", provider=NAME, format="files", path=root.resolved, kind="cache"
218
+ )
219
+ ]