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.

Fix text-only VLM decoder saves reloading with random weights (#12561)

Stefan Wangf9342970dd7f
diff --git a/tests/python/test_fast_language_model_text_only.py b/tests/python/test_fast_language_model_text_only.py
index c6bbf795d0e..d98ee371fa7 100644
--- a/tests/python/test_fast_language_model_text_only.py
+++ b/tests/python/test_fast_language_model_text_only.py
@@ -86,6 +86,7 @@ def _load_text_only_namespace():
"_get_text_only_config",
"_get_text_only_key_mapping",
"_apply_text_only_key_mapping",
+ "_drop_text_only_key_mapping",
):
if name in funcs:
exec(funcs[name], ns)
@@ -363,18 +364,13 @@ def test_text_only_key_mapping_targets_published_prefixes():
assert mapping.get(r"^language_model\.lm_head\.") == "lm_head."
-def test_gemma3_text_only_loads_real_language_weights_from_vlm_checkpoint(tmp_path):
- # PR #5816: text-only loading of a Gemma 3 VLM checkpoint must load real language weights, not random ones.
- # Fails on tf >=5 without the key_mapping fix.
- transformers = pytest.importorskip("transformers")
- torch = pytest.importorskip("torch")
+def _write_published_gemma3_checkpoint(tmp_path, sentinel):
import shutil
- from safetensors.torch import load_file, save_file
- get_text_config = _load_text_only_helper()
- get_key_mapping = _load_util_func("_get_text_only_key_mapping")
+ import torch
+ import transformers
+ from safetensors.torch import load_file, save_file
- sentinel = 0.1234
text_cfg = transformers.Gemma3TextConfig(
hidden_size = 32,
intermediate_size = 64,
@@ -434,6 +430,20 @@ def test_gemma3_text_only_loads_real_language_weights_from_vlm_checkpoint(tmp_pa
if not p.name.endswith((".safetensors", ".bin", ".index.json")):
shutil.copy(p, real_dir / p.name)
save_file(weights, str(real_dir / "model.safetensors"))
+ return real_dir, full_config
+
+
+def test_gemma3_text_only_loads_real_language_weights_from_vlm_checkpoint(tmp_path):
+ # PR #5816: text-only loading of a Gemma 3 VLM checkpoint must load real language weights, not random ones.
+ # Fails on tf >=5 without the key_mapping fix.
+ transformers = pytest.importorskip("transformers")
+ torch = pytest.importorskip("torch")
+
+ get_text_config = _load_text_only_helper()
+ get_key_mapping = _load_util_func("_get_text_only_key_mapping")
+
+ sentinel = 0.1234
+ real_dir, full_config = _write_published_gemma3_checkpoint(tmp_path, sentinel)
text_config = get_text_config(full_config, "google/gemma-3-27b-it")
load_kwargs = {}
@@ -459,6 +469,56 @@ def test_gemma3_text_only_loads_real_language_weights_from_vlm_checkpoint(tmp_pa
), "vision tower should be skipped on the text-only path"
+def test_gemma3_text_only_save_reloads_as_the_decoder(tmp_path):
+ # #12554: tf 5 save_pretrained reverses the load's key_mapping unless the loader drops it.
+ transformers = pytest.importorskip("transformers")
+ torch = pytest.importorskip("torch")
+ if int(transformers.__version__.split(".")[0]) < 5:
+ pytest.skip(
+ reason = "#12554: transformers 4 strips the wrapper prefix itself, so no key_mapping is added or dropped"
+ )
+ ns = _load_text_only_namespace()
+ ns["_parent_conversions_for_text_only"] = lambda model_type: []
+
+ real_dir, full_config = _write_published_gemma3_checkpoint(tmp_path, 0.1234)
+ text_config = ns["_get_text_only_config"](full_config, "google/gemma-3-4b-pt")
+ kwargs = {}
+ mapping = ns["_apply_text_only_key_mapping"](kwargs, full_config, text_config)
+ assert mapping and kwargs["key_mapping"] == mapping
+ model = transformers.AutoModelForCausalLM.from_pretrained(
+ real_dir,
+ config = text_config,
+ dtype = torch.float32,
+ local_files_only = True,
+ **kwargs,
+ )
+ ns["_drop_text_only_key_mapping"](model, mapping)
+
+ model.save_pretrained(tmp_path / "saved")
+ reloaded = transformers.AutoModelForCausalLM.from_pretrained(
+ tmp_path / "saved", dtype = torch.float32, local_files_only = True
+ )
+ expected, actual = model.state_dict(), reloaded.state_dict()
+ assert actual.keys() == expected.keys()
+ for name, tensor in expected.items():
+ assert torch.equal(actual[name], tensor), f"{name} was not reloaded from the save"
+
+
+def test_text_only_loaders_keep_the_key_mapping_they_drop():
+ # #12554: the family-decoder branch must hand its mapping to _drop_text_only_key_mapping.
+ def _from_apply(value):
+ return (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Name)
+ and value.func.id == "_apply_text_only_key_mapping"
+ )
+
+ for path, class_name in ((LOADER_PATH, "FastModel"), (VISION_PATH, "FastBaseModel")):
+ method = _class_method(ast.parse(_source(path)), class_name, "from_pretrained")
+ assert _assigns_name(method, "_text_key_mapping", _from_apply), class_name
+ assert _calls_function(method, "_drop_text_only_key_mapping"), class_name
+
+
def _module_function(tree, name):
for node in tree.body:
if isinstance(node, ast.FunctionDef) and node.name == name:
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 87921d74bdd..3ebbb240780 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -1715,6 +1715,7 @@ def _apply_text_only_key_mapping(kwargs, parent_config, text_config):
):
_TEXT_ONLY_PARENT_MODEL_TYPES[text_model_type] = parent_model_type
_install_text_only_conversion_carry()
+ return mapping
def _cast_text_only_prequantized_params(model, dtype):
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 1c8c56d7985..456457165d4 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -2517,7 +2517,9 @@ class FastModel(FastBaseModel):
"Use FastVisionModel for multimodal inputs."
)
# Remap VLM text weights (tf >= 5) while model_config is still the parent (#5816).
- _apply_text_only_key_mapping(kwargs, model_config, text_config)
+ _text_key_mapping = _apply_text_only_key_mapping(
+ kwargs, model_config, text_config
+ )
model_config = text_config
is_vlm = False
# model_config is no longer the repo's config, so anything rebuilding it from model_name (the device-map planner) sees a different model.
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 510c752c636..21646b3be8a 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -2574,7 +2574,7 @@ class FastBaseModel:
elif family_decoder:
auto_config = text_config
auto_model = AutoModelForCausalLM
- _apply_text_only_key_mapping(kwargs, parent_config, text_config)
+ _text_key_mapping = _apply_text_only_key_mapping(kwargs, parent_config, text_config)
text_only_decoder = True
elif text_only and auto_model in [
AutoModelForVision2Seq,