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
Load 4.x-era configs that transformers 5 strict validation rejects (Llama 4 attn_temperature_tuning) (#11836)
Daniel Hanff8e6586a0c3
diff --git a/tests/test_legacy_config_type_coercion.py b/tests/test_legacy_config_type_coercion.pynew file mode 100644index 00000000000..ca6fbbd9e27--- /dev/null+++ b/tests/test_legacy_config_type_coercion.py@@ -0,0 +1,321 @@+# SPDX-License-Identifier: AGPL-3.0-only+# 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.+"""Llama 4 configs saved on 4.51 (attn_temperature_tuning: 4) must load on transformers 5.4+."""++import json+import logging+import os+import pathlib++import pytest++os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")+transformers = pytest.importorskip("transformers")++import unsloth # noqa: E402,F401 (installs the fix, as a user's import would)+from packaging.version import Version # noqa: E402++TRANSFORMERS_5 = Version(transformers.__version__) >= Version("5.0.0")+++def _strict_configs():+ from transformers.configuration_utils import PretrainedConfig+ return isinstance(getattr(PretrainedConfig, "__validators__", None), dict)+++needs_strict = pytest.mark.skipif(+ not (TRANSFORMERS_5 and _strict_configs()),+ reason = "configs are not @strict dataclasses on this transformers (4.x, 5.0 to 5.3)",+)+++def _llama4_config_dict(attn_temperature_tuning = 4):+ return {+ "architectures": ["Llama4ForConditionalGeneration"],+ "model_type": "llama4",+ "boi_token_index": 200080,+ "eoi_token_index": 200081,+ "image_token_index": 200092,+ "tie_word_embeddings": False,+ "transformers_version": "4.51.0",+ "text_config": {+ "model_type": "llama4_text",+ "attn_temperature_tuning": attn_temperature_tuning,+ "attention_chunk_size": 64,+ "floor_scale": 8192,+ "attn_scale": 0.1,+ "hidden_size": 64,+ "head_dim": 16,+ "intermediate_size": 64,+ "intermediate_size_mlp": 128,+ "num_attention_heads": 4,+ "num_key_value_heads": 2,+ "num_hidden_layers": 2,+ "num_local_experts": 2,+ "num_experts_per_tok": 1,+ "interleave_moe_layer_step": 1,+ "vocab_size": 256,+ "max_position_embeddings": 256,+ "rope_theta": 500000.0,+ "rope_scaling": {+ "rope_type": "llama3",+ "factor": 8.0,+ "high_freq_factor": 4.0,+ "low_freq_factor": 1.0,+ "original_max_position_embeddings": 64,+ },+ "use_qk_norm": True,+ "no_rope_layers": [],+ },+ "vision_config": {+ "model_type": "llama4_vision_model",+ "hidden_size": 32,+ "intermediate_size": 64,+ "num_attention_heads": 2,+ "num_hidden_layers": 1,+ "image_size": 28,+ "patch_size": 14,+ "vision_output_dim": 32,+ "projector_input_dim": 32,+ "projector_output_dim": 32,+ },+ }+++def _write(tmp_path, config):+ (tmp_path / "config.json").write_text(json.dumps(config), encoding = "utf-8")+ return str(tmp_path)+++def test_llama4_4x_config_loads_through_autoconfig(tmp_path):+ from transformers import AutoConfig++ config = AutoConfig.from_pretrained(_write(tmp_path, _llama4_config_dict(4)))+ value = config.text_config.attn_temperature_tuning+ if TRANSFORMERS_5 and _strict_configs():+ assert value is True+ else:+ # 4.x and 5.0 to 5.3 load the int unchanged; the fix must not touch them.+ assert value == 4 and type(value) is int+++def test_llama4_zero_means_false(tmp_path):+ from transformers import AutoConfig+ config = AutoConfig.from_pretrained(_write(tmp_path, _llama4_config_dict(0)))+ assert not config.text_config.attn_temperature_tuning+++def test_llama4_bool_config_is_untouched(tmp_path):+ from transformers import AutoConfig+ config = AutoConfig.from_pretrained(_write(tmp_path, _llama4_config_dict(True)))+ assert config.text_config.attn_temperature_tuning is True+++@needs_strict+def test_direct_construction_and_save_round_trip(tmp_path):+ from transformers import Llama4Config, Llama4TextConfig++ assert Llama4TextConfig(attn_temperature_tuning = 4).attn_temperature_tuning is True+ config = Llama4Config(text_config = _llama4_config_dict(4)["text_config"])+ assert config.text_config.attn_temperature_tuning is True+ config.save_pretrained(str(tmp_path))+ saved = json.loads((tmp_path / "config.json").read_text(encoding = "utf-8"))+ assert saved["text_config"].get("attn_temperature_tuning", True) is True+++@needs_strict+def test_lossless_conversions():+ from transformers import LlamaConfig++ config = LlamaConfig(+ hidden_size = 64.0, # integral float for int+ initializer_range = 1, # int for float+ mlp_bias = 1, # 0/1 for bool+ tie_word_embeddings = 0,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ )+ assert config.hidden_size == 64 and type(config.hidden_size) is int+ assert config.initializer_range == 1.0 and type(config.initializer_range) is float+ assert config.mlp_bias is True+ assert config.tie_word_embeddings is False+++@needs_strict+def test_values_transformers_accepts_are_not_touched():+ from transformers import LlamaConfig++ # attention_dropout is annotated int | float | None: an int is valid and must stay an int.+ config = LlamaConfig(attention_dropout = 0)+ assert type(config.attention_dropout) is int+++@needs_strict+ "kwargs",+ [+ {"hidden_size": "64"}, # string for a number+ {"hidden_size": 64.5}, # fractional float for int+ {"mlp_bias": 2}, # non 0/1 int for a bool that was never a truthiness int+ {"mlp_bias": "true"}, # string for bool+ {"problem_type": "not_a_problem_type"}, # string outside a Literal+ ],+)+def test_real_errors_still_raise(kwargs):+ from transformers import LlamaConfig+ with pytest.raises(Exception) as info:+ LlamaConfig(**kwargs)+ assert "Validation" in type(info.value).__name__ or isinstance(+ info.value, (TypeError, ValueError)+ )+++@needs_strict+def test_other_int_for_llama4_is_a_real_error_only_outside_the_allowlist():+ from transformers import Llama4TextConfig+ with pytest.raises(Exception):+ Llama4TextConfig(use_qk_norm = 4)+ with pytest.raises(Exception):+ Llama4TextConfig(attn_temperature_tuning = "4")+++@needs_strict+def test_classes_defined_after_import_are_covered():+ from huggingface_hub.dataclasses import strict+ from transformers.configuration_utils import PretrainedConfig++ @strict+ class LateConfig(PretrainedConfig):+ model_type = "unsloth_late_probe"+ flag: bool = False+ sizes: tuple[int, ...] = (1,)+ scale: float = 1.0++ config = LateConfig(flag = 1, sizes = [2, 3], scale = 2)+ assert config.flag is True+ assert config.sizes == (2, 3)+ assert type(config.scale) is float+ with pytest.raises(Exception):+ LateConfig(flag = 3)++ # accept_kwargs=True replaces __init__ without calling the one it wrapped.+ @strict(accept_kwargs = True)+ class LateKwargsConfig(PretrainedConfig):+ model_type = "unsloth_late_kwargs_probe"+ flag: bool = False++ assert LateKwargsConfig(flag = 1).flag is True+ assert LateKwargsConfig(flag = 1, extra = 5).extra == 5+++@needs_strict+def test_hand_written_init_normalises_before_coercion():+ from huggingface_hub.dataclasses import strict+ from transformers.configuration_utils import PretrainedConfig++ @strict+ class TupleConfig(PretrainedConfig):+ model_type = "unsloth_tuple_probe"+ sizes: tuple[int, ...] = (1,)+ flag: bool = False++ class ListOpsConfig(TupleConfig):+ model_type = "unsloth_list_ops_probe"++ def __init__(+ self,+ sizes = None,+ **kwargs,+ ):+ super().__init__(sizes = tuple(sizes + [99]), **kwargs)++ config = ListOpsConfig(sizes = [1, 2], flag = 1)+ assert config.sizes == (1, 2, 99)+ assert config.flag is True+++@needs_strict+def test_coercion_is_logged_once(caplog):+ from transformers import Llama4TextConfig++ import unsloth.import_fixes as import_fixes++ import_fixes._legacy_config_coercions_logged.discard(+ ("Llama4TextConfig", "attn_temperature_tuning", "int")+ )+ with caplog.at_level(logging.WARNING, logger = "unsloth.import_fixes"):+ Llama4TextConfig(attn_temperature_tuning = 4)+ Llama4TextConfig(attn_temperature_tuning = 4)+ hits = [r for r in caplog.records if "attn_temperature_tuning" in r.getMessage()]+ assert len(hits) == 1+++@needs_strict+def test_fix_is_idempotent_and_original_reachable():+ from transformers import LlamaConfig+ from transformers.configuration_utils import PretrainedConfig++ from unsloth.import_fixes import _legacy_config_wrappers, fix_transformers5_legacy_config_types++ LlamaConfig()+ init = LlamaConfig.__dict__["__init__"]+ new = PretrainedConfig.__dict__["__new__"]+ assert init in _legacy_config_wrappers+ fix_transformers5_legacy_config_types()+ assert LlamaConfig.__dict__["__init__"] is init+ assert PretrainedConfig.__dict__["__new__"] is new+ assert getattr(init, "__wrapped__", None) is not None++[email protected](TRANSFORMERS_5, reason = "checks the 4.x no-op")+def test_noop_on_transformers_4():+ from transformers import LlamaConfig+ from transformers.configuration_utils import PretrainedConfig++ from unsloth.import_fixes import fix_transformers5_legacy_config_types++ fix_transformers5_legacy_config_types()+ LlamaConfig()+ assert "__new__" not in PretrainedConfig.__dict__+++def test_the_mlx_branch_installs_the_fix_too():+ source = (pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "__init__.py").read_text(+ encoding = "utf-8"+ )+ mlx_branch = source[source.find("if _IS_MLX:") :]+ assert "fix_transformers5_legacy_config_types" in mlx_branch+++@needs_strict+def test_fields_strict_does_not_validate_are_not_touched():+ """A config that already loads must load byte-identically."""+ from transformers import LlamaConfig+ from transformers.configuration_utils import PretrainedConfig++ class NotStrictConfig(PretrainedConfig):+ model_type = "unsloth_not_strict_probe"+ flag: bool = False+ scale: float = 1.0+ sizes: tuple[int, ...] = (1,)++ config = NotStrictConfig(flag = 1, scale = 2, sizes = [2, 3])+ assert type(config.flag) is int and type(config.scale) is int and type(config.sizes) is list++ class RetypedConfig(LlamaConfig):+ model_type = "unsloth_retyped_probe"+ hidden_size: float = 64.0++ assert type(RetypedConfig(hidden_size = 64).hidden_size) is intdiff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 52fe9ff3391..a9f11e8f328 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -221,6 +221,12 @@ if _IS_MLX:del _fix_remote_rope_scalingexcept Exception:pass+ try:+ from .import_fixes import fix_transformers5_legacy_config_types as _fix_legacy_types+ _fix_legacy_types()+ del _fix_legacy_types+ except Exception:+ passtry:import unsloth_zooexcept ImportError as _e:diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex 28b21c14f2a..9d429386136 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -250,6 +250,7 @@ from .device_type import (from .import_fixes import (fix_transformers5_bare_annotation_configs,+ fix_transformers5_legacy_config_types,fix_transformers5_image_processing_reexports,fix_transformers_composite_prefix_renaming,fix_transformers_fully_masked_rows,@@ -297,6 +298,7 @@ from .import_fixes import (patch_accelerate_recursively_apply,)+fix_transformers5_legacy_config_types()# Must run first: guards PretrainedConfig before vLLM defines its config classes.fix_transformers5_bare_annotation_configs()# Probe-gated: no-ops unless this transformers really hands SDPA a query row that attends to@@ -383,6 +385,7 @@ fix_peft_torchao_missing_tensor_subclass()patch_accelerate_recursively_apply()del fix_transformers5_bare_annotation_configs+del fix_transformers5_legacy_config_typesdel fix_transformers_rope_scaling_drops_thetadel fix_transformers_fp8_modulelist_expertsdel fix_transformers_validate_rope_ignore_keysdiff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex cd9799726b5..e4a8b86c748 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -687,6 +687,240 @@ def fix_transformers5_bare_annotation_configs():logger.info(f"Unsloth: Failed patching PretrainedConfig ({e})")+# 4.51 defaulted attn_temperature_tuning to 4, only ever read for truthiness; 4.52 made it True.+_LEGACY_TRUTHY_BOOL_FIELDS = {+ "attn_temperature_tuning": frozenset({"llama4_text"}),+}+# Identity, not a marker attribute: functools.wraps copies attributes onto whatever wraps us.+_legacy_config_wrappers = set()+_legacy_config_ready = set()+_LEGACY_CONFIG_NOT_COERCED = object()+_legacy_config_field_types = {}+_legacy_config_coercions_logged = set()+++def _legacy_config_accepted_types(annotation):+ import typing+ import types as _types++ if annotation is typing.Any or isinstance(annotation, (str, typing.ForwardRef)):+ return None+ origin = typing.get_origin(annotation)+ if origin is typing.Union or (+ hasattr(_types, "UnionType") and origin is getattr(_types, "UnionType")+ ):+ accepted = set()+ for argument in typing.get_args(annotation):+ inner = _legacy_config_accepted_types(argument)+ if inner is None:+ return None+ accepted |= inner+ return frozenset(accepted)+ if annotation is None or annotation is type(None):+ return frozenset({type(None)})+ if origin is typing.Literal:+ return frozenset({typing.Literal})+ if origin is not None:+ return frozenset({origin})+ if isinstance(annotation, type):+ return frozenset({annotation})+ return None+++def _legacy_config_fields(cls):+ # Read from the class owning __validators__: non-strict dataclass subclasses validate nothing.+ cached = _legacy_config_field_types.get(cls)+ if cached is not None:+ return cached+ import dataclasses++ table = {}+ owner = next(+ (+ k+ for k in getattr(cls, "__mro__", ())+ if isinstance(k.__dict__.get("__validators__"), dict)+ ),+ None,+ )+ try:+ if owner is not None:+ validated = owner.__dict__["__validators__"]+ for field in dataclasses.fields(owner):+ if field.name not in validated:+ continue+ accepted = _legacy_config_accepted_types(field.type)+ if accepted is not None:+ table[field.name] = (field.type, accepted)+ except TypeError:+ pass+ _legacy_config_field_types[cls] = table+ return table+++def _legacy_truthy_bool_field(cls, name):+ model_types = _LEGACY_TRUTHY_BOOL_FIELDS.get(name)+ if not model_types:+ return False+ return any(+ klass.__dict__.get("model_type") in model_types for klass in getattr(cls, "__mro__", ())+ )+++def _legacy_config_coerced_value(cls, name, value, accepted):+ import math++ wants_bool = bool in accepted+ wants_int = int in accepted+ wants_float = float in accepted+ kind = type(value)+ if kind is int:+ if wants_bool and not wants_int and not wants_float:+ if value in (0, 1) or _legacy_truthy_bool_field(cls, name):+ return bool(value)+ return _LEGACY_CONFIG_NOT_COERCED+ if wants_float and not wants_int:+ converted = float(value)+ if math.isfinite(converted) and converted == value:+ return converted+ return _LEGACY_CONFIG_NOT_COERCED+ if kind is float:+ if wants_bool and not wants_int and not wants_float and value in (0.0, 1.0):+ return bool(value)+ if wants_int and not wants_float and math.isfinite(value) and value.is_integer():+ return int(value)+ return _LEGACY_CONFIG_NOT_COERCED+ if kind is list and tuple in accepted and list not in accepted:+ return tuple(value)+ return _LEGACY_CONFIG_NOT_COERCED+++def _coerce_legacy_config_kwargs(cls, kwargs):+ """Convert only values the real validator rejects and accepts once converted."""+ fields = _legacy_config_fields(cls)+ if not fields:+ return kwargs+ try:+ from huggingface_hub.dataclasses import type_validator+ except Exception:+ type_validator = None++ def valid(name, value, annotation):+ if type_validator is None:+ return False+ try:+ type_validator(name, value, annotation)+ return True+ except TypeError:+ return False+ except Exception:+ return True++ updated = None+ for name, value in kwargs.items():+ entry = fields.get(name)+ if entry is None or isinstance(value, (str, dict)) or value is None:+ continue+ annotation, accepted = entry+ converted = _legacy_config_coerced_value(cls, name, value, accepted)+ if converted is _LEGACY_CONFIG_NOT_COERCED:+ continue+ if valid(name, value, annotation):+ continue+ if type_validator is not None and not valid(name, converted, annotation):+ continue+ if updated is None:+ updated = dict(kwargs)+ updated[name] = converted+ key = (cls.__name__, name, type(value).__name__)+ if key not in _legacy_config_coercions_logged:+ _legacy_config_coercions_logged.add(key)+ logger.warning(+ f"Unsloth: `{cls.__name__}.{name}` is {value!r} ({type(value).__name__}), written by "+ f"an older transformers; using {converted!r} since transformers 5 expects "+ f"`{getattr(annotation, '__name__', None) or annotation}`."+ )+ return kwargs if updated is None else updated+++def _legacy_config_init_is_generated(init):+ # dataclass writes __init__ via exec ("<string>"); a hand-written one normalises its own+ # arguments before forwarding, so only the generated init it reaches coerces them.+ depth = 0+ while hasattr(init, "__wrapped__") and depth < 32:+ init, depth = init.__wrapped__, depth + 1+ code = getattr(init, "__code__", None)+ return code is not None and code.co_filename == "<string>"+++def _patch_config_init_for_legacy_types(cls):+ init = cls.__dict__.get("__init__")+ if (+ init is None+ or init in _legacy_config_wrappers+ or not _legacy_config_init_is_generated(init)+ ):+ return++ @functools.wraps(init)+ def __init__(self, *args, **kwargs):+ if kwargs:+ try:+ kwargs = _coerce_legacy_config_kwargs(type(self), kwargs)+ except Exception as e:+ logger.info(f"Unsloth: legacy config type coercion skipped ({e})")+ return init(self, *args, **kwargs)++ _legacy_config_wrappers.add(__init__)+ try:+ cls.__init__ = __init__+ except Exception:+ pass+++def fix_transformers5_legacy_config_types():+ """Coerce 4.x-era config values (e.g. Llama 4 attn_temperature_tuning: 4) that 5.x @strict rejects."""+ try:+ import transformers+ if Version(transformers.__version__) < Version("5.0.0"):+ return+ from transformers.configuration_utils import PretrainedConfig as _BaseConfig+ except Exception as e:+ logger.info(f"Unsloth: Skipping legacy config type fix ({e})")+ return+ if not isinstance(getattr(_BaseConfig, "__validators__", None), dict):+ return+ previous = _BaseConfig.__dict__.get("__new__")+ previous = getattr(previous, "__func__", previous)+ if previous in _legacy_config_wrappers:+ return++ # Patch lazily on first instantiation, once every class decorator has run:+ # @strict(accept_kwargs=True) swaps in an __init__ that never calls the one it replaced.+ def __new__(cls, *args, **kwargs):+ if cls not in _legacy_config_ready:+ for klass in cls.__mro__:+ if isinstance(klass, type) and issubclass(klass, _BaseConfig):+ try:+ _patch_config_init_for_legacy_types(klass)+ except Exception as e:+ logger.info(+ f"Unsloth: legacy config type patch skipped for {klass.__name__} ({e})"+ )+ _legacy_config_ready.add(cls)+ if previous is not None:+ return previous(cls, *args, **kwargs)+ return object.__new__(cls)++ _legacy_config_wrappers.add(__new__)+ try:+ _BaseConfig.__new__ = staticmethod(__new__)+ except Exception as e:+ logger.info(f"Unsloth: Failed patching PretrainedConfig.__new__ ({e})")+ return+ logger.info("Unsloth: Patched transformers config classes to accept legacy 4.x value types.")++# Where the image helpers that `modeling_*.py` files reach for actually live.# Ordered so the image modules win: `resize` exists in image_transforms and is# the one a preprocessor means, and `transformers.utils` is last because it is