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
Accept the transformers 5.0 ignore_keys argument in validate_rope (#11560)
Daniel Hande801746386a
diff --git a/tests/test_validate_rope_ignore_keys.py b/tests/test_validate_rope_ignore_keys.pynew file mode 100644index 00000000000..89e2498601e--- /dev/null+++ b/tests/test_validate_rope_ignore_keys.py@@ -0,0 +1,161 @@+# 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.+import inspect++import pytest++transformers = pytest.importorskip("transformers")+from unsloth.import_fixes import (+ fix_transformers_validate_rope_ignore_keys,+ fix_transformers_is_torch_fx_available,+)+++def _mixin():+ try:+ from transformers.modeling_rope_utils import RotaryEmbeddingConfigMixin+ except Exception:+ pytest.skip("no RotaryEmbeddingConfigMixin on this transformers")+ return RotaryEmbeddingConfigMixin+++def test_validate_rope_accepts_ignore_keys_after_the_fix():+ from transformers import LlamaConfig++ fix_transformers_validate_rope_ignore_keys()+ mixin = _mixin()+ assert "ignore_keys" in inspect.signature(mixin.validate_rope).parameters or getattr(+ mixin.__dict__.get("validate_rope"), "_unsloth_ignore_keys", False+ )+ config = LlamaConfig(+ hidden_size = 8,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ intermediate_size = 8,+ vocab_size = 16,+ )+ config.validate_rope(ignore_keys = {"mscale", "mscale_all_dim"})+ config.validate_rope({"mscale", "mscale_all_dim"})+ config.validate_rope()+++def test_the_fix_is_idempotent_and_keeps_the_original_reachable():+ fix_transformers_validate_rope_ignore_keys()+ mixin = _mixin()+ first = mixin.__dict__["validate_rope"]+ fix_transformers_validate_rope_ignore_keys()+ assert mixin.__dict__["validate_rope"] is first+ original = getattr(first, "__wrapped__", None)+ if original is not None:+ assert "ignore_keys" not in inspect.signature(original).parameters+++def test_the_mlx_branch_installs_the_fix_too():+ import pathlib++ 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_transformers_validate_rope_ignore_keys" in mlx_branch+++def test_is_torch_fx_available_is_importable_from_transformers_utils_after_the_fix():+ fix_transformers_is_torch_fx_available()+ from transformers.utils import is_torch_fx_available+ import transformers.utils.import_utils as import_utils++ assert is_torch_fx_available() == import_utils.is_torch_available()+ assert import_utils.is_torch_fx_available() == import_utils.is_torch_available()+ first = import_utils.is_torch_fx_available+ fix_transformers_is_torch_fx_available()+ assert import_utils.is_torch_fx_available is first+++def test_the_mlx_branch_installs_the_fx_shim_too():+ import pathlib+ source = (pathlib.Path(__file__).resolve().parents[1] / "unsloth" / "__init__.py").read_text(+ encoding = "utf-8"+ )+ assert "fix_transformers_is_torch_fx_available" in source[source.find("if _IS_MLX:") :]+++def test_a_config_with_its_own_validator_accepts_ignore_keys_too():+ fix_transformers_validate_rope_ignore_keys()+ from transformers import Phi3Config++ if not hasattr(Phi3Config, "validate_rope"):+ pytest.skip("this transformers has no validate_rope (4.x)")+ config = Phi3Config(+ hidden_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ intermediate_size = 32,+ vocab_size = 16,+ )+ config.validate_rope(ignore_keys = {"mscale", "mscale_all_dim"})+ if not getattr(_mixin().__dict__.get("validate_rope"), "_unsloth_ignore_keys", False):+ return # 5.0 to 5.3 take ignore_keys natively, so the fix is not installed++ class LaterConfig(Phi3Config):+ model_type = "later_phi3_for_test"++ def validate_rope(self):+ return "own"++ assert LaterConfig.validate_rope(config, ignore_keys = {"x"}) == "own"+++def test_ignore_keys_keep_their_meaning_on_a_validator_without_the_parameter():+ import logging++ from transformers import LlamaConfig++ fix_transformers_validate_rope_ignore_keys()+ mixin = _mixin()+ if not getattr(mixin.__dict__.get("validate_rope"), "_unsloth_ignore_keys", False):+ pytest.skip("this transformers still takes ignore_keys itself")+ config = LlamaConfig(+ hidden_size = 8,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ intermediate_size = 8,+ vocab_size = 16,+ rope_scaling = {"rope_type": "linear", "factor": 2.0, "model_specific_key": 1},+ )+ records = []++ class _Collect(logging.Handler):+ def emit(self, record):+ records.append(record.getMessage())++ handler = _Collect()+ rope_logger = logging.getLogger("transformers.modeling_rope_utils")+ rope_logger.addHandler(handler)+ try:+ before = set(config.ignore_keys_at_rope_validation or ())+ for call in (+ lambda: config.validate_rope(ignore_keys = {"model_specific_key"}),+ lambda: config.validate_rope({"model_specific_key"}),+ ):+ records.clear()+ call()+ assert not [m for m in records if "Unrecognized keys" in m], records+ assert set(config.ignore_keys_at_rope_validation or ()) == before+ records.clear()+ config.validate_rope()+ assert [m for m in records if "Unrecognized keys" in m]+ finally:+ rope_logger.removeHandler(handler)diff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 5c1c15f8f9d..52fe9ff3391 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -180,6 +180,18 @@ if _IS_MLX:del _fix_nf4except Exception:pass+ try:+ from .import_fixes import fix_transformers_validate_rope_ignore_keys as _fix_validate_rope+ _fix_validate_rope()+ del _fix_validate_rope+ except Exception:+ pass+ try:+ from .import_fixes import fix_transformers_is_torch_fx_available as _fix_torch_fx+ _fix_torch_fx()+ del _fix_torch_fx+ except Exception:+ passtry:# Same reason: this branch imports transformers itself further down, so a --no-deps floor miss would# surface here with the same wrong remedy.diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex cc9485736bb..0bc5c090085 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -254,6 +254,7 @@ from .import_fixes import (fix_transformers_composite_prefix_renaming,fix_transformers_fully_masked_rows,fix_transformers_rope_scaling_drops_theta,+ fix_transformers_validate_rope_ignore_keys,fix_transformers_remote_rope_scaling_none,fix_transformers_is_torch_fx_available,fix_xformers_performance_issue,@@ -314,6 +315,7 @@ del check_transformers_prequantized_vlm_quant_state# RoPE base frequency. Ordered here, before any config is built, so the object-style delegation# retry in models/llama.py sees a config that kept its base (#2405).fix_transformers_rope_scaling_drops_theta()+fix_transformers_validate_rope_ignore_keys()# Remote code written for 4.x reads plain RoPE as rope_scaling None and imports is_torch_fx_available.fix_transformers_remote_rope_scaling_none()fix_transformers_is_torch_fx_available()@@ -372,6 +374,7 @@ patch_accelerate_recursively_apply()del fix_transformers5_bare_annotation_configsdel fix_transformers_rope_scaling_drops_theta+del fix_transformers_validate_rope_ignore_keysdel fix_transformers_remote_rope_scaling_nonedel fix_transformers_is_torch_fx_availabledel fix_xformers_performance_issuediff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex f60639182e9..27431ce472c 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -2313,6 +2313,149 @@ def _transformers_rope_scaling_assignment_drops_theta():return False+def fix_transformers_is_torch_fx_available():+ """Restore ``is_torch_fx_available`` (removed in 5.0) for 4.x-era remote code."""+ try:+ import transformers.utils as utils+ import transformers.utils.import_utils as import_utils+ except Exception:+ return+ if hasattr(import_utils, "is_torch_fx_available") and hasattr(utils, "is_torch_fx_available"):+ return+ is_torch_available = getattr(import_utils, "is_torch_available", None)+ if is_torch_available is None:+ return++ def is_torch_fx_available():+ return is_torch_available()++ is_torch_fx_available._unsloth_restored = True+ for module in (import_utils, utils):+ if not hasattr(module, "is_torch_fx_available"):+ module.is_torch_fx_available = is_torch_fx_available+ logger.info(+ "Unsloth: Restored transformers `is_torch_fx_available` for remote modeling code written against 4.x."+ )+++_no_own_ignore_keys = object()+++def _validate_rope_accepting_ignore_keys(original):+ if original is None or getattr(original, "_unsloth_ignore_keys", False):+ return None+ try:+ parameters = inspect.signature(original).parameters+ except (TypeError, ValueError):+ return None+ if "ignore_keys" in parameters:+ return None+ # 5.0 was (self, ignore_keys = None): a lone positional arg is ignore_keys only if the validator takes none.+ takes_positional = any(+ p.kind+ in (+ inspect.Parameter.POSITIONAL_ONLY,+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ inspect.Parameter.VAR_POSITIONAL,+ )+ for p in list(parameters.values())[1:]+ )++ @functools.wraps(original)+ def validate_rope(+ self,+ *args,+ ignore_keys = None,+ **kwargs,+ ):+ if len(args) == 1 and not kwargs and not takes_positional:+ if ignore_keys is None:+ ignore_keys = args[0]+ args = ()+ if not ignore_keys:+ return original(self, *args, **kwargs)+ # 5.4 moved ignore_keys onto this attribute; merge them in for this call only.+ own = self.__dict__.get("ignore_keys_at_rope_validation", _no_own_ignore_keys)+ try:+ merged = set(getattr(self, "ignore_keys_at_rope_validation", None) or ()) | set(+ ignore_keys+ )+ self.ignore_keys_at_rope_validation = merged+ except Exception:+ return original(self, *args, **kwargs)+ try:+ return original(self, *args, **kwargs)+ finally:+ if own is _no_own_ignore_keys:+ self.__dict__.pop("ignore_keys_at_rope_validation", None)+ else:+ self.ignore_keys_at_rope_validation = own++ validate_rope._unsloth_ignore_keys = True+ return validate_rope+++def _patch_own_validate_rope(cls):+ wrapped = _validate_rope_accepting_ignore_keys(cls.__dict__.get("validate_rope"))+ if wrapped is not None:+ try:+ cls.validate_rope = wrapped+ except Exception:+ pass+++def fix_transformers_validate_rope_ignore_keys():+ """Accept 5.0-era ``validate_rope(ignore_keys = ...)``, removed in 5.4 (TypeError on load).+ Configs like Phi3Config define their own validator: patch subclasses, hook later/remote ones."""+ try:+ from transformers.modeling_rope_utils import RotaryEmbeddingConfigMixin+ except Exception:+ return+ original = RotaryEmbeddingConfigMixin.__dict__.get("validate_rope")+ try:+ if original is None or "ignore_keys" in inspect.signature(original).parameters:+ return+ except (TypeError, ValueError):+ return+ _patch_own_validate_rope(RotaryEmbeddingConfigMixin)++ try:+ from transformers import PretrainedConfig as _BaseConfig+ except Exception:+ _BaseConfig = None+ if _BaseConfig is not None:+ pending = [_BaseConfig]+ seen = set()+ while pending:+ cls = pending.pop()+ if id(cls) in seen:+ continue+ seen.add(id(cls))+ _patch_own_validate_rope(cls)+ try:+ pending.extend(cls.__subclasses__())+ except Exception:+ pass+ hook = _BaseConfig.__dict__.get("__init_subclass__")+ if not getattr(getattr(hook, "__func__", hook), "_unsloth_ignore_keys_hook", False):+ previous = hook.__func__ if isinstance(hook, classmethod) else None++ def __init_subclass__(cls, **kwargs):+ if previous is not None:+ previous(cls, **kwargs)+ else:+ super(_BaseConfig, cls).__init_subclass__(**kwargs)+ _patch_own_validate_rope(cls)++ __init_subclass__._unsloth_ignore_keys_hook = True+ if previous is not None:+ __init_subclass__.__wrapped__ = previous+ _BaseConfig.__init_subclass__ = classmethod(__init_subclass__)+ logger.info(+ "Unsloth: Patched transformers `validate_rope` to accept the 5.0 `ignore_keys` argument."+ )++_PLAIN_ROPE_KEYS = frozenset({"rope_type", "type", "rope_theta", "partial_rotary_factor"})_ATTRIBUTE_ROPE_KEYS = ("rope_theta", "partial_rotary_factor")_NO_ROPE_ATTRIBUTE = object()@@ -2378,23 +2521,6 @@ def fix_transformers_remote_rope_scaling_none():PretrainedConfig.rope_scaling = property(rope_scaling, prop.fset, prop.fdel, prop.__doc__)-def fix_transformers_is_torch_fx_available():- """Restore ``transformers.utils.import_utils.is_torch_fx_available``, removed in 5.x and- imported at module level by 4.x-era remote code (Ling / BailingMoe, DeepSeek-V3, Kimi-K2).- Same body as 4.57.6; only added when missing."""- try:- import transformers.utils.import_utils as import_utils- except Exception:- return- if hasattr(import_utils, "is_torch_fx_available"):- return-- def is_torch_fx_available():- return import_utils.is_torch_available()-- import_utils.is_torch_fx_available = is_torch_fx_available--def fix_transformers_rope_scaling_drops_theta():"""Stop a replaced ``rope_scaling`` silently unscaling RoPE (issue #2405).