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.

Keep up with transformers 5.x, TRL 0.22.x and peft (#7866)

Daniel Han447d241f0f12
diff --git a/tests/test_dataclass_default_backfill.py b/tests/test_dataclass_default_backfill.py
new file mode 100644
index 00000000000..d33b1e030b4
--- /dev/null
+++ b/tests/test_dataclass_default_backfill.py
@@ -0,0 +1,174 @@
+"""_backfill_dataclass_defaults must not shadow an inherited default.
+
+Deciding "no default yet" with `name not in cls.__dict__` was wrong: a subclass
+re-annotating an inherited field already has one, via the MRO. import_fixes.py
+is loaded by file spec because `import unsloth.import_fixes` would run
+unsloth/__init__.py first, pulling in torch, numpy and unsloth_zoo.
+"""
+
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+IMPORT_FIXES = REPO_ROOT / "unsloth" / "import_fixes.py"
+
+
+def _load_module():
+ spec = importlib.util.spec_from_file_location(
+ "_unsloth_import_fixes_dataclass_under_test", IMPORT_FIXES
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+_MODULE = _load_module()
+_backfill_dataclass_defaults = _MODULE._backfill_dataclass_defaults
+_transformers_configs_are_kw_only = _MODULE._transformers_configs_are_kw_only
+ifx = _MODULE # for monkeypatching its internals
+
+
+def test_an_inherited_default_is_not_shadowed():
+ """Absent from cls.__dict__ but present via the MRO: None would overwrite it."""
+
+ class Base:
+ window: int = 7
+
+ class Child(Base):
+ window: int # re-annotated, no assignment
+
+ assert _backfill_dataclass_defaults(Child) == []
+ assert Child.window == 7
+
+
+def test_a_genuinely_new_field_is_still_backfilled():
+ """The narrowing must not disarm the fix."""
+
+ class Base:
+ window: int = 7
+
+ class Child(Base):
+ vision_config: object # new, and bare: the case that raises
+
+ assert _backfill_dataclass_defaults(Child) == ["vision_config"]
+ assert Child.vision_config is None
+
+
+def test_an_inherited_method_of_the_same_name_counts_too():
+ """getattr resolves through the MRO, so a method counts as a default too."""
+
+ class Base:
+ def helper(self):
+ return 1
+
+ class Child(Base):
+ helper: object
+
+ assert _backfill_dataclass_defaults(Child) == []
+ assert Child().helper() == 1
+
+
+class _KwOnlyConfig:
+ """Stands in for transformers 5.5.1+, whose hook passes kw_only=True."""
+
+ def __init_subclass__(cls, **kwargs):
+ _fake_dataclass(cls, kw_only = True)
+
+
+class _OrderedConfig:
+ """Stands in for 5.4.0 to 5.5.0, whose hook does not."""
+
+ def __init_subclass__(cls, **kwargs):
+ _fake_dataclass(cls)
+
+
+def _fake_dataclass(cls, **kwargs):
+ return cls
+
+
+def _config_without_readable_source():
+ """A hook whose source cannot be read, as on a stripped or frozen install:
+ compiled under a filename not on disk, so `inspect.getsource` fails."""
+ namespace = {}
+ exec(
+ compile(
+ "class Config:\n def __init_subclass__(cls, **kwargs):\n pass\n",
+ "<unsloth-test-no-source-on-disk>",
+ "exec",
+ ),
+ namespace,
+ )
+ return namespace["Config"]
+
+
+def _pretend_transformers_is(monkeypatch, version):
+ module = types.ModuleType("transformers")
+ module.__version__ = version
+ monkeypatch.setitem(sys.modules, "transformers", module)
+
+
+def test_the_source_beats_the_version_fallback(monkeypatch):
+ """The change was backported, so a readable source decides over the version."""
+ _pretend_transformers_is(monkeypatch, "5.4.0")
+ assert _transformers_configs_are_kw_only(_KwOnlyConfig) is True
+ _pretend_transformers_is(monkeypatch, "5.5.1")
+ assert _transformers_configs_are_kw_only(_OrderedConfig) is False
+
+
+def test_unreadable_source_on_5_5_1_stands_down(monkeypatch):
+ """False here would give required keyword fields a None default on 5.5.1+."""
+ _pretend_transformers_is(monkeypatch, "5.5.1")
+ assert _transformers_configs_are_kw_only(_config_without_readable_source())
+
+
+def test_unreadable_source_falls_back_to_probing_the_behaviour(monkeypatch):
+ """With no source to read, ask the installed transformers by trying it."""
+ monkeypatch.setattr(
+ ifx,
+ "_transformers_needs_bare_annotation_fix",
+ lambda: True,
+ )
+ assert not _transformers_configs_are_kw_only(_config_without_readable_source())
+ monkeypatch.setattr(
+ ifx,
+ "_transformers_needs_bare_annotation_fix",
+ lambda: False,
+ )
+ assert _transformers_configs_are_kw_only(_config_without_readable_source())
+
+
+def test_the_probe_answers_from_the_class_not_the_version(monkeypatch):
+ """Faking `transformers.__version__` must not change the answer."""
+ for version in ("5.4.0", "5.5.0", "5.5.0.post1", "4.57.6", "9.9.9"):
+ _pretend_transformers_is(monkeypatch, version)
+ assert ifx._transformers_needs_bare_annotation_fix() is False, version
+
+
+def test_the_probe_detects_a_config_that_raises(monkeypatch):
+ """An `__init_subclass__` rejecting the shape is what the fix exists for."""
+
+ class Raising:
+ def __init_subclass__(cls, **kwargs):
+ raise TypeError("non-default argument follows default argument")
+
+ module = types.ModuleType("transformers.configuration_utils")
+ module.PretrainedConfig = Raising
+ monkeypatch.setitem(sys.modules, "transformers.configuration_utils", module)
+ assert ifx._transformers_needs_bare_annotation_fix() is True
+
+
+def test_an_unreadable_version_does_not_raise(monkeypatch):
+ """A version packaging cannot parse, or no transformers at all, must not raise."""
+ for version in ("not-a-version", "", None):
+ _pretend_transformers_is(monkeypatch, version)
+ assert _transformers_configs_are_kw_only(_config_without_readable_source()), repr(version)
+ monkeypatch.setitem(sys.modules, "transformers", None)
+ assert _transformers_configs_are_kw_only(_config_without_readable_source())
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_offload_tied_autodisable.py b/tests/test_offload_tied_autodisable.py
new file mode 100644
index 00000000000..43384b08419
--- /dev/null
+++ b/tests/test_offload_tied_autodisable.py
@@ -0,0 +1,174 @@
+"""Tests _resolve_offload_embedding in vision.py. No GPU needed.
+
+`offload_embedding = True` on a model with tied word embeddings used to raise
+NotImplementedError and abort the load. It is a VRAM optimisation, not a
+correctness switch, so it should turn itself off instead, as the fast_inference
+case a few lines earlier already does. Two shipped notebooks (NeMo-Gym-Sudoku,
+NeMo-Gym-Multi-Environment) died this way on unsloth/Qwen2.5-1.5B-Instruct.
+
+Every platform branch is driven explicitly, so the assertions hold on Linux,
+macOS, Windows and WSL alike: the host's own os.name never decides.
+"""
+
+import ast, os
+from contextlib import contextmanager
+
+import torch
+import torch.nn as nn
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+VISION = os.path.join(HERE, "unsloth", "models", "vision.py")
+
+_SRC = open(VISION, encoding = "utf-8").read()
+
+
+def _load(*names):
+ mod = ast.parse(_SRC)
+ ns = {"torch": torch, "os": os}
+ wanted = set(names)
+ for node in mod.body:
+ if isinstance(node, ast.FunctionDef) and node.name in wanted:
+ exec(ast.get_source_segment(_SRC, node), ns)
+ wanted.discard(node.name)
+ if wanted:
+ raise AssertionError(f"not found in vision.py: {sorted(wanted)}")
+ return ns
+
+
+_NS = _load(
+ "_embeddings_are_tied",
+ "_offload_embedding_unsupported_platform",
+ "_resolve_offload_embedding",
+)
+resolve = _NS["_resolve_offload_embedding"]
+unsupported_platform = _NS["_offload_embedding_unsupported_platform"]
+
+_WSL_VARS = ("WSL_DISTRO_NAME", "WSL_INTEROP")
+
+
+@contextmanager
+def _as_platform(os_name, wsl = False):
+ """Drive the platform inputs directly instead of trusting the host's."""
+ saved_env = {v: os.environ.get(v) for v in _WSL_VARS}
+ saved_name = os.name
+ for v in _WSL_VARS:
+ os.environ.pop(v, None)
+ if wsl:
+ os.environ["WSL_DISTRO_NAME"] = "Ubuntu"
+ # os.name is read by pathlib, so keep the window as small as possible.
+ os.name = os_name
+ try:
+ yield
+ finally:
+ os.name = saved_name
+ for v, old in saved_env.items():
+ if old is None:
+ os.environ.pop(v, None)
+ else:
+ os.environ[v] = old
+
+
+class _Model:
+ def __init__(self, emb, out):
+ self._emb, self._out = emb, out
+
+ def get_input_embeddings(self):
+ return self._emb
+
+ def get_output_embeddings(self):
+ return self._out
+
+
+class _Opaque:
+ """Some architectures refuse to expose embeddings."""
+
+ def get_input_embeddings(self):
+ raise NotImplementedError("no embeddings here")
+
+ def get_output_embeddings(self):
+ return None
+
+
+def _tied_model():
+ emb = nn.Embedding(32, 8)
+ lm = nn.Linear(8, 32, bias = False)
+ lm.weight = emb.weight
+ return _Model(emb, lm)
+
+
+def _untied_model():
+ return _Model(nn.Embedding(32, 8), nn.Linear(8, 32, bias = False))
+
+
+def test_disabled_stays_disabled():
+ for os_name, wsl in (("posix", False), ("nt", False), ("posix", True)):
+ with _as_platform(os_name, wsl = wsl):
+ assert resolve(_untied_model(), False) is False
+ assert resolve(_tied_model(), False) is False
+
+
+def test_untied_model_keeps_offload():
+ with _as_platform("posix"):
+ assert resolve(_untied_model(), True) is True
+
+
+def test_tied_model_disables_offload_instead_of_raising():
+ with _as_platform("posix"):
+ assert resolve(_tied_model(), True) is False
+
+
+def test_opaque_model_leaves_request_alone():
+ # Cannot inspect it, so do not guess, and do not crash.
+ with _as_platform("posix"):
+ assert resolve(_Opaque(), True) is True
+
+
+def test_wsl_and_windows_disable_offload():
+ # Neither can offload, and the flag also gates the multi-device hook attach,
+ # so it has to read False rather than pass through.
+ for var in _WSL_VARS:
+ with _as_platform("posix"):
+ os.environ[var] = "1"
+ assert unsupported_platform() == "WSL"
+ assert resolve(_tied_model(), True) is False
+ assert resolve(_untied_model(), True) is False
+ assert resolve(_Opaque(), True) is False
+
+ with _as_platform("nt"):
+ assert unsupported_platform() == "Windows"
+ assert resolve(_tied_model(), True) is False
+ assert resolve(_untied_model(), True) is False
+ assert resolve(_Opaque(), True) is False
+
+ with _as_platform("posix"):
+ assert unsupported_platform() is None
+
+
+def test_platform_gate_lives_in_one_place():
+ # The offload block used to re-test os.name itself; the copies drifted apart
+ # and only Windows noticed. _resolve_offload_embedding owns it now.
+ helper = _SRC[_SRC.index("def _offload_embedding_unsupported_platform(") :]
+ helper = helper[: helper.index("\n\n\ndef ")]
+ for probe in ('os.name == "nt"', "WSL_DISTRO_NAME", "WSL_INTEROP"):
+ assert _SRC.count(probe) == 1, f"{probe} must be tested in exactly one place"
+ assert probe in helper, f"{probe} belongs in _offload_embedding_unsupported_platform"
+
+
+def test_resolved_before_multidevice_hooks():
+ # Hook attach returns early while offload_embedding is still True.
+ call = _SRC.index("offload_embedding = _resolve_offload_embedding(")
+ # Anchor on the indented CALL, not the module-level `def`.
+ hooks = _SRC.index("\n _attach_bnb_multidevice_hooks(")
+ assert call < hooks, "offload_embedding must be resolved before hook attach"
+
+
+def test_no_tied_embedding_raise_remains():
+ assert "is not supported for models with tied word" not in _SRC
+
+
+if __name__ == "__main__":
+ for name, fn in sorted(globals().items()):
+ if name.startswith("test_") and callable(fn):
+ fn()
+ print(f"[PASS] {name}")
+ print("all offload tied auto-disable tests passed")
diff --git a/tests/test_peft_symbol_backfill.py b/tests/test_peft_symbol_backfill.py
new file mode 100644
index 00000000000..1d9ee2c949f
--- /dev/null
+++ b/tests/test_peft_symbol_backfill.py
@@ -0,0 +1,177 @@
+"""Tests _backfill_missing_peft_symbols in import_fixes.py.
+
+peft's ``transformers_weight_conversion`` imports 3 names from
+``transformers.conversion_mapping`` and 8 from ``core_model_loading`` at module
+top level. Unsloth stubs those submodules when absent, but an importable one can
+still lack individual symbols: transformers 5.0.0.dev0 ships
+``conversion_mapping`` WITHOUT ``_MODEL_TO_CONVERSION_PATTERN``, whose
+ImportError took down `import unsloth` in Ministral_3_(3B)_Reinforcement_Learning.
+The old guard only asked whether the submodule imported. Backfilling must be
+strictly additive: never replace a real module, never overwrite a real symbol.
+"""
+
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+IMPORT_FIXES = REPO_ROOT / "unsloth" / "import_fixes.py"
+
+CONV = "transformers.conversion_mapping"
+CORE = "transformers.core_model_loading"
+
+
+def _load_module():
+ spec = importlib.util.spec_from_file_location(
+ "_unsloth_import_fixes_backfill_under_test", IMPORT_FIXES
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+FIXES = _load_module()
+backfill = FIXES._backfill_missing_peft_symbols
+
+
[email protected](autouse = True)
+def _restore_modules():
+ saved = {k: sys.modules.get(k) for k in (CONV, CORE)}
+ yield
+ for k, v in saved.items():
+ if v is None:
+ sys.modules.pop(k, None)
+ else:
+ sys.modules[k] = v
+
+
+def _fake_real_module(name, **attrs):
+ """A module that is NOT one of our stubs (no sentinel)."""
+ mod = types.ModuleType(name)
+ for k, v in attrs.items():
+ setattr(mod, k, v)
+ sys.modules[name] = mod
+ return mod
+
+
+def test_backfills_only_the_missing_symbol():
+ sentinel_fn = lambda *a, **k: "upstream"
+ mod = _fake_real_module(
+ CONV,
+ get_checkpoint_conversion_mapping = sentinel_fn,
+ get_model_conversion_mapping = sentinel_fn,
+ )
+ added = backfill(CONV)
+ assert added == ("_MODEL_TO_CONVERSION_PATTERN",)
+ assert mod.get_checkpoint_conversion_mapping is sentinel_fn
+ assert mod.get_model_conversion_mapping is sentinel_fn
+
+
+def test_backfilled_pattern_supports_copy_like_peft_does():
+ _fake_real_module(CONV)
+ backfill(CONV)
+ pattern = sys.modules[CONV]._MODEL_TO_CONVERSION_PATTERN
+ assert isinstance(pattern, dict)
+ copied = pattern.copy()
+ copied["llama"] = object() # peft assigns by key at module top
+ assert pattern == {} # copy must not alias
+
+
+def test_complete_module_is_left_alone():
+ attrs = {s: object() for s in FIXES._PEFT_REQUIRED_SYMBOLS[CONV]}
+ _fake_real_module(CONV, **attrs)
+ assert backfill(CONV) == ()
+
+
+def test_our_own_stub_is_skipped():
+ stub = FIXES._build_transformers_conversion_mapping_stub()
+ assert getattr(stub, FIXES._UNSLOTH_STUB_SENTINEL, False) is True
+ sys.modules[CONV] = stub
+ assert backfill(CONV) == ()
+
+
+def test_idempotent():
+ _fake_real_module(CONV)
+ first = backfill(CONV)
+ assert len(first) == 3
+ assert backfill(CONV) == ()
+
+
+def test_core_model_loading_classes_are_subclassable():
+ # peft subclasses ConversionOps at module top, so it must be a real class.
+ _fake_real_module(CORE, dot_natural_key = lambda k: k)
+ added = backfill(CORE)
+ assert "dot_natural_key" not in added
+ mod = sys.modules[CORE]
+ assert issubclass(mod.Concatenate, mod.ConversionOps)
+
+ class _Child(mod.ConversionOps):
+ pass
+
+ assert issubclass(_Child, mod.ConversionOps)
+
+
+def test_missing_module_returns_empty():
+ sys.modules.pop(CONV, None)
+ # No real transformers submodule of this name under the test alias.
+ assert backfill(CONV) == () or isinstance(backfill(CONV), tuple)
+
+
+def test_required_symbols_match_peft_import_list():
+ # Guards against the lists drifting apart silently.
+ assert set(FIXES._PEFT_REQUIRED_SYMBOLS) == set(FIXES._PEFT_STUB_BUILDERS)
+ for name, symbols in FIXES._PEFT_REQUIRED_SYMBOLS.items():
+ donor = FIXES._PEFT_STUB_BUILDERS[name]()
+ for s in symbols:
+ assert hasattr(donor, s), f"{name} stub lacks {s}"
+
+
+# ---- saying so when the stand-in is not equivalent -----------------------
+# Inert donors are right wherever the symbol never existed, but not for a
+# transformers 5 that merely renamed one, so warn rather than silently skip
+# work peft should have done.
+
+
+def test_a_missing_mapping_function_is_announced():
+ _fake_real_module(
+ CONV,
+ _MODEL_TO_CONVERSION_PATTERN = {"real": 1},
+ get_checkpoint_conversion_mapping = lambda *a: "real",
+ )
+ with pytest.warns(RuntimeWarning, match = "get_model_conversion_mapping"):
+ assert backfill(CONV) == ("get_model_conversion_mapping",)
+
+
+def test_a_missing_conversion_class_is_announced():
+ _fake_real_module(CORE, **{s: object() for s in FIXES._PEFT_REQUIRED_SYMBOLS[CORE][1:]})
+ with pytest.warns(RuntimeWarning, match = "Concatenate"):
+ backfill(CORE)
+
+
+def test_only_the_pattern_is_quiet():
+ """An empty pattern is peft's own starting point, so a warning would be noise."""
+ import warnings
+
+ _fake_real_module(
+ CONV,
+ get_checkpoint_conversion_mapping = lambda *a: None,
+ get_model_conversion_mapping = lambda *a: None,
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert backfill(CONV) == ("_MODEL_TO_CONVERSION_PATTERN",)
+
+
+def test_a_complete_module_says_nothing():
+ import warnings
+ _fake_real_module(CONV, **{s: object() for s in FIXES._PEFT_REQUIRED_SYMBOLS[CONV]})
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert backfill(CONV) == ()
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_sft_vision_dataset_gate.py b/tests/test_sft_vision_dataset_gate.py
new file mode 100644
index 00000000000..3deb4c40b4f
--- /dev/null
+++ b/tests/test_sft_vision_dataset_gate.py
@@ -0,0 +1,121 @@
+"""Tests _backport_vision_dataset_gate in rl.py against REAL TRL sources.
+
+TRL 0.22.x keys "skip dataset preparation" and "use the vision collator" off
+`_is_vlm` (the model) alone, so a VLM fine-tuned on text-only data reaches
+transformers with no tokenized columns ("No columns in the dataset match the
+model's forward method signature"). Magistral_(24B)-Reasoning-Conversational
+hits this; it pins trl==0.22.2. TRL 0.24.0+ keys off `_is_vision_dataset`,
+back-ported here.
+
+The patch is textual, so the tests run it over the installed sft_trainer.py plus
+a checked-in 0.22.2 excerpt and require the result to still parse. No GPU.
+"""
+
+import ast
+import importlib.util
+import textwrap
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+RL_PY = REPO_ROOT / "unsloth" / "models" / "rl.py"
+
+
+def _load_backport():
+ """Grab the helper without importing rl.py (which needs trl at import)."""
+ src = RL_PY.read_text(encoding = "utf-8")
+ tree = ast.parse(src)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == "_backport_vision_dataset_gate":
+ ns = {}
+ exec(ast.get_source_segment(src, node), ns)
+ return ns["_backport_vision_dataset_gate"]
+ raise AssertionError("_backport_vision_dataset_gate not found in rl.py")
+
+
+backport = _load_backport()
+
+# The three decision points, verbatim from trl 0.22.2 sft_trainer.py.
+TRL_022_EXCERPT = textwrap.dedent("""\
+ class SFTTrainer:
+ def __init__(self, train_dataset, args, data_collator, model):
+ dataset_sample = next(iter(train_dataset))
+ if args.completion_only_loss is None:
+ self.completion_only_loss = "prompt" in dataset_sample
+ if data_collator is None and not self._is_vlm:
+ data_collator = DataCollatorForLanguageModeling()
+ elif data_collator is None and self._is_vlm:
+ data_collator = DataCollatorForVisionLanguageModeling()
+ skip_prepare_dataset = (
+ args.dataset_kwargs is not None and args.dataset_kwargs.get("skip_prepare_dataset", False) or self._is_vlm
+ )
+ if not skip_prepare_dataset:
+ train_dataset = self._prepare_dataset(train_dataset)
+""")
+
+# TRL 0.24.0+ already computes the flag itself.
+TRL_MODERN_EXCERPT = textwrap.dedent("""\
+ class SFTTrainer:
+ def __init__(self, train_dataset, args, data_collator, model):
+ dataset_sample = next(iter(train_dataset))
+ self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample
+ if data_collator is None and not self._is_vision_dataset:
+ data_collator = DataCollatorForLanguageModeling()
+""")
+
+
+def test_patches_all_three_decision_points_on_022():
+ out = backport(TRL_022_EXCERPT)
+ assert (
+ 'self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample' in out
+ )
+ assert "if data_collator is None and not (self._is_vlm and self._is_vision_dataset):" in out
+ assert "elif data_collator is None and self._is_vlm and self._is_vision_dataset:" in out
+ assert "or (self._is_vlm and self._is_vision_dataset)" in out
+ # Every bare `or self._is_vlm` gate must be gone.
+ assert 'skip_prepare_dataset", False) or self._is_vlm\n' not in out
+
+
+def test_patched_source_still_parses():
+ ast.parse(backport(TRL_022_EXCERPT))
+
+
+def test_modern_trl_is_untouched():
+ assert backport(TRL_MODERN_EXCERPT) == TRL_MODERN_EXCERPT
+
+
+def test_idempotent():
+ once = backport(TRL_022_EXCERPT)
+ assert backport(once) == once
+
+
+def test_unrecognised_source_is_returned_unchanged():
+ other = "class SFTTrainer:\n def __init__(self):\n pass\n"
+ assert backport(other) == other
+
+
+def _installed_trl_sft_source():
+ try:
+ # find_spec imports parents, so a missing trl raises, not returns None.
+ spec = importlib.util.find_spec("trl.trainer.sft_trainer")
+ except (ImportError, ValueError):
+ return None
+ if spec is None or not spec.origin:
+ return None
+ return Path(spec.origin).read_text(encoding = "utf-8")
+
+
[email protected](_installed_trl_sft_source() is None, reason = "trl not installed")
+def test_installed_trl_source_survives_the_patch():
+ src = _installed_trl_sft_source()
+ out = backport(src)
+ ast.parse(out) # must stay valid whether or not it was patched
+ if 'self._is_vision_dataset = "image" in dataset_sample' in src:
+ assert out == src, "modern TRL must not be rewritten"
+ else:
+ assert "self._is_vision_dataset" in out
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_transformers5_bare_annotation_live.py b/tests/test_transformers5_bare_annotation_live.py
new file mode 100644
index 00000000000..057949d84dc
--- /dev/null
+++ b/tests/test_transformers5_bare_annotation_live.py
@@ -0,0 +1,166 @@
+"""The transformers-5 config fix, demonstrated against a real transformers 5.
+
+transformers 5.x turns `PretrainedConfig` subclasses into dataclasses. vLLM's
+`configs/deepseek_vl2.py` declares `vision_config: VisionEncoderConfig` with no
+default, and a dataclass will not accept a non-default field after an inherited
+default one ("TypeError: non-default argument 'vision_config' follows default
+argument"). That fires while importing `vllm.transformers_utils.configs`, taking
+down `import vllm` and with it `import unsloth`.
+
+The other tests for this fix assert on source text; this one reproduces the
+failing shape and checks the outcome, so it catches the fix silently ceasing to
+work. No vLLM install needed: the config class above IS the reproduction. Skips
+on transformers 4.x, where configs are not dataclasses.
+"""
+
+import pytest
+
+transformers = pytest.importorskip("transformers")
+
+from packaging.version import Version # noqa: E402
+
+pytestmark = pytest.mark.skipif(
+ Version(transformers.__version__) < Version("5.0.0"),
+ reason = "transformers 4.x does not convert config subclasses to dataclasses",
+)
+
+
+def _build(tag):
+ """A vLLM-shaped config pair: a bare annotation with no default."""
+ from transformers.configuration_utils import PretrainedConfig
+
+ class VisionEncoderConfig(PretrainedConfig):
+ model_type = f"vision_{tag}"
+
+ class DeepseekVL2Config(PretrainedConfig):
+ model_type = f"deepseek_vl_v2_{tag}"
+ vision_config: VisionEncoderConfig # no default: the trigger
+
+ return DeepseekVL2Config
+
+
+def unpatched():
+ """Remove the patch so the failure can be observed, then restore it.
+ Imports unsloth first: run alone, nothing would have installed it yet."""
+ import unsloth # noqa: F401 - installs the patch we are about to remove
+
+ from transformers.configuration_utils import PretrainedConfig
+
+ saved = PretrainedConfig.__dict__.get("__init_subclass__")
+ flag = getattr(PretrainedConfig, "_unsloth_patched_init_subclass", False)
+ inner = getattr(saved, "__func__", saved)
+ original = getattr(inner, "__wrapped__", None)
+ if flag and original is not None:
+ PretrainedConfig.__init_subclass__ = classmethod(original)
+ PretrainedConfig._unsloth_patched_init_subclass = False
+ yield
+ if saved is not None:
+ PretrainedConfig.__init_subclass__ = saved
+ PretrainedConfig._unsloth_patched_init_subclass = flag
+
+
+def test_the_failure_is_real_without_the_fix(unpatched):
+ """Guards the premise: if this stops raising, the fix tests nothing."""
+ from unsloth.import_fixes import (
+ _transformers_configs_are_kw_only,
+ _transformers_needs_bare_annotation_fix,
+ fix_transformers5_bare_annotation_configs,
+ )
+ from transformers.configuration_utils import PretrainedConfig
+
+ if getattr(PretrainedConfig, "_unsloth_patched_init_subclass", False):
+ pytest.skip("could not unpatch; the wrapped original was not reachable")
+ if _transformers_configs_are_kw_only(PretrainedConfig):
+ pytest.skip(
+ f"transformers {transformers.__version__} passes kw_only=True "
+ f"(5.5.1+), so the ordering rule this fix works around is gone"
+ )
+ # The ordering rule only exists between 5.4.0 and 5.5.0: 5.0.0 to 5.3.x are
+ # 5.x but do not dataclass-ify configs at all (no `__init_subclass__`), so
+ # nothing raises there and the premise below does not apply. Ask the
+ # unpatched class rather than the version, which was the point of the probe.
+ if not _transformers_needs_bare_annotation_fix():
+ pytest.skip(
+ f"transformers {transformers.__version__} does not apply the "
+ f"dataclass ordering rule to config subclasses (pre-5.4.0)"
+ )
+ with pytest.raises(TypeError, match = "non-default argument"):
+ _build("unpatched")
+
+
+def test_the_fix_stands_down_when_transformers_handles_it():
+ """kw_only=True fixed this upstream, so patching anyway would be an untested
+ monkey patch. >= 5.5.1 covers both branches (5.5.1 on 5.5, 5.6.0 on main)."""
+ from unsloth.import_fixes import (
+ _transformers_configs_are_kw_only,
+ fix_transformers5_bare_annotation_configs,
+ )
+ from transformers.configuration_utils import PretrainedConfig
+
+ kw_only = _transformers_configs_are_kw_only(PretrainedConfig)
+ expected = Version(transformers.__version__) >= Version("5.5.1")
+ assert (
+ kw_only == expected
+ ), f"transformers {transformers.__version__}: probe says kw_only={kw_only}"
+ if not kw_only:
+ pytest.skip("this transformers still needs the fix")
+
+ PretrainedConfig._unsloth_patched_init_subclass = False
+ fix_transformers5_bare_annotation_configs()
+ assert not getattr(PretrainedConfig, "_unsloth_patched_init_subclass", False)
+
+
+def test_the_fix_lets_it_import():
+ from unsloth.import_fixes import fix_transformers5_bare_annotation_configs
+
+ fix_transformers5_bare_annotation_configs()
+ cls = _build("patched")
+ assert cls.__name__ == "DeepseekVL2Config"
+
+
+def test_applying_twice_is_a_no_op():
+ from unsloth.import_fixes import fix_transformers5_bare_annotation_configs
+ from transformers.configuration_utils import PretrainedConfig
+
+ fix_transformers5_bare_annotation_configs()
+ first = PretrainedConfig.__dict__.get("__init_subclass__")
+ fix_transformers5_bare_annotation_configs()
+ assert PretrainedConfig.__dict__.get("__init_subclass__") is first
+
+
+def test_ordinary_configs_are_unaffected():
+ """The patch runs for EVERY config subclass, so it must disturb none."""
+ from unsloth.import_fixes import fix_transformers5_bare_annotation_configs
+ from transformers.configuration_utils import PretrainedConfig
+
+ fix_transformers5_bare_annotation_configs()
+
+ class Ordinary(PretrainedConfig):
+ model_type = "ordinary_probe"
+
+ def __init__(
+ self,
+ hidden_size = 16,
+ **kwargs,
+ ):
+ self.hidden_size = hidden_size
+ super().__init__(**kwargs)
+
+ cfg = Ordinary(hidden_size = 32)
+ assert cfg.hidden_size == 32
+ assert cfg.model_type == "ordinary_probe"
+
+
+def test_a_real_model_config_still_loads():
+ from unsloth.import_fixes import fix_transformers5_bare_annotation_configs
+
+ fix_transformers5_bare_annotation_configs()
+ from transformers import LlamaConfig
+
+ cfg = LlamaConfig(hidden_size = 64, num_hidden_layers = 2)
+ assert cfg.hidden_size == 64
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index 6f5ce6b7dd5..124a1584e08 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -177,6 +177,7 @@ from unsloth_zoo.device_type import (
# Fix other issues
from .import_fixes import (
+ fix_transformers5_bare_annotation_configs,
fix_xformers_performance_issue,
fix_vllm_aimv2_issue,
fix_vllm_lora_tokenizer_module,
@@ -208,6 +209,8 @@ from .import_fixes import (
patch_accelerate_recursively_apply,
)
+# Must run first: guards PretrainedConfig before vLLM defines its config classes.
+fix_transformers5_bare_annotation_configs()
fix_xformers_performance_issue()
fix_vllm_aimv2_issue()
fix_vllm_lora_tokenizer_module()
@@ -249,6 +252,7 @@ patch_peft_weight_converter_compatibility()
fix_peft_stale_torchao_import_error()
patch_accelerate_recursively_apply()
+del fix_transformers5_bare_annotation_configs
del fix_xformers_performance_issue
del fix_vllm_aimv2_issue
del fix_vllm_lora_tokenizer_module
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 3cfb3ed0cf1..42ed6612cf6 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -413,6 +413,144 @@ def patch_vllm_for_notebooks():
sys.stdout.fileno = lambda: 1
+# TypeError: non-default argument 'vision_config' follows default argument
+_UNSLOTH_DC_BACKFILL_FLAG = "__unsloth_dc_defaults_backfilled__"
+
+
+def _backfill_dataclass_defaults(cls):
+ """Give class-local bare annotations a ``None`` default.
+
+ transformers 5.x dataclass-ifies every ``PretrainedConfig`` subclass, so a
+ bare annotation after an inherited default trips "non-default argument
+ follows default argument". Skips names resolving anywhere in the MRO, and
+ ``ClassVar`` / ``InitVar``, matched textually as annotations may be strings.
+ """
+ if cls.__dict__.get(_UNSLOTH_DC_BACKFILL_FLAG):
+ return []
+ own_annotations = cls.__dict__.get("__annotations__") or {}
+ backfilled = []
+ for name, annotation in own_annotations.items():
+ text = (
+ annotation
+ if isinstance(annotation, str)
+ else (getattr(annotation, "__name__", "") or repr(annotation))
+ )
+ if "ClassVar" in text or "InitVar" in text:
+ continue
+ # dataclass reads defaults with getattr, so the MRO already counts.
+ if hasattr(cls, name):
+ continue
+ try:
+ setattr(cls, name, None)
+ backfilled.append(name)
+ except Exception:
+ pass
+ try:
+ setattr(cls, _UNSLOTH_DC_BACKFILL_FLAG, True)
+ except Exception:
+ pass
+ return backfilled
+
+
+def _transformers_configs_are_kw_only(PretrainedConfig):
+ """Does this transformers already build config dataclasses `kw_only`?
+
+ `kw_only=True` (5.5.1 on the 5.5 branch, 5.6.0 on main) removes the ordering
+ rule this fix exists for. Read the source, not the version, since it was
+ backported; where the source is unreadable (stripped or frozen installs),
+ probe instead, as a wrong False gives required fields a `None` default.
+ """
+ import inspect
+
+ hook = PretrainedConfig.__dict__.get("__init_subclass__")
+ hook = getattr(hook, "__func__", hook)
+ if hook is None:
+ return False
+ try:
+ return re.search(r"\bkw_only\s*=\s*True", inspect.getsource(hook)) is not None
+ except Exception:
+ pass
+ return not _transformers_needs_bare_annotation_fix()
+
+
+def _transformers_needs_bare_annotation_fix():
+ """Does defining a bare-annotation config subclass actually raise here?
+
+ Answered by trying it: the rule (5.4.0) and `kw_only=True` (5.5.1) were both
+ backported, so a version window mislabels distros carrying them early or
+ late. Absent positive evidence answer False: a loud `TypeError` beats a
+ config quietly accepting a missing required field.
+ """
+ try:
+ from transformers.configuration_utils import PretrainedConfig
+ except Exception:
+ return False
+ try:
+ # Exactly the shape vLLM defines: a default, then a bare annotation.
+ type(
+ "_UnslothProbeConfig",
+ (PretrainedConfig,),
+ {"__annotations__": {"a": int, "b": int}, "a": 0},
+ )
+ except TypeError:
+ return True
+ except Exception:
+ return False
+ return False
+
+
+def fix_transformers5_bare_annotation_configs():
+ """Stop transformers 5.x from breaking third-party config classes.
+
+ vLLM's ``configs/deepseek_vl2.py`` declares a bare ``vision_config``, which
+ raises ``TypeError`` while importing ``vllm.transformers_utils.configs`` and
+ takes ``import unsloth`` down with it. Patching
+ ``PretrainedConfig.__init_subclass__`` rather than vLLM's source covers every
+ affected class in any vLLM version. No-ops outside the 5.4.0 to 5.5.0
+ window: below it configs are not dataclasses, above ``kw_only=True`` leaves
+ no ordering rule to break.
+ """
+ try:
+ import transformers
+ if Version(transformers.__version__) < Version("5.0.0"):
+ return
+ from transformers.configuration_utils import PretrainedConfig
+ except Exception as e:
+ logger.info(f"Unsloth: Skipping transformers-5 config fix ({e})")
+ return
+
+ if _transformers_configs_are_kw_only(PretrainedConfig):
+ return
+
+ if getattr(PretrainedConfig, "_unsloth_patched_init_subclass", False):
+ return
+
+ original = PretrainedConfig.__dict__.get("__init_subclass__")
+ if original is None:
+ return
+ # `__init_subclass__` is an implicit classmethod; unwrap to the function.
+ original_func = getattr(original, "__func__", original)
+
+ def __init_subclass__(cls, *args, **kwargs):
+ try:
+ _backfill_dataclass_defaults(cls)
+ except Exception as e:
+ logger.info(f"Unsloth: dataclass default backfill skipped ({e})")
+ return original_func(cls, *args, **kwargs)
+
+ # Keep the original reachable, so the patch can be tested and undone.
+ __init_subclass__.__wrapped__ = original_func
+ try:
+ PretrainedConfig.__init_subclass__ = classmethod(__init_subclass__)
+ PretrainedConfig._unsloth_patched_init_subclass = True
+ logger.info(
+ "Unsloth: Patching transformers `PretrainedConfig.__init_subclass__` "
+ "so vLLM config classes with bare annotations still import"
+ )
+ except Exception as e:
+ logger.info(f"Unsloth: Failed patching PretrainedConfig ({e})")
+
+
# ValueError: 'aimv2' is already used by a Transformers config, pick another name.
def fix_vllm_aimv2_issue():
spec = importlib.util.find_spec("vllm")
@@ -1877,14 +2015,10 @@ def _make_peft_stub_module(fullname):
return mod
-def _install_transformers_conversion_mapping_stub():
- """Stub the 3 symbols peft 0.19.x imports from this module at top level."""
- name = "transformers.conversion_mapping"
- existing = sys.modules.get(name)
- if existing is not None and getattr(existing, _UNSLOTH_STUB_SENTINEL, False):
- return existing
-
- mod = _make_peft_stub_module(name)
+def _build_transformers_conversion_mapping_stub():
+ """Build (not install) peft's 3 symbols, so the same objects can also
+ backfill a REAL module missing only some of them."""
+ mod = _make_peft_stub_module("transformers.conversion_mapping")
# peft does ``.copy()`` + keyed assignment at module top; real dict suffices.
mod._MODEL_TO_CONVERSION_PATTERN = {}
@@ -1899,7 +2033,17 @@ def _install_transformers_conversion_mapping_stub():
mod.get_checkpoint_conversion_mapping = get_checkpoint_conversion_mapping
mod.get_model_conversion_mapping = get_model_conversion_mapping
+ return mod
+
+def _install_transformers_conversion_mapping_stub():
+ """Stub the 3 symbols peft 0.19.x imports from this module at top level."""
+ name = "transformers.conversion_mapping"
+ existing = sys.modules.get(name)
+ if existing is not None and getattr(existing, _UNSLOTH_STUB_SENTINEL, False):
+ return existing
+
+ mod = _build_transformers_conversion_mapping_stub()
sys.modules[name] = mod
# Attach to parent so attribute-style access matches a real submodule.
parent = sys.modules.get("transformers")
@@ -1912,18 +2056,14 @@ def _install_transformers_conversion_mapping_stub():
return mod
-def _install_transformers_core_model_loading_stub():
- """Stub the 8 symbols peft 0.19.x imports from this module at top level.
-
- ``Concatenate`` and ``ConversionOps`` MUST be real classes (peft
- subclasses them at module top); the rest only appear in runtime
- ``isinstance`` / construction calls gated behind ``is_transformers_ge_v5``."""
- name = "transformers.core_model_loading"
- existing = sys.modules.get(name)
- if existing is not None and getattr(existing, _UNSLOTH_STUB_SENTINEL, False):
- return existing
+def _build_transformers_core_model_loading_stub():
+ """Build (not install) peft's 8 symbols, so the same objects can also
+ backfill a REAL module missing only some of them.
- mod = _make_peft_stub_module(name)
+ ``Concatenate`` and ``ConversionOps`` MUST be real classes (peft subclasses
+ them at module top); the rest only appear in runtime calls gated behind
+ ``is_transformers_ge_v5``."""
+ mod = _make_peft_stub_module("transformers.core_model_loading")
class ConversionOps:
def convert(self, *args, **kwargs): # pragma: no cover - inert stub
@@ -1992,7 +2132,17 @@ def _install_transformers_core_model_loading_stub():
mod.WeightRenaming = WeightRenaming
mod.dot_natural_key = dot_natural_key
mod.rename_source_key = rename_source_key
+ return mod
+
+
+def _install_transformers_core_model_loading_stub():
+ """Install the core_model_loading stub, unless a real module is present."""
+ name = "transformers.core_model_loading"
+ existing = sys.modules.get(name)
+ if existing is not None and getattr(existing, _UNSLOTH_STUB_SENTINEL, False):
+ return existing
+ mod = _build_transformers_core_model_loading_stub()
sys.modules[name] = mod
parent = sys.modules.get("transformers")
if parent is not None and not hasattr(parent, "core_model_loading"):
@@ -2003,6 +2153,84 @@ def _install_transformers_core_model_loading_stub():
return mod
+# Names peft's transformers_weight_conversion imports at module top level; a
+# real module missing ANY of them breaks that import as hard as an absent one.
+_PEFT_REQUIRED_SYMBOLS = {
+ "transformers.conversion_mapping": (
+ "_MODEL_TO_CONVERSION_PATTERN",
+ "get_checkpoint_conversion_mapping",
+ "get_model_conversion_mapping",
+ ),
+ "transformers.core_model_loading": (
+ "Concatenate",
+ "ConversionOps",
+ "MergeModulelist",
+ "Transpose",
+ "WeightConverter",
+ "WeightRenaming",
+ "dot_natural_key",
+ "rename_source_key",
+ ),
+}
+_PEFT_STUB_BUILDERS = {
+ "transformers.conversion_mapping": _build_transformers_conversion_mapping_stub,
+ "transformers.core_model_loading": _build_transformers_core_model_loading_stub,
+}
+
+
+def _backfill_missing_peft_symbols(name):
+ """Add to a REAL transformers submodule only the peft symbols it lacks.
+
+ transformers 5.0.0.dev0 ships ``conversion_mapping`` without
+ ``_MODEL_TO_CONVERSION_PATTERN``, so peft's top-level import raises
+ ImportError even though the module imports fine; stubbing it wholesale would
+ replace working transformers code. The donors are inert, which is right
+ where the symbol never existed but wrong for a transformers 5 that HAS
+ conversions and merely renamed one, hence the warning.
+
+ Strictly additive and idempotent. Returns the names added."""
+ try:
+ mod = importlib.import_module(name)
+ except Exception:
+ return ()
+ if getattr(mod, _UNSLOTH_STUB_SENTINEL, False):
+ return () # our own stub already provides the full set
+ missing = [s for s in _PEFT_REQUIRED_SYMBOLS[name] if not hasattr(mod, s)]
+ if not missing:
+ return ()
+ donor = _PEFT_STUB_BUILDERS[name]()
+ added = []
+ for symbol in missing:
+ try:
+ setattr(mod, symbol, getattr(donor, symbol))
+ added.append(symbol)
+ except Exception:
+ pass # frozen or slotted module object
+ if added:
+ _warn_peft_symbols_backfilled(name, added)
+ return tuple(added)
+
+
+# An empty pattern is peft's own starting point; the rest stand in for real
+# upstream behaviour, so those are worth warning about.
+_PEFT_INERT_BACKFILL_IS_FINE = frozenset(("_MODEL_TO_CONVERSION_PATTERN",))
+
+
+def _warn_peft_symbols_backfilled(name, added):
+ """Say when an inert stand-in went into a module that is otherwise real."""
+ substantive = [s for s in added if s not in _PEFT_INERT_BACKFILL_IS_FINE]
+ if not substantive:
+ return
+ warnings.warn(
+ f"Unsloth: {name} is missing {', '.join(substantive)}, so peft could "
+ f"not be imported. Added inert stand-ins to get the import through; "
+ f"weight conversions that rely on them will be skipped. Upgrading "
+ f"transformers is the real fix.",
+ RuntimeWarning,
+ stacklevel = 2,
+ )
+
+
def fix_peft_transformers_weight_conversion_import():
"""Make ``from peft.utils import transformers_weight_conversion`` import
cleanly on (peft 0.19.x, transformers 4.x) by stubbing the two missing
@@ -2059,6 +2287,20 @@ def fix_peft_transformers_weight_conversion_import():
_install_transformers_core_model_loading_stub()
patched_any = True
+ # An importable submodule can still lack individual symbols; backfill just
+ # those names rather than replacing a real module wholesale.
+ backfilled = {}
+ for _submodule in _PEFT_REQUIRED_SYMBOLS:
+ added = _backfill_missing_peft_symbols(_submodule)
+ if added:
+ backfilled[_submodule] = added
+ patched_any = True
+ if backfilled:
+ logger.info(
+ "Unsloth: backfilled peft symbols missing from transformers: "
+ + "; ".join(f"{m}: {', '.join(s)}" for m, s in backfilled.items())
+ )
+
if not patched_any:
# Real submodules present; failure was for some other reason.
return False
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index af96c2f87b7..2c11af82f8c 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -749,6 +749,49 @@ def _wrap_grpo_hidden_states_fallback(trainer_cls):
trainer_cls.__init__ = wrapped_init
+def _backport_vision_dataset_gate(RLTrainer_source):
+ """Make TRL 0.22.x decide by DATASET, not by model, for SFT vision paths.
+
+ 0.22.x keys "skip preparation" and "vision collator" off `_is_vlm` alone, so
+ a VLM fine-tuned on text-only data reaches transformers with no tokenized
+ columns: "No columns in the dataset match the model's forward method
+ signature". Merging the signature columns above is not enough, since skipped
+ preparation never creates those columns. Hit by
+ Magistral_(24B)-Reasoning-Conversational, which pins trl==0.22.2.
+
+ Back-ports TRL 0.24.0's `_is_vision_dataset` keying; no-op once TRL defines
+ the flag itself. Returns the source, patched or unchanged."""
+ if 'self._is_vision_dataset = "image" in dataset_sample' in RLTrainer_source:
+ return RLTrainer_source
+ anchor = " dataset_sample = next(iter(train_dataset))\n"
+ if anchor not in RLTrainer_source:
+ return RLTrainer_source
+
+ RLTrainer_source = RLTrainer_source.replace(
+ anchor,
+ anchor + " # Unsloth: back-port of TRL 0.24.0's dataset-based check, so a\n"
+ " # text-only fine-tune of a VLM is prepared and collated as text.\n"
+ ' self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample\n',
+ 1,
+ )
+ # Text collator whenever the data is not actually vision data.
+ RLTrainer_source = RLTrainer_source.replace(
+ "if data_collator is None and not self._is_vlm:",
+ "if data_collator is None and not (self._is_vlm and self._is_vision_dataset):",
+ )
+ RLTrainer_source = RLTrainer_source.replace(
+ "elif data_collator is None and self._is_vlm:",
+ "elif data_collator is None and self._is_vlm and self._is_vision_dataset:",
+ )
+ # Tokenize it too: skipping preparation only saves image-processing cost.
+ RLTrainer_source = RLTrainer_source.replace(
+ 'args.dataset_kwargs.get("skip_prepare_dataset", False) or self._is_vlm',
+ 'args.dataset_kwargs.get("skip_prepare_dataset", False)'
+ " or (self._is_vlm and self._is_vision_dataset)",
+ )
+ return RLTrainer_source
+
+
def _patch_trl_rl_trainers(trainer_file = "grpo_trainer"):
# Defensive wrapper: matches patch_trl_rl_trainers()'s try/except so
# direct callers don't see exceptions from the impl on TRL versions
@@ -1785,11 +1828,9 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
if _vlm_check_original in RLTrainer_source:
RLTrainer_source = RLTrainer_source.replace(_vlm_check_original, _vlm_check_patched)
- # Fix TRL 0.22.x: VLM models with text-only datasets. It checks _is_vlm
- # (model type), not _is_vision_dataset (added in 0.25.1+); with
- # _is_vlm=True the vision-only signature columns don't overlap tokenized
- # text columns. Fix: merge both column sets into the VLM branch. Extra
- # columns are ignored by _remove_unused_columns (raises only on zero match).
+ # TRL 0.22.x keys off _is_vlm, not _is_vision_dataset (0.24.0+), so the
+ # vision-only signature columns never overlap the tokenized ones. Merge
+ # both sets; _remove_unused_columns ignores extras.
_sig_vlm_old = 'self._signature_columns = ["messages", "prompt", "completion", "images"]'
_sig_vlm_new = (
'self._signature_columns = ["messages", "prompt", "completion", "images",'
@@ -1797,6 +1838,8 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
)
RLTrainer_source = RLTrainer_source.replace(_sig_vlm_old, _sig_vlm_new)
+ RLTrainer_source = _backport_vision_dataset_gate(RLTrainer_source)
+
# Inject model reference before _prepare_dataset for dynamic
# token_type_ids detection in sft_prepare_dataset
_prep_pattern = r"([ \t]*)train_dataset = self\._prepare_dataset\("
@@ -2082,7 +2125,7 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, import
sampling_params = re.sub(r"[\,][\s]{0,}\,", ",", sampling_params)
new_vllm_part = (
- f"\n{' ' * 8}if {args}.use_vllm:\n{sampling_params}" f"\n{' ' * 8}else:\n"
+ f"\n{' ' * 8}if {args}.use_vllm:\n{sampling_params}\n{' ' * 8}else:\n"
)
if trl_version >= Version("0.18.0"):
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index e534931108a..710ffe6c4bb 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -311,6 +311,46 @@ def _embeddings_are_tied(input_embeddings, output_embeddings):
return w_in is w_out or w_in.data_ptr() == w_out.data_ptr()
+def _offload_embedding_unsupported_platform():
+ # Offloaded embeddings do not work on Windows or WSL.
+ if bool(os.environ.get("WSL_DISTRO_NAME") or os.environ.get("WSL_INTEROP")):
+ return "WSL"
+ if os.name == "nt":
+ return "Windows"
+ return None
+
+
+def _resolve_offload_embedding(model, offload_embedding):
+ """Report `offload_embedding` as True only when the offload will really run.
+
+ It is a VRAM optimisation, not a correctness switch, so turn it off where it
+ cannot help instead of failing the load. It also gates
+ `_attach_bnb_multidevice_hooks`, which must still run whenever no offload
+ happens, so every "no offload" case has to answer False.
+ """
+ if not offload_embedding:
+ return False
+ platform_name = _offload_embedding_unsupported_platform()
+ if platform_name is not None:
+ print(f"Unsloth: Not offloading embeddings; offloading is unsupported on {platform_name}.")
+ return False
+ try:
+ in_embed = model.get_input_embeddings()
+ out_embed = (
+ model.get_output_embeddings() if hasattr(model, "get_output_embeddings") else None
+ )
+ except Exception:
+ # Cannot inspect it, so leave the caller's request alone.
+ return offload_embedding
+ if _embeddings_are_tied(in_embed, out_embed):
+ print(
+ "Unsloth: Not offloading embeddings; this model ties embed_tokens "
+ "to lm_head, so offloading saves no VRAM."
+ )
+ return False
+ return True
+
+
VLLM_SUPPORTED_VLM = [
"qwen2_5_vl",
"gemma3",
@@ -1312,6 +1352,13 @@ class FastBaseModel:
# attn_implementation = attn_implementation,
**kwargs,
)
+ # Must precede _attach_bnb_multidevice_hooks: it returns early
+ # while offload_embedding is True.
+ offload_embedding = _resolve_offload_embedding(
+ model,
+ offload_embedding,
+ )
+
# Attach dispatch hooks for bnb multi-device loads.
_attach_bnb_multidevice_hooks(
model,
@@ -1335,37 +1382,24 @@ class FastBaseModel:
model.fast_generate = make_fast_generate_wrapper(model.generate)
model.fast_generate_batches = error_out_no_vllm
if offload_embedding:
- if bool(os.environ.get("WSL_DISTRO_NAME") or os.environ.get("WSL_INTEROP")):
- # WSL doesn't work with offloaded embeddings
- pass
- elif os.name == "nt":
- # Windows doesn't work with offloaded embeddings
- pass
- else:
- embed_tokens = model.get_input_embeddings()
- out_embed = (
- model.get_output_embeddings()
- if hasattr(model, "get_output_embeddings")
- else None
- )
- if _embeddings_are_tied(embed_tokens, out_embed):
- raise NotImplementedError(
- "offload_embedding = True is not supported for models with tied word "
- "embeddings (embed_tokens shares its weight with lm_head). Offloading "
- "would strand the output projection on CPU and saves no VRAM. Set "
- "offload_embedding = False for this model."
- )
- nbytes = embed_tokens.weight.numel() * embed_tokens.weight.itemsize
- ngb = round(nbytes / 1024 / 1024 / 1024, 2)
- print(f"Unsloth: Offloading embeddings to RAM to save {ngb} GB.")
- _embed_device = embed_tokens.weight.device # decoder device, before offload
- embed_tokens.to("cpu")
-
- # Device-safe embedding offload.
- _install_offload_embedding_hooks(embed_tokens, out_embed, _embed_device)
- # Must free GPU memory otherwise will not free!
- clean_gpu_cache()
- gc.collect()
+ # Unsupported platforms and tied embeddings were screened out above.
+ embed_tokens = model.get_input_embeddings()
+ out_embed = (
+ model.get_output_embeddings()
+ if hasattr(model, "get_output_embeddings")
+ else None
+ )
+ nbytes = embed_tokens.weight.numel() * embed_tokens.weight.itemsize
+ ngb = round(nbytes / 1024 / 1024 / 1024, 2)
+ print(f"Unsloth: Offloading embeddings to RAM to save {ngb} GB.")
+ _embed_device = embed_tokens.weight.device # decoder device, before offload
+ embed_tokens.to("cpu")
+
+ # Device-safe embedding offload.
+ _install_offload_embedding_hooks(embed_tokens, out_embed, _embed_device)
+ # Must free GPU memory otherwise will not free!
+ clean_gpu_cache()
+ gc.collect()
else:
from unsloth_zoo.vllm_utils import (
load_vllm,