Skip to content

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.

Check a sentence-transformers module config on every version, and confirm the resolved class (#12444)

Daniel Han6102d2c7942b
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index c28a9cc87ac..a7a4cc919e5 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -742,7 +742,14 @@ jobs:
# torchvision: unsloth_zoo.vision_utils imports it at module scope.
pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \
'torch>=2.4,<2.11' 'torchvision<0.26' 'torchaudio<2.11'
- pip install 'transformers>=4.51,<5.5'
+ # sentence-transformers rides the transformers pin rather than a separate install, so
+ # resolving it cannot bump transformers past the ceiling. It is an extra, not a core
+ # dependency, and tests/test_st_modules_json_trust_gate.py skips without it, so
+ # installing it here is what makes that gate run in this shard instead of skipping.
+ # version-compat-ci's zoo-imports job runs the same file against the pinned
+ # transformers matrix; this shard adds the core dependency set, where discovery
+ # picks the file up and the importorskip would otherwise skip it for good.
+ pip install 'transformers>=4.51,<5.5' sentence-transformers
# bitsandbytes: hard import in unsloth/models/_utils.py. Recent
# versions ship a CPU build that imports cleanly on Linux.
pip install 'bitsandbytes>=0.45'
diff --git a/tests/test_st_modules_json_trust_gate.py b/tests/test_st_modules_json_trust_gate.py
index 233d78fb433..6357cf27ff6 100644
--- a/tests/test_st_modules_json_trust_gate.py
+++ b/tests/test_st_modules_json_trust_gate.py
@@ -27,8 +27,17 @@ import sys
import pytest
-# The gate runs inside sentence-transformers' module loading. The CPU repo-test shards do not
-# install it; version-compat-ci's zoo-imports-under-spoof job does, and runs this file.
+# sentence-transformers is an extra (`huggingfacenotorch`), not a core dependency, so
+# without this the whole file errors with ModuleNotFoundError in the shard that installs
+# the core set only, rather than skipping.
+#
+# Two jobs run this file, and for different reasons. version-compat-ci's zoo-imports job
+# names it on the pytest line and installs sentence-transformers for it, which is where
+# it runs under the CUDA spoof against the pinned transformers matrix. studio-backend-ci's
+# "Repo tests (CPU, auto-discovered)" shard collects it by discovery, where without a
+# sentence-transformers install the importorskip would leave it permanently skipped: that
+# branch also installs the package so the gate runs there too, on the core dependency set
+# rather than the version matrix.
pytest.importorskip("sentence_transformers")
from unsloth import FastSentenceTransformer # noqa: E402
@@ -176,14 +185,10 @@ def test_an_untrusted_type_is_not_probed_as_a_transformer_ref(model_dir):
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
+def test_a_module_config_may_not_smuggle_a_class_path_past_the_gate(tmp_path):
+ """Dense imports AND CALLS activation_function, on whichever version is installed."""
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(
@@ -191,7 +196,7 @@ def test_a_module_config_may_not_smuggle_a_class_path_past_the_gate(tmp_path, mo
encoding = "utf-8",
)
- with pytest.raises(ValueError, match = "does not gate it"):
+ with pytest.raises(ValueError, match = "executes third-party code"):
FastSentenceTransformer._check_module_config_class_refs(
str(load_path), "sentence_transformers.models.Dense", "some/repo", False, Dense
)
@@ -207,14 +212,12 @@ def test_a_module_config_may_not_smuggle_a_class_path_past_the_gate(tmp_path, mo
],
)
def test_an_in_namespace_type_cannot_smuggle_a_path_via_its_own_config_file(
- module_name, config_name, config, model_dir, monkeypatch
+ module_name, config_name, config, model_dir
):
"""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}")
@@ -235,20 +238,17 @@ def test_an_in_namespace_type_cannot_smuggle_a_path_via_its_own_config_file(
encoding = "utf-8",
)
- with pytest.raises(ValueError, match = "does not gate it"):
+ with pytest.raises(ValueError, match = "executes third-party code"):
_load_modules(model, False)
assert not witness.exists()
-def test_a_real_dense_config_is_untouched_by_that_check(tmp_path, monkeypatch):
+def test_a_real_dense_config_is_untouched_by_that_check(tmp_path):
"""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(
@@ -272,13 +272,19 @@ def test_a_real_dense_config_is_untouched_by_that_check(tmp_path, monkeypatch):
)
-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."""
[email protected]("helper", ["present", "absent", "none"])
+def test_the_check_does_not_key_off_the_import_module_class_attribute(
+ helper, tmp_path, monkeypatch
+):
+ """Not a version test: 5.5 exports it while its WordEmbeddings.load still calls
+ import_from_string on tokenizer_class, so the refusal holds whatever the attribute is."""
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")
+ if helper == "absent":
+ monkeypatch.delattr(st_util, "import_module_class", raising = False)
+ elif helper == "none":
+ monkeypatch.setattr(st_util, "import_module_class", None, raising = False)
load_path = tmp_path / "2_Dense"
load_path.mkdir()
@@ -286,6 +292,169 @@ def test_the_installed_sentence_transformers_gate_is_not_second_guessed(tmp_path
json.dumps({"activation_function": f"{MARKER}.Thing"}), encoding = "utf-8"
)
+ with pytest.raises(ValueError, match = "executes third-party code"):
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(load_path), "sentence_transformers.models.Dense", "some/repo", False, Dense
+ )
+
+
+def test_a_legacy_module_class_without_config_file_name_is_still_read(tmp_path):
+ """3.x/4.x WordEmbeddings has no config_file_name and opens its file by name."""
+
+ class WordEmbeddings: # no config_file_name, like the 3.x/4.x class
+ pass
+
+ load_path = tmp_path / "0_WordEmbeddings"
+ load_path.mkdir()
+ (load_path / "wordembedding_config.json").write_text(
+ json.dumps({"tokenizer_class": f"{MARKER}.Thing"}), encoding = "utf-8"
+ )
+
+ with pytest.raises(ValueError, match = "executes third-party code"):
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(load_path),
+ "sentence_transformers.models.WordEmbeddings",
+ "some/repo",
+ False,
+ WordEmbeddings,
+ )
+
+
[email protected]("trusted, expect_refusal", [(False, True), (True, False)])
+def test_the_checkpoint_reload_honours_the_consent_the_model_was_loaded_with(
+ trusted, expect_refusal, tmp_path
+):
+ """The reload takes only a checkpoint path, so hard-coding False left no way to consent."""
+ from sentence_transformers.models import Dense
+
+ 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"
+ )
+
+ class FakeModel:
+ _unsloth_trust_remote_code = trusted
+
+ trust = getattr(FakeModel, "_unsloth_trust_remote_code", False)
+ if expect_refusal:
+ with pytest.raises(ValueError, match = "executes third-party code"):
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(load_path), "sentence_transformers.models.Dense", str(tmp_path), trust, Dense
+ )
+ else:
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(load_path), "sentence_transformers.models.Dense", str(tmp_path), trust, Dense
+ )
+
+
+def test_every_load_route_records_the_consent_it_used():
+ """The reload reads the flag off the model, so every route must set it."""
+ import inspect
+
+ source = inspect.getsource(FastSentenceTransformer.from_pretrained)
+ assert source.count("_unsloth_trust_remote_code = trust_remote_code") == source.count(
+ "return st_model"
+ )
+
+
+def _write_module_config(folder, name, payload):
+ folder.mkdir(parents = True, exist_ok = True)
+ (folder / name).write_text(json.dumps(payload), encoding = "utf8")
+ return folder
+
+
+def test_a_literal_activation_on_a_pooling_module_is_not_a_class_ref(tmp_path):
+ """SpladePooling's activation_function is an enum it compares, not a path it imports.
+
+ It lists activation_function in its own config_keys and saves "relu" or "log1p_relu"
+ there, then does `if self.activation_function == "log1p_relu"`. Keying the check on
+ the key name alone refused both values for not starting with "torch.", so no SPLADE
+ sparse model could load without the user turning on remote code for no reason.
+ """
+
+ class SpladePooling:
+ config_file_name = "config.json"
+
+ folder = _write_module_config(
+ tmp_path / "1_SpladePooling",
+ "config.json",
+ {"pooling_strategy": "max", "activation_function": "log1p_relu"},
+ )
FastSentenceTransformer._check_module_config_class_refs(
- str(load_path), "sentence_transformers.models.Dense", "some/repo", False, Dense
+ str(folder),
+ "sentence_transformers.sparse_encoder.models.SpladePooling",
+ "acme/sparse",
+ False,
+ SpladePooling,
+ )
+
+
+def test_dense_still_refuses_an_activation_outside_torch(tmp_path):
+ """Dense.load does `import_from_string(config["activation_function"])()`, so this one
+ is a real import and the scoping must not have let it through."""
+ st_models = pytest.importorskip("sentence_transformers.models")
+
+ folder = _write_module_config(
+ tmp_path / "2_Dense",
+ "config.json",
+ {"in_features": 8, "out_features": 8, "activation_function": "evil_pkg.Boom"},
)
+ with pytest.raises(ValueError, match = "evil_pkg.Boom"):
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(folder),
+ "sentence_transformers.models.Dense",
+ "acme/embedder",
+ False,
+ st_models.Dense,
+ )
+
+
+def test_word_embeddings_still_refuses_a_foreign_tokenizer_class(tmp_path):
+ """WordEmbeddings.load does `import_from_string(config.pop("tokenizer_class"))`."""
+ st_models = pytest.importorskip("sentence_transformers.models")
+ if getattr(st_models, "WordEmbeddings", None) is None:
+ pytest.skip("this sentence-transformers has no WordEmbeddings")
+
+ folder = _write_module_config(
+ tmp_path / "0_WordEmbeddings",
+ "config.json",
+ {"tokenizer_class": "evil_pkg.Tok", "max_seq_length": 8},
+ )
+ with pytest.raises(ValueError, match = "evil_pkg.Tok"):
+ FastSentenceTransformer._check_module_config_class_refs(
+ str(folder),
+ "sentence_transformers.models.WordEmbeddings",
+ "acme/embedder",
+ False,
+ st_models.WordEmbeddings,
+ )
+
+
+def test_a_subclass_inherits_its_parents_rules(tmp_path):
+ """The rules follow the bases, so a version that subclasses Dense is still gated."""
+ st_models = pytest.importorskip("sentence_transformers.models")
+
+ class TunedDense(st_models.Dense):
+ pass
+
+ assert ("activation_function", "torch.") in FastSentenceTransformer._class_ref_rules(TunedDense)
+
+
+def test_every_config_driven_import_in_sentence_transformers_has_a_rule():
+ """The scoping is only safe if the list of loaders is complete.
+
+ Asym is an alias of Router from 5.0, so it reports Router's name and is covered by
+ that entry rather than its own. This asserts the set of classes, so a version that
+ adds another config-driven import shows up here as a missing key rather than as a
+ silently unchecked path.
+ """
+ covered = set(FastSentenceTransformer._MODULE_CONFIG_CLASS_REFS)
+ assert covered == {"Dense", "WordEmbeddings", "Router", "Asym"}
+
+ st_models = pytest.importorskip("sentence_transformers.models")
+ for name in ("Dense", "WordEmbeddings", "Router"):
+ klass = getattr(st_models, name, None)
+ if klass is None:
+ continue
+ assert FastSentenceTransformer._class_ref_rules(klass), name
diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.py
index 95ae07bf7de..69b360e86db 100644
--- a/unsloth/models/sentence_transformer.py
+++ b/unsloth/models/sentence_transformer.py
@@ -1220,7 +1220,9 @@ class FastSentenceTransformer(FastModel):
)
if class_ref.startswith("sentence_transformers."):
- return import_from_string(class_ref)
+ return FastSentenceTransformer._import_sentence_transformers_class(
+ class_ref, model_name
+ )
if not trust_remote_code:
# Not transformers' resolve_trust_remote_code: it appends a hf.co URL that is bogus for local dirs.
@@ -1251,6 +1253,35 @@ class FastSentenceTransformer(FastModel):
cache_folder = cache_dir,
)
+ @staticmethod
+ def _import_sentence_transformers_class(class_ref, model_name):
+ """The prefix pins the import to the installed package, but not to a module class: the
+ same syntax names any attribute, and _load_modules then calls .load() on it."""
+ from sentence_transformers.util import import_from_string
+
+ if not class_ref.split(".")[-1] or not all(
+ part.isidentifier() for part in class_ref.split(".")
+ ):
+ raise ValueError(
+ f"Unsloth: The model {model_name} declares the module type {class_ref!r}, which is "
+ f"not a dotted class path. Refusing to resolve it."
+ )
+
+ resolved = import_from_string(class_ref)
+ module_name = getattr(resolved, "__module__", "") or ""
+ if not (
+ isinstance(resolved, type)
+ and issubclass(resolved, torch.nn.Module)
+ and module_name.split(".")[0] == "sentence_transformers"
+ and hasattr(resolved, "load")
+ ):
+ raise ValueError(
+ f"Unsloth: The model {model_name} declares the module type {class_ref!r}, which "
+ f"resolves to {resolved!r} rather than a sentence-transformers module class. "
+ f"Refusing to load it."
+ )
+ return resolved
+
@staticmethod
def _is_transformer_module_ref(class_ref):
"""Name ST's Transformer without importing anything, since importing to compare is the same
@@ -1265,16 +1296,51 @@ class FastSentenceTransformer(FastModel):
"sentence_transformers.base.modules.transformer.Transformer",
}
- # 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."),
- )
+ # Dense imports AND CALLS config["activation_function"], WordEmbeddings imports
+ # config["tokenizer_class"], Router/Asym import every config["types"] value, all ungated on
+ # some versions, so an allowed in-namespace "type" reaches them. Prefixes are upstream's own
+ # rules, applied unconditionally: util.import_module_class is not a version test, since 5.5
+ # exports it while its WordEmbeddings.load still calls import_from_string on tokenizer_class.
+ # Which config key each loader resolves as a dotted import path, keyed by the class
+ # that resolves it. By class and not by key name: SpladePooling lists
+ # activation_function in its own config_keys too, but the value there is the literal
+ # "relu" or "log1p_relu" and it is compared, never imported (SpladePooling.py:
+ # `if self.activation_function == "log1p_relu"`). Matching on the key name alone
+ # refused every SPLADE sparse model for naming a value that no loader imports.
+ #
+ # Complete for the module path as of 5.1: the only config-driven import_from_string
+ # calls in the package are Dense.load on activation_function, WordEmbeddings.load on
+ # tokenizer_class, Router.load on types, and SentenceTransformer's own modules.json
+ # type, which _resolve_module_class covers. Asym is an alias of Router from 5.0
+ # (`Asym = Router`), so it arrives here as Router; the entry is kept for versions
+ # where it is its own class.
+ _MODULE_CONFIG_CLASS_REFS = {
+ "Dense": (("activation_function", "torch."),),
+ "WordEmbeddings": (("tokenizer_class", "sentence_transformers."),),
+ "Router": (("types", "sentence_transformers."),),
+ "Asym": (("types", "sentence_transformers."),),
+ }
+
+ @staticmethod
+ def _class_ref_rules(module_class):
+ """The key rules for this class, following its bases so a subclass is covered."""
+ rules = []
+ for ancestor in getattr(module_class, "__mro__", (module_class,)):
+ for rule in FastSentenceTransformer._MODULE_CONFIG_CLASS_REFS.get(
+ getattr(ancestor, "__name__", ""), ()
+ ):
+ if rule not in rules:
+ rules.append(rule)
+ return tuple(rules)
+
+ # config_file_name only exists from 5: on 3.x/4.x these classes open their file by name.
+ _LEGACY_MODULE_CONFIG_FILES = {
+ "WordEmbeddings": "wordembedding_config.json",
+ "Router": "router_config.json",
+ "Asym": "router_config.json",
+ "CNN": "cnn_config.json",
+ "LSTM": "lstm_config.json",
+ }
@staticmethod
def _check_module_config_class_refs(
@@ -1283,11 +1349,11 @@ class FastSentenceTransformer(FastModel):
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.
+ # Nothing to check unless this class is one that resolves a dotted path out of its
+ # own config. Every other module reads plain values, so looking for these keys in
+ # its config found a name nobody imports and refused a load that works.
+ rules = FastSentenceTransformer._class_ref_rules(module_class)
+ if not rules:
return
# Read what the loader will read: each module names its own file (Router
@@ -1298,6 +1364,11 @@ class FastSentenceTransformer(FastModel):
config_file_name = getattr(module_class, "config_file_name", None)
if isinstance(config_file_name, str):
config_names.append(config_file_name)
+ legacy = FastSentenceTransformer._LEGACY_MODULE_CONFIG_FILES.get(
+ getattr(module_class, "__name__", "")
+ )
+ if legacy is not None:
+ config_names.append(legacy)
config_names.append("config.json")
refs = []
@@ -1316,28 +1387,26 @@ class FastSentenceTransformer(FastModel):
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, prefix in rules:
+ if key == "types":
+ # Router keeps a mapping of route name to class, not a single ref.
+ types = config.get("types")
+ if isinstance(types, dict):
+ refs += [
+ ("types", value, prefix)
+ for value in types.values()
+ if isinstance(value, str)
+ ]
+ elif isinstance(config.get(key), str):
+ refs.append((key, config[key], prefix))
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."
+ f"code. Please pass the argument `trust_remote_code=True` to allow custom code to "
+ f"be run."
)
@staticmethod
@@ -1714,6 +1783,7 @@ class FastSentenceTransformer(FastModel):
) and hasattr(st_model[0], "unpad_inputs"):
# Refresh ST's cached capability decision after changing the backend.
st_model[0].unpad_inputs = st_model[0].unpad_inputs
+ st_model._unsloth_trust_remote_code = trust_remote_code
return st_model
if "auto_model" not in kwargs:
@@ -1891,6 +1961,7 @@ class FastSentenceTransformer(FastModel):
st_model.push_to_hub_merged = types.MethodType(_push_to_hub_merged, st_model)
+ st_model._unsloth_trust_remote_code = trust_remote_code
return st_model
# Warn if using 4-bit with an encoder: it is slow due to dequantization overhead.
@@ -2143,6 +2214,7 @@ class FastSentenceTransformer(FastModel):
print(f"Unsloth: Successfully pushed merged model to https://huggingface.co/{repo_id}")
st_model.push_to_hub_merged = types.MethodType(_push_to_hub_merged, st_model)
+ st_model._unsloth_trust_remote_code = trust_remote_code
return st_model
@staticmethod
@@ -2528,6 +2600,17 @@ def _patch_st_trainer_load_from_checkpoint():
raise RuntimeError(f"Unsloth: Bad checkpoint module path for index {idx}.")
if not hasattr(module_cls, "load"):
raise RuntimeError(f"Unsloth: Module {idx} cannot be reloaded.")
+ # The class is trusted, coming from the live model, but load() reads the checkpoint's
+ # own configs and some versions import dotted paths out of them.
+ FastSentenceTransformer._check_module_config_class_refs(
+ module_dir,
+ saved_type or module_cls.__name__,
+ root,
+ # The consent the model was loaded with. Hard-coding False would make a resume
+ # impossible for a model that legitimately needed it, with no way to say so here.
+ getattr(self.model, "_unsloth_trust_remote_code", False),
+ module_cls,
+ )
fresh = module_cls.load(module_dir)
if not isinstance(fresh, module_cls):
raise RuntimeError(f"Unsloth: Module {idx} reload returned wrong type.")