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
Save models loaded from pre-quantized bitsandbytes checkpoints on transformers 5 (#13054)
Daniel Hancfdb966ba003
diff --git a/tests/test_bnb_prequantized_save.py b/tests/test_bnb_prequantized_save.pynew file mode 100644index 00000000000..8bd8d15cc0f--- /dev/null+++ b/tests/test_bnb_prequantized_save.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""save_pretrained after a pre-quantized bitsandbytes load on transformers 5.x (#638)."""++import os++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("transformers")++from unsloth.import_fixes import ( # noqa: E402+ _BNB_PREQUANTIZED_SAVE_FLAG,+ _bnb_deserialize_ops_without_reverse,+ fix_transformers_bnb_prequantized_save,+)+++def _modules():+ try:+ from transformers import core_model_loading, modeling_utils+ from transformers.integrations import bitsandbytes as bnb_integration+ except Exception:+ pytest.skip("this transformers has no core_model_loading")+ if not os.path.isfile(getattr(core_model_loading, "__file__", None) or ""):+ pytest.skip("core_model_loading is unsloth's transformers 4.x stand-in")+ if not hasattr(bnb_integration, "Bnb4bitDeserialize"):+ pytest.skip("this transformers has no Bnb4bitDeserialize")+ return core_model_loading, modeling_utils, bnb_integration+++def _tiny_llama():+ from transformers import LlamaConfig, LlamaForCausalLM+ config = LlamaConfig(+ vocab_size = 32,+ hidden_size = 16,+ intermediate_size = 32,+ num_hidden_layers = 1,+ num_attention_heads = 2,+ num_key_value_heads = 2,+ )+ return LlamaForCausalLM(config)+++def _bnb_converter(bnb_integration, core_model_loading):+ return core_model_loading.WeightConverter(+ source_patterns = [+ "weight.nested_absmax",+ "weight.nested_quant_map",+ "weight.quant_map",+ "weight.absmax",+ "weight.quant_state.bitsandbytes__nf4",+ "weight.quant_state.bitsandbytes__fp4",+ "weight",+ ],+ target_patterns = "weight",+ operations = [bnb_integration.Bnb4bitDeserialize(None)],+ )+++def _unwrapped(fn):+ while getattr(fn, _BNB_PREQUANTIZED_SAVE_FLAG, False):+ fn = fn.__wrapped__+ return fn+++def test_upstream_revert_raises_on_bnb_converter():+ core_model_loading, _, bnb_integration = _modules()+ if not _bnb_deserialize_ops_without_reverse():+ pytest.skip("this transformers implements Bnb4bitDeserialize.reverse_op")+ model = _tiny_llama()+ model._weight_conversions = [_bnb_converter(bnb_integration, core_model_loading)]+ original = _unwrapped(core_model_loading.revert_weight_conversion)+ with pytest.raises(NotImplementedError):+ original(model, model.state_dict())+++def test_patched_revert_skips_bnb_converter_and_keeps_others():+ core_model_loading, modeling_utils, bnb_integration = _modules()+ if not _bnb_deserialize_ops_without_reverse():+ pytest.skip("this transformers implements Bnb4bitDeserialize.reverse_op")+ fix_transformers_bnb_prequantized_save()+ fix_transformers_bnb_prequantized_save()+ patched = core_model_loading.revert_weight_conversion+ assert getattr(patched, _BNB_PREQUANTIZED_SAVE_FLAG, False)+ assert not getattr(patched.__wrapped__, _BNB_PREQUANTIZED_SAVE_FLAG, False)+ assert modeling_utils.revert_weight_conversion is patched++ model = _tiny_llama()+ state_dict = model.state_dict()+ renaming = core_model_loading.WeightRenaming("^old_lm_head", "^lm_head")+ conversions = [renaming, _bnb_converter(bnb_integration, core_model_loading)]+ model._weight_conversions = conversions++ saved = patched(model, dict(state_dict))+ assert model._weight_conversions is conversions++ model._weight_conversions = [renaming]+ expected = patched.__wrapped__(model, dict(state_dict))+ assert set(saved) == set(expected)+ assert "old_lm_head.weight" in saved+ for key in expected:+ assert torch.equal(saved[key], expected[key])++ model._weight_conversions = [_bnb_converter(bnb_integration, core_model_loading)]+ saved = patched(model, dict(state_dict))+ assert set(saved) == set(state_dict)+ for key in state_dict:+ assert torch.equal(saved[key], state_dict[key])diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex b3f1705298d..e965fc50c5f 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -308,6 +308,7 @@ from .import_fixes import (fix_transformers5_legacy_config_types,fix_transformers5_image_processing_reexports,fix_transformers_composite_prefix_renaming,+ fix_transformers_bnb_prequantized_save,fix_transformers_fully_masked_rows,fix_transformers_flash_attention_mrope_packed_sequence,fix_transformers_untrusted_config_fields,@@ -382,6 +383,7 @@ fix_transformers_chat_template_path_traversal()# composite model's conversion mapping. Ordered here, before anything loads a checkpoint, so a# plain transformers.from_pretrained in the same process keeps its bitsandbytes quant_state too.fix_transformers_composite_prefix_renaming()+fix_transformers_bnb_prequantized_save()# After the repair above, never before it, and this is the ONLY call: on exactly the releases# the repair covers, warning first tells users to downgrade away from a version that now works,# and a second call cannot retract a warning already logged. The check reads the live attribute,@@ -471,6 +473,7 @@ del fix_transformers5_legacy_config_typesdel fix_transformers_untrusted_config_fieldsdel fix_transformers_chat_template_path_traversaldel fix_transformers_rope_scaling_drops_theta+del fix_transformers_bnb_prequantized_savedel fix_transformers_fp8_modulelist_expertsdel fix_transformers_fp8_unscaled_checkpoint_linearsdel fix_transformers_validate_rope_ignore_keysdiff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 2873ff70dff..93a3ee219d7 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -2746,6 +2746,77 @@ def fix_transformers_composite_prefix_renaming():logger.info(f"Unsloth: Failed patching get_model_conversion_mapping ({e})")+_BNB_PREQUANTIZED_SAVE_FLAG = "_unsloth_skips_bnb_deserialize_on_save"+++def _bnb_deserialize_ops_without_reverse():+ """The bitsandbytes deserialize ops on this transformers whose `reverse_op` raises."""+ try:+ from transformers.integrations import bitsandbytes as bnb_integration+ except Exception:+ return ()+ broken = []+ for name in ("Bnb4bitDeserialize", "Bnb8bitDeserialize"):+ op_class = getattr(bnb_integration, name, None)+ if not isinstance(op_class, type):+ continue+ try:+ op_class.__new__(op_class).reverse_op+ except NotImplementedError:+ broken.append(op_class)+ except Exception:+ continue+ return tuple(broken)+++def fix_transformers_bnb_prequantized_save():+ """transformers 5.x: `save_pretrained` reverses the `Bnb{4,8}bitDeserialize` converter a+ pre-quantized load attaches, and neither op has a `reverse_op` (NotImplementedError, #638;+ upstream PR #45743 closed unmerged). Quantized modules already emit the checkpoint layout,+ so skip that converter on save. Probe-gated on `reverse_op` raising."""+ broken_ops = _bnb_deserialize_ops_without_reverse()+ if not broken_ops:+ return+ try:+ from transformers import core_model_loading, modeling_utils+ except Exception as e:+ logger.info(f"Unsloth: Skipping the bitsandbytes save fix ({e})")+ return+ original = getattr(core_model_loading, "revert_weight_conversion", None)+ if original is None or getattr(original, _BNB_PREQUANTIZED_SAVE_FLAG, False):+ return++ def _is_bnb_deserialize(conversion):+ operations = getattr(conversion, "operations", None)+ return bool(operations) and all(isinstance(op, broken_ops) for op in operations)++ @functools.wraps(original)+ def revert_weight_conversion(model, *args, **kwargs):+ conversions = getattr(model, "_weight_conversions", None)+ if not isinstance(conversions, list) or not any(map(_is_bnb_deserialize, conversions)):+ return original(model, *args, **kwargs)+ # An empty list, never None: None makes transformers rebuild the default mapping.+ model._weight_conversions = [c for c in conversions if not _is_bnb_deserialize(c)]+ try:+ return original(model, *args, **kwargs)+ finally:+ model._weight_conversions = conversions++ revert_weight_conversion.__wrapped__ = original+ setattr(revert_weight_conversion, _BNB_PREQUANTIZED_SAVE_FLAG, True)+ try:+ core_model_loading.revert_weight_conversion = revert_weight_conversion+ # modeling_utils binds the function at import (`from .core_model_loading import ...`).+ if modeling_utils.__dict__.get("revert_weight_conversion") is original:+ modeling_utils.revert_weight_conversion = revert_weight_conversion+ logger.info(+ "Unsloth: Patching transformers `revert_weight_conversion` so a pre-quantized "+ "bitsandbytes model can be saved"+ )+ except Exception as e:+ logger.info(f"Unsloth: Failed patching revert_weight_conversion ({e})")++_ROPE_SCALING_PATCH_FLAG = "_unsloth_patched_rope_scaling_setter"