Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fetch a sentence-transformers model's subfolder weights instead of pruning them (#7855)
Daniel Han057e6fd03fa2
diff --git a/tests/test_prefetch_snapshot_scope.py b/tests/test_prefetch_snapshot_scope.pyindex c7ec4f2c342..97b17c0756a 100644--- a/tests/test_prefetch_snapshot_scope.py+++ b/tests/test_prefetch_snapshot_scope.py@@ -1,18 +1,16 @@-# Unsloth Zoo - Utilities for Unsloth-# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.#-# This program is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published-# by the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at#-# This program is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU Affero General Public License for more details.+# http://www.apache.org/licenses/LICENSE-2.0#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <https://www.gnu.org/licenses/>.+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License."""Pure-CPU, no-network unit tests for prefetch snapshot scoping in unsloth/models/_utils.py.@@ -74,6 +72,14 @@ def capture(monkeypatch):monkeypatch.setattr(huggingface_hub, "HfApi", _NoNetworkApi)+ # Same for the modules.json probe: unstubbed it reaches out for the fake repo, so every+ # weights_at_root case in this no-network file made a live request. The probe is best-effort, so+ # raising here is exactly its "not a sentence-transformers repo" answer.+ def _no_network_download(*a, **k):+ raise RuntimeError("no network in test")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", _no_network_download)+def run(**call_kwargs):state.clear()ok = U.maybe_prefetch_hf_snapshot("some-org/some-repo", **call_kwargs)diff --git a/tests/test_st_subfolder_weights_are_fetched.py b/tests/test_st_subfolder_weights_are_fetched.pynew file mode 100644index 00000000000..927e229dbcf--- /dev/null+++ b/tests/test_st_subfolder_weights_are_fetched.py@@ -0,0 +1,339 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""A sentence-transformers model can have weights at the root AND in subfolders.++`weights_at_root` splits repos two ways, root weights or per-subfolder weights,+and `unsloth/embeddinggemma-300m` is both: a root `model.safetensors` plus+`2_Dense/model.safetensors` and `3_Dense/model.safetensors`, which the ST load+reads as part of the model. `_SUBDIR_WEIGHT_IGNORE_PATTERNS` pruned those two,+unsloth_zoo's post-download gate correctly flagged the missing weights, and the+retry excluded the same files again and raised DownloadStallError, blaming the+network for a request that could never have been satisfied.++Offline: the hub call is stubbed, since a test that depends on the network+eventually reports a bug that is not there.+"""++import json+import sys+import types+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import unsloth.models._utils as U # noqa: E402+++ROOT_ONLY = [+ {"idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer"},+ {"idx": 1, "name": "1", "path": "1_Pooling", "type": "sentence_transformers.models.Pooling"},+]++EMBEDDINGGEMMA = ROOT_ONLY + [+ {"idx": 2, "name": "2", "path": "2_Dense", "type": "sentence_transformers.models.Dense"},+ {"idx": 3, "name": "3", "path": "3_Dense", "type": "sentence_transformers.models.Dense"},+ {"idx": 4, "name": "4", "path": "", "type": "sentence_transformers.models.Normalize"},+]+++def modules_json(tmp_path, monkeypatch):+ """Stub hf_hub_download so it hands back a modules.json we control."""++ def _install(payload):+ if payload is None: # repo ships no modules.json++ def boom(*a, **k):+ raise OSError("404 modules.json")++ monkeypatch.setattr(U, "hf_hub_download", boom, raising = False)+ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", boom)+ return+ p = tmp_path / "modules.json"+ p.write_text(payload if isinstance(payload, str) else json.dumps(payload), encoding = "utf-8")+ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda *a, **k: str(p))++ return _install+++# ---- detection -----------------------------------------------------------+++def test_embeddinggemma_layout_is_detected(modules_json):+ modules_json(EMBEDDINGGEMMA)+ assert U._repo_has_weighted_st_subfolders("unsloth/embeddinggemma-300m") is True+++def test_a_root_only_st_model_is_not(modules_json):+ """Pooling lives in a subfolder but holds no weight, so nothing is at risk+ and the existing subdir pruning should stay in force."""+ modules_json(ROOT_ONLY)+ assert U._repo_has_weighted_st_subfolders("org/plain-st") is False+++def test_a_repo_without_modules_json_is_not(modules_json):+ """The overwhelming majority. A plain causal LM must keep the old+ behaviour exactly, so a fix for one notebook does not enlarge 400 other+ downloads."""+ modules_json(None)+ assert U._repo_has_weighted_st_subfolders("unsloth/Qwen3-0.6B") is False+++ "payload",+ [+ "{ not json",+ json.dumps({"not": "a list"}),+ json.dumps([None, 3, "x"]),+ json.dumps([{"path": "2_Dense"}]), # no type+ json.dumps([{"type": "...Dense"}]), # no path+ json.dumps([{"path": " ", "type": "...Dense"}]), # blank path+ json.dumps([{"path": "/", "type": "...Dense"}]), # root, slash only+ ],+)+def test_malformed_modules_json_falls_back_to_the_old_behaviour(modules_json, payload):+ """Best-effort by design: anything unreadable must not start failing loads+ that work today."""+ modules_json(payload)+ assert U._repo_has_weighted_st_subfolders("org/whatever") is False+++def test_an_unknown_subfolder_module_type_is_not_assumed_weighted(modules_json):+ modules_json([{"path": "2_Custom", "type": "mypkg.WeirdModule"}])+ assert U._repo_has_weighted_st_subfolders("org/custom") is False++[email protected]("leaf", ["Dense", "CNN", "LSTM", "dense"])+def test_every_weight_bearing_type_counts(modules_json, leaf):+ modules_json([{"path": f"2_{leaf}", "type": f"sentence_transformers.models.{leaf}"}])+ assert U._repo_has_weighted_st_subfolders("org/x") is True+++def test_the_taxonomy_is_shared_with_unsloth_zoo_not_restated():+ """If these two ever disagree, unsloth would fetch a module the gate then+ rejects, or prune one it demands -- the exact shape of the original bug."""+ src = (Path(U.__file__)).read_text(encoding = "utf-8")+ assert "_ST_WEIGHTED_MODULE_TYPES" in src+ assert '"dense"' not in src.split("_repo_has_weighted_st_subfolders")[1][:2000]+++# ---- the behaviour that actually changed ---------------------------------+++def _ignores(+ model_name,+ monkeypatch,+ siblings = None,+ **kw,+):+ """The ignore_patterns `maybe_prefetch_hf_snapshot` actually sends.++ Driven through the real function with the downloader stubbed, not through+ `_prefetch_ignore_patterns`, which knows nothing about the subdir branch and+ would have passed either way.+ """+ seen = {}++ def fake_download(name, **kwargs):+ seen.update(kwargs)+ return "/nonexistent/snapshot"++ # The prefetch is a no-op in offline mode, so clear it: nothing here reaches+ # the network anyway, the downloader is stubbed.+ for flag in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):+ monkeypatch.delenv(flag, raising = False)++ import unsloth_zoo.hf_xet_fallback as XF++ monkeypatch.setattr(XF, "snapshot_download_with_xet_fallback", fake_download)+ # The auto format branch calls model_info; unstubbed that is a live request for a real repo.+ import huggingface_hub++ class _Api:+ def model_info(self, *a, **k):+ if siblings is None:+ raise RuntimeError("no network in test")+ return types.SimpleNamespace(+ siblings = [types.SimpleNamespace(rfilename = f) for f in siblings]+ )++ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)+ U.maybe_prefetch_hf_snapshot(model_name, weights_at_root = True, **kw)+ assert seen, "the downloader was never reached; the call bailed out early"+ return list(seen.get("ignore_patterns") or [])+++def test_the_subdir_weight_patterns_are_dropped_for_such_a_repo(modules_json, monkeypatch):+ modules_json(EMBEDDINGGEMMA)+ got = _ignores("unsloth/embeddinggemma-300m", monkeypatch)+ assert "*/*.safetensors" not in got, got+++def test_the_subdir_weight_patterns_are_kept_for_everything_else(modules_json, monkeypatch):+ """The other half of the claim. Without this, the test above would pass+ just as well if the patterns had been deleted outright."""+ modules_json(None)+ got = _ignores("unsloth/Qwen3-0.6B", monkeypatch)+ assert "*/*.safetensors" in got, got+++def test_only_the_subdir_weight_patterns_differ(modules_json, monkeypatch):+ """The fix must not quietly change anything else about the request."""+ modules_json(None)+ plain = set(_ignores("unsloth/Qwen3-0.6B", monkeypatch))+ modules_json(EMBEDDINGGEMMA)+ st = set(_ignores("unsloth/embeddinggemma-300m", monkeypatch))+ assert plain - st == set(U._SUBDIR_WEIGHT_IGNORE_PATTERNS)+ assert st - plain == set()+++def test_the_patterns_still_exist(modules_json):+ """They are correct for the case they were written for -- an fp16/ or+ experimental/ directory a root load never reads. This fix narrows where+ they apply, it does not retire them."""+ assert "*/*.safetensors" in U._SUBDIR_WEIGHT_IGNORE_PATTERNS+ assert "*/*.bin" in U._SUBDIR_WEIGHT_IGNORE_PATTERNS+++def test_an_older_unsloth_zoo_degrades_instead_of_crashing(modules_json):+ """`_ST_WEIGHTED_MODULE_TYPES` is private, so a user on an older zoo must+ fall back to today's pruning rather than get an ImportError on every load."""+ import unsloth_zoo.hf_cache_state as HCS++ modules_json(EMBEDDINGGEMMA)+ saved = HCS._ST_WEIGHTED_MODULE_TYPES+ del HCS._ST_WEIGHTED_MODULE_TYPES+ try:+ assert U._repo_has_weighted_st_subfolders("unsloth/embeddinggemma-300m") is False+ finally:+ HCS._ST_WEIGHTED_MODULE_TYPES = saved+ # ...and the taxonomy being back restores the fix, so the assertion above+ # is about the missing name and not about a broken stub.+ assert U._repo_has_weighted_st_subfolders("unsloth/embeddinggemma-300m") is True+++def test_both_weights_at_root_call_sites_go_through_the_check():+ """`weights_at_root = True` is passed from exactly two places (vision.py and+ llama.py), both reaching the prune through maybe_prefetch_hf_snapshot, so one+ carve-out covers both. A third call site, or an inlined copy of the patterns,+ fails here instead of leaving half the loaders pruning ST weights."""+ root = Path(U.__file__).resolve().parents[1]+ sites = []+ for p in root.rglob("*.py"):+ if "tests" in p.parts:+ continue+ for n, line in enumerate(p.read_text(encoding = "utf-8").splitlines(), 1):+ if "weights_at_root = True" in line:+ sites.append(f"{p.name}:{n}")+ assert sorted(s.split(":")[0] for s in sites) == ["llama.py", "vision.py"], sites++ # AST, not grep: the name also appears in prose inside a docstring, and a+ # text count would police the documentation instead of the code.+ import ast++ tree = ast.parse(Path(U.__file__).read_text(encoding = "utf-8"))+ loads = [+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.Name)+ and n.id == "_SUBDIR_WEIGHT_IGNORE_PATTERNS"+ and isinstance(n.ctx, ast.Load)+ ]+ assert len(loads) == 1, [n.lineno for n in loads]+++def test_a_hub_failure_keeps_the_patterns(monkeypatch):+ """Network trouble must not silently enlarge every download."""+ import huggingface_hub++ def boom(*a, **k):+ raise RuntimeError("hub down")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", boom)+ got = _ignores("org/anything", monkeypatch)+ assert "*/*.safetensors" in got+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))+++# ---- mixed weight formats: root safetensors, subfolder .bin ---------------++BIN_DENSE_FILES = [+ "config.json",+ "modules.json",+ "model.safetensors",+ "pytorch_model.bin",+ "1_Pooling/config.json",+ "2_Dense/config.json",+ "2_Dense/pytorch_model.bin",+]+++def _kept(files, patterns):+ """What snapshot_download would actually fetch, using its own matcher."""+ import fnmatch+ return [f for f in files if not any(fnmatch.fnmatch(f, p) for p in patterns)]+++def test_a_bin_only_dense_module_keeps_its_only_weight(modules_json, monkeypatch):+ """Root model.safetensors plus 2_Dense/pytorch_model.bin, the legacy ST head shape. The redundant+ format prune adds a bare "*.bin", and "*" spans "/" in the Hub's fnmatch, so the glob would strip+ the Dense module's only weight: the same unsatisfiable request, one branch further along."""+ modules_json(EMBEDDINGGEMMA)+ patterns = _ignores("org/st-bin-dense", monkeypatch, siblings = BIN_DENSE_FILES)+ kept = _kept(BIN_DENSE_FILES, patterns)+ assert "2_Dense/pytorch_model.bin" in kept, patterns+ assert "pytorch_model.bin" not in kept, (+ "the redundant ROOT .bin must still be pruned",+ patterns,+ )+ assert "model.safetensors" in kept, patterns+++def test_the_bin_prune_is_untouched_without_st_modules(modules_json, monkeypatch):+ """A plain repo still gets the cheap glob, not an enumeration."""+ modules_json(None)+ patterns = _ignores("org/plain", monkeypatch, siblings = BIN_DENSE_FILES)+ assert "*.bin" in patterns+ assert "pytorch_model.bin" not in _kept(BIN_DENSE_FILES, patterns)+++def test_an_explicit_format_request_keeps_both_for_such_a_repo(modules_json, monkeypatch):+ """use_safetensors fetches no repo listing, so the glob cannot be scoped and pruning it would+ drop the module weight. Keeping both formats is the trade the multi-component case already makes."""+ modules_json(EMBEDDINGGEMMA)+ patterns = _ignores("org/st-bin-dense", monkeypatch, use_safetensors = True)+ assert "*.bin" not in patterns+ modules_json(None)+ assert "*.bin" in _ignores("org/plain", monkeypatch, use_safetensors = True)+++def test_a_module_path_is_not_read_as_a_glob(modules_json, monkeypatch):+ """Repo filenames go into ignore_patterns verbatim, so a "[" in a name would silently become a+ character class and stop matching itself."""+ modules_json(EMBEDDINGGEMMA)+ files = ["model.safetensors", "weird[1].bin", "2_Dense/pytorch_model.bin"]+ patterns = _ignores("org/st-bin-dense", monkeypatch, siblings = files)+ kept = _kept(files, patterns)+ assert "weird[1].bin" not in kept, patterns+ assert "2_Dense/pytorch_model.bin" in kept, patternsdiff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 0f0135c768e..34a9803a0b2 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -1113,6 +1113,96 @@ def _adapter_repo_has_safetensors(return False+def _st_weighted_subfolder_paths(+ model_name,+ *,+ token = None,+ revision = None,+ cache_dir = None,+):+ """Best-effort: which subfolder modules of this sentence-transformers repo hold weights the load+ reads? Returns their declared paths, or () for anything that is not such a repo. Any failure returns+ (), which keeps the previous behaviour.++ weights_at_root is a two-way split, root weights or per-subfolder weights, and an ST model can be+ both: unsloth/embeddinggemma-300m ships a root model.safetensors plus 2_Dense/model.safetensors and+ 3_Dense/model.safetensors, which the ST load reads as part of the model. Pruning those made the+ download unsatisfiable, and unsloth_zoo's post-download gate then reported it as a network fault.++ modules.json is a few hundred bytes, and the module taxonomy is shared with unsloth_zoo rather than+ restated, so the two cannot drift apart."""+ try:+ import json as _json++ from huggingface_hub import hf_hub_download++ from unsloth_zoo.hf_cache_state import _ST_WEIGHTED_MODULE_TYPES++ path = hf_hub_download(+ model_name,+ "modules.json",+ token = token,+ revision = revision,+ cache_dir = cache_dir,+ )+ with open(path, "r", encoding = "utf-8") as f:+ modules = _json.load(f)+ if not isinstance(modules, list):+ return ()+ paths = []+ for module in modules:+ if not isinstance(module, dict):+ continue+ module_path = module.get("path")+ # strip() before strip("/"): " ".strip("/") is still truthy, and blank is not a subfolder.+ if not isinstance(module_path, str) or not module_path.strip().strip("/"):+ continue # the root module, already covered by the root weight check+ module_type = module.get("type")+ leaf = module_type.rsplit(".", 1)[-1].lower() if isinstance(module_type, str) else ""+ if leaf in _ST_WEIGHTED_MODULE_TYPES:+ paths.append(module_path.strip().strip("/").replace("\\", "/"))+ return tuple(paths)+ except Exception:+ return ()+++def _repo_has_weighted_st_subfolders(+ model_name,+ *,+ token = None,+ revision = None,+ cache_dir = None,+):+ """Does this repo declare at least one weight-bearing module subfolder?"""+ return bool(+ _st_weighted_subfolder_paths(+ model_name,+ token = token,+ revision = revision,+ cache_dir = cache_dir,+ )+ )+++def _weight_format_ignore_patterns(extensions, st_module_paths, siblings):+ """ignore_patterns dropping *extensions*, scoped away from declared ST module subfolders.++ A bare "*.bin" spans "/" under the Hub's fnmatch matcher, so on a repo with a root+ model.safetensors AND a 2_Dense/pytorch_model.bin it strips that module's only weight and the+ snapshot is unsatisfiable again. With module paths known, the glob is replaced by the concrete+ repo files outside them: the redundant root weight is still pruned, nothing new is fetched."""+ if not st_module_paths:+ return tuple(f"*{extension}" for extension in extensions)+ from glob import escape as _glob_escape++ prefixes = tuple(f"{path}/" for path in st_module_paths)+ return tuple(+ _glob_escape(name)+ for name in (sibling.rfilename.replace("\\", "/") for sibling in (siblings or []))+ if name.endswith(extensions) and not name.startswith(prefixes)+ )++def _prefetch_ignore_patterns(model_name,*,@@ -1124,6 +1214,7 @@ def _prefetch_ignore_patterns(from_flax = False,variant = None,weights_at_root = False,+ st_module_paths = (),):"""ignore_patterns for the prewarm snapshot: the static skip list, minus the checkpoint guard whenloading from a checkpoint-* subfolder, minus the weight format the load will not read. use_safetensors@@ -1154,6 +1245,11 @@ def _prefetch_ignore_patterns()if whole_multi_component:pass+ elif st_module_paths and (from_tf or from_flax or use_safetensors is not None):+ # An explicit format request cannot be scoped: no repo listing is fetched on these branches, and+ # the globs span "/", so they would prune a declared ST module's only weight. Keep both formats,+ # the same trade whole_multi_component already makes.+ passelif from_tf or from_flax:# TF / Flax loads never read the PyTorch formats; drop safetensors and .bin.ignore_patterns.extend(@@ -1198,7 +1294,13 @@ def _prefetch_ignore_patterns(for sibling in siblings)if has_safetensors:- ignore_patterns.extend(("*.bin", "*.bin.index.json"))+ ignore_patterns.extend(+ _weight_format_ignore_patterns(+ (".bin", ".bin.index.json"),+ st_module_paths,+ siblings,+ )+ )except Exception:passreturn ignore_patterns@@ -1265,6 +1367,21 @@ def maybe_prefetch_hf_snapshot(if fast_inference: # vLLM has its own download pathreturn False+ # A sentence-transformers repo can hold weights at the root AND in declared module subfolders+ # (2_Dense/...). Probed once here and shared, since both the subdir prune below and the redundant+ # format prune span "/" and would drop those weights.+ st_module_paths = ()+ if (+ weights_at_root+ and not (tokenizer_only or adapter_only or gguf_file)+ and not (isinstance(subfolder, str) and subfolder.strip("/"))+ ):+ st_module_paths = _st_weighted_subfolder_paths(+ model_name,+ token = token,+ revision = revision,+ cache_dir = cache_dir,+ )# tokenizer-only / adapter-only warms allow-list exact files below, so the weight-format ignore# list (and its auto-branch model_info call) is skipped.ignore_patterns = (@@ -1280,6 +1397,7 @@ def maybe_prefetch_hf_snapshot(from_flax = from_flax,variant = variant,weights_at_root = weights_at_root,+ st_module_paths = st_module_paths,))# Narrow the warm to what the load reads (skip extra checkpoints/precisions); every branch still warms@@ -1318,7 +1436,12 @@ def maybe_prefetch_hf_snapshot(elif weights_at_root:# A bare load reads only root weights: drop subdir weights (fp16/, checkpoint dirs) while keeping# subdir configs. Diffusion leaves weights_at_root False.- ignore_patterns = [*(ignore_patterns or []), *_SUBDIR_WEIGHT_IGNORE_PATTERNS]+ #+ # Except when the repo is both: a sentence-transformers model with a root weight AND weighted+ # module subfolders (2_Dense/...), which the ST load reads too. Dropping those turned a+ # satisfiable request into one that could never succeed. See _st_weighted_subfolder_paths.+ if not st_module_paths:+ ignore_patterns = [*(ignore_patterns or []), *_SUBDIR_WEIGHT_IGNORE_PATTERNS]try:snapshot_download_with_xet_fallback(model_name,