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
Studio: load downloaded tokenizers offline, size unsloth mirrors from the family table (#12300)
Daniel Han7cee0c1888b1
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex bb1f3e8afd4..14389f9c768 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -7739,7 +7739,10 @@ class DiffusionBackend:model_dense_mib = estimate_safetensors_dense_mib(cached_mib)# A repo can store weights NARROWER than the loaded dtype (ideogram-4 ships raw float8), so cached bytes# undershoot the bf16 footprint ~2x. Plan against the size table's bf16 total when it knows this repo.- is_narrow_base = bool(repo_id) and repo_id.strip().lower() == fam.base_repo.lower()+ # A known mirror is a byte copy of its upstream, so it reads the upstream's table.+ is_narrow_base = (+ bool(repo_id) and canonical_base(repo_id).lower() == fam.base_repo.strip().lower()+ )if (not is_narrow_baseand fam.name == IDEOGRAM4_FAMILY_NAMEdiff --git a/studio/backend/core/inference/diffusion_krea2.py b/studio/backend/core/inference/diffusion_krea2.pyindex 69a9346d659..a0c13ff5248 100644--- a/studio/backend/core/inference/diffusion_krea2.py+++ b/studio/backend/core/inference/diffusion_krea2.py@@ -62,20 +62,27 @@ def load_krea2_tokenizer(check_cancelled()from transformers import AutoTokenizer+ from .diffusion_offline_source import offline_snapshot_source++ cache_dir = _live_cache_dir()kwargs: dict[str, Any] = {"subfolder": "tokenizer","local_files_only": local_files_only,- "cache_dir": _live_cache_dir(),+ "cache_dir": cache_dir,}if hf_token:kwargs["token"] = hf_token+ # Offline by repo id, transformers 5.x fails both attempts below (see diffusion_offline_source).+ source = offline_snapshot_source(+ repo_id, "tokenizer", local_files_only = local_files_only, cache_dir = cache_dir+ )try:- return AutoTokenizer.from_pretrained(repo_id, **kwargs)+ return AutoTokenizer.from_pretrained(source, **kwargs)except Exception as exc: # noqa: BLE001 -- 4.x config-parse failure, retry with overrideif check_cancelled is not None:check_cancelled()logger.info("diffusion.krea2 tokenizer compat fallback: %s", exc)- return AutoTokenizer.from_pretrained(repo_id, extra_special_tokens = {}, **kwargs)+ return AutoTokenizer.from_pretrained(source, extra_special_tokens = {}, **kwargs)def remap_rope_parameters(text_config) -> None:diff --git a/studio/backend/core/inference/diffusion_offline_source.py b/studio/backend/core/inference/diffusion_offline_source.pynew file mode 100644index 00000000000..ffa9b15d9a5--- /dev/null+++ b/studio/backend/core/inference/diffusion_offline_source.py@@ -0,0 +1,120 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Offline tokenizer / processor loads open the cached snapshot folder, not the Hub repo id.++transformers 5.x asks for ``<subfolder>/config.json`` first; offline by repo id it ignores the+``.no_exist`` marker and raises, while a local folder just skips the missing file.+"""++from __future__ import annotations++import os+from pathlib import Path, PurePosixPath+from typing import Any, Optional++# Any one locates the snapshot; the loader reports a genuinely missing file by name.+_PROBE_FILES = (+ "tokenizer_config.json",+ "processor_config.json",+ "preprocessor_config.json",+ "tokenizer.json",+)+++def _offline_requested(local_files_only: bool) -> bool:+ if local_files_only:+ return True+ try:+ from huggingface_hub import constants+ return bool(constants.HF_HUB_OFFLINE)+ except Exception: # noqa: BLE001 -- no hub library means nothing to redirect+ return False+++def offline_snapshot_source(+ repo_id: Any,+ subfolder: Optional[str],+ *,+ local_files_only: bool,+ cache_dir: Optional[str] = None,+ revision: Optional[str] = None,+) -> Any:+ """The cached snapshot folder for ``repo_id`` when this load is offline and ``subfolder`` is+ cached there; ``repo_id`` unchanged otherwise (online, a local path, or nothing cached)."""+ if not isinstance(repo_id, str) or not repo_id or not _offline_requested(local_files_only):+ return repo_id+ try:+ if Path(repo_id).expanduser().is_dir():+ return repo_id+ except (OSError, ValueError):+ return repo_id+ try:+ from huggingface_hub import try_to_load_from_cache+ except Exception: # noqa: BLE001+ return repo_id+ parts = PurePosixPath((subfolder or "").replace("\\", "/").strip("/")).parts+ for name in _PROBE_FILES:+ rel = "/".join((*parts, name))+ try:+ hit = try_to_load_from_cache(repo_id, rel, cache_dir = cache_dir, revision = revision)+ except Exception: # noqa: BLE001 -- an invalid id or unreadable cache: keep the caller's source+ continue+ if not isinstance(hit, str):+ continue+ root = Path(hit).parent+ for _ in parts:+ root = root.parent+ if root.is_dir():+ return os.fspath(root)+ return repo_id+++def _is_tokenizer_or_processor(type_hint: Any) -> bool:+ if not isinstance(type_hint, type):+ return False+ try:+ import transformers+ except Exception: # noqa: BLE001+ return False+ bases = tuple(+ cls+ for cls in (+ getattr(transformers, "PreTrainedTokenizerBase", None),+ getattr(transformers, "ProcessorMixin", None),+ )+ if isinstance(cls, type)+ )+ return bool(bases) and issubclass(type_hint, bases)+++def offline_component_sources(+ pipe: Any,+ *,+ local_files_only: bool,+ cache_dir: Optional[str] = None,+) -> dict[str, str]:+ """``{component: snapshot folder}`` for the tokenizer / processor specs, as the per-component+ ``load_components(pretrained_model_name_or_path = ...)`` dict."""+ if not _offline_requested(local_files_only):+ return {}+ specs = getattr(pipe, "_component_specs", None)+ if not isinstance(specs, dict):+ return {}+ overrides: dict[str, str] = {}+ for name, spec in specs.items():+ if getattr(spec, "default_creation_method", "from_pretrained") != "from_pretrained":+ continue+ if not _is_tokenizer_or_processor(getattr(spec, "type_hint", None)):+ continue+ repo_id = getattr(spec, "pretrained_model_name_or_path", None)+ source = offline_snapshot_source(+ repo_id,+ getattr(spec, "subfolder", None),+ local_files_only = local_files_only,+ cache_dir = cache_dir,+ revision = getattr(spec, "revision", None),+ )+ if source != repo_id:+ overrides[name] = source+ return overridesdiff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 1d0af4d89af..99c97b0682e 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -6127,12 +6127,19 @@ class VideoBackend:# cache_dir for the same reason as the token: load_components forwards extra kwargs through ComponentSpec.load# into each from_pretrained, and without it those ~145 GB of Hub-pinned components resolve against the# import-time HF_HUB_CACHE snapshot rather than Unsloth's live cache folder, which the user can move.+ # Offline by repo id, load_components only warns and returns processor=None (diffusion_offline_source).+ from .diffusion_offline_source import offline_component_sources++ offline_sources = offline_component_sources(+ pipe, local_files_only = local_files_only, cache_dir = hub_cache_dir()+ )pipe.load_components(workflow = workflow,dtype = dtype,cache_dir = hub_cache_dir(),local_files_only = local_files_only,**({"token": hf_token} if hf_token else {}),+ **({"pretrained_model_name_or_path": offline_sources} if offline_sources else {}),)# The video VAE loads at float32 and the decode runs under float16 autocast, so both copies are resident for the# whole decode. Pre-casting the decoder removes the pair without changing a single output value. The encoderdiff --git a/studio/backend/tests/test_diffusion_mirror_size_table.py b/studio/backend/tests/test_diffusion_mirror_size_table.pynew file mode 100644index 00000000000..d6d532e87ab--- /dev/null+++ b/studio/backend/tests/test_diffusion_mirror_size_table.py@@ -0,0 +1,80 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An uncached unsloth mirror is sized from its family's bf16 table, like its upstream (empty caches, no GPU)."""++from __future__ import annotations++import types++import pytest++from core.inference import diffusion as dmod+from core.inference.diffusion import DiffusionBackend+from core.inference.diffusion_families import canonical_base, detect_family+from core.inference.diffusion_memory import OFFLOAD_NONE, DeviceMemory++MIRROR = "unsloth/FLUX.1-schnell"+UPSTREAM = "black-forest-labs/FLUX.1-schnell"+++def l4_with_empty_cache(monkeypatch, tmp_path):+ from huggingface_hub import constants as hf_constants++ live, other = tmp_path / "live-hub", tmp_path / "import-time-hub"+ live.mkdir()+ other.mkdir()+ monkeypatch.setattr(dmod, "hub_cache_dir", lambda: str(live))+ monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(other))+ # A 24 GB L4 with ~22 GB free.+ monkeypatch.setattr(+ dmod,+ "settled_snapshot_device_memory",+ lambda t: DeviceMemory("cuda", "cuda", "discrete_vram", 22_000, 23_034),+ )+ monkeypatch.setattr(dmod, "estimate_image_runtime_mib", lambda **kw: 1_000)+ return types.SimpleNamespace(device = "cuda", backend = "cuda", supports_model_cpu_offload = True)+++def _plan(target, repo_id):+ fam = detect_family(repo_id)+ assert fam is not None and fam.base_repo.lower() == UPSTREAM.lower()+ return DiffusionBackend()._plan_memory(+ target, None, repo_id, fam, None, False, kind = "pipeline", repo_id = repo_id+ )+++def test_the_mirror_table_pairs_this_repo_with_the_family_base():+ assert canonical_base(MIRROR) == UPSTREAM+++def test_an_uncached_mirror_is_sized_from_the_family_table(l4_with_empty_cache):+ plan = _plan(l4_with_empty_cache, MIRROR)+ assert plan.estimates["model_dense_mib"] is not None, plan.reasons+ assert plan.offload_policy != OFFLOAD_NONE, plan.reasons+ assert not any("unknown" in reason for reason in plan.reasons), plan.reasons+++def test_the_mirror_plans_exactly_like_its_upstream(l4_with_empty_cache):+ mirror, upstream = _plan(l4_with_empty_cache, MIRROR), _plan(l4_with_empty_cache, UPSTREAM)+ assert mirror.offload_policy == upstream.offload_policy+ for key in ("model_dense_mib", "companion_dense_mib", "text_encoder_dense_mib"):+ assert mirror.estimates[key] == upstream.estimates[key], key+++def test_an_unrelated_repo_still_sizes_from_its_own_bytes(l4_with_empty_cache):+ """Only a known mirror borrows the table: a fine-tune in the same family, uncached, stays+ unknown exactly as before."""+ fam = detect_family(UPSTREAM)+ plan = DiffusionBackend()._plan_memory(+ l4_with_empty_cache,+ None,+ "someone/flux-schnell-finetune",+ fam,+ None,+ False,+ kind = "pipeline",+ repo_id = "someone/flux-schnell-finetune",+ )+ assert plan.estimates["model_dense_mib"] is Nonediff --git a/studio/backend/tests/test_diffusion_offline_source.py b/studio/backend/tests/test_diffusion_offline_source.pynew file mode 100644index 00000000000..aada5b8e699--- /dev/null+++ b/studio/backend/tests/test_diffusion_offline_source.py@@ -0,0 +1,243 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A fully downloaded model must load its tokenizer / processor offline (hand-built hub cache)."""++from __future__ import annotations++import ast+import json+import pathlib+import sys+from types import SimpleNamespace++import pytest++from core.inference import diffusion_offline_source as offline_source++REPO = "acme/tiny-diffusion"+SHA = "0123456789abcdef0123456789abcdef01234567"+++def _fake_cache(+ root: pathlib.Path,+ *,+ subfolders = ("tokenizer",),+ no_exist_marker = True,+) -> pathlib.Path:+ """A completed download; the ``.no_exist`` marker (an online 404) does not rescue a repo-id load."""+ repo_dir = root / ("models--" + REPO.replace("/", "--"))+ (repo_dir / "refs").mkdir(parents = True)+ (repo_dir / "refs" / "main").write_text(SHA, encoding = "utf-8")+ snapshot = repo_dir / "snapshots" / SHA+ for sub in subfolders:+ (snapshot / sub).mkdir(parents = True)+ (snapshot / sub / "tokenizer_config.json").write_text("{}", encoding = "utf-8")+ if no_exist_marker:+ marker = repo_dir / ".no_exist" / SHA / sub / "config.json"+ marker.parent.mkdir(parents = True, exist_ok = True)+ marker.touch()+ return snapshot+++def online(monkeypatch):+ import huggingface_hub.constants as constants+ monkeypatch.setattr(constants, "HF_HUB_OFFLINE", False)+++def test_an_offline_load_opens_the_cached_snapshot_folder(tmp_path, online):+ snapshot = _fake_cache(tmp_path)+ got = offline_source.offline_snapshot_source(+ REPO, "tokenizer", local_files_only = True, cache_dir = str(tmp_path)+ )+ assert pathlib.Path(got) == snapshot+++def test_hf_hub_offline_counts_as_offline(tmp_path, monkeypatch):+ import huggingface_hub.constants as constants++ snapshot = _fake_cache(tmp_path)+ monkeypatch.setattr(constants, "HF_HUB_OFFLINE", True)+ got = offline_source.offline_snapshot_source(+ REPO, "tokenizer", local_files_only = False, cache_dir = str(tmp_path)+ )+ assert pathlib.Path(got) == snapshot+++def test_an_online_load_keeps_the_repo_id(tmp_path, online):+ _fake_cache(tmp_path)+ assert (+ offline_source.offline_snapshot_source(+ REPO, "tokenizer", local_files_only = False, cache_dir = str(tmp_path)+ )+ == REPO+ )+++def test_nothing_cached_keeps_the_repo_id(tmp_path, online):+ _fake_cache(tmp_path, subfolders = ("vae",))+ assert (+ offline_source.offline_snapshot_source(+ REPO, "tokenizer", local_files_only = True, cache_dir = str(tmp_path)+ )+ == REPO+ )+ assert (+ offline_source.offline_snapshot_source(+ "acme/never-downloaded", "tokenizer", local_files_only = True, cache_dir = str(tmp_path)+ )+ == "acme/never-downloaded"+ )+++def test_a_local_folder_is_left_alone(tmp_path, online):+ local = tmp_path / "local_model"+ (local / "tokenizer").mkdir(parents = True)+ assert offline_source.offline_snapshot_source(+ str(local), "tokenizer", local_files_only = True, cache_dir = str(tmp_path)+ ) == str(local)+++def _spec(+ type_hint,+ subfolder,+ repo = REPO,+):+ return SimpleNamespace(+ type_hint = type_hint,+ subfolder = subfolder,+ pretrained_model_name_or_path = repo,+ revision = None,+ default_creation_method = "from_pretrained",+ )+++def test_modular_tokenizer_and_processor_specs_are_pointed_at_the_snapshot(tmp_path, online):+ transformers = pytest.importorskip("transformers")++ class _Processor(transformers.ProcessorMixin):+ pass++ class _Tokenizer(transformers.PreTrainedTokenizerBase):+ pass++ class _Encoder(transformers.PreTrainedModel):+ pass++ snapshot = _fake_cache(tmp_path, subfolders = ("processor", "tokenizer", "text_encoder"))+ pipe = SimpleNamespace(+ _component_specs = {+ "processor": _spec(_Processor, "processor"),+ "tokenizer": _spec(_Tokenizer, "tokenizer"),+ # Models carry their own config.json and load offline by repo id already.+ "text_encoder": _spec(_Encoder, "text_encoder"),+ "guider": SimpleNamespace(type_hint = _Tokenizer, default_creation_method = "from_config"),+ }+ )+ offline = offline_source.offline_component_sources(+ pipe, local_files_only = True, cache_dir = str(tmp_path)+ )+ assert {k: pathlib.Path(v) for k, v in offline.items()} == {+ "processor": snapshot,+ "tokenizer": snapshot,+ }+ assert (+ offline_source.offline_component_sources(+ pipe, local_files_only = False, cache_dir = str(tmp_path)+ )+ == {}+ )+++def test_the_h3_modular_build_hands_the_offline_sources_to_load_components():+ """The H3 build needs a real Modular Diffusers pipeline to reach, so read the call site: the+ per-component source override has to be spelled on load_components."""+ backend_root = pathlib.Path(offline_source.__file__).resolve().parents[2]+ tree = ast.parse((backend_root / "core/inference/video.py").read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name == "_load_h3_modular_pipeline":+ calls = [+ call+ for call in ast.walk(node)+ if isinstance(call, ast.Call)+ and getattr(call.func, "attr", None) == "load_components"+ ]+ assert calls, "no load_components call"+ sources = ast.unparse(node)+ assert "offline_component_sources(" in sources+ for call in calls:+ spelled = ast.unparse(call)+ assert "pretrained_model_name_or_path" in spelled, spelled+ return+ raise AssertionError("_load_h3_modular_pipeline not found")+++def _live_cache(monkeypatch, root: pathlib.Path) -> None:+ import utils.hf_cache_settings as cache_settings+ monkeypatch.setattr(cache_settings, "active_hf_hub_cache", lambda: str(root))+++def test_the_krea_tokenizer_and_its_fallback_open_the_snapshot_offline(+ monkeypatch, tmp_path, online+):+ from core.inference import diffusion_krea2++ snapshot = _fake_cache(tmp_path)+ _live_cache(monkeypatch, tmp_path)+ sources: list = []++ class _AutoTokenizer:+ @staticmethod+ def from_pretrained(source, **kwargs):+ sources.append(source)+ if "extra_special_tokens" not in kwargs:+ raise OSError("4.x compat failure")+ return SimpleNamespace(source = source)++ monkeypatch.setitem(sys.modules, "transformers", SimpleNamespace(AutoTokenizer = _AutoTokenizer))+ diffusion_krea2.load_krea2_tokenizer(REPO, local_files_only = True)+ assert [pathlib.Path(s) for s in sources] == [snapshot, snapshot]+++def test_an_online_krea_tokenizer_load_still_uses_the_repo_id(monkeypatch, tmp_path, online):+ from core.inference import diffusion_krea2++ _fake_cache(tmp_path)+ _live_cache(monkeypatch, tmp_path)+ sources: list = []++ class _AutoTokenizer:+ @staticmethod+ def from_pretrained(source, **kwargs):+ sources.append(source)+ return SimpleNamespace()++ monkeypatch.setitem(sys.modules, "transformers", SimpleNamespace(AutoTokenizer = _AutoTokenizer))+ diffusion_krea2.load_krea2_tokenizer(REPO, local_files_only = False)+ assert sources == [REPO]+++def _write_real_tokenizer(folder: pathlib.Path) -> None:+ tokenizers = pytest.importorskip("tokenizers")+ vocab = {"[UNK]": 0, "hello": 1, "world": 2}+ tok = tokenizers.Tokenizer(tokenizers.models.WordLevel(vocab, unk_token = "[UNK]"))+ tok.pre_tokenizer = tokenizers.pre_tokenizers.Whitespace()+ tok.save(str(folder / "tokenizer.json"))+ (folder / "tokenizer_config.json").write_text(+ json.dumps({"tokenizer_class": "PreTrainedTokenizerFast", "unk_token": "[UNK]"}),+ encoding = "utf-8",+ )+++def test_a_downloaded_krea_tokenizer_really_loads_offline(monkeypatch, tmp_path, online):+ """Real transformers, real files, no network: on transformers 5.x the repo-id load raises even+ with the .no_exist marker present, which is the Krea-2-Turbo failure the benchmark hit."""+ pytest.importorskip("transformers")+ from core.inference import diffusion_krea2++ snapshot = _fake_cache(tmp_path)+ _write_real_tokenizer(snapshot / "tokenizer")+ _live_cache(monkeypatch, tmp_path)+ tokenizer = diffusion_krea2.load_krea2_tokenizer(REPO, local_files_only = True)+ assert tokenizer("hello world")["input_ids"] == [1, 2]