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.

Stop losing the cause of a failed save, and stop dropping 4bit in silence (#9678)

Daniel Hanb74852da1b00
diff --git a/tests/test_bf16_quant_disabled_message.py b/tests/test_bf16_quant_disabled_message.py
new file mode 100644
index 00000000000..a1f07b32a0d
--- /dev/null
+++ b/tests/test_bf16_quant_disabled_message.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The '-bf16' notice must not claim 16bit when a quantization_config survives.
+
+A `-bf16` name drops the plain load_in_4bit / 8bit / fp8 flags, so the notice is
+accurate for those. A user-supplied `quantization_config` is only read into the
+local flags: it stays in `**kwargs`, both loaders forward it, and Transformers
+quantizes anyway, so there the notice would say the opposite of what happens.
+
+Source-level, because reaching the branch needs a real checkpoint download.
+"""
+
+import ast
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+LOADER = ROOT / "unsloth" / "models" / "loader.py"
+SRC = LOADER.read_text(encoding = "utf-8")
+TREE = ast.parse(SRC)
+
+
+def _bf16_notice_guards():
+ """Every `if` whose body is only the '-bf16' notice `print`."""
+ guards = []
+ for node in ast.walk(TREE):
+ if not isinstance(node, ast.If) or len(node.body) != 1:
+ continue
+ stmt = node.body[0]
+ if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
+ continue
+ func = stmt.value.func
+ if not (isinstance(func, ast.Name) and func.id == "print"):
+ continue
+ text = ast.get_source_segment(SRC, stmt) or ""
+ if "load in 16bit" in text and "-bf16" in text:
+ guards.append(node)
+ return guards
+
+
+def test_all_four_bf16_branches_carry_the_notice():
+ """Two in FastLanguageModel.from_pretrained, two in FastModel.from_pretrained."""
+ assert len(_bf16_notice_guards()) == 4
+
+
[email protected]("index", [0, 1, 2, 3])
+def test_the_notice_is_gated_on_no_user_quantization_config(index):
+ guards = _bf16_notice_guards()
+ assert len(guards) == 4, "the notice moved; update this test"
+ test_src = ast.get_source_segment(SRC, guards[index].test) or ""
+ assert "quantization_config" in test_src, (
+ "the '-bf16' notice claims a 16bit load, but a user-supplied "
+ "quantization_config is still forwarded to Transformers and still "
+ "quantizes, so the notice must be suppressed when one is present"
+ )
+ assert "kwargs" in test_src, (
+ "read kwargs['quantization_config']: the local `quantization_config` is "
+ "not cleared when the bitsandbytes-unavailable branch pops it from kwargs"
+ )
+
+
+def test_the_flags_are_still_cleared():
+ """The notice is a message; it must not change what the branch does."""
+ assert SRC.count("load_in_16bit = True") >= 4
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_kaggle_gguf_error_message.py b/tests/test_kaggle_gguf_error_message.py
index 02b9051df89..0dba934d1cf 100644
--- a/tests/test_kaggle_gguf_error_message.py
+++ b/tests/test_kaggle_gguf_error_message.py
@@ -152,7 +152,11 @@ def test_the_real_error_survives_either_way():
assert (
window.count("from e") >= 2
), "the original exception must be chained so the traceback survives"
- assert "GGUF conversion failed: {e}" in window
+ # `{e}` is empty when the exception has no args, so the type-leading form counts too.
+ assert (
+ "GGUF conversion failed: {e}" in window
+ or "GGUF conversion failed: {_describe_exception(e)}" in window
+ )
if __name__ == "__main__":
diff --git a/tests/test_offloaded_parameter_hint.py b/tests/test_offloaded_parameter_hint.py
index f21f7d91b65..edc5d452f28 100644
--- a/tests/test_offloaded_parameter_hint.py
+++ b/tests/test_offloaded_parameter_hint.py
@@ -144,9 +144,19 @@ def test_the_original_error_is_still_reported():
repo's ruff hook may merge the hint into the same f-string or split it out
again, and either shape satisfies what this is actually checking.
"""
- for anchor in ("Failed to save/merge model: {e}", "Failed to save model: {e}"):
- i = SRC.index(anchor)
- assert "_offloaded_parameter_hint" in SRC[i : i + 200]
+ for anchor in ("Failed to save/merge model: ", "Failed to save model: "):
+ # All occurrences, not the first: a docstring also quotes these messages.
+ windows = []
+ i = SRC.find(anchor)
+ assert i != -1, anchor
+ while i != -1:
+ windows.append(SRC[i : i + 200])
+ i = SRC.find(anchor, i + 1)
+ # `{e}` is empty when the exception has no args, so the type-leading form counts too.
+ assert any(
+ ("{e}" in w or "_describe_exception(e)" in w) and "_offloaded_parameter_hint" in w
+ for w in windows
+ ), anchor
def test_it_still_raises_runtimeerror():
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 848023a8fca..495bf6cf337 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -649,9 +649,22 @@ class FastLanguageModel(FastLlamaModel):
):
model_name = _strip_unsloth_bnb_4bit_suffix(model_name)
# '-bf16' hub repos load bf16; a local dir keeps the requested quant unless 16bit is set
+ # Say so: dropping the flags in silence surfaces much later as an
+ # out-of-memory failure whose message never mentions quantization.
if model_name.lower().endswith("-bf16") and (
load_in_16bit or not os.path.isdir(os.path.expanduser(model_name))
):
+ # Only the plain flags are dropped; a user quantization_config stays
+ # in **kwargs and still quantizes, so stay quiet in that case.
+ if (load_in_4bit or load_in_8bit or load_in_fp8 != False) and kwargs.get(
+ "quantization_config", None
+ ) is None:
+ print(
+ f"Unsloth: `{model_name}` is a 16bit (-bf16) checkpoint, so the "
+ f"requested 4bit/8bit/fp8 loading is disabled and the model will "
+ f"load in 16bit. Point at the 4bit repo instead if that is not "
+ f"what you wanted -- a 16bit load needs far more VRAM."
+ )
load_in_4bit = False
load_in_8bit = False
load_in_fp8 = False
@@ -830,9 +843,22 @@ class FastLanguageModel(FastLlamaModel):
):
model_name = _strip_unsloth_bnb_4bit_suffix(model_name)
# '-bf16' hub repos load bf16; a local dir keeps the requested quant unless 16bit is set
+ # Say so: dropping the flags in silence surfaces much later as an
+ # out-of-memory failure whose message never mentions quantization.
if model_name.lower().endswith("-bf16") and (
load_in_16bit or not os.path.isdir(os.path.expanduser(model_name))
):
+ # Only the plain flags are dropped; a user quantization_config
+ # stays in **kwargs and still quantizes, so stay quiet then.
+ if (load_in_4bit or load_in_8bit or load_in_fp8 != False) and kwargs.get(
+ "quantization_config", None
+ ) is None:
+ print(
+ f"Unsloth: `{model_name}` is a 16bit (-bf16) checkpoint, so the "
+ f"requested 4bit/8bit/fp8 loading is disabled and the model will "
+ f"load in 16bit. Point at the 4bit repo instead if that is not "
+ f"what you wanted -- a 16bit load needs far more VRAM."
+ )
load_in_4bit = False
load_in_8bit = False
load_in_fp8 = False
@@ -1422,9 +1448,22 @@ class FastModel(FastBaseModel):
):
model_name = _strip_unsloth_bnb_4bit_suffix(model_name)
# '-bf16' hub repos load bf16; a local dir keeps the requested quant unless 16bit is set
+ # Say so: dropping the flags in silence surfaces much later as an
+ # out-of-memory failure whose message never mentions quantization.
if model_name.lower().endswith("-bf16") and (
load_in_16bit or not os.path.isdir(os.path.expanduser(model_name))
):
+ # Only the plain flags are dropped; a user quantization_config stays
+ # in **kwargs and still quantizes, so stay quiet in that case.
+ if (load_in_4bit or load_in_8bit or load_in_fp8 != False) and kwargs.get(
+ "quantization_config", None
+ ) is None:
+ print(
+ f"Unsloth: `{model_name}` is a 16bit (-bf16) checkpoint, so the "
+ f"requested 4bit/8bit/fp8 loading is disabled and the model will "
+ f"load in 16bit. Point at the 4bit repo instead if that is not "
+ f"what you wanted -- a 16bit load needs far more VRAM."
+ )
load_in_4bit = False
load_in_8bit = False
load_in_fp8 = False
@@ -1808,9 +1847,22 @@ class FastModel(FastBaseModel):
):
model_name = _strip_unsloth_bnb_4bit_suffix(model_name)
# '-bf16' hub repos load bf16; a local dir keeps the requested quant unless 16bit is set
+ # Say so: dropping the flags in silence surfaces much later as an
+ # out-of-memory failure whose message never mentions quantization.
if model_name.lower().endswith("-bf16") and (
load_in_16bit or not os.path.isdir(os.path.expanduser(model_name))
):
+ # Only the plain flags are dropped; a user quantization_config
+ # stays in **kwargs and still quantizes, so stay quiet then.
+ if (load_in_4bit or load_in_8bit or load_in_fp8 != False) and kwargs.get(
+ "quantization_config", None
+ ) is None:
+ print(
+ f"Unsloth: `{model_name}` is a 16bit (-bf16) checkpoint, so the "
+ f"requested 4bit/8bit/fp8 loading is disabled and the model will "
+ f"load in 16bit. Point at the 4bit repo instead if that is not "
+ f"what you wanted -- a 16bit load needs far more VRAM."
+ )
load_in_4bit = False
load_in_8bit = False
load_in_fp8 = False
diff --git a/unsloth/save.py b/unsloth/save.py
index eac0b72a9e6..7815d4ae385 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -188,6 +188,18 @@ IMATRIX_QUANTS = {
}
+def _describe_exception(exc) -> str:
+ """A description that survives an exception with no message.
+
+ `f"{exc}"` is the EMPTY STRING when the args are empty, so
+ `f"Failed to save model: {exc}"` named nothing at all on a real Kaggle
+ Q8_0 export. Leading with the type keeps the class of failure visible.
+ """
+ text = str(exc).strip()
+ name = type(exc).__name__
+ return f"{name}: {text}" if text else name
+
+
def has_curl():
return shutil.which("curl") is not None
@@ -430,7 +442,10 @@ def _quantize_q2_k_l(
error_details += f"\nSubprocess stdout:\n{e.stdout}"
if hasattr(e, "stderr") and e.stderr:
error_details += f"\nSubprocess stderr:\n{e.stderr}"
- raise RuntimeError(f"Failed to quantize {input_gguf} to q2_k_l: {e}{error_details}")
+ raise RuntimeError(
+ f"Failed to quantize {input_gguf} to q2_k_l: "
+ f"{_describe_exception(e)}{error_details}"
+ ) from e
output_path = Path(output_gguf)
if not output_path.exists():
@@ -4747,7 +4762,10 @@ def unsloth_save_pretrained_gguf(
unsloth_generic_save(**arguments)
except Exception as e:
- raise RuntimeError(f"Failed to save/merge model: {e}{_offloaded_parameter_hint(self)}")
+ raise RuntimeError(
+ f"Failed to save/merge model: {_describe_exception(e)}"
+ f"{_offloaded_parameter_hint(self)}"
+ ) from e
else:
# Non-PEFT model: checkpoint files already exist; point save_to_gguf
# at the original path instead of re-saving to a temp subdir.
@@ -4774,7 +4792,10 @@ def unsloth_save_pretrained_gguf(
if tokenizer is not None:
tokenizer.save_pretrained(save_directory)
except Exception as e:
- raise RuntimeError(f"Failed to save model: {e}{_offloaded_parameter_hint(self)}")
+ raise RuntimeError(
+ f"Failed to save model: {_describe_exception(e)}"
+ f"{_offloaded_parameter_hint(self)}"
+ ) from e
if is_processor:
tokenizer = tokenizer.tokenizer
@@ -4871,17 +4892,17 @@ def unsloth_save_pretrained_gguf(
f"about system memory rather than GPU memory or disk.\n"
f"Try a smaller quantization, a machine with more RAM, or "
f"convert from a saved 16bit checkpoint on a larger host.\n"
- f"Error: {e}"
+ f"Error: {_describe_exception(e)}"
) from e
if IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk(e, save_directory):
raise RuntimeError(
f"Unsloth: GGUF conversion failed in Kaggle environment.\n"
f"This is likely due to the 20GB disk space limit.\n"
f"Try saving to /tmp directory or use a smaller model.\n"
- f"Error: {e}"
+ f"Error: {_describe_exception(e)}"
) from e
else:
- raise RuntimeError(f"Unsloth: GGUF conversion failed: {e}") from e
+ raise RuntimeError(f"Unsloth: GGUF conversion failed: {_describe_exception(e)}") from e
# Step 9: Create Ollama modelfile
modelfile_location = None
@@ -5494,7 +5515,7 @@ def unsloth_push_to_hub_gguf(
shutil.rmtree(d)
except:
pass
- raise RuntimeError(f"Failed to convert model to GGUF: {e}")
+ raise RuntimeError(f"Failed to convert model to GGUF: {_describe_exception(e)}") from e
# Step 3: Upload to HuggingFace Hub
print("Unsloth: Uploading GGUF to Huggingface Hub...")
@@ -5669,7 +5690,7 @@ This model was finetuned and converted to GGUF format using [Unsloth](https://gi
)
except Exception as e:
- raise RuntimeError(f"Failed to upload to Hugging Face Hub: {e}")
+ raise RuntimeError(f"Failed to upload to Hugging Face Hub: {_describe_exception(e)}") from e
finally:
# Clean up temporary directory