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
Prefetch: keep subfolder weights that a root safetensors index maps to (#15184)
Daniel Han3fe735b02478
diff --git a/tests/test_root_index_subfolder_weights.py b/tests/test_root_index_subfolder_weights.pynew file mode 100644index 00000000000..966f08aaa15--- /dev/null+++ b/tests/test_root_index_subfolder_weights.py@@ -0,0 +1,153 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A root safetensors index mapping weights into subfolders (nvidia/Cosmos3-*) must keep those weights in the prefetch."""++import json+import sys+import types+from pathlib import Path++import pytest+from huggingface_hub.utils import filter_repo_objects++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++try:+ import unsloth.models._utils as U+except ImportError as exc: # a bare runner: unsloth_zoo, peft or torch absent+ pytest.skip(f"unsloth is not importable here: {exc}", allow_module_level = True)++SHARD = "transformer/diffusion_pytorch_model-00001-of-00002.safetensors"+VISION = "vision_encoder/model.safetensors"+COSMOS3 = {"weight_map": {"a": SHARD, "b": VISION}}+ROOT_SHARDS = {+ "weight_map": {"a": "model-00001-of-00002.safetensors", "b": "model-00002-of-00002.safetensors"}+}+LISTING = ["config.json", "model.safetensors.index.json", SHARD, VISION, "transformer/config.json"]+++def hub(tmp_path, monkeypatch):+ import huggingface_hub++ for flag in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):+ monkeypatch.delenv(flag, raising = False)+ state = {"index": None, "seen": {}, "calls": []}++ def fake_hf_hub_download(repo_id, filename, *a, **k):+ state["calls"].append({"filename": filename, **k})+ index = state["index"]+ if filename == "model.safetensors.index.json" and index is not None:+ p = tmp_path / filename+ p.write_text(index if isinstance(index, str) else json.dumps(index), encoding = "utf-8")+ return str(p)+ raise OSError(f"404 {filename}")++ class _Api:+ def model_info(self, *a, **k):+ return types.SimpleNamespace(+ siblings = [types.SimpleNamespace(rfilename = f) for f in LISTING]+ )++ def fake_download(repo_id, **kwargs):+ state["seen"] = kwargs+ return str(tmp_path / "snapshot")++ zoo = types.ModuleType("unsloth_zoo.hf_xet_fallback")+ zoo.snapshot_download_with_xet_fallback = fake_download+ zoo.DownloadStallError = type("DownloadStallError", (RuntimeError,), {})+ monkeypatch.setitem(sys.modules, "unsloth_zoo.hf_xet_fallback", zoo)+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_hf_hub_download)+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)++ def run(+ index,+ model = "nvidia/Cosmos3-Edge",+ **kwargs,+ ):+ state.update(index = index, seen = {}, calls = [])+ U.maybe_prefetch_hf_snapshot(model, **{"weights_at_root": True, **kwargs})+ return state["seen"], state["calls"]++ run.state = state+ return run+++ "index, expected",+ [+ (COSMOS3, ("transformer", "vision_encoder")),+ (ROOT_SHARDS, ()),+ (None, ()),+ (+ {"weight_map": {"a": "/transformer\\shard.safetensors", "b": "root.safetensors"}},+ ("transformer",),+ ),+ ("{ not json", ()),+ (["a", "list"], ()),+ ({"weight_map": ["not", "a", "dict"]}, ()),+ ({"weight_map": {"a": None, "b": 3, "c": " / "}}, ()),+ ({"no": "weight_map"}, ()),+ ],+ ids = [+ "subfolders",+ "root_only",+ "no_index",+ "normalised",+ "bad_json",+ "list",+ "map_list",+ "bad_values",+ "no_map",+ ],+)+def test_root_index_weight_subfolders(hub, index, expected):+ hub.state["index"] = index+ assert U._root_index_weight_subfolders("org/repo") == expected+++ "index, keeps_subfolder_weights", [(COSMOS3, True), (ROOT_SHARDS, False), (None, False)]+)+def test_prefetch_keeps_subfolder_weights_only_when_the_root_index_maps_there(+ hub, index, keeps_subfolder_weights+):+ seen, _ = hub(index)+ assert seen, "the downloader was never reached"+ selected = set(+ filter_repo_objects(+ LISTING,+ allow_patterns = seen.get("allow_patterns"),+ ignore_patterns = seen.get("ignore_patterns"),+ )+ )+ assert ({SHARD, VISION} <= selected) is keeps_subfolder_weights, seen+ assert "transformer/config.json" in selected+ pruned, _ = hub(ROOT_SHARDS)+ diff = set(pruned["ignore_patterns"]) - set(seen["ignore_patterns"])+ assert diff == (set(U._SUBDIR_WEIGHT_IGNORE_PATTERNS) if keeps_subfolder_weights else set())+ assert set(seen["ignore_patterns"]) <= set(pruned["ignore_patterns"])+++ "kwargs",+ [+ {"tokenizer_only": True},+ {"adapter_only": True},+ {"gguf_file": "m.gguf"},+ {"subfolder": "transformer"},+ {"weights_at_root": False},+ {"local_files_only": True},+ ],+)+def test_index_is_not_probed_without_a_root_weight_load(hub, kwargs):+ _, calls = hub(COSMOS3, **kwargs)+ assert all(c["filename"] != "model.safetensors.index.json" for c in calls), calls+++def test_probe_forwards_revision_token_and_cache_dir(hub, tmp_path):+ _, calls = hub(COSMOS3, revision = "344d602b", token = "hf_test", cache_dir = str(tmp_path / "c"))+ probe = [c for c in calls if c["filename"] == "model.safetensors.index.json"]+ assert probe and probe[0]["revision"] == "344d602b" and probe[0]["token"] == "hf_test"+ assert probe[0]["cache_dir"] == str(tmp_path / "c")diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 89d17810b29..3e9d8720d69 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -3204,6 +3204,43 @@ def _st_weighted_subfolder_paths(return ()+def _root_index_weight_subfolders(+ model_name,+ *,+ token = None,+ revision = None,+ cache_dir = None,+):+ """Subfolders the root safetensors index maps weights into (Cosmos3 keeps every shard under transformer/), else ()."""+ try:+ import json as _json++ from huggingface_hub import hf_hub_download++ path = hf_hub_download(+ model_name,+ "model.safetensors.index.json",+ token = token,+ revision = revision,+ cache_dir = cache_dir,+ )+ with open(path, "r", encoding = "utf-8") as f:+ index = _json.load(f)+ weight_map = index.get("weight_map") if isinstance(index, dict) else None+ if not isinstance(weight_map, dict):+ return ()+ folders = set()+ for filename in weight_map.values():+ if not isinstance(filename, str):+ continue+ filename = filename.strip().replace("\\", "/").strip("/")+ if "/" in filename:+ folders.add(filename.rsplit("/", 1)[0])+ return tuple(sorted(folders))+ except Exception:+ return ()++def _repo_has_weighted_st_subfolders(model_name,*,@@ -3390,6 +3427,7 @@ def maybe_prefetch_hf_snapshot(# A sentence-transformers repo can hold weights at the root AND in declared module subfolders. Probed once and shared, since the subdir prune and the format prune both span "/" and would drop those weights.st_module_paths = ()+ index_subfolders = ()if (weights_at_rootand not (tokenizer_only or adapter_only or gguf_file)@@ -3401,6 +3439,12 @@ def maybe_prefetch_hf_snapshot(revision = revision,cache_dir = cache_dir,)+ index_subfolders = _root_index_weight_subfolders(+ 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 model_info call are skipped.ignore_patterns = (None@@ -3448,8 +3492,8 @@ def maybe_prefetch_hf_snapshot(# subfolder=X: the load resolves every weight under X/, so warm that subfolder plus root aux.allow_patterns = [f"{subfolder.strip('/')}/*", *_ROOT_AUX_PREFETCH_PATTERNS]elif weights_at_root:- # A bare load reads only root weights, so drop subdir weights and keep subdir configs. Except a sentence-transformers model with a root weight AND weighted module subfolders, which the ST load also reads.- if not st_module_paths:+ # A bare load reads only root weights, so drop subdir weights, except ST module subfolders and a root index mapping into subfolders: then keep all of them, since Cosmos3's root model_index.json makes unsloth_zoo's download gate require every component (vae/ too).+ if not st_module_paths and not index_subfolders:ignore_patterns = [*(ignore_patterns or []), *_SUBDIR_WEIGHT_IGNORE_PATTERNS]try:if snapshot_download_with_xet_fallback is not None: