Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix notebook failures on Kaggle T4x2 and duplicate import warnings (#13024)

Daniel Hancd905b3cced6
diff --git a/tests/python/test_sentence_transformer_config_kwargs.py b/tests/python/test_sentence_transformer_config_kwargs.py
index d910400a458..9bebe2bcf65 100644
--- a/tests/python/test_sentence_transformer_config_kwargs.py
+++ b/tests/python/test_sentence_transformer_config_kwargs.py
@@ -145,6 +145,30 @@ def test_float16_pooling_with_batch_encoding_features():
assert torch.isfinite(out["sentence_embedding"]).all()
+def test_float16_dense_head_after_float32_pooling():
+ # EmbeddingGemma on T4: float16 Dense head after the float32 pooled vector, autocast off.
+ import torch
+ from sentence_transformers.models import Dense, Normalize, Pooling
+
+ pooling = Pooling(word_embedding_dimension = 8, pooling_mode = "mean")
+ torch.manual_seed(0)
+ dense = Dense(
+ in_features = 8, out_features = 4, bias = False, activation_function = torch.nn.Identity()
+ ).half()
+ tokens = torch.randn(2, 5, 8, dtype = torch.float16)
+ features = {"token_embeddings": tokens, "attention_mask": torch.ones(2, 5, dtype = torch.long)}
+ out = Normalize()(dense(pooling(features)))
+ assert out["sentence_embedding"].shape == (2, 4)
+ assert torch.isfinite(out["sentence_embedding"]).all()
+ want = dense.linear(tokens.float().mean(1).half())
+ torch.testing.assert_close(
+ out["sentence_embedding"].float(),
+ torch.nn.functional.normalize(want.float(), dim = -1),
+ atol = 2e-3,
+ rtol = 2e-3,
+ )
+
+
def test_bfloat16_pooling_is_unchanged():
import torch
from sentence_transformers.models import Pooling
diff --git a/tests/test_datasets_audio_fallback.py b/tests/test_datasets_audio_fallback.py
index b444baa1577..d9465191b0b 100644
--- a/tests/test_datasets_audio_fallback.py
+++ b/tests/test_datasets_audio_fallback.py
@@ -223,6 +223,36 @@ def test_a_wheel_that_raises_anything_at_import_is_disabled(
assert said and "soundfile and PyAV" in said[0] and "reinstall torchcodec" in said[0]
[email protected]("hint_from", ["version", "provenance"])
+def test_a_broken_codec_with_a_remedy_is_reported_once(
+ broken_torchcodec, monkeypatch, tmp_path, hint_from
+):
+ # A torchcodec built for another torch: one warning carrying the remedy, not two.
+ import sys
+ import warnings
+
+ pkg = tmp_path / "torchcodec"
+ pkg.mkdir()
+ (pkg / "__init__.py").write_text("", encoding = "utf-8")
+ (pkg / "decoders.py").write_text("raise RuntimeError('libtorchcodec')\n", encoding = "utf-8")
+ for name in [n for n in sys.modules if n == "torchcodec" or n.startswith("torchcodec.")]:
+ monkeypatch.delitem(sys.modules, name)
+ monkeypatch.syspath_prepend(str(tmp_path))
+ hint = "torchcodec 0.5 is incompatible with torch 2.11.0+cu128; install a matching build."
+ monkeypatch.setattr(
+ import_fixes,
+ "_torchcodec_version_mismatch_hint",
+ lambda: hint if hint_from == "version" else None,
+ )
+ monkeypatch.setattr(import_fixes, "_torchcodec_provenance_hint", lambda: hint)
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ import_fixes.disable_torchcodec_if_broken()
+ said = [str(w.message) for w in caught if "torchcodec" in str(w.message)]
+ assert len(said) == 1, said
+ assert "torchcodec is installed but" in said[0] and hint in said[0]
+
+
def test_the_audio_extras_carry_the_fallback_decoders():
# `unsloth[audio-torch2xx]` must install what decodes when torchcodec cannot load, or the
# fallback re-raises libsndfile's error on exactly the containers it exists for.
diff --git a/tests/test_online_dpo_left_padding.py b/tests/test_online_dpo_left_padding.py
index aaac1a169ac..638cc43262a 100644
--- a/tests/test_online_dpo_left_padding.py
+++ b/tests/test_online_dpo_left_padding.py
@@ -33,6 +33,21 @@ TRL_0_22_FORWARD = """
"""
+# TRL 0.18-0.19 spelling of the slice.
+TRL_0_18_FORWARD = """
+ def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask):
+ num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0)
+ prompt_ids = prompt_ids[:, num_tokens_to_truncate:]
+ prompt_mask = prompt_mask[:, num_tokens_to_truncate:]
+ prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1)
+ prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1)
+ output = model(prompt_completion_ids, attention_mask=prompt_completion_mask)
+ logits = output.logits[:, prompt_ids.size(1) - 1 : -1]
+ logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1)
+ return logprobs
+"""
+
+
def _patcher():
tree = ast.parse(SOURCE.read_text(encoding = "utf-8"))
wanted = [
@@ -55,7 +70,7 @@ def _compile(source):
def _trl_sources():
# Read TRL's file, not the live class: an imported unsloth has already swapped in its patched trainer.
- sources = {"trl-0.22.2": TRL_0_22_FORWARD}
+ sources = {"trl-0.18.2": TRL_0_18_FORWARD, "trl-0.22.2": TRL_0_22_FORWARD}
spec = importlib.util.find_spec("trl")
if spec is None or not spec.submodule_search_locations:
return sources
diff --git a/tests/test_trainer_data_parallel_guard.py b/tests/test_trainer_data_parallel_guard.py
new file mode 100644
index 00000000000..008171bce96
--- /dev/null
+++ b/tests/test_trainer_data_parallel_guard.py
@@ -0,0 +1,125 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""An Unsloth LoRA model under a plain Trainer on two GPUs trains on one (Kaggle T4x2 Whisper,
+EmbeddingGemma). Extracted with ast so no GPU is needed."""
+
+import ast
+import os
+
+import pytest
+import torch
+from transformers.training_args import ParallelMode
+
+SOURCE = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "unsloth", "models", "_utils.py"
+)
+
+
+def _guard():
+ src = open(SOURCE, encoding = "utf-8").read()
+ node = next(
+ n
+ for n in ast.parse(src).body
+ if isinstance(n, ast.FunctionDef) and n.name == "_keep_unsloth_models_off_data_parallel"
+ )
+ ns = {}
+ exec(ast.get_source_segment(src, node), ns)
+ return ns["_keep_unsloth_models_off_data_parallel"]
+
+
+class _Args:
+ def __init__(
+ self,
+ n_gpu,
+ mode = ParallelMode.NOT_DISTRIBUTED,
+ per_device = 2,
+ ):
+ self._n_gpu = n_gpu
+ self.parallel_mode = mode
+ self.per_device_train_batch_size = per_device
+
+ @property
+ def n_gpu(self):
+ return self._n_gpu
+
+ @property
+ def train_batch_size(self):
+ return self.per_device_train_batch_size * max(1, self.n_gpu)
+
+
+def _wrapped(marked = True):
+ inner = torch.nn.Linear(2, 2)
+ if marked:
+ inner._unsloth_disable_data_parallel = True
+ return torch.nn.Sequential(inner) # the marker sits inside, as in a SentenceTransformer
+
+
+def test_a_marked_model_trains_on_one_gpu():
+ args = _Args(2)
+ assert _guard()(_wrapped(), args) is True
+ assert args.n_gpu == 1 and args.train_batch_size == 2
+
+
+ "model, args",
+ [
+ (_wrapped(marked = False), _Args(2)), # not an Unsloth LoRA model: DataParallel as before
+ (_wrapped(), _Args(1)), # one GPU already
+ (_wrapped(), _Args(2, ParallelMode.DISTRIBUTED)), # DDP owns placement
+ (_wrapped(), None),
+ (None, _Args(2)),
+ ],
+)
+def test_everything_else_is_left_alone(model, args):
+ before = None if args is None else args.n_gpu
+ assert _guard()(model, args) is False
+ if args is not None:
+ assert args.n_gpu == before
+
+
+def _init_patch():
+ import functools
+
+ src = open(SOURCE, encoding = "utf-8").read()
+ ns = {"functools": functools}
+ for n in ast.parse(src).body:
+ if isinstance(n, ast.FunctionDef) and n.name in (
+ "_keep_unsloth_models_off_data_parallel",
+ "_patch_trainer_init_data_parallel",
+ ):
+ exec(ast.get_source_segment(src, n), ns)
+ return ns["_patch_trainer_init_data_parallel"]
+
+
+class _FakeTrainer:
+ def __init__(
+ self,
+ model = None,
+ args = None,
+ ):
+ self.model, self.args = model, args
+ self._train_batch_size = args.train_batch_size
+
+
[email protected]("positional", [False, True])
+def test_the_marker_alone_guards_trainer_init(positional):
+ # Fast encoders never call patch_gradient_accumulation_fix; marking must be enough.
+ Trainer = type("Trainer", (_FakeTrainer,), {})
+ _init_patch()(Trainer)
+ _init_patch()(Trainer)
+ args = _Args(2)
+ trainer = Trainer(_wrapped(), args) if positional else Trainer(model = _wrapped(), args = args)
+ assert args.n_gpu == 1 and trainer._train_batch_size == 2
+ unmarked = _Args(2)
+ assert Trainer(model = _wrapped(marked = False), args = unmarked)._train_batch_size == 4
+
+
+def test_marking_installs_the_init_guard():
+ src = open(SOURCE, encoding = "utf-8").read()
+ fn = next(
+ n
+ for n in ast.parse(src).body
+ if isinstance(n, ast.FunctionDef) and n.name == "_patch_transformers_trainer_data_parallel"
+ )
+ assert "_patch_trainer_init_data_parallel(Trainer)" in ast.get_source_segment(src, fn)
diff --git a/tests/test_unsloth_device_map_optin.py b/tests/test_unsloth_device_map_optin.py
index 0b510bcd88e..ba3859e194d 100644
--- a/tests/test_unsloth_device_map_optin.py
+++ b/tests/test_unsloth_device_map_optin.py
@@ -1315,3 +1315,101 @@ def test_the_loader_pins_on_the_placement_being_unchosen_not_on_it_being_a_strin
f"loader.py:{lineno}: an explicit device_map='cpu' is a str too, so this guard "
f"moves the load onto the rank's GPU"
)
+
+
+# ------------------------------------------------- a model one card holds stays on one card
+
+
+class _SizedPlan(_Plan):
+ def __init__(
+ self,
+ total_gib,
+ budget_gib = 14.4,
+ headroom_gib = 0.5,
+ devices = (0, 1),
+ transient_gib = 0.0,
+ reserve_gib = 0.0,
+ ):
+ super().__init__({"model.layers.0": devices[0], "lm_head": devices[-1]})
+ self.raw_budgets = {d: int(budget_gib * 2**30) for d in devices}
+ self.total_weight_bytes = int(total_gib * 2**30)
+ self.headroom_bytes = int(headroom_gib * 2**30)
+ self.load_transient_by_device = {devices[-1]: int(transient_gib * 2**30)}
+ self.activation_reserve_by_device = {d: int(reserve_gib * 2**30) for d in devices}
+
+
[email protected]("total_gib", [1.2, 6.2, 9.7]) # Qwen3-0.6B, DeepSeek-OCR, Gemma 3n fp32
+def test_a_model_that_fits_one_card_is_not_split(total_gib, capsys):
+ ns = _load(planner = lambda name, **kw: _SizedPlan(total_gib))
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == {"": 0}
+ assert "fits on cuda:0" in capsys.readouterr().out
+
+
+def test_the_single_card_is_one_the_caller_allowed():
+ """max_memory {2, 3} withholds cuda:0 and cuda:1."""
+ seen = {}
+
+ def planner(name, max_memory, **kw):
+ seen["devices"] = sorted(max_memory)
+ return _SizedPlan(1.2, devices = sorted(max_memory))
+
+ ns = _load(devices = 4, planner = planner)
+ device_map = ns["resolve_unsloth_device_map"](
+ "unsloth", "m", planner_kwargs = {"max_memory": {3: "14GiB", 2: "14GiB"}}
+ )
+ assert seen["devices"] == [2, 3]
+ assert device_map == {"": 2}
+
+
+ "total_gib, transient_gib, single",
+ [
+ (11.0, 0.0, True), # 11.5 of 14.4 GiB: just under the 80% line
+ (11.2, 0.0, False),
+ (10.0, 1.5, False), # the load transient counts too
+ ],
+)
+def test_the_single_card_line_is_a_fifth_of_the_card_free(total_gib, transient_gib, single):
+ plan = _SizedPlan(total_gib, transient_gib = transient_gib)
+ ns = _load(planner = lambda name, **kw: plan)
+ expected = {"": 0} if single else plan.device_map
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == expected
+
+
+def test_a_plan_without_sizes_is_used_as_before():
+ """An older unsloth_zoo whose plan carries no sizes keeps its split."""
+ plan = _Plan({"model.layers.0": 0, "lm_head": 1})
+ ns = _load(planner = lambda name, **kw: plan)
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == plan.device_map
+
+
+def test_a_model_too_big_for_one_card_is_still_planned():
+ plan = _SizedPlan(13.0)
+ ns = _load(planner = lambda name, **kw: plan)
+ assert ns["resolve_unsloth_device_map"]("unsloth", "m") == plan.device_map
+
+
+def test_balanced_still_splits_a_small_model():
+ plan = _SizedPlan(1.2)
+ ns = _load(planner = lambda name, **kw: plan)
+ assert ns["resolve_unsloth_device_map"]("unsloth_balanced", "m") == plan.device_map
+
+
+ "planner_kwargs, single",
+ [
+ (None, True), # an auto-derived reserve stays the planner's business
+ ({"activation_reserve_bytes": 4 * 2**30}, True),
+ ({"activation_reserve_bytes": 6 * 2**30}, False),
+ ],
+)
+def test_a_reserve_the_caller_passed_is_kept_on_the_single_card(planner_kwargs, single):
+ plan = _SizedPlan(
+ 9.7,
+ reserve_gib = 6.0
+ if planner_kwargs is None
+ else planner_kwargs["activation_reserve_bytes"] / 2**30,
+ )
+ ns = _load(planner = lambda name, **kw: plan)
+ got = ns["resolve_unsloth_device_map"]("unsloth", "m", planner_kwargs = planner_kwargs)
+ assert got == ({"": 0} if single else plan.device_map)
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 9b8acdf4168..2873ff70dff 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -7519,31 +7519,34 @@ def disable_torchcodec_if_broken():
their existing except ImportError handlers cleanly.
"""
mismatch_hint = _torchcodec_version_mismatch_hint()
- if mismatch_hint is not None:
+
+ def _warn_mismatch():
+ if mismatch_hint is None:
+ return
try:
import warnings
- warnings.warn(mismatch_hint, stacklevel = 2)
+ warnings.warn(mismatch_hint, stacklevel = 3)
except Exception:
# Warning filters promoted to errors (PYTHONWARNINGS=error, pytest -W error) must not abort the
# disable fallback below.
pass
+
try:
import importlib.util
if importlib.util.find_spec("torchcodec") is None:
+ _warn_mismatch()
return # absent or already disabled
# RuntimeError on dlopen failure, OSError on chained libavutil.so misses, and a damaged or
# version-skewed wheel can raise anything else; the package is present, so every shape is "broken".
from torchcodec.decoders import AudioDecoder
except Exception as load_error:
- if mismatch_hint is None:
+ remedy_hint = mismatch_hint
+ if remedy_hint is None:
# Versions agree, so the load failed for another reason. A mismatched accelerator
# build is the one this can still name, and the one pinning the index repairs.
try:
- provenance_hint = _torchcodec_provenance_hint()
- if provenance_hint is not None:
- import warnings
- warnings.warn(provenance_hint, stacklevel = 2)
+ remedy_hint = _torchcodec_provenance_hint()
except Exception:
pass # a diagnostic must never abort the disable fallback below
# transformers: flip the flag (<5) and/or rebind the lru_cache'd func (>=5).
@@ -7594,9 +7597,15 @@ def disable_torchcodec_if_broken():
if decodes
else "audio datasets will not decode until soundfile and PyAV are installed (pip install soundfile av)"
)
- warnings.warn(f"Unsloth: torchcodec is installed but {note}; {tail}.", stacklevel = 2)
+ # One warning per broken codec; the version remedy rides along.
+ remedy = f" {remedy_hint}" if remedy_hint is not None else ""
+ warnings.warn(
+ f"Unsloth: torchcodec is installed but {note}; {tail}.{remedy}", stacklevel = 2
+ )
except Exception:
pass # a report must never abort the disable fallback above
+ else:
+ _warn_mismatch()
def _audio_av_open(av, source):
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 4db94fc7342..c9288cd1a49 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -246,6 +246,7 @@ def _patch_transformers_trainer_data_parallel():
except (ImportError, ModuleNotFoundError):
return False
+ _patch_trainer_init_data_parallel(Trainer)
original_wrap_model = getattr(Trainer, "_wrap_model", None)
if original_wrap_model is None:
return False
@@ -297,6 +298,50 @@ def _patch_transformers_trainer_data_parallel():
return True
+def _keep_unsloth_models_off_data_parallel(model, args):
+ """`args._n_gpu = 1` for a marked Unsloth model, as the TRL trainers do; True if changed.
+ Before Trainer.__init__: it sizes the batch from n_gpu, too early for `_wrap_model`."""
+ try:
+ if args is None or model is None or not hasattr(model, "modules"):
+ return False
+ if getattr(args, "n_gpu", 1) <= 1 or getattr(model, "is_loaded_in_8bit", False):
+ return False
+ from transformers.training_args import ParallelMode
+
+ if getattr(args, "parallel_mode", None) != ParallelMode.NOT_DISTRIBUTED:
+ return False
+ if not any(
+ getattr(module, "_unsloth_disable_data_parallel", False) for module in model.modules()
+ ):
+ return False
+ args._n_gpu = 1
+ return True
+ except Exception:
+ return False
+
+
+def _patch_trainer_init_data_parallel(Trainer):
+ # Every marked path, not only the ones that call patch_gradient_accumulation_fix (fast encoders).
+ if getattr(Trainer, "_unsloth_data_parallel_init_patched", False):
+ return
+ original_init = Trainer.__init__
+
+ @functools.wraps(original_init)
+ def _unsloth_data_parallel_init(self, *args, **kwargs):
+ model = kwargs.get("model", args[0] if len(args) > 0 else None)
+ training_args = kwargs.get("args", args[1] if len(args) > 1 else None)
+ _keep_unsloth_models_off_data_parallel(model, training_args)
+ original_init(self, *args, **kwargs)
+ # Args the Trainer built itself; refresh the batch size it cached.
+ if _keep_unsloth_models_off_data_parallel(
+ getattr(self, "model", None), getattr(self, "args", None)
+ ):
+ self._train_batch_size = self.args.train_batch_size
+
+ Trainer.__init__ = _unsloth_data_parallel_init
+ Trainer._unsloth_data_parallel_init_patched = True
+
+
def _mark_unsloth_disable_data_parallel(model, disable = True):
if disable:
_patch_transformers_trainer_data_parallel()
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 8d7ad339cdb..456e7e40463 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -554,6 +554,29 @@ def resolve_unsloth_device_map(
print(f"Unsloth: Not planning a device map; {reason}. Using `{_declined}`.")
return _declined
+ def _plan_fits_first_device(
+ plan,
+ explicit_reserve,
+ activation_share = 0.2,
+ ):
+ """First allowed card if weights + headroom + load transient leave `activation_share` (about
+ Gemma 3n E4B fp32 on a T4) and any passed reserve free; None for a planner without sizes."""
+ try:
+ budgets = plan.raw_budgets
+ first = min(budgets)
+ budget = int(budgets[first])
+ transient = max((plan.load_transient_by_device or {}).values(), default = 0)
+ need = int(plan.total_weight_bytes) + int(plan.headroom_bytes) + int(transient)
+ free = budget * activation_share
+ if explicit_reserve:
+ # A passed reserve is a hard constraint to the planner.
+ free = max(free, int(plan.activation_reserve_by_device.get(first, 0)))
+ except Exception:
+ return None
+ if budget > 0 and need + free <= budget:
+ return first
+ return None
+
if skip_reason is not None:
return _fallback(skip_reason)
if fast_inference:
@@ -639,6 +662,18 @@ def resolve_unsloth_device_map(
if plan is None:
return _declined
+ single_device = (
+ _plan_fits_first_device(plan, planner_kwargs.get("activation_reserve_bytes") is not None)
+ if device_map == UNSLOTH_DEVICE_MAP
+ else None
+ )
+ if single_device is not None:
+ # Splitting a model one card holds only adds cross-device bugs (Kaggle T4x2).
+ print(
+ f"Unsloth: Not splitting across GPUs; the model fits on cuda:{single_device} with room "
+ f'to train. Pass device_map = "{UNSLOTH_BALANCED_DEVICE_MAP}" to split it anyway.'
+ )
+ return {"": single_device}
print(plan.describe())
return plan.device_map
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 061e6ef3c7a..f4fbc849253 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -456,8 +456,10 @@ _ONLINE_DPO_MODEL_CALL = re.compile(
r"(?P<kwargs>attention_mask=prompt_completion_mask|\*\*model_kwargs)\)[ \t]*$",
flags = re.MULTILINE,
)
+# TRL 0.18-0.19 slice from `prompt_ids.size(1) - 1`, TRL 0.20+ name it start_idx.
_ONLINE_DPO_LOGITS_SLICE = re.compile(
- r"^(?P<indent>[ \t]*)(?P<line>logits = output\.logits\[:, start_idx:(?:end_idx|-1)\])[ \t]*$",
+ r"^(?P<indent>[ \t]*)(?P<line>logits = output\.logits\[:, "
+ r"(?P<start>start_idx|prompt_ids\.size\(1\) - 1) ?: ?(?:end_idx|-1)\])[ \t]*$",
flags = re.MULTILINE,
)
@@ -494,7 +496,7 @@ def online_dpo_trainer__forward(function_name, function):
j = logits_slice.group("indent")
gather = (
f"{j}if _unsloth_left_pad is not None:\n"
- f"{j} _unsloth_index = (start_idx - _unsloth_left_pad).unsqueeze(1) + torch.arange(\n"
+ f"{j} _unsloth_index = ({logits_slice.group('start')} - _unsloth_left_pad).unsqueeze(1) + torch.arange(\n"
f"{j} completion_ids.size(1), device = completion_ids.device\n"
f"{j} ).unsqueeze(0)\n"
f"{j} _unsloth_index = _unsloth_index.clamp(0, output.logits.size(1) - 1)\n"
diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.py
index a33cd505986..99ad8940d70 100644
--- a/unsloth/models/sentence_transformer.py
+++ b/unsloth/models/sentence_transformer.py
@@ -3029,6 +3029,9 @@ class FastSentenceTransformer(FastModel):
)
peft_model = peft_get_peft_model(inner_model, lora_config)
+ from ._utils import _mark_unsloth_disable_data_parallel
+
+ _mark_unsloth_disable_data_parallel(peft_model)
qat_scheme = kwargs.get("qat_scheme", None)
if qat_scheme is not None:
@@ -3374,6 +3377,42 @@ def _patch_pooling_float16_accumulation():
Pooling._unsloth_float16_pooling = True
+def _patch_dense_input_dtype():
+ """Cast Dense input to its weight dtype: the float32 pooled vector meets float16 Dense
+ weights (EmbeddingGemma on T4), which F.linear refuses without autocast."""
+ try:
+ from sentence_transformers.models import Dense
+ except Exception:
+ return
+ if getattr(Dense, "_unsloth_input_dtype", False):
+ return
+ _original_forward = Dense.forward
+
+ def forward(self, features, *args, **kwargs):
+ key = getattr(self, "module_input_name", "sentence_embedding")
+ weight = getattr(getattr(self, "linear", None), "weight", None)
+ x = features.get(key, None) if hasattr(features, "get") else None
+ if not (
+ torch.is_tensor(x)
+ and torch.is_tensor(weight)
+ and x.is_floating_point()
+ and x.dtype != weight.dtype
+ and not torch.is_autocast_enabled(x.device.type)
+ ):
+ return _original_forward(self, features, *args, **kwargs)
+ features[key] = x.to(weight.dtype)
+ try:
+ return _original_forward(self, features, *args, **kwargs)
+ finally:
+ if getattr(self, "module_output_name", key) != key:
+ features[key] = x
+
+ forward.__wrapped__ = _original_forward
+ Dense.forward = forward
+ Dense._unsloth_input_dtype = True
+
+
_patch_sentence_transformer_trainer()
_patch_st_trainer_load_from_checkpoint()
_patch_pooling_float16_accumulation()
+_patch_dense_input_dtype()