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
fix: preserve sentence encoder adapters and export dense 16bit weights (#14246)
cherry77-cloud1917996f806e
diff --git a/tests/test_st_merged_export_keeps_live_model.py b/tests/test_st_merged_export_keeps_live_model.pynew file mode 100644index 00000000000..63db369b104--- /dev/null+++ b/tests/test_st_merged_export_keeps_live_model.py@@ -0,0 +1,100 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+++"""The fast-encoder merged export must merge a copy and leave the live LoRA model training (unsloth#14246)."""++import ast+import copy+from pathlib import Path++import pytest+import torch++peft = pytest.importorskip("peft")+transformers = pytest.importorskip("transformers")++ST_PY = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "sentence_transformer.py"+++def _helper():+ src = ST_PY.read_text(encoding = "utf-8")+ node = [+ n+ for n in ast.parse(src).body+ if isinstance(n, ast.FunctionDef) and n.name == "_copy_sentence_encoder_for_merge"+ ]+ assert node, "_copy_sentence_encoder_for_merge not found"+ ns = {"copy": copy, "torch": torch}+ exec(ast.get_source_segment(src, node[0]), ns)+ return ns["_copy_sentence_encoder_for_merge"]+++class _FakeQuantBert(transformers.BertModel):+ """Takes the bitsandbytes rebuild branch on CPU: flagged 4bit, dequantize is a no-op."""++ def dequantize(self, dtype = None):+ return self+++def _bert(cls = transformers.BertModel):+ torch.manual_seed(0)+ cfg = transformers.BertConfig(+ vocab_size = 64,+ hidden_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ intermediate_size = 64,+ max_position_embeddings = 32,+ )+ return cls(cfg).eval()+++def _lora(base, init = True):+ cfg = peft.LoraConfig(+ r = 4,+ lora_alpha = 8,+ target_modules = ["query", "value"],+ init_lora_weights = init,+ task_type = "FEATURE_EXTRACTION",+ )+ model = peft.get_peft_model(base, cfg)+ with torch.no_grad():+ for name, p in model.named_parameters():+ if "lora_B" in name:+ p.normal_(0, 0.05)+ return model+++def _out(model, ids):+ with torch.no_grad():+ return model(input_ids = ids).last_hidden_state+++IDS = torch.tensor([[1, 5, 9, 13, 2, 7]])+++def test_live_adapters_survive_and_merged_copy_matches():+ live = _lora(_bert())+ params = {n: p for n, p in live.named_parameters() if "lora_" in n}+ expected = _out(live, IDS)+ merged = _helper()(live, torch.float32)+ assert isinstance(live, peft.PeftModel)+ assert {n: p for n, p in live.named_parameters() if "lora_" in n} == params+ assert not any("lora_" in n for n, _ in merged.named_parameters())+ torch.testing.assert_close(_out(merged, IDS), expected)+ torch.testing.assert_close(_out(live, IDS), expected)++[email protected]("init", [True, "olora"])+def test_quantized_rebuild_merges_the_trained_weights(init):+ base = _bert(_FakeQuantBert)+ base.is_loaded_in_4bit = True+ live = _lora(base, init)+ expected = _out(live, IDS)+ rng = torch.get_rng_state()+ merged = _helper()(live, torch.float32)+ assert torch.equal(torch.get_rng_state(), rng), "the export advanced the live run's RNG"+ assert isinstance(live, peft.PeftModel)+ assert not getattr(merged, "is_loaded_in_4bit", False)+ torch.testing.assert_close(_out(merged, IDS), expected, atol = 1e-5, rtol = 1e-4)diff --git a/tests/test_st_save_merged_signature.py b/tests/test_st_save_merged_signature.pyindex 915f8f16773..e9c4f687574 100644--- a/tests/test_st_save_merged_signature.py+++ b/tests/test_st_save_merged_signature.py@@ -19,6 +19,7 @@ import inspectfrom pathlib import Pathimport pytest+import torchREPO_ROOT = Path(__file__).resolve().parents[1]ST_PY = REPO_ROOT / "unsloth" / "models" / "sentence_transformer.py"@@ -158,6 +159,9 @@ def _extract(i):"os": __import__("os"),"print": lambda *a, **k: None,"_normalize_save_method": _normalize_save_method,+ "_copy_sentence_encoder_for_merge": lambda model, dtype: _Merged(),+ "copy": __import__("copy"),+ "torch": torch,"FastSentenceTransformer": type("F", (), {"_add_unsloth_branding": staticmethod(lambda d: branding.append(d))}),@@ -212,13 +216,26 @@ class _Module:self.auto_model = inner+class _Log(list):+ """Shared by a model and its export copy, so the copy's writes are visible here."""++ def __deepcopy__(self, memo):+ return self+++class _Merged:+ """What the fast-encoder path exports in place of the live transformer."""++class _FakeST:"""A SentenceTransformer stand-in: a sequence of modules, module 0 ofwhich wraps the transformer."""def __init__(self, no_modules = False):self.tokenizer = _Tok()- self.saved = []+ self.saved = _Log()+ self.saved_encoders = _Log()+ self._dtype = torch.float32self.inner = _Inner()self.no_modules = no_modulesself._modules_list = [_Module(self.inner)]@@ -228,6 +245,7 @@ class _FakeST:def save_pretrained(self, d):self.saved.append(d)+ self.saved_encoders.append(self[0].auto_model)def test_positional_call_completes_the_merge(tmp_path):@@ -238,8 +256,8 @@ def test_positional_call_completes_the_merge(tmp_path):tok = _Tok()fn(st, str(tmp_path), tok, "merged_16bit")assert st.saved == [str(tmp_path)]- assert st.inner.merged, "LoRA should have been merged away"- assert st.inner.saved == [str(tmp_path)]+ assert isinstance(st.saved_encoders[0], _Merged), "the export must carry the merged encoder"+ assert st[0].auto_model is st.inner and not st.inner.merged, "the live model keeps its LoRA"assert tok.saved == [str(tmp_path)], "the passed tokenizer must be used"assert branding == [str(tmp_path)]@@ -348,7 +366,10 @@ def test_case_and_space_variants_are_accepted(method, i, tmp_path):fn, _ = _extract(i)st = _FakeST(no_modules = True)fn(st, str(tmp_path), None, method)- assert st.inner.merged+ if i == 0:+ assert isinstance(st.saved_encoders[0], _Merged)+ else:+ assert st.inner.mergeddef test_normalization_leaves_non_strings_alone():diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 942ff5eb7eb..1cf1ce2b0ca 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -10,6 +10,7 @@# limitations under the License.import logging+import copyfrom .loader import FastModel, DISABLE_SDPA_MODEL_NAMESfrom .loader_utils import (@@ -183,6 +184,43 @@ def _normalize_save_method(save_method):return save_method+def _copy_sentence_encoder_for_merge(model, dtype):+ """Merge an independent encoder; never unload the training model's adapters."""+ from peft import PeftModel, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict++ model = copy.deepcopy(getattr(model, "_orig_mod", model))+ adapter_names = None+ if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False):+ # bnb LoRA merges requantize; merge into a dequantized base instead.+ adapters = []+ if isinstance(model, PeftModel):+ adapter_names = list(model.active_adapters)+ adapters = [+ (name, model.peft_config[name], get_peft_model_state_dict(model, adapter_name = name))+ for name in adapter_names+ ]+ model = model.unload()+ model = model.dequantize()+ model.is_loaded_in_4bit = False+ model.is_loaded_in_8bit = False+ model.to(dtype = dtype)+ devices = list(range(torch.cuda.device_count())) if torch.cuda.is_available() else []+ # Fresh adapter layers draw from the global RNG; keep the live run's stream untouched.+ with torch.random.fork_rng(devices = devices):+ for name, config, state in adapters:+ # Residual initializers (OLoRA, PiSSA, LoftQ) already rewrote the base; rerunning one subtracts it twice.+ config = copy.deepcopy(config)+ config.init_lora_weights = False+ if isinstance(model, PeftModel):+ model.add_adapter(name, config)+ else:+ model = get_peft_model(model, config, adapter_name = name)+ set_peft_model_state_dict(model, state, adapter_name = name)+ if hasattr(model, "merge_and_unload"):+ model = model.merge_and_unload(safe_merge = True, adapter_names = adapter_names)+ return model.to(dtype = dtype)++def _save_pretrained_torchao(self,save_directory,@@ -2592,20 +2630,19 @@ class FastSentenceTransformer(FastModel):f"supported for this SentenceTransformer; only "f"'merged_16bit' is.")- self.save_pretrained(save_directory)+ # Keep the load dtype; quantized weights dequantize into it.+ dtype = self._dtype if isinstance(self._dtype, torch.dtype) else torch.float16+ merged = _copy_sentence_encoder_for_merge(self[0].auto_model, dtype)+ exported = copy.deepcopy(self, {id(self[0].auto_model): merged})+ transformer = exported[0]+ # The adapter-save hook is bound to the live module; it would write its adapter config.+ if getattr(transformer, "_unsloth_save_config_patched", False):+ del transformer.save+ exported.save_pretrained(save_directory)if tokenizer is None:tokenizer = save_kwargs.pop("tokenizer", self.tokenizer)else:save_kwargs.pop("tokenizer", None)- if hasattr(self[0], "auto_model"):- inner = self[0].auto_model- if hasattr(inner, "_orig_mod"):- inner = inner._orig_mod- if hasattr(inner, "merge_and_unload"):- merged = inner.merge_and_unload()- merged.save_pretrained(save_directory)- elif hasattr(inner, "save_pretrained"):- inner.save_pretrained(save_directory)if tokenizer is not None:tokenizer.save_pretrained(save_directory)FastSentenceTransformer._add_unsloth_branding(save_directory)