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.

Load and train remote-code multimodal wrappers: Phi-4-reasoning-vision in 4-bit and Nemotron-3-Nano-Omni (#11526)

Daniel Hanb53a6d7a4818
diff --git a/tests/test_merged_hub_destination.py b/tests/test_merged_hub_destination.py
index 355bd316769..dbbf05917d9 100644
--- a/tests/test_merged_hub_destination.py
+++ b/tests/test_merged_hub_destination.py
@@ -182,6 +182,7 @@ def saving(monkeypatch, tmp_path):
"_normalize_safe_serialization",
"_is_adapter_save_method",
"_honours_safe_serialization",
+ "_refuse_unsaveable_text_core",
}
nodes = []
for node in tree.body:
diff --git a/tests/test_remote_code_dtype_cast_on_quantized_model.py b/tests/test_remote_code_dtype_cast_on_quantized_model.py
new file mode 100644
index 00000000000..8764596553b
--- /dev/null
+++ b/tests/test_remote_code_dtype_cast_on_quantized_model.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""A remote-code from_pretrained ending in model.to(dtype) must not break a 4-bit load.
+
+Small PreTrainedModel with a fake packed weight, no downloads.
+"""
+
+import pytest
+import torch
+import torch.nn as nn
+
+from transformers import PretrainedConfig, PreTrainedModel
+
+from unsloth.models.vision import (
+ _cast_unquantized_floats,
+ _tolerate_dtype_cast_on_quantized_model,
+)
+
+
+class _Params4bit(nn.Parameter):
+ """The shape of a bitsandbytes packed weight: uint8 storage plus a quant_state."""
+
+ def __new__(cls, data):
+ p = super().__new__(cls, data, requires_grad = False)
+ p.quant_state = object()
+ return p
+
+
+class _Cfg(PretrainedConfig):
+ model_type = "unsloth-test-quantized"
+
+
+class _Model(PreTrainedModel):
+ config_class = _Cfg
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.norm = nn.LayerNorm(4) # plain float parameters
+ self.packed = _Params4bit(torch.zeros(8, dtype = torch.uint8))
+ self.register_buffer("scale", torch.ones(4, dtype = torch.float32))
+
+ def forward(self, x):
+ return self.norm(x)
+
+
+def _quantized_model():
+ m = _Model(_Cfg())
+ from transformers.utils.quantization_config import QuantizationMethod
+
+ m.quantization_method = QuantizationMethod.BITS_AND_BYTES
+ m.is_quantized = True
+ return m
+
+
+def test_transformers_still_refuses_outside_the_context():
+ """The behaviour we are scoping around, on this transformers version."""
+ m = _quantized_model()
+ with pytest.raises(ValueError, match = "cannot cast a bitsandbytes model"):
+ m.to(torch.bfloat16)
+
+
+def test_cast_inside_the_context_moves_only_unquantized_floats():
+ m = _quantized_model()
+ with _tolerate_dtype_cast_on_quantized_model(True):
+ out = m.to(torch.bfloat16)
+ assert out is m
+ assert m.norm.weight.dtype == torch.bfloat16
+ assert m.scale.dtype == torch.bfloat16
+ assert m.packed.dtype == torch.uint8, "the packed weight must never be cast"
+ with pytest.raises(ValueError):
+ m.to(torch.float16)
+
+
+def test_disabled_context_changes_nothing():
+ m = _quantized_model()
+ with _tolerate_dtype_cast_on_quantized_model(False):
+ with pytest.raises(ValueError):
+ m.to(torch.bfloat16)
+
+
+def test_unquantized_model_and_device_moves_pass_through():
+ m = _Model(_Cfg())
+ with _tolerate_dtype_cast_on_quantized_model(True):
+ m.to(torch.bfloat16) # plain model: transformers' own path
+ assert m.norm.weight.dtype == torch.bfloat16
+ q = _quantized_model()
+ q.to("cpu") # device only: untouched, no error
+ q.to(device = "cpu", dtype = torch.bfloat16) # both: cast floats, then move
+ assert q.norm.weight.dtype == torch.bfloat16
+ assert q.packed.dtype == torch.uint8
+
+
+def test_cast_helper_skips_every_quantized_flavour():
+ m = _Model(_Cfg())
+ m.int8 = nn.Parameter(torch.zeros(2, dtype = torch.int8), requires_grad = False)
+ m.int8.SCB = torch.ones(1)
+ _cast_unquantized_floats(m, torch.bfloat16)
+ assert m.packed.dtype == torch.uint8 and m.int8.dtype == torch.int8
+ assert m.norm.bias.dtype == torch.bfloat16
diff --git a/tests/test_remote_code_training_gates.py b/tests/test_remote_code_training_gates.py
new file mode 100644
index 00000000000..a25a5d4aa6c
--- /dev/null
+++ b/tests/test_remote_code_training_gates.py
@@ -0,0 +1,498 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Gates that let a remote-code multimodal model reach its first training step:
+padding-free off for a fixed-signature forward, gradient checkpointing inherited by
+a wrapper, and text training through the wrapped language model. No downloads.
+"""
+
+import os
+
+import pytest
+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py
+import torch
+import torch.nn as nn
+from transformers import PretrainedConfig, PreTrainedModel
+
+from unsloth.trainer import _forward_accepts_packing_kwargs
+from unsloth.models.vision import _inherit_gradient_checkpointing_support
+
+
+class _Fixed(nn.Module):
+ """The Phi-4 shape: named arguments only."""
+
+ def forward(
+ self,
+ input_ids = None,
+ attention_mask = None,
+ labels = None,
+ ):
+ return input_ids
+
+
+class _Kwargs(nn.Module):
+ def forward(
+ self,
+ input_ids = None,
+ **kwargs,
+ ):
+ return input_ids
+
+
+class _Explicit(nn.Module):
+ def forward(
+ self,
+ input_ids = None,
+ packed_seq_lengths = None,
+ ):
+ return input_ids
+
+
+class _PeftLike(nn.Module):
+ """PEFT forwards every keyword to the wrapped model."""
+
+ def __init__(self, inner):
+ super().__init__()
+ self.inner = inner
+ self.peft_config = {"default": None}
+
+ def get_base_model(self):
+ return self.inner
+
+ def forward(self, *args, **kwargs):
+ return self.inner(*args, **kwargs)
+
+
+def test_fixed_signature_cannot_take_packed_seq_lengths():
+ """Without the gate this model was made padding-free."""
+ assert _forward_accepts_packing_kwargs(_Fixed()) is False
+
+
+def test_kwargs_and_explicit_parameter_can():
+ assert _forward_accepts_packing_kwargs(_Kwargs()) is True
+ assert _forward_accepts_packing_kwargs(_Explicit()) is True
+
+
+def test_peft_wrapper_is_looked_through():
+ assert _forward_accepts_packing_kwargs(_PeftLike(_Fixed())) is False
+ assert _forward_accepts_packing_kwargs(_PeftLike(_Kwargs())) is True
+
+
+def test_unknown_shapes_leave_the_decision_alone():
+ assert _forward_accepts_packing_kwargs(None) is True
+ assert _forward_accepts_packing_kwargs("unsloth/Qwen3-0.6B") is True
+ assert _forward_accepts_packing_kwargs(object()) is True
+
+
+class _Cfg(PretrainedConfig):
+ model_type = "unsloth-test-gc-wrapper"
+
+
+class _Layer(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(4, 4)
+ self.gradient_checkpointing = False
+
+ def forward(self, x):
+ return self.linear(x)
+
+
+class _CausalLM(PreTrainedModel):
+ config_class = _Cfg
+ supports_gradient_checkpointing = True
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.embed_tokens = nn.Embedding(8, 4)
+ self.layers = nn.ModuleList([_Layer(), _Layer()])
+ self.lm_head = nn.Linear(4, 8, bias = False)
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def forward(
+ self,
+ input_ids = None,
+ **kwargs,
+ ):
+ x = self.embed_tokens(input_ids)
+ for layer in self.layers:
+ x = layer(x)
+ return self.lm_head(x)
+
+
+class _Wrapper(PreTrainedModel):
+ """The Nemotron-Omni shape: transformers' default False around a model that supports it."""
+
+ config_class = _Cfg
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.language_model = _CausalLM(config)
+ self.vision_model = nn.Linear(4, 4)
+
+ def get_input_embeddings(self):
+ return self.language_model.embed_tokens
+
+ def forward(
+ self,
+ input_ids = None,
+ **kwargs,
+ ):
+ return self.language_model(input_ids = input_ids)
+
+
+def test_wrapper_refuses_gradient_checkpointing_on_its_own():
+ """The precondition, on this transformers version."""
+ model = _Wrapper(_Cfg())
+ assert model.supports_gradient_checkpointing is False
+ with pytest.raises(ValueError, match = "does not support gradient checkpointing"):
+ model.gradient_checkpointing_enable()
+
+
+def test_wrapper_inherits_support_and_every_layer_is_switched_on():
+ model = _Wrapper(_Cfg())
+ assert _inherit_gradient_checkpointing_support(model) is True
+ assert model.supports_gradient_checkpointing is True
+ model.gradient_checkpointing_enable()
+ assert all(layer.gradient_checkpointing for layer in model.language_model.layers)
+ # the class default is untouched: a fresh wrapper starts from False again
+ assert _Wrapper.supports_gradient_checkpointing is False
+
+
+def test_models_that_already_answer_are_left_alone():
+ model = _CausalLM(_Cfg())
+ assert _inherit_gradient_checkpointing_support(model) is False
+ assert model.supports_gradient_checkpointing is True
+
+
+def test_wrapper_without_a_supporting_submodel_stays_false():
+ class _Plain(PreTrainedModel):
+ config_class = _Cfg
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.encoder = nn.Linear(4, 4)
+
+ model = _Plain(_Cfg())
+ assert _inherit_gradient_checkpointing_support(model) is False
+ assert model.supports_gradient_checkpointing is False
+
+
+from unsloth.models.vision import _text_trainable_core, _required_non_text_inputs
+
+
+class _OmniWrapper(PreTrainedModel):
+ """The Nemotron-Omni shape: pixel_values has no default."""
+
+ config_class = _Cfg
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.language_model = _CausalLM(config)
+ self.vision_model = nn.Linear(4, 4)
+ self.mlp1 = nn.Linear(4, 4)
+
+ def forward(
+ self,
+ pixel_values,
+ input_ids = None,
+ attention_mask = None,
+ image_flags = None,
+ labels = None,
+ ):
+ return self.language_model(input_ids = input_ids)
+
+
+class _VlmWrapper(_OmniWrapper):
+ """Every transformers VLM: image inputs default to None, so a text batch is fine."""
+
+ def forward(
+ self,
+ input_ids = None,
+ pixel_values = None,
+ attention_mask = None,
+ labels = None,
+ ):
+ return self.language_model(input_ids = input_ids)
+
+
+def test_required_non_text_inputs_are_listed():
+ assert _required_non_text_inputs(_OmniWrapper.forward) == ["pixel_values"]
+ assert _required_non_text_inputs(_VlmWrapper.forward) == []
+ assert _required_non_text_inputs(_CausalLM.forward) == []
+
+
+def test_omni_wrapper_trains_its_language_model():
+ """Without the unwrap the wrapper was trained as is."""
+ model = _OmniWrapper(_Cfg())
+ core = _text_trainable_core(model)
+ assert isinstance(core, _CausalLM)
+ assert core._unsloth_composed_parent == "_OmniWrapper"
+ assert not hasattr(model, "vision_model") and not hasattr(model, "mlp1")
+ core(input_ids = torch.tensor([[1, 2, 3]]))
+
+
+def test_vlm_wrapper_and_plain_causal_lm_are_left_alone():
+ vlm = _VlmWrapper(_Cfg())
+ assert _text_trainable_core(vlm) is vlm
+ assert hasattr(vlm, "vision_model")
+ lm = _CausalLM(_Cfg())
+ assert _text_trainable_core(lm) is lm
+
+
+def test_ambiguous_wrapper_is_left_alone():
+ class _Two(_OmniWrapper):
+ def __init__(self, config):
+ super().__init__(config)
+ self.talker = _CausalLM(config)
+ self.listener = _CausalLM(config)
+ del self.language_model
+
+ model = _Two(_Cfg())
+ assert _text_trainable_core(model) is model
+
+
+def test_multimodal_intent_keeps_the_wrapper(capsys):
+ """Without text_only the wrapper is kept and the hint names text_only = True."""
+ model = _OmniWrapper(_Cfg())
+ assert _text_trainable_core(model, text_intent = False) is model
+ assert hasattr(model, "vision_model")
+ out = capsys.readouterr().out
+ assert "pixel_values" in out and "text_only = True" in out
+ # A wrapper that can take a text batch prints nothing either way.
+ vlm = _VlmWrapper(_Cfg())
+ assert _text_trainable_core(vlm, text_intent = False) is vlm
+ assert capsys.readouterr().out == ""
+
+
+def test_opt_out_env_keeps_the_wrapper(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_KEEP_COMPOSED_WRAPPER", "1")
+ model = _OmniWrapper(_Cfg())
+ assert _text_trainable_core(model) is model
+ assert hasattr(model, "vision_model")
+
+
+def test_core_carries_the_wrapper_loader_state():
+ """The core must carry the wrapper's bitsandbytes flags and device map."""
+ model = _OmniWrapper(_Cfg())
+ model.is_loaded_in_4bit = True
+ model.is_quantized = True
+ model.quantization_method = "bitsandbytes"
+ model.hf_quantizer = object()
+ model.hf_device_map = {
+ "language_model.embed_tokens": 0,
+ "language_model.layers.0": 0,
+ "language_model.layers.1": 1,
+ "language_model.lm_head": 1,
+ "vision_model": 0,
+ "mlp1": 0,
+ }
+ model.config.quantization_config = {"quant_method": "bitsandbytes", "load_in_4bit": True}
+ core = _text_trainable_core(model)
+ assert isinstance(core, _CausalLM)
+ assert core.is_loaded_in_4bit is True
+ assert core.is_quantized is True
+ assert core.quantization_method == "bitsandbytes"
+ assert core.hf_quantizer is model.hf_quantizer
+ assert core.hf_device_map == {"embed_tokens": 0, "layers.0": 0, "layers.1": 1, "lm_head": 1}
+ assert core.config.quantization_config == model.config.quantization_config
+
+
+def test_core_inherits_the_wrapper_dtype_and_repo_path():
+ """A sub-config with no dtype left bnb's compute dtype None (backward crashed), and no path broke adapter reloads."""
+ model = _OmniWrapper(_Cfg())
+ model.language_model.config = _Cfg()
+ model.language_model.config.dtype = None
+ model.config.dtype = torch.bfloat16
+ model.config._name_or_path = "org/omni-repo"
+ core = _text_trainable_core(model)
+ assert core.config.dtype == torch.bfloat16
+ assert core.config._name_or_path == "org/omni-repo"
+ assert core.name_or_path == "org/omni-repo"
+
+
+def test_merged_save_of_a_text_core_is_refused(tmp_path):
+ """The merge re-reads the wrapper-layout shards: it wrote an unmerged or unloadable checkpoint."""
+ from unsloth.save import unsloth_generic_save
+
+ from peft import LoraConfig, get_peft_model
+
+ core = _text_trainable_core(_OmniWrapper(_Cfg()))
+ peft_model = get_peft_model(core, LoraConfig(r = 2, target_modules = ["lm_head"]))
+ with pytest.raises(NotImplementedError, match = "text_only = True"):
+ unsloth_generic_save(peft_model, None, str(tmp_path), save_method = "merged_16bit")
+
+
+def test_full_finetuned_text_core_saves_its_own_weights(tmp_path):
+ """No adapter to merge: the core writes its resident state_dict, which the refusal used to block."""
+ from unsloth.save import unsloth_generic_save
+
+ core = _text_trainable_core(_OmniWrapper(_Cfg()))
+ unsloth_generic_save(core, None, str(tmp_path), save_method = "merged_16bit")
+ assert any(name.endswith(".safetensors") for name in os.listdir(tmp_path))
+
+
+def test_core_without_loader_state_gets_none_invented():
+ model = _OmniWrapper(_Cfg())
+ core = _text_trainable_core(model)
+ assert "is_loaded_in_4bit" not in vars(core)
+ assert getattr(core, "hf_device_map", None) is None
+
+
[email protected](not has_real_cuda(), reason = "bitsandbytes 4-bit needs a GPU")
+def test_peft_dispatches_the_4bit_lora_layer_on_the_core():
+ """Without the flags PEFT wraps a Linear4bit in the plain lora.Linear."""
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
+ from peft import LoraConfig, get_peft_model
+ import peft.tuners.lora.bnb as lora_bnb
+
+ inner = AutoModelForCausalLM.from_pretrained(
+ "unsloth/Llama-3.2-1B-Instruct-bnb-4bit",
+ device_map = {"": 0},
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit = True, bnb_4bit_compute_dtype = torch.bfloat16
+ ),
+ )
+
+ class _Composed(_OmniWrapper):
+ def __init__(self, config):
+ PreTrainedModel.__init__(self, config)
+ self.language_model = inner
+ self.vision_model = nn.Linear(4, 4)
+
+ wrapper = _Composed(_Cfg())
+ for attribute in ("is_loaded_in_4bit", "is_quantized", "quantization_method", "hf_quantizer"):
+ setattr(wrapper, attribute, vars(inner).pop(attribute))
+ core = _text_trainable_core(wrapper)
+ assert core is inner
+ peft_model = get_peft_model(core, LoraConfig(r = 8, target_modules = ["q_proj"]))
+ layer = peft_model.base_model.model.model.layers[0].self_attn.q_proj
+ assert isinstance(layer, lora_bnb.Linear4bit), type(layer)
+
+
+def test_model_built_on_gradient_checkpointing_layer_is_recognised():
+ from transformers.modeling_layers import GradientCheckpointingLayer
+
+ class _Block(GradientCheckpointingLayer):
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(4, 4)
+
+ def forward(self, x):
+ return self.linear(x)
+
+ class _RemoteCausalLM(PreTrainedModel):
+ """The NemotronHForCausalLM shape: blocks checkpoint, the class says False."""
+
+ config_class = _Cfg
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.embed_tokens = nn.Embedding(8, 4)
+ self.layers = nn.ModuleList([_Block(), _Block()])
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ model = _RemoteCausalLM(_Cfg())
+ assert model.supports_gradient_checkpointing is False
+ assert _inherit_gradient_checkpointing_support(model) is True
+ model.gradient_checkpointing_enable()
+ assert all(layer.gradient_checkpointing for layer in model.layers)
+
+
+def test_the_loader_carries_the_callers_text_intent_past_its_own_normalisation():
+ """loader.py passes the caller's own text_only as text_intent, not its normalised value."""
+ import inspect
+ from unsloth.models import loader, vision
+
+ assert "text_intent" in inspect.signature(vision.FastBaseModel.from_pretrained).parameters
+ source = inspect.getsource(loader.FastModel.from_pretrained)
+ assert "text_intent = bool(text_only)" in source
+ assert "text_only = load_text_only" in source
+
+
+def test_standard_tokenizer_fields_count_as_text_inputs():
+ """token_type_ids is supplied by the Trainer, so it is no reason to unwrap."""
+ from unsloth.models.vision import _TEXT_BATCH_KEYS
+ assert "token_type_ids" in _TEXT_BATCH_KEYS
+
+
+def test_a_required_cache_control_is_a_missing_text_input():
+ """A required cache_position is not supplied by the collator; input_ids is."""
+ from unsloth.models.vision import _required_non_text_inputs
+
+ def needs_cache(
+ self,
+ input_ids,
+ attention_mask,
+ cache_position,
+ labels = None,
+ ):
+ pass
+
+ def plain(
+ self,
+ input_ids,
+ attention_mask,
+ labels = None,
+ cache_position = None,
+ ):
+ pass
+
+ assert _required_non_text_inputs(needs_cache) == ["cache_position"]
+ assert _required_non_text_inputs(plain) == []
+
+
+def test_non_bitsandbytes_quantizers_keep_their_own_dtype_handling(monkeypatch):
+ """GPTQ / HQQ / Quark refuse or special-case dtype casts; the shim must not take them over."""
+ import unsloth.models.vision as vision
+
+ called = []
+ monkeypatch.setattr(vision, "_cast_unquantized_floats", lambda m, d: called.append(d))
+ model = _CausalLM(_Cfg())
+ model.quantization_method = "gptq"
+ with vision._tolerate_dtype_cast_on_quantized_model(True):
+ try:
+ model.to(torch.bfloat16)
+ except Exception:
+ pass
+ assert called == []
+ model.quantization_method = "bitsandbytes"
+ with vision._tolerate_dtype_cast_on_quantized_model(True):
+ model.to(torch.bfloat16)
+ assert called == [torch.bfloat16]
+
+
+def test_core_keeps_the_wrapper_generation_config():
+ """generation_config.json lands on the wrapper; the child only had config defaults."""
+ model = _OmniWrapper(_Cfg())
+ from transformers import GenerationConfig
+
+ model.generation_config = GenerationConfig(eos_token_id = [7, 8])
+ core = _text_trainable_core(model)
+ assert core.generation_config.eos_token_id == [7, 8]
+
+
[email protected]("spelling", ["LoRA", "lora ", "LORA"])
+def test_adapter_save_spellings_of_a_text_core_are_not_refused(spelling, tmp_path):
+ from unsloth.save import unsloth_generic_save
+
+ core = _text_trainable_core(_OmniWrapper(_Cfg()))
+ try:
+ unsloth_generic_save(core, None, str(tmp_path), save_method = spelling)
+ except NotImplementedError as error:
+ pytest.fail(f"adapter save refused: {error}")
+ except Exception:
+ pass
+
+
+def test_full_finetuned_remote_child_core_is_refused(tmp_path):
+ """A remote-code child class is saved without auto_map or its modeling file: nothing could reload it."""
+ from unsloth.save import unsloth_generic_save
+
+ core = _text_trainable_core(_OmniWrapper(_Cfg()))
+ core.__class__ = type(type(core).__name__, (type(core),), {"__module__": "transformers_modules.repo.modeling"})
+ with pytest.raises(NotImplementedError, match = "remote code"):
+ unsloth_generic_save(core, None, str(tmp_path), save_method = "merged_16bit")
+ assert not os.listdir(tmp_path)
diff --git a/tests/test_tolerated_cast_and_compiled_packing.py b/tests/test_tolerated_cast_and_compiled_packing.py
new file mode 100644
index 00000000000..9255892dd12
--- /dev/null
+++ b/tests/test_tolerated_cast_and_compiled_packing.py
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Unquantized casts inside the tolerated load, and padding-free on compiled models."""
+
+import torch
+import torch.nn as nn
+import pytest
+
+from transformers import LlamaConfig, LlamaForCausalLM
+from unsloth.models.vision import _tolerate_dtype_cast_on_quantized_model
+from unsloth.trainer import _forward_accepts_packing_kwargs
+
+
+def _tiny():
+ return LlamaForCausalLM(
+ LlamaConfig(
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_hidden_layers = 1,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ vocab_size = 99,
+ )
+ ).to(torch.float32)
+
+
+ "call",
+ [
+ lambda m: m.to(dtype = torch.bfloat16),
+ lambda m: m.to(torch.bfloat16),
+ lambda m: m.to(device = "cpu", dtype = torch.bfloat16),
+ ],
+)
+def test_an_unquantized_cast_inside_the_tolerated_load_is_not_dropped(call):
+ """The context must not swallow a cast on an unquantized model."""
+ model = _tiny()
+ with _tolerate_dtype_cast_on_quantized_model(True):
+ call(model)
+ assert next(model.parameters()).dtype is torch.bfloat16
+
+
+def test_a_compiled_model_keeps_padding_free():
+ """OptimizedModule sets `forward` on the instance, not the class."""
+
+ class Kwargs(nn.Module):
+ def forward(
+ self,
+ input_ids = None,
+ **kwargs,
+ ):
+ return input_ids
+
+ assert _forward_accepts_packing_kwargs(Kwargs()) is True
+ assert _forward_accepts_packing_kwargs(torch.compile(Kwargs())) is True
+
+
+def test_a_fixed_signature_is_still_refused():
+ """The negative control: the Phi-4 shape must still block padding-free."""
+
+ class Fixed(nn.Module):
+ def forward(
+ self,
+ input_ids = None,
+ attention_mask = None,
+ ):
+ return input_ids
+
+ assert _forward_accepts_packing_kwargs(Fixed()) is False
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index cf7b640066b..ba4dfd7f51b 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -2084,6 +2084,7 @@ class FastModel(FastBaseModel):
disable_log_stats = disable_log_stats,
load_in_fp8 = load_in_fp8,
text_only = load_text_only,
+ text_intent = bool(text_only),
text_only_decoder = text_only_decoder,
*args,
**kwargs,
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index b9dc33173bc..cc222675200 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -156,6 +156,7 @@ from transformers import __version__ as transformers_version
import types
import functools
import os
+import copy
import gc
import math
import warnings
@@ -1212,6 +1213,260 @@ def _get_total_transformer_layers(model):
return None
+def _cast_unquantized_floats(model, dtype):
+ """Cast every floating parameter and buffer that is not a quantized weight."""
+ for tensor in list(model.parameters()) + list(model.buffers()):
+ if not tensor.is_floating_point() or tensor.dtype == dtype:
+ continue
+ # bitsandbytes packed weights (Params4bit / Int8Params) must not move.
+ if (
+ hasattr(tensor, "quant_state")
+ or hasattr(tensor, "SCB")
+ or type(tensor).__name__ in ("Params4bit", "Int8Params")
+ ):
+ continue
+ tensor.data = tensor.data.to(dtype)
+ return model
+
+
+def _inherit_gradient_checkpointing_support(model):
+ """Remote-code wrappers (Nemotron-3-Nano-Omni) keep the default False; inherit from submodels."""
+ if getattr(model, "supports_gradient_checkpointing", False):
+ return False
+ if not hasattr(model, "gradient_checkpointing_enable"):
+ return False
+ try:
+ from transformers.modeling_layers import GradientCheckpointingLayer
+ except Exception:
+ GradientCheckpointingLayer = ()
+ for name, module in model.named_modules():
+ if module is model or not name:
+ continue
+ if (
+ getattr(module, "supports_gradient_checkpointing", False)
+ and hasattr(module, "gradient_checkpointing_enable")
+ ) or (GradientCheckpointingLayer and isinstance(module, GradientCheckpointingLayer)):
+ model.supports_gradient_checkpointing = True
+ logger.info(
+ f"Unsloth: {type(model).__name__} inherits gradient checkpointing support from {name}."
+ )
+ return True
+ return False
+
+
+_TEXT_BATCH_KEYS = frozenset(
+ (
+ "input_ids",
+ "inputs_embeds",
+ "attention_mask",
+ "token_type_ids",
+ "labels",
+ "position_ids",
+ "past_key_values",
+ "use_cache",
+ "output_attentions",
+ "output_hidden_states",
+ "return_dict",
+ "cache_position",
+ "logits_to_keep",
+ "num_logits_to_keep",
+ )
+)
+
+
+# What a text collator puts in a batch; required control arguments (cache_position, ...) are not.
+_COLLATOR_SUPPLIED_KEYS = frozenset(
+ ("input_ids", "attention_mask", "labels", "token_type_ids", "position_ids")
+)
+
+
+def _required_non_text_inputs(forward):
+ try:
+ parameters = inspect.signature(forward).parameters
+ except (TypeError, ValueError):
+ return []
+ return [
+ name
+ for name, p in parameters.items()
+ if name != "self"
+ and p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
+ and p.default is inspect.Parameter.empty
+ and name not in _COLLATOR_SUPPLIED_KEYS
+ ]
+
+
+def _text_trainable_core(model, text_intent = True):
+ """Nemotron-3-Nano-Omni's forward requires `pixel_values`: with text_only, train the one text child instead."""
+ if os.environ.get("UNSLOTH_KEEP_COMPOSED_WRAPPER", "0") == "1":
+ return model
+ forward = getattr(type(model), "forward", None)
+ if forward is None or forward is torch.nn.Module.forward:
+ return model
+ required = _required_non_text_inputs(forward)
+ if not required:
+ return model
+ if not text_intent:
+ print(
+ f"Unsloth: `{type(model).__name__}.forward` requires {', '.join(required)}, so it "
+ "trains on multimodal batches only. Pass `text_only = True` to from_pretrained to "
+ "train its language model on text batches instead."
+ )
+ return model
+ try:
+ from transformers import PreTrainedModel
+ except Exception:
+ return model
+ cores = []
+ for name, child in model.named_children():
+ if not isinstance(child, PreTrainedModel):
+ continue
+ child_forward = getattr(type(child), "forward", None)
+ if child_forward is None or child_forward is torch.nn.Module.forward:
+ continue
+ if _required_non_text_inputs(child_forward):
+ continue
+ try:
+ has_embeddings = (
+ child.get_input_embeddings() is not None
+ and child.get_output_embeddings() is not None
+ )
+ except Exception:
+ has_embeddings = False
+ if has_embeddings:
+ cores.append((name, child))
+ preferred = [core for core in cores if core[0] in ("language_model", "thinker")]
+ if len(preferred) == 1:
+ cores = preferred
+ if len(cores) != 1:
+ return model
+ name, core = cores[0]
+ dropped = [child_name for child_name, _ in model.named_children() if child_name != name]
+ for child_name in dropped:
+ delattr(model, child_name)
+ gc.collect()
+ clean_gpu_cache()
+ print(
+ f"Unsloth: `{type(model).__name__}.forward` requires {', '.join(required)}, which a text "
+ f"batch does not carry, so training uses its `{name}` (`{type(core).__name__}`)."
+ + (f" Dropped {', '.join(dropped)}: not used by text training." if dropped else "")
+ + " Saving writes a checkpoint of that module."
+ )
+ core._unsloth_composed_parent = type(model).__name__
+ _carry_loader_state_to_core(model, core, name)
+ return core
+
+
+_LOADER_STATE_ATTRIBUTES = (
+ "is_loaded_in_4bit",
+ "is_loaded_in_8bit",
+ "is_4bit_serializable",
+ "is_8bit_serializable",
+ "is_quantized",
+ "quantization_method",
+ "hf_quantizer",
+ "_is_quantized_training_enabled",
+)
+
+
+def _carry_loader_state_to_core(model, core, name):
+ """PEFT reads `is_loaded_in_4bit` to choose `lora.bnb.Linear4bit` over `lora.Linear`."""
+ for attribute in _LOADER_STATE_ATTRIBUTES:
+ if attribute in vars(core):
+ continue
+ if attribute in vars(model):
+ try:
+ setattr(core, attribute, vars(model)[attribute])
+ except Exception:
+ pass
+ device_map = getattr(model, "hf_device_map", None)
+ if isinstance(device_map, dict) and getattr(core, "hf_device_map", None) is None:
+ prefix = name + "."
+ carried = {}
+ for key, device in device_map.items():
+ if key == "" or key == name:
+ carried[""] = device
+ elif key.startswith(prefix):
+ carried[key[len(prefix) :]] = device
+ if carried:
+ core.hf_device_map = carried
+ wrapper_config = getattr(model, "config", None)
+ core_config = getattr(core, "config", None)
+ # A sub-config without its own dtype leaves correct_dtype None, so bnb quant_state.dtype becomes None.
+ wrapper_dtype = getattr(wrapper_config, "dtype", None)
+ # A child built in __init__ has no _name_or_path: adapter_config and merged saves need the repo.
+ wrapper_path = getattr(wrapper_config, "_name_or_path", "") or getattr(
+ model, "name_or_path", ""
+ )
+ if core_config is not None and wrapper_path and not getattr(core_config, "_name_or_path", ""):
+ core_config._name_or_path = wrapper_path
+ try:
+ core.name_or_path = wrapper_path
+ except Exception:
+ pass
+ if (
+ core_config is not None
+ and wrapper_dtype is not None
+ and getattr(core_config, "dtype", None) is None
+ ):
+ try:
+ core_config.dtype = wrapper_dtype
+ except Exception:
+ pass
+ # generation_config.json is loaded onto the wrapper only; the child has config defaults (EOS etc).
+ wrapper_generation_config = getattr(model, "generation_config", None)
+ if wrapper_generation_config is not None:
+ try:
+ core.generation_config = copy.deepcopy(wrapper_generation_config)
+ except Exception:
+ pass
+ quantization_config = getattr(wrapper_config, "quantization_config", None)
+ if (
+ quantization_config is not None
+ and core_config is not None
+ and getattr(core_config, "quantization_config", None) is None
+ ):
+ try:
+ core_config.quantization_config = quantization_config
+ except Exception:
+ pass
+
+
+def _tolerate_dtype_cast_on_quantized_model(enabled):
+ """Phi-4-reasoning-vision calls `model.to(dtype)`, which transformers refuses on bitsandbytes models."""
+ if not enabled:
+ yield
+ return
+ from transformers.modeling_utils import PreTrainedModel
+
+ original_to = PreTrainedModel.to
+
+ def to(self, *args, **kwargs):
+ # bitsandbytes only: GPTQ / HQQ / Quark keep their own dtype handling.
+ quantized = getattr(self, "quantization_method", None) == "bitsandbytes"
+ dtype = kwargs.get("dtype", None)
+ rest = []
+ for arg in args:
+ if isinstance(arg, torch.dtype) and dtype is None:
+ dtype = arg
+ else:
+ rest.append(arg)
+ if not quantized or dtype is None:
+ # Pass through unchanged; `dtype` is read with .get, not popped, so the cast is kept.
+ return original_to(self, *args, **kwargs)
+ kwargs.pop("dtype", None)
+ _cast_unquantized_floats(self, dtype)
+ if rest or kwargs:
+ return original_to(self, *rest, **kwargs)
+ return self
+
+ PreTrainedModel.to = to
+ try:
+ yield
+ finally:
+ PreTrainedModel.to = original_to
+
+
class FastBaseModel:
@staticmethod
@_offline_aware_load
@@ -1252,6 +1507,8 @@ class FastBaseModel:
# True when auto_config came from the caller. It cannot be inferred here: FastModel pops config out of kwargs before this sees them, so it looks exactly like one we resolved ourselves.
auto_config_from_caller = False,
fix_tokenizer = True,
+ # The caller's text_only before loader.py normalised it; None means same as text_only.
+ text_intent = None,
**kwargs,
):
user_config = kwargs.pop("config", None)
@@ -1765,14 +2022,26 @@ class FastBaseModel:
_cfg_val = kwargs.pop("max_position_embeddings", None)
if _cfg_val is not None:
setattr(model_config, "max_position_embeddings", _cfg_val)
- model = auto_model.from_pretrained(
- model_name,
- config = model_config,
- device_map = device_map,
- token = token,
- trust_remote_code = trust_remote_code,
- **kwargs,
+ with _tolerate_dtype_cast_on_quantized_model(
+ bool(trust_remote_code)
+ and (
+ load_in_4bit
+ or load_in_8bit
+ or kwargs.get("quantization_config") is not None
+ )
+ ):
+ model = auto_model.from_pretrained(
+ model_name,
+ config = model_config,
+ device_map = device_map,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ **kwargs,
+ )
+ model = _text_trainable_core(
+ model, text_intent = bool(text_only) if text_intent is None else bool(text_intent)
)
+ _inherit_gradient_checkpointing_support(model)
warn_if_bitsandbytes_quantized_nothing(
model, kwargs.get("quantization_config", None), model_name
)
diff --git a/unsloth/save.py b/unsloth/save.py
index 636107fd934..ea01a9efbae 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -5458,6 +5458,29 @@ def _push_merged_to_hub_revision(save_kwargs):
return commit
+def _refuse_unsaveable_text_core(model, save_method):
+ """A helper, not inline: unsloth_generic_save forwards its own locals() as keywords."""
+ get_base_model = getattr(model, "get_base_model", None) if isinstance(model, PeftModel) else None
+ core = get_base_model() if callable(get_base_model) else model
+ # A str set by _text_trainable_core; mocks answer any attribute with a truthy stand-in.
+ parent = getattr(core, "_unsloth_composed_parent", None)
+ if isinstance(parent, str) and not _is_adapter_save_method(save_method):
+ if isinstance(model, PeftModel):
+ # The merge re-reads the repo's shards, which hold the wrapper's layout, not this child's.
+ raise NotImplementedError(
+ f"Unsloth: this model is the text core of `{parent}` (loaded with text_only = True), "
+ f"so `{save_method}` would write the wrapper's weights under the text core's config. "
+ 'Save the adapter with `save_method = "lora"` and reload it with `text_only = True` instead.'
+ )
+ if "transformers_modules" in (type(core).__module__ or ""):
+ # A full finetune writes its own weights, but a remote child class gets no auto_map or code copy.
+ raise NotImplementedError(
+ f"Unsloth: this model is the text core of `{parent}` (loaded with text_only = True) "
+ f"and its class `{type(core).__name__}` exists only in the repo's remote code, so a "
+ f"`{save_method}` checkpoint of it could not be reloaded. Load without text_only to save the full model."
+ )
+
+
@_normalize_tied_weights_keys_for_save
@torch.inference_mode
def unsloth_generic_save(
@@ -5492,6 +5515,7 @@ def unsloth_generic_save(
"if you're planning to do multiple saves.\n"
"If you are certain, change `save_method` to `merged_4bit_forced`."
)
+ _refuse_unsaveable_text_core(model, save_method)
# Rebound rather than kept in a new local, because the `locals()` below is forwarded as
# this function's own keywords.