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
Resolve a sentence-transformers modules.json module class through the same trust gate as upstream (#12436)
Daniel Hand0b3a7b84138
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex abfc0bec771..0d40019ac6c 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -5133,6 +5133,10 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->token = hf_token,revision = model_revision,use_exact_model_name = model_revision is not None,+ # Deliberately NOT config["trust_remote_code"]: the consent scan above decides purely+ # on auto_map, so a modules.json module class is never scanned. Forwarding consent+ # here would fetch and run that unscanned code.+ trust_remote_code = False,)except Exception as error:if not model_local_only:@@ -5161,6 +5165,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->token = hf_token,revision = model_revision,use_exact_model_name = model_revision is not None,+ # Deliberately False, as above.+ trust_remote_code = False,)except Exception as e:event_queue.put(diff --git a/tests/test_st_modules_json_trust_gate.py b/tests/test_st_modules_json_trust_gate.pynew file mode 100644index 00000000000..002e42cd11e--- /dev/null+++ b/tests/test_st_modules_json_trust_gate.py@@ -0,0 +1,287 @@+# 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 modules.json "type" is untrusted input, not an import target.++`_module_path` fetches modules.json with `hf_hub_download`, so publishing a Hub repo is+enough; no local access required. See `_resolve_module_class` for the gate being tested.++Offline and CPU-only: the marker package is inert and only appends to a file, which is how+these tests observe whether an import happened at all.+"""++import json+import os+import sys++import pytest++from unsloth import FastSentenceTransformer+++MARKER = "unsloth_st_gate_marker"+++def model_dir(tmp_path, monkeypatch):+ """A model folder whose single modules.json entry names the marker package."""+ witness = tmp_path / "witness.txt"++ pkg = tmp_path / "site" / MARKER+ pkg.mkdir(parents = True)+ (pkg / "__init__.py").write_text(+ f"open({str(witness)!r}, 'a').write('imported\\n')\n"+ "class Thing:\n"+ " @staticmethod\n"+ " def load(path, **kwargs):\n"+ " return Thing()\n",+ encoding = "utf-8",+ )+ monkeypatch.syspath_prepend(str(tmp_path / "site"))++ model = tmp_path / "model"+ (model / "0_Sub").mkdir(parents = True)+ (model / "modules.json").write_text(+ json.dumps([{"idx": 0, "name": "0", "path": "0_Sub", "type": f"{MARKER}.Thing"}]),+ encoding = "utf-8",+ )++ yield model, witness++ for name in [m for m in sys.modules if m.split(".")[0] == MARKER]:+ del sys.modules[name]+++def _load_modules(model, trust_remote_code):+ return FastSentenceTransformer._load_modules(+ str(model),+ None,+ None,+ None,+ 64,+ "mean",+ trust_remote_code = trust_remote_code,+ )+++def test_an_untrusted_module_type_is_never_imported(model_dir):+ """The refusal must land BEFORE the import, so the witness must not exist."""+ model, witness = model_dir++ with pytest.raises(ValueError, match = "not part of Sentence Transformers"):+ _load_modules(model, False)++ assert not witness.exists(), "modules.json type was imported without consent"+++def test_the_refusal_fails_the_load_rather_than_skipping_the_module(model_dir):+ """Fail closed, rather than degrading to "load the other modules and carry on"."""+ model, witness = model_dir+ (model / "1_Pooling").mkdir()+ (model / "modules.json").write_text(+ json.dumps(+ [+ {"idx": 0, "name": "0", "path": "0_Sub", "type": f"{MARKER}.Thing"},+ {+ "idx": 1,+ "name": "1",+ "path": "1_Pooling",+ "type": "sentence_transformers.models.Pooling",+ },+ ]+ ),+ encoding = "utf-8",+ )++ with pytest.raises(ValueError):+ _load_modules(model, False)++ assert not witness.exists()+++def test_consent_still_loads_a_custom_module_type(model_dir):+ model, witness = model_dir++ modules, no_modules_json = _load_modules(model, True)++ assert witness.exists(), "consented module type was not imported"+ assert no_modules_json is False+ assert [type(m).__name__ for m in modules.values()] == ["Thing"]+++def test_a_non_string_module_type_is_refused(model_dir):+ model, witness = model_dir+ (model / "modules.json").write_text(+ json.dumps([{"idx": 0, "name": "0", "path": "0_Sub", "type": {"bad": 1}}]),+ encoding = "utf-8",+ )++ with pytest.raises(ValueError):+ _load_modules(model, False)++ assert not witness.exists()+++ "class_ref",+ [+ "sentence_transformers.models.Transformer",+ "sentence_transformers.models.Pooling",+ "sentence_transformers.models.Normalize",+ "sentence_transformers.models.Dense",+ ],+)+def test_the_stock_module_types_resolve_without_consent(class_ref, tmp_path):+ """These are every type real embedders ship: bge, MiniLM, e5, gte, bge-m3 and+ Qwen3-Embedding use the first three, embeddinggemma-300m adds the two Dense entries."""+ module_class = FastSentenceTransformer._resolve_module_class(class_ref, str(tmp_path), False)++ assert module_class.__module__.startswith("sentence_transformers")+++ "class_ref",+ [+ "sentence_transformers.models.Transformer",+ "sentence_transformers.models.transformer.Transformer",+ "sentence_transformers.base.modules.transformer.Transformer",+ ],+)+def test_the_fast_encoder_path_still_recognises_the_transformer_refs(class_ref):+ """These three refs name ST's Transformer across the 5.x/6.x layouts."""+ assert FastSentenceTransformer._is_transformer_module_ref(class_ref) is True+++def test_an_untrusted_type_is_not_probed_as_a_transformer_ref(model_dir):+ """It used to import the ref just to compare it against ST's Transformer, which is the same+ execution by another door. It is now a pure string test."""+ model, witness = model_dir++ assert FastSentenceTransformer._is_transformer_module_ref(f"{MARKER}.Thing") is False+ assert not witness.exists()+++def test_a_module_config_may_not_smuggle_a_class_path_past_the_gate(tmp_path, monkeypatch):+ """Simulate sentence-transformers < 6, whose Dense loader imports AND CALLS+ activation_function ungated, by hiding import_module_class."""+ import sentence_transformers.util as st_util+ from sentence_transformers.models import Dense++ monkeypatch.delattr(st_util, "import_module_class", raising = False)++ load_path = tmp_path / "2_Dense"+ load_path.mkdir()+ (load_path / "config.json").write_text(+ json.dumps({"in_features": 8, "out_features": 8, "activation_function": f"{MARKER}.Thing"}),+ encoding = "utf-8",+ )++ with pytest.raises(ValueError, match = "does not gate it"):+ FastSentenceTransformer._check_module_config_class_refs(+ str(load_path), "sentence_transformers.models.Dense", "some/repo", False, Dense+ )+++ "module_name, config_name, config",+ [+ # Each module names its own config file, so a check reading only "config.json" skips the two+ # modules whose loaders resolve a dotted path out of it, which are the reason it exists.+ ("Router", "router_config.json", {"types": {"query": MARKER + ".Thing"}}),+ ("WordEmbeddings", "wordembedding_config.json", {"tokenizer_class": MARKER + ".Thing"}),+ ],+)+def test_an_in_namespace_type_cannot_smuggle_a_path_via_its_own_config_file(+ module_name, config_name, config, model_dir, monkeypatch+):+ """Through _load_modules, not the helper: the type is an allowed sentence_transformers.* class,+ so the refusal has to come from reading the config file that module's loader reads."""+ import sentence_transformers.util as st_util+ from sentence_transformers import models as st_models++ monkeypatch.delattr(st_util, "import_module_class", raising = False)+ if getattr(st_models, module_name, None) is None:+ pytest.skip(f"installed sentence-transformers has no {module_name}")++ model, witness = model_dir+ (model / f"1_{module_name}").mkdir()+ (model / f"1_{module_name}" / config_name).write_text(json.dumps(config), encoding = "utf-8")+ (model / "modules.json").write_text(+ json.dumps(+ [+ {+ "idx": 0,+ "name": "0",+ "path": f"1_{module_name}",+ "type": f"sentence_transformers.models.{module_name}",+ }+ ]+ ),+ encoding = "utf-8",+ )++ with pytest.raises(ValueError, match = "does not gate it"):+ _load_modules(model, False)++ assert not witness.exists()+++def test_a_real_dense_config_is_untouched_by_that_check(tmp_path, monkeypatch):+ """embeddinggemma-300m's Dense modules declare torch.nn.modules.linear.Identity, exactly what+ ST >= 6 allows unconsented."""+ import sentence_transformers.util as st_util+ from sentence_transformers.models import Dense++ monkeypatch.delattr(st_util, "import_module_class", raising = False)++ load_path = tmp_path / "2_Dense"+ load_path.mkdir()+ (load_path / "config.json").write_text(+ json.dumps(+ {+ "in_features": 768,+ "out_features": 3072,+ "bias": False,+ "activation_function": "torch.nn.modules.linear.Identity",+ }+ ),+ encoding = "utf-8",+ )++ FastSentenceTransformer._check_module_config_class_refs(+ str(load_path),+ "sentence_transformers.models.Dense",+ "unsloth/embeddinggemma-300m",+ False,+ Dense,+ )+++def test_the_installed_sentence_transformers_gate_is_not_second_guessed(tmp_path):+ """ST >= 6 gates its own config refs, so the check is a no-op rather than a diverging copy."""+ import sentence_transformers.util as st_util+ from sentence_transformers.models import Dense++ if not hasattr(st_util, "import_module_class"):+ pytest.skip("installed sentence-transformers has no gate of its own")++ load_path = tmp_path / "2_Dense"+ load_path.mkdir()+ (load_path / "config.json").write_text(+ json.dumps({"activation_function": f"{MARKER}.Thing"}), encoding = "utf-8"+ )++ FastSentenceTransformer._check_module_config_class_refs(+ str(load_path), "sentence_transformers.models.Dense", "some/repo", False, Dense+ )diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 7d5189c14d5..95ae07bf7de 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -1194,28 +1194,151 @@ class FastSentenceTransformer(FastModel):return transformer_module+ @staticmethod+ def _resolve_module_class(+ class_ref,+ model_name,+ trust_remote_code,+ token = None,+ cache_dir = None,+ revision = None,+ ):+ """Resolve a modules.json "type" to a class, gated like sentence-transformers >= 6.0.++ modules.json ships inside the model directory or Hub repo, so its "type" is untrusted+ input: resolving it imports that dotted path and runs its top-level code in this process,+ with no .py needed anywhere in the model folder. sentence-transformers 6.0 refuses any+ class outside sentence_transformers.* without trust_remote_code (its #3801); since+ _load_modules reimplements their module scan, that gate has to be mirrored here.+ """+ from sentence_transformers.util import import_from_string++ if not isinstance(class_ref, str):+ raise ValueError(+ f"Unsloth: modules.json of {model_name} declares a module type that is not a string "+ f"({class_ref!r}). Refusing to resolve it."+ )++ if class_ref.startswith("sentence_transformers."):+ return import_from_string(class_ref)++ if not trust_remote_code:+ # Not transformers' resolve_trust_remote_code: it appends a hf.co URL that is bogus for local dirs.+ is_local_dir = isinstance(model_name, (str, os.PathLike)) and os.path.isdir(model_name)+ location = (+ os.path.abspath(model_name) if is_local_dir else f"https://hf.co/{model_name}"+ )+ raise ValueError(+ f"Unsloth: The model {model_name} references the module class {class_ref!r}, which is not "+ f"part of Sentence Transformers. Importing it executes third-party code. You can inspect the "+ f"repository content at {location}.\n"+ f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."+ )++ # Consented: prefer the repo's own modeling file over a same-named installed package, like stock ST >= 6.+ try:+ from sentence_transformers.util import import_module_class+ except ImportError:+ # sentence-transformers < 6 has no dynamic-module resolver; the gate above still applies.+ return import_from_string(class_ref)++ return import_module_class(+ class_ref,+ model_name_or_path = model_name,+ trust_remote_code = True,+ revision = revision,+ token = token,+ cache_folder = cache_dir,+ )+@staticmethoddef _is_transformer_module_ref(class_ref):- if class_ref in {+ """Name ST's Transformer without importing anything, since importing to compare is the same+ execution the gate refuses. Any other spelling is caught by `is Transformer` in+ _load_modules, after gating; refusals all live in _resolve_module_class."""+ if not isinstance(class_ref, str):+ return False++ return class_ref in {"sentence_transformers.models.Transformer","sentence_transformers.models.transformer.Transformer","sentence_transformers.base.modules.transformer.Transformer",- }:- return True+ }- try:- from sentence_transformers.models import Transformer- from sentence_transformers.util import import_from_string-- module_class = import_from_string(class_ref)- return module_class is Transformer- except (ImportError, AttributeError, TypeError, ValueError) as exception:- logging.debug(- "Unsloth: Could not resolve SentenceTransformer module ref %r: %s",- class_ref,- exception,- )- return False+ # A module's own config carries further dotted class paths that the ST < 6 loaders import+ # ungated, so an allowed in-namespace "type" could walk around the gate above: Dense imports AND+ # CALLS config["activation_function"], WordEmbeddings imports config["tokenizer_class"], and+ # Router/Asym import every value of config["types"]. The prefixes are upstream's own rules+ # (ST >= 6 allows only "torch.*" for Dense and routes the rest through import_module_class),+ # applied only where the installed library has no gate.+ _MODULE_CONFIG_CLASS_REFS = (+ ("activation_function", "torch."),+ ("tokenizer_class", "sentence_transformers."),+ )++ @staticmethod+ def _check_module_config_class_refs(+ load_path, class_ref, model_name, trust_remote_code, module_class+ ):+ if trust_remote_code:+ return++ import sentence_transformers+ import sentence_transformers.util as st_util++ if hasattr(st_util, "import_module_class"):+ # sentence-transformers >= 6 applies these gates in the module loaders themselves.+ return++ # Read what the loader will read: each module names its own file (Router+ # "router_config.json", WordEmbeddings "wordembedding_config.json"), and Router falls back to+ # "config.json", which is also Module's default and so Dense's. Hard-coding "config.json"+ # would skip exactly the two modules this check exists for.+ config_names = []+ config_file_name = getattr(module_class, "config_file_name", None)+ if isinstance(config_file_name, str):+ config_names.append(config_file_name)+ config_names.append("config.json")++ refs = []+ for config_name in dict.fromkeys(config_names):+ config_path = os.path.join(load_path, config_name)+ if not os.path.isfile(config_path):+ continue+ try:+ with open(config_path, encoding = "utf8") as f:+ config = json.load(f)+ except (OSError, ValueError) as exception:+ logging.debug(+ "Unsloth: Could not read module config %s: %s", config_path, exception+ )+ continue+ if not isinstance(config, dict):+ continue++ refs += [+ (key, config[key], prefix)+ for key, prefix in FastSentenceTransformer._MODULE_CONFIG_CLASS_REFS+ if isinstance(config.get(key), str)+ ]+ types = config.get("types")+ if isinstance(types, dict):+ refs += [+ ("types", value, "sentence_transformers.")+ for value in types.values()+ if isinstance(value, str)+ ]++ for key, value, prefix in refs:+ if not value.startswith(prefix):+ raise ValueError(+ f"Unsloth: The model {model_name} declares the module {class_ref} whose config "+ f"{key} is {value!r}, a class outside {prefix}*. Importing it executes third-party "+ f"code, and the installed sentence-transformers "+ f"({getattr(sentence_transformers, '__version__', 'unknown')}) does not gate it. "+ f"Upgrade to sentence-transformers >= 6.0, or pass the argument "+ f"`trust_remote_code=True` to allow custom code to be run."+ )@staticmethoddef _load_modules(@@ -1230,8 +1353,8 @@ class FastSentenceTransformer(FastModel):revision = None,) -> tuple[OrderedDict, bool]:"""Load modules from modules.json, else fall back to hard-coded modules. Returns (modules, no_modules_json)."""- from sentence_transformers.util import import_from_string, load_dir_path- from sentence_transformers.models import Pooling, Normalize+ from sentence_transformers.util import load_dir_path+ from sentence_transformers.models import Pooling, Normalize, Transformermodules = OrderedDict()modules_json_path = FastSentenceTransformer._module_path(@@ -1246,7 +1369,24 @@ class FastSentenceTransformer(FastModel):class_ref = module_config["type"]name = module_config.get("name", str(module_config.get("idx", len(modules))))+ # Gate before any download: a refused type must fail the load outright, not fall+ # through the "could not download" skip below. Resolved once, since a consented+ # repo-local ref costs a Hub round trip.+ module_class = Noneif FastSentenceTransformer._is_transformer_module_ref(class_ref):+ is_transformer_module = True+ else:+ module_class = FastSentenceTransformer._resolve_module_class(+ class_ref,+ model_name,+ trust_remote_code,+ token = token,+ cache_dir = cache_dir,+ revision = revision,+ )+ is_transformer_module = module_class is Transformer++ if is_transformer_module:transformer_module = FastSentenceTransformer._create_transformer_module(model_name,model,@@ -1276,7 +1416,10 @@ class FastSentenceTransformer(FastModel):print(f"Unsloth Warning: Could not download module {module_path}: {e}")continue- module_class = import_from_string(class_ref)+ FastSentenceTransformer._check_module_config_class_refs(+ load_path, class_ref, model_name, trust_remote_code, module_class+ )+try:module = module_class.load(load_path)modules[name] = module