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
Report the real cause when a save or GGUF export fails (#7861)
Daniel Han5da63be9671b
diff --git a/tests/test_device_helpers.py b/tests/test_device_helpers.pyindex fa0f21b6a39..c06c8f8d901 100644--- a/tests/test_device_helpers.py+++ b/tests/test_device_helpers.py@@ -20,7 +20,16 @@ def _load_device_type(monkeypatch,torch_module,mlx_available = False,+ allow_cpu = False,):+ # Always pinned, never inherited. UNSLOTH_ALLOW_CPU short-circuits+ # get_device_type() to "cuda", so a GPU-less host that exports it silently+ # rewrites what the hip and xpu cases are testing.+ if allow_cpu:+ monkeypatch.setenv("UNSLOTH_ALLOW_CPU", "1")+ else:+ monkeypatch.delenv("UNSLOTH_ALLOW_CPU", raising = False)+package_name = "_device_helpers_test"package = types.ModuleType(package_name)package.__path__ = [str(DEVICE_TYPE_PATH.parent)]@@ -135,6 +144,30 @@ def test_xpu_cache_and_current_device_dispatch(monkeypatch):assert (name, snippet, max_memory) == ("Intel Arc. ", "Intel Toolkit: 2026.1.", 8.0)+def test_cpu_fallback_does_not_override_mlx(monkeypatch):+ # UNSLOTH_ALLOW_CPU used to be checked first, so an MLX Mac reported "cuda"+ # and get_device_count() then hit torch, which is never imported there.+ device_type = _load_device_type(+ monkeypatch,+ torch_module = None,+ mlx_available = True,+ allow_cpu = True,+ )++ assert device_type.DEVICE_TYPE == "mlx"+ assert device_type.DEVICE_COUNT == 1+++def test_cpu_fallback_still_reports_cuda_off_mlx(monkeypatch):+ # The GPU hosts' behaviour must be unchanged: no MLX means the CPU fallback wins.+ torch = _fake_torch(properties = CUDA_PROPERTIES, cuda_available = False)++ device_type = _load_device_type(monkeypatch, torch, allow_cpu = True)++ assert device_type.DEVICE_TYPE == "cuda"+ assert device_type.DEVICE_COUNT == 1++def test_mlx_helpers_do_not_require_torch(monkeypatch):device_type = _load_device_type(monkeypatch,diff --git a/tests/test_kaggle_gguf_error_message.py b/tests/test_kaggle_gguf_error_message.pynew file mode 100644index 00000000000..02b9051df89--- /dev/null+++ b/tests/test_kaggle_gguf_error_message.py@@ -0,0 +1,317 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""The Kaggle 20GB message must only fire on failures that are about disk.++It used to fire for every GGUF failure, so an unconvertible architecture, a+missing tokenizer and a bad quant method all told the user to free up space.+"""++import os+import shutil+import sys+from collections import namedtuple+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++save = pytest.importorskip("unsloth.save")+_looks_like_disk = save._gguf_failure_looks_like_disk++_Usage = namedtuple("_Usage", ("total", "used", "free"))+++def plenty_of_free_space(monkeypatch):+ """State the premise the "not a disk problem" tests are written under.++ `_gguf_failure_looks_like_disk` has a second, independent signal: a+ filesystem with less than `_DISK_HEADROOM_BYTES` (2GiB) free is a disk+ failure whatever the exception says. It probes `save_directory` and then+ `os.getcwd()`, so on a host whose working directory is that full, every+ "this is NOT a disk problem" test inverts and fails for a reason that has+ nothing to do with the message it is asserting about.++ Report ample space so the message is the only signal left, which is what+ those tests are about ("a broken quantizer with 19GB free is not a disk+ problem", save.py). The real threshold is left alone, so the comparison+ still runs and a nonsensical headroom would still be caught.+ """+ real_disk_usage = shutil.disk_usage+ ample = _Usage(total = 100 * 1024**3, used = 1 * 1024**3, free = 99 * 1024**3)++ def plenty(path):+ # Keep the real failure modes; only the numbers are ours.+ real_disk_usage(path)+ return ample++ monkeypatch.setattr(shutil, "disk_usage", plenty)+ return ample+++# ---- failures that ARE about disk -----------------------------------------+++ "msg",+ [+ "OSError: [Errno 28] No space left on device",+ "Not enough free space to write 262144 bytes",+ "Disk quota exceeded",+ "write failed: no space left",+ ],+)+def test_disk_wordings_are_recognised(msg):+ assert _looks_like_disk(RuntimeError(msg)) is True+++def test_errno_attribute_is_enough_on_its_own():+ exc = OSError("something opaque")+ exc.errno = 28+ assert _looks_like_disk(exc) is True+++def test_the_check_is_case_insensitive():+ assert _looks_like_disk(RuntimeError("NO SPACE LEFT ON DEVICE")) is True+++# ---- failures that are NOT about disk -------------------------------------++[email protected]("plenty_of_free_space")+def test_an_unconvertible_architecture_is_not_a_disk_problem():+ """The bert_classification case."""+ exc = NotImplementedError("Model ModernBertForSequenceClassification is not supported")+ assert _looks_like_disk(exc, os.getcwd()) is False++[email protected]("plenty_of_free_space")+def test_a_missing_tokenizer_is_not_a_disk_problem():+ exc = ValueError("Unsloth: Saving to GGUF must have a tokenizer.")+ assert _looks_like_disk(exc, os.getcwd()) is False++[email protected]("plenty_of_free_space")+def test_a_bad_quant_method_is_not_a_disk_problem():+ exc = RuntimeError("Unknown quantization method: q9_k_xxl")+ assert _looks_like_disk(exc, os.getcwd()) is False+++# ---- the guard must never be what raises ---------------------------------+++def test_a_nonexistent_directory_does_not_raise():+ assert _looks_like_disk(RuntimeError("boom"), "/definitely/not/a/real/path") in (True, False)+++def test_none_directory_does_not_raise():+ assert _looks_like_disk(RuntimeError("boom"), None) in (True, False)+++def test_an_exception_with_no_message_does_not_raise():+ assert _looks_like_disk(RuntimeError()) in (True, False)+++# ---- the call site --------------------------------------------------------+++def test_the_kaggle_branch_is_gated_on_the_check():+ """Source-level, because reaching the branch needs a real conversion."""+ import ast++ src = Path(save.__file__).read_text(encoding = "utf-8")+ tree = ast.parse(src)+ gated = False+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ names = {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}+ if "IS_KAGGLE_ENVIRONMENT" in names and "_gguf_failure_looks_like_disk" in names:+ gated = True+ assert gated, "the Kaggle 20GB message is no longer gated on the disk check"+++def test_the_real_error_survives_either_way():+ """Both branches must carry the original error text."""+ src = Path(save.__file__).read_text(encoding = "utf-8")+ i = src.index("GGUF conversion failed in Kaggle environment")+ window = src[i - 200 : i + 900]+ assert (+ window.count("from e") >= 2+ ), "the original exception must be chained so the traceback survives"+ assert "GGUF conversion failed: {e}" in window+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))+++# ---- a converter killed by the OOM-killer ---------------------------------+++def test_sigkill_is_recognised_from_the_message():+ """subprocess renders it as text, which is all Unsloth re-raises."""+ from unsloth.save import _gguf_child_was_oom_killed++ exc = RuntimeError("Command '[...]' died with <Signals.SIGKILL: 9>.")+ assert _gguf_child_was_oom_killed(exc)++[email protected]("code", [-9, 137])+def test_sigkill_is_recognised_from_the_returncode(code):+ """CalledProcessError uses -9; a shell wrapper reports 137."""+ from unsloth.save import _gguf_child_was_oom_killed++ class _Called(Exception):+ returncode = code++ assert _gguf_child_was_oom_killed(_Called())+++def test_a_shell_wrapped_137_is_recognised():+ """llama-quantize runs under `shell = True`, so /bin/sh reports a SIGKILLed+ child as exit status 137 and never names the signal. unsloth_zoo then+ re-raises a plain RuntimeError, dropping `returncode`, so the wording is+ the only thing left."""+ from unsloth.save import _gguf_child_was_oom_killed++ exc = RuntimeError(+ "Failed to quantize model.BF16.gguf to q4_k_m: Command "+ "'/root/llama.cpp/llama-quantize model.BF16.gguf model.Q4_K_M.gguf q4_k_m 8' "+ "returned non-zero exit status 137."+ )+ assert _gguf_child_was_oom_killed(exc)+++def test_a_chained_cause_is_inspected():+ """`raise RuntimeError(...) from e` keeps the CalledProcessError, and its+ returncode is a stronger signal than any wording."""+ import subprocess++ from unsloth.save import _gguf_child_was_oom_killed++ cause = subprocess.CalledProcessError(137, "llama-quantize ...")+ outer = RuntimeError("Unsloth: Quantization failed for model.Q4_K_M.gguf")+ outer.__cause__ = cause+ assert _gguf_child_was_oom_killed(outer)+++def test_an_implicit_context_is_inspected():+ """Layers that re-raise without `from` still leave __context__ behind."""+ import subprocess++ from unsloth.save import _gguf_child_was_oom_killed++ try:+ try:+ raise subprocess.CalledProcessError(-9, "convert_hf_to_gguf.py ...")+ except subprocess.CalledProcessError:+ raise RuntimeError("Unsloth: GGUF conversion failed")+ except RuntimeError as outer:+ assert _gguf_child_was_oom_killed(outer)+++def test_the_quantize_wrapper_chains_its_cause():+ """The build-llama.cpp branch must chain too, else the 137 is unreachable+ from the outer handler."""+ src = Path(save.__file__).read_text(encoding = "utf-8")+ i = src.index("You might have to compile llama.cpp yourself")+ assert "from e" in src[i : i + 900]+++def test_an_ordinary_converter_failure_is_not_called_an_oom():+ """A converter that fails on its own must keep its own message."""+ from unsloth.save import _gguf_child_was_oom_killed++ exc = RuntimeError("NotImplementedError: Unknown tensor name audio_tower.x")+ assert not _gguf_child_was_oom_killed(exc)+++def test_a_disk_failure_is_not_called_an_oom():+ from unsloth.save import _gguf_child_was_oom_killed+ assert not _gguf_child_was_oom_killed(OSError("No space left on device"))+++def test_the_oom_branch_runs_before_the_kaggle_disk_branch():+ """A SIGKILL on Kaggle with a full-ish disk would otherwise be reported as+ a disk problem, which is the wrong advice."""+ import inspect+ from unsloth import save as _s++ src = inspect.getsource(_s.unsloth_save_pretrained_gguf)+ assert src.index("_gguf_child_was_oom_killed(e)") < src.index(+ "IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk"+ )+++def test_the_message_says_host_ram_not_gpu_or_disk():+ """The whole point: SIGKILL names no resource, and the user's first guess+ is usually VRAM."""+ import inspect+ from unsloth import save as _s++ src = inspect.getsource(_s.unsloth_save_pretrained_gguf)+ i = src.index("_gguf_child_was_oom_killed(e)")+ body = src[i : i + 900]+ assert "host RAM" in body+ assert "rather than GPU memory or disk" in body+++def test_it_chains_the_original():+ import inspect+ from unsloth import save as _s++ src = inspect.getsource(_s.unsloth_save_pretrained_gguf)+ i = src.index("_gguf_child_was_oom_killed(e)")+ assert "from e" in src[i : i + 900]+++# ---- the inner conversion/quantize branches are gated too ------------------+++def test_no_kaggle_disk_message_is_left_ungated():+ """The outer gate cannot undo a disk explanation already baked into the+ inner RuntimeError's message, so save_to_gguf's own missing-output and+ quantize handlers have to make the same check. unslothai/unsloth#835."""+ import ast++ src = Path(save.__file__).read_text(encoding = "utf-8")+ tree = ast.parse(src)+ ungated = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ names = {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}+ if "IS_KAGGLE_ENVIRONMENT" not in names:+ continue+ if "20GB" not in (ast.get_source_segment(src, node) or ""):+ continue+ if "_gguf_failure_looks_like_disk" not in names:+ ungated.append(node.lineno)+ assert not ungated, f"20GB disk message still ungated at lines {ungated}"++[email protected]("plenty_of_free_space")+def test_a_broken_quantizer_is_not_a_disk_problem():+ """The failure the inner quantize handler used to blame on disk."""+ exc = RuntimeError("llama-quantize: unknown quantization type")+ assert _looks_like_disk(exc, os.getcwd()) is False+++def test_the_inner_quantize_branch_chains_the_original():+ src = Path(save.__file__).read_text(encoding = "utf-8")+ i = src.index("Unsloth: Quantization failed for {output_location}")+ assert "from e" in src[i : i + 900]diff --git a/tests/test_offloaded_parameter_hint.py b/tests/test_offloaded_parameter_hint.pynew file mode 100644index 00000000000..f21f7d91b65--- /dev/null+++ b/tests/test_offloaded_parameter_hint.py@@ -0,0 +1,159 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""A save that fails because the model was offloaded should say so.++Offloaded parameters sit on the meta device, and saving then dies inside+accelerate with an error that names neither the model nor the offload. The+hint is appended to that error, never substituted for it, and stays empty+unless a meta parameter is really present.+"""++import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++import torch # noqa: E402++from unsloth.save import _offloaded_parameter_hint # noqa: E402+++class _Model:+ def __init__(self, params):+ self._params = params++ def named_parameters(self):+ return iter(self._params)+++def _p(device):+ return torch.nn.Parameter(torch.zeros(2, device = device), requires_grad = False)+++# ---- fires when it should --------------------------------------------------+++def test_a_meta_parameter_produces_a_hint():+ m = _Model([("model.layers.0.mlp.down_proj.weight", _p("meta"))])+ hint = _offloaded_parameter_hint(m)+ assert hint+ assert "meta device" in hint+++def test_the_hint_names_the_offending_parameter():+ """So the reader can tell which part of the model was offloaded."""+ m = _Model([("model.layers.31.mlp.experts.w1", _p("meta"))])+ assert "model.layers.31.mlp.experts.w1" in _offloaded_parameter_hint(m)+++def test_the_hint_states_the_remedy():+ m = _Model([("a", _p("meta"))])+ hint = _offloaded_parameter_hint(m)+ assert "did not fit" in hint+ assert "device_map" in hint or "large enough" in hint+++def test_it_reports_a_few_names_not_all_of_them():+ """A 30B MoE has thousands of offloaded tensors; pasting them all would+ bury the actual error."""+ m = _Model([(f"layer.{i}.weight", _p("meta")) for i in range(500)])+ hint = _offloaded_parameter_hint(m)+ assert hint.count("layer.") <= 3+ assert len(hint) < 600+++def test_a_mix_of_real_and_meta_still_fires():+ """Partial offload is the normal case -- only some layers move."""+ m = _Model([("good", _p("cpu")), ("bad", _p("meta"))])+ assert _offloaded_parameter_hint(m)+++# ---- stays silent when it should ------------------------------------------+++def test_a_fully_resident_model_gets_no_hint():+ """The mislabelling risk. An unrelated save failure must not be blamed+ on an offload that never happened."""+ m = _Model([("a", _p("cpu")), ("b", _p("cpu"))])+ assert _offloaded_parameter_hint(m) == ""+++def test_a_model_with_no_parameters_gets_no_hint():+ assert _offloaded_parameter_hint(_Model([])) == ""+++def test_a_model_without_named_parameters_gets_no_hint():+ class Odd:+ pass++ assert _offloaded_parameter_hint(Odd()) == ""+++def test_none_gets_no_hint():+ assert _offloaded_parameter_hint(None) == ""+++def test_a_raising_named_parameters_gets_no_hint():+ """A diagnostic must never replace the real error with its own."""++ class Boom:+ def named_parameters(self):+ raise RuntimeError("model is in a bad state")++ assert _offloaded_parameter_hint(Boom()) == ""+++def test_a_parameter_with_no_device_does_not_crash():+ class NoDevice:+ device = None++ m = _Model([("weird", NoDevice())])+ assert _offloaded_parameter_hint(m) == ""+++# ---- wiring ---------------------------------------------------------------++SRC = (ROOT / "unsloth" / "save.py").read_text(encoding = "utf-8")+++def test_both_save_failure_paths_use_it():+ """The GGUF export can fail at the merge step or at the plain save step,+ and offloading breaks both."""+ assert SRC.count("_offloaded_parameter_hint(self)") == 2+++def test_the_original_error_is_still_reported():+ """The hint is added TO the error, never instead of it.++ Anchored on the message text alone, not on a whole string literal: the+ 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]+++def test_it_still_raises_runtimeerror():+ """Callers catch RuntimeError; changing the type would break them."""+ i = SRC.index("_offloaded_parameter_hint(self)")+ assert "raise RuntimeError(" in SRC[max(0, i - 300) : i]+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_save_entrypoints_reach_converter.py b/tests/test_save_entrypoints_reach_converter.pynew file mode 100644index 00000000000..0f1fabb9060--- /dev/null+++ b/tests/test_save_entrypoints_reach_converter.py@@ -0,0 +1,153 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""A save entry point must actually reach its converter.++A helper definition spliced into the middle of `unsloth_save_pretrained_gguf`+left both halves valid Python and the import working, while the function+returned before ever calling `save_to_gguf`. These are the structural+properties that break when a function gets cut in two, checked against the AST+so no unsloth import or GPU is needed.+"""++import ast+from pathlib import Path++import pytest++SAVE_PY = Path(__file__).resolve().parents[1] / "unsloth" / "save.py"++[email protected](scope = "module")+def tree():+ return ast.parse(SAVE_PY.read_text(encoding = "utf-8"))+++def _func(tree, name):+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return node+ raise AssertionError(f"{name} is not defined in save.py")+++def _calls(node):+ out = set()+ for sub in ast.walk(node):+ if isinstance(sub, ast.Call):+ f = sub.func+ if isinstance(f, ast.Name):+ out.add(f.id)+ elif isinstance(f, ast.Attribute):+ out.add(f.attr)+ return out+++# ---- the property that broke -------------------------------------------+++def test_save_pretrained_gguf_calls_the_converter(tree):+ """The whole purpose of the function. Without this call it is an+ expensive no-op that reports success."""+ assert "save_to_gguf" in _calls(_func(tree, "unsloth_save_pretrained_gguf"))+++def test_push_to_hub_gguf_reaches_a_converter(tree):+ """Same hazard, same shape, different entry point."""+ calls = _calls(_func(tree, "unsloth_push_to_hub_gguf"))+ assert calls & {"save_to_gguf", "unsloth_save_pretrained_gguf"}, sorted(calls)+++def test_the_gguf_conversion_is_not_dead_code(tree):+ """Reaching the call is not enough -- it has to be reachable.++ In the regression the `save_to_gguf(...)` call still existed in the file,+ which is exactly why grepping for it looked reassuring. It had simply+ landed inside another function after a `return`.+ """+ fn = _func(tree, "unsloth_save_pretrained_gguf")+ assert "save_to_gguf" in _calls(fn)+ for owner in (n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n is not fn):+ if owner.name == "save_to_gguf":+ continue+ assert not _unreachable_calls(owner, "save_to_gguf"), (+ f"a save_to_gguf call is stranded as dead code inside "+ f"{owner.name} (line {owner.lineno})"+ )+++# ---- the general shape --------------------------------------------------+++def _unreachable(body):+ """Statements following an unconditional terminator in one block."""+ for i, stmt in enumerate(body):+ if isinstance(stmt, (ast.Return, ast.Raise, ast.Continue, ast.Break)):+ return body[i + 1 :]+ return []+++def _unreachable_calls(fn, name):+ for stmt in _unreachable(fn.body):+ for sub in ast.walk(stmt):+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name) and sub.func.id == name:+ return True+ return False+++def test_no_function_in_save_py_has_a_stranded_body(tree):+ """The splice signature, checked across the whole module.++ A function whose top-level block continues past an unconditional `return`+ is either dead code or, as here, someone else's body that got spliced in.+ Either way it is worth failing on, and it generalises past this one bug.+ """+ offenders = []+ for fn in (n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)):+ stranded = _unreachable(fn.body)+ # A lone trailing `pass` is this codebase's block terminator idiom.+ stranded = [s for s in stranded if not isinstance(s, ast.Pass)]+ if stranded:+ offenders.append(+ f"{fn.name} (line {fn.lineno} -> dead code at line {stranded[0].lineno})"+ )+ assert not offenders, "stranded function bodies:\n " + "\n ".join(offenders)+++def test_the_disk_helper_is_a_module_level_function(tree):+ """It was nested by accident once; nesting it again would re-break the+ caller that uses it."""+ names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef)]+ assert "_gguf_failure_looks_like_disk" in names+ assert "unsloth_save_pretrained_gguf" in names+++def test_the_disk_helper_is_actually_used(tree):+ """It exists to narrow the Kaggle disk claim; if nothing calls it, that+ claim has silently gone back to being unconditional."""+ assert "_gguf_failure_looks_like_disk" in _calls(_func(tree, "unsloth_save_pretrained_gguf"))+++def test_module_still_parses_and_defines_the_public_entry_points(tree):+ names = {n.name for n in tree.body if isinstance(n, ast.FunctionDef)}+ for required in (+ "save_to_gguf",+ "unsloth_save_pretrained_gguf",+ "unsloth_push_to_hub_gguf",+ "unsloth_generic_save",+ ):+ assert required in names, required+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/test_st_save_merged_signature.py b/tests/test_st_save_merged_signature.pynew file mode 100644index 00000000000..258134b0d39--- /dev/null+++ b/tests/test_st_save_merged_signature.py@@ -0,0 +1,307 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""`save_pretrained_merged` must mean the same thing on every model type.++FastSentenceTransformer bound the name to `(self, save_directory, **kwargs)`+while FastLanguageModel takes `tokenizer` and `save_method` positionally, so+the documented positional call raised TypeError on embedding models.+`save_method` must be honoured, not accepted and dropped.+"""++import ast+import inspect+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[1]+ST_PY = REPO_ROOT / "unsloth" / "models" / "sentence_transformer.py"+SAVE_PY = REPO_ROOT / "unsloth" / "save.py"+++def _defs(name, path):+ """Matching definitions in SOURCE order.++ `ast.walk` is breadth-first, so nested closures come back in an order+ that has nothing to do with the file, and indexing into it silently+ tested the wrong one.+ """+ src = path.read_text(encoding = "utf-8")+ found = [+ n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == name+ ]+ return sorted(found, key = lambda n: n.lineno)+++def _params(node):+ return [a.arg for a in node.args.args]+++def test_both_definitions_exist():+ assert (+ len(_defs("_save_pretrained_merged", ST_PY)) == 2+ ), "two closures bind this name; both must be fixed or one model path keeps the old signature"++[email protected]("i", [0, 1])+def test_signature_matches_fastlanguagemodel(i):+ node = _defs("_save_pretrained_merged", ST_PY)[i]+ assert _params(node)[:4] == ["self", "save_directory", "tokenizer", "save_method"]++[email protected]("i", [0, 1])+def test_still_accepts_arbitrary_keywords(i):+ node = _defs("_save_pretrained_merged", ST_PY)[i]+ assert node.args.kwarg is not None, "**kwargs must survive"++[email protected]("i", [0, 1])+def test_defaults_keep_the_old_keyword_call_working(i):+ node = _defs("_save_pretrained_merged", ST_PY)[i]+ defaults = {+ a.arg: d for a, d in zip(node.args.args[-len(node.args.defaults) :], node.args.defaults)+ }+ assert isinstance(defaults["tokenizer"], ast.Constant)+ assert defaults["tokenizer"].value is None+ assert defaults["save_method"].value == "merged_16bit"+++def test_the_reference_signature_is_what_we_matched():+ """Guards the premise: if FastLanguageModel's signature moves, these+ two have to move with it, and the test should say so."""+ node = _defs("unsloth_save_pretrained_merged", SAVE_PY)+ assert node, "unsloth_save_pretrained_merged not found"+ assert _params(node[0])[:4] == ["self", "save_directory", "tokenizer", "save_method"]+++# ---- save_method is honoured, not swallowed -------------------------------+++def test_merge_and_unload_path_refuses_an_unsupported_method():+ src = ST_PY.read_text(encoding = "utf-8")+ node = _defs("_save_pretrained_merged", ST_PY)[0]+ body = ast.get_source_segment(src, node)+ assert "NotImplementedError" in body+ assert "merged_16bit" in body+++def test_forwarding_path_passes_save_method_through():+ src = ST_PY.read_text(encoding = "utf-8")+ node = _defs("_save_pretrained_merged", ST_PY)[1]+ body = ast.get_source_segment(src, node)+ assert 'kwargs.setdefault("save_method", save_method)' in body++[email protected]("i", [0, 1])+def test_an_explicit_tokenizer_is_not_shadowed_by_kwargs(i):+ """Passing it positionally AND as a keyword must not raise or silently+ prefer the wrong one."""+ src = ST_PY.read_text(encoding = "utf-8")+ body = ast.get_source_segment(src, _defs("_save_pretrained_merged", ST_PY)[i])+ assert "if tokenizer is None:" in body+ assert 'pop("tokenizer", None)' in body+++# ---- behavioural check with a stand-in ------------------------------------+++def _extract_helper(name):+ """Pull a module-level helper out by source, so nothing imports unsloth."""+ 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 == name]+ assert node, f"{name} not found in sentence_transformer.py"+ ns = {}+ exec(ast.get_source_segment(src, node[0]), ns)+ return ns[name]+++_normalize_save_method = _extract_helper("_normalize_save_method")+++def _extract(i):+ """Exec one closure body standalone so it can actually be called."""+ src = ST_PY.read_text(encoding = "utf-8")+ node = _defs("_save_pretrained_merged", ST_PY)[i]+ import textwrap++ branding = []+ ns = {+ "os": __import__("os"),+ "print": lambda *a, **k: None,+ "_normalize_save_method": _normalize_save_method,+ "FastSentenceTransformer": type(+ "F", (), {"_add_unsloth_branding": staticmethod(lambda d: branding.append(d))}+ ),+ }+ exec(textwrap.dedent(ast.get_source_segment(src, node)), ns)+ return ns["_save_pretrained_merged"], branding+++class _Tok:+ def __init__(self):+ self.saved = []++ def save_pretrained(self, d):+ self.saved.append(d)+++class _Inner:+ """The wrapped transformer, whose LoRA gets merged away."""++ def __init__(self):+ self.merged = False+ self.saved = []+ self.forwarded = None++ def merge_and_unload(self):+ self.merged = True+ return self++ def save_pretrained(self, d, **kwargs):+ self.saved.append(d)++ def save_pretrained_merged(self, d, **kwargs):+ self.forwarded = kwargs+++class _Module:+ def __init__(self, inner):+ self.auto_model = inner+++class _FakeST:+ """A SentenceTransformer stand-in: a sequence of modules, module 0 of+ which wraps the transformer."""++ def __init__(self, no_modules = False):+ self.tokenizer = _Tok()+ self.saved = []+ self.inner = _Inner()+ self.no_modules = no_modules+ self._modules_list = [_Module(self.inner)]++ def __getitem__(self, i):+ return self._modules_list[i]++ def save_pretrained(self, d):+ self.saved.append(d)+++def test_positional_call_completes_the_merge(tmp_path):+ """The documented positional call. Before the fix this raised TypeError+ before running a single statement."""+ fn, branding = _extract(0)+ st = _FakeST()+ 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 tok.saved == [str(tmp_path)], "the passed tokenizer must be used"+ assert branding == [str(tmp_path)]+++def test_the_positional_tokenizer_wins_over_the_models_own(tmp_path):+ fn, _ = _extract(0)+ st = _FakeST()+ tok = _Tok()+ fn(st, str(tmp_path), tok)+ assert tok.saved == [str(tmp_path)]+ assert st.tokenizer.saved == [], "self.tokenizer must not be used instead"+++def test_omitting_the_tokenizer_falls_back_to_the_models_own(tmp_path):+ fn, _ = _extract(0)+ st = _FakeST()+ fn(st, str(tmp_path))+ assert st.tokenizer.saved == [str(tmp_path)]+++def test_keyword_tokenizer_still_works(tmp_path):+ """The call style that worked before must keep working."""+ fn, _ = _extract(0)+ st = _FakeST()+ tok = _Tok()+ fn(st, str(tmp_path), tokenizer = tok)+ assert tok.saved == [str(tmp_path)]+++def test_unsupported_save_method_raises_not_implemented(tmp_path):+ fn, _ = _extract(0)+ st = _FakeST()+ with pytest.raises(NotImplementedError, match = "merged_16bit"):+ fn(st, str(tmp_path), None, "lora")+ assert not st.inner.merged, "must refuse BEFORE merging anything away"+ assert st.saved == [], "and before writing a half-finished directory"+++# ---- the no_modules fallback honours save_method too -----------------------+++def test_no_modules_fallback_refuses_an_unsupported_method(tmp_path):+ """That branch drops save_method and merges unconditionally, so "lora"+ would return full weights for a request to write adapters."""+ fn, _ = _extract(1)+ st = _FakeST(no_modules = True)+ with pytest.raises(NotImplementedError, match = "merged_16bit"):+ fn(st, str(tmp_path), None, "lora")+ assert not st.inner.merged, "must refuse BEFORE merging the adapters away"+ assert st.saved == [], "and before writing a half-finished directory"+++def test_no_modules_fallback_still_does_a_16bit_merge(tmp_path):+ fn, _ = _extract(1)+ st = _FakeST(no_modules = True)+ fn(st, str(tmp_path), None, "merged_16bit")+ assert st.inner.merged+++def test_the_forwarding_path_still_accepts_lora(tmp_path):+ """With modules.json present the merge understands every method, so the+ refusal above must not leak into this branch."""+ fn, _ = _extract(1)+ st = _FakeST(no_modules = False)+ fn(st, str(tmp_path), None, "lora")+ assert st.inner.forwarded["save_method"] == "lora"+ assert not st.inner.merged+++# ---- spellings mean the same thing as in unsloth_save_model ----------------+++def test_the_reference_normalizes_before_validating():+ """Guards the premise: save.py lowercases and strips spaces first."""+ body = ast.get_source_segment(+ SAVE_PY.read_text(encoding = "utf-8"), _defs("unsloth_save_model", SAVE_PY)[0]+ )+ assert 'save_method.lower().replace(" ", "_")' in body++[email protected]("method", ["MERGED_16BIT", "merged 16bit", "Merged_16bit"])[email protected]("i", [0, 1])+def test_case_and_space_variants_are_accepted(method, i, tmp_path):+ """These keyword calls worked before the signature change."""+ fn, _ = _extract(i)+ st = _FakeST(no_modules = True)+ fn(st, str(tmp_path), None, method)+ assert st.inner.merged+++def test_normalization_leaves_non_strings_alone():+ assert _normalize_save_method(None) is None+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-q"]))diff --git a/unsloth/device_type.py b/unsloth/device_type.pyindex 81332acce82..420944eefc0 100644--- a/unsloth/device_type.py+++ b/unsloth/device_type.py@@ -58,12 +58,15 @@ def is_hip():@functools.cachedef get_device_type():+ # MLX first: torch is never imported on the MLX runtime, so claiming "cuda" here+ # would NameError in get_device_count. Matches unsloth/__init__.py and+ # unsloth_zoo.device_type, which both pick MLX ahead of the CPU fallback.+ if _IS_MLX:+ return "mlx"# Test-only CPU fallback: report "cuda" so every DEVICE_TYPE == "cuda"# branch behaves identically. Read once per process (function is cached).if os.environ.get("UNSLOTH_ALLOW_CPU", "0") == "1":return "cuda"- if _IS_MLX:- return "mlx"if hasattr(torch, "cuda") and torch.cuda.is_available():if is_hip():return "hip"diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex b309b3b2f0e..c0c7fc58897 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -47,6 +47,18 @@ import shutil_CREATE_TRANSFORMER_MODULE_LOCK = threading.RLock()+def _normalize_save_method(save_method):+ """Fold "MERGED_16BIT" and "merged 16bit" onto "merged_16bit".++ unsloth_save_model (save.py) normalizes case and spaces before validating,+ so the same spelling has to mean the same thing here, else a keyword call+ that worked before starts raising.+ """+ if isinstance(save_method, str):+ return save_method.lower().replace(" ", "_")+ return save_method++def _save_pretrained_torchao(self,save_directory,@@ -1671,9 +1683,32 @@ class FastSentenceTransformer(FastModel):)# Add save methods- def _save_pretrained_merged(self, save_directory, **save_kwargs):+ def _save_pretrained_merged(+ self,+ save_directory,+ tokenizer = None,+ save_method = "merged_16bit",+ **save_kwargs,+ ):+ # `tokenizer` and `save_method` are positional to match+ # FastLanguageModel.save_pretrained_merged(dir, tokenizer,+ # save_method = ...), which is how the docs and notebooks call+ # it. Keyword callers behave exactly as before.+ save_method = _normalize_save_method(save_method)+ if save_method not in ("merged_16bit", None):+ # Refused before anything is written: this path merges and+ # unloads unconditionally, so accepting "lora" would write+ # full weights for a request to write adapters.+ raise NotImplementedError(+ f"Unsloth: save_method = {save_method!r} is not "+ f"supported for this SentenceTransformer; only "+ f"'merged_16bit' is."+ )self.save_pretrained(save_directory)- tokenizer = save_kwargs.pop("tokenizer", self.tokenizer)+ 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# Handle compiled model@@ -1848,7 +1883,30 @@ class FastSentenceTransformer(FastModel):st_model = SentenceTransformer(modules = modules, device = st_device)st_model.no_modules = no_modules- def _save_pretrained_merged(self, save_directory, **kwargs):+ def _save_pretrained_merged(+ self,+ save_directory,+ tokenizer = None,+ save_method = "merged_16bit",+ **kwargs,+ ):+ # Positional to match FastLanguageModel.save_pretrained_merged;+ # see the note on the other definition above. This path forwards to+ # that merge, which understands every save_method.+ save_method = _normalize_save_method(save_method)+ if self.no_modules and save_method not in ("merged_16bit", None):+ # The no_modules branch below merges and unloads unconditionally+ # and drops save_method, so accepting "lora" here would return+ # full weights for a request to write adapters. Refuse before+ # writing, as the fast-encoder definition above does.+ raise NotImplementedError(+ f"Unsloth: save_method = {save_method!r} is not supported "+ f"for this SentenceTransformer: no modules.json was found, "+ f"so Unsloth falls back to merge_and_unload, which can only "+ f"produce 'merged_16bit'."+ )+ if save_method is not None:+ kwargs.setdefault("save_method", save_method)# check which adapter files exist before save_pretrainedadapter_files = ["adapter_model.safetensors", "adapter_config.json"]existing_before = {@@ -1866,7 +1924,10 @@ class FastSentenceTransformer(FastModel):except:pass- tokenizer = kwargs.pop("tokenizer", self.tokenizer)+ if tokenizer is None:+ tokenizer = kwargs.pop("tokenizer", self.tokenizer)+ else:+ kwargs.pop("tokenizer", None)if self.no_modules:# fallback for non-sentence-transformers modelsprint("Unsloth: No modules detected. Using standard merge_and_unload for saving...")diff --git a/unsloth/save.py b/unsloth/save.pyindex ad1fa40648b..33ec0badbe9 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -531,8 +531,7 @@ def _preserve_sentencepiece_tokenizer_assets(json.dump(tokenizer_config, file, indent = 2, ensure_ascii = False)file.write("\n")logger.warning_once(- f"Unsloth: Restored added_tokens_decoder metadata in "- f"{tokenizer_config_path}."+ f"Unsloth: Restored added_tokens_decoder metadata in {tokenizer_config_path}.")tokenizer_model = os.path.join(save_directory, "tokenizer.model")@@ -581,7 +580,7 @@ def _preserve_sentencepiece_tokenizer_assets(if not os.path.isfile(tokenizer_model) and downloaded_path is not None:shutil.copy2(downloaded_path, tokenizer_model)logger.warning_once(- f"Unsloth: Preserved sentencepiece asset `tokenizer.model` in " f"{save_directory}."+ f"Unsloth: Preserved sentencepiece asset `tokenizer.model` in {save_directory}.")@@ -1158,8 +1157,8 @@ def unsloth_save_model(max_ram = int(max(0, max_ram) * maximum_memory_usage)print(f"Unsloth: Will use up to "- f"{round(max_ram/1024/1024/1024, 2)} out of "- f"{round(psutil.virtual_memory().total/1024/1024/1024, 2)} RAM for saving."+ f"{round(max_ram / 1024 / 1024 / 1024, 2)} out of "+ f"{round(psutil.virtual_memory().total / 1024 / 1024 / 1024, 2)} RAM for saving.")# Move temporary_location to /tmp in Kaggle@@ -1727,7 +1726,7 @@ def install_llama_cpp_old(version = -10):import timefor i in range(30):- print(f"**[WARNING]** Deleting llama.cpp directory... {30-i} seconds left.")+ print(f"**[WARNING]** Deleting llama.cpp directory... {30 - i} seconds left.")time.sleep(1)shutil.rmtree("llama.cpp", ignore_errors = True)@@ -1747,7 +1746,7 @@ def install_llama_cpp_old(version = -10):# Try using MAKEcommands = ["make clean -C llama.cpp",- f"make all -j{(psutil.cpu_count() or 1)*2} -C llama.cpp",+ f"make all -j{(psutil.cpu_count() or 1) * 2} -C llama.cpp",]use_cmake = try_execute(commands) == "CMAKE"@@ -1755,7 +1754,7 @@ def install_llama_cpp_old(version = -10):# Use CMAKEcommands = [f"cmake llama.cpp -B llama.cpp/build -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=OFF {CURL_FLAG}",- f"cmake --build llama.cpp/build --config Release -j{(psutil.cpu_count() or 1)*2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}",+ f"cmake --build llama.cpp/build --config Release -j{(psutil.cpu_count() or 1) * 2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}","cp llama.cpp/build/bin/llama-* llama.cpp","rm -rf llama.cpp/build",]@@ -1799,7 +1798,7 @@ def install_llama_cpp_blocking(use_cuda = False):# https://github.com/ggerganov/llama.cpp/issues/7062# Weirdly GPU conversion for GGUF breaks??# f"{use_cuda} make all -j{(psutil.cpu_count() or 1)*2} -C llama.cpp",- f"make all -j{(psutil.cpu_count() or 1)*2} -C llama.cpp",+ f"make all -j{(psutil.cpu_count() or 1) * 2} -C llama.cpp",]use_cmake = try_execute(commands) == "CMAKE"@@ -1807,7 +1806,7 @@ def install_llama_cpp_blocking(use_cuda = False):# Use CMAKEcommands = [f"cmake llama.cpp -B llama.cpp/build -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=OFF {CURL_FLAG}",- f"cmake --build llama.cpp/build --config Release -j{(psutil.cpu_count() or 1)*2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}",+ f"cmake --build llama.cpp/build --config Release -j{(psutil.cpu_count() or 1) * 2} --clean-first --target {' '.join(LLAMA_CPP_TARGETS)}","cp llama.cpp/build/bin/llama-* llama.cpp","rm -rf llama.cpp/build",]@@ -2026,7 +2025,13 @@ def save_to_gguf(# Check conversion successfor file in initial_files:if not os.path.exists(file):- if IS_KAGGLE_ENVIRONMENT:+ # Gated like the outer handler: the disk advice is only right when+ # the disk is actually the problem, and a converter that has no+ # llama.cpp support fails here with plenty of space free.+ if IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk(+ RuntimeError(f"Conversion produced no output at {file}"),+ os.path.dirname(file) or None,+ ):raise RuntimeError(f"Unsloth: Conversion failed for {file}\n""You are in a Kaggle environment with limited disk space (20GB).\n"@@ -2035,8 +2040,7 @@ def save_to_gguf()else:raise RuntimeError(- f"Unsloth: Conversion failed for {file}\n"- "Please check disk space and try again."+ f"Unsloth: Conversion failed for {file}\nPlease check disk space and try again.")# Move initial GGUF files into a dedicated _gguf directory@@ -2100,7 +2104,10 @@ def save_to_gguf(quant_kwargs["n_threads"] = n_threadsreturn quantize_gguf(**quant_kwargs)except Exception as e:- if IS_KAGGLE_ENVIRONMENT:+ # Same gate as above: a broken quantizer with 19GB free is not+ # a disk problem, and the outer handler cannot undo an+ # explanation already baked into this message.+ if IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk(e, gguf_directory):raise RuntimeError(f"Unsloth: Quantization failed for {output_location}\n""You are in a Kaggle environment, which might be the reason this is failing.\n"@@ -2111,7 +2118,7 @@ def save_to_gguf("You can try saving it to the `/tmp` directory for larger disk space.\n""I suggest you to save the 16bit model first, then use manual llama.cpp conversion.\n"f"Error: {e}"- )+ ) from eelse:if IS_WINDOWS:build_instructions = (@@ -2132,7 +2139,7 @@ def save_to_gguf(f"{build_instructions}\n""Once that's done, redo the quantization.\n"f"Error: {e}"- )+ ) from e # keep the cause: the OOM check walks it for the returncode# Outputs already on disk pre-date this run; never delete them on a failure.preexisting_outputs = {@@ -2863,6 +2870,38 @@ def push_to_ollama(tokenizer, gguf_location, username: str, model_name: str, tagprint("Successfully pushed to ollama")+def _offloaded_parameter_hint(model):+ """Sentence to append when a save failed on offloaded (meta) parameters.++ Accelerate leaves offloaded parameters on the meta device, so saving dies+ inside accelerate with "'NoneType' object is not subscriptable" or "Cannot+ copy out of meta tensor", neither of which names the offload. Returns ""+ when no meta parameter is present, so unrelated failures are not+ mislabelled.+ """+ try:+ meta = []+ for name, tensor in model.named_parameters():+ if getattr(tensor, "device", None) is not None and tensor.device.type == "meta":+ meta.append(name)+ # A 30B MoE has thousands; listing them would bury the error.+ if len(meta) >= 3:+ break+ if not meta:+ return ""+ return (+ f" Unsloth: this model has parameters on the meta device "+ f"(offloaded because it did not fit the GPU), for example "+ f"{', '.join(meta)}. Saving needs the real weights, which the "+ f"offload hooks do not expose here. Re-run on a GPU large enough "+ f"to hold the model without offloading, or reload it with "+ f"`device_map` pinned to a single device before saving."+ )+ except Exception:+ # A diagnostic must never replace the real error with its own.+ return ""++def _model_basename(name_or_path, default = "model") -> str:"""Leaf name of a model id or path, for use as a GGUF filename stem.@@ -3055,13 +3094,13 @@ def unsloth_save_pretrained_gguf(is_peft_model = isinstance(self, PeftModelForCausalLM) or isinstance(self, PeftModel)if is_peft_model:- print(f'Unsloth: Merging model weights to {"mxfp4" if is_gpt_oss else "16-bit"} format...')+ print(f"Unsloth: Merging model weights to {'mxfp4' if is_gpt_oss else '16-bit'} format...")try:# Call unsloth_generic_save directly (it's in the same file)unsloth_generic_save(**arguments)except Exception as e:- raise RuntimeError(f"Failed to save/merge model: {e}")+ raise RuntimeError(f"Failed to save/merge model: {e}{_offloaded_parameter_hint(self)}")else:# Non-PEFT model: checkpoint files already exist; point save_to_gguf# at the original path instead of re-saving to a temp subdir.@@ -3084,7 +3123,7 @@ 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}")+ raise RuntimeError(f"Failed to save model: {e}{_offloaded_parameter_hint(self)}")if is_processor:tokenizer = tokenizer.tokenizer@@ -3170,15 +3209,25 @@ def unsloth_save_pretrained_gguf(imatrix = imatrix_path,)except Exception as e:- if IS_KAGGLE_ENVIRONMENT:+ if _gguf_child_was_oom_killed(e):+ raise RuntimeError(+ f"Unsloth: GGUF conversion was killed by the operating system "+ f"(SIGKILL), which almost always means the machine ran out of "+ f"host RAM. The converter holds tensors in RAM, so this is "+ 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}"+ ) 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}"- )+ ) from eelse:- raise RuntimeError(f"Unsloth: GGUF conversion failed: {e}")+ raise RuntimeError(f"Unsloth: GGUF conversion failed: {e}") from e# Step 9: Create Ollama modelfilegguf_directory = f"{save_directory}_gguf"@@ -3245,6 +3294,104 @@ def unsloth_save_pretrained_gguf(}+# Errno 28 / ENOSPC and the wordings the various layers use for it.+_DISK_FULL_PATTERNS = (+ "no space left on device",+ "not enough free space",+ "disk quota exceeded",+ "errno 28",+ "insufficient disk",+ "write failed: no space",+)++# Kaggle allows 20GB. Below this headroom a failed conversion is plausibly+# about space; above it, blaming disk sends the user nowhere useful.+_DISK_HEADROOM_BYTES = 2 * 1024**3++# A SIGKILLed child is 128 + 9 to a shell, so llama-quantize (run through+# `shell = True`) surfaces as "returned non-zero exit status 137" with no+# signal named anywhere in the text.+_OOM_KILL_PATTERNS = (+ "sigkill",+ "exit status 137",+ "exit code 137",+ "exited with code 137",+ "exited with code -9",+)+++def _iter_exception_chain(exc, max_links = 10):+ """The exception plus its explicit causes and implicit contexts.++ Every layer here re-raises as a plain RuntimeError, so `returncode` and the+ original wording only survive on the chained cause.+ """+ seen = set()+ queue = [exc]+ while queue and len(seen) < max_links:+ current = queue.pop(0)+ if current is None or id(current) in seen:+ continue+ seen.add(id(current))+ yield current+ queue.append(getattr(current, "__cause__", None))+ queue.append(getattr(current, "__context__", None))+++def _gguf_child_was_oom_killed(exc):+ """Was the converter killed by the kernel rather than failing on its own?++ llama.cpp's converter loads tensors in host RAM, and a large model exceeds+ what a free Colab or Kaggle VM has. The kernel OOM-killer takes the process+ and subprocess reports only++ Command '[...]' died with <Signals.SIGKILL: 9>++ which says nothing about memory. Gemma3N_(4B)-Audio hits this on both the+ plain and the high-RAM T4, having trained, inferred and merged cleanly.++ SIGKILL alone is the signal: a converter that fails on its own raises and+ exits non-zero, so a kill is either the OOM-killer or someone stopping the+ run by hand, and both are worth naming.++ llama-quantize runs under a shell, which reports the kill as exit status+ 137 instead of a signal, and every layer re-raises as a plain RuntimeError,+ so the whole chain is checked rather than just the outermost exception.+ """+ for error in _iter_exception_chain(exc):+ if getattr(error, "returncode", None) in (-9, 137):+ return True+ text = f"{error}".lower()+ if any(pattern in text for pattern in _OOM_KILL_PATTERNS):+ return True+ return False+++def _gguf_failure_looks_like_disk(exc, save_directory = None):+ """Is this GGUF failure plausibly about running out of disk?++ Two independent signals, either alone sufficient: each can be absent for a+ good reason. The message may name ENOSPC after the directory was cleaned+ up, and the disk may be genuinely full while a subprocess surfaced+ something vaguer. Never raises; an unreadable path just means "not disk".+ """+ text = f"{type(exc).__name__}: {exc}".lower()+ if any(p in text for p in _DISK_FULL_PATTERNS):+ return True+ if getattr(exc, "errno", None) == 28:+ return True+ for path in (save_directory, os.getcwd()):+ if not path:+ continue+ try:+ if shutil.disk_usage(path).free < _DISK_HEADROOM_BYTES:+ return True+ except OSError:+ # Never let the diagnostic be the thing that raises.+ continue+ return False++def unsloth_push_to_hub_gguf(self,repo_id: str,