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: train gated upstream models through public unsloth copies (#11214)
oobabooga891feb1afdf9
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 5913c486d19..c1b6232b462 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -73,6 +73,7 @@ from utils.third_party_source import (from utils.models import is_vision_model, detect_audio_type_checkedfrom utils.models.model_identity import restore_hf_cache_repo_identity+from utils.models.unsloth_mirror import unsloth_public_mirrorfrom utils.models.model_config import _env_offlinefrom utils.datasets import format_and_template_datasetfrom utils.datasets.completion_masking import apply_completion_masking@@ -171,6 +172,45 @@ def _drop_hf_stdout_callbacks(trainer) -> None:pass+def _bitsandbytes_allows_4bit() -> bool:+ """``loader.ALLOW_BITSANDBYTES``: False when bitsandbytes is absent or its native kernels+ are unusable, which is the normal state on Studio's Mac, Intel and CPU installs and on+ some AMD stacks. from_pretrained clears load_in_4bit on that path BEFORE it calls+ get_model_name (unsloth/models/loader.py, the `if not ALLOW_BITSANDBYTES` block), so a+ 4-bit request resolves the SIXTEEN-bit mapping there. Read it rather than assume it, or+ the metadata read names a repo the loader never fetches."""+ try:+ from unsloth.device_type import ALLOW_BITSANDBYTES+ return bool(ALLOW_BITSANDBYTES)+ except Exception: # noqa: BLE001 -- unreadable means "cannot narrow", so keep the request+ return True+++def _metadata_lookup_name(+ model_name: str,+ lookup_name: str,+ local_files_only: bool,+ model_revision: Optional[str],+ load_in_4bit: bool,+) -> str:+ """Return the repo whose config and tokenizer the loader will read."""+ if local_files_only or model_revision is not None or lookup_name != model_name:+ return lookup_name+ # MLX loads the picked name as given: unsloth_zoo/mlx/loader.py never consults the+ # upstream-to-Unsloth mapper, so on Apple Silicon there is no mirror to read from.+ from core.training.training import should_use_mlx_training_backend++ if should_use_mlx_training_backend():+ return lookup_name+ mirror = unsloth_public_mirror(model_name, load_in_4bit and _bitsandbytes_allows_4bit())+ if mirror is None:+ return lookup_name+ logger.info(+ "Reading %s config and tokenizer from %s, the repo Unsloth loads", model_name, mirror+ )+ return mirror++def _spark_tts_tokenizer_kwargs(audio_type: Optional[str], lookup_name: str) -> dict:"""``subfolder`` for a Spark-TTS repo root, empty for anything else. Only the canonical repolayout needs it: a local checkpoint or an alias that already names LLM/ points at the@@ -335,6 +375,7 @@ class UnslothTrainer:model_load_name: Optional[str] = None,local_files_only: bool = False,model_revision: Optional[str] = None,+ load_in_4bit: bool = True,) -> None:"""Lightweight detection and tokenizer load: no model weights, no VRAM. Sets is_vlm,_audio_type, is_audio_vlm, model_name and loads a lightweight tokenizer for dataset@@ -344,7 +385,13 @@ class UnslothTrainer:self.model_name = model_nameself.max_seq_length = max_seq_lengthself.trust_remote_code = trust_remote_code- lookup_name = model_load_name or model_name+ lookup_name = _metadata_lookup_name(+ model_name,+ model_load_name or model_name,+ local_files_only,+ model_revision,+ load_in_4bit,+ )if hf_token:os.environ["HF_TOKEN"] = hf_token@@ -826,6 +873,9 @@ class UnslothTrainer:use_gradient_checkpointing = normalize_gradient_checkpointing(use_gradient_checkpointing)self._use_gradient_checkpointing = use_gradient_checkpointinglookup_name = model_load_name or model_name+ metadata_name = _metadata_lookup_name(+ model_name, lookup_name, local_files_only, model_revision, load_in_4bit+ )self.model_load_error = Nonetry:if self.model is not None:@@ -861,7 +911,7 @@ class UnslothTrainer:# Checked: this reassigns _audio_type, so an unchecked answer would leave the flag describing the previous# probe.self._audio_type, self._audio_type_known = detect_audio_type_checked(- lookup_name,+ metadata_name,hf_token,local_files_only = local_files_only,revision = model_revision,@@ -880,7 +930,7 @@ class UnslothTrainer:vision = (is_vision_model(- lookup_name,+ metadata_name,hf_token = hf_token,local_files_only = local_files_only,revision = model_revision,@@ -918,7 +968,7 @@ class UnslothTrainer:if hf_token:os.environ["HF_TOKEN"] = hf_token- # Proactive gated/private check before from_pretrained; skipped offline (uses cache).+ # Gate-check the repo Unsloth will fetch, which may be a public mirror of it.if "/" in model_name and not local_files_only and not _env_offline():try:from huggingface_hub import model_info as hf_model_info@@ -926,7 +976,7 @@ class UnslothTrainer:model_info_kwargs = {"token": hf_token or None}if model_revision:model_info_kwargs["revision"] = model_revision- info = hf_model_info(model_name, **model_info_kwargs)+ info = hf_model_info(metadata_name, **model_info_kwargs)# model_info works on gated repos (metadata is public); info.gated flags acceptance.if info.gated and not hf_token:friendly = (diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 07c7175ea30..6140934b0f2 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -716,6 +716,21 @@ def _load_embedding_hf_dataset(return dataset+def _pre_detect_load_in_4bit(config: dict, model_load_target: str, hf_token: str | None) -> bool:+ """The mode the real load will use, so pre-detect reads the repo the loader fetches.++ The load calls _effective_training_load_in_4bit, which also REFUSES an exact-resource+ 4-bit resume once the sidecar is active. That refusal belongs to the load, not to a+ metadata read, so the flip is read directly here and the refusal is left to raise where+ it already does.+ """+ if not bool(config.get("load_in_4bit", True)):+ return False+ from utils.transformers_version import latest_tier_active_for++ return not latest_tier_active_for(model_load_target, hf_token)++def _pre_detect_training_model(trainer,config: dict,@@ -735,6 +750,7 @@ def _pre_detect_training_model(model_load_name = model_load_name,local_files_only = local_files_only,model_revision = model_revision,+ load_in_4bit = _pre_detect_load_in_4bit(config, model_load_name, hf_token),)_check_finetune_targets_after_detect(trainer, config)@@ -884,6 +900,16 @@ def _reload_dataset_with_remote_model_tokenizer(return reload_dataset()+def _strip_unsloth_bnb_4bit_suffix(model_name: str) -> str:+ """unsloth.models.loader._strip_unsloth_bnb_4bit_suffix, copied rather than imported: that+ module pulls in torch, and this runs before the worker is allowed to."""+ stripped = model_name+ for suffix in ("-unsloth-bnb-4bit", "-bnb-4bit"):+ if len(stripped) >= len(suffix) and stripped.lower().endswith(suffix):+ stripped = stripped[: -len(suffix)]+ return stripped++def _model_load_security_error(config: dict, load_target: str, hf_token: str | None) -> dict | None:from utils.models.model_config import get_base_model_from_lora_identifierfrom utils.security import (@@ -901,6 +927,66 @@ def _model_load_security_error(config: dict, load_target: str, hf_token: str | Nexcept Exception as error:logger.debug("Could not resolve LoRA base for security scan: %s", error)+ # Scan the repo the loader SUBSTITUTES too. The mapper can send the download somewhere+ # other than the name the user picked, and scanning only the picked name would let the+ # bytes that are actually fetched, and any custom code they carry, past both the malware+ # scan and the trust_remote_code consent fingerprint.+ #+ # BOTH modes, and nothing heavier than utils.models.unsloth_mirror. This runs early in+ # run_training_process, after the MLX fast path's "before any torch import" guarantee and+ # before the Windows ROCm torchao stub, so it must not reach anything that imports torch+ # or unsloth: not core.training.trainer, and not ALLOW_BITSANDBYTES. The 4-bit and 16-bit+ # candidates together are a superset of whichever the run picks, which is the safe+ # direction for a scan and needs no load mode at all.+ #+ # And only where the TORCH loader runs. _run_mlx_training hands the name straight to+ # FastMLXModel.from_pretrained and _run_embedding_training to SentenceTransformer, and+ # neither consults this mapper, so on those paths a mirror is a repo that will never be+ # fetched: scanning it can block a valid run on an unrelated repo's files and fingerprints+ # remote-code consent against something that is never loaded. core.training.training is+ # safe to import here - the MLX fast path above already imports it for its own guard.+ try:+ from core.training.training import should_use_mlx_training_backend+ from utils.models.unsloth_mirror import unsloth_public_mirror++ torch_loader_path = not config.get("is_embedding", False) and (+ not should_use_mlx_training_backend()+ )+ if (+ torch_loader_path+ and not _model_local_files_only(config)+ and not config.get("model_revision")+ ):+ # The fallbacks only ever run DOWNWARDS: an unusable bitsandbytes or an active+ # latest-transformers sidecar turns a 4-bit request into a 16-bit load, and+ # effective_training_load_in_4bit returns False outright for a config that is+ # already False (full finetunes among them). So a configured 16-bit load can never+ # become 4-bit, and scanning the 4-bit mirror there would let an unused repo's+ # findings block a run whose real repo is clean.+ _modes = (True, False) if config.get("load_in_4bit", True) else (False,)+ # Every resolved seed, not just the picked name. For a remote LoRA adapter the+ # loader takes peft_config.base_model_name_or_path and runs get_model_name over it+ # (loader.py:756-765), so the base has a mirror of its own and that mirror is what+ # gets downloaded. Expanding only the adapter id left it unscanned.+ for _seed in list(dict.fromkeys(requested_targets)):+ for _mode in _modes:+ mirrored = unsloth_public_mirror(_seed, _mode)+ if mirrored and mirrored != _seed:+ requested_targets.append(mirrored)+ # Where ALLOW_PREQUANTIZED_MODELS is false - ROCm Instinct on+ # bitsandbytes < 0.49.2, whose blocksize is 128 while our pre-quants use+ # 64 - loader.py:581 strips the 4-bit suffix off the name the mapper just+ # produced and downloads THAT repo. For a mapping that only exists in the+ # 4-bit direction it is the one repo that actually gets fetched, and+ # without it here its files bypass both the malware scan and the+ # remote-code consent fingerprint. Unlike a mode that cannot happen, this+ # repo really is loaded on a live configuration, so it belongs in the scan.+ stripped = _strip_unsloth_bnb_4bit_suffix(mirrored)+ if stripped != mirrored and stripped != _seed:+ requested_targets.append(stripped)+ except Exception as error: # noqa: BLE001+ logger.debug("Could not resolve the mirror for the security scan: %s", error)+from utils.utils import hf_env_offlineprimary_name = config["model_name"]diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex b6c3e805835..9223cf654fb 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -461,9 +461,21 @@ def _has_adapter_metadata(path: Path) -> bool:return path.is_dir() and (path / "adapter_config.json").is_file()-def _remote_untrainable_model_format(model_name: str, hf_token: HfTokenArg) -> Optional[str]:+_HF_MODEL_ACCESS_DENIED = (+ "Hugging Face denied access to this model. Add a valid Hugging Face "+ "token with repository access and accept any required access terms, "+ "then try again."+)+++def _remote_untrainable_model_format(+ model_name: str,+ hf_token: HfTokenArg,+ is_embedding: bool = False,+) -> Optional[str]:from huggingface_hub import model_info as hf_model_infofrom hub.utils.hf_errors import hf_error_status+ from utils.models.unsloth_mirror import unsloth_public_mirrorfrom utils.security import load_scan_target# Registry aliases such as "Spark-TTS-0.5B/LLM" are not repos; probe the repo the trainer@@ -498,11 +510,7 @@ def _remote_untrainable_model_format(model_name: str, hf_token: HfTokenArg) -> Oraise _hf_preflight_error(422,"hf_model_access_denied",- (- "Hugging Face denied access to this model. Add a valid Hugging Face "- "token with repository access and accept any required access terms, "- "then try again."- ),+ _HF_MODEL_ACCESS_DENIED,) from errorretry_available = attempt + 1 < len(timeouts)if transient_status:@@ -539,6 +547,78 @@ def _remote_untrainable_model_format(model_name: str, hf_token: HfTokenArg) -> O),) from error+ # Which mirror a run fetches depends on the mode the WORKER ends up in, and this process+ # cannot know it. A full finetune forces 16-bit, the latest-transformers sidecar forces+ # 16-bit, and from_pretrained silently clears load_in_4bit wherever bitsandbytes is+ # unusable - which is not "not installed": unsloth/device_type.py decides it with a guarded+ # import plus native_kernels_ready(bnb, DEVICE_TYPE), because from 0.46 a dead native+ # library still imports and only raises when called. Reading that here would import+ # bitsandbytes and torch into the backend parent, which this whole helper exists to avoid.+ #+ # So do not guess. A mirror in EITHER mode admits the model. The two directions are not+ # symmetric in cost: a wrong refusal blocks a model the worker would have trained, which is+ # a regression against main, while a wrong admission only lets the run reach the worker and+ # fail there exactly as it does on main today. 36 of the 1617 mapper keys map in one mode+ # only, so the widened set is small either way.+ #+ # This deliberately supersedes the earlier narrowing to "bitsandbytes is not installed at+ # all": find_spec answers a different question from the one the loader asks.+ # "Could not read the tables" is not "no public copy": they live in the installed unsloth+ # package and find_spec can land on a directory with no models/mapper.py under it, in which+ # case every lookup answers None and every gated model is refused, the trainable ones+ # included. Unknown admits, exactly as an unanswered auth-check does.+ #+ # And only where the TORCH loader runs. _run_mlx_training hands model_load_name straight to+ # FastMLXModel.from_pretrained, and that loader never consults the upstream-to-Unsloth+ # mapper (unsloth_zoo/mlx/loader.py only strips bnb suffixes off ids already under+ # unsloth/), so on Apple Silicon the worker really does fetch the gated upstream.+ # Embedding runs take _run_embedding_training, whose primary path is+ # `SentenceTransformer(model_name, ...)` with the name as given: same reasoning, separate+ # backend. Both are platform/route tests rather than device probes, so the parent may ask.+ from core.training.training import should_use_mlx_training_backend+ from utils.models.unsloth_mirror import mirror_lookup_available++ # Fail open only INSIDE the Torch path. MLX and embedding runs fetch the picked repo+ # directly, so an unreadable mapper tells us nothing about them and the auth-check is the+ # only thing standing between an inaccessible gated model and a worker-side failure.+ # Written the other way round, an unreadable mapper admitted those runs too.+ torch_loader_path = not should_use_mlx_training_backend() and not is_embedding+ has_public_copy = torch_loader_path and (+ not mirror_lookup_available()+ or any(unsloth_public_mirror(repo_id, mode) is not None for mode in (True, False))+ )++ # Gated model metadata is public, so verify access to its files separately.+ if getattr(info, "gated", False) and not has_public_copy:+ from urllib.parse import quote+ from huggingface_hub import constants+ from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status++ url = f"{constants.ENDPOINT}/api/models/{quote(repo_id, safe = '/')}/auth-check"+ headers = build_hf_headers(token = account_hf_token(hf_token))+ # Same two timeouts as the model_info probe above: a transient failure here admits a+ # run that then dies in the worker with the raw Hub error, which is the whole point of+ # asking. Retry it, then fail open, since only a definite denial may block a start.+ for attempt, timeout in enumerate(timeouts):+ try:+ hf_raise_for_status(get_session().get(url, headers = headers, timeout = timeout))+ break+ except Exception as error:+ status_code = hf_error_status(error)+ if status_code in (401, 403):+ raise _hf_preflight_error(+ 422,+ "hf_model_access_denied",+ _HF_MODEL_ACCESS_DENIED,+ ) from error+ if attempt + 1 < len(timeouts):+ continue+ logger.warning(+ "Could not verify access to gated %s (%s); starting anyway",+ repo_id,+ type(error).__name__,+ )+load_roots = ("", *(f"{subdir.strip('/')}/" for subdir in load_subdirs if subdir))root_files: set[str] = set()has_gguf = False@@ -976,7 +1056,11 @@ def _reject_untrainable_model_request("Retry before starting training."),)- remote_format = _remote_untrainable_model_format(request.model_name, hf_token)+ remote_format = _remote_untrainable_model_format(+ request.model_name,+ hf_token,+ is_embedding = bool(getattr(request, "is_embedding", False)),+ )except HTTPException as error:metadata_error = errorfrom core.training.training import _resolve_model_snapshotdiff --git a/studio/backend/tests/test_account_cached_resource_paths.py b/studio/backend/tests/test_account_cached_resource_paths.pyindex 1311f274ace..dac081a294f 100644--- a/studio/backend/tests/test_account_cached_resource_paths.py+++ b/studio/backend/tests/test_account_cached_resource_paths.py@@ -143,7 +143,12 @@ def test_a_cache_fallback_after_a_refused_remote_probe_needs_a_grant(from routes import trainingfrom models.training import TrainingStartRequest- def refused(model_name, hf_token):+ def refused(+ model_name,+ hf_token,+ load_in_4bit = True,+ is_embedding = False,+ ):raise HTTPException(status_code = 422, detail = {"code": "hf_model_access_denied"})monkeypatch.setattr(training, "_remote_untrainable_model_format", refused)diff --git a/studio/backend/tests/test_training_ambient_hf_token.py b/studio/backend/tests/test_training_ambient_hf_token.pyindex 9bcb5db97b3..c45d9c0c520 100644--- a/studio/backend/tests/test_training_ambient_hf_token.py+++ b/studio/backend/tests/test_training_ambient_hf_token.py@@ -67,7 +67,12 @@ def test_start_gives_the_model_preflight_only_the_callers_token(backend = _Backend()probed = []- def _probe(model_name, hf_token):+ def _probe(+ model_name,+ hf_token,+ load_in_4bit = True,+ is_embedding = False,+ ):probed.append(hf_token)return None@@ -166,7 +171,7 @@ def test_snapshot_cached_during_the_metadata_probe_is_authorized(monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)monkeypatch.setattr(hf_tokens, "_explicit_token_reaches_repo", lambda *a, **k: False)- def denied(*args):+ def denied(*args, **kwargs):raise tr._hf_preflight_error(422, "hf_model_access_denied", "Denied")monkeypatch.setattr(tr, "_remote_untrainable_model_format", denied)@@ -433,7 +438,7 @@ def test_private_cached_model_requires_caller_authorization(monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)monkeypatch.setattr(hf_tokens, "_explicit_token_reaches_repo", lambda *a, **k: False)- def denied(*args):+ def denied(*args, **kwargs):raise tr._hf_preflight_error(422, "hf_model_access_denied", "Denied")monkeypatch.setattr(diff --git a/studio/backend/tests/test_training_gated_upstream.py b/studio/backend/tests/test_training_gated_upstream.pynew file mode 100644index 00000000000..3bcbe6ca8d3--- /dev/null+++ b/studio/backend/tests/test_training_gated_upstream.py@@ -0,0 +1,981 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression tests for training gated models through public Unsloth mirrors."""++from __future__ import annotations++import importlib+import importlib.util+import sys+import types+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+from fastapi import HTTPException++import routes.training as tr+from models import TrainingStartRequest+from utils.models import unsloth_mirror+++_STUBBED: list[str] = []+++def _stub_if_missing(name, attrs):+ # Stub training dependencies absent from the backend pytest environment.+ if name in sys.modules:+ return+ try:+ importlib.import_module(name)+ return+ except Exception: # noqa: BLE001+ pass+ _STUBBED.append(name)+ mod = types.ModuleType(name)+ mod.__spec__ = None+ for attr in attrs:+ setattr(mod, attr, MagicMock())+ sys.modules[name] = mod+ parent, _, child = name.rpartition(".")+ if parent and parent in sys.modules:+ setattr(sys.modules[parent], child, mod)+++_stub_if_missing("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"))+_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))+_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))++# core.training.trainer imports torch at module scope. A runner without it errored the whole+# module out, which reads as a red CI leg rather than as "this runner cannot answer": skip+# honestly instead. The staging legs install torch so the skip does not make them vacuous.+pytest.importorskip("torch", reason = "core.training.trainer imports torch at module scope")++import core.training.trainer as trainer_mod # noqa: E402++for _name in reversed(_STUBBED):+ sys.modules.pop(_name, None)++import transformers # noqa: E402++transformers.AutoTokenizer # noqa: B018+transformers = sys.modules["transformers"]+++_TABLES = (+ {"unsloth/gemma-3-270m-it-unsloth-bnb-4bit": "unsloth/gemma-3-270m-it"},+ {+ "google/gemma-3-270m-it": "unsloth/gemma-3-270m-it-unsloth-bnb-4bit",+ "meta-llama/meta-llama-3-70b-instruct": "unsloth/llama-3-70b-instruct-bnb-4bit",+ },+ {+ "google/gemma-3-270m-it": "unsloth/gemma-3-270m-it",+ "google/gemma-4-26b-a4b": "unsloth/gemma-4-26B-A4B",+ },+)++[email protected](autouse = True)+def _clear_mirror_caches():+ # Both lookups are lru_cached and several tests point them at a tmp_path package, so a+ # stale entry would otherwise decide the next test's answer. getattr, because the mapper+ # fixture swaps _mapper_tables for a plain lambda that has no cache to clear.+ def clear():+ for lookup in (unsloth_mirror._mapper_tables, unsloth_mirror._bad_mappings):+ getattr(lookup, "cache_clear", lambda: None)()++ clear()+ yield+ clear()++[email protected](autouse = True)+def _torch_trainer(monkeypatch):+ # UnslothTrainer.__new__ hands back _MLXTrainerAdapter when should_use_mlx_training_backend()+ # is true, and that adapter has no pre_detect_and_load_tokenizer at all. On a real Apple+ # Silicon runner every test here that builds a trainer therefore exercised the MLX adapter+ # and died with AttributeError, which the Linux and Windows legs could never show. These+ # tests are about the Torch path by construction; the MLX path has its own tests below,+ # which patch core.training.training and so are unaffected by this.+ import core.training.training as training_mod++ # Patch the definition AND trainer.py's module-scope copy of the name. The route resolves+ # it from core.training.training at call time, trainer.py bound it at import, and+ # trainer._metadata_lookup_name re-imports it inside the function; a single patch leaves+ # one of the three on the real answer, which on Apple Silicon is True.+ for module in (training_mod, trainer_mod):+ monkeypatch.setattr(+ module, "should_use_mlx_training_backend", lambda *a, **kw: False, raising = False+ )+++def mapper(monkeypatch):+ monkeypatch.setattr(unsloth_mirror, "_mapper_tables", lambda: _TABLES)+++ "name,load_in_4bit,mirror",+ [+ ("google/gemma-3-270m-it", False, "unsloth/gemma-3-270m-it"),+ ("Google/Gemma-3-270M-it", False, "unsloth/gemma-3-270m-it"),+ # A 4-bit load resolves through the 4-bit table, which can map a different model.+ ("google/gemma-3-270m-it", True, "unsloth/gemma-3-270m-it-unsloth-bnb-4bit"),+ ("meta-llama/Meta-Llama-3-70B-Instruct", True, "unsloth/llama-3-70b-instruct-bnb-4bit"),+ ("meta-llama/Meta-Llama-3-70B-Instruct", False, None),+ ("google/gemma-4-26B-A4B", False, "unsloth/gemma-4-26B-A4B"),+ ("google/gemma-4-26B-A4B", True, None),+ # A public Unsloth repo is not automatically a fixed point: see+ # test_an_unsloth_id_is_not_a_fixed_point. get_model_name resolves this one back+ # through INT_TO_FLOAT_MAPPER for a 16-bit load.+ ("unsloth/gemma-3-270m-it-unsloth-bnb-4bit", False, "unsloth/gemma-3-270m-it"),+ ("google/gemma-2-2b-jpn-it", True, None),+ ("google/gemma-2-2b-jpn-it", False, None),+ ("/models/google/gemma-3-270m-it", True, None),+ ("", True, None),+ (None, True, None),+ ],+)+def test_mirror_is_the_repo_the_loader_substitutes(mapper, name, load_in_4bit, mirror):+ assert unsloth_mirror.unsloth_public_mirror(name, load_in_4bit) == mirror+++ "name,mirror",+ [+ # get_model_name corrects these after the table lookup. The uncorrected name+ # unsloth/Qwen3-30B-A3B-unsloth-bnb-4bit does not exist on the Hub at all.+ ("Qwen/Qwen3-30B-A3B", "unsloth/Qwen3-30B-A3B"),+ ("Qwen/Qwen3-30B-A3B-Base", "unsloth/Qwen3-30B-A3B-Base"),+ ("Qwen/Qwen3-32B", "unsloth/Qwen3-32B-bnb-4bit"),+ ],+)+def test_the_loader_corrections_are_applied_to_the_mirror(name, mirror):+ assert unsloth_mirror.unsloth_public_mirror(name, True).lower() == mirror.lower()+++def test_corrections_are_read_from_the_real_loader_source():+ # Parsed out of loader_utils.py, so the table cannot drift from the loader.+ corrections = unsloth_mirror._bad_mappings()+ assert corrections+ assert all(key == key.lower() for key in corrections)+ assert "unsloth/qwen3-30b-a3b-unsloth-bnb-4bit" in corrections+++ "source",+ [+ "BAD_MAPPINGS = {compute(): 'x'}\n", # an entry that is not readable as data+ "BAD_MAPPINGS = build()\n", # not a dict literal at all+ "", # no BAD_MAPPINGS in the file+ ],+)+def test_unreadable_corrections_redirect_nothing(mapper, monkeypatch, tmp_path, source):+ # None, not {}: an uncorrected lookup can name a repo that does not exist, so the mirror+ # has to fall back to the name the caller picked rather than to a repo Unsloth never loads.+ (tmp_path / "loader_utils.py").write_text(source)+ monkeypatch.setattr(unsloth_mirror, "_unsloth_models_dir", lambda: tmp_path)+ unsloth_mirror._bad_mappings.cache_clear()+ try:+ assert unsloth_mirror._bad_mappings() is None+ assert unsloth_mirror.unsloth_public_mirror("google/gemma-3-270m-it", False) is None+ finally:+ unsloth_mirror._bad_mappings.cache_clear()+++def test_mapper_is_read_from_the_file_without_importing_unsloth(monkeypatch, tmp_path):+ package = tmp_path / "unsloth"+ (package / "models").mkdir(parents = True)+ (package / "__init__.py").write_text("raise RuntimeError('the package must not be imported')\n")+ (package / "models" / "mapper.py").write_text(+ "INT_TO_FLOAT_MAPPER = {}\n"+ "FLOAT_TO_INT_MAPPER = {}\n"+ "MAP_TO_UNSLOTH_16bit = {'google/gemma-3-270m-it': 'unsloth/gemma-3-270m-it'}\n"+ )+ # Ships beside mapper.py in every real install, and the corrections are read from it.+ (package / "models" / "loader_utils.py").write_text("BAD_MAPPINGS = {}\n")+ spec = importlib.util.spec_from_file_location(+ "unsloth", package / "__init__.py", submodule_search_locations = [str(package)]+ )+ monkeypatch.setattr(unsloth_mirror.importlib.util, "find_spec", lambda name: spec)+ unsloth_mirror._mapper_tables.cache_clear()+ try:+ assert unsloth_mirror.unsloth_public_mirror("google/gemma-3-270m-it", False) == (+ "unsloth/gemma-3-270m-it"+ )+ finally:+ unsloth_mirror._mapper_tables.cache_clear()+++def test_an_unreadable_mapper_redirects_nothing(monkeypatch):+ monkeypatch.setattr(unsloth_mirror.importlib.util, "find_spec", lambda name: None)+ unsloth_mirror._mapper_tables.cache_clear()+ try:+ assert unsloth_mirror.unsloth_public_mirror("google/gemma-3-270m-it", False) is None+ finally:+ unsloth_mirror._mapper_tables.cache_clear()+++ "load_name,local_only,revision,expected",+ [+ (None, False, None, "unsloth/gemma-3-270m-it-unsloth-bnb-4bit"),+ # A pinned revision loads with use_exact_model_name, so the loader keeps the upstream.+ (None, False, "0123456789abcdef0123456789abcdef01234567", "google/gemma-3-270m-it"),+ ("/hf/models--google--gemma-3-270m-it/snapshots/abc", True, None, None),+ (None, True, None, "google/gemma-3-270m-it"),+ ],+)+def test_pre_detect_reads_the_repo_the_loader_fetches(+ mapper, monkeypatch, load_name, local_only, revision, expected+):+ expected = expected or load_name+ reads = []++ def probe(name, *a, **kw):+ reads.append(name)+ return None, True++ def vision(name, **kw):+ reads.append(name)+ return False++ class _Tokenizer:+ @classmethod+ def from_pretrained(cls, name, **kw):+ reads.append(name)+ return object()++ monkeypatch.setattr(trainer_mod, "detect_audio_type_checked", probe)+ monkeypatch.setattr(trainer_mod, "is_vision_model", vision)+ monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)++ trainer = trainer_mod.UnslothTrainer()+ trainer.pre_detect_and_load_tokenizer(+ "google/gemma-3-270m-it",+ model_load_name = load_name,+ local_files_only = local_only,+ model_revision = revision,+ )++ assert reads == [expected, expected, expected]+ assert trainer.model_name == "google/gemma-3-270m-it"+++def test_pre_detect_follows_the_requested_load_mode(mapper, monkeypatch):+ reads = []++ class _Tokenizer:+ @classmethod+ def from_pretrained(cls, name, **kw):+ reads.append(name)+ return object()++ def probe(name, *a, **kw):+ reads.append(name)+ return None, True++ def vision(name, **kw):+ reads.append(name)+ return False++ monkeypatch.setattr(trainer_mod, "detect_audio_type_checked", probe)+ monkeypatch.setattr(trainer_mod, "is_vision_model", vision)+ monkeypatch.setattr(transformers, "AutoTokenizer", _Tokenizer, raising = False)++ trainer_mod.UnslothTrainer().pre_detect_and_load_tokenizer(+ "google/gemma-3-270m-it", load_in_4bit = False+ )++ assert reads == ["unsloth/gemma-3-270m-it"] * 3+++class _Session:+ def __init__(self, outcome):+ self.outcome = outcome+ self.urls = []++ def get(self, url, **kwargs):+ self.urls.append(url)+ if isinstance(self.outcome, Exception):+ raise self.outcome+ return SimpleNamespace(status_code = self.outcome)+++def _http_error(status):+ error = Exception(f"{status} Client Error")+ error.response = SimpleNamespace(status_code = status)+ return error+++def _route(monkeypatch, *, gated, session):+ import huggingface_hub+ import huggingface_hub.utils++ info = SimpleNamespace(+ gated = gated,+ siblings = [+ SimpleNamespace(rfilename = "config.json"),+ SimpleNamespace(rfilename = "model.safetensors"),+ ],+ )+ monkeypatch.setattr(huggingface_hub, "model_info", lambda *a, **kw: info)+ monkeypatch.setattr(huggingface_hub.utils, "get_session", lambda: session)+ monkeypatch.setattr(huggingface_hub.utils, "hf_raise_for_status", lambda response: None)+++def test_gated_repo_without_access_or_a_public_copy_is_refused(mapper, monkeypatch):+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-2-2b-jpn-it", None)++ assert error.value.status_code == 422+ assert error.value.detail["code"] == "hf_model_access_denied"+ assert session.urls and session.urls[0].endswith(+ "/api/models/google/gemma-2-2b-jpn-it/auth-check"+ )+++ "model,gated,outcome",+ [+ ("google/gemma-3-270m-it", "manual", _http_error(401)),+ ("google/gemma-2-2b-jpn-it", "manual", 200),+ # Timeouts and server errors are inconclusive.+ ("google/gemma-2-2b-jpn-it", "auto", TimeoutError("timed out")),+ ("google/gemma-2-2b-jpn-it", "manual", _http_error(500)),+ ("org/public-model", False, _http_error(401)),+ ],+)+def test_gated_check_admits_what_the_worker_can_load(mapper, monkeypatch, model, gated, outcome):+ session = _Session(outcome)+ _route(monkeypatch, gated = gated, session = session)++ assert tr._remote_untrainable_model_format(model, None) is None+ if model == "google/gemma-3-270m-it" or not gated:+ assert session.urls == []+++def test_a_transient_auth_check_failure_is_retried_then_fails_open(mapper, monkeypatch):+ # A single timeout used to admit the run, which then died in the worker with the raw Hub+ # error. The model_info probe above it already retries on two timeouts.+ class _Flaky(_Session):+ def get(self, url, **kwargs):+ self.urls.append(url)+ if len(self.urls) == 1:+ raise TimeoutError("first attempt timed out")+ raise _http_error(401)++ session = _Flaky(None)+ _route(monkeypatch, gated = "manual", session = session)++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-2-2b-jpn-it", None)++ assert error.value.detail["code"] == "hf_model_access_denied"+ assert len(session.urls) == 2+++def test_an_auth_check_that_never_answers_admits_the_run(mapper, monkeypatch):+ session = _Session(TimeoutError("timed out"))+ _route(monkeypatch, gated = "manual", session = session)++ assert tr._remote_untrainable_model_format("google/gemma-2-2b-jpn-it", None) is None+ assert len(session.urls) == 2+++def test_start_request_surfaces_the_refusal_code(mapper, monkeypatch):+ session = _Session(_http_error(403))+ _route(monkeypatch, gated = "manual", session = session)+ monkeypatch.setattr(tr, "hf_env_offline", lambda: False)+ monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)+ monkeypatch.setattr(tr, "cached_read_refused", lambda *a, **kw: False)++ request = TrainingStartRequest(+ model_name = "google/gemma-2-2b-jpn-it",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ )+ with pytest.raises(HTTPException) as error:+ tr._reject_untrainable_model_request(request, hf_token = None)+ assert error.value.detail["code"] == "hf_model_access_denied"+++def test_a_4bit_public_copy_admits_a_gated_upstream(mapper, monkeypatch):+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ model = "meta-llama/Meta-Llama-3-70B-Instruct"+ assert tr._remote_untrainable_model_format(model, None) is None+ assert session.urls == []+++def test_a_mirror_in_either_load_mode_admits_the_model(mapper, monkeypatch):+ # Llama-3-70B-Instruct maps for 4-bit only, gemma-4-26B-A4B for 16-bit only. This process+ # cannot tell which mode the worker lands in (full finetune, latest-transformers sidecar+ # and an unusable bitsandbytes all force 16-bit, and the last needs torch to detect), so+ # either mapping admits. The alternative refuses models the worker would have trained.+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ for model in ("meta-llama/Meta-Llama-3-70B-Instruct", "google/gemma-4-26B-A4B"):+ assert tr._remote_untrainable_model_format(model, None) is None+ assert session.urls == []+++def test_a_gated_model_with_no_mirror_in_any_mode_is_still_refused(mapper, monkeypatch):+ # The widening above must not reach the PR's headline case.+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-2-2b-jpn-it", None)+ assert error.value.detail["code"] == "hf_model_access_denied"+ assert session.urls+++def test_the_start_route_does_not_pass_a_guessed_load_mode(mapper, monkeypatch):+ # Regression guard for the signature: a 4th positional argument here broke stubs in+ # test_account_cached_resource_paths and test_training_ambient_hf_token.+ import inspect++ params = list(inspect.signature(tr._remote_untrainable_model_format).parameters)+ assert params == ["model_name", "hf_token", "is_embedding"]++ seen = {}++ def probe(+ model_name,+ hf_token,+ is_embedding = False,+ ):+ seen["args"] = (model_name, is_embedding)+ return None++ monkeypatch.setattr(tr, "_remote_untrainable_model_format", probe)+ monkeypatch.setattr(tr, "hf_env_offline", lambda: False)+ monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)+ monkeypatch.setattr(tr, "cached_read_refused", lambda *a, **kw: False)++ request = TrainingStartRequest(+ model_name = "google/gemma-3-270m-it",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ load_in_4bit = False,+ )+ tr._reject_untrainable_model_request(request, hf_token = None)+ assert seen == {"args": ("google/gemma-3-270m-it", False)}+++def test_a_full_finetune_of_a_gated_unmirrored_model_is_still_refused(mapper, monkeypatch):+ # Full Finetuning is forced to 16-bit by _build_training_worker_config. The route no longer+ # derives that, because it cannot derive the other two flips (sidecar, unusable+ # bitsandbytes) without importing torch; a model with no mirror in EITHER mode is refused+ # regardless, which is what this path has to keep doing.+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)+ monkeypatch.setattr(tr, "hf_env_offline", lambda: False)+ monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)+ monkeypatch.setattr(tr, "cached_read_refused", lambda *a, **kw: False)++ request = TrainingStartRequest(+ model_name = "google/gemma-2-2b-jpn-it",+ training_type = "Full Finetuning",+ format_type = "alpaca",+ )+ with pytest.raises(HTTPException) as error:+ tr._reject_untrainable_model_request(request, hf_token = None)++ assert error.value.detail["code"] == "hf_model_access_denied"+ assert request.load_in_4bit is True+++ "config_4bit,sidecar,expected",+ [+ (True, False, True),+ # The load is flipped to 16-bit by _effective_training_load_in_4bit, so pre-detect has+ # to read the 16-bit mirror or it inspects a repo the loader never fetches.+ (True, True, False),+ (False, False, False),+ (False, True, False),+ ],+)+def test_pre_detect_follows_the_sidecar_flip_like_the_load_does(+ monkeypatch, config_4bit, sidecar, expected+):+ import core.training.worker as worker_mod+ import utils.transformers_version as tv++ monkeypatch.setattr(tv, "latest_tier_active_for", lambda *a, **kw: sidecar)+ config = {"load_in_4bit": config_4bit}+ assert worker_mod._pre_detect_load_in_4bit(config, "google/gemma-3-270m-it", None) is expected++ # and it agrees with the mode the real load uses, for every case the load does not refuse+ from core.training.provenance import effective_training_load_in_4bit++ assert effective_training_load_in_4bit(config, "google/gemma-3-270m-it", None) is expected+++ "bnb_ok,expected",+ [(True, "unsloth/gemma-3-270m-it-unsloth-bnb-4bit"), (False, "unsloth/gemma-3-270m-it")],+)+def test_pre_detect_follows_the_bitsandbytes_fallback(mapper, monkeypatch, bnb_ok, expected):+ # from_pretrained clears load_in_4bit when bitsandbytes is unusable, BEFORE it calls+ # get_model_name, so a 4-bit request resolves the 16-bit mapping on a Mac or CPU install.+ monkeypatch.setattr(trainer_mod, "_bitsandbytes_allows_4bit", lambda: bnb_ok)+ assert (+ trainer_mod._metadata_lookup_name(+ "google/gemma-3-270m-it", "google/gemma-3-270m-it", False, None, True+ )+ == expected+ )+++def test_load_model_gate_checks_the_repo_the_loader_fetches(mapper, monkeypatch):+ import huggingface_hub++ checked = []++ def probe(name, *a, **kw):+ return None, True++ def model_info(name, **kw):+ checked.append(name)+ return SimpleNamespace(gated = "manual")++ monkeypatch.setattr(trainer_mod, "detect_audio_type_checked", probe)+ monkeypatch.setattr(trainer_mod, "is_vision_model", lambda name, **kw: False)+ monkeypatch.setattr(huggingface_hub, "model_info", model_info)++ trainer = trainer_mod.UnslothTrainer()+ assert trainer.load_model("google/gemma-3-270m-it", load_in_4bit = False) is False+ assert checked == ["unsloth/gemma-3-270m-it"]+++def test_mlx_has_no_mirror_so_the_check_still_runs(mapper, monkeypatch):+ # unsloth_zoo/mlx/loader.py only remaps ids already under unsloth/ (stripping bnb+ # suffixes); it never consults the upstream-to-Unsloth mapper. _run_mlx_training hands+ # model_load_name straight to FastMLXModel.from_pretrained, so on Apple Silicon the worker+ # fetches the gated upstream and a Torch mapping proves nothing.+ import core.training.training as training_mod++ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)+ monkeypatch.setattr(training_mod, "should_use_mlx_training_backend", lambda **kw: True)++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-3-270m-it", None)+ assert error.value.detail["code"] == "hf_model_access_denied"+ assert session.urls+++def test_mlx_pre_detect_reads_the_repo_the_mlx_loader_fetches(mapper, monkeypatch):+ import core.training.training as training_mod+ monkeypatch.setattr(training_mod, "should_use_mlx_training_backend", lambda **kw: True)+ assert (+ trainer_mod._metadata_lookup_name(+ "google/gemma-3-270m-it", "google/gemma-3-270m-it", False, None, True+ )+ == "google/gemma-3-270m-it"+ )+++def test_an_unreadable_mapper_admits_instead_of_refusing(monkeypatch):+ # The tables live in the installed unsloth package and find_spec can land on a directory+ # with no models/mapper.py under it, which is how this was found: a real Studio install+ # answered None for every lookup and refused google/gemma-3-270m-it, a model it trains.+ # Unknown must admit, the same way an unanswered auth-check does.+ monkeypatch.setattr(unsloth_mirror.importlib.util, "find_spec", lambda name: None)+ unsloth_mirror._mapper_tables.cache_clear()+ unsloth_mirror._bad_mappings.cache_clear()+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)+ try:+ assert unsloth_mirror.mirror_lookup_available() is False+ assert tr._remote_untrainable_model_format("google/gemma-3-270m-it", None) is None+ assert session.urls == []+ finally:+ unsloth_mirror._mapper_tables.cache_clear()+ unsloth_mirror._bad_mappings.cache_clear()+++def test_an_embedding_run_has_no_mirror_so_the_check_still_runs(mapper, monkeypatch):+ # _run_embedding_training's primary path is SentenceTransformer(model_name, ...) with the+ # name as given (unsloth/models/sentence_transformer.py), so the mapper never runs and a+ # Torch mapping says nothing about what that backend fetches.+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-3-270m-it", None, is_embedding = True)+ assert error.value.detail["code"] == "hf_model_access_denied"+ assert session.urls+++def test_the_start_route_passes_the_embedding_flag(mapper, monkeypatch):+ seen = {}++ def probe(+ model_name,+ hf_token,+ load_in_4bit = True,+ is_embedding = False,+ ):+ seen["is_embedding"] = is_embedding+ return None++ monkeypatch.setattr(tr, "_remote_untrainable_model_format", probe)+ monkeypatch.setattr(tr, "hf_env_offline", lambda: False)+ monkeypatch.setattr(tr, "_hub_unreachable", lambda: False)+ monkeypatch.setattr(tr, "cached_read_refused", lambda *a, **kw: False)++ request = TrainingStartRequest(+ model_name = "google/gemma-3-270m-it",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ is_embedding = True,+ )+ tr._reject_untrainable_model_request(request, hf_token = None)+ assert seen == {"is_embedding": True}+++def test_the_security_scan_covers_the_repo_the_loader_substitutes(mapper, monkeypatch):+ # The mapper can send the download somewhere other than the picked name; scanning only the+ # picked name would let the bytes actually fetched past the malware scan and the consent+ # fingerprint.+ import core.training.worker as worker_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ import utils.security as security_mod++ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ config = {+ "model_name": "google/gemma-3-270m-it",+ "load_in_4bit": True,+ "trust_remote_code": False,+ }+ assert worker_mod._model_load_security_error(config, "google/gemma-3-270m-it", None) is None+ assert "unsloth/gemma-3-270m-it-unsloth-bnb-4bit" in scanned+++def test_the_security_scan_covers_both_load_modes(mapper, monkeypatch):+ # The sidecar and the bitsandbytes fallback both change which mirror a run fetches, and+ # neither can be read here: this runs before the torchao stub and before the MLX path's+ # first torch import, so it must not reach ALLOW_BITSANDBYTES or core.training.trainer.+ # Scanning both candidates is a superset of whichever the run picks.+ import core.training.worker as worker_mod+ import utils.security as security_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ assert (+ worker_mod._model_load_security_error(+ {+ "model_name": "google/gemma-3-270m-it",+ "load_in_4bit": True,+ "trust_remote_code": False,+ },+ "google/gemma-3-270m-it",+ None,+ )+ is None+ )+ assert "unsloth/gemma-3-270m-it" in scanned+ assert "unsloth/gemma-3-270m-it-unsloth-bnb-4bit" in scanned+++def test_the_security_scan_imports_nothing_heavy():+ # It runs before the Windows ROCm torchao stub and after the MLX path's "no torch yet"+ # guarantee, so reaching core.training.trainer (which imports unsloth at module scope)+ # would initialise torch ahead of the patches those paths depend on.+ import ast+ import pathlib as _pathlib++ import core.training.worker as worker_mod++ # From the module, not a relative path: pytest is run from the repo root in CI and from+ # studio/backend locally, and a relative path only resolves in the second.+ src = _pathlib.Path(worker_mod.__file__).read_text()+ fn = next(+ node+ for node in ast.walk(ast.parse(src))+ if isinstance(node, ast.FunctionDef) and node.name == "_model_load_security_error"+ )+ imported = {n.module for n in ast.walk(fn) if isinstance(n, ast.ImportFrom) and n.module} | {+ alias.name for n in ast.walk(fn) if isinstance(n, ast.Import) for alias in n.names+ }+ assert not any(+ m == "torch"+ or m.startswith(("torch.", "unsloth.", "core.training.trainer"))+ or m in {"unsloth", "unsloth_zoo"}+ for m in imported+ ), sorted(imported)+++ "name,load_in_4bit,mirror",+ [+ # Verified against unsloth.models.loader_utils.get_model_name. A 16-bit load of an+ # explicit dynamic-quant id resolves back through INT_TO_FLOAT_MAPPER...+ ("unsloth/gemma-3-270m-it-unsloth-bnb-4bit", False, "unsloth/gemma-3-270m-it"),+ # ...while a 4-bit load keeps it, so the tables resolve nothing and BAD_MAPPINGS is+ # applied to the input name instead, landing on a DIFFERENT repo.+ ("unsloth/Qwen3-30B-A3B-unsloth-bnb-4bit", True, "unsloth/qwen3-30b-a3b"),+ # An id the loader really does leave alone still answers None.+ ("unsloth/gemma-3-270m-it-unsloth-bnb-4bit", True, None),+ ("unsloth/gemma-3-270m-it", False, None),+ ],+)+def test_an_unsloth_id_is_not_a_fixed_point(mapper, name, load_in_4bit, mirror):+ # These used to return None from an early "starts with unsloth/" branch, which let the+ # security scan check a repo the loader never fetches while the one it does fetch went+ # unscanned.+ assert unsloth_mirror.unsloth_public_mirror(name, load_in_4bit) == mirror++[email protected]("config_key", ["is_embedding", "mlx"])+def test_the_scan_does_not_expand_mirrors_off_the_torch_path(mapper, monkeypatch, config_key):+ # _run_mlx_training and _run_embedding_training never consult this mapper, so a mirror+ # there is a repo that will never be fetched: scanning it can block a valid run on an+ # unrelated repo's files and fingerprints remote-code consent against something that is+ # never loaded.+ import core.training.training as training_mod+ import core.training.worker as worker_mod+ import utils.security as security_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ config = {+ "model_name": "google/gemma-3-270m-it",+ "load_in_4bit": True,+ "trust_remote_code": False,+ }+ if config_key == "is_embedding":+ config["is_embedding"] = True+ else:+ monkeypatch.setattr(training_mod, "should_use_mlx_training_backend", lambda **kw: True)++ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ assert worker_mod._model_load_security_error(config, "google/gemma-3-270m-it", None) is None+ assert scanned == ["google/gemma-3-270m-it"]+++def test_a_configured_16bit_load_does_not_scan_the_4bit_mirror(mapper, monkeypatch):+ # The mode fallbacks only run downwards, so a configured 16-bit load cannot become 4-bit+ # and the 4-bit mirror is a repo it will never fetch.+ import core.training.worker as worker_mod+ import utils.security as security_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ assert (+ worker_mod._model_load_security_error(+ {+ "model_name": "google/gemma-3-270m-it",+ "load_in_4bit": False,+ "trust_remote_code": False,+ },+ "google/gemma-3-270m-it",+ None,+ )+ is None+ )+ assert scanned == ["google/gemma-3-270m-it", "unsloth/gemma-3-270m-it"]+++def test_the_scan_covers_the_repo_left_after_the_4bit_suffix_is_stripped(mapper, monkeypatch):+ # Where ALLOW_PREQUANTIZED_MODELS is false (ROCm Instinct on bitsandbytes < 0.49.2)+ # loader.py:581 strips the suffix off the name the mapper produced and downloads that+ # repo. Meta-Llama-3-70B-Instruct maps only in the 4-bit direction, so the stripped repo+ # is the one that actually gets fetched there.+ import core.training.worker as worker_mod+ import utils.security as security_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ model = "meta-llama/Meta-Llama-3-70B-Instruct"+ assert (+ worker_mod._model_load_security_error(+ {"model_name": model, "load_in_4bit": True, "trust_remote_code": False}, model, None+ )+ is None+ )+ # Lower case: that is how the mapper stores this value, and the strip preserves whatever+ # case it is handed (HF cache directories are case sensitive).+ assert "unsloth/llama-3-70b-instruct-bnb-4bit" in scanned+ assert "unsloth/llama-3-70b-instruct" in scanned+++ "name,stripped",+ [+ ("unsloth/gemma-3-270m-it-unsloth-bnb-4bit", "unsloth/gemma-3-270m-it"),+ ("unsloth/llama-3-70b-Instruct-bnb-4bit", "unsloth/llama-3-70b-Instruct"),+ ("unsloth/gemma-3-270m-it", "unsloth/gemma-3-270m-it"),+ ],+)+def test_the_suffix_strip_matches_the_loader(name, stripped):+ import ast+ from pathlib import Path++ import core.training.worker as worker_mod++ # load the pure helper without importing the gpu stack into backend-only tests.+ loader_path = Path(__file__).resolve().parents[3] / "unsloth" / "models" / "loader.py"+ loader_tree = ast.parse(loader_path.read_text(encoding = "utf-8"))+ helper = next(+ node+ for node in loader_tree.body+ if isinstance(node, ast.FunctionDef) and node.name == "_strip_unsloth_bnb_4bit_suffix"+ )+ namespace = {}+ exec(compile(ast.Module(body = [helper], type_ignores = []), str(loader_path), "exec"), namespace)+ loader_strip = namespace["_strip_unsloth_bnb_4bit_suffix"]++ assert worker_mod._strip_unsloth_bnb_4bit_suffix(name) == stripped+ assert loader_strip(name) == stripped++[email protected]("backend", ["mlx", "embedding"])+def test_an_unreadable_mapper_does_not_admit_a_non_torch_backend(monkeypatch, backend):+ # The fail-open for an unreadable mapper is about the Torch loader, whose target the+ # mapper decides. MLX and embedding runs fetch the picked repo directly, so there the+ # auth-check is the only thing between an inaccessible gated model and a worker failure.+ import core.training.training as training_mod+ import utils.models.unsloth_mirror as mirror_mod++ monkeypatch.setattr(mirror_mod, "mirror_lookup_available", lambda: False)+ session = _Session(_http_error(401))+ _route(monkeypatch, gated = "manual", session = session)++ kwargs = {}+ if backend == "mlx":+ monkeypatch.setattr(training_mod, "should_use_mlx_training_backend", lambda **kw: True)+ else:+ kwargs["is_embedding"] = True++ with pytest.raises(HTTPException) as error:+ tr._remote_untrainable_model_format("google/gemma-3-270m-it", None, **kwargs)+ assert error.value.detail["code"] == "hf_model_access_denied"+ assert session.urls+++def test_a_lora_adapter_base_gets_its_own_mirror_scanned(mapper, monkeypatch):+ # loader.py:756-765 runs get_model_name over peft_config.base_model_name_or_path, so the+ # adapter's BASE has a mirror of its own and that mirror is what gets downloaded.+ import core.training.worker as worker_mod+ import utils.models.model_config as model_config_mod+ import utils.security as security_mod++ scanned: list[str] = []++ class _Decision:+ blocked = False++ def response_payload(self):+ return {}++ monkeypatch.setattr(+ model_config_mod,+ "get_base_model_from_lora_identifier",+ lambda target, token: "google/gemma-3-270m-it",+ )+ monkeypatch.setattr(worker_mod, "_model_local_files_only", lambda config: False, raising = False)+ monkeypatch.setattr(security_mod, "security_load_subdirs", lambda *a, **kw: ())+ monkeypatch.setattr(security_mod, "load_scan_target", lambda t, s: (t, s))+ monkeypatch.setattr(+ security_mod,+ "evaluate_file_security",+ lambda target, **kw: (scanned.append(target), _Decision())[1],+ )++ adapter = "someone/my-lora-adapter"+ assert (+ worker_mod._model_load_security_error(+ {"model_name": adapter, "load_in_4bit": True, "trust_remote_code": False},+ adapter,+ None,+ )+ is None+ )+ assert "google/gemma-3-270m-it" in scanned+ assert "unsloth/gemma-3-270m-it-unsloth-bnb-4bit" in scanneddiff --git a/studio/backend/utils/models/unsloth_mirror.py b/studio/backend/utils/models/unsloth_mirror.pynew file mode 100644index 00000000000..bc393fa253a--- /dev/null+++ b/studio/backend/utils/models/unsloth_mirror.py@@ -0,0 +1,151 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The public Unsloth repo that Unsloth's loader substitutes for an upstream model id."""++from __future__ import annotations++import ast+import importlib.util+from functools import lru_cache+from pathlib import Path+from typing import Optional++from loggers import get_logger+from utils.paths import is_local_path++logger = get_logger(__name__)+++def _unsloth_models_dir() -> Optional[Path]:+ spec = importlib.util.find_spec("unsloth")+ locations = list(spec.submodule_search_locations or ()) if spec else []+ return Path(locations[0]) / "models" if locations else None+++@lru_cache(maxsize = 1)+def _mapper_tables() -> Optional[tuple[dict, dict, dict]]:+ # Load the data file directly to avoid initializing Unsloth's GPU stack.+ try:+ models_dir = _unsloth_models_dir()+ if models_dir is None:+ return None+ mapper_spec = importlib.util.spec_from_file_location(+ "_studio_unsloth_mapper", models_dir / "mapper.py"+ )+ module = importlib.util.module_from_spec(mapper_spec)+ mapper_spec.loader.exec_module(module)+ return (+ module.INT_TO_FLOAT_MAPPER,+ module.FLOAT_TO_INT_MAPPER,+ module.MAP_TO_UNSLOTH_16bit,+ )+ except Exception as error:+ logger.debug("Could not read the Unsloth model mapper: %s", error)+ return None+++def _string_literal(node) -> Optional[str]:+ """``"Repo".lower()`` and ``"Repo"`` as data. BAD_MAPPINGS is written with ``.lower()``+ calls on both sides, so ast.literal_eval alone cannot read it."""+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ if (+ isinstance(node, ast.Call)+ and not node.args+ and not node.keywords+ and isinstance(node.func, ast.Attribute)+ and node.func.attr in ("lower", "upper", "strip")+ ):+ inner = _string_literal(node.func.value)+ return getattr(inner, node.func.attr)() if inner is not None else None+ return None+++@lru_cache(maxsize = 1)+def _bad_mappings() -> Optional[dict]:+ """``loader_utils.BAD_MAPPINGS``, the corrections the loader applies AFTER a table lookup+ (a 4-bit dynamic quant that is too big, or a MoE that HF loads too slowly). Parsed out of+ the source, because importing loader_utils imports torch.++ ``None`` means the corrections could not be read, which is NOT the same as an empty table:+ an uncorrected lookup can name a repo that does not exist, so the caller redirects nothing+ rather than redirect somewhere the loader will never go."""+ try:+ models_dir = _unsloth_models_dir()+ if models_dir is None:+ return None+ tree = ast.parse((models_dir / "loader_utils.py").read_text(encoding = "utf-8"))+ for node in tree.body:+ if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Dict):+ continue+ if not any(+ isinstance(target, ast.Name) and target.id == "BAD_MAPPINGS"+ for target in node.targets+ ):+ continue+ table = {}+ for key, value in zip(node.value.keys, node.value.values):+ name, replacement = _string_literal(key), _string_literal(value)+ if name is None or replacement is None:+ # An entry we cannot read as data. Reading the rest would silently drop+ # whichever correction that entry was.+ return None+ table[name.lower()] = replacement+ return table+ except Exception as error:+ logger.debug("Could not read the Unsloth loader corrections: %s", error)+ return None+++def mirror_lookup_available() -> bool:+ """Whether a None from :func:`unsloth_public_mirror` means "no public copy" at all.++ It can also mean "could not tell": the tables live in the installed unsloth package, and+ find_spec can resolve to a directory that has no models/mapper.py under it. Callers that+ REFUSE on a missing mirror have to tell those apart, or an unreadable table turns every+ gated model into a refusal, including the ones Unsloth would have trained.+ """+ return _mapper_tables() is not None and _bad_mappings() is not None+++def unsloth_public_mirror(model_name: Optional[str], load_in_4bit: bool = True) -> Optional[str]:+ """Return the public repo substituted by Unsloth's loader for this load mode, if any."""+ if (+ not isinstance(model_name, str)+ or model_name.strip().count("/") != 1+ or is_local_path(model_name)+ ):+ return None+ tables = _mapper_tables()+ if tables is None:+ return None+ int_to_float, float_to_int, map_to_unsloth_16bit = tables+ lower = model_name.strip().lower()+ # An unsloth/ id is NOT a fixed point. A 16-bit load of an explicit -unsloth-bnb-4bit id+ # resolves through INT_TO_FLOAT_MAPPER (unsloth/gemma-3-270m-it-unsloth-bnb-4bit ->+ # unsloth/gemma-3-270m-it), and BAD_MAPPINGS is applied to the INPUT name when the tables+ # resolve nothing (loader_utils.py:1014-1016), which is how a 4-bit+ # unsloth/Qwen3-30B-A3B-unsloth-bnb-4bit becomes unsloth/qwen3-30b-a3b. Both were verified+ # against get_model_name. Returning None for these let the security scan check a repo the+ # loader never fetches while the one it does fetch, and any custom code in it, went+ # unscanned. Identity results are still dropped at the end.+ if load_in_4bit:+ # A 4-bit load resolves through FLOAT_TO_INT_MAPPER alone, and keeps an explicit+ # -bnb-4bit name as given (unsloth.models.loader_utils.__get_model_name).+ mirror = None if lower.endswith("-bnb-4bit") else float_to_int.get(lower)+ else:+ mirror = int_to_float.get(lower) or map_to_unsloth_16bit.get(lower)+ # get_model_name corrects the resolved name, and corrects the INPUT name when the tables+ # resolved nothing. Without this, a 4-bit Qwen/Qwen3-30B-A3B resolves to+ # unsloth/Qwen3-30B-A3B-unsloth-bnb-4bit, which does not exist: the loader never fetches it.+ corrections = _bad_mappings()+ if corrections is None:+ return None+ if isinstance(mirror, str):+ mirror = corrections.get(mirror.lower(), mirror)+ else:+ mirror = corrections.get(lower)+ if not isinstance(mirror, str) or mirror.lower() == lower:+ return None+ return mirror