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.

Use Kaggle's large overlay for saves, and refuse a GGUF export that cannot fit (#8439)

Daniel Han48ea5560ee0c
diff --git a/tests/saving/test_gguf_disk_preflight.py b/tests/saving/test_gguf_disk_preflight.py
new file mode 100644
index 00000000000..424d4ba34ed
--- /dev/null
+++ b/tests/saving/test_gguf_disk_preflight.py
@@ -0,0 +1,3845 @@
+# 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 disk preflight in front of a GGUF export, and its wiring.
+
+Three notebooks -- Gemma4 (26B A4B) Vision, Gemma4 (31B) Vision and Qwen3 32B
+-- trained, ran inference and wrote a complete `merged_16bit`, then died
+partway through a GGUF shard with the VM out of space. The size estimate in
+front of them counted the model twice. The real peak is four artefacts on one
+filesystem: the pre-warmed base in the Hugging Face cache, the 16-bit merge,
+the intermediate GGUF and the quants.
+
+The arithmetic itself is unsloth_zoo's, and is tested in
+`unsloth_zoo/tests/test_disk_utils_kaggle.py`. What is tested here is
+unsloth's use of it: which of the three outcomes it picks (proceed / drop the
+pre-warm / refuse), that it never blocks on an unmeasurable number, and that
+nothing it computes leaks into the kwargs of a save.
+
+The sizing functions are stubbed rather than exercised, so this runs on CPU,
+in milliseconds, against any installed unsloth_zoo.
+"""
+
+import contextlib
+import math
+import os
+
+import pytest
+
+from unsloth import save as S
+
+GB = 1024**3
+
+
+def _with_merge_headroom(n_bytes):
+ """What `merge_and_overwrite_lora` needs free to write `n_bytes` of merge.
+
+ unsloth_zoo's merge guard compares against `int(free * 0.95)`, so the
+ preflight has to ask for the same effective figure. The 0.95 is written
+ out rather than read from `S`, so dropping the headroom fails here.
+ """
+ return math.ceil(n_bytes / 0.95)
+
+
+def _merge_preflight_ask(total_bytes, merge_bytes):
+ """What the merge preflight asks for, given what lands where.
+
+ The reserve belongs on the merge alone, because that is the only artefact
+ `merge_and_overwrite_lora` writes and the only one its guard measures. A
+ quantized sibling beside it, a torchao sibling with the merge staged in a
+ temp directory, and a full-model `"lora"` save written straight through
+ `save_pretrained` are all charged at face value. Reserving around the whole
+ estimate instead moves an export that fits, and on Kaggle "moves" means
+ into a /tmp the kernel does not keep as notebook output.
+ """
+ return max(math.ceil(total_bytes), _with_merge_headroom(merge_bytes))
+
+
+class _FakeModel:
+ """Not a PeftModel; the preflight is called with an explicit needs_merge."""
+
+
+class _ModelWithLayers:
+ """The `.model.layers` layout `unsloth_save_model` rebuilds a dict for.
+
+ Anything else takes its generic fallback, which hands the caller's
+ dictionary to `save_pretrained` untouched.
+ """
+
+ class _Inner:
+ layers = ()
+
+ def __init__(self):
+ self.model = self._Inner()
+
+
+class _FakeAdapterModel:
+ """Stands in for a PeftModel: monkeypatch `S.PeftModel` onto this class.
+
+ Building a real one needs a base model and an adapter config, and the
+ preflight only ever asks `isinstance`.
+ """
+
+
+class _ModelWithEmbeddings:
+ """Answers the two embedding getters a weight-only export leaves alone."""
+
+ class _Weight:
+ def __init__(self, numel):
+ self._numel = numel
+
+ def numel(self):
+ return self._numel
+
+ class _Embedding:
+ def __init__(self, weight):
+ self.weight = weight
+
+ def __init__(
+ self,
+ input_numel,
+ output_numel = 0,
+ tied = False,
+ ):
+ self._input = self._Embedding(self._Weight(input_numel))
+ if tied:
+ self._output = self._input
+ elif output_numel:
+ self._output = self._Embedding(self._Weight(output_numel))
+ else:
+ self._output = None
+
+ def get_input_embeddings(self):
+ return self._input
+
+ def get_output_embeddings(self):
+ return self._output
+
+
+def stub_sizing(monkeypatch):
+ """Replace the size and free-space calls with numbers a test dictates.
+
+ Returns a setter. `need` is the export without the cached base, and
+ `need_with_cache` the export with it.
+ """
+ state = {"need": 0, "need_with_cache": 0, "free": None, "redirect": (None, None)}
+
+ def fake_estimate(**kwargs):
+ return state["need_with_cache"] if kwargs.get("base_cache_copy") else state["need"]
+
+ def fake_free(path):
+ return state["free"]
+
+ def fake_redirect(
+ save_directory,
+ need_bytes = 0,
+ what = "export",
+ ):
+ target, message = state["redirect"]
+ if message is None:
+ return save_directory, None
+ return target, message
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(S, "free_bytes", fake_free)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", fake_redirect)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+
+ def configure(**kwargs):
+ state.update(kwargs)
+ return state
+
+ return configure
+
+
+class TestNormalizeQuantizationMethods:
+ def test_friendly_aliases(self):
+ assert S._normalize_quantization_methods("fast_quantized") == ["q8_0"]
+ assert S._normalize_quantization_methods("quantized") == ["q4_k_m"]
+ assert S._normalize_quantization_methods("not_quantized") == ["f16"]
+
+ def test_list_and_case(self):
+ assert S._normalize_quantization_methods(["Q4_K_M", "Q8_0"]) == ["q4_k_m", "q8_0"]
+
+ def test_none_entries_become_the_default(self):
+ assert S._normalize_quantization_methods([None]) == ["q8_0"]
+
+ def test_none_and_junk_are_empty(self):
+ assert S._normalize_quantization_methods(None) == []
+ assert S._normalize_quantization_methods(object()) == []
+
+
+class TestPreflightOutcomes:
+ def test_plenty_of_room_changes_nothing(self, stub_sizing):
+ stub_sizing(need = 30 * GB, need_with_cache = 44 * GB, free = 500 * GB)
+ directory, prewarm_ok = S._preflight_gguf_disk(
+ _FakeModel(), "model", "q4_k_m", first_conversion = "f16"
+ )
+ assert directory == "model"
+ assert prewarm_ok is True
+
+ def test_fits_only_without_the_prewarm(self, stub_sizing, capsys):
+ """The Gemma4 31B case: drop the cache, keep the export."""
+ stub_sizing(need = 148 * GB, need_with_cache = 206 * GB, free = 174 * GB)
+ directory, prewarm_ok = S._preflight_gguf_disk(
+ _FakeModel(), "model", "q8_0", first_conversion = "f16"
+ )
+ assert directory == "model"
+ assert prewarm_ok is False, "refusing here would decline an export that fits"
+ out = capsys.readouterr().out
+ assert "pre-warm" in out
+
+ def test_does_not_fit_at_all_raises_with_the_numbers(self, stub_sizing):
+ stub_sizing(need = 40 * GB, need_with_cache = 54 * GB, free = 19 * GB)
+ with pytest.raises(RuntimeError) as excinfo:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", first_conversion = "f16")
+ message = str(excinfo.value)
+ assert "40.0GB" in message and "19.0GB" in message
+ # Actionable, not merely correct.
+ assert "push_to_hub_gguf" in message
+ assert "UNSLOTH_DISK_PREFLIGHT=0" in message
+ assert "q4_k_m" in message
+
+ def test_unmeasurable_model_never_blocks(self, stub_sizing, monkeypatch):
+ """A guard that blocks on a guess is worse than no guard.
+
+ With no size to work from there is also nothing to justify moving the
+ files, so the Kaggle redirect must not even be consulted -- otherwise
+ an unmeasurable model on Kaggle gets relocated on the strength of
+ `need_bytes = 0`.
+ """
+ redirect_calls = []
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda *a, **k: redirect_calls.append((a, k)) or (a[0], None),
+ )
+ stub_sizing(need = 0, need_with_cache = 0, free = 0)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+ assert redirect_calls == []
+
+ def test_unmeasurable_disk_never_blocks(self, stub_sizing):
+ stub_sizing(need = 10**15, need_with_cache = 10**15, free = None)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ def test_sizing_that_raises_never_blocks(self, monkeypatch):
+ def boom(**kwargs):
+ raise RuntimeError("no")
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", boom)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ @pytest.mark.parametrize("value", ["0", "false", "no", "off", "OFF"])
+ def test_kill_switch(self, stub_sizing, monkeypatch, value):
+ stub_sizing(need = 10**15, need_with_cache = 10**15, free = 1)
+ monkeypatch.setenv("UNSLOTH_DISK_PREFLIGHT", value)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ def test_prewarm_already_off_is_not_offered_as_a_saving(self, stub_sizing, monkeypatch):
+ """With the pre-warm already disabled there is no cache copy to drop."""
+ monkeypatch.setenv("UNSLOTH_PREWARM_HUB_CACHE", "0")
+ stub_sizing(need = 148 * GB, need_with_cache = 206 * GB, free = 174 * GB)
+ directory, prewarm_ok = S._preflight_gguf_disk(
+ _FakeModel(), "model", "q8_0", first_conversion = "f16"
+ )
+ assert (directory, prewarm_ok) == ("model", True)
+
+ def test_non_peft_export_has_no_merge_and_no_cache_copy(self, stub_sizing, monkeypatch):
+ seen = {}
+
+ def fake_estimate(**kwargs):
+ seen.update(kwargs)
+ return 1
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ stub_sizing(free = 10 * GB)
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", needs_merge = False)
+ assert seen["needs_merge"] is False
+ # No merge means no pre-warm, so no cache copy is ever priced in.
+ assert seen.get("base_cache_copy") in (None, False)
+
+
+class TestKaggleRedirectWiring:
+ def test_redirect_is_taken_and_announced_once(self, stub_sizing, capsys):
+ stub_sizing(
+ need = 34 * GB,
+ need_with_cache = 48 * GB,
+ free = 1000 * GB,
+ redirect = ("/tmp/unsloth_saves/model", "Unsloth: moved, /tmp is not saved"),
+ )
+ directory, prewarm_ok = S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert directory == "/tmp/unsloth_saves/model"
+ out = capsys.readouterr().out
+ assert out.count("Unsloth: moved") == 1
+
+ def test_the_redirected_directory_is_what_gets_size_checked(self, stub_sizing, monkeypatch):
+ """A redirect that is not re-measured would report the old disk."""
+ probed = []
+
+ def fake_free(path):
+ probed.append(path)
+ return 1000 * GB
+
+ stub_sizing(
+ need = 34 * GB,
+ need_with_cache = 48 * GB,
+ redirect = ("/tmp/unsloth_saves/model", "moved"),
+ )
+ monkeypatch.setattr(S, "free_bytes", fake_free)
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ # The `_gguf` sibling is measured as well, and so is the working
+ # directory the intermediate conversion is written to. What must never
+ # be measured is the directory the redirect moved away from.
+ assert probed[0] == "/tmp/unsloth_saves/model"
+ assert "model" not in probed
+ assert set(probed) <= {
+ "/tmp/unsloth_saves/model",
+ "/tmp/unsloth_saves/model_gguf",
+ os.getcwd(),
+ }
+
+ def test_merge_preflight_never_rewrites_a_repo_id(self, monkeypatch):
+ """`push_to_hub=True` makes save_directory "user/model", not a path."""
+ called = []
+ monkeypatch.setattr(
+ S, "kaggle_tmp_redirect", lambda *a, **k: called.append(a) or ("/tmp/x", "moved")
+ )
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", lambda **k: 10 * GB)
+ result = S._preflight_merge_disk(
+ _FakeModel(), "danielhanchen/my-model", "merged_16bit", push_to_hub = True
+ )
+ assert result == "danielhanchen/my-model"
+ assert called == []
+
+ def test_merge_preflight_skips_an_export_that_writes_no_checkpoint(self, monkeypatch):
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("/tmp/x", "moved"))
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ assert S._preflight_merge_disk(_FakeModel(), "model", "merged_4bit") == "model"
+
+ def test_merge_preflight_skips_adapters(self, monkeypatch):
+ """`lora` on a real PeftModel writes adapters, which are megabytes."""
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("/tmp/x", "moved"))
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ assert S._preflight_merge_disk(_FakeAdapterModel(), "model", "lora") == "model"
+
+ def test_merge_preflight_takes_the_redirect(self, monkeypatch, capsys):
+ monkeypatch.setattr(
+ S, "kaggle_tmp_redirect", lambda *a, **k: ("/tmp/unsloth_saves/model", "moved")
+ )
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ assert S._preflight_merge_disk(_FakeModel(), "model", "merged_16bit") == (
+ "/tmp/unsloth_saves/model"
+ )
+ assert "moved" in capsys.readouterr().out
+
+ def test_merge_preflight_never_raises(self, monkeypatch):
+ def boom(model):
+ raise RuntimeError("no")
+
+ monkeypatch.setattr(S, "model_16bit_bytes", boom)
+ assert S._preflight_merge_disk(_FakeModel(), "model", "merged_16bit") == "model"
+
+
+class TestPrewarmContextManager:
+ def test_disables_and_restores_a_previous_value(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_PREWARM_HUB_CACHE", "1")
+ with S._hub_cache_prewarm_disabled(True):
+ assert os.environ["UNSLOTH_PREWARM_HUB_CACHE"] == "0"
+ assert os.environ["UNSLOTH_PREWARM_HUB_CACHE"] == "1"
+
+ def test_removes_the_variable_it_invented(self, monkeypatch):
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ with S._hub_cache_prewarm_disabled(True):
+ assert os.environ["UNSLOTH_PREWARM_HUB_CACHE"] == "0"
+ assert "UNSLOTH_PREWARM_HUB_CACHE" not in os.environ
+
+ def test_restores_on_an_exception(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_PREWARM_HUB_CACHE", "1")
+ with pytest.raises(ValueError):
+ with S._hub_cache_prewarm_disabled(True):
+ raise ValueError("merge blew up")
+ assert os.environ["UNSLOTH_PREWARM_HUB_CACHE"] == "1"
+
+ def test_no_op_when_not_disabling(self, monkeypatch):
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ with S._hub_cache_prewarm_disabled(False):
+ assert "UNSLOTH_PREWARM_HUB_CACHE" not in os.environ
+
+
+class TestNoLeakIntoSaveKwargs:
+ def test_preflight_locals_never_reach_unsloth_generic_save(self):
+ """`arguments = dict(locals())` snapshots every local in scope.
+
+ The preflight adds one, and `unsloth_generic_save` takes named
+ keyword arguments, so forgetting the matching `del` turns every GGUF
+ export into `TypeError: unexpected keyword argument`. Read the
+ function rather than run it: reaching this line for real needs a
+ loaded 4-bit model and a llama.cpp build.
+ """
+ import inspect
+
+ source = inspect.getsource(S.unsloth_save_pretrained_gguf)
+ assert "_gguf_prewarm_ok" in source
+ assert 'del arguments["_gguf_prewarm_ok"]' in source
+
+ accepted = set(inspect.signature(S.unsloth_generic_save).parameters)
+ deleted = set()
+ for line in source.splitlines():
+ line = line.strip()
+ if line.startswith('del arguments["'):
+ deleted.add(line.split('"')[1])
+ # Every local that exists at the snapshot point and is not a parameter
+ # of unsloth_generic_save has to be deleted before the call.
+ introduced = {
+ "self",
+ "base_model_name",
+ "model_name",
+ "is_vlm",
+ "is_processor",
+ "is_gpt_oss",
+ "_gguf_prewarm_ok",
+ "quantization_method",
+ "first_conversion",
+ "imatrix_file",
+ }
+ for name in introduced - accepted:
+ assert name in deleted, f"{name} would be passed to unsloth_generic_save"
+
+
+# The unsloth_zoo.disk_utils signatures, transcribed. The fixtures above accept
+# `**kwargs`, which is convenient and hides the one failure that matters: an
+# argument the real function does not take raises TypeError, and every caller
+# here swallows exceptions, so the guard silently turns itself off.
+# `test_reference_signatures_match_the_installed_zoo` keeps these honest.
+def _zoo_estimate_gguf_export_bytes(
+ model = None,
+ quantization_methods = (),
+ first_conversion = "f16",
+ needs_merge = True,
+ n_parameters = None,
+ base_cache_copy = False,
+):
+ return 10 * GB
+
+
+def _zoo_model_16bit_bytes(model):
+ return 10 * GB
+
+
+def _zoo_kaggle_tmp_redirect(
+ save_directory,
+ need_bytes = 0,
+ what = "export",
+ subdirectory = "unsloth_saves",
+):
+ return "/tmp/unsloth_saves/model", "moved"
+
+
+def zoo_api(monkeypatch):
+ """Bind the preflights against the real zoo signatures, not `**kwargs`."""
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", _zoo_estimate_gguf_export_bytes)
+ monkeypatch.setattr(S, "model_16bit_bytes", _zoo_model_16bit_bytes)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", _zoo_kaggle_tmp_redirect)
+ monkeypatch.setattr(S, "free_bytes", lambda path: 1000 * GB)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+
+
+class TestCallsBindToTheZooApi:
+ """A guard that cannot call its own sizing function is not a guard.
+
+ `_preflight_merge_disk` passed `keep_intermediate_gguf`, which
+ `unsloth_zoo.disk_utils.estimate_gguf_export_bytes` does not accept, so
+ every call raised TypeError into the surrounding `except Exception` and
+ no `save_pretrained_merged` was ever redirected on Kaggle.
+ """
+
+ def test_merge_preflight_reaches_the_redirect(self, zoo_api):
+ assert (
+ S._preflight_merge_disk(_FakeModel(), "model", "merged_16bit")
+ == "/tmp/unsloth_saves/model"
+ )
+
+ def test_gguf_preflight_reaches_the_redirect(self, zoo_api):
+ directory, _ = S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert directory == "/tmp/unsloth_saves/model"
+
+ def test_reference_signatures_match_the_installed_zoo(self):
+ import inspect
+ disk_utils = pytest.importorskip("unsloth_zoo.disk_utils")
+ for reference, name in (
+ (_zoo_estimate_gguf_export_bytes, "estimate_gguf_export_bytes"),
+ (_zoo_model_16bit_bytes, "model_16bit_bytes"),
+ (_zoo_kaggle_tmp_redirect, "kaggle_tmp_redirect"),
+ ):
+ assert inspect.signature(reference) == inspect.signature(
+ getattr(disk_utils, name)
+ ), f"{name} drifted; the stubs above no longer prove anything"
+
+
+class TestMergeSizing:
+ """A merge writes the model once, and a compressed export writes it twice."""
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ def test_a_plain_merge_is_two_bytes_per_parameter(self, sized):
+ S._preflight_merge_disk(_FakeModel(), "model", "merged_16bit")
+ # Not the GGUF estimate, which would add an intermediate conversion
+ # this export never writes. No headroom either: `_FakeModel` has no
+ # adapter, so nothing here reaches `merge_and_overwrite_lora`.
+ assert sized == [_merge_preflight_ask(10 * GB, 0)]
+
+ @pytest.mark.parametrize("save_method", ["merged 16bit", "MERGED_16BIT", " merged-16bit "])
+ def test_supported_spellings_are_measured_too(self, sized, save_method):
+ """`unsloth_save_model` normalizes spaces, so these are the same export."""
+ S._preflight_merge_disk(_FakeModel(), "model", save_method)
+ assert sized == [_merge_preflight_ask(10 * GB, 0)]
+
+ @pytest.mark.parametrize(
+ "save_method,expected_gb",
+ [
+ ("fp8", 15), # 16-bit merge + an 8-bit sibling
+ ("mxfp8", 15),
+ ("int8", 15),
+ ("mxfp4", 12.5), # 16-bit merge + a 4-bit sibling
+ ("nvfp4", 12.5),
+ ("w4a16", 12.5),
+ ],
+ )
+ def test_every_compressed_export_sizes_its_sibling(self, sized, save_method, expected_gb):
+ """`_unsloth_save_compressed_tensors` keeps the merge AND the sibling."""
+ S._preflight_merge_disk(_FakeModel(), "model", save_method)
+ assert sized == [pytest.approx(_merge_preflight_ask(expected_gb * GB, 10 * GB))]
+
+ def test_an_unsupported_near_miss_is_left_to_its_own_error(self, sized):
+ """`_normalize_compressed_method` raises on these; the message is downstream."""
+ assert S._preflight_merge_disk(_FakeModel(), "model", "fp4_banana") == "model"
+ assert sized == []
+
+ @pytest.mark.parametrize(
+ "save_method", ["torchao_fp8", "torchao_int8", "portable_fp8", "portable-int8"]
+ )
+ def test_a_torchao_export_is_sized_by_its_sibling_alone(self, sized, save_method):
+ """The torchao path merges into a temp dir, not into `save_directory`.
+
+ So `save_directory` holds the 8-bit sibling only, and pricing the
+ 16-bit merge there as well would move an export that fits. No merge
+ guard runs against this filesystem either, so no reserve is charged.
+ """
+ S._preflight_merge_disk(_FakeModel(), "model", save_method)
+ assert sized == [_merge_preflight_ask(5 * GB, 0)]
+
+ def test_the_embeddings_are_not_priced_as_quantized(self, sized):
+ """Weight-only schemes quantize `Linear` only.
+
+ The input embeddings and an untied lm_head stay 16-bit in the sibling,
+ so a model that is a quarter embeddings costs more than half the merge.
+ """
+ model = _ModelWithEmbeddings(input_numel = 1024**3, output_numel = 1024**3 // 2)
+ # 10GB merge, 3GB of it embeddings -> 7GB at 8 bits + 3GB copied.
+ S._preflight_merge_disk(model, "model", "fp8")
+ assert sized == [_merge_preflight_ask(10 * GB + 3 * GB + int(3.5 * GB), 10 * GB)]
+
+ def test_tied_embeddings_are_counted_once(self, sized):
+ model = _ModelWithEmbeddings(input_numel = 1024**3, tied = True)
+ S._preflight_merge_disk(model, "model", "fp8")
+ assert sized == [_merge_preflight_ask(10 * GB + 2 * GB + 4 * GB, 10 * GB)]
+
+ def test_a_model_that_does_not_answer_is_sized_as_before(self, sized):
+ """The old whole-model arithmetic, so this can only ever ask for more."""
+ S._preflight_merge_disk(_FakeModel(), "model", "fp8")
+ assert sized == [_merge_preflight_ask(15 * GB, 10 * GB)]
+
+ def test_the_torchao_merge_really_is_staged_elsewhere(self):
+ """The sizing above is only right while this stays true."""
+ import inspect
+
+ source = inspect.getsource(S._unsloth_save_torchao)
+ assert "mkdtemp" in source
+ assert "save_directory = staging" in source
+ assert 'out_dir = base + "-" + suffix' in source
+
+
+class _FakeParameter:
+ """A parameter the sizing can measure without torch."""
+
+ def __init__(self, numel):
+ self._numel = numel
+
+ def numel(self):
+ return self._numel
+
+
+class _FakeModule:
+ """A module tree answering the two calls the sizing makes.
+
+ `parameters()` recurses, exactly as `torch.nn.Module.parameters()` does,
+ so a parent that matches an ignore pattern reports its children's weights
+ too and the deduplication has something to do.
+ """
+
+ def __init__(
+ self,
+ parameters = (),
+ children = None,
+ ):
+ self._parameters = list(parameters)
+ self._children = dict(children or {})
+
+ def parameters(self):
+ for parameter in self._parameters:
+ yield parameter
+ for child in self._children.values():
+ yield from child.parameters()
+
+ def named_modules(self, prefix = ""):
+ yield prefix, self
+ for name, child in self._children.items():
+ yield from child.named_modules(f"{prefix}.{name}" if prefix else name)
+
+
+class _ShapedModel(_FakeModule):
+ """A named module tree plus the embedding getters and a config."""
+
+ def __init__(
+ self,
+ children,
+ config,
+ input_embeddings = None,
+ output_embeddings = None,
+ ):
+ super().__init__(children = children)
+ self.config = config
+ self._input = input_embeddings
+ self._output = output_embeddings
+
+ def get_input_embeddings(self):
+ return self._input
+
+ def get_output_embeddings(self):
+ return self._output
+
+
+class _Config:
+ def __init__(self, **kwargs):
+ self.model_type = ""
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+
+def _embedding(numel):
+ """A module whose single weight is also what the getters return."""
+ parameter = _FakeParameter(numel)
+ module = _FakeModule(parameters = [parameter])
+ module.weight = parameter
+ return module
+
+
+def _sibling_bytes(merge_bytes, unquantized_bytes, weight_bits):
+ """The arithmetic `_quantized_sibling_bytes` does, written out."""
+ return int((merge_bytes - unquantized_bytes) * weight_bits / 16) + unquantized_bytes
+
+
+class TestTheRecipesIgnoredModulesStay16Bit:
+ """Everything `_compressed_quantize`'s recipe refuses to quantize is copied at 16 bits.
+
+ The recipe ignores `lm_head`, every module under a `linear_attn` or a
+ `visual`, anything named `*mtp*`, and on an MoE the router gates. Only the
+ embeddings were priced at 16 bits here, so a VLM's vision tower or a
+ hybrid's linear attention was charged 4 or 8 bits for bytes the export
+ writes at 16 - an under-count, which is the direction that loses the
+ Kaggle redirect an export needed.
+ """
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ def _vlm(self):
+ """A 10GB VLM: 2GB of input embeddings and a 1GB vision tower."""
+ embeddings = _embedding(1024**3)
+ visual = _FakeModule(
+ children = {
+ "blocks": _FakeModule(
+ children = {
+ "0": _FakeModule(
+ children = {
+ "attn": _FakeModule(parameters = [_FakeParameter(1024**3 // 2)]),
+ }
+ ),
+ }
+ ),
+ }
+ )
+ return _ShapedModel(
+ children = {
+ "model": _FakeModule(children = {"embed_tokens": embeddings, "visual": visual}),
+ },
+ config = _Config(model_type = "qwen3_vl"),
+ input_embeddings = embeddings,
+ )
+
+ def test_a_vision_tower_is_not_priced_as_quantized(self, sized):
+ S._preflight_merge_disk(self._vlm(), "model", "fp8")
+ # 2GB embeddings + 1GB vision tower stay 16-bit; the other 7GB go to 8.
+ expected = 10 * GB + _sibling_bytes(10 * GB, 3 * GB, 8)
+ assert sized == [_merge_preflight_ask(expected, 10 * GB)]
+ # And strictly more than the embeddings-only figure this replaces, which
+ # is the whole point: the old estimate was short.
+ assert sized[0] > _merge_preflight_ask(
+ 10 * GB + _sibling_bytes(10 * GB, 2 * GB, 8), 10 * GB
+ )
+
+ def test_the_vision_tower_is_counted_once(self):
+ """`re:.*\\.visual\\..*` matches the tower's children, not just the tower."""
+ model = self._vlm()
+ patterns = S._compressed_ignore_patterns(model)
+ assert S._unquantized_parameter_bytes(model, patterns) == 3 * GB
+
+ def test_a_torchao_export_is_charged_none_of_them(self, sized):
+ """torchao quantizes with no ignore list, so charging these over-counts."""
+ S._preflight_merge_disk(self._vlm(), "model", "torchao_fp8")
+ assert sized == [_merge_preflight_ask(_sibling_bytes(10 * GB, 2 * GB, 8), 0)]
+
+ def test_an_lm_head_module_is_not_counted_twice(self):
+ """`lm_head` is both `get_output_embeddings()` and an ignored name."""
+ embeddings = _embedding(1024**3)
+ head = _embedding(1024**3)
+ model = _ShapedModel(
+ children = {"model": _FakeModule(children = {"embed_tokens": embeddings}), "lm_head": head},
+ config = _Config(model_type = "llama"),
+ input_embeddings = embeddings,
+ output_embeddings = head,
+ )
+ patterns = S._compressed_ignore_patterns(model)
+ assert "lm_head" in patterns
+ assert S._unquantized_parameter_bytes(model, patterns) == 4 * GB
+
+ def test_the_moe_gates_are_counted_and_gate_proj_is_not(self):
+ """`re:.*\\.gate$` is anchored: it must not swallow `gate_proj`."""
+ embeddings = _embedding(1024**3)
+ layer = _FakeModule(
+ children = {
+ "mlp": _FakeModule(
+ children = {
+ "gate": _FakeModule(parameters = [_FakeParameter(1024**3 // 2)]),
+ "gate_proj": _FakeModule(parameters = [_FakeParameter(1024**3)]),
+ }
+ ),
+ }
+ )
+ model = _ShapedModel(
+ children = {
+ "model": _FakeModule(
+ children = {
+ "embed_tokens": embeddings,
+ "layers": _FakeModule(children = {"0": layer}),
+ },
+ ),
+ },
+ config = _Config(model_type = "qwen3_moe", num_experts = 128),
+ input_embeddings = embeddings,
+ )
+ patterns = S._compressed_ignore_patterns(model)
+ assert "re:.*\\.gate$" in patterns
+ # 2GB embeddings + 1GB router gate. `gate_proj` is 2GB and quantizes.
+ assert S._unquantized_parameter_bytes(model, patterns) == 3 * GB
+
+ def test_a_dense_model_gets_no_gate_patterns(self):
+ model = _ShapedModel(children = {}, config = _Config(model_type = "llama"))
+ assert "re:.*\\.gate$" not in S._compressed_ignore_patterns(model)
+
+ def test_a_model_whose_modules_cannot_be_walked_keeps_the_old_figure(self):
+ """Degrade to today's behaviour rather than raise."""
+ model = self._vlm()
+
+ def explode():
+ raise RuntimeError("no modules here")
+
+ model.named_modules = explode
+ assert S._unquantized_parameter_bytes(model, S._compressed_ignore_patterns(model)) == 2 * GB
+
+ def test_a_missing_recipe_symbol_leaves_the_estimate_alone(self, monkeypatch):
+ """A renamed or deleted `compressed_ignore_patterns` must not raise."""
+ import unsloth._compressed_quantize as Q
+
+ monkeypatch.delattr(Q, "compressed_ignore_patterns")
+ assert S._compressed_ignore_patterns(self._vlm()) == []
+
+ def test_an_unparseable_pattern_matches_nothing(self):
+ module = _FakeModule(parameters = [_FakeParameter(1024**3)])
+ assert not S._matches_ignore_pattern("model.visual.attn", module, ["re:*["])
+
+ def test_the_matcher_mirrors_compressed_tensors(self):
+ """`re:` is `re.match` (start-anchored, not full); plain is an exact name."""
+ module = _FakeModule()
+ assert S._matches_ignore_pattern("visual.blocks.0", module, ["re:visual.*"])
+ # Start-anchored: a mid-string match is not one.
+ assert not S._matches_ignore_pattern("model.visual.blocks", module, ["re:visual.*"])
+ assert S._matches_ignore_pattern("model.visual.blocks", module, ["re:.*\\.visual\\..*"])
+ # Not required to reach the end of the name.
+ assert S._matches_ignore_pattern("model.mtp.layers.0", module, ["re:.*mtp.*"])
+ # Plain entries are exact, never substrings.
+ assert S._matches_ignore_pattern("lm_head", module, ["lm_head"])
+ assert not S._matches_ignore_pattern("model.lm_head", module, ["lm_head"])
+ # Plain entries also match a parent class name, as `_match_class` does.
+ assert S._matches_ignore_pattern("anything", module, ["_FakeModule"])
+
+ def test_the_recipe_is_read_from_the_runner_not_restated(self):
+ """The drift this fixes is two copies of one list; keep there being one."""
+ import inspect
+
+ source = inspect.getsource(S._compressed_ignore_patterns)
+ assert "from unsloth._compressed_quantize import compressed_ignore_patterns" in source
+ import unsloth._compressed_quantize as Q
+
+ main_source = inspect.getsource(Q.main)
+ assert "compressed_ignore_patterns(config)" in main_source
+ assert "re:.*mtp.*" not in main_source, "main() must not rebuild the list"
+
+
+class TestTorchaoStagingSharesTheRedirectDestination:
+ """The torchao staging merge is on /tmp, and so is the redirect target.
+
+ `_unsloth_save_torchao` merges into `tempfile.mkdtemp()` and deletes it
+ only after quantization, so on a Kaggle kernel both artefacts are on /tmp
+ at once. Sending the sibling to a /tmp that cannot hold the staging merge
+ as well turns an export that fit in /kaggle/working into a disk-full
+ failure, so a destination that is too small for both is not used.
+
+ The staging bytes are deliberately NOT added to `need_bytes`: nothing
+ stages in the working directory, and charging it there would relocate
+ exports that fit into /tmp, which is not kept as notebook output.
+ """
+
+ @pytest.fixture
+ def redirected(self, monkeypatch, tmp_path):
+ """A redirect that always fires, onto a real directory the test owns."""
+ target = str(tmp_path)
+ free = {"bytes": 0}
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (target, "moved"),
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: free["bytes"])
+ monkeypatch.setattr(S, "_same_filesystem", lambda left, right: True)
+ return target, free
+
+ # 10GB merge -> a 5GB sibling. No headroom: the merge is staged in a temp
+ # directory, so no merge guard ever measures this filesystem.
+ _SIBLING = 5 * GB
+
+ def test_room_for_the_sibling_alone_is_not_enough(self, redirected):
+ target, free = redirected
+ free["bytes"] = self._SIBLING + 10 * GB - 1
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == "model"
+
+ def test_room_for_both_takes_the_redirect(self, redirected):
+ target, free = redirected
+ free["bytes"] = self._SIBLING + 10 * GB
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == target
+
+ def test_a_separate_staging_filesystem_is_not_charged(self, redirected, monkeypatch):
+ """Off Kaggle `tempfile` can be its own mount; then only the sibling lands here."""
+ target, free = redirected
+ free["bytes"] = self._SIBLING
+ monkeypatch.setattr(S, "_same_filesystem", lambda left, right: False)
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == target
+
+ @pytest.mark.parametrize("save_method", ["merged_16bit", "fp8", "mxfp4"])
+ def test_an_export_that_stages_nothing_is_never_cancelled(self, redirected, save_method):
+ """Only torchao stages a second copy; the rest write into `save_directory`."""
+ target, free = redirected
+ free["bytes"] = 0
+ assert S._preflight_merge_disk(_FakeModel(), "model", save_method) == target
+
+ def test_an_unmeasurable_destination_takes_the_redirect(self, redirected):
+ target, free = redirected
+ free["bytes"] = None
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == target
+
+ def test_the_staging_is_not_charged_to_the_working_directory(self, monkeypatch):
+ """What `kaggle_tmp_redirect` is asked for stays the sibling alone."""
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ assert asked == [self._SIBLING]
+
+ def test_a_cancelled_redirect_says_the_filesystem_is_short(self, monkeypatch, capsys):
+ """The one outcome nothing downstream measures.
+
+ The redirect fired because /kaggle/working could not hold the 5GB
+ sibling, and it was cancelled because /tmp cannot hold that sibling
+ and the 10GB staging merge together. The export is handed back a
+ filesystem with 4GB free, the torchao merge guard only ever measures
+ the staging disk, and the sibling is written at the end of a long
+ quantization, so this has to be said up front.
+ """
+ import tempfile
+
+ working, scratch = 4 * GB, 12 * GB
+ on_tmp = lambda path: str(path).startswith("/tmp") or str(path) == tempfile.gettempdir()
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ ("/tmp/unsloth_saves/model", "moved")
+ if working < need_bytes <= scratch
+ else (save_directory, None)
+ ),
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: scratch if on_tmp(path) else working)
+ monkeypatch.setattr(
+ S, "_same_filesystem", lambda left, right: on_tmp(left) == on_tmp(right)
+ )
+ assert (
+ S._preflight_merge_disk(_FakeModel(), "kaggle/working/model", "torchao_fp8")
+ == "kaggle/working/model"
+ )
+ printed = capsys.readouterr().out
+ assert "4.0GB free" in printed
+ assert "5.0GB" in printed
+
+ def test_a_cancelled_redirect_onto_a_roomy_filesystem_is_silent(self, monkeypatch, capsys):
+ """`UNSLOTH_KAGGLE_USE_TMP=1` moves without measuring, so silence is right."""
+ import tempfile
+
+ on_tmp = lambda path: str(path).startswith("/tmp") or str(path) == tempfile.gettempdir()
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ "/tmp/unsloth_saves/model",
+ "moved",
+ ),
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: 12 * GB if on_tmp(path) else 500 * GB)
+ monkeypatch.setattr(
+ S, "_same_filesystem", lambda left, right: on_tmp(left) == on_tmp(right)
+ )
+ assert (
+ S._preflight_merge_disk(_FakeModel(), "kaggle/working/model", "torchao_fp8")
+ == "kaggle/working/model"
+ )
+ assert capsys.readouterr().out == ""
+
+ def test_a_real_stat_of_the_destination_cancels_the_redirect(self, monkeypatch):
+ """The same cancellation, with `_same_filesystem` left unstubbed.
+
+ Cancelling is the one outcome the helper cannot reach by accident:
+ every failure inside it, `os.stat` included, returns True and takes
+ the redirect. So a real destination that is really rejected is proof
+ that both stats resolved and compared equal.
+ """
+ import shutil
+ import tempfile
+
+ # Under the tempfile default, so it shares that mount by construction.
+ destination = tempfile.mkdtemp(prefix = "unsloth-staging-test-")
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (destination, "moved"),
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: self._SIBLING + 10 * GB - 1)
+ try:
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == "model"
+ finally:
+ shutil.rmtree(destination, ignore_errors = True)
+
+ def test_the_redirect_creates_its_target_before_returning_it(self, monkeypatch, tmp_path):
+ """Which is why stat-ing the destination is safe on a first export.
+
+ `kaggle_tmp_redirect` returns a message only after `os.makedirs`
+ succeeded, and the `unsloth.disk_utils` fallback never returns one, so
+ the helper is unreachable with a destination that does not exist.
+ """
+ from unsloth.disk_utils import HAS_ZOO_DISK_UTILS
+
+ if not HAS_ZOO_DISK_UTILS:
+ assert S.kaggle_tmp_redirect("model", need_bytes = GB)[1] is None
+ return
+
+ import unsloth_zoo.disk_utils as zoo
+
+ working = tmp_path / "kaggle" / "working"
+ scratch = tmp_path / "tmp"
+ working.mkdir(parents = True)
+ scratch.mkdir()
+ monkeypatch.setattr(zoo, "KAGGLE_WORKING", str(working))
+ monkeypatch.setattr(zoo, "KAGGLE_TMP", str(scratch))
+ monkeypatch.setenv("UNSLOTH_IS_KAGGLE", "1")
+ monkeypatch.delenv("UNSLOTH_KAGGLE_USE_TMP", raising = False)
+ # The working directory is full and the scratch overlay is not, which
+ # is the only shape that moves anything.
+ monkeypatch.setattr(
+ zoo,
+ "free_bytes",
+ lambda path: 1 if os.path.abspath(str(path)) == str(working) else 1000 * GB,
+ )
+ monkeypatch.chdir(working)
+ target, message = zoo.kaggle_tmp_redirect(
+ "model",
+ need_bytes = GB,
+ what = "16-bit merge",
+ )
+ assert message is not None, "the redirect never fired, so nothing was proven"
+ assert os.path.isdir(target)
+
+
+class TestASeparateStagingFilesystemIsStillMeasured:
+ """The other half: `_destination_holds_torchao_staging` asks nothing there.
+
+ When `tempfile` resolves onto its own mount that helper returns True and
+ the staging filesystem is never measured at all, so a 4GB tmpfs is handed
+ a 60GB merge and `_unsloth_save_torchao` dies inside `tempfile.mkdtemp`
+ without saying which disk ran out.
+
+ A warning, not a refusal. Cancelling the redirect cannot help: the staging
+ merge goes to TMPDIR either way, so declining the move leaves the same
+ failure and puts the output on the smaller disk too.
+ """
+
+ _STAGING = 10 * GB
+
+ @pytest.fixture
+ def separate(self, monkeypatch, tmp_path):
+ """A TMPDIR on its own mount, with free space the test dictates."""
+ import tempfile
+
+ staging = tmp_path / "tmp"
+ staging.mkdir()
+ # `tempfile.gettempdir()` caches its answer on first use, so setting
+ # the variable alone would leave the process's real temp directory.
+ monkeypatch.setattr(tempfile, "tempdir", str(staging))
+ free = {"staging": 0, "other": 1000 * GB}
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: self._STAGING)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: (a[0], None))
+ monkeypatch.setattr(S, "_same_filesystem", lambda left, right: False)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: free["staging"] if str(path) == str(staging) else free["other"],
+ )
+ monkeypatch.setenv("TMPDIR", str(staging))
+ return free
+
+ def test_a_short_staging_filesystem_is_named(self, separate, capsys):
+ separate["staging"] = _with_merge_headroom(self._STAGING) - 1
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ out = capsys.readouterr().out
+ assert "TMPDIR" in out
+ # 10GB of merge over the 0.95 the merge guard reserves.
+ assert "10.5GB" in out
+
+ def test_a_staging_filesystem_with_room_says_nothing(self, separate, capsys):
+ separate["staging"] = _with_merge_headroom(self._STAGING)
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ assert capsys.readouterr().out == ""
+
+ def test_the_warning_carries_the_merge_guards_own_reserve(self, separate, capsys):
+ """Exactly the merge's size on TMPDIR is not enough to write it there.
+
+ `merge_and_overwrite_lora` compares the staging save against
+ `int(free * 0.95)` and raises "Failed saving - no disk space left"
+ when it is short, and on a separate TMPDIR its own /tmp fallback is
+ that same filesystem, so there is no recovery. Between `staging_bytes`
+ and `staging_bytes / 0.95` the merge therefore dies and only this
+ warning could have named the disk, so it has to use the same figure
+ `_preflight_merge_disk` asks the redirect for.
+ """
+ separate["staging"] = self._STAGING
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ assert "TMPDIR" in capsys.readouterr().out
+
+ separate["staging"] = self._STAGING - 1
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ assert "TMPDIR" in capsys.readouterr().out
+
+ @pytest.mark.parametrize("save_method", ["merged_16bit", "fp8", "mxfp4"])
+ def test_an_export_that_stages_nothing_is_silent(self, separate, capsys, save_method):
+ """Only torchao writes a second full copy outside `save_directory`."""
+ separate["staging"] = 0
+ S._preflight_merge_disk(_FakeModel(), "model", save_method)
+ assert capsys.readouterr().out == ""
+
+ def test_a_shared_staging_filesystem_is_left_to_the_other_helper(
+ self, separate, capsys, monkeypatch
+ ):
+ """On Kaggle both are /tmp, and that case is already charged for."""
+ separate["staging"] = 0
+ monkeypatch.setattr(S, "_same_filesystem", lambda left, right: True)
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+ assert capsys.readouterr().out == ""
+
+ def test_it_warns_rather_than_refusing(self, separate):
+ """The preflight still returns the directory it was given."""
+ separate["staging"] = 0
+ assert S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8") == "model"
+
+ def test_an_unmeasurable_staging_filesystem_says_nothing(self, separate, monkeypatch):
+ monkeypatch.setattr(S, "free_bytes", lambda path: None)
+ S._preflight_merge_disk(_FakeModel(), "model", "torchao_fp8")
+
+ def test_the_staging_really_is_a_full_second_copy(self):
+ """The warning is only worth printing while this stays true."""
+ import inspect
+
+ source = inspect.getsource(S._unsloth_save_torchao)
+ assert 'tempfile.mkdtemp(prefix = "unsloth-torchao-")' in source
+ assert "save_pretrained_merged" in source or "merge" in source.lower()
+
+
+class TestTheStagingWarningSurvivesAFreshDestination:
+ """The destination of a first export does not exist yet.
+
+ `_preflight_merge_disk` runs before anything is written, so on a first
+ export `save_directory` is a name and not a directory. Comparing devices
+ by stat-ing it directly raised, the helper's broad handler swallowed the
+ whole probe, and the undersized TMPDIR went unmentioned in exactly the
+ case the warning exists for. The nearest existing ancestor is the
+ filesystem the write lands on, and is what `free_bytes` already measures.
+
+ `os.stat` is faked rather than `_same_filesystem` monkeypatched, because
+ the bug is inside `_same_filesystem` and a stub for it cannot show it.
+ Existence still comes from the real `os.stat`, so the missing directory
+ is genuinely missing.
+ """
+
+ _STAGING = 10 * GB
+
+ @pytest.fixture
+ def fresh(self, monkeypatch, tmp_path):
+ import tempfile
+
+ staging = tmp_path / "tmp"
+ staging.mkdir()
+ monkeypatch.chdir(tmp_path)
+ # `tempfile.gettempdir()` caches its answer, so the attribute and the
+ # variable both have to move.
+ monkeypatch.setattr(tempfile, "tempdir", str(staging))
+ monkeypatch.setenv("TMPDIR", str(staging))
+
+ class _Device:
+ def __init__(self, st_dev):
+ self.st_dev = st_dev
+
+ devices = {str(staging): 20, str(tmp_path): 10}
+ real_stat = os.stat
+
+ def fake_stat(path, *args, **kwargs):
+ result = real_stat(path, *args, **kwargs)
+ device = devices.get(str(path), None)
+ return result if device is None else _Device(device)
+
+ monkeypatch.setattr(os, "stat", fake_stat)
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: self._STAGING)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: (a[0], None))
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 0 if str(path) == str(staging) else 1000 * GB,
+ )
+ return tmp_path
+
+ def test_an_absent_destination_still_gets_the_warning(self, fresh, capsys):
+ destination = str(fresh / "model")
+ assert not os.path.exists(destination)
+ S._preflight_merge_disk(_FakeModel(), destination, "torchao_fp8")
+ assert "TMPDIR" in capsys.readouterr().out
+
+ def test_a_shared_filesystem_is_still_silent(self, fresh, capsys, monkeypatch):
+ """Resolving the ancestor must not turn every fresh path into a warning."""
+ monkeypatch.setattr(S, "_filesystem_id", lambda path: 10)
+ S._preflight_merge_disk(_FakeModel(), str(fresh / "model"), "torchao_fp8")
+ assert capsys.readouterr().out == ""
+
+ def test_an_unidentifiable_path_cancels_the_probe(self, fresh, capsys, monkeypatch):
+ """Unmeasurable stays "cannot tell", which is silence and not a guess."""
+ monkeypatch.setattr(S, "_filesystem_id", lambda path: None)
+ S._preflight_merge_disk(_FakeModel(), str(fresh / "model"), "torchao_fp8")
+ assert capsys.readouterr().out == ""
+
+
+class TestMergeHeadroomMatchesTheZooGuard:
+ """A working directory that is "just big enough" is not big enough.
+
+ `merge_and_overwrite_lora` compares the save against `int(free * 0.95)`,
+ so a 30GB merge with 31GB free was left in /kaggle/working by the redirect
+ and then refused outright by the merge itself.
+
+ An adapter merged by `unsloth_generic_save`, because that is the only
+ writer here that calls the guarded function at all.
+ """
+
+ @pytest.fixture(autouse = True)
+ def adapter(self, monkeypatch):
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+
+ @pytest.fixture
+ def kaggle(self, monkeypatch):
+ """A `kaggle_tmp_redirect` that answers like the real one."""
+ free_working = 31 * GB
+
+ def fake_redirect(
+ save_directory,
+ need_bytes = 0,
+ what = "export",
+ ):
+ if need_bytes <= 0 or free_working >= need_bytes:
+ return save_directory, None
+ return "/tmp/unsloth_saves/model", "moved"
+
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 30 * GB)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", fake_redirect)
+
+ def test_a_merge_that_only_just_fits_is_still_redirected(self, kaggle):
+ assert S._preflight_merge_disk(
+ _FakeAdapterModel(),
+ "model",
+ "merged_16bit",
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ ) == ("/tmp/unsloth_saves/model")
+
+ def test_the_ask_clears_the_guard_that_comes_next(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 30 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ S._preflight_merge_disk(
+ _FakeAdapterModel(),
+ "model",
+ "merged_16bit",
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ )
+ # Free space that satisfies this preflight also satisfies the 5% the
+ # merge reserves; 31GB satisfies neither.
+ assert int(asked[0] * 0.95) >= 30 * GB
+ assert int(31 * GB * 0.95) < 30 * GB
+
+
+class TestSixteenBitCheckpointDetection:
+ """`needs_merge` is "does a 16-bit checkpoint get written", not "is it PEFT"."""
+
+ class _NonPeft:
+ class config:
+ _name_or_path = "unsloth/Qwen3-32B"
+
+ class _NonPeftFromDisk:
+ def __init__(self, directory):
+ self.config = type("cfg", (), {"_name_or_path": directory})()
+
+ def test_a_hub_id_still_writes_a_checkpoint(self):
+ """The non-PEFT fallback `save_pretrained`s the whole model first."""
+ assert S._gguf_writes_16bit_checkpoint(self._NonPeft()) is True
+
+ def test_an_existing_local_checkpoint_is_reused(self, tmp_path):
+ assert S._gguf_writes_16bit_checkpoint(self._NonPeftFromDisk(str(tmp_path))) is False
+
+ def test_no_config_at_all_is_counted(self):
+ assert S._gguf_writes_16bit_checkpoint(_FakeModel()) is True
+
+
+class TestFallbackCheckpointDtype:
+ """The non-PEFT fallback `save_pretrained`s the model at its own dtype.
+
+ The estimator budgets two bytes per parameter for that checkpoint, so an
+ fp32 model (`dtype = torch.float32` is a supported load) writes twice what
+ was measured and can fill a disk this called big enough.
+ """
+
+ @pytest.fixture
+ def sized_from_parameters(self, monkeypatch):
+ import torch
+ monkeypatch.setattr(
+ S,
+ "model_16bit_bytes",
+ lambda model: sum(p.numel() for p in model.parameters()) * 2,
+ )
+ return torch
+
+ def test_float32_parameters_cost_the_difference(self, sized_from_parameters):
+ torch = sized_from_parameters
+ model = torch.nn.Linear(8, 8, dtype = torch.float32)
+ n_parameters = sum(p.numel() for p in model.parameters())
+ assert S._fallback_checkpoint_extra_bytes(model) == n_parameters * 2
+
+ def test_a_sixteen_bit_model_adds_nothing(self, sized_from_parameters):
+ torch = sized_from_parameters
+ model = torch.nn.Linear(8, 8, dtype = torch.bfloat16)
+ assert S._fallback_checkpoint_extra_bytes(model) == 0
+
+ def test_a_reused_checkpoint_on_disk_adds_nothing(self, sized_from_parameters, tmp_path):
+ """Nothing is written, whatever dtype the model is in memory."""
+ torch = sized_from_parameters
+ model = torch.nn.Linear(8, 8, dtype = torch.float32)
+ model.config = type("cfg", (), {"_name_or_path": str(tmp_path)})()
+ assert S._fallback_checkpoint_extra_bytes(model) == 0
+
+ def test_an_unmeasurable_model_adds_nothing(self):
+ assert S._fallback_checkpoint_extra_bytes(_FakeModel()) == 0
+
+ def test_the_gguf_preflight_asks_for_it(self, sized_from_parameters, monkeypatch):
+ torch = sized_from_parameters
+ asked = []
+ model = torch.nn.Linear(8, 8, dtype = torch.float32)
+ n_parameters = sum(p.numel() for p in model.parameters())
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", lambda **kwargs: 100 * GB)
+ monkeypatch.setattr(S, "free_bytes", lambda path: 1000 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ S._preflight_gguf_disk(model, "model", "q4_k_m", needs_merge = True)
+ assert asked == [100 * GB + n_parameters * 2]
+
+
+class TestFullModelSavedAsLora:
+ """`lora` on a model with no adapter writes the WHOLE model.
+
+ `unsloth_generic_save` and `unsloth_save_model` both fall back to
+ `save_pretrained` there, so the checkpoint is the size of the model and
+ fills /kaggle/working exactly like a merge. Skipping the preflight on the
+ method name alone let that through.
+ """
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ # Deliberately not the size of the checkpoint: a full-model save is
+ # written with no cast, so believing this figure is the bug.
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ @staticmethod
+ def _float32_model():
+ import torch
+ return torch.nn.Linear(8, 8, dtype = torch.float32)
+
+ def test_a_full_model_lora_save_is_sized(self, sized):
+ model = self._float32_model()
+ expected = sum(p.numel() * p.element_size() for p in model.parameters())
+ S._preflight_merge_disk(model, "model", "lora")
+ assert sized == [_merge_preflight_ask(expected, 0)]
+
+ def test_it_is_sized_at_the_tensors_own_dtype(self, sized):
+ """Four bytes per parameter for fp32, not the two a merge writes."""
+ model = self._float32_model()
+ n_parameters = sum(p.numel() for p in model.parameters())
+ assert S._full_model_checkpoint_bytes(model) == n_parameters * 4
+ S._preflight_merge_disk(model, "model", "lora")
+ assert sized == [_merge_preflight_ask(n_parameters * 4, 0)]
+
+ def test_a_sixteen_bit_model_is_sized_at_two_bytes(self):
+ import torch
+
+ model = torch.nn.Linear(8, 8, dtype = torch.bfloat16)
+ n_parameters = sum(p.numel() for p in model.parameters())
+ assert S._full_model_checkpoint_bytes(model) == n_parameters * 2
+
+ def test_an_adapter_save_is_still_skipped(self, sized, monkeypatch):
+ """A real PeftModel writes adapters only; moving those buys nothing."""
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ assert S._preflight_merge_disk(_FakeAdapterModel(), "model", "lora") == "model"
+ assert sized == []
+
+ @pytest.mark.parametrize("save_method", ["LoRA", " lora "])
+ def test_the_supported_spellings_are_measured_too(self, sized, save_method):
+ S._preflight_merge_disk(self._float32_model(), "model", save_method)
+ assert len(sized) == 1
+
+ def test_an_unmeasurable_model_is_left_alone(self, sized):
+ assert S._preflight_merge_disk(_FakeModel(), "model", "lora") == "model"
+ assert sized == []
+
+ def test_the_redirect_is_taken(self, monkeypatch, capsys):
+ monkeypatch.setattr(
+ S, "kaggle_tmp_redirect", lambda *a, **k: ("/tmp/unsloth_saves/model", "moved")
+ )
+ assert S._preflight_merge_disk(self._float32_model(), "model", "lora") == (
+ "/tmp/unsloth_saves/model"
+ )
+ assert "moved" in capsys.readouterr().out
+
+ def test_the_message_does_not_call_it_a_merge(self, monkeypatch):
+ described = []
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ described.append(what) or (save_directory, None)
+ ),
+ )
+ S._preflight_merge_disk(self._float32_model(), "model", "lora")
+ assert described == ["model checkpoint"]
+
+ def test_the_fallback_really_writes_the_whole_model(self):
+ """The sizing above is only right while this stays true."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_generic_save)
+ assert "_is_peft = isinstance(model, PeftModel)" in source
+ assert "model.save_pretrained(save_directory, **_save_kwargs)" in source
+
+ def test_a_caller_state_dict_is_what_gets_measured(self, sized):
+ """`save_pretrained` writes the dict it was handed, not the model.
+
+ Only `"16bit" in save_method` casts that dict, so a `"lora"` save can
+ forward an fp32 one over fp16 resident parameters and the export is
+ twice what sizing the model says. Undercounting is not a crash, it is
+ a missed redirect, which is how a 20GB Kaggle working directory fills.
+ """
+ import torch
+
+ model = torch.nn.Linear(8, 8, dtype = torch.float16)
+ state_dict = {name: tensor.to(torch.float32) for name, tensor in model.state_dict().items()}
+ n_parameters = sum(p.numel() for p in model.parameters())
+ assert S._full_model_checkpoint_bytes(model, state_dict) == n_parameters * 4
+ S._preflight_merge_disk(model, "model", "lora", state_dict = state_dict)
+ assert sized == [_merge_preflight_ask(n_parameters * 4, 0)]
+
+ def test_no_state_dict_measures_the_model(self, sized):
+ """`None` is the only spelling of "the caller passed nothing"."""
+ model = self._float32_model()
+ n_parameters = sum(p.numel() for p in model.parameters())
+ assert S._full_model_checkpoint_bytes(model, None) == n_parameters * 4
+ S._preflight_merge_disk(model, "model", "lora", state_dict = None)
+ assert sized == [_merge_preflight_ask(n_parameters * 4, 0)]
+
+ def test_an_explicitly_empty_state_dict_is_not_no_state_dict(self, sized):
+ """`{}` is a caller's answer, and the answer is "write nothing".
+
+ `unsloth_generic_save` forwards the dict on `state_dict is not None`,
+ so an empty one reaches `save_pretrained` and no model tensors are
+ written at all. This selected on truthiness and priced the resident
+ model instead, which on Kaggle moves a save that writes nothing off
+ persistent storage and into a /tmp the kernel does not keep.
+ """
+ model = self._float32_model()
+ assert S._full_model_checkpoint_bytes(model, {}) == 0
+ assert S._preflight_merge_disk(model, "model", "lora", state_dict = {}) == "model"
+ assert sized == [], "nothing is written, so nothing is asked for"
+
+ def test_the_writer_really_forwards_an_empty_dict(self):
+ """The sizing above is only right while this stays true."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_generic_save)
+ assert (
+ 'if state_dict is not None:\n _save_kwargs["state_dict"] = state_dict'
+ in source
+ )
+
+ def test_both_call_sites_forward_the_dict(self, monkeypatch):
+ """A parameter nothing passes measures nothing.
+
+ Both of these accept a `state_dict` and both document `"lora"`, so
+ both have to hand it on. Driven rather than read, because the string
+ `state_dict = state_dict` also appears where they forward it to
+ `save_pretrained`, which would pass on a body that never wires it in.
+ """
+ import torch
+
+ seen = []
+ monkeypatch.setattr(
+ S,
+ "_preflight_merge_disk",
+ lambda *args, **kwargs: seen.append(kwargs.get("state_dict", "MISSING")) or args[1],
+ )
+ state_dict = {"weight": torch.zeros(4)}
+ for function in (
+ S.unsloth_save_pretrained_merged,
+ S.unsloth_generic_save_pretrained_merged,
+ ):
+ with contextlib.suppress(Exception):
+ function(
+ self._float32_model(),
+ "model",
+ tokenizer = None,
+ save_method = "lora",
+ state_dict = state_dict,
+ )
+ assert seen == [state_dict, state_dict]
+
+
+class TestASuppliedDictIsWhatASixteenBitSaveWrites:
+ """`unsloth_generic_save` writes the dictionary it was handed, cast.
+
+ It only reaches for `model.state_dict()` when it was given none, so a
+ caller-supplied one decides the size of the checkpoint: `{}` or a subset
+ writes less than the resident model, and a dictionary carrying more writes
+ more. Sizing the model either moves a nearly empty save off persistent
+ Kaggle storage for nothing, or leaves a bigger one to fill the 20GB
+ working directory it should have been redirected out of.
+
+ `unsloth_save_model` is the other writer and rebuilds the dictionary from
+ the merged layers, dropping whatever it was passed, so only the generic
+ call site says the dict is followed.
+ """
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ # Deliberately not the size of the dict below: believing this figure
+ # for a save driven by the caller's dictionary is the bug.
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ @staticmethod
+ def _model():
+ import torch
+ return torch.nn.Linear(8, 8, dtype = torch.float16)
+
+ @staticmethod
+ def _dict(numel = 4096):
+ import torch
+ return {"model.embed_tokens.weight": torch.zeros(numel, dtype = torch.float32)}
+
+ def test_floats_are_charged_at_two_bytes_whatever_they_arrived_as(self):
+ """The writer casts every floating entry to bf16/fp16 before saving."""
+ assert S._cast_16bit_state_dict_bytes(self._dict(4096)) == 4096 * 2
+
+ def test_an_integer_entry_keeps_its_own_width(self):
+ import torch
+ state_dict = {"buffer": torch.zeros(16, dtype = torch.int64)}
+ assert S._cast_16bit_state_dict_bytes(state_dict) == 16 * 8
+
+ def test_the_dict_is_measured_and_not_the_model(self, sized):
+ state_dict = self._dict(8 * 1024**3 // 2)
+ expected = S._cast_16bit_state_dict_bytes(state_dict)
+ S._preflight_merge_disk(
+ self._model(),
+ "model",
+ "merged_16bit",
+ state_dict = state_dict,
+ forwards_state_dict = True,
+ )
+ assert expected == 8 * GB
+ # No adapter, so `unsloth_generic_save` casts this dictionary and
+ # writes it with a bare `save_pretrained`. There is no
+ # `merge_and_overwrite_lora` behind that and so nothing to reserve.
+ assert sized == [_merge_preflight_ask(expected, 0)]
+
+ def test_an_empty_dict_writes_nothing(self, sized):
+ """`{}` reaches `save_pretrained` and no model tensor is written."""
+ assert (
+ S._preflight_merge_disk(
+ self._model(),
+ "model",
+ "merged_16bit",
+ state_dict = {},
+ forwards_state_dict = True,
+ )
+ == "model"
+ )
+ assert sized == [], "nothing is written, so nothing is asked for"
+
+ def test_no_dict_measures_the_model(self, sized):
+ """`None` is when the writer builds the dictionary itself."""
+ S._preflight_merge_disk(
+ self._model(),
+ "model",
+ "merged_16bit",
+ state_dict = None,
+ forwards_state_dict = True,
+ )
+ # Still a bare `save_pretrained`, so still no reserve.
+ assert sized == [_merge_preflight_ask(10 * GB, 0)]
+
+ def test_an_adapter_merge_ignores_the_dict(self, sized, monkeypatch):
+ """A PeftModel goes to `merge_and_overwrite_lora`, which takes none."""
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ S._preflight_merge_disk(
+ _FakeAdapterModel(),
+ "model",
+ "merged_16bit",
+ state_dict = self._dict(),
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ )
+ # And that is the one writer whose guard is real, so this keeps its 5%.
+ assert sized == [_merge_preflight_ask(10 * GB, 10 * GB)]
+
+ def test_the_other_writer_rebuilds_the_dict(self, sized):
+ """`unsloth_save_model` merges the layers itself, so the model is sized."""
+ S._preflight_merge_disk(
+ self._model(),
+ "model",
+ "merged_16bit",
+ state_dict = self._dict(),
+ )
+ # It writes the merged shards itself and runs no zoo guard, so the
+ # model is sized at two bytes a parameter and reserved against nothing.
+ assert sized == [_merge_preflight_ask(10 * GB, 0)]
+
+ def test_each_call_site_says_what_its_writer_does_with_the_dict(self, monkeypatch):
+ """Driven rather than read, so a body that never wires it in fails.
+
+ `unsloth_save_model` rebuilds the dictionary only on the path that
+ walks `.model.layers`, so that is the model this asks about.
+ """
+ import torch
+
+ seen = []
+ monkeypatch.setattr(
+ S,
+ "_preflight_merge_disk",
+ lambda *args, **kwargs: (
+ seen.append(
+ (
+ kwargs.get("forwards_state_dict", False),
+ kwargs.get("writes_model_verbatim", False),
+ kwargs.get("writer_runs_merge_guard", False),
+ )
+ )
+ or args[1]
+ ),
+ )
+ for function in (
+ S.unsloth_save_pretrained_merged,
+ S.unsloth_generic_save_pretrained_merged,
+ ):
+ with contextlib.suppress(Exception):
+ function(
+ _ModelWithLayers(),
+ "model",
+ tokenizer = None,
+ save_method = "merged_16bit",
+ state_dict = {"weight": torch.zeros(4)},
+ )
+ # The third flag is the merge guard: only `unsloth_generic_save` runs
+ # `merge_and_overwrite_lora`, and only for an adapter.
+ assert seen == [(False, False, False), (True, False, True)]
+
+ def test_the_writers_really_differ(self):
+ """The split above is only right while these two stay as they are."""
+ import inspect
+
+ generic = inspect.getsource(S.unsloth_generic_save)
+ assert '("16bit" in save_method or is_qwen3_5_vlm) and state_dict is None' in generic
+ assert "v.to(dtype = _target_dtype) if v.is_floating_point() else v" in generic
+ # The other writer overwrites the caller's dictionary with its own.
+ assert "state_dict = OrderedDict()" in inspect.getsource(S.unsloth_save_model)
+
+
+class TestTheGgufSiblingIsMeasuredToo:
+ """The GGUF files land in `save_directory + "_gguf"`, a SIBLING.
+
+ So they are on the PARENT's filesystem, which is the same disk as
+ `save_directory` unless that path is itself a mount point or a symlink
+ onto another one. Measuring only `save_directory` then passes an export
+ whose quants fill a filesystem nobody looked at.
+
+ Only genuinely separate filesystems change anything, so a single
+ filesystem behaves exactly as before.
+ """
+
+ @pytest.fixture
+ def split(self, monkeypatch):
+ """Free space per path, and the estimate split into its two halves."""
+ state = {"free": 1000 * GB, "sibling_free": 1000 * GB, "separate": False}
+
+ def fake_free(path):
+ return state["sibling_free"] if str(path).endswith("_gguf") else state["free"]
+
+ def fake_estimate(**kwargs):
+ if kwargs.get("base_cache_copy"):
+ return 48 * GB
+ # Without the checkpoint: the intermediate conversion + quants.
+ return 34 * GB if kwargs.get("needs_merge", True) else 18 * GB
+
+ monkeypatch.setattr(S, "free_bytes", fake_free)
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ # Only the save-directory / sibling pair is split. Every other pair the
+ # preflight asks about -- notably the working directory the intermediate
+ # conversion is written to -- is one filesystem, which is the ordinary
+ # machine these tests describe. The conversion travels with the sibling
+ # there, so the save directory's filesystem holds the checkpoint alone.
+ monkeypatch.setattr(
+ S,
+ "_on_separate_filesystems",
+ lambda left, right: state["separate"]
+ if (str(left), str(right)) == ("model", "model_gguf")
+ else False,
+ )
+ monkeypatch.setattr(S, "_shares_filesystem", lambda left, right: False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def test_a_tighter_sibling_filesystem_refuses(self, split):
+ """`model` is a symlink onto a big disk; `model_gguf` is not."""
+ split.update(free = 1000 * GB, sibling_free = 10 * GB, separate = True)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "model_gguf" in str(error.value)
+
+ @pytest.mark.parametrize(
+ "free_gb,expected",
+ [(1000, ("model", True)), (40, ("model", False))],
+ )
+ def test_one_filesystem_is_unchanged(self, split, free_gb, expected):
+ """Both probes return the same figure, so nothing new can fire."""
+ split.update(free = free_gb * GB, sibling_free = free_gb * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == expected
+
+ def test_a_roomier_sibling_is_not_a_refusal(self, split):
+ """5GB holds neither half, so this is the checkpoint's own refusal."""
+ split.update(free = 5 * GB, sibling_free = 1000 * GB, separate = True)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ # The ordinary refusal, about the checkpoint's own filesystem.
+ assert "model_gguf" not in str(error.value)
+
+ def test_the_sibling_is_sized_without_the_checkpoint(self, split):
+ """20GB holds the quants but not the merge, and only the quants go there."""
+ split.update(free = 1000 * GB, sibling_free = 20 * GB, separate = True)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ def test_an_unmeasurable_sibling_leaves_the_decision_alone(self, split, monkeypatch):
+ split["separate"] = True
+ monkeypatch.setattr(
+ S, "free_bytes", lambda path: None if str(path).endswith("_gguf") else 1000 * GB
+ )
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ def test_an_unmeasurable_save_directory_leaves_the_decision_alone(self, split, monkeypatch):
+ split["separate"] = True
+ monkeypatch.setattr(
+ S, "free_bytes", lambda path: 1 * GB if str(path).endswith("_gguf") else None
+ )
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+
+ def test_the_sibling_measured_is_the_redirect_target(self, split, monkeypatch):
+ probed = []
+ monkeypatch.setattr(
+ S, "kaggle_tmp_redirect", lambda *a, **k: ("/tmp/unsloth_saves/model", "moved")
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: probed.append(path) or 1000 * GB)
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert probed == ["/tmp/unsloth_saves/model", "/tmp/unsloth_saves/model_gguf"]
+
+ def test_an_estimator_that_cannot_size_the_sibling_keeps_the_main_guard(
+ self, split, monkeypatch
+ ):
+ """The new call must not be able to switch the whole preflight off."""
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ raise TypeError("older unsloth_zoo")
+ return 48 * GB if kwargs.get("base_cache_copy") else 34 * GB
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ split.update(free = 10 * GB, sibling_free = 10 * GB)
+ with pytest.raises(RuntimeError):
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+
+ def test_the_export_writes_where_the_preflight_measured(self):
+ """One definition, so the two cannot drift apart."""
+ import inspect
+
+ assert S._gguf_output_directory("model") == "model_gguf"
+ source = inspect.getsource(S.unsloth_save_pretrained_gguf)
+ assert "gguf_directory = _gguf_output_directory(save_directory)" in source
+ assert 'f"{save_directory}_gguf"' not in inspect.getsource(S._preflight_gguf_disk)
+
+
+class TestEachFilesystemIsChargedForWhatItHolds:
+ """Two filesystems, and each one is charged only for what lands on it.
+
+ The other half of the sibling problem. Measuring the sibling caught the
+ case where it is too tight; the aggregate estimate was still charged in
+ full to the filesystem holding `save_directory`, which refuses a split
+ export whose checkpoint fits on one disk and whose quants fit on the
+ other. A guard that blocks an export that works is worse than no guard.
+
+ Numbers throughout: the export is 34GB (16GB checkpoint + 18GB of
+ conversion and quants), 48GB with a pre-warmed base cache.
+ """
+
+ CHECKPOINT = 16 * GB
+ SIBLING = 18 * GB
+ AGGREGATE = 34 * GB
+ AGGREGATE_WITH_CACHE = 48 * GB
+
+ @pytest.fixture
+ def split(self, monkeypatch):
+ state = {"free": 1000 * GB, "sibling_free": 1000 * GB, "separate": True}
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ return self.SIBLING
+ if kwargs.get("base_cache_copy"):
+ return self.AGGREGATE_WITH_CACHE
+ return self.AGGREGATE
+
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: state["sibling_free"] if str(path).endswith("_gguf") else state["free"],
+ )
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ # Only the save-directory / sibling pair is split. Every other pair the
+ # preflight asks about -- notably the working directory the intermediate
+ # conversion is written to -- is one filesystem, which is the ordinary
+ # machine these tests describe. The conversion travels with the sibling
+ # there, so the save directory's filesystem holds the checkpoint alone.
+ monkeypatch.setattr(
+ S,
+ "_on_separate_filesystems",
+ lambda left, right: state["separate"]
+ if (str(left), str(right)) == ("model", "model_gguf")
+ else False,
+ )
+ monkeypatch.setattr(S, "_shares_filesystem", lambda left, right: False)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ # The reserve below belongs to `merge_and_overwrite_lora`, which only
+ # a PEFT model reaches, so the tests that exercise it need a model the
+ # preflight recognises as one.
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def test_a_split_export_that_fits_is_not_refused(self, split):
+ """20GB holds the 16GB checkpoint; the 18GB of quants go elsewhere."""
+ split.update(free = 20 * GB, sibling_free = 1000 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", False)
+
+ @pytest.mark.parametrize("free_gb,fits", [(17, True), (16, False)])
+ def test_the_checkpoint_portion_is_the_boundary(self, split, free_gb, fits):
+ """`need - need_sibling`, not the aggregate, decides.
+
+ The boundary is the 16GB checkpoint over the 0.95 reserve
+ `merge_and_overwrite_lora` applies, so 16.85GB rather than 16GB.
+ Exactly 16GB free is the case that motivates it: the checkpoint
+ nominally fits, and the merge refuses it anyway a moment later.
+ """
+ split.update(free = free_gb * GB, sibling_free = 1000 * GB)
+ if fits:
+ assert S._preflight_gguf_disk(_FakeAdapterModel(), "model", "q4_k_m") == (
+ "model",
+ False,
+ )
+ else:
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeAdapterModel(), "model", "q4_k_m")
+ assert "about 16.8GB" in str(error.value)
+
+ def test_the_cache_copy_is_charged_here_too(self, split):
+ """The pre-warm goes to the HF cache, not the sibling, so it stays here.
+
+ 48GB with the cache minus the 18GB sibling half is 30GB: at 30GB the
+ cache is affordable, at 29GB it is dropped rather than refused.
+ """
+ split.update(free = 30 * GB, sibling_free = 1000 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", True)
+ split.update(free = 29 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", False)
+
+ def test_the_split_carries_the_merge_guards_own_reserve(self, split):
+ """16GB of checkpoint on 16GB of disk is what the merge itself refuses.
+
+ `merge_and_overwrite_lora` will not write a merge unless `free * 0.95`
+ covers it, and the aggregate branch never had to think about that
+ because it charges the quants too. Charging the checkpoint alone
+ removes that cover, so the reserve has to come back with it or this
+ passes an export the merge kills seconds later.
+ """
+ split.update(free = 16 * GB, sibling_free = 1000 * GB)
+ with pytest.raises(RuntimeError):
+ S._preflight_gguf_disk(_FakeAdapterModel(), "model", "q4_k_m")
+ assert S.free_bytes("model") * S._MERGE_FREE_SPACE_RESERVE < self.CHECKPOINT
+
+ def test_only_a_lora_merge_is_charged_the_reserve(self, split):
+ """A non-PEFT checkpoint is written by `save_pretrained`, which reserves nothing.
+
+ `needs_merge` is true for a non-PEFT model with no reusable local
+ `_name_or_path` as well, because the GGUF path still has to write a
+ checkpoint - but it writes it with a bare `self.save_pretrained`,
+ which never consults `merge_and_overwrite_lora` and never applies its
+ `free * 0.95`. Charging the reserve there refuses 16GB of checkpoint
+ on 16GB of disk that the writer would have accepted.
+ """
+ split.update(free = 16 * GB, sibling_free = 1000 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", False)
+
+ def test_the_non_peft_writer_really_has_no_guard(self):
+ """The reserve is only skippable while this stays true."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_save_pretrained_gguf)
+ fallback = source.split("Saving directly without LoRA merge")[1]
+ assert "self.save_pretrained(save_directory)" in fallback
+ assert "merge_and_overwrite_lora" not in fallback
+
+ def test_an_export_writing_no_merge_is_not_charged_the_reserve(self, split):
+ """`needs_merge = False` reaches no merge guard, so it pays for none.
+
+ Nothing else is on this filesystem then, so the checkpoint portion is
+ zero, the whole export is the sibling's, and 1GB is enough here.
+ """
+ split.update(free = 1 * GB, sibling_free = 1000 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", needs_merge = False) == (
+ "model",
+ True,
+ )
+
+ def test_the_reserve_never_exceeds_the_aggregate(self, split, monkeypatch):
+ """A sibling small next to the checkpoint must not add a refusal.
+
+ 1GB of sibling leaves 33GB of checkpoint, and 33 / 0.95 is 34.7GB:
+ more than the 34GB aggregate the single-filesystem branch charges. The
+ split may cancel a redirect, never cause a refusal the aggregate would
+ have allowed, so the reserved figure is clamped at `need`.
+ """
+ monkeypatch.setattr(
+ S,
+ "estimate_gguf_export_bytes",
+ lambda **kwargs: (
+ 1 * GB
+ if not kwargs.get("needs_merge", True)
+ else (
+ self.AGGREGATE_WITH_CACHE if kwargs.get("base_cache_copy") else self.AGGREGATE
+ )
+ ),
+ )
+ split.update(free = 34 * GB, sibling_free = 1000 * GB)
+ assert S._preflight_gguf_disk(_FakeAdapterModel(), "model", "q4_k_m") == ("model", False)
+
+ def test_a_short_sibling_roomier_than_the_checkpoint_disk_still_refuses(self, split):
+ """The hole the split would leave if the refusal still needed a TIGHTER sibling.
+
+ 10GB on the sibling holds neither the 18GB of quants nor anything
+ else, and it is more than the 5GB here, so "tighter than `free`"
+ would miss it, and the aggregate comparison that used to catch it is
+ gone once the checkpoint is charged only its own portion.
+ """
+ split.update(free = 5 * GB, sibling_free = 10 * GB)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "model_gguf" in str(error.value)
+
+ @pytest.mark.parametrize(
+ "free_gb,expected",
+ [
+ (5, "raises"),
+ (16, "raises"),
+ (20, "raises"),
+ (34, ("model", False)),
+ (40, ("model", False)),
+ (48, ("model", True)),
+ (1000, ("model", True)),
+ ],
+ )
+ def test_one_filesystem_is_unchanged_across_the_range(self, split, free_gb, expected):
+ """Every outcome is the aggregate one, at every level of free space.
+
+ This is the whole of the previous behaviour: refuse below 34GB, drop
+ the pre-warm between 34GB and 48GB, proceed at 48GB. Nothing about
+ the split may move any of it.
+ """
+ split.update(free = free_gb * GB, sibling_free = free_gb * GB, separate = False)
+ if expected == "raises":
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "about 34.0GB" in str(error.value)
+ assert "model_gguf" not in str(error.value)
+ else:
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == expected
+
+ def test_one_filesystem_that_moved_between_the_probes_is_still_one(self, split):
+ """Two `disk_usage` calls on ONE filesystem can disagree.
+
+ Something else writing a single block between them is not a second
+ filesystem, and reading it as one would charge this export the larger
+ half, 16GB, instead of the 34GB sum. The predicate is the device id,
+ so the difference in free space cannot decide it.
+ """
+ split.update(free = 20 * GB, sibling_free = 20 * GB - 4096, separate = False)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "about 34.0GB" in str(error.value)
+
+ def test_two_filesystems_with_the_same_free_space_are_still_two(self, split):
+ """And the converse: equal figures are not evidence of one filesystem."""
+ split.update(free = 20 * GB, sibling_free = 20 * GB, separate = True)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m") == ("model", False)
+
+ def test_an_unmeasurable_sibling_charges_the_aggregate(self, split, monkeypatch):
+ monkeypatch.setattr(
+ S, "free_bytes", lambda path: None if str(path).endswith("_gguf") else 20 * GB
+ )
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "about 34.0GB" in str(error.value)
+
+ def test_a_sibling_the_estimator_cannot_size_charges_the_aggregate(self, split, monkeypatch):
+ """`need_sibling` falls back to 0, so `need - need_sibling` is `need`."""
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ raise TypeError("older unsloth_zoo")
+ return self.AGGREGATE_WITH_CACHE if kwargs.get("base_cache_copy") else self.AGGREGATE
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ split.update(free = 20 * GB, sibling_free = 1000 * GB)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ assert "about 34.0GB" in str(error.value)
+
+ def _outcome_before(self, free, sibling_free):
+ """What the previous revision did: sibling refusal, then the aggregate."""
+ if sibling_free < free and sibling_free < self.SIBLING:
+ return "raises"
+ if free >= self.AGGREGATE_WITH_CACHE:
+ return ("model", True)
+ if free >= self.AGGREGATE:
+ return ("model", False)
+ return "raises"
+
+ def test_the_split_never_refuses_where_the_aggregate_allowed(self, split):
+ """A guard may cancel a redirect, never cause one, and may not add refusals.
+
+ Over a grid of both filesystems: every refusal the split produces was
+ already a refusal before it, so no working export is newly blocked.
+ """
+ for free_gb in (1, 5, 16, 17, 20, 34, 48, 100):
+ for sibling_gb in (1, 5, 17, 18, 19, 50, 1000):
+ split.update(free = free_gb * GB, sibling_free = sibling_gb * GB)
+ try:
+ now = S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m")
+ except RuntimeError:
+ now = "raises"
+ before = self._outcome_before(free_gb * GB, sibling_gb * GB)
+ if now == "raises":
+ assert before == "raises", (free_gb, sibling_gb)
+
+ def test_the_probe_matches_free_bytes_on_one_filesystem(self, tmp_path):
+ """The real helper, real paths, no monkeypatching.
+
+ A directory and its not-yet-created sibling under one tmp dir are one
+ filesystem, so the split is inert on every ordinary setup.
+ """
+ directory = tmp_path / "model"
+ directory.mkdir()
+ assert S._on_separate_filesystems(str(directory), f"{directory}_gguf") is False
+ assert S._filesystem_id(str(directory)) == S._filesystem_id(f"{directory}_gguf")
+
+ def test_the_probe_sees_a_real_second_filesystem(self, tmp_path):
+ """A symlinked save directory on another mount: the reachable case."""
+ other = "/dev/shm"
+ if not os.path.isdir(other) or os.stat(other).st_dev == os.stat(tmp_path).st_dev:
+ pytest.skip("no second filesystem available here")
+ directory = tmp_path / "model"
+ directory.symlink_to(other)
+ assert S._on_separate_filesystems(str(directory), f"{directory}_gguf") is True
+
+ def test_an_unidentifiable_path_is_not_split(self):
+ """Unmeasurable is never read as two filesystems."""
+
+ class _Unusable:
+ def __str__(self):
+ raise ValueError("not a path")
+
+ assert S._filesystem_id(_Unusable()) is None
+ assert S._on_separate_filesystems(_Unusable(), "model_gguf") is False
+
+ def test_a_zero_device_id_is_unmeasurable(self, tmp_path, monkeypatch):
+ """Windows fills `st_dev` from the volume serial; zero means it did not."""
+ directory = tmp_path / "model"
+ directory.mkdir()
+
+ class _Zero:
+ st_dev = 0
+
+ real_stat = os.stat
+ monkeypatch.setattr(
+ S.os,
+ "stat",
+ lambda path, *a, **k: _Zero()
+ if str(path) == str(directory)
+ else real_stat(path, *a, **k),
+ )
+ assert S._filesystem_id(str(directory)) is None
+ assert S._on_separate_filesystems(str(directory), f"{directory}_gguf") is False
+
+
+class TestDisabledImatrixIsNotSizedAsAnImatrix:
+ @pytest.mark.parametrize("value", [None, False])
+ def test_agrees_with_the_resolver(self, value):
+ assert S._imatrix_is_enabled(value) is False
+ assert S._resolve_imatrix_file(_FakeModel(), value, None, "unused") is None
+
+ def test_a_real_path_is_enabled(self, tmp_path):
+ path = tmp_path / "imatrix.gguf"
+ path.write_bytes(b"x")
+ assert S._imatrix_is_enabled(str(path)) is True
+ assert S._resolve_imatrix_file(_FakeModel(), str(path), None, str(tmp_path)) == str(path)
+
+ def test_a_disabled_imatrix_keeps_the_single_pass_conversion(self):
+ """The point of the flag: q8_0 alone converts straight to q8_0."""
+ assert S._choose_first_conversion(["q8_0"], "f16", has_imatrix = False) == "q8_0"
+ assert S._choose_first_conversion(["q8_0"], "f16", has_imatrix = True) == "f16"
+
+
+class TestKaggleNeverPricesACacheCopy:
+ """`_prewarm_base_model_hub_cache` returns before it runs on Kaggle and Colab.
+
+ Pricing a cache that cannot exist sends an export that fits in
+ /kaggle/working to /tmp, which is not kept as notebook output.
+ """
+
+ @pytest.fixture
+ def asked(self, monkeypatch):
+ seen = []
+ monkeypatch.setattr(
+ S,
+ "estimate_gguf_export_bytes",
+ lambda **kwargs: seen.append(kwargs)
+ or (44 * GB if kwargs.get("base_cache_copy") else 30 * GB),
+ )
+ monkeypatch.setattr(S, "free_bytes", lambda path: 1000 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ seen.append({"need_bytes": need_bytes}) or (save_directory, None)
+ ),
+ )
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return seen
+
+ @pytest.mark.parametrize("environment", ["IS_KAGGLE_ENVIRONMENT", "IS_COLAB_ENVIRONMENT"])
+ def test_the_redirect_is_priced_without_the_cache(self, asked, monkeypatch, environment):
+ monkeypatch.setattr(S, environment, True)
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", needs_merge = True)
+ assert not any(call.get("base_cache_copy") for call in asked)
+ assert asked[-1]["need_bytes"] == 30 * GB
+
+ def test_an_ordinary_machine_still_prices_it(self, asked, monkeypatch):
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", needs_merge = True)
+ assert any(call.get("base_cache_copy") for call in asked)
+ assert asked[-1]["need_bytes"] == 44 * GB
+
+
+class _Packed4bitParameter:
+ """A `Params4bit`: uint8 storage, with the real shape on `quant_state`.
+
+ `numel()` is the packed count, which bitsandbytes fits two 4-bit
+ parameters into. `logical_numel` is what a helper that reads
+ `quant_state.shape` returns for it, and what the merge is sized with.
+ """
+
+ class _QuantState:
+ def __init__(self, shape):
+ self.shape = shape
+
+ def __init__(self, logical):
+ self.logical_numel = logical
+ self.quant_state = self._QuantState((logical,))
+
+ def numel(self):
+ return self.logical_numel // 2
+
+
+class _NamedModule(_FakeModule):
+ """A `_FakeModule` that can also name its parameters, as torch does."""
+
+ def named_parameters(self, prefix = ""):
+ for index, parameter in enumerate(self._parameters):
+ yield f"{prefix}weight{index}", parameter
+ for name, child in self._children.items():
+ yield from child.named_parameters(f"{prefix}{name}.")
+
+
+class TestIgnoredModulesAreSizedFromLogicalShapes:
+ """An ignored module on a 4-bit model is priced at its LOGICAL size.
+
+ `model_16bit_bytes` sizes the merge through unsloth_zoo's `logical_numel`,
+ which reads `quant_state.shape`. Sizing the ignored subtree that is
+ subtracted from it with `numel()` instead prices packed uint8 storage --
+ about half -- so the two disagree and the quantized sibling comes out
+ small. On a tight Kaggle filesystem that is a redirect that never happens.
+ """
+
+ @pytest.fixture
+ def logical(self, monkeypatch):
+ """Route `logical_numel` at the fake parameters' declared logical size.
+
+ Deliberately not a copy of the zoo's implementation: what is under
+ test is that save.py ASKS, and passes the name along, not that it can
+ re-derive an answer the zoo already owns.
+ """
+ seen = []
+
+ def fake_logical_numel(parameter, name = ""):
+ seen.append(name)
+ return getattr(parameter, "logical_numel", parameter.numel())
+
+ monkeypatch.setattr(S, "logical_numel", fake_logical_numel)
+ return seen
+
+ def _model(self):
+ """Qwen3-Next shaped: a 4-bit `linear_attn` the recipe will not touch."""
+ return _ShapedModel(
+ children = {
+ "model": _NamedModule(
+ children = {
+ "layers": _NamedModule(
+ children = {
+ "0": _NamedModule(
+ children = {
+ "linear_attn": _NamedModule(
+ children = {
+ "in_proj_qkvz": _NamedModule(
+ parameters = [_Packed4bitParameter(4 * GB)],
+ ),
+ },
+ ),
+ },
+ ),
+ },
+ ),
+ },
+ ),
+ },
+ config = _Config(model_type = "qwen3_next"),
+ )
+
+ def test_a_four_bit_ignored_module_is_charged_its_logical_size(self, logical):
+ model = self._model()
+ patterns = S._compressed_ignore_patterns(model)
+ # 4e9 logical parameters at 2 bytes, not the 2e9 packed ones.
+ assert S._unquantized_parameter_bytes(model, patterns) == 8 * GB
+
+ def test_the_packed_count_is_not_what_is_used(self, monkeypatch):
+ """Without the logical lookup the same subtree prices at half."""
+ monkeypatch.setattr(S, "logical_numel", lambda parameter, name = "": parameter.numel())
+ model = self._model()
+ patterns = S._compressed_ignore_patterns(model)
+ assert S._unquantized_parameter_bytes(model, patterns) == 4 * GB
+
+ def test_the_parameter_name_reaches_the_helper(self, logical):
+ """MXFP4 packing has no `quant_state`; only the name gives it away."""
+ model = self._model()
+ S._unquantized_parameter_bytes(model, S._compressed_ignore_patterns(model))
+ assert "weight0" in logical
+
+ def test_the_embeddings_go_through_it_too(self, logical):
+ model = _ShapedModel(
+ children = {},
+ config = _Config(),
+ input_embeddings = _embedding(1 * GB),
+ )
+ assert S._unquantized_parameter_bytes(model) == 2 * GB
+ assert logical, "the embedding weight was measured without the helper"
+
+ def test_a_module_that_cannot_name_its_parameters_still_counts(self, logical):
+ """`_FakeModule` has no `named_parameters`, and must still be sized."""
+ model = _ShapedModel(
+ children = {
+ "visual": _FakeModule(parameters = [_FakeParameter(1 * GB)]),
+ },
+ config = _Config(),
+ )
+ assert S._unquantized_parameter_bytes(model, ["re:.*visual.*"]) == 2 * GB
+
+ def test_the_helper_is_the_one_the_merge_estimate_uses(self):
+ """One definition, so the two sizings cannot drift apart."""
+ from unsloth import disk_utils
+
+ assert S.logical_numel is disk_utils.logical_numel
+ assert "logical_numel" in disk_utils.__all__
+
+ def test_a_helper_that_raises_leaves_the_estimate_standing(self, monkeypatch):
+ def boom(parameter, name = ""):
+ raise RuntimeError("no")
+
+ monkeypatch.setattr(S, "logical_numel", boom)
+ model = self._model()
+ assert S._unquantized_parameter_bytes(model, S._compressed_ignore_patterns(model)) == 0
+
+
+class TestADisposableMergeIsNotChargedForAllThreeAtOnce:
+ """`_free_merge_if_disk_is_tight` deletes the merge before the quants run.
+
+ Nemotron-3-Nano-30B-A3B on a 132GB disk: a 63GB merge, a 60GB BF16
+ intermediate and an 18GB Q4_K_M. The two phases peak at 123GB and 78GB,
+ and the export runs. Summing all three gives 141GB and refuses it -- the
+ same export the reclamation in this PR was written to make work.
+ """
+
+ AGGREGATE = 141 * GB
+ AGGREGATE_WITH_CACHE = 204 * GB
+ MERGE_PHASE = 123 * GB # merge + intermediate, before reclamation
+ QUANT_PHASE = 78 * GB # intermediate + quants, after it
+
+ @pytest.fixture
+ def phases(self, monkeypatch, tmp_path):
+ state = {"free": 132 * GB, "separate": False}
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ return self.QUANT_PHASE if kwargs.get("quantization_methods") else 60 * GB
+ if not kwargs.get("quantization_methods"):
+ return self.MERGE_PHASE
+ return self.AGGREGATE_WITH_CACHE if kwargs.get("base_cache_copy") else self.AGGREGATE
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 1000 * GB if str(path).endswith("_gguf") else state["free"],
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: (a[0], None))
+ # Only the save-directory / sibling pair can be split. The working
+ # directory the conversion writes to is one filesystem with the sibling
+ # here, so it is never charged to the save directory's disk.
+ monkeypatch.setattr(
+ S,
+ "_on_separate_filesystems",
+ lambda left, right: state["separate"] and str(right).endswith("_gguf"),
+ )
+ monkeypatch.setattr(S, "_shares_filesystem", lambda left, right: False)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ # A disposable merge is a LoRA merge, so the model is a PEFT one and
+ # the split branch's reserve applies to it.
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ state["directory"] = str(tmp_path / "model")
+ return state
+
+ def _preflight(self, phases, **kwargs):
+ kwargs.setdefault("merge_is_disposable", True)
+ return S._preflight_gguf_disk(
+ _FakeAdapterModel(),
+ phases["directory"],
+ "q4_k_m",
+ first_conversion = "bf16",
+ **kwargs,
+ )
+
+ def test_the_export_the_reclamation_makes_work_is_not_refused(self, phases):
+ assert self._preflight(phases) == (phases["directory"], False)
+
+ def test_a_merge_that_is_not_disposable_still_needs_all_three(self, phases):
+ """The SentenceTransformer export keeps its merge, so it pays for it."""
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases, merge_is_disposable = False)
+ assert "141.0GB" in str(error.value)
+
+ def test_the_default_is_the_aggregate(self, phases):
+ """Every caller that does not opt in behaves exactly as before."""
+ with pytest.raises(RuntimeError):
+ S._preflight_gguf_disk(
+ _FakeModel(), phases["directory"], "q4_k_m", first_conversion = "bf16"
+ )
+
+ @pytest.mark.parametrize("free_gb,fits", [(123, True), (122, False)])
+ def test_the_larger_phase_is_the_boundary(self, phases, free_gb, fits):
+ phases.update(free = free_gb * GB)
+ if fits:
+ assert self._preflight(phases) == (phases["directory"], False)
+ else:
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "123.0GB" in str(error.value)
+
+ def test_the_cache_copy_rides_on_top_of_the_peak(self, phases):
+ """204 - 141 = 63GB of cached base, on top of the 123GB peak."""
+ phases.update(free = 186 * GB)
+ assert self._preflight(phases) == (phases["directory"], True)
+ phases.update(free = 185 * GB)
+ assert self._preflight(phases) == (phases["directory"], False)
+
+ def test_an_export_with_no_merge_is_unchanged(self, phases):
+ """Nothing was written here to reclaim, so the sibling total stands."""
+ phases.update(free = 70 * GB)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases, needs_merge = False)
+ assert "78.0GB" in str(error.value)
+
+ def test_a_single_pass_export_gets_no_relief(self, phases):
+ """No quantize pass follows, so there is nothing to reclaim for."""
+ phases.update(free = 132 * GB)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(
+ _FakeModel(),
+ phases["directory"],
+ "bf16",
+ first_conversion = "bf16",
+ merge_is_disposable = True,
+ )
+ assert "141.0GB" in str(error.value)
+
+ def test_a_reused_output_directory_gets_no_relief(self, phases):
+ """The reclamation never deletes weights it did not write."""
+ directory = phases["directory"]
+ os.makedirs(directory, exist_ok = True)
+ with open(os.path.join(directory, "model.safetensors"), "w") as handle:
+ handle.write("x")
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "141.0GB" in str(error.value)
+
+ def test_an_unrelated_file_in_the_output_directory_is_not_a_merge(self, phases):
+ """A training `output_dir` holding an optimizer state still qualifies."""
+ directory = phases["directory"]
+ os.makedirs(directory, exist_ok = True)
+ with open(os.path.join(directory, "optimizer.pt"), "w") as handle:
+ handle.write("x")
+ assert self._preflight(phases) == (directory, False)
+
+ def test_an_unreadable_output_directory_gets_no_relief(self, phases, monkeypatch):
+ def boom(path):
+ raise PermissionError("no")
+
+ monkeypatch.setattr(S.os, "listdir", boom)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "141.0GB" in str(error.value)
+
+ def test_split_storage_charges_each_side_instead(self, phases):
+ """The reclamation declines across filesystems, so the relief must too."""
+ phases.update(separate = True, free = 62 * GB)
+ # 141 aggregate - 78 sibling = 63GB of checkpoint, 66.3GB once the
+ # merge's own 0.95 reserve is on it, and 62GB holds neither.
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "66.3GB" in str(error.value)
+
+ def test_it_can_only_ever_lower_the_figure(self, phases, monkeypatch):
+ """An estimator whose phases exceed the aggregate changes nothing."""
+ monkeypatch.setattr(
+ S,
+ "estimate_gguf_export_bytes",
+ lambda **kwargs: 300 * GB
+ if kwargs.get("base_cache_copy")
+ else (200 * GB if not kwargs.get("quantization_methods") else 141 * GB),
+ )
+ phases.update(free = 132 * GB)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "141.0GB" in str(error.value)
+
+ def test_an_estimator_that_cannot_size_a_phase_charges_the_aggregate(self, phases, monkeypatch):
+ real = S.estimate_gguf_export_bytes
+
+ def fake_estimate(**kwargs):
+ if kwargs.get("needs_merge", True) and not kwargs.get("quantization_methods"):
+ raise RuntimeError("no")
+ return real(**kwargs)
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight(phases)
+ assert "141.0GB" in str(error.value)
+
+ def _redirect_ask(self, phases, monkeypatch, **kwargs):
+ """What `kaggle_tmp_redirect` is asked for, with the move declined.
+
+ On Kaggle, which is the only environment the redirect fires in, and
+ where nothing is ever charged for a cache copy.
+ """
+ asked = []
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", True)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ try:
+ self._preflight(phases, **kwargs)
+ except RuntimeError:
+ # The ask is recorded before the refusal, and it is the ask this
+ # is about: a declined move followed by a refusal is exactly what
+ # a too-small aggregate produces.
+ pass
+ return asked
+
+ def test_the_redirect_is_asked_for_the_peak_and_not_the_aggregate(self, phases, monkeypatch):
+ """Or Kaggle relocates an export that fits to a /tmp it does not keep.
+
+ The refusal below reads the 123GB peak, so the redirect above it has
+ to as well: asked for the 141GB aggregate, a 132GB /kaggle/working
+ looks too small and the export is moved off notebook storage.
+ """
+ assert self._redirect_ask(phases, monkeypatch) == [self.MERGE_PHASE]
+
+ def test_a_merge_that_is_not_disposable_still_asks_the_aggregate(self, phases, monkeypatch):
+ asked = self._redirect_ask(phases, monkeypatch, merge_is_disposable = False)
+ assert asked == [self.AGGREGATE]
+
+ def test_split_storage_asks_the_aggregate(self, phases, monkeypatch):
+ """The reclamation declines across filesystems, so the ask must too."""
+ phases.update(separate = True)
+ asked = self._redirect_ask(phases, monkeypatch)
+ assert asked == [self.AGGREGATE]
+
+ def _reuse(self, phases):
+ """Leave a previous export's checkpoint in the output directory."""
+ directory = phases["directory"]
+ os.makedirs(directory, exist_ok = True)
+ with open(os.path.join(directory, "model.safetensors"), "w") as handle:
+ handle.write("x")
+ return directory
+
+ def test_a_reused_output_directory_asks_the_aggregate_first(self, phases, monkeypatch):
+ """Then asks the peak, because the move writes into a fresh directory.
+
+ The reclamation this directory cannot offer is available at the
+ redirect target, so a declined move is worth a second ask: 132GB free
+ here is already less than the 141GB aggregate, and the export really
+ does peak at 123GB once it is relocated.
+ """
+ self._reuse(phases)
+ assert self._redirect_ask(phases, monkeypatch) == [self.AGGREGATE, self.MERGE_PHASE]
+
+ def test_a_reused_output_directory_with_room_here_is_asked_once(self, phases, monkeypatch):
+ """Nothing is refused here, so there is nothing a move could rescue."""
+ self._reuse(phases)
+ phases.update(free = self.AGGREGATE)
+ assert self._redirect_ask(phases, monkeypatch) == [self.AGGREGATE]
+
+ def _zoo_redirect(self, phases, monkeypatch, tmp_path, working_free, tmp_free):
+ """Run the preflight against `kaggle_tmp_redirect`'s own move rule.
+
+ Returns `(asks, directory)`, with `directory` the one the export ends
+ up writing to.
+ """
+ target = str(tmp_path / "overlay" / "unsloth_saves" / "model")
+ asked = []
+
+ def redirect(
+ save_directory,
+ need_bytes = 0,
+ what = "export",
+ ):
+ asked.append(need_bytes)
+ if tmp_free <= working_free or need_bytes <= 0:
+ return save_directory, None
+ if working_free >= need_bytes or tmp_free < need_bytes:
+ return save_directory, None
+ os.makedirs(target, exist_ok = True)
+ return target, f"Unsloth: moved to {target}"
+
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", True)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", redirect)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: tmp_free if str(path).startswith(target) else working_free,
+ )
+ directory, _ = self._preflight(phases)
+ return asked, directory
+
+ def test_a_reused_directory_is_relocated_instead_of_refused(
+ self, phases, monkeypatch, tmp_path, capsys
+ ):
+ """100GB here, 130GB on the overlay: the 123GB peak fits after the move.
+
+ Asked only the 141GB aggregate, the overlay declines it too and the
+ export is refused on a filesystem it never had to use.
+ """
+ self._reuse(phases)
+ phases.update(free = 100 * GB)
+ asked, directory = self._zoo_redirect(
+ phases, monkeypatch, tmp_path, working_free = 100 * GB, tmp_free = 130 * GB
+ )
+ assert asked == [self.AGGREGATE, self.MERGE_PHASE]
+ assert directory == str(tmp_path / "overlay" / "unsloth_saves" / "model")
+ assert "moved to" in capsys.readouterr().out
+
+ def test_a_move_the_aggregate_would_have_made_is_not_cancelled(
+ self, phases, monkeypatch, tmp_path
+ ):
+ """130GB here holds the peak but not the aggregate, and no merge is
+
+ reclaimable here, so the refusal would read 141GB. Asking the peak
+ outright keeps the export on a filesystem that cannot run it; the
+ second ask only ever follows a move this directory could not avoid.
+ """
+ self._reuse(phases)
+ phases.update(free = 130 * GB)
+ asked, directory = self._zoo_redirect(
+ phases, monkeypatch, tmp_path, working_free = 130 * GB, tmp_free = 200 * GB
+ )
+ assert asked == [self.AGGREGATE]
+ assert directory == str(tmp_path / "overlay" / "unsloth_saves" / "model")
+
+ def test_save_to_gguf_passes_the_flag_through(self):
+ """The preflight and the reclamation must agree about disposability."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_save_pretrained_gguf)
+ assert "merge_is_disposable = merge_is_disposable" in source
+ assert source.index("_preflight_gguf_disk(") < source.index(
+ 'del arguments["merge_is_disposable"]'
+ )
+
+
+class TestTheConversionWorkingDirectoryIsMeasured:
+ """The intermediate GGUF is written to the process CWD, then moved.
+
+ `unsloth_zoo.llama_cpp.convert_to_gguf` passes a bare `--outfile`, which
+ llama.cpp resolves against the CWD; only an unwritable CWD falls back to
+ the input folder. So a Kaggle export redirected to /tmp still writes its
+ largest staging artefact into the 20GB /kaggle/working, and that was the
+ one filesystem this preflight never measured.
+ """
+
+ TMP = "/tmp/unsloth_saves/model"
+ WORKING = "/kaggle/working"
+
+ @pytest.fixture
+ def kaggle(self, monkeypatch):
+ state = {"cwd_free": 19 * GB, "conversion": self.WORKING}
+
+ def fake_estimate(**kwargs):
+ total = 60 * GB if kwargs.get("needs_merge", True) else 0
+ total += 30 * GB
+ if kwargs.get("quantization_methods"):
+ total += 9 * GB
+ return total
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 1000 * GB if str(path).startswith("/tmp") else state["cwd_free"],
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: (self.TMP, "moved to /tmp"))
+ monkeypatch.setattr(
+ S,
+ "_on_separate_filesystems",
+ lambda left, right: str(left).startswith("/tmp") != str(right).startswith("/tmp"),
+ )
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: state["conversion"])
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self):
+ return S._preflight_gguf_disk(
+ _FakeModel(), "/kaggle/working/model", "q4_k_m", first_conversion = "bf16"
+ )
+
+ def test_a_redirect_that_cannot_hold_the_conversion_is_refused(self, kaggle):
+ with pytest.raises(RuntimeError) as error:
+ self._preflight()
+ message = str(error.value)
+ assert self.WORKING in message and f"{self.TMP}_gguf" in message
+ assert "19.0GB free" in message and "30.0GB" in message
+ assert "UNSLOTH_DISK_PREFLIGHT=0" in message
+
+ def test_a_working_directory_with_room_changes_nothing(self, kaggle):
+ kaggle.update(cwd_free = 31 * GB)
+ assert self._preflight() == (self.TMP, True)
+
+ def test_the_boundary_is_the_conversion_alone(self, kaggle):
+ """Not the whole export: only the intermediate passes through here."""
+ kaggle.update(cwd_free = 30 * GB)
+ assert self._preflight() == (self.TMP, True)
+ kaggle.update(cwd_free = 29 * GB)
+ with pytest.raises(RuntimeError):
+ self._preflight()
+
+ def test_a_working_directory_on_the_same_filesystem_is_not_charged(self, kaggle):
+ """Then the move is a rename and the bytes are already counted."""
+ kaggle.update(conversion = "/tmp/somewhere", cwd_free = 1 * GB)
+ assert self._preflight() == (self.TMP, True)
+
+ def test_an_unmeasurable_working_directory_leaves_the_decision_alone(self, kaggle):
+ kaggle.update(cwd_free = None)
+ assert self._preflight() == (self.TMP, True)
+
+ def test_a_working_directory_that_cannot_be_identified_is_not_charged(self, kaggle):
+ kaggle.update(conversion = None)
+ assert self._preflight() == (self.TMP, True)
+
+ def test_it_is_not_reached_when_the_preflight_is_disabled(self, kaggle, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DISK_PREFLIGHT", "0")
+ assert self._preflight() == ("/kaggle/working/model", True)
+
+
+class TestWhereTheConversionWrites:
+ """`_gguf_conversion_directory` mirrors `convert_to_gguf`'s own rule."""
+
+ def test_a_writable_working_directory_wins(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ assert S._gguf_conversion_directory("model") == os.getcwd()
+
+ def test_an_unwritable_working_directory_falls_back_to_the_model(self, monkeypatch):
+ monkeypatch.setattr(S, "_directory_is_writable", lambda directory: False)
+ assert S._gguf_conversion_directory("model") == "model"
+
+ def test_an_unreadable_working_directory_is_unmeasurable(self, monkeypatch):
+ def boom():
+ raise OSError("no")
+
+ monkeypatch.setattr(S.os, "getcwd", boom)
+ assert S._gguf_conversion_directory("model") is None
+
+ def test_the_probe_answers_for_real_directories(self, tmp_path):
+ assert S._directory_is_writable(str(tmp_path)) is True
+ assert S._directory_is_writable(str(tmp_path / "nope")) is False
+
+ def test_the_probe_leaves_nothing_behind(self, tmp_path):
+ S._directory_is_writable(str(tmp_path))
+ assert list(tmp_path.iterdir()) == []
+
+
+class TestAColocatedConversionIsChargedWithTheCheckpoint:
+ """Split storage, and the conversion lands on the checkpoint's disk.
+
+ `save_directory` is a mount, so the `_gguf` sibling is on another
+ filesystem and the split branch charges this one for the checkpoint alone.
+ The intermediate conversion goes to the working directory and is only
+ moved to the sibling afterwards, so when that working directory is on the
+ same filesystem as `save_directory` the two sit there together - and the
+ conversion check charged this disk for the conversion alone. A 60GB
+ checkpoint and a 60GB conversion each passed on 100GB, and then it filled.
+
+ Numbers: 120GB aggregate, 60GB of it the sibling's, so a 60GB checkpoint
+ and a 60GB conversion.
+ """
+
+ CHECKPOINT = 60 * GB
+ SIBLING = 60 * GB
+ CONVERSION = 60 * GB
+
+ @pytest.fixture
+ def colocated(self, monkeypatch):
+ # One device map rather than a stub per pair, so the three paths cannot
+ # describe a machine that does not exist -- and so this fixture drives
+ # the code as it stands rather than a helper added to fix it.
+ state = {"free": 100 * GB, "devices": {"model": 1, "model_gguf": 2, "work": 1}}
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ return self.SIBLING if kwargs.get("quantization_methods") else self.CONVERSION
+ return self.CHECKPOINT + self.SIBLING
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 1000 * GB if str(path).endswith("_gguf") else state["free"],
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ # `model` is the mount and `model_gguf` is not, so the export is split;
+ # the working directory is on the mount with `model`.
+ monkeypatch.setattr(S, "_filesystem_id", lambda path: state["devices"].get(str(path)))
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self):
+ return S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", first_conversion = "bf16")
+
+ def test_both_artefacts_are_charged_to_the_one_filesystem(self, colocated):
+ """100GB holds either alone and not the pair."""
+ with pytest.raises(RuntimeError) as error:
+ self._preflight()
+ assert "120.0GB" in str(error.value)
+
+ def test_room_for_the_pair_is_not_refused(self, colocated):
+ colocated.update(free = 120 * GB)
+ assert self._preflight() == ("model", True)
+
+ def test_a_conversion_elsewhere_is_charged_only_once(self, colocated):
+ """The working directory on the sibling's disk leaves this one alone."""
+ colocated["devices"]["work"] = 2
+ assert self._preflight() == ("model", True)
+
+ def test_an_unmeasurable_working_directory_charges_nothing_extra(self, colocated, monkeypatch):
+ """`_shares_filesystem` says no to what it cannot see, so this is unchanged."""
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: None)
+ assert self._preflight() == ("model", True)
+
+ def test_the_predicate_never_guesses(self, monkeypatch):
+ monkeypatch.setattr(S, "_filesystem_id", lambda path: None)
+ assert S._shares_filesystem("a", "b") is False
+ assert S._on_separate_filesystems("a", "b") is False
+
+
+class TestTheMergeGuardAndTheConversionAreTwoPhases:
+ """The same colocated split, with a LoRA merge in front of it.
+
+ `merge_and_overwrite_lora` runs first and wants the checkpoint covered by
+ `free * 0.95`, with nothing else on the disk yet. The conversion is
+ written afterwards, next to the finished checkpoint and against no guard
+ at all. Adding the conversion to the reserved figure charges both at once
+ and asks for a peak that never exists.
+
+ Numbers: a 60GB checkpoint and a 60GB conversion. The merge phase wants
+ 63.2GB and the conversion phase 120GB, so 122GB of disk clears both, and
+ the sum asks 123.2GB and refuses it.
+ """
+
+ CHECKPOINT = 60 * GB
+ SIBLING = 60 * GB
+ CONVERSION = 60 * GB
+
+ @pytest.fixture
+ def colocated_merge(self, monkeypatch):
+ state = {"free": 122 * GB, "conversion": self.CONVERSION}
+
+ def fake_estimate(**kwargs):
+ if not kwargs.get("needs_merge", True):
+ return self.SIBLING if kwargs.get("quantization_methods") else state["conversion"]
+ return self.CHECKPOINT + self.SIBLING
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", fake_estimate)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 1000 * GB if str(path).endswith("_gguf") else state["free"],
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ # `model` and the working directory are one mount, the `_gguf` sibling
+ # another, so the export is split and the conversion lands here.
+ monkeypatch.setattr(
+ S,
+ "_filesystem_id",
+ lambda path: 2 if str(path) == "model_gguf" else 1,
+ )
+ # Only a PeftModel reaches the merge guard whose reserve this is about.
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self):
+ return S._preflight_gguf_disk(
+ _FakeAdapterModel(), "model", "q4_k_m", first_conversion = "bf16"
+ )
+
+ def test_the_taller_phase_decides_and_not_their_sum(self, colocated_merge):
+ """122GB clears the 63.2GB merge and then the 120GB pair."""
+ assert self._preflight() == ("model", True)
+
+ def test_the_pair_is_still_charged_in_full(self, colocated_merge):
+ colocated_merge.update(free = 119 * GB)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight()
+ assert "120.0GB" in str(error.value)
+
+ def test_the_merge_reserve_survives_a_small_conversion(self, colocated_merge):
+ """A 1GB conversion leaves the merge phase the taller of the two.
+
+ 61GB holds the checkpoint and the conversion together and is still
+ less than the 63.2GB `merge_and_overwrite_lora` insists on, so this
+ has to refuse: taking the maximum must not drop the reserve.
+ """
+ colocated_merge.update(conversion = 1 * GB, free = 62 * GB)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight()
+ assert "63.2GB" in str(error.value)
+
+ def test_a_non_peft_export_is_unchanged(self, colocated_merge):
+ """No merge guard, so the requirement is the pair and nothing more."""
+ colocated_merge.update(free = 120 * GB)
+ assert S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", first_conversion = "bf16") == (
+ "model",
+ True,
+ )
+
+ def test_the_guard_really_runs_before_the_conversion(self):
+ """The two phases are only separate while the merge is written first."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_save_pretrained_gguf)
+ assert source.index("unsloth_generic_save(**arguments)") < source.index("save_to_gguf(")
+ assert "merge_and_overwrite_lora" in inspect.getsource(S.unsloth_generic_save)
+
+
+class TestTheFallbackFollowsTheReusedCheckpoint:
+ """An unwritable CWD sends the conversion to the folder the converter READS.
+
+ `convert_to_gguf` redirects a bare `--outfile` into `input_folder`, and for
+ a non-PEFT model with a local `_name_or_path` that folder is the reused
+ checkpoint, not the requested output: `unsloth_save_pretrained_gguf`
+ reassigns `save_directory` to it before the conversion runs. Probing the
+ requested output there measures a filesystem nothing is written to, while
+ the intermediate fills the checkpoint's.
+ """
+
+ class _NonPeftFromDisk:
+ def __init__(self, directory):
+ self.config = type("cfg", (), {"_name_or_path": directory})()
+
+ def test_the_reused_checkpoint_is_the_input_folder(self, tmp_path):
+ model = self._NonPeftFromDisk(str(tmp_path))
+ assert S._gguf_model_input_directory(model, "model") == str(tmp_path)
+
+ def test_a_merged_model_still_reads_the_output(self, tmp_path, monkeypatch):
+ """A PEFT merge writes the checkpoint into `save_directory` and converts it."""
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ assert S._gguf_model_input_directory(_FakeAdapterModel(), "model") == "model"
+
+ def test_a_hub_id_is_not_a_directory(self):
+ model = self._NonPeftFromDisk("unsloth/Qwen3-32B")
+ assert S._gguf_model_input_directory(model, "model") == "model"
+
+ def test_a_model_with_no_config_reads_the_output(self):
+ assert S._gguf_model_input_directory(_FakeModel(), "model") == "model"
+
+ def test_the_probe_measures_the_checkpoints_filesystem(self, tmp_path, monkeypatch):
+ """End to end: the refusal names the checkpoint, not the requested output."""
+ checkpoint = tmp_path / "base"
+ checkpoint.mkdir()
+ model = self._NonPeftFromDisk(str(checkpoint))
+ monkeypatch.setattr(S, "_directory_is_writable", lambda directory: False)
+ monkeypatch.setattr(
+ S,
+ "estimate_gguf_export_bytes",
+ lambda **kwargs: 30 * GB if kwargs.get("quantization_methods") else 20 * GB,
+ )
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: 1 * GB if str(path) == str(checkpoint) else 1000 * GB,
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: (a[0], None))
+ monkeypatch.setattr(
+ S,
+ "_on_separate_filesystems",
+ lambda left, right: str(left) != str(right),
+ )
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ with pytest.raises(RuntimeError) as error:
+ S._preflight_gguf_disk(
+ model, "output", "q4_k_m", first_conversion = "bf16", needs_merge = False
+ )
+ message = str(error.value)
+ assert str(checkpoint) in message
+ assert "1.0GB free" in message and "20.0GB" in message
+
+ def test_the_converter_really_falls_back_to_its_input_folder(self):
+ """The redirect is only worth following while llama_cpp does this."""
+ import inspect
+
+ from unsloth_zoo import llama_cpp
+
+ source = inspect.getsource(llama_cpp.convert_to_gguf)
+ assert "os.path.abspath(input_folder)" in source
+ assert '"--outfile": output_file' in source
+
+
+class TestWhetherTheMergeCanBeReclaimed:
+ """`_merge_reclamation_is_possible` asks the question the reclamation asks."""
+
+ def test_a_directory_that_does_not_exist_yet(self, tmp_path):
+ assert S._merge_reclamation_is_possible(str(tmp_path / "new")) is True
+
+ def test_an_empty_directory(self, tmp_path):
+ assert S._merge_reclamation_is_possible(str(tmp_path)) is True
+
+ def test_a_directory_already_holding_a_checkpoint(self, tmp_path):
+ (tmp_path / "model.safetensors").write_text("x")
+ assert S._merge_reclamation_is_possible(str(tmp_path)) is False
+
+ def test_a_directory_holding_only_training_artifacts(self, tmp_path):
+ (tmp_path / "optimizer.pt").write_text("x")
+ (tmp_path / "training_args.bin").write_text("x")
+ assert S._merge_reclamation_is_possible(str(tmp_path)) is True
+
+ def test_an_unreadable_directory(self, monkeypatch):
+ def boom(path):
+ raise PermissionError("no")
+
+ monkeypatch.setattr(S.os, "listdir", boom)
+ assert S._merge_reclamation_is_possible("model") is False
+
+
+class TestTheGenericFallbackCopiesWhatItHolds:
+ """`unsloth_save_model` rebuilds a dictionary for ONE architecture layout.
+
+ Everything else -- GPT-2 style, custom heads, anything without
+ `.model.layers` -- falls to the generic branch, which calls
+ `save_pretrained(**save_pretrained_settings)` with the caller's dictionary
+ still in it and with no cast at all. So the checkpoint is that
+ dictionary's own bytes at its own dtypes, and a supplied fp32 dictionary
+ is twice what a 16-bit merge would have been.
+ """
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ @staticmethod
+ def _fp32_dict(numel = 4 * 1024**3 // 4):
+ import torch
+ return {"model.embed_tokens.weight": torch.zeros(numel, dtype = torch.float32)}
+
+ def test_the_dispositions_split_on_the_layout(self):
+ import torch
+ assert S._merge_writer_disposition(torch.nn.Linear(8, 8), "merged_16bit") == (True, True)
+ assert S._merge_writer_disposition(_ModelWithLayers(), "merged_16bit") == (False, False)
+
+ def test_a_supplied_dict_is_written_uncast(self, sized):
+ """4GB of fp32 stays 4GB here, where a cast would have called it 2GB."""
+ import torch
+
+ state_dict = self._fp32_dict()
+ S._preflight_merge_disk(
+ torch.nn.Linear(8, 8),
+ "model",
+ "merged_16bit",
+ state_dict = state_dict,
+ forwards_state_dict = True,
+ writes_model_verbatim = True,
+ )
+ assert S._cast_16bit_state_dict_bytes(state_dict) == 2 * GB
+ assert sized == [_merge_preflight_ask(4 * GB, 0)]
+
+ def test_no_dict_is_the_resident_model_at_its_own_dtype(self, sized):
+ """A bare `save_pretrained` casts nothing, so fp32 parameters cost four bytes."""
+ import torch
+
+ model = torch.nn.Linear(1024, 1024, bias = False, dtype = torch.float32)
+ S._preflight_merge_disk(
+ model,
+ "model",
+ "merged_16bit",
+ forwards_state_dict = True,
+ writes_model_verbatim = True,
+ )
+ assert sized == [_merge_preflight_ask(1024 * 1024 * 4, 0)]
+
+ def test_nothing_is_reserved_for_a_merge_that_never_runs(self, sized):
+ """No `merge_and_overwrite_lora` here, so no `free * 0.95` either."""
+ import torch
+
+ S._preflight_merge_disk(
+ torch.nn.Linear(8, 8),
+ "model",
+ "merged_16bit",
+ state_dict = self._fp32_dict(),
+ forwards_state_dict = True,
+ writes_model_verbatim = True,
+ )
+ assert sized == [4 * GB], "a reserve would round this up"
+
+ def test_an_adapter_is_left_exactly_as_it_was(self, sized, monkeypatch):
+ """A PeftModel in that branch writes adapters, not a checkpoint."""
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ S._preflight_merge_disk(
+ _FakeAdapterModel(),
+ "model",
+ "merged_16bit",
+ state_dict = self._fp32_dict(),
+ forwards_state_dict = True,
+ writes_model_verbatim = True,
+ )
+ # Sized from the model rather than the dictionary, and unreserved: the
+ # writer these two flags describe is `unsloth_save_model`, which merges
+ # and writes the shards itself with no `merge_and_overwrite_lora`
+ # anywhere behind it.
+ assert sized == [_merge_preflight_ask(10 * GB, 0)]
+ assert S._merge_writer_disposition(_FakeAdapterModel(), "merged_16bit") == (False, False)
+
+ def test_the_writer_really_still_forwards_it(self):
+ """The split above is only right while `unsloth_save_model` stays as it is."""
+ import inspect
+
+ source = inspect.getsource(S.unsloth_save_model)
+ assert (
+ 'or (not hasattr(model, "model") or not hasattr(internal_model.model, "layers"))'
+ in source
+ )
+ assert "model.save_pretrained(**save_pretrained_settings)" in source
+
+
+class TestASpecialExportStagesFromTheSuppliedDict:
+ """compressed-tensors and torchao merge through `unsloth_generic_save` too.
+
+ Both hand it `save_method = "merged_16bit"` and the caller's dictionary, so
+ that dictionary is what the kept (compressed) or staged (torchao) merge
+ costs. Sizing the resident model there prices a checkpoint that is not the
+ one being written.
+ """
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: 10 * GB)
+ monkeypatch.setattr(S, "_unquantized_parameter_bytes", lambda model, patterns = (): 0)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ @staticmethod
+ def _dict(gigabytes = 8):
+ import torch
+ return {
+ "model.embed_tokens.weight": torch.zeros(gigabytes * 1024**3 // 2, dtype = torch.float16)
+ }
+
+ def test_a_compressed_export_measures_the_dict(self, sized):
+ """8GB of merge plus its fp8 sibling, not the 10GB resident model."""
+ import torch
+
+ S._preflight_merge_disk(
+ torch.nn.Linear(8, 8),
+ "model",
+ "fp8",
+ state_dict = self._dict(8),
+ forwards_state_dict = True,
+ )
+ # Unreserved: with no adapter, `unsloth_generic_save` casts the dict
+ # and writes it, and the sibling is a quarter of the merge at worst,
+ # so the 5% band never showed up in this figure anyway.
+ assert sized == [_merge_preflight_ask(8 * GB + 4 * GB, 0)]
+
+ def test_a_torchao_export_measures_the_dict(self, sized):
+ """The staging merge is the dict; only the 8-bit sibling lands here."""
+ import torch
+
+ S._preflight_merge_disk(
+ torch.nn.Linear(8, 8),
+ "model",
+ "torchao_fp8",
+ state_dict = self._dict(8),
+ forwards_state_dict = True,
+ )
+ assert sized == [_merge_preflight_ask(4 * GB, 0)]
+
+ def test_the_special_methods_forward_without_casting_twice(self):
+ import torch
+ for method in ("fp8", "mxfp4", "torchao_fp8", "torchao_int8"):
+ assert S._merge_writer_disposition(torch.nn.Linear(8, 8), method) == (
+ True,
+ False,
+ ), method
+
+ def test_both_special_writers_really_pass_the_dict_on(self):
+ import inspect
+
+ for function in (S._unsloth_save_compressed_tensors, S._unsloth_save_torchao):
+ source = inspect.getsource(function)
+ assert "unsloth_generic_save(" in source
+ assert "merge_kwargs" in source
+ entrypoint = inspect.getsource(S.unsloth_save_pretrained_merged)
+ assert entrypoint.count("state_dict = state_dict,") >= 2
+
+
+class TestOnlyTheGuardedWriterIsCharged:
+ """The 5% reserve belongs to `merge_and_overwrite_lora` and to nothing else.
+
+ One function in this module calls it: `unsloth_generic_save`, and only on
+ its adapter branch. Every other writer that lands a 16-bit checkpoint at
+ `save_directory` is a bare `save_pretrained` that reserves nothing, so
+ charging it `1 / 0.95` moves an export off persistent Kaggle storage that
+ its writer would have accepted.
+
+ The reserve is decided apart from the sizing on purpose: a compressed
+ export IS cast to two bytes by that writer and keeps that sizing, adapter
+ or not.
+ """
+
+ MERGE = 10 * GB
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ asked = []
+ monkeypatch.setattr(S, "model_16bit_bytes", lambda model: self.MERGE)
+ monkeypatch.setattr(S, "_unquantized_parameter_bytes", lambda model, patterns = (): 0)
+ monkeypatch.setattr(
+ S,
+ "kaggle_tmp_redirect",
+ lambda save_directory, need_bytes = 0, what = "export": (
+ asked.append(need_bytes) or (save_directory, None)
+ ),
+ )
+ return asked
+
+ @pytest.fixture
+ def adapter(self, monkeypatch):
+ monkeypatch.setattr(S, "PeftModel", _FakeAdapterModel)
+ return _FakeAdapterModel()
+
+ def test_a_generic_sixteen_bit_save_with_no_adapter_reserves_nothing(self, sized):
+ """`unsloth_generic_save` casts the dict and writes it, with no merge.
+
+ The reserve here redirected a checkpoint that fits in the 5% band.
+ """
+ S._preflight_merge_disk(
+ _FakeModel(),
+ "model",
+ "merged_16bit",
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ )
+ assert sized == [self.MERGE]
+ assert sized != [_with_merge_headroom(self.MERGE)]
+
+ @pytest.mark.parametrize("save_method", ["torchao_fp8", "torchao_int8"])
+ def test_a_torchao_export_reserves_nothing_here(self, sized, adapter, save_method):
+ """It merges into a temp dir, so no guard runs against THIS filesystem.
+
+ True with an adapter as well, which is the case that has a guard at
+ all; it just runs somewhere else.
+ """
+ S._preflight_merge_disk(
+ adapter,
+ "model",
+ save_method,
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ )
+ assert sized == [self.MERGE // 2], "the sibling alone, at face value"
+
+ def test_a_compressed_export_with_no_adapter_reserves_nothing(self, sized):
+ """Sized as a cast 16-bit merge, because it is one, and still unguarded."""
+ S._preflight_merge_disk(_FakeModel(), "model", "fp8", forwards_state_dict = True)
+ assert sized == [self.MERGE + self.MERGE // 2]
+
+ def test_an_adapter_merged_by_the_generic_writer_keeps_its_reserve(self, sized, adapter):
+ """The one case the guard is real: it must survive all of the above."""
+ S._preflight_merge_disk(
+ adapter,
+ "model",
+ "merged_16bit",
+ forwards_state_dict = True,
+ writer_runs_merge_guard = True,
+ )
+ assert sized == [_with_merge_headroom(self.MERGE)]
+
+ def test_a_compressed_export_of_an_adapter_keeps_its_reserve(self, sized, adapter):
+ """Both entrypoints route a compressed export through the same writer.
+
+ So the method alone settles it and the flag is not needed.
+ """
+ S._preflight_merge_disk(adapter, "model", "fp8", forwards_state_dict = True)
+ # The sibling is half the merge, well past the 5%, so the aggregate is
+ # the binding figure. What matters is that the reserve is still there.
+ assert sized == [max(self.MERGE + self.MERGE // 2, _with_merge_headroom(self.MERGE))]
+
+ def test_the_plain_entrypoint_runs_no_guard_at_all(self, sized, adapter):
+ """`unsloth_save_pretrained_merged` merges in `unsloth_save_model`.
+
+ Which writes the merged shards itself and never calls the guarded
+ function, adapter or not.
+ """
+ S._preflight_merge_disk(adapter, "model", "merged_16bit")
+ assert sized == [self.MERGE]
+
+ def test_the_guarded_writer_is_the_only_one_in_the_module(self):
+ """The split above holds only while that stays true."""
+ import inspect
+
+ source = inspect.getsource(S)
+ assert source.count("merge_and_overwrite_lora(\n") == 1
+ generic = inspect.getsource(S.unsloth_generic_save)
+ before, _, after = generic.partition("merge_and_overwrite_lora(")
+ # The call sits on the adapter branch, and the no-adapter branch above
+ # it writes with `save_pretrained`.
+ assert "if not _is_peft:" in before
+ assert "model.save_pretrained(save_directory, **_save_kwargs)" in before
+ assert after.strip(), "the call takes arguments"
+
+
+class TestTheGgufPreflightIsToldTheModelDtype:
+ """`estimate_gguf_export_bytes` drops a requested output that EQUALS the
+ initial conversion, so naming the wrong dtype hides a whole checkpoint.
+
+ A bf16 model asked for `["f16", "q4_k_m"]` writes a bf16 intermediate AND
+ a separate f16 file. Told "f16", the estimate charges one 16-bit file
+ where the export writes two.
+ """
+
+ class _Config:
+ def __init__(self, dtype):
+ self.torch_dtype = dtype
+ self.dtype = dtype
+ self._name_or_path = "unsloth/model"
+
+ class _Model:
+ def __init__(self, config):
+ self.config = config
+
+ @pytest.fixture(autouse = True)
+ def bf16_hardware(self, monkeypatch):
+ monkeypatch.setattr(S.torch.cuda, "is_bf16_supported", lambda: True)
+
+ def test_a_bfloat16_model_reports_bf16(self):
+ import torch
+ assert S._gguf_source_dtype(self._Model(self._Config(torch.bfloat16))) == "bf16"
+ assert S._gguf_source_dtype(self._Model(self._Config("bfloat16"))) == "bf16"
+
+ def test_a_float16_model_reports_f16(self):
+ import torch
+ assert S._gguf_source_dtype(self._Model(self._Config(torch.float16))) == "f16"
+
+ def test_hardware_without_bf16_falls_back_like_the_exporter(self, monkeypatch):
+ import torch
+ monkeypatch.setattr(S.torch.cuda, "is_bf16_supported", lambda: False)
+ assert S._gguf_source_dtype(self._Model(self._Config(torch.bfloat16))) == "f16"
+
+ def test_an_unreadable_model_reports_the_exporters_own_fallback(self):
+ assert S._gguf_source_dtype(_FakeModel()) == "f16"
+
+ def test_the_wrong_dtype_undercounts_a_whole_checkpoint(self, monkeypatch):
+ """The zoo estimator, transcribed at the top of this file, priced for real."""
+ n = 8_190_735_360 # Qwen3-8B logical parameters
+
+ def estimate(
+ model = None,
+ quantization_methods = (),
+ first_conversion = "f16",
+ needs_merge = True,
+ n_parameters = None,
+ base_cache_copy = False,
+ ):
+ bits = {"f16": 16.0, "bf16": 16.0, "q4_k_m": 4.9}
+ total = n * 2 if needs_merge else 0
+ total += int(n * bits[first_conversion] / 8)
+ for method in dict.fromkeys(quantization_methods):
+ if method != first_conversion:
+ total += int(n * bits[method] / 8)
+ return total
+
+ asked = []
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", estimate)
+ monkeypatch.setattr(S, "free_bytes", lambda path: 1000 * GB)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(
+ S,
+ "_fallback_checkpoint_extra_bytes",
+ lambda model: asked.append(None) or 0,
+ )
+ wrong = estimate(quantization_methods = ["f16", "q4_k_m"], first_conversion = "f16")
+ right = estimate(quantization_methods = ["f16", "q4_k_m"], first_conversion = "bf16")
+ assert (right - wrong) == n * 2
+ assert round((right - wrong) / GB, 1) == 15.3
+
+ def test_the_call_site_resolves_it(self, monkeypatch):
+ """Driven, so a preflight left on its "f16" default fails here."""
+ import torch
+
+ seen = []
+ monkeypatch.setattr(
+ S,
+ "_preflight_gguf_disk",
+ lambda **kwargs: (
+ seen.append(kwargs.get("model_dtype")) or (kwargs["save_directory"], True)
+ ),
+ )
+ with contextlib.suppress(Exception):
+ S.unsloth_save_pretrained_gguf(
+ self._Model(self._Config(torch.bfloat16)),
+ "model",
+ # Any object gets past the "GGUF needs a tokenizer" check and
+ # dies well after the preflight, which is the point.
+ tokenizer = object(),
+ quantization_method = ["f16", "q4_k_m"],
+ )
+ assert seen == ["bf16"], "the preflight has to be told what the exporter will use"
+
+
+class TestThePrewarmedCacheIsChargedToItsOwnFilesystem:
+ """`save_directory` is a mount; `~/.cache` and the `_gguf` sibling are not.
+
+ Then the cached base model is written to the sibling's filesystem, and
+ charging it to the checkpoint's both drops a pre-warm that had room and
+ lets the sibling check accept `need_sibling` alone on a disk the base is
+ about to land on.
+
+ Numbers: a 60GB checkpoint, a 40GB sibling, a 60GB cache copy.
+ """
+
+ CHECKPOINT = 60 * GB
+ SIBLING = 40 * GB
+ CACHE = 60 * GB
+
+ @pytest.fixture
+ def split(self, monkeypatch):
+ # The cache is looked up through `_hub_cache_directory`, whose answer
+ # is a real path on this machine, so it is the DEFAULT of the device
+ # map rather than an entry in it. Patching the resolver instead would
+ # let a build that never calls it pass.
+ state = {"here": 1000 * GB, "there": 1000 * GB, "cache_device": 2}
+ devices = {"model": 1, "model_gguf": 2, "work": 2}
+
+ def estimate(**kwargs):
+ total = 0
+ if kwargs.get("needs_merge", True):
+ total += self.CHECKPOINT
+ if kwargs.get("base_cache_copy", False):
+ total += self.CACHE
+ if kwargs.get("quantization_methods"):
+ total += self.SIBLING
+ return total
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", estimate)
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: state["there"] if str(path).endswith("_gguf") else state["here"],
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ monkeypatch.setattr(
+ S, "_filesystem_id", lambda path: devices.get(str(path), state["cache_device"])
+ )
+ monkeypatch.setattr(S, "_fallback_checkpoint_extra_bytes", lambda model: 0)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self):
+ return S._preflight_gguf_disk(_FakeModel(), "model", "q4_k_m", first_conversion = "bf16")
+
+ def test_a_sibling_that_cannot_also_hold_the_cache_drops_the_prewarm(self, split, capsys):
+ """40GB of GGUF fits in 60GB; 40GB plus a 60GB base does not."""
+ split.update(there = 60 * GB)
+ assert self._preflight() == ("model", False)
+ assert "Skipping the Hugging Face cache pre-warm" in capsys.readouterr().out
+
+ def test_a_sibling_with_room_for_both_keeps_it(self, split):
+ split.update(there = 120 * GB)
+ assert self._preflight() == ("model", True)
+
+ def test_the_checkpoint_is_not_charged_for_bytes_written_elsewhere(self, split):
+ """60GB of checkpoint on a 63.2GB mount, with the cache on the other disk."""
+ split.update(here = math.ceil(self.CHECKPOINT / 0.95), there = 1000 * GB)
+ assert self._preflight() == ("model", True)
+
+ def test_a_cache_on_this_filesystem_is_still_charged_here(self, split):
+ """The premise reversed: nothing about the old accounting was wrong there."""
+ split.update(cache_device = 1, here = math.ceil(self.CHECKPOINT / 0.95), there = 1000 * GB)
+ assert self._preflight() == ("model", False)
+
+ def test_an_unresolvable_cache_is_charged_where_it_always_was(self, split, monkeypatch):
+ monkeypatch.setattr(S, "_hub_cache_directory", lambda: None)
+ split.update(here = math.ceil(self.CHECKPOINT / 0.95), there = 1000 * GB)
+ assert self._preflight() == ("model", False)
+
+ def test_the_resolver_follows_the_same_cache_the_prewarm_downloads_into(self):
+ import inspect
+
+ prewarm = inspect.getsource(S._prewarm_base_model_hub_cache)
+ assert "from unsloth_zoo.hf_cache import _active_caches" in prewarm
+ assert "_active_caches" in inspect.getsource(S._hub_cache_directory)
+
+
+class TestAnUnsupportedBF16IsNormalizedBeforeEstimating:
+ """`save_to_gguf` drops a bf16 initial conversion to f16 on a T4.
+
+ It does so AFTER resolving one, so the preflight has to do the same after
+ both of its branches. `_gguf_source_dtype` covers only the dtype the
+ preflight is TOLD; it cannot cover a `first_conversion` the caller passed,
+ nor the single direct-convert method `_choose_first_conversion` hands back
+ unchanged.
+
+ The cost is a whole checkpoint, because the estimate omits an output that
+ EQUALS the initial conversion: `["bf16"]` at "bf16" is priced as one
+ 16-bit file, and the export writes an f16 intermediate AND a bf16 output.
+ """
+
+ N = 8_190_735_360 # Qwen3-8B logical parameters
+ BITS = {"f32": 32.0, "f16": 16.0, "bf16": 16.0, "q4_k_m": 4.9}
+
+ @classmethod
+ def _estimate(
+ cls,
+ model = None,
+ quantization_methods = (),
+ first_conversion = "f16",
+ needs_merge = True,
+ n_parameters = None,
+ base_cache_copy = False,
+ ):
+ total = cls.N * 2 if needs_merge else 0
+ total += int(cls.N * cls.BITS[first_conversion] / 8)
+ for method in dict.fromkeys(quantization_methods):
+ if method != first_conversion:
+ total += int(cls.N * cls.BITS[method] / 8)
+ return total
+
+ @pytest.fixture
+ def sized(self, monkeypatch):
+ """Records the `first_conversion` the preflight prices the export at."""
+ asked = []
+
+ def estimate(**kwargs):
+ if kwargs.get("quantization_methods") and kwargs.get("needs_merge"):
+ # Once for `need` and once for `need_with_cache`; deduped so
+ # the assertions below are about the NAME and not the count.
+ if kwargs["first_conversion"] not in asked:
+ asked.append(kwargs["first_conversion"])
+ return self._estimate(**kwargs)
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", estimate)
+ monkeypatch.setattr(S, "free_bytes", lambda path: 1000 * GB)
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_fallback_checkpoint_extra_bytes", lambda model: 0)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ return asked
+
+ def _run(self, first_conversion):
+ S._preflight_gguf_disk(
+ _FakeModel(),
+ "model",
+ "bf16",
+ first_conversion = first_conversion,
+ model_dtype = "bf16",
+ )
+
+ @pytest.mark.parametrize("first_conversion", ["bf16", None])
+ def test_hardware_without_bf16_is_priced_at_f16(self, sized, monkeypatch, first_conversion):
+ """None goes through `_choose_first_conversion`, which returns "bf16" too."""
+ monkeypatch.setattr(S.torch.cuda, "is_bf16_supported", lambda: False)
+ self._run(first_conversion)
+ assert sized == ["f16"]
+
+ @pytest.mark.parametrize("first_conversion", ["bf16", None])
+ def test_hardware_with_bf16_is_left_alone(self, sized, monkeypatch, first_conversion):
+ monkeypatch.setattr(S.torch.cuda, "is_bf16_supported", lambda: True)
+ self._run(first_conversion)
+ assert sized == ["bf16"]
+
+ def test_an_unanswerable_probe_takes_the_wider_reading(self, sized, monkeypatch):
+ def boom():
+ raise RuntimeError("no CUDA here")
+
+ monkeypatch.setattr(S.torch.cuda, "is_bf16_supported", boom)
+ self._run("bf16")
+ assert sized == ["f16"]
+
+ def test_the_undercount_is_a_whole_checkpoint(self):
+ """What the wrong name costs, priced with the transcribed estimator."""
+ wrong = self._estimate(quantization_methods = ["bf16"], first_conversion = "bf16")
+ right = self._estimate(quantization_methods = ["bf16"], first_conversion = "f16")
+ assert (right - wrong) == self.N * 2
+ assert round(wrong / GB, 1) == 30.5
+ assert round(right / GB, 1) == 45.8
+ assert round((right - wrong) / GB, 1) == 15.3
+
+ def test_the_exporter_still_does_the_drop_this_mirrors(self):
+ import inspect
+
+ source = inspect.getsource(S.save_to_gguf)
+ assert 'first_conversion == "bf16" and not torch.cuda.is_bf16_supported()' in source
+ assert 'first_conversion = "f16"' in source
+
+
+class TestTheCacheIsChargedOnTheConversionFilesystem:
+ """A third filesystem: the output on an external drive, the CWD and the
+ Hugging Face cache together on the machine's own disk.
+
+ The pre-warm downloads the base there and leaves it there for the rest of
+ the export, so the cached base and the intermediate conversion are on that
+ disk together. `cache_here` and `cache_sibling` only ever place the cache
+ on the checkpoint's filesystem or the `_gguf` sibling's, and this is
+ neither, so nothing charged it.
+
+ The pre-warmer's own gate does not cover it: it asks for two base copies
+ free, and an `f32` conversion is two base copies on its own. Qwen3-8B, a
+ 15.3GB base and a 30.5GB conversion, on 38.1GB free: 38.1 clears the
+ pre-warm's 30.5 threshold and the conversion-only 30.5 check, then the
+ conversion writes 30.5 into the 22.8 the cached base left. 7.6GB short.
+ """
+
+ N = 8_190_735_360
+ BASE = 2 * N # the 16-bit base the pre-warm downloads: 15.3GB
+ CONVERSION = 4 * N # an f32 intermediate: 30.5GB, two base copies
+ WORK = "/work"
+ CACHE = "/home/u/.cache/huggingface"
+
+ @pytest.fixture
+ def state(self, monkeypatch):
+ # The output and its `_gguf` sibling on device 1; the CWD on device 2.
+ # `cache_device` is a knob so the same scenario can put the cache on
+ # the conversion's disk, on the output's, or nowhere resolvable.
+ state = {"conversion_free": int(2.5 * self.BASE), "cache_device": 2}
+ devices = {"model": 1, "model_gguf": 1, self.WORK: 2}
+
+ def estimate(**kwargs):
+ total = self.BASE if kwargs.get("needs_merge", True) else 0
+ if kwargs.get("base_cache_copy", False):
+ total += self.BASE
+ total += self.CONVERSION
+ return total
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", estimate)
+ monkeypatch.setattr(
+ S,
+ "_filesystem_id",
+ lambda path: devices.get(str(path), state["cache_device"]),
+ )
+ monkeypatch.setattr(
+ S,
+ "free_bytes",
+ lambda path: state["conversion_free"] if str(path) == self.WORK else 1000 * GB,
+ )
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_fallback_checkpoint_extra_bytes", lambda model: 0)
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: self.WORK)
+ monkeypatch.setattr(S, "_hub_cache_directory", lambda: self.CACHE)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self):
+ return S._preflight_gguf_disk(
+ _FakeModel(), "model", "f32", first_conversion = "f32", needs_merge = True
+ )
+
+ def test_the_prewarms_own_threshold_lets_this_through(self, state):
+ """Two base copies free, which is the gate `_prewarm...` applies."""
+ assert state["conversion_free"] >= 2 * self.BASE
+ assert round(state["conversion_free"] / GB, 1) == 38.1
+ assert round(self.CONVERSION / GB, 1) == 30.5
+ assert round(self.BASE / GB, 1) == 15.3
+ assert round((self.BASE + self.CONVERSION - state["conversion_free"]) / GB, 1) == 7.6
+
+ def test_a_cache_sharing_the_working_directory_drops_the_prewarm(self, state, capsys):
+ assert self._preflight() == ("model", False)
+ assert "Skipping the Hugging Face cache pre-warm" in capsys.readouterr().out
+
+ def test_room_for_both_keeps_it(self, state):
+ state.update(conversion_free = self.BASE + self.CONVERSION)
+ assert self._preflight() == ("model", True)
+
+ def test_a_cache_elsewhere_is_not_charged_here(self, state):
+ """The premise reversed: only a cache on THIS disk costs the pre-warm."""
+ state.update(cache_device = 3)
+ assert self._preflight() == ("model", True)
+
+ def test_an_unresolvable_cache_charges_nothing_new(self, state, monkeypatch):
+ monkeypatch.setattr(S, "_hub_cache_directory", lambda: None)
+ assert self._preflight() == ("model", True)
+
+ def test_a_conversion_that_does_not_fit_at_all_still_refuses(self, state):
+ """The raise comes first, so this can never soften a refusal."""
+ state.update(conversion_free = self.CONVERSION - 1)
+ with pytest.raises(RuntimeError, match = "written to the current working directory"):
+ self._preflight()
+
+ def test_no_prewarm_means_no_charge(self, state, monkeypatch):
+ """Kaggle and Colab return before the pre-warm, so it costs nothing."""
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", True)
+ assert self._preflight() == ("model", True)
+
+ def test_the_message_names_the_filesystem_it_measured(self, state, capsys):
+ self._preflight()
+ out = capsys.readouterr().out
+ assert self.WORK in out
+ assert "38.1GB free" in out
+ assert "~30.5GB" in out
+
+
+class TestACacheOnAnotherFilesystemIsNotChargedToTheOutputDisk:
+ """One filesystem for the export, another for the Hugging Face cache.
+
+ `HF_HOME` on a data volume is the ordinary layout on a machine with more
+ than one disk, and then the cached base is never written to the disk the
+ export lands on. Charging it there anyway drops the pre-warm on a disk
+ that had room for everything written to it, and the next export downloads
+ the whole base again - the exact re-download the pre-warm exists to stop.
+ The split branch already asks this question; the single-filesystem one
+ did not.
+
+ Numbers: a 60GB checkpoint, 40GB of quants, a 60GB cached base, 120GB
+ free. The export needs 100GB here and fits; only the fictitious cache
+ copy takes it to 160GB.
+ """
+
+ CHECKPOINT = 60 * GB
+ QUANTS = 40 * GB
+ CACHE = 60 * GB
+ ELSEWHERE = "/hf_cache"
+
+ @pytest.fixture
+ def state(self, monkeypatch):
+ state = {"free": 120 * GB, "cache_device": 2}
+ devices = {"model": 1, "model_gguf": 1, "work": 1}
+
+ def estimate(**kwargs):
+ total = 0
+ if kwargs.get("needs_merge", True):
+ total += self.CHECKPOINT
+ if kwargs.get("base_cache_copy", False):
+ total += self.CACHE
+ if kwargs.get("quantization_methods"):
+ total += self.QUANTS
+ return total
+
+ monkeypatch.setattr(S, "estimate_gguf_export_bytes", estimate)
+ monkeypatch.setattr(S, "free_bytes", lambda path: state["free"])
+ monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
+ monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ monkeypatch.setattr(
+ S, "_filesystem_id", lambda path: devices.get(str(path), state["cache_device"])
+ )
+ monkeypatch.setattr(S, "_hub_cache_directory", lambda: self.ELSEWHERE)
+ monkeypatch.setattr(S, "_fallback_checkpoint_extra_bytes", lambda model: 0)
+ monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
+ monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
+ monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
+ return state
+
+ def _preflight(self, **kwargs):
+ return S._preflight_gguf_disk(
+ _FakeModel(), "model", "q4_k_m", first_conversion = "bf16", **kwargs
+ )
+
+ def test_the_export_is_not_split_across_filesystems(self, state):
+ """The premise: this is the single-filesystem branch, not the split one."""
+ assert S._on_separate_filesystems("model", "model_gguf") is False
+ assert S._on_separate_filesystems(self.ELSEWHERE, "model") is True
+
+ def test_a_cache_elsewhere_keeps_the_prewarm(self, state, capsys):
+ """100GB of export on 120GB free; the 60GB cache is on another disk."""
+ assert self._preflight() == ("model", True)
+ assert "Skipping the Hugging Face cache pre-warm" not in capsys.readouterr().out
+
+ def test_a_cache_on_this_filesystem_still_drops_it(self, state, capsys):
+ """The premise reversed: nothing was wrong about the accounting there."""
+ state.update(cache_device = 1)
+ assert self._preflight() == ("model", False)
+ assert "Skipping the Hugging Face cache pre-warm" in capsys.readouterr().out
+
+ def test_room_for_both_keeps_it(self, state):
+ state.update(cache_device = 1, free = 160 * GB)
+ assert self._preflight() == ("model", True)
+
+ def test_an_unresolvable_cache_is_charged_where_it_always_was(self, state, monkeypatch):
+ monkeypatch.setattr(S, "_hub_cache_directory", lambda: None)
+ assert self._preflight() == ("model", False)
+
+ def test_no_prewarm_means_no_charge_either_way(self, state, monkeypatch):
+ """Colab returns before the pre-warm, so the cache costs nothing."""
+ monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", True)
+ state.update(cache_device = 1)
+ assert self._preflight() == ("model", True)
+
+ def test_an_export_that_does_not_fit_is_still_refused(self, state):
+ """Only the pre-warm decision reads this figure, so no refusal moves."""
+ state.update(free = 99 * GB)
+ with pytest.raises(RuntimeError) as error:
+ self._preflight()
+ assert "100.0GB" in str(error.value)
+
+ def test_a_reclaimed_merge_charges_the_cache_where_it_lands(self, state, monkeypatch):
+ """The peak branch takes the same figure, so it needs the same answer.
+
+ 60GB merge phase against 40GB of quants peaks at 60GB, not 100GB.
+ """
+ monkeypatch.setattr(S, "_merge_reclamation_is_possible", lambda directory: True)
+ state.update(free = 80 * GB)
+ assert self._preflight(merge_is_disposable = True) == ("model", True)
+ state.update(cache_device = 1)
+ assert self._preflight(merge_is_disposable = True) == ("model", False)
diff --git a/unsloth/_compressed_quantize.py b/unsloth/_compressed_quantize.py
index 8f7ed6e09e5..ec7564ef2f3 100644
--- a/unsloth/_compressed_quantize.py
+++ b/unsloth/_compressed_quantize.py
@@ -53,6 +53,28 @@ def _has_mtp(config):
return False
+def compressed_ignore_patterns(config):
+ """Modules the compressed recipe refuses to quantize, as llm-compressor `ignore` entries.
+
+ Module level, and reachable without importing anything outside the stdlib, so `save.py`
+ can size the quantized sibling from the same list the recipe is built from rather than a
+ second copy of it that drifts. This module is still only ever *executed* by file path.
+
+ Matching is compressed-tensors' `is_match`: a `re:` prefix is `re.match(pattern, name)`
+ against the module's fully qualified name, anything else is an exact name (or parent
+ class name) match.
+ """
+ ignore = ["lm_head"]
+ # Skip the same modules RedHatAI/NVIDIA skip for the Qwen3.5 / Qwen3-Next family (these also
+ # have shapes not divisible by the grouped-scheme group_size, which would otherwise error).
+ # No-ops elsewhere. Hybrid linear attention, VLM vision tower, and the MTP/speculative head.
+ ignore += ["re:.*\\.linear_attn\\..*", "re:.*\\.visual\\..*", "re:.*mtp.*"]
+ if _is_moe(config):
+ # Keep MoE routing layers unquantized: the router gate and (Qwen) shared-expert gate.
+ ignore += ["re:.*\\.gate$", "re:.*\\.shared_expert_gate$"]
+ return ignore
+
+
def _build_calibration_dataset(tokenizer, kind, value, num_samples, max_seq_length):
from datasets import DatasetDict, load_dataset, load_from_disk
@@ -248,15 +270,9 @@ def main():
# MoE models: keep the router/gate unquantized (it decides expert routing) and calibrate every
# expert even if the sample set does not route tokens to all of them.
- is_moe = _is_moe(getattr(model, "config", None))
- ignore = ["lm_head"]
- # Skip the same modules RedHatAI/NVIDIA skip for the Qwen3.5 / Qwen3-Next family (these also have
- # shapes not divisible by the grouped-scheme group_size, which would otherwise error). No-ops
- # elsewhere. Hybrid linear attention, VLM vision tower, and the MTP/speculative head.
- ignore += ["re:.*\\.linear_attn\\..*", "re:.*\\.visual\\..*", "re:.*mtp.*"]
- if is_moe:
- # Keep MoE routing layers unquantized: the router gate and (Qwen) shared-expert gate.
- ignore += ["re:.*\\.gate$", "re:.*\\.shared_expert_gate$"]
+ config = getattr(model, "config", None)
+ is_moe = _is_moe(config)
+ ignore = compressed_ignore_patterns(config)
moe_kwargs = {"moe_calibrate_all_experts": True} if is_moe else {}
def _make_recipe():
diff --git a/unsloth/disk_utils.py b/unsloth/disk_utils.py
new file mode 100644
index 00000000000..43110475d33
--- /dev/null
+++ b/unsloth/disk_utils.py
@@ -0,0 +1,124 @@
+# 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.
+"""Access to unsloth_zoo.disk_utils that survives an older installed zoo.
+
+The disk sizing and Kaggle detection logic is owned by
+`unsloth_zoo.disk_utils` so the two packages cannot disagree about whether we
+are on Kaggle. unsloth pins a new enough unsloth_zoo, but a stale environment
+that satisfies `import unsloth_zoo` and not `unsloth_zoo.disk_utils` must
+still be able to save a model, so the fallbacks below keep the environment
+question answered correctly and turn the new disk guard into a no-op rather
+than an ImportError.
+"""
+
+import os
+
+__all__ = [
+ "KAGGLE_TMP",
+ "KAGGLE_WORKING",
+ "is_kaggle_environment",
+ "is_colab_environment",
+ "free_bytes",
+ "logical_numel",
+ "model_16bit_bytes",
+ "model_logical_numel",
+ "estimate_gguf_export_bytes",
+ "kaggle_tmp_redirect",
+ "HAS_ZOO_DISK_UTILS",
+]
+
+try:
+ from unsloth_zoo.disk_utils import (
+ KAGGLE_TMP,
+ KAGGLE_WORKING,
+ is_kaggle_environment,
+ is_colab_environment,
+ free_bytes,
+ logical_numel,
+ model_16bit_bytes,
+ model_logical_numel,
+ estimate_gguf_export_bytes,
+ kaggle_tmp_redirect,
+ )
+ HAS_ZOO_DISK_UTILS = True
+
+except ImportError:
+ HAS_ZOO_DISK_UTILS = False
+
+ KAGGLE_TMP = "/tmp"
+ KAGGLE_WORKING = "/kaggle/working"
+ _TRUE = ("1", "true", "yes", "on")
+
+ def is_kaggle_environment():
+ # Kept byte for byte in step with unsloth_zoo.disk_utils: only a real
+ # kernel sets KAGGLE_KERNEL_RUN_TYPE, and only the Kaggle image has a
+ # /kaggle/working. KAGGLE_USERNAME / KAGGLE_KEY / KAGGLE_CONFIG_DIR
+ # are what people export for the Kaggle CLI on their own machines,
+ # and must never be mistaken for one.
+ override = os.environ.get("UNSLOTH_IS_KAGGLE", None)
+ if override is not None:
+ return str(override).strip().lower() in _TRUE
+ if not os.environ.get("KAGGLE_KERNEL_RUN_TYPE", "").strip():
+ return False
+ try:
+ return os.path.isdir(KAGGLE_WORKING)
+ except Exception:
+ return False
+
+ def is_colab_environment():
+ for key in os.environ:
+ if key.startswith("COLAB_"):
+ return True
+ return False
+
+ def free_bytes(path):
+ import shutil
+
+ try:
+ probe = os.path.abspath(os.path.expanduser(str(path)))
+ except Exception:
+ return None
+ while probe and not os.path.exists(probe):
+ parent = os.path.dirname(probe)
+ if parent == probe:
+ break
+ probe = parent
+ try:
+ return shutil.disk_usage(probe).free
+ except Exception:
+ return None
+
+ def logical_numel(param, name = ""):
+ # Packed storage cannot be unpacked without the zoo's knowledge of the
+ # packing schemes, so this reports what `numel()` says, exactly as the
+ # code did before it asked. Barely reachable: `model_16bit_bytes` is 0
+ # here, and every caller returns before sizing anything.
+ try:
+ return int(param.numel())
+ except Exception:
+ return 0
+
+ def model_logical_numel(model):
+ return 0
+
+ def model_16bit_bytes(model):
+ return 0
+
+ def estimate_gguf_export_bytes(*args, **kwargs):
+ # 0 means "unmeasurable", and every caller treats that as "do not
+ # block". An old unsloth_zoo therefore behaves exactly as it did.
+ return 0
+
+ def kaggle_tmp_redirect(save_directory, *args, **kwargs):
+ return save_directory, None
diff --git a/unsloth/save.py b/unsloth/save.py
index d98c12ad441..eac0b72a9e6 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -15,6 +15,7 @@
from unsloth_zoo.utils import Version
from importlib.metadata import version as importlib_version
from unsloth_zoo.hf_utils import dtype_from_config, HAS_TORCH_DTYPE
+from contextlib import contextmanager
from unsloth_zoo.llama_cpp import (
convert_to_gguf,
quantize_gguf,
@@ -49,6 +50,7 @@ except Exception:
from peft.tuners.lora import Linear as Peft_Linear
from typing import Optional, Callable, Union, List
import sys
+import math
import requests
import torch
import os
@@ -102,12 +104,24 @@ LLAMA_CPP_TARGETS = [
"llama-server",
]
-# Check environments
-keynames = "\n" + "\n".join(os.environ.keys())
-IS_COLAB_ENVIRONMENT = "\nCOLAB_" in keynames
-IS_KAGGLE_ENVIRONMENT = "\nKAGGLE_" in keynames
-KAGGLE_TMP = "/tmp"
-del keynames
+# Check environments. `is_kaggle_environment` needs a real Kaggle kernel, not
+# merely a KAGGLE_* variable: KAGGLE_USERNAME / KAGGLE_KEY / KAGGLE_CONFIG_DIR
+# are what the Kaggle CLI reads on an ordinary laptop, and every one of the
+# Kaggle branches below (rewriting save paths to /tmp, deleting the cached base
+# model) is wrong to take there.
+from .disk_utils import (
+ KAGGLE_TMP,
+ is_colab_environment,
+ is_kaggle_environment,
+ estimate_gguf_export_bytes,
+ free_bytes,
+ kaggle_tmp_redirect,
+ logical_numel,
+ model_16bit_bytes,
+)
+
+IS_COLAB_ENVIRONMENT = is_colab_environment()
+IS_KAGGLE_ENVIRONMENT = is_kaggle_environment()
# Weights
LLAMA_WEIGHTS = (
@@ -2379,6 +2393,26 @@ def unsloth_save_pretrained_merged(
"You can do it separately via `tokenizer.save_pretrained(...)`"
)
+ # Kaggle's working directory is ~20GB while the overlay at /tmp on the same
+ # kernel is measured in terabytes. Relative paths under /kaggle/working that
+ # do not fit move there; absolute paths, hub pushes and every non-Kaggle
+ # machine are untouched.
+ _forwards_state_dict, _writes_model_verbatim = _merge_writer_disposition(self, save_method)
+ save_directory = _preflight_merge_disk(
+ self,
+ save_directory,
+ save_method,
+ push_to_hub = push_to_hub,
+ state_dict = state_dict,
+ forwards_state_dict = _forwards_state_dict,
+ writes_model_verbatim = _writes_model_verbatim,
+ # No `writer_runs_merge_guard`: this entrypoint's writer for a plain
+ # merge is `unsloth_save_model`, which merges and writes the shards
+ # itself and never reaches `merge_and_overwrite_lora`. A compressed
+ # export from here does go through `unsloth_generic_save`, and the
+ # preflight recognises that from the method alone.
+ )
+
# FP8 / FP4 compressed-tensors export (llm-compressor) -> handled separately.
_compressed = _normalize_compressed_method(save_method)
if _compressed is not None:
@@ -2446,6 +2480,8 @@ def unsloth_save_pretrained_merged(
del arguments["self"]
del arguments["_compressed"]
del arguments["_torchao"]
+ del arguments["_forwards_state_dict"]
+ del arguments["_writes_model_verbatim"]
del arguments["calibration_dataset"]
del arguments["num_calibration_samples"]
del arguments["max_seq_length"]
@@ -2959,6 +2995,1469 @@ def push_to_ollama(tokenizer, gguf_location, username: str, model_name: str, tag
print("Successfully pushed to ollama")
+@contextmanager
+def _hub_cache_prewarm_disabled(disable):
+ """Turn the base-model cache pre-warm off for one export, then restore it.
+
+ The pre-warm is an optimization for the NEXT export, so on a disk that
+ cannot hold the cached base and the export at once, the export wins. The
+ old value goes back afterwards, including on an exception, so nothing
+ leaks into the rest of the session.
+ """
+ if not disable:
+ yield
+ return
+ key = "UNSLOTH_PREWARM_HUB_CACHE"
+ previous = os.environ.get(key, None)
+ os.environ[key] = "0"
+ try:
+ yield
+ finally:
+ if previous is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = previous
+
+
+# unsloth_zoo's own merge guard compares the save against `int(free * 0.95)`
+# (`saving_utils.merge_and_overwrite_lora`), and `model_16bit_bytes` counts
+# tensors only: config.json, the tokenizer files and the safetensors index are
+# written on top of them. Ask the redirect for that same effective figure, or a
+# working directory that measures "just big enough" keeps the export and the
+# merge then refuses it outright instead of using /tmp.
+_MERGE_FREE_SPACE_RESERVE = 0.95
+
+# torchao weight-only fp8 / int8: one byte per quantized weight.
+_TORCHAO_SIBLING_WEIGHT_BITS = 8
+
+
+def _compressed_scheme_weight_bits(scheme):
+ """Bits per weight of a compressed-tensors sibling checkpoint.
+
+ Four for every scheme that quantizes weights to 4 bits (`W4*`, and any
+ `*FP4` microscaling variant), eight for the rest. Rounded the way
+ unsloth_zoo rounds its GGUF table: over-estimating costs headroom,
+ under-estimating costs the whole export.
+ """
+ scheme = str(scheme).upper()
+ return 4 if scheme.startswith("W4") or "FP4" in scheme else 8
+
+
+def _compressed_ignore_patterns(model):
+ """The compressed recipe's own `ignore` list for this model, or an empty list.
+
+ Read out of `_compressed_quantize.py` rather than restated here, so the
+ sizing cannot drift from the recipe the way it already had. That module is
+ otherwise only ever *executed* by file path; its module-level imports are
+ stdlib only, so importing it costs nothing and imports no llm-compressor.
+
+ Any failure (module renamed, symbol gone, a config that will not answer)
+ returns nothing, which leaves the estimate exactly as it was.
+ """
+ try:
+ from unsloth._compressed_quantize import compressed_ignore_patterns
+ return list(compressed_ignore_patterns(getattr(model, "config", None)))
+ except Exception:
+ return []
+
+
+def _matches_ignore_pattern(name, module, patterns):
+ """Mirror compressed-tensors' `is_match` for one module against `ignore`.
+
+ `compressed_tensors.utils.match._match_name` treats a `re:` prefix as
+ `re.match(pattern, name)` - anchored at the start of the fully qualified
+ module name, and not required to reach its end - and everything else as
+ `target == name`. `_match_class` additionally matches a plain entry
+ against the names of the module's parent classes, which is why the MRO is
+ walked here too.
+
+ An unparseable pattern matches nothing rather than raising.
+ """
+ for pattern in patterns:
+ try:
+ if isinstance(pattern, str) and pattern.startswith("re:"):
+ if re.match(pattern.removeprefix("re:"), name) is not None:
+ return True
+ elif pattern == name:
+ return True
+ elif any(cls.__name__ == pattern for cls in type(module).__mro__):
+ return True
+ except Exception:
+ continue
+ return False
+
+
+def _named_parameters(module):
+ """`(name, parameter)` pairs, named where the module can say.
+
+ `logical_numel` needs the name to spot MXFP4 packing, which has no
+ `quant_state` to give it away and is only identifiable by the
+ `_blocks` / `_scales` suffix. `torch.nn.Module` always offers
+ `named_parameters`; the fall back to `parameters()` keeps any other object
+ that answers the older call working, just without the MXFP4 case.
+ """
+ try:
+ return list(module.named_parameters())
+ except Exception:
+ return [("", parameter) for parameter in module.parameters()]
+
+
+def _unquantized_parameter_bytes(model, ignore_patterns = ()):
+ """Bytes a weight-only export leaves at 16 bits in the sibling checkpoint.
+
+ compressed-tensors and torchao both quantize `Linear` weights only, so the
+ input embeddings and an untied `lm_head` stay 16-bit. They are the
+ dominant exclusion (a 4.5B model measured 0.5B of them), so pricing the
+ whole sibling at the scheme's width under-sizes it by the embedding share.
+
+ `ignore_patterns` is the recipe's `ignore` list, and every module it names
+ stays 16-bit as well: the vision tower of a VLM, a Qwen3-Next hybrid's
+ linear-attention blocks, an MTP head, the MoE router gates. Those are the
+ same order of magnitude as the embeddings, and pricing them at 4 or 8 bits
+ under-sizes the merge, which is the direction that loses the redirect.
+ Empty for torchao, which quantizes with no ignore list of its own.
+
+ Every parameter is measured with `logical_numel`, the same helper
+ `model_16bit_bytes` sizes the merge with, and NOT with `numel()`. A model
+ loaded in 4 bits holds `Params4bit`, whose `numel()` is the packed uint8
+ count and roughly half the logical one; MXFP4 blocks are worth twice
+ theirs. Believing `numel()` would price an ignored subtree at half what
+ the export writes for it while the merge it is subtracted from was priced
+ logically, and the two have to agree.
+
+ Tied embeddings are one tensor and are counted once, and a module already
+ counted through an embedding getter or through an enclosing ignored module
+ is not counted again. Zero when the model does not answer, which leaves
+ the estimate exactly as it was.
+ """
+ total = 0
+ seen = set()
+ for getter in ("get_input_embeddings", "get_output_embeddings"):
+ try:
+ weight = getattr(getattr(model, getter)(), "weight", None)
+ if weight is None or id(weight) in seen:
+ continue
+ seen.add(id(weight))
+ total += logical_numel(weight) * 2
+ except Exception:
+ continue
+ if not ignore_patterns:
+ return total
+ try:
+ named_modules = list(model.named_modules())
+ except Exception:
+ # A model whose modules cannot be walked keeps the embeddings-only figure.
+ return total
+ for name, module in named_modules:
+ try:
+ if not _matches_ignore_pattern(name, module, ignore_patterns):
+ continue
+ for parameter_name, parameter in _named_parameters(module):
+ if id(parameter) in seen:
+ continue
+ seen.add(id(parameter))
+ total += logical_numel(parameter, parameter_name) * 2
+ except Exception:
+ continue
+ return total
+
+
+def _quantized_sibling_bytes(
+ model,
+ merge_bytes,
+ weight_bits,
+ ignore_patterns = (),
+):
+ """Bytes of the quantized sibling written to `save_directory + "-<suffix>"`.
+
+ `merge_bytes` is the 16-bit checkpoint size. Only the part of it that a
+ weight-only scheme actually quantizes shrinks; the rest is copied across
+ at 16 bits.
+ """
+ unquantized = min(_unquantized_parameter_bytes(model, ignore_patterns), merge_bytes)
+ return int((merge_bytes - unquantized) * weight_bits / 16) + unquantized
+
+
+def _full_model_checkpoint_bytes(model, state_dict = None):
+ """Bytes `save_pretrained` writes for a model with no adapter to merge.
+
+ Measured from the parameters' real storage rather than assumed to be a
+ 16-bit merge, because this checkpoint is written with no cast: an fp32
+ model costs four bytes per parameter, a 4-bit one its packed storage.
+ Zero when the model cannot be measured, which leaves the caller with
+ today's behaviour.
+
+ A caller-supplied `state_dict` is measured INSTEAD of the model, because
+ it is what `save_pretrained` writes and the two can disagree by a whole
+ factor: only `"16bit" in save_method` casts the dict, so a `"lora"` save
+ on a model with no adapter forwards an fp32 dict verbatim while the
+ resident parameters are fp16, and sizing the model would price the export
+ at half. Undercounting here is not a crash but a missed `/tmp` redirect,
+ which is how the 20GB Kaggle working directory fills instead.
+ """
+ try:
+ # `is not None`, matching `unsloth_generic_save`, which forwards the
+ # dict on exactly that test. An explicitly empty one therefore reaches
+ # `save_pretrained` and writes no tensors at all, so sizing the resident
+ # model there would price tens of gigabytes for a save that writes none
+ # and move it off persistent Kaggle storage for nothing.
+ if state_dict is not None:
+ total = 0
+ for tensor in state_dict.values():
+ tensor = getattr(tensor, "data", tensor)
+ total += tensor.numel() * tensor.element_size()
+ return int(total)
+ total = 0
+ for parameter in model.parameters():
+ total += parameter.numel() * parameter.element_size()
+ return int(total)
+ except Exception:
+ return 0
+
+
+def _cast_16bit_state_dict_bytes(state_dict):
+ """Bytes a `"16bit"` save writes for a caller-supplied `state_dict`.
+
+ `unsloth_generic_save` casts every FLOATING entry to bf16/fp16 and leaves
+ the rest alone, then hands the dictionary straight to `save_pretrained`.
+ So the floats are two bytes per element whatever they arrived as, and an
+ integer or bool entry keeps its own width.
+
+ `numel()` and not `logical_numel`, because these are the tensors the
+ writer writes: a packed 4-bit entry is stored exactly as it stands here,
+ not expanded.
+ """
+ total = 0
+ for tensor in state_dict.values():
+ tensor = getattr(tensor, "data", tensor)
+ try:
+ floating = bool(tensor.is_floating_point())
+ except Exception:
+ floating = False
+ total += tensor.numel() * (2 if floating else tensor.element_size())
+ return int(total)
+
+
+def _same_filesystem(left, right):
+ """True when two paths sit on the same mount.
+
+ Neither path has to exist. The nearest existing ancestor answers, exactly
+ as `free_bytes` resolves the disk it measures, because that ancestor is
+ the filesystem a write to the path really lands on. A destination is
+ routinely absent here: `_preflight_merge_disk` runs before anything is
+ created, so stat-ing it directly raised, the callers' broad handlers
+ swallowed the probe, and a first export got no TMPDIR warning at all.
+
+ Raises when either side cannot be identified, which is what every caller
+ already reads as "cannot tell".
+ """
+ left_id = _filesystem_id(left)
+ right_id = _filesystem_id(right)
+ if left_id is None or right_id is None:
+ raise OSError(f"Unsloth: cannot identify the filesystem holding `{left}` or `{right}`.")
+ return left_id == right_id
+
+
+def _destination_holds_torchao_staging(destination, need_bytes, staging_bytes):
+ """Can the redirect target hold the torchao staging merge as well?
+
+ `_unsloth_save_torchao` merges into `tempfile.mkdtemp()` and removes it
+ only once quantization has finished, so where the tempfile default and the
+ redirect target are the same filesystem - which is exactly a Kaggle kernel,
+ where both are /tmp - the staging checkpoint and the quantized sibling sit
+ on the destination at the same time.
+
+ Checked here rather than added to `need_bytes`, because the staging
+ directory never lands in /kaggle/working: charging it there would relocate
+ exports that fit into /tmp, which is not kept as notebook output. So this
+ can only ever cancel a redirect, never cause one, and it cancels one only
+ when the destination could not have held the export anyway - in which case
+ staying put leaves the working directory's own guard to raise the real
+ error.
+ """
+ import tempfile
+ try:
+ if staging_bytes <= 0:
+ return True
+ if not _same_filesystem(tempfile.gettempdir(), destination):
+ return True
+ free = free_bytes(destination)
+ if free is None:
+ return True
+ return free >= need_bytes + staging_bytes
+ except Exception:
+ return True
+
+
+def _warn_if_sibling_filesystem_is_short(save_directory, suffix, sibling_bytes):
+ """Say so when the quantized sibling lands on a disk nobody measured.
+
+ Compressed and torchao exports build their output lexically, as
+ `save_directory + "-<suffix>"`, so the sibling is a child of the PARENT of
+ `save_directory`. That is the same filesystem the preflight probed, unless
+ `save_directory` is itself a symlink or a mount point. When it is, the
+ probe answers for the target and the sibling is written on the other side:
+ a `model` symlinked into a roomy /tmp passes here while `model-fp8` fills
+ a 20GB working directory.
+
+ A warning rather than a different redirect, for the same reason as the
+ staging one. `kaggle_tmp_redirect` relocates `save_directory`, and the
+ caller derives the sibling from whatever this function returns, so a
+ redirect already moves both. The uncovered case is the one where NO
+ redirect fires, and there is nothing to cancel there.
+ """
+ try:
+ if sibling_bytes <= 0 or not suffix:
+ return
+ sibling = f"{save_directory}-{suffix}"
+ # The directory the sibling is created IN, which is what has the space.
+ holder = os.path.dirname(os.path.abspath(sibling)) or "."
+ if _same_filesystem(holder, save_directory):
+ return
+ free = free_bytes(holder)
+ if free is None or free >= sibling_bytes:
+ return
+ print(
+ f"Unsloth: `{holder}` has {free / 1024**3:.1f}GB free and the quantized "
+ f"`{os.path.basename(sibling)}` needs about {sibling_bytes / 1024**3:.1f}GB there.\n"
+ f"`{save_directory}` resolves to a different filesystem, and the sibling is "
+ f"written next to the name rather than next to the target, so the room at "
+ f"`{save_directory}` does not help.\n"
+ f"Save to a path on the roomy filesystem itself rather than through a link."
+ )
+ except Exception:
+ return
+
+
+def _warn_if_torchao_staging_filesystem_is_short(destination, staging_bytes):
+ """Say so when TMPDIR cannot hold the staging merge either.
+
+ `_destination_holds_torchao_staging` asks whether the DESTINATION can hold
+ the staging directory as well, which is the whole question while
+ `tempfile` resolves onto the same filesystem. When it does not, that
+ function returns True and nothing has measured the staging filesystem at
+ all, so a 4GB tmpfs is handed a 60GB merge and `_unsloth_save_torchao`
+ dies inside `tempfile.mkdtemp` without naming TMPDIR as the reason.
+
+ A warning, not a refusal: the preflight never raises, and unlike the
+ destination check this cannot be answered by cancelling the redirect.
+ The staging merge is written to TMPDIR whether or not the export was
+ relocated, so declining the move leaves the identical failure and puts
+ the output on the smaller disk as well.
+ """
+ import tempfile
+ try:
+ if staging_bytes <= 0:
+ return
+ staging_directory = tempfile.gettempdir()
+ if _same_filesystem(staging_directory, destination):
+ return
+ free = free_bytes(staging_directory)
+ # The staging merge is written by `merge_and_overwrite_lora`, which
+ # refuses it unless `free * 0.95` covers it. Comparing against the
+ # bare size leaves the 5% band where the merge predictably dies and
+ # this says nothing, which is the one thing it exists to prevent.
+ needed = math.ceil(staging_bytes / _MERGE_FREE_SPACE_RESERVE)
+ if free is None or free >= needed:
+ return
+ print(
+ f"Unsloth: `{staging_directory}` has {free / 1024**3:.1f}GB free and the "
+ f"16-bit staging merge needs about {needed / 1024**3:.1f}GB there.\n"
+ f"The torchao export merges into a temporary directory before it quantizes, "
+ f"and that directory is on a different filesystem from `{destination}`, so "
+ f"the room at the destination does not help.\n"
+ f"Point TMPDIR at a filesystem with the space if the export runs out."
+ )
+ except Exception:
+ return
+
+
+def _warn_if_a_cancelled_redirect_leaves_no_room(save_directory, sibling_bytes):
+ """Say so when the export is handed back a filesystem that cannot hold it.
+
+ Cancelling the torchao redirect returns the quantized sibling to
+ `save_directory`, and outside `UNSLOTH_KAGGLE_USE_TMP=1` the only reason
+ the redirect fired at all is that that filesystem measured too small for
+ it. Nothing downstream covers the sibling: the torchao merge is staged in
+ TMPDIR, so `merge_and_overwrite_lora`'s `free * 0.95` measures the staging
+ disk and never this one, and the sibling is written at the very end of a
+ long quantization. Cancelling is still the right move - /tmp cannot hold
+ the staging merge and the sibling together, so relocating fails too - but
+ it must not be silent for the minutes the quantization takes.
+
+ A warning and not a refusal, for the same reason as the two warnings
+ beside it: this preflight never raises, and the sibling is an estimate.
+ """
+ try:
+ if sibling_bytes <= 0:
+ return
+ free = free_bytes(save_directory)
+ if free is None or free >= sibling_bytes:
+ return
+ print(
+ f"Unsloth: `{save_directory}` has {free / 1024**3:.1f}GB free and the quantized "
+ f"checkpoint needs about {sibling_bytes / 1024**3:.1f}GB there.\n"
+ f"The export was left here rather than moved to a larger filesystem, because "
+ f"that filesystem cannot hold the temporary 16-bit merge as well.\n"
+ f"Free space here, or point TMPDIR at a filesystem with room for the merge, "
+ f"before the quantization runs: it is written at the end of the export."
+ )
+ except Exception:
+ return
+
+
+def _merge_writer_disposition(model, save_method):
+ """What `save_pretrained_merged`'s writer does with a supplied `state_dict`.
+
+ Returns `(forwards, verbatim)` for the `_preflight_merge_disk` arguments of
+ the same meaning. Three writers sit behind that one entrypoint and they do
+ not agree:
+
+ - a compressed-tensors or torchao export hands the dictionary to
+ `unsloth_generic_save(save_method = "merged_16bit")`, which casts every
+ floating entry to two bytes and writes it. That checkpoint is the
+ staging (torchao) or kept (compressed) merge, so it is sized from the
+ dictionary, not from the resident model,
+ - `unsloth_save_model` on an architecture that walks `.model.layers`
+ rebuilds the dictionary from the merged layers and drops whatever it
+ was handed, so sizing the caller's would price a save that is not
+ happening,
+ - `unsloth_save_model` on any other architecture takes its generic
+ fallback and calls `save_pretrained(**save_pretrained_settings)` with
+ the caller's dictionary untouched AND uncast, so the bytes written are
+ the dictionary's own, at its own dtypes.
+
+ Never raises: an unreadable model or an unrecognised method reports the
+ conservative `(False, False)`, which is the behaviour before this existed.
+ """
+ method = str(save_method).lower().strip().replace("-", "_").replace(" ", "_")
+ try:
+ compressed = _normalize_compressed_method(method)
+ torchao = _normalize_torchao_method(method)
+ except Exception:
+ return False, False
+ if compressed is not None or torchao is not None:
+ return True, False
+ if method != "merged_16bit":
+ return False, False
+ # A PeftModel in the generic fallback writes ADAPTERS and not a checkpoint,
+ # so it keeps the sizing it has rather than being priced a full model.
+ if isinstance(model, (PeftModel, PeftModelForCausalLM)):
+ return False, False
+ try:
+ # The same predicate `unsloth_save_model` dispatches on, and no other.
+ takes_generic_fallback = not hasattr(model, "model") or not hasattr(
+ getattr(model, "model", None), "layers"
+ )
+ except Exception:
+ return False, False
+ return (True, True) if takes_generic_fallback else (False, False)
+
+
+def _preflight_merge_disk(
+ model,
+ save_directory,
+ save_method,
+ push_to_hub = False,
+ state_dict = None,
+ forwards_state_dict = False,
+ writes_model_verbatim = False,
+ writer_runs_merge_guard = False,
+):
+ """Kaggle only: send a merge that cannot fit in /kaggle/working to /tmp.
+
+ Never raises. A merge that is short of space on an ordinary machine is
+ already handled by unsloth_zoo's own guard, which knows about shard
+ streaming and the push_to_hub fallbacks; this exists purely so the ~20GB
+ Kaggle working directory stops being the ceiling when a terabyte of
+ overlay is mounted next to it.
+
+ Skipped entirely when pushing to the hub, because there `save_directory`
+ is a repo id like "user/model", not a filesystem path, and rewriting it
+ would push to the wrong repository.
+
+ `forwards_state_dict` says the writer behind this call hands a supplied
+ `state_dict` to `save_pretrained` for a 16-bit save rather than building
+ its own, casting its floating entries to two bytes on the way, as
+ `unsloth_generic_save` does. `unsloth_save_model`'s merge path instead
+ rebuilds the dictionary from the merged layers and drops whatever it was
+ given, so sizing the caller's there would price a save that is not
+ happening.
+
+ `writes_model_verbatim` says the writer copies what it holds to
+ `save_pretrained` with no cast at all, which is `unsloth_save_model`'s
+ generic architecture fallback. Then the checkpoint is the dictionary's own
+ bytes, at its own dtypes, or the resident parameters' own bytes when no
+ dictionary was supplied, and never two bytes per logical parameter.
+ `_merge_writer_disposition` decides both for the public entrypoint.
+
+ `writer_runs_merge_guard` says the writer behind this call is
+ `unsloth_generic_save`, whose PEFT branch is the one and only caller of
+ `merge_and_overwrite_lora` here and therefore the only writer that brings
+ its `free * 0.95` guard with it. It is deliberately separate from the two
+ flags above, which decide SIZING: a compressed export is cast to two bytes
+ by that same writer and is sized accordingly, yet it reserves nothing
+ unless there is an adapter for the guard to merge.
+ """
+ if push_to_hub:
+ return save_directory
+ # `unsloth_save_model` normalizes spaces before it dispatches, so
+ # "merged 16bit" is the same full merge as "merged_16bit" and has to be
+ # measured as one. `_normalize_compressed_method` normalizes the same way.
+ method = str(save_method).lower().strip().replace("-", "_").replace(" ", "_")
+ try:
+ # Every compressed export keeps the 16-bit merge at `save_directory`
+ # and writes a quantized sibling next to it, so all of them belong
+ # here, not just mxfp4.
+ compressed = _normalize_compressed_method(method)
+ except Exception:
+ # An unsupported near-miss name raises later, where the message is.
+ return save_directory
+ # The torchao portable exports are the same shape as the compressed ones
+ # from here: a quantized sibling at `save_directory + "-<suffix>"`.
+ torchao = _normalize_torchao_method(method)
+ # `lora` on a model that has no adapter writes the WHOLE model instead:
+ # both `unsloth_generic_save` and `unsloth_save_model` fall back to
+ # `save_pretrained` there, so a full fine-tune asked for "lora" fills
+ # /kaggle/working exactly like a merge. A real PeftModel writes adapters
+ # only and is still skipped.
+ is_peft = isinstance(model, (PeftModel, PeftModelForCausalLM))
+ full_model_lora = method == "lora" and not is_peft
+ # `unsloth_generic_save` only reaches for `model.state_dict()` when it was
+ # given none, and a model with no adapter is saved from whatever dictionary
+ # it ends up holding. A PeftModel goes to `merge_and_overwrite_lora`, which
+ # takes no state dict at all, so only the non-PEFT case follows it.
+ supplied_dict = state_dict if (forwards_state_dict and not is_peft) else None
+ # Same reason the dict is only followed for a non-PEFT model: a PeftModel
+ # never reaches the fallback that would copy one verbatim.
+ verbatim = bool(writes_model_verbatim) and not is_peft
+ if compressed is None and torchao is None and method != "merged_16bit" and not full_model_lora:
+ return save_directory
+ try:
+ # A merge writes 2 bytes per logical parameter and no GGUF at all, so
+ # this is `model_16bit_bytes` and not the GGUF export estimate: that
+ # one always prices an intermediate GGUF conversion this never does.
+ # The full-model fallback casts nothing, so it is sized from the
+ # tensors' own dtype instead.
+ #
+ # A 16-bit save of a model with no adapter writes the dictionary it was
+ # handed, cast, and not the resident parameters: an empty or partial one
+ # writes correspondingly less, and one carrying more than the model does
+ # writes more. Sizing the model there redirects a nearly empty save off
+ # persistent Kaggle storage, or leaves a larger one to fill the working
+ # filesystem.
+ #
+ # A compressed or torchao export writes that same 16-bit checkpoint
+ # through the same `unsloth_generic_save`, as its staging (torchao) or
+ # kept (compressed) merge, so the dictionary decides its size too and
+ # not only a literal `merged_16bit` request.
+ if full_model_lora or verbatim:
+ need = _full_model_checkpoint_bytes(model, state_dict)
+ elif supplied_dict is not None:
+ need = _cast_16bit_state_dict_bytes(supplied_dict)
+ else:
+ need = model_16bit_bytes(model)
+ if need <= 0:
+ return save_directory
+ # What the torchao staging directory costs on whatever filesystem
+ # `tempfile` resolves to. Zero for every other export, which stages
+ # nothing.
+ staging = 0
+ # The lexical suffix the quantized sibling is written under, so the
+ # filesystem holding it can be measured separately below.
+ sibling_suffix = ""
+ sibling_bytes = 0
+ # What `merge_and_overwrite_lora` will be asked to write HERE, which is
+ # the only part its `free * 0.95` guard measures. Split out from `need`
+ # because the reserve belongs on this and on nothing else: charging it
+ # around the whole estimate relocates an export that fits, and on
+ # Kaggle that means moving it to a /tmp the kernel does not keep.
+ # The guard belongs to `merge_and_overwrite_lora` and to nothing else,
+ # and only `unsloth_generic_save`'s PEFT branch calls it. Every other
+ # writer that lands a 16-bit checkpoint here is a bare
+ # `save_pretrained`: the generic architecture fallback, the full-model
+ # `lora` fallback, `unsloth_save_model`'s own merge, and
+ # `unsloth_generic_save`'s no-adapter branch, which casts the dict and
+ # writes it directly. None of them reserves anything, so charging them
+ # 1/0.95 refuses a filesystem their writer would have accepted.
+ #
+ # Sizing is decided separately, above: a compressed export really is
+ # cast to two bytes by `unsloth_generic_save`, so it keeps that sizing
+ # whether or not there is an adapter to merge.
+ guard_runs_here = is_peft and (compressed is not None or bool(writer_runs_merge_guard))
+ merge_here = need if guard_runs_here else 0
+ if torchao is not None:
+ # `_unsloth_save_torchao` merges into a `tempfile.mkdtemp` staging
+ # directory rather than `save_directory`, so the only thing landing
+ # here is the 8-bit sibling, and no merge guard runs against this
+ # filesystem at all.
+ staging = need
+ merge_here = 0
+ # No ignore list: `_unsloth_save_torchao` quantizes with a bare
+ # `Float8WeightOnlyConfig()` / `Int8WeightOnlyConfig()`. Charging it
+ # the compressed recipe's exclusions would over-count, and
+ # over-counting relocates an export that fits into a /tmp Kaggle
+ # does not keep as notebook output.
+ need = _quantized_sibling_bytes(model, need, _TORCHAO_SIBLING_WEIGHT_BITS)
+ sibling_suffix = torchao[1]
+ sibling_bytes = need
+ elif compressed is not None:
+ sibling_bytes = _quantized_sibling_bytes(
+ model,
+ need,
+ _compressed_scheme_weight_bits(compressed[0]),
+ # Everything the recipe refuses to quantize is copied across at
+ # 16 bits: the vision tower, linear attention, MTP, MoE gates.
+ _compressed_ignore_patterns(model),
+ )
+ sibling_suffix = compressed[2]
+ need += sibling_bytes
+ # The reserve raises the ask for the merge alone, and the rest is added
+ # at face value. `max` rather than a sum of the two halves: the sibling
+ # coexists with the merge, so the peak is the whole estimate, and it
+ # must also clear the merge's own reserved figure.
+ need = max(need, math.ceil(merge_here / _MERGE_FREE_SPACE_RESERVE))
+ new_directory, message = kaggle_tmp_redirect(
+ save_directory,
+ need_bytes = need,
+ what = "model checkpoint" if (full_model_lora or verbatim) else "16-bit merge",
+ )
+ except Exception:
+ return save_directory
+ if message is not None:
+ if not _destination_holds_torchao_staging(new_directory, need, staging):
+ _warn_if_a_cancelled_redirect_leaves_no_room(save_directory, need)
+ _warn_if_torchao_staging_filesystem_is_short(save_directory, staging)
+ _warn_if_sibling_filesystem_is_short(save_directory, sibling_suffix, sibling_bytes)
+ return save_directory
+ print(message)
+ _warn_if_torchao_staging_filesystem_is_short(new_directory, staging)
+ _warn_if_sibling_filesystem_is_short(new_directory, sibling_suffix, sibling_bytes)
+ return new_directory
+ _warn_if_torchao_staging_filesystem_is_short(save_directory, staging)
+ _warn_if_sibling_filesystem_is_short(save_directory, sibling_suffix, sibling_bytes)
+ return save_directory
+
+
+def _normalize_quantization_methods(quantization_method):
+ """The list of GGUF types an export will actually write.
+
+ Mirrors the normalisation `save_to_gguf` does, but cheaply and without
+ validating, because this only feeds a size estimate: an unrecognised name
+ is sized as q8_0 rather than rejected here, and the real validation still
+ happens later where it always did.
+ """
+ if quantization_method is None:
+ return []
+ if isinstance(quantization_method, str):
+ methods = [quantization_method]
+ elif isinstance(quantization_method, (list, tuple)):
+ methods = list(quantization_method)
+ else:
+ return []
+ out = []
+ for method in methods:
+ if method is None:
+ method = "q8_0"
+ method = str(method).lower()
+ if method == "not_quantized":
+ method = "f16"
+ elif method == "fast_quantized":
+ method = "q8_0"
+ elif method == "quantized":
+ method = "q4_k_m"
+ out.append(method)
+ return out
+
+
+def _imatrix_is_enabled(imatrix_file):
+ """Whether an imatrix will really be applied, as `_resolve_imatrix_file` reads it.
+
+ None and False both disable it. The preflight has to agree: an imatrix
+ forces the two-pass route, so reading False as "enabled" sizes an
+ intermediate GGUF that a direct-convertible export never writes, and can
+ refuse an export that fits.
+ """
+ return imatrix_file is not None and imatrix_file is not False
+
+
+def _gguf_writes_16bit_checkpoint(model):
+ """Whether a GGUF export writes a full 16-bit checkpoint before converting.
+
+ A PEFT model is merged into one. A non-PEFT model reuses an existing
+ checkpoint when `_name_or_path` names a directory, and otherwise falls
+ back to `save_pretrained`, which writes the same two bytes per parameter
+ the merge would have. Sizing that fallback at zero is what lets an export
+ pass the preflight and then fill the disk with the checkpoint.
+
+ A module-level helper rather than a local, because the caller snapshots
+ `locals()` into the kwargs of `unsloth_generic_save`.
+ """
+ if isinstance(model, (PeftModel, PeftModelForCausalLM)):
+ return True
+ name_or_path = getattr(getattr(model, "config", None), "_name_or_path", None)
+ try:
+ return not (name_or_path and os.path.isdir(str(name_or_path)))
+ except Exception:
+ return True
+
+
+def _fallback_checkpoint_extra_bytes(model):
+ """Bytes the non-PEFT fallback checkpoint costs ON TOP of the 16-bit estimate.
+
+ `estimate_gguf_export_bytes` budgets two bytes per logical parameter for
+ the checkpoint, which is what a LoRA merge writes. The non-PEFT fallback
+ calls `self.save_pretrained` with no cast, so a model loaded with
+ `dtype = torch.float32` (a supported load) writes four and can fill a disk
+ the preflight called big enough.
+
+ Measured from the parameters' real storage, so a mixed-dtype model is not
+ priced off its largest tensor, and clamped at zero: this can only ever ask
+ for more room, never less, and an unmeasurable model adds nothing.
+ """
+ if isinstance(model, (PeftModel, PeftModelForCausalLM)):
+ return 0
+ if not _gguf_writes_16bit_checkpoint(model):
+ return 0
+ try:
+ actual = 0
+ for parameter in model.parameters():
+ actual += parameter.numel() * parameter.element_size()
+ return max(0, actual - model_16bit_bytes(model))
+ except Exception:
+ return 0
+
+
+def _gguf_output_directory(save_directory):
+ """Where the GGUF files land: a SIBLING of `save_directory`, not a child.
+
+ One definition for the preflight and for the export itself, so the disk
+ that gets measured cannot drift from the disk that gets written.
+ """
+ return f"{save_directory}_gguf"
+
+
+def _filesystem_id(path):
+ """Device id of the filesystem `free_bytes(path)` would measure, or None.
+
+ Mirrors `free_bytes`: lexical `abspath`, so a symlinked directory keeps
+ its own name, then the nearest existing ancestor, because the GGUF
+ sibling does not exist yet. `os.stat` follows symlinks, so this is the
+ device `shutil.disk_usage` reports for the very same path. Windows fills
+ `st_dev` from the volume serial number; a zero is the platform declining
+ to answer and counts as unmeasurable.
+ """
+ try:
+ probe = os.path.abspath(os.path.expanduser(str(path)))
+ while probe and not os.path.exists(probe):
+ parent = os.path.dirname(probe)
+ if parent == probe:
+ break
+ probe = parent
+ return os.stat(probe).st_dev or None
+ except Exception:
+ return None
+
+
+def _on_separate_filesystems(directory, sibling):
+ """True only when both paths are identified AND on different filesystems.
+
+ Unmeasurable is False rather than a guess, so a path nothing can identify
+ leaves the caller charging one filesystem for the whole export, which is
+ what it did before this existed. Device ids and not "the sibling reports
+ less free space": two `disk_usage` calls on ONE filesystem can disagree
+ when something else writes between them, and reading that as two
+ filesystems would charge a single-filesystem export the larger of the two
+ halves instead of their sum.
+
+ Separate from `_same_filesystem`, which resolves paths the same way but
+ answers a different question for the torchao redirect: it raises when a
+ path cannot be identified, because its callers want that to cancel the
+ probe rather than to charge one filesystem for both halves.
+ """
+ left = _filesystem_id(directory)
+ right = _filesystem_id(sibling)
+ if left is None or right is None:
+ return False
+ return left != right
+
+
+def _shares_filesystem(directory, sibling):
+ """True only when both paths are identified AND on the same filesystem.
+
+ Not `not _on_separate_filesystems(...)`: that reads an unidentifiable path
+ as "together", which is right where the answer removes a charge and wrong
+ where it adds one. This is the predicate for the adding case, so it says
+ no to anything it cannot see, and neither predicate ever guesses.
+ """
+ left = _filesystem_id(directory)
+ right = _filesystem_id(sibling)
+ if left is None or right is None:
+ return False
+ return left == right
+
+
+def _directory_is_writable(directory):
+ """Can a file be created here? The same probe `convert_to_gguf` makes.
+
+ `tempfile.mkstemp` is exclusive, so it never truncates an existing file
+ and never follows a symlink. Anything that goes wrong reads as "no".
+ """
+ import tempfile
+ try:
+ handle, probe = tempfile.mkstemp(prefix = ".unsloth_write_test_", dir = directory)
+ os.close(handle)
+ os.remove(probe)
+ return True
+ except Exception:
+ return False
+
+
+def _gguf_conversion_directory(model_directory):
+ """Where the intermediate GGUF is written, before it is moved.
+
+ `unsloth_zoo.llama_cpp.convert_to_gguf` passes a BARE filename as
+ `--outfile`, so llama.cpp resolves it against the process CWD; the only
+ fallback to the input folder fires when that CWD cannot be written to.
+ `save_to_gguf` then `shutil.move`s the finished file into the `_gguf`
+ directory, which is a copy and not a rename when the two sit on different
+ filesystems.
+
+ So on a Kaggle kernel the intermediate - two bytes per parameter, the
+ largest single staging artefact - still lands in the 20GB /kaggle/working
+ even after the export has been redirected to /tmp, and that is the one
+ filesystem the rest of this preflight never measures.
+
+ None when the CWD cannot be read, and then nothing is charged.
+ """
+ try:
+ cwd = os.getcwd()
+ except Exception:
+ return None
+ return cwd if _directory_is_writable(cwd) else model_directory
+
+
+def _gguf_model_input_directory(model, save_directory):
+ """The folder the converter reads, which is not always `save_directory`.
+
+ A non-PEFT model whose `_name_or_path` names a directory is converted from
+ that checkpoint: `unsloth_save_pretrained_gguf` reassigns `save_directory`
+ to it before calling `save_to_gguf`, so it is that path which arrives as
+ `convert_to_gguf`'s `input_folder`. The same condition
+ `_gguf_writes_16bit_checkpoint` uses to decide no merge is written.
+
+ It matters only where the input folder is also written to, which is the
+ unwritable-CWD fallback: the intermediate GGUF then lands beside the
+ reused checkpoint rather than beside the requested output, and those two
+ can be on different filesystems.
+ """
+ if isinstance(model, (PeftModel, PeftModelForCausalLM)):
+ return save_directory
+ name_or_path = getattr(getattr(model, "config", None), "_name_or_path", None)
+ try:
+ if name_or_path and os.path.isdir(str(name_or_path)):
+ return str(name_or_path)
+ except Exception:
+ pass
+ return save_directory
+
+
+def _merge_reclamation_is_possible(save_directory):
+ """Will `_free_merge_if_disk_is_tight` have a merge to reclaim?
+
+ It never touches a file that was in `save_directory` before the export
+ started, because that file is the caller's, not this export's. A directory
+ already holding a checkpoint under the names a merge writes therefore
+ yields nothing, and sizing that export as though the merge would go would
+ pass one that really does peak at all three artefacts.
+
+ A directory that does not exist yet is entirely this export's own, so
+ True. One that cannot be listed is False, which is what the reclamation
+ itself does with unreadable provenance.
+ """
+ try:
+ names = os.listdir(save_directory)
+ except FileNotFoundError:
+ return True
+ except Exception:
+ return False
+ try:
+ return not _merge_weight_files(save_directory, names)
+ except Exception:
+ return False
+
+
+def _hub_cache_directory():
+ """Where `_prewarm_base_model_hub_cache` downloads the base model.
+
+ Resolved from the live environment exactly as the pre-warm does, and not
+ from huggingface_hub's frozen constants, so a runtime cache redirect is
+ followed here too. Falls back to the constant, then to None, and None
+ leaves every caller charging the cache where it charged it before.
+ """
+ try:
+ from unsloth_zoo.hf_cache import _active_caches
+ cache = _active_caches()[1]
+ if cache is not None:
+ return str(cache)
+ except Exception:
+ pass
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ return str(HF_HUB_CACHE) or None
+ except Exception:
+ return None
+
+
+def _gguf_source_dtype(model):
+ """The initial-conversion dtype `save_to_gguf` will derive from the model.
+
+ `estimate_gguf_export_bytes` omits a requested output that EQUALS the
+ initial conversion, because that file is already on disk and gets no
+ quantize pass. So the preflight has to name the same dtype the export
+ will: told "f16" for a bf16 model asked for `["f16", "q4_k_m"]`, it charges
+ the f16 file as the intermediate and nothing else, while `save_to_gguf`
+ writes a bf16 intermediate AND a separate f16 output. That is one whole
+ checkpoint unaccounted for (15.3GB on Qwen3-8B).
+
+ Mirrors `save_to_gguf` step for step: `dtype_from_config`, mapped to the
+ f16 / bf16 names it uses, then the same drop to f16 on hardware with no
+ bf16. Returns "f16" whenever anything cannot be read, which is the same
+ fallback the exporter prints and takes.
+ """
+ try:
+ model_dtype = dtype_from_config(model.config)
+ if type(model_dtype) is str:
+ dtype = "bf16" if model_dtype == "bfloat16" else "f16"
+ elif model_dtype == torch.bfloat16:
+ dtype = "bf16"
+ else:
+ dtype = "f16"
+ except Exception:
+ return "f16"
+ if dtype == "bf16":
+ try:
+ if not torch.cuda.is_bf16_supported():
+ return "f16"
+ except Exception:
+ # `save_to_gguf` calls this unguarded, so a raise here means no
+ # export happens at all and the figure never gets used. "f16" is
+ # the same width either way; only the name has to match.
+ return "f16"
+ return dtype
+
+
+def _preflight_gguf_disk(
+ model,
+ save_directory,
+ quantization_method,
+ first_conversion = None,
+ model_dtype = "f16",
+ has_imatrix = False,
+ needs_merge = True,
+ merge_is_disposable = False,
+):
+ """Refuse a GGUF export that cannot fit, before it writes a single byte.
+
+ Returns `(directory, prewarm_ok)`. `directory` differs from the input
+ only when a Kaggle kernel's tiny working directory was swapped for the
+ large /tmp overlay (and then it says so, once). `prewarm_ok` is False when
+ the export fits only if the Hugging Face cache is not pre-warmed with the
+ base model first.
+
+ A GGUF export peaks at more than "the model, twice". It caches the
+ full-precision base, writes the 16-bit HF merge, then an intermediate
+ GGUF at the source dtype, then each requested quant, and every earlier
+ artefact is still on disk while the next is written. Gemma4 (26B A4B)
+ Vision, Gemma4 (31B) Vision and Qwen3 32B each trained, ran inference and
+ completed `merged_16bit` before dying partway through a GGUF shard,
+ because the check in front of them had sized the job at two copies.
+
+ Dropping the pre-warm is tried before refusing, because it is a pure
+ optimization for the NEXT export - the merge downloads what it needs
+ either way - and an export that runs is worth more than a cache.
+
+ `merge_is_disposable` says the merge is this export's own throwaway, so
+ `_free_merge_if_disk_is_tight` may delete it once the intermediate GGUF
+ exists. Then the three artefacts never coexist and the peak is the larger
+ of the two phases, not their sum. Defaults off: charging the aggregate is
+ what every caller got before this argument existed.
+
+ Never blocks on a guess: an unmeasurable model or an unmeasurable disk
+ returns the directory untouched. Set UNSLOTH_DISK_PREFLIGHT=0 to disable.
+ """
+ if os.environ.get("UNSLOTH_DISK_PREFLIGHT", "1").strip().lower() in (
+ "0",
+ "false",
+ "no",
+ "off",
+ ):
+ return save_directory, True
+
+ try:
+ methods = _normalize_quantization_methods(quantization_method)
+ if first_conversion is None or not isinstance(first_conversion, str):
+ first_conversion = _choose_first_conversion(
+ methods, model_dtype, has_imatrix = has_imatrix
+ )
+ # `save_to_gguf` drops a bf16 initial conversion to f16 on hardware
+ # with no bf16, AFTER it has resolved one, so the drop has to be
+ # applied after both branches above and not only inside the resolver.
+ # `_gguf_source_dtype` covers the dtype this is TOLD; it cannot cover
+ # a `first_conversion` the caller passed, nor the single direct-convert
+ # method `_choose_first_conversion` returns unchanged.
+ #
+ # It is the requested-output rule that makes this cost a checkpoint:
+ # the estimate omits an output EQUAL to the initial conversion, so
+ # `["bf16"]` at first_conversion "bf16" is priced as one 16-bit file,
+ # while a T4 writes an f16 intermediate AND a separate bf16 output.
+ # 15.3GB unaccounted for on Qwen3-8B, the same figure and the same
+ # mechanism as the dtype case.
+ if first_conversion == "bf16":
+ try:
+ if not torch.cuda.is_bf16_supported():
+ first_conversion = "f16"
+ except Exception:
+ # `save_to_gguf` asks unguarded, so a raise here means no
+ # export runs and this figure is never used. f16 is the wider
+ # of the two readings, and never the narrower.
+ first_conversion = "f16"
+ need = estimate_gguf_export_bytes(
+ model = model,
+ quantization_methods = methods,
+ first_conversion = first_conversion,
+ needs_merge = needs_merge,
+ )
+ # The pre-warm only happens on the merge path, and only when it has
+ # not already been switched off. Kaggle and Colab return before it
+ # ever runs (`_prewarm_base_model_hub_cache`), so pricing a cache copy
+ # there would send an export that fits in /kaggle/working to /tmp,
+ # which is not kept as notebook output.
+ prewarm_possible = (
+ needs_merge
+ and not IS_KAGGLE_ENVIRONMENT
+ and not IS_COLAB_ENVIRONMENT
+ and os.environ.get("UNSLOTH_PREWARM_HUB_CACHE", "1").strip().lower()
+ not in ("0", "false", "no", "off")
+ )
+ need_with_cache = (
+ estimate_gguf_export_bytes(
+ model = model,
+ quantization_methods = methods,
+ first_conversion = first_conversion,
+ needs_merge = needs_merge,
+ base_cache_copy = True,
+ )
+ if prewarm_possible
+ else need
+ )
+ # The estimate prices the checkpoint at two bytes per parameter. The
+ # non-PEFT fallback writes it at the model's own dtype, so an fp32
+ # model needs the difference on top. Zero for every 16-bit model.
+ if need > 0 and needs_merge:
+ extra = _fallback_checkpoint_extra_bytes(model)
+ need += extra
+ need_with_cache += extra
+ # The same estimate without the checkpoint: what lands in the `_gguf`
+ # sibling directory, which is the intermediate conversion plus every
+ # quant. Only used when that sibling turns out to be on a different,
+ # smaller filesystem than `save_directory`. Its own try, so an
+ # estimator that cannot answer this leaves the main guard standing
+ # rather than turning the whole preflight off.
+ try:
+ need_sibling = estimate_gguf_export_bytes(
+ model = model,
+ quantization_methods = methods,
+ first_conversion = first_conversion,
+ needs_merge = False,
+ )
+ except Exception:
+ need_sibling = 0
+ # The first of the two phases a disposable merge really peaks at: the
+ # merge and the intermediate GGUF on disk together, before any quant
+ # is written. `quantization_methods = ()` still prices the
+ # intermediate, which is what the conversion has to write before it
+ # can be read. Its own try for the same reason as the sibling: an
+ # estimator that cannot answer leaves the aggregate standing.
+ try:
+ need_merge_phase = estimate_gguf_export_bytes(
+ model = model,
+ quantization_methods = (),
+ first_conversion = first_conversion,
+ needs_merge = needs_merge,
+ ) + (extra if need > 0 and needs_merge else 0)
+ except Exception:
+ need_merge_phase = 0
+ # Reclamation only helps when a quantize pass actually follows it, and
+ # `save_to_gguf` skips a method equal to the initial conversion because
+ # that file is already on disk. Same rule, same list.
+ has_quantize_pass = bool([m for m in dict.fromkeys(methods) if m != first_conversion])
+ # The intermediate conversion on its own, for the filesystem it is
+ # written to before the move. Same shape of `try` as the two above.
+ try:
+ need_conversion = estimate_gguf_export_bytes(
+ model = model,
+ quantization_methods = (),
+ first_conversion = first_conversion,
+ needs_merge = False,
+ )
+ except Exception:
+ need_conversion = 0
+ except Exception:
+ # Sizing is best effort. A failure here must not stop an export that
+ # would otherwise have worked.
+ return save_directory, True
+ if need <= 0:
+ return save_directory, True
+
+ # The redirect has to be asked for the same figure the refusal below reads.
+ # `need_with_cache` is the aggregate, and a disposable merge is reclaimed
+ # before the quants are written, so an export whose phased peak fits in
+ # /kaggle/working was relocated to a /tmp Kaggle does not keep as notebook
+ # output. Same predicates as the branch that lowers `need_here`, read
+ # against the directory as it stands BEFORE any move, and it can only ever
+ # lower the ask: nothing that used to stay put is relocated now.
+ phased_need = 0
+ if (
+ merge_is_disposable
+ and needs_merge
+ and has_quantize_pass
+ and need_merge_phase > 0
+ and need_sibling > 0
+ and not _on_separate_filesystems(save_directory, _gguf_output_directory(save_directory))
+ ):
+ redirect_peak = max(need_merge_phase, need_sibling)
+ if redirect_peak < need:
+ phased_need = redirect_peak + max(0, need_with_cache - need)
+
+ redirect_need = need_with_cache
+ if phased_need > 0 and _merge_reclamation_is_possible(save_directory):
+ redirect_need = phased_need
+
+ new_directory, message = kaggle_tmp_redirect(
+ save_directory,
+ need_bytes = redirect_need,
+ what = "GGUF export",
+ )
+ # Asked the aggregate because THIS directory already holds weights the
+ # reclamation may not touch, and declined. The relocation writes the merge
+ # into a directory of the export's own, where it can be reclaimed, so the
+ # move is worth a second ask at the phased peak: 63GB merge, 60GB
+ # intermediate, 18GB Q4_K_M asks 141GB, a 130GB /tmp declines it, and the
+ # 123GB peak it would really have peaked at there fits.
+ #
+ # Gated on this directory already being too small for the aggregate the
+ # refusal below will read, which is what makes the lower ask safe. A lower
+ # ask can otherwise CANCEL a move: /kaggle/working with room for the peak
+ # but not the aggregate keeps an export that has no reclamation here, and
+ # then the refusal reads the aggregate anyway.
+ if message is None and 0 < phased_need < redirect_need:
+ free_before_move = free_bytes(save_directory)
+ if free_before_move is not None and free_before_move < need:
+ new_directory, message = kaggle_tmp_redirect(
+ save_directory,
+ need_bytes = phased_need,
+ what = "GGUF export",
+ )
+ if message is not None:
+ print(message)
+ save_directory = new_directory
+
+ free = free_bytes(save_directory)
+
+ # The quants and the intermediate GGUF are written to a SIBLING of
+ # `save_directory`, so they live on the parent's filesystem. That is the
+ # same disk `free` just measured unless `save_directory` is itself a mount
+ # point or a symlink onto another one. When it is, each filesystem is
+ # charged only for what is written to it: the checkpoint here, the
+ # conversion and the quants there. Charging the aggregate to either one
+ # refuses a split export whose every artefact has room.
+ #
+ # One predicate, computed once, so the two halves cannot disagree about
+ # whether the storage is split, and an unmeasurable path leaves every
+ # decision below exactly as it was.
+ gguf_directory = _gguf_output_directory(save_directory)
+ gguf_free = free_bytes(gguf_directory)
+ separate_storage = (
+ free is not None
+ and gguf_free is not None
+ and _on_separate_filesystems(save_directory, gguf_directory)
+ )
+ # Resolved before the split is priced, because where the conversion lands
+ # decides which filesystem it is charged to.
+ conversion_directory = _gguf_conversion_directory(
+ _gguf_model_input_directory(model, save_directory)
+ )
+
+ # Cleared where the base-model cache turns out to share a filesystem that
+ # has room for what the export writes there but not for a cached base as
+ # well: dropping the optional half beats failing the export. The message
+ # travels with the flag because more than one filesystem can now set it,
+ # and each has to name the one it measured.
+ sibling_prewarm_ok = True
+ prewarm_drop_message = None
+ # Resolved once, above the split, because the cache is not necessarily on
+ # either of the two filesystems the split is about: the conversion's own
+ # filesystem below asks the same question of the same path. Zero whenever
+ # the pre-warm cannot run, which is what leaves every branch below inert.
+ cache_extra = max(0, need_with_cache - need)
+ cache_directory = _hub_cache_directory() if cache_extra > 0 else None
+ # The cache copy lands wherever the cache is, which is not necessarily the
+ # filesystem holding `save_directory` - `HF_HOME` on a data volume is the
+ # ordinary layout on a machine with more than one disk. Charging it here
+ # anyway drops the pre-warm on a disk that had room for everything written
+ # to it, and the next export downloads the whole base again, which is the
+ # exact re-download the pre-warm exists to stop. It only ever LOWERS the
+ # figure, and only the pre-warm decision reads it, so no export that fit
+ # before is refused now. Unresolvable leaves it charged here, where it was
+ # charged before. The split branch asks the same of the sibling below.
+ cache_here = cache_extra
+ if (
+ cache_extra > 0
+ and cache_directory is not None
+ and _on_separate_filesystems(cache_directory, save_directory)
+ ):
+ cache_here = 0
+ need_here = need
+ need_here_with_cache = need + cache_here
+ if separate_storage:
+ # `need_sibling` is the same estimate without the checkpoint, so the
+ # difference is the checkpoint and nothing else. An estimator that
+ # could not size the sibling leaves it 0, and then this is `need`:
+ # the previous behaviour, not a relaxed one.
+ #
+ # Nothing else, though, includes the slack: both terms carry the
+ # estimator's flat `DISK_SLACK_BYTES` and the subtraction cancels it,
+ # leaving two bytes per parameter exactly. `merge_and_overwrite_lora`
+ # refuses that merge unless `free * 0.95` covers it, so the same
+ # reserve `_preflight_merge_disk` already applies has to be applied
+ # here too, or this passes an export the merge kills seconds later.
+ # The aggregate branch needs no such thing: it charges the quants as
+ # well, which is already more than the checkpoint plus its reserve.
+ checkpoint_here = max(0, need - need_sibling)
+ need_here = checkpoint_here
+ # The cache copy is not part of the merge and is not what the zoo
+ # guard measures, so it rides on top of the checkpoint rather than
+ # being reserved itself.
+ #
+ # It also does not necessarily land HERE. `save_directory` being a
+ # mount onto another disk is the whole premise of this branch, and
+ # then `~/.cache` and the lexical `_gguf` sibling both stay on the
+ # parent disk. Charging the checkpoint's filesystem for bytes written
+ # to the sibling's drops a pre-warm that had room and, worse, lets the
+ # sibling check accept `need_sibling` alone on a filesystem the base
+ # model is about to be downloaded onto. `cache_here` above has already
+ # answered the first half; the sibling is the half only this branch has.
+ cache_sibling = 0
+ if (
+ cache_extra > 0
+ and cache_here == 0
+ and _shares_filesystem(cache_directory, gguf_directory)
+ ):
+ cache_sibling = cache_extra
+ need_here_with_cache = checkpoint_here + cache_here
+ writes_a_lora_merge = isinstance(model, (PeftModel, PeftModelForCausalLM))
+ if writes_a_lora_merge and needs_merge and need_sibling > 0 and checkpoint_here > 0:
+ # Four conditions, each removing a way to charge for a guard that
+ # will not run. Only a PEFT model reaches `merge_and_overwrite_lora`
+ # and its `free * 0.95`: a non-PEFT model with no reusable local
+ # checkpoint still needs `needs_merge`, because the GGUF path has
+ # to write one, but it is written by a bare `self.save_pretrained`
+ # that reserves nothing, so charging the reserve there refuses a
+ # filesystem with room for the checkpoint the writer would have
+ # accepted. `needs_merge = False` writes no merge at all. A sibling
+ # the estimator could not size leaves `checkpoint_here` equal to
+ # the aggregate, which is a fallback figure and not a checkpoint
+ # to reserve against. And `min(need, ...)` keeps the promise the
+ # split made when it was introduced: it may cancel a redirect,
+ # never cause a refusal the aggregate would have allowed.
+ reserved = min(need, math.ceil(checkpoint_here / _MERGE_FREE_SPACE_RESERVE))
+ need_here = max(need_here, reserved)
+ # The cache copy is written BEFORE the merge and is still there when
+ # the guard runs, so it comes off the free space the guard measures.
+ # It rides on top of the reserved figure rather than beside it: a
+ # 16GB checkpoint with a 14GB cache on 30.5GB free passes a `max`
+ # asking 30GB, and then the merge sees 16.5GB and refuses 16GB under
+ # its own 5%. Added instead, this band drops the pre-warm, which is
+ # the optional half, rather than failing the export.
+ need_here_with_cache = max(need_here_with_cache, reserved + cache_here)
+ # The intermediate conversion is written to the working directory and
+ # only moved to the sibling afterwards, so when that working directory
+ # is on THIS filesystem the checkpoint and the conversion are on it
+ # together. Charging each of them alone lets a 60GB checkpoint and a
+ # 60GB conversion both pass on 100GB, and then it fills. Only the
+ # split branch needs this: on one filesystem the aggregate already
+ # counts them both, and a conversion sharing the sibling's disk is
+ # counted in `need_sibling`.
+ #
+ # `max` and not `+`, because the two figures are two PHASES and not two
+ # artefacts. The merge runs first and its guard wants the checkpoint
+ # over 0.95 with nothing else written yet; the conversion is written
+ # after, against the unreserved checkpoint. Summing them charges the
+ # reserve on top of a conversion that does not exist while the guard
+ # runs: a 60GB merge and a 60GB conversion on 122GB free clear both
+ # phases (63.2GB, then 120GB) and the sum asks 123.2GB and refuses.
+ if (
+ need_conversion > 0
+ and conversion_directory is not None
+ and _shares_filesystem(conversion_directory, save_directory)
+ ):
+ need_here = max(need_here, checkpoint_here + need_conversion)
+ need_here_with_cache = max(
+ need_here_with_cache, checkpoint_here + need_conversion + cache_here
+ )
+ # Not gated on the sibling being the TIGHTER of the two any more.
+ # Now that the checkpoint is charged only its own portion, a sibling
+ # with more free space than `save_directory` and still less than
+ # `need_sibling` has to be refused here, because the aggregate
+ # comparison that used to catch it no longer exists.
+ if gguf_free < need_sibling:
+ raise RuntimeError(
+ f"Unsloth: Not enough disk space to convert to GGUF.\n"
+ f"The GGUF files are written to `{gguf_directory}`, which is on a different "
+ f"filesystem from `{save_directory}` and has {gguf_free / 1024**3:.1f}GB free; "
+ f"the intermediate `{first_conversion}` conversion and the quants need about "
+ f"{need_sibling / 1024**3:.1f}GB there.\n"
+ f"Options: free space on that filesystem, export fewer quantization methods, or "
+ f"point `save_directory` at a path whose parent directory has the room.\n"
+ f"To skip this check set the environment variable UNSLOTH_DISK_PREFLIGHT=0."
+ )
+ if cache_sibling > 0 and gguf_free < need_sibling + cache_sibling:
+ sibling_prewarm_ok = False
+ prewarm_drop_message = (
+ f"Unsloth: Skipping the Hugging Face cache pre-warm - the Hugging Face "
+ f"cache is on the same filesystem as `{gguf_directory}`, which has "
+ f"{gguf_free / 1024**3:.1f}GB free: enough for the GGUF files "
+ f"(~{need_sibling / 1024**3:.1f}GB) but not for a cached copy of the base "
+ f"model as well. The next export will download the base again."
+ )
+ elif (
+ merge_is_disposable
+ and needs_merge
+ and has_quantize_pass
+ and need_merge_phase > 0
+ and need_sibling > 0
+ and _merge_reclamation_is_possible(save_directory)
+ ):
+ # `_free_merge_if_disk_is_tight` deletes this export's own merge once
+ # the intermediate GGUF exists and before the first quantize pass, so
+ # the three artefacts never coexist: the peak is the larger of "merge
+ # plus intermediate" and "intermediate plus every quant", not their
+ # sum. Nemotron-3-Nano-30B-A3B is the case in front of it - 63GB merge,
+ # 60GB BF16 intermediate, 18GB Q4_K_M - which peaks at 123GB on a 132GB
+ # disk and which the aggregate 141GB refuses.
+ #
+ # Only in the single-filesystem branch, because the reclamation itself
+ # declines when the merge and the GGUF output are on different devices:
+ # freeing bytes on one filesystem does nothing for a quantize pass
+ # writing to another.
+ peak = max(need_merge_phase, need_sibling)
+ if peak < need:
+ # Can only ever lower the figure, so no input that head allowed is
+ # refused here. The cache copy is not what gets reclaimed, so it
+ # rides on top of the peak exactly as it rode on top of the sum.
+ need_here = peak
+ need_here_with_cache = peak + cache_here
+
+ # The intermediate conversion is written to the process CWD, not into
+ # `save_directory` and not into the `_gguf` sibling, and only afterwards
+ # moved. When that CWD is on its own filesystem, nothing above has measured
+ # the disk the largest staging artefact actually lands on: on Kaggle it is
+ # the 20GB working directory the redirect just moved the export away from.
+ if (
+ need_conversion > 0
+ and conversion_directory is not None
+ and _on_separate_filesystems(conversion_directory, gguf_directory)
+ ):
+ conversion_free = free_bytes(conversion_directory)
+ # The pre-warm runs BEFORE the merge and leaves the base model in the
+ # Hugging Face cache for the rest of the export, so when the cache
+ # shares this filesystem the cached base and the intermediate are on
+ # it together. Nothing above has charged that: `cache_here` and
+ # `cache_sibling` only ever place the cache on the checkpoint's
+ # filesystem or the sibling's, and this is neither.
+ #
+ # The pre-warmer's own gate does not cover it either. It asks for two
+ # base copies free on the cache filesystem, and an `f32` conversion is
+ # two base copies on its own: 38.1GB free clears the pre-warm's 30.5GB
+ # threshold and this 30.5GB conversion check, then holds a 15.3GB
+ # cached base while writing 30.5GB, and runs out 7.6GB short.
+ cache_with_conversion = (
+ cache_extra
+ if cache_directory is not None
+ and _shares_filesystem(cache_directory, conversion_directory)
+ else 0
+ )
+ if conversion_free is not None and conversion_free < need_conversion:
+ raise RuntimeError(
+ f"Unsloth: Not enough disk space to convert to GGUF.\n"
+ f"The intermediate `{first_conversion}` conversion is written to the current "
+ f"working directory `{conversion_directory}` before it is moved to "
+ f"`{gguf_directory}`, and that filesystem has "
+ f"{conversion_free / 1024**3:.1f}GB free; the conversion needs about "
+ f"{need_conversion / 1024**3:.1f}GB there.\n"
+ f"Options: free space on that filesystem, or `os.chdir(...)` to a directory "
+ f"on the same filesystem as the export.\n"
+ f"`.push_to_hub_gguf(...)` does not avoid this one: it exports through a "
+ f"temporary directory but never changes the working directory, so the "
+ f"conversion is written here either way.\n"
+ f"To skip this check set the environment variable UNSLOTH_DISK_PREFLIGHT=0."
+ )
+ if (
+ conversion_free is not None
+ and cache_with_conversion > 0
+ and conversion_free < need_conversion + cache_with_conversion
+ ):
+ # Only reached once the conversion alone has cleared the raise
+ # above, so this can never turn a refusal into a pass: it drops
+ # the optional half of an export that otherwise fits.
+ sibling_prewarm_ok = False
+ prewarm_drop_message = (
+ f"Unsloth: Skipping the Hugging Face cache pre-warm - the Hugging Face "
+ f"cache is on the same filesystem as the working directory "
+ f"`{conversion_directory}`, which has "
+ f"{conversion_free / 1024**3:.1f}GB free: enough for the intermediate "
+ f"`{first_conversion}` conversion (~{need_conversion / 1024**3:.1f}GB) but "
+ f"not for a cached copy of the base model as well. The next export will "
+ f"download the base again."
+ )
+
+ if free is None or free >= need_here_with_cache:
+ if not sibling_prewarm_ok and prewarm_possible and prewarm_drop_message:
+ print(prewarm_drop_message)
+ return save_directory, sibling_prewarm_ok
+
+ if free >= need_here:
+ if prewarm_possible:
+ print(
+ f"Unsloth: Skipping the Hugging Face cache pre-warm - "
+ f"{free / 1024**3:.1f}GB free is enough for this GGUF export "
+ f"(~{need_here / 1024**3:.1f}GB) but not for a cached copy of the base "
+ f"model as well. The next export will download the base again."
+ )
+ return save_directory, False
+
+ raise RuntimeError(
+ f"Unsloth: Not enough disk space to convert to GGUF.\n"
+ f"The export needs about {need_here / 1024**3:.1f}GB on the filesystem holding "
+ f"`{save_directory}`, which has {free / 1024**3:.1f}GB free.\n"
+ + (
+ f"Only the 16-bit merge is charged here; the intermediate "
+ f"`{first_conversion}` conversion and the quants go to a sibling directory "
+ f"on another filesystem.\n"
+ if separate_storage
+ else f"It writes a 16-bit merge, then a `{first_conversion}` GGUF, then "
+ f"{', '.join(_normalize_quantization_methods(quantization_method)) or 'no'} "
+ f"quants, and the merge and the intermediate are both still on disk while "
+ f"the quants are written.\n"
+ )
+ + f"Options: free space, export fewer quantization methods, point "
+ f"`save_directory` at a bigger filesystem, or push straight to Hugging Face "
+ f"with `.push_to_hub_gguf(...)`.\n"
+ f"To skip this check set the environment variable UNSLOTH_DISK_PREFLIGHT=0."
+ )
+
+
def _offloaded_parameter_hint(model):
"""Sentence to append when a save failed on offloaded (meta) parameters.
@@ -3141,6 +4640,30 @@ def unsloth_save_pretrained_gguf(
is_processor = is_vlm and isinstance(tokenizer, ProcessorMixin)
is_gpt_oss = _is_gpt_oss(self)
+
+ # Step 1b: Will this fit? Ask before the merge, not after. Runs here rather
+ # than lower down because `arguments` below snapshots locals(), so a
+ # redirected `save_directory` has to be in place first. gpt-oss takes the
+ # mxfp4 route instead of the merge/convert/quantize one this sizes.
+ _gguf_prewarm_ok = True
+ if not is_gpt_oss:
+ save_directory, _gguf_prewarm_ok = _preflight_gguf_disk(
+ model = self,
+ save_directory = save_directory,
+ quantization_method = quantization_method,
+ first_conversion = first_conversion,
+ # Resolved here rather than left at the default, because the
+ # default says "f16" and the export asks the config.
+ model_dtype = _gguf_source_dtype(self),
+ has_imatrix = _imatrix_is_enabled(imatrix_file),
+ needs_merge = _gguf_writes_16bit_checkpoint(self),
+ # The same flag `save_to_gguf` reclaims on. Where a non-PEFT model
+ # reuses its own checkpoint the flag is cleared below, and there
+ # `_gguf_writes_16bit_checkpoint` is already False on the same
+ # condition, so the two cannot disagree.
+ merge_is_disposable = merge_is_disposable,
+ )
+
# Step 2: Prepare arguments for model saving
arguments = dict(locals())
arguments["model"] = self
@@ -3174,10 +4697,13 @@ def unsloth_save_pretrained_gguf(
del arguments["base_model_name"]
del arguments["is_processor"]
del arguments["imatrix_file"] # only used by the gguf quantize step, not the 16bit merge
+ del arguments["_gguf_prewarm_ok"] # a local decision, not a save_pretrained kwarg
del arguments["merge_is_disposable"] # decides reclamation, not how the merge is written
# Preserve the requested output before reusing a non-PEFT checkpoint as input.
- gguf_directory = f"{save_directory}_gguf"
+ # Same definition the preflight sized, so the disk it measured is the one
+ # these files land on.
+ gguf_directory = _gguf_output_directory(save_directory)
# Step 3: Fix tokenizer BOS token if needed
if is_processor:
@@ -3217,7 +4743,8 @@ def unsloth_save_pretrained_gguf(
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)
+ with _hub_cache_prewarm_disabled(not _gguf_prewarm_ok):
+ unsloth_generic_save(**arguments)
except Exception as e:
raise RuntimeError(f"Failed to save/merge model: {e}{_offloaded_parameter_hint(self)}")
@@ -4936,6 +6463,24 @@ def unsloth_generic_save_pretrained_merged(
"You can do it separately via `tokenizer.save_pretrained(...)`"
)
+ # Kaggle's working directory is ~20GB while the overlay at /tmp on the same
+ # kernel is measured in terabytes. Relative paths under /kaggle/working that
+ # do not fit move there; absolute paths, hub pushes and every non-Kaggle
+ # machine are untouched.
+ save_directory = _preflight_merge_disk(
+ self,
+ save_directory,
+ save_method,
+ push_to_hub = push_to_hub,
+ state_dict = state_dict,
+ # `unsloth_generic_save` writes a supplied dictionary rather than the
+ # resident model when there is no adapter to merge.
+ forwards_state_dict = True,
+ # And it is the writer that runs `merge_and_overwrite_lora` when there
+ # IS one, which no other entrypoint here does.
+ writer_runs_merge_guard = True,
+ )
+
# FP8 / FP4 compressed-tensors export (llm-compressor) -> handled separately.
_compressed = _normalize_compressed_method(save_method)
if _compressed is not None:
diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.py
index f1909305077..1bc5fe30138 100644
--- a/unsloth/tokenizer_utils.py
+++ b/unsloth/tokenizer_utils.py
@@ -69,11 +69,17 @@ IGNORED_TOKENIZER_NAMES = frozenset(
os.environ["UNSLOTH_IGNORED_TOKENIZER_NAMES"] = "\n".join(IGNORED_TOKENIZER_NAMES)
# Check environments
-keynames = "\n" + "\n".join(os.environ.keys())
-IS_COLAB_ENVIRONMENT = "\nCOLAB_" in keynames
-IS_KAGGLE_ENVIRONMENT = "\nKAGGLE_" in keynames
-KAGGLE_TMP = "/tmp"
-del keynames
+# A KAGGLE_* variable is not a Kaggle kernel - the Kaggle CLI reads
+# KAGGLE_USERNAME / KAGGLE_KEY from the environment on ordinary machines, and
+# redirecting their tokenizer cache to /tmp because of it was wrong.
+from .disk_utils import (
+ KAGGLE_TMP,
+ is_colab_environment,
+ is_kaggle_environment,
+)
+
+IS_COLAB_ENVIRONMENT = is_colab_environment()
+IS_KAGGLE_ENVIRONMENT = is_kaggle_environment()
def try_fix_tokenizer(tokenizer, prepend = True):