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
torchrun: plain Trainer DDP find_unused default, FSDP2-collective SentenceTransformer save (#15324)
Daniel Hane0a8f07846b6
diff --git a/tests/python/_plain_trainer_ddp_gc_worker.py b/tests/python/_plain_trainer_ddp_gc_worker.pynew file mode 100644index 00000000000..ea8d27c6143--- /dev/null+++ b/tests/python/_plain_trainer_ddp_gc_worker.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""One gloo rank for test_plain_trainer_ddp_gc.py. No unsloth import at module level: a spawned rank must set up the GPU-free harness first."""++from __future__ import annotations++import os+import runpy+import tempfile+++def run_rank(rank, port, cases, queue):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ LOCAL_RANK = str(rank),+ WORLD_SIZE = "2",+ LOCAL_WORLD_SIZE = "2",+ ACCELERATE_USE_CPU = "true",+ )+ runpy.run_path(+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "conftest.py")+ )+ import torch++ torch.set_num_threads(1)+ import unsloth # noqa: F401+ import peft+ import transformers+ from unsloth.models._utils import patch_gradient_accumulation_fix++ # What FastLanguageModel / FastModel.from_pretrained installs on transformers.Trainer.+ patch_gradient_accumulation_fix(transformers.Trainer)++ out = {}+ try:+ for name, trainer_name, user_value in cases:+ torch.manual_seed(0)+ config = transformers.LlamaConfig(+ vocab_size = 64,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ )+ model = transformers.LlamaForCausalLM(config)+ # Reentrant checkpointing armed on the model (Unsloth's get_peft_model does this), not in the args.+ model.gradient_checkpointing_enable(+ gradient_checkpointing_kwargs = {"use_reentrant": True}+ )+ model.enable_input_require_grads()+ model = peft.get_peft_model(+ model,+ peft.LoraConfig(+ r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj", "gate_proj"]+ ),+ )+ g = torch.Generator().manual_seed(7)+ rows = []+ for _ in range(8):+ ids = torch.randint(1, 64, (12,), generator = g)+ rows.append(+ {"input_ids": ids, "attention_mask": torch.ones_like(ids), "labels": ids}+ )+ extra = {} if user_value is None else {"ddp_find_unused_parameters": user_value}+ args_cls = (+ transformers.Seq2SeqTrainingArguments+ if trainer_name == "Seq2SeqTrainer"+ else transformers.TrainingArguments+ )+ args = args_cls(+ output_dir = tempfile.mkdtemp(prefix = "ddp_gc_"),+ per_device_train_batch_size = 2,+ max_steps = 2,+ learning_rate = 1e-2,+ use_cpu = True,+ report_to = "none",+ save_strategy = "no",+ logging_steps = 1,+ dataloader_num_workers = 0,+ **extra,+ )+ trainer = getattr(transformers, trainer_name)(+ model = model, args = args, train_dataset = rows+ )+ error = None+ try:+ trainer.train()+ except RuntimeError as e:+ error = str(e).splitlines()[0] or type(e).__name__+ ddp = trainer.model_wrapped+ out[name] = dict(+ error = error,+ find_unused = getattr(ddp, "find_unused_parameters", None),+ is_ddp = isinstance(ddp, torch.nn.parallel.DistributedDataParallel),+ args_value = args.ddp_find_unused_parameters,+ losses = [h["loss"] for h in trainer.state.log_history if "loss" in h],+ )+ if error is not None:+ # A rank that raised leaves the group unusable for the next case.+ break+ queue.put((rank, out))+ except BaseException:+ import traceback+ queue.put((rank, {"error": traceback.format_exc()}))+ raise+ if not any(case.get("error") for case in out.values()):+ import torch.distributed as dist+ if dist.is_initialized():+ dist.destroy_process_group()diff --git a/tests/python/_st_fsdp2_save_worker.py b/tests/python/_st_fsdp2_save_worker.pynew file mode 100644index 00000000000..b2c0dfbce15--- /dev/null+++ b/tests/python/_st_fsdp2_save_worker.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""One gloo rank for test_sentence_transformer_fsdp2_save.py. No unsloth import at module level: a spawned rank must set up the GPU-free harness first."""++from __future__ import annotations++import os+import runpy+++def _files(path):+ out = {}+ for root, _, names in os.walk(path):+ for name in names:+ full = os.path.join(root, name)+ with open(full, "rb") as f:+ out[os.path.relpath(full, path)] = f.read()+ return out+++def run_rank(rank, port, checkpoint, out_dir, queue):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ LOCAL_RANK = str(rank),+ WORLD_SIZE = "2",+ LOCAL_WORLD_SIZE = "2",+ ACCELERATE_USE_CPU = "true",+ UNSLOTH_FSDP2 = "1",+ )+ runpy.run_path(+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "conftest.py")+ )+ import torch+ import torch.distributed as dist++ torch.set_num_threads(1)+ from sentence_transformers import SentenceTransformer+ from sentence_transformers.models import Pooling, Transformer++ import unsloth # noqa: F401+ from unsloth import FastSentenceTransformer+ from unsloth.models.fsdp2_native import FSDP2Config, shard_model++ dist.init_process_group("gloo", rank = rank, world_size = 2)+ result = {}+ try:+ torch.manual_seed(0)+ transformer = Transformer(checkpoint)+ model = SentenceTransformer(+ modules = [transformer, Pooling(transformer.get_word_embedding_dimension())],+ device = "cpu",+ )+ # The fast encoder route from_pretrained takes for BERT-family models.+ model._unsloth_fast_encoder = True+ model._compile_mode = None+ model = FastSentenceTransformer.get_peft_model(+ model,+ r = 4,+ lora_alpha = 8,+ target_modules = ["query", "key", "value", "dense"],+ use_gradient_checkpointing = False,+ )+ # Non-zero, rank-independent adapters so the saved bytes are not just the init.+ g = torch.Generator().manual_seed(1)+ with torch.no_grad():+ for name, p in model.named_parameters():+ if p.requires_grad:+ p.copy_(torch.randn(p.shape, generator = g) * 0.1)+ reference = os.path.join(out_dir, "one_process")+ if rank == 0:+ # Not sharded yet: the plain single-process save. ST's first save sets the tokenizer's+ # truncation (its model card tokenizes), so compare against a second one, as the FSDP2 one is.+ model.save_pretrained(os.path.join(out_dir, "warm"))+ model.save_pretrained(reference)+ dist.barrier()+ shard_model(model, FSDP2Config(device = "cpu", reshard_after_forward = True))+ n_sharded = sum(type(p).__name__ == "DTensor" for p in model.parameters())+ # A training-style forward / backward first (no optimizer step: the weights stay the reference's).+ ids = torch.randint(2, 64, (4, 8), generator = torch.Generator().manual_seed(rank))+ emb = model({"input_ids": ids, "attention_mask": torch.ones_like(ids)})[+ "sentence_embedding"+ ]+ emb.float().pow(2).mean().backward()+ # The model card's usage snippet (a forward) must be computed again, collectively, by this save.+ model.model_card_data.similarities = None+ error = None+ returned = "unset"+ try:+ returned = model.save_pretrained(os.path.join(out_dir, "fsdp2"))+ except Exception as e:+ error = f"{type(e).__name__}: {str(e).splitlines()[0] if str(e) else ''}"+ result = dict(+ error = error,+ returned_none = returned is None,+ n_sharded = n_sharded,+ still_sharded = sum(type(p).__name__ == "DTensor" for p in model.parameters()),+ )+ if error is None:+ # The native FSDP2 Trainer.save_model hook, with a trainer whose _save is+ # SentenceTransformerTrainer's: model.save_pretrained(output_dir).+ import types++ import transformers+ from unsloth.models.fsdp2_native import install_native_fsdp2_hooks++ install_native_fsdp2_hooks()+ trainer = types.SimpleNamespace(+ model = model,+ args = types.SimpleNamespace(should_save = rank == 0, push_to_hub = False),+ is_fsdp_enabled = False,+ )+ trainer._save = lambda output_dir = None, state_dict = None: trainer.model.save_pretrained(+ output_dir+ )+ model.model_card_data.similarities = None+ transformers.Trainer.save_model(trainer, os.path.join(out_dir, "trainer"))+ dist.barrier()+ if rank == 0:+ result["reference"] = _files(reference)+ result["fsdp2"] = _files(os.path.join(out_dir, "fsdp2"))+ result["trainer"] = _files(os.path.join(out_dir, "trainer"))+ queue.put((rank, result))+ except BaseException:+ import traceback+ queue.put((rank, {"error": traceback.format_exc()}))+ raise+ if result.get("error") is None:+ dist.destroy_process_group()diff --git a/tests/python/test_plain_trainer_ddp_gc.py b/tests/python/test_plain_trainer_ddp_gc.pynew file mode 100644index 00000000000..7e22546224c--- /dev/null+++ b/tests/python/test_plain_trainer_ddp_gc.py@@ -0,0 +1,89 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""A plain transformers Trainer (and Seq2SeqTrainer) on a LoRA model with reentrant gradient+checkpointing must train under DDP: Unsloth picks find_unused_parameters = False as it does for its+TRL trainers, where transformers' True fails with "marked as ready twice". An explicit value is kept."""++from __future__ import annotations++import os+import queue as queue_module+import socket+import sys++import pytest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # spawned ranks inherit sys.path+import _plain_trainer_ddp_gc_worker as worker # noqa: E402++pytest.importorskip("peft")+pytest.importorskip("accelerate")+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "two gloo ranks over TCP localhost")+++def _failed(results):+ """A rank that raised (in backward, in the save) can leave its peer blocked in a collective:+ once one has, wait only briefly for the other."""+ return any(+ out.get("error") or any(isinstance(c, dict) and c.get("error") for c in out.values())+ for out in results.values()+ )+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _run(cases):+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ queue = ctx.Queue()+ port = _free_port()+ procs = [ctx.Process(target = worker.run_rank, args = (r, port, cases, queue)) for r in range(2)]+ for p in procs:+ p.start()+ results = {}+ try:+ while len(results) < len(procs):+ try:+ rank, out = queue.get(timeout = 60 if _failed(results) else 600)+ except queue_module.Empty:+ break+ results[rank] = out+ finally:+ for p in procs:+ p.join(5 if len(results) < len(procs) else 120)+ if p.is_alive():+ p.kill()+ assert results, "no rank reported"+ for out in results.values():+ assert "error" not in out, out.get("error")+ return results+++def test_plain_trainers_train_under_ddp_with_reentrant_checkpointing():+ results = _run([("trainer", "Trainer", None), ("seq2seq", "Seq2SeqTrainer", None)])+ for rank in results:+ for name in ("trainer", "seq2seq"):+ case = results[rank].get(name)+ assert case is not None, (rank, name, results[rank])+ assert case["error"] is None, (rank, name, case["error"])+ assert case["is_ddp"] and case["find_unused"] is False+ assert case["args_value"] is False+ assert len(case["losses"]) == 2+ assert sorted(results) == [0, 1]+ # DDP averages the gradients: both ranks log the same losses.+ assert results[0]["trainer"]["losses"] == results[1]["trainer"]["losses"]+++def test_explicit_user_value_is_kept():+ results = _run([("user_true", "Trainer", True)])+ for rank in results:+ case = results[rank]["user_true"]+ assert case["args_value"] is True+ assert case["find_unused"] is True+ # The user's choice is honoured, so the reentrant checkpointing failure is theirs to see.+ assert case["error"] is not None and "ready" in case["error"], case["error"]diff --git a/tests/python/test_sentence_transformer_fsdp2_save.py b/tests/python/test_sentence_transformer_fsdp2_save.pynew file mode 100644index 00000000000..bf6b5fac2c0--- /dev/null+++ b/tests/python/test_sentence_transformer_fsdp2_save.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""A FastSentenceTransformer LoRA model sharded by native FSDP2 (UNSLOTH_FSDP2=1) must save like one+process: every rank calls save_pretrained, rank 0 writes the gathered weights, and the folder equals,+byte for byte, a single-process save of the same weights."""++from __future__ import annotations++import os+import queue as queue_module+import socket+import sys++import pytest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # spawned ranks inherit sys.path+import _st_fsdp2_save_worker as worker # noqa: E402++pytest.importorskip("sentence_transformers")+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "two gloo ranks over TCP localhost")+++def _failed(results):+ """A rank that raised (in backward, in the save) can leave its peer blocked in a collective:+ once one has, wait only briefly for the other."""+ return any(+ out.get("error") or any(isinstance(c, dict) and c.get("error") for c in out.values())+ for out in results.values()+ )+++def _free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _tiny_bert(path):+ import torch+ from tokenizers import Tokenizer+ from tokenizers.models import WordLevel+ from tokenizers.pre_tokenizers import Whitespace+ from transformers import BertConfig, BertModel, PreTrainedTokenizerFast++ torch.manual_seed(0)+ BertModel(+ BertConfig(+ vocab_size = 64,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ max_position_embeddings = 40,+ hidden_dropout_prob = 0.0,+ attention_probs_dropout_prob = 0.0,+ ),+ add_pooling_layer = False,+ ).save_pretrained(path)+ vocab = {f"w{i}": i for i in range(2, 64)}+ vocab.update({"[PAD]": 0, "[UNK]": 1})+ tokenizer = Tokenizer(WordLevel(vocab, unk_token = "[UNK]"))+ tokenizer.pre_tokenizer = Whitespace()+ PreTrainedTokenizerFast(+ tokenizer_object = tokenizer, pad_token = "[PAD]", unk_token = "[UNK]", model_max_length = 32+ ).save_pretrained(path)+ return str(path)+++def test_fsdp2_sentence_transformer_save_equals_one_process(tmp_path):+ import torch.multiprocessing as mp++ checkpoint = _tiny_bert(tmp_path / "bert")+ ctx = mp.get_context("spawn")+ queue = ctx.Queue()+ port = _free_port()+ procs = [+ ctx.Process(target = worker.run_rank, args = (r, port, checkpoint, str(tmp_path), queue))+ for r in range(2)+ ]+ for p in procs:+ p.start()+ results = {}+ try:+ while len(results) < len(procs):+ try:+ rank, out = queue.get(timeout = 60 if _failed(results) else 600)+ except queue_module.Empty:+ break+ results[rank] = out+ finally:+ for p in procs:+ p.join(5 if len(results) < len(procs) else 120)+ if p.is_alive():+ p.kill()+ assert results, "no rank reported"+ for rank, out in sorted(results.items()):+ assert out["error"] is None, (rank, out["error"])+ assert sorted(results) == [0, 1]+ for rank in (0, 1):+ assert results[rank]["n_sharded"] > 0+ # The gather put the shards back afterwards.+ assert results[rank]["still_sharded"] == results[rank]["n_sharded"]+ assert results[1]["returned_none"]+ reference, fsdp2 = results[0]["reference"], results[0]["fsdp2"]+ assert any(name.endswith("adapter_model.safetensors") for name in reference)+ assert sorted(fsdp2) == sorted(reference)+ for name in reference:+ assert fsdp2[name] == reference[name], name+ # Trainer.save_model (checkpoints, SentenceTransformerTrainer._save -> save_pretrained) writes the same.+ assert results[0]["trainer"] == fsdp2diff --git a/tests/test_ddp_find_unused_default.py b/tests/test_ddp_find_unused_default.pyindex 0a107b974ab..c894dbf8138 100644--- a/tests/test_ddp_find_unused_default.py+++ b/tests/test_ddp_find_unused_default.py@@ -128,6 +128,7 @@ def test_skippable_models_keep_transformers_default(ddp_env, make):{"encoder_layerdrop": 0.1},{"decoder_layerdrop": 0.1},{"add_cross_attention": True},+ {"cross_attention_layers": [3, 8]}, # MllamaTextConfig: layers skipped without images{"speech_encoder_layerdrop": 0.1},{"is_encoder_decoder": True},],diff --git a/unsloth/models/_ddp_defaults.py b/unsloth/models/_ddp_defaults.pyindex be85c87661b..d3a31d47049 100644--- a/unsloth/models/_ddp_defaults.py+++ b/unsloth/models/_ddp_defaults.py@@ -91,6 +91,9 @@ def _config_may_skip(config):# Optional cross-attention (GPT-2 style) only runs when encoder states are passed.if getattr(c, "add_cross_attention", False) and not getattr(c, "is_encoder_decoder", False):return True+ # Mllama text: its cross-attention decoder layers are skipped without image states.+ if getattr(c, "cross_attention_layers", None):+ return True# layerdrop, encoder_layerdrop, decoder_layerdrop, speech_encoder_layerdrop, ...for key, value in getattr(c, "__dict__", {}).items():if (diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 816820cddf6..381601b51c3 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -6053,6 +6053,19 @@ def patch_gradient_accumulation_fix(Trainer):model_init = bound["model_init"],optimizer_cls_and_kwargs = bound["optimizer_cls_and_kwargs"],)+ # The generated TRL trainers already do this (rl.py); plain Trainer / Seq2SeqTrainer / other+ # subclasses need it too. Before init: transformers 5 builds the DDP kwargs in __init__.+ if model is not None:+ try:+ from ._ddp_defaults import unsloth_default_ddp_find_unused_parameters+ unsloth_default_ddp_find_unused_parameters(+ kwargs["args"]+ if "args" in kwargs+ else (args[1] if len(args) > 1 else None),+ model,+ )+ except Exception:+ pass_original_trainer_init(self, *args, **kwargs)if native_fsdp2:native_fsdp2_trainer_setup(self, phase = "post")diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 8ecbd9099e2..f6d61eca61f 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -3089,6 +3089,14 @@ def _install_trainer_hooks():with fsdp2_gathered(root, trainable_only = True, include = include) as writer:if writer is not False and _trainer_save_writer(self, root)[0]:_save_unwrapped(self, root, output_dir)+ elif getattr(getattr(type(root), "save", None), "_unsloth_fsdp2_collective", False):+ # A SentenceTransformer (FastSentenceTransformer): its trainer's _save ignores a state_dict+ # and calls model.save_pretrained, so gather here; the collective save then just writes.+ from .fsdp2_save import fsdp2_gathered+ from .sentence_transformer import fsdp2_st_usage_snippet+ with fsdp2_st_usage_snippet(root), fsdp2_gathered(root) as writer:+ if writer is not False and _trainer_save_writer(self, root)[0]:+ _save_unwrapped(self, root, output_dir)else:from .fsdp2_save import _dist, _wait_for_writer, writes_off_rank0diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex da271ce1029..670d31d48e0 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -71,12 +71,91 @@ unsloth_save_pretrained_gguf._unsloth_deferred_shim = Trueimport contextlib+import functoolsimport shutil_CREATE_TRANSFORMER_MODULE_LOCK = threading.RLock()+def fsdp2_st_usage_snippet(model):+ """Collective (every rank enters) around an FSDP2 SentenceTransformer save. The model card's usage+ snippet encodes example sentences, and a forward of a sharded model is collective: run it here on+ every rank (same inputs, same result), so the writer's card reuses it instead of a forward only rank+ 0 would enter. `encode` moves the model to its own device first, which a DTensor parameter refuses+ to be swapped for, so that move is skipped (the model is already there)."""+ card = getattr(model, "model_card_data", None)+ run = getattr(card, "run_usage_snippet", None)+ if not callable(run) or "run_usage_snippet" in getattr(card, "__dict__", {}):+ yield+ return+ from .fsdp2_native import native_fsdp2_unsharded++ model.__dict__["to"] = lambda *args, **kwargs: model+ try:+ # Whole weights on every rank for the snippet: older sentence-transformers' encode calls+ # self.forward, which skips the root unit's FSDP2 hooks.+ with native_fsdp2_unsharded(model):+ run()+ except Exception as exc:+ print(f"Unsloth: FSDP2 save: model card usage snippet not computed ({exc}).")+ finally:+ model.__dict__.pop("to", None)+ card.__dict__["run_usage_snippet"] = lambda *args, **kwargs: None+ try:+ yield+ finally:+ card.__dict__.pop("run_usage_snippet", None)+++def _install_fsdp2_collective_st_save(SentenceTransformer):+ """Under native FSDP2 (UNSLOTH_FSDP2=1) the encoder's weights are DTensor shards, and ST's `save`+ (behind `save_pretrained` and the Trainer's `_save`) reads them directly, on every rank, into the+ same folder. Make it collective, like the causal LM `save_pretrained`: every rank calls it, the+ shards are gathered to rank 0, which writes; the others return None. Idempotent, and a model FSDP2+ does not shard is passed straight through."""+ original = getattr(SentenceTransformer, "save", None)+ if original is None or getattr(original, "_unsloth_fsdp2_collective", False):+ return++ def plainly_named(self, args, kwargs):+ # The model card prints the architecture: name the modules as one process would, not+ # FSDP2's FSDP<Name> subclasses.+ renamed = []+ for module in self.modules():+ cls = type(module)+ if cls.__name__.startswith("FSDP") and "_get_name" not in module.__dict__:+ plain = next((c for c in cls.__mro__[1:] if not c.__name__.startswith("FSDP")), cls)+ module.__dict__["_get_name"] = lambda name = plain.__name__: name+ renamed.append(module)+ try:+ return original(self, *args, **kwargs)+ finally:+ for module in renamed:+ module.__dict__.pop("_get_name", None)++ @functools.wraps(original)+ def save(self, *args, **kwargs):+ from .fsdp2_save import fsdp2_gather_active, fsdp2_gathered, fsdp2_units++ if not fsdp2_units(self):+ return original(self, *args, **kwargs)+ if fsdp2_gather_active():+ # The writer inside a gather already made (Trainer.save_model under native FSDP2, which+ # also ran fsdp2_st_usage_snippet on every rank).+ return plainly_named(self, args, kwargs)+ # Every parameter, not just the trainable ones: ST writes its other modules (Dense, ...) too,+ # and embedding models are small.+ with fsdp2_st_usage_snippet(self), fsdp2_gathered(self) as writer:+ if writer is False:+ return None+ return plainly_named(self, args, kwargs)++ save._unsloth_fsdp2_collective = True+ SentenceTransformer.save = save++def _ensure_sentence_attention_masks(model):"""Match Gemma3's advertised backend to its patched SDPA implementation."""config = getattr(model, "config", None)@@ -2402,6 +2481,7 @@ class FastSentenceTransformer(FastModel):try:from sentence_transformers import SentenceTransformerfrom sentence_transformers.models import Transformer, Pooling, Normalize+ _install_fsdp2_collective_st_save(SentenceTransformer)except ImportError:raise ImportError("Unsloth: To use `FastSentenceTransformer`, you must install `sentence-transformers`.\n"@@ -3037,6 +3117,8 @@ class FastSentenceTransformer(FastModel):from sentence_transformers import SentenceTransformerfrom peft import LoraConfig, get_peft_model as peft_get_peft_model+ _install_fsdp2_collective_st_save(SentenceTransformer)+if "task_type" not in kwargs:kwargs["task_type"] = "FEATURE_EXTRACTION"print("Setting task_type to FEATURE_EXTRACTION")