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.

GGUF export: write the intermediate conversion inside the output folder so placing it is a rename (#15783)

Daniel Han9a269643da3a
diff --git a/tests/saving/test_gguf_disk_preflight.py b/tests/saving/test_gguf_disk_preflight.py
index cb8a3870e87..45412816520 100644
--- a/tests/saving/test_gguf_disk_preflight.py
+++ b/tests/saving/test_gguf_disk_preflight.py
@@ -2355,6 +2355,7 @@ class TestTheConversionWorkingDirectoryIsMeasured:
lambda left, right: str(left).startswith("/tmp") != str(right).startswith("/tmp"),
)
monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: state["conversion"])
+ monkeypatch.setattr(S, "_gguf_conversion_is_staged", lambda directory: False)
monkeypatch.delenv("UNSLOTH_DISK_PREFLIGHT", raising = False)
monkeypatch.delenv("UNSLOTH_PREWARM_HUB_CACHE", raising = False)
return state
@@ -2401,6 +2402,16 @@ class TestTheConversionWorkingDirectoryIsMeasured:
monkeypatch.setenv("UNSLOTH_DISK_PREFLIGHT", "0")
assert self._preflight() == ("/kaggle/working/model", True)
+ def test_a_staged_conversion_does_not_charge_the_working_directory(self, kaggle, monkeypatch):
+ """Staged inside the `_gguf` folder, the intermediate never touches /kaggle/working."""
+ seen = []
+ monkeypatch.setattr(
+ S, "_gguf_conversion_is_staged", lambda directory: seen.append(directory) or True
+ )
+ kaggle.update(cwd_free = 1 * GB)
+ assert self._preflight() == (self.TMP, True)
+ assert seen == [f"{self.TMP}_gguf"]
+
class TestWhereTheConversionWrites:
"""`_gguf_conversion_directory` mirrors `convert_to_gguf`'s own rule."""
@@ -2420,6 +2431,26 @@ class TestWhereTheConversionWrites:
monkeypatch.setattr(S.os, "getcwd", boom)
assert S._gguf_conversion_directory("model") is None
+
+class TestTheStagingPrediction:
+ """`_gguf_conversion_is_staged` must agree with `_gguf_conversion_staging`."""
+
+ def test_a_writable_parent_stages(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(S, "IS_WINDOWS", False)
+ target = tmp_path / "a" / "model_gguf"
+ assert S._gguf_conversion_is_staged(str(target))
+ staging, created = S._gguf_conversion_staging(str(target))
+ assert staging is not None and created
+
+ def test_an_unwritable_parent_does_not(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(S, "IS_WINDOWS", False)
+ monkeypatch.setattr(S, "_directory_is_writable", lambda directory: False)
+ assert not S._gguf_conversion_is_staged(str(tmp_path / "model_gguf"))
+
+ def test_windows_keeps_the_working_directory_charge(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(S, "IS_WINDOWS", True)
+ assert not S._gguf_conversion_is_staged(str(tmp_path / "model_gguf"))
+
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
@@ -2455,6 +2486,7 @@ class TestAColocatedConversionIsChargedWithTheCheckpoint:
)
monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ monkeypatch.setattr(S, "_gguf_conversion_is_staged", lambda directory: False)
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)
@@ -2483,6 +2515,7 @@ class TestAColocatedConversionIsChargedWithTheCheckpoint:
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)
+ monkeypatch.setattr(S, "_gguf_conversion_is_staged", lambda directory: False)
assert self._preflight() == ("model", True)
def test_the_predicate_never_guesses(self, monkeypatch):
@@ -2515,6 +2548,7 @@ class TestTheMergeGuardAndTheConversionAreTwoPhases:
)
monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ monkeypatch.setattr(S, "_gguf_conversion_is_staged", lambda directory: False)
monkeypatch.setattr(
S,
"_filesystem_id",
@@ -3035,6 +3069,7 @@ class TestThePrewarmedCacheIsChargedToItsOwnFilesystem:
)
monkeypatch.setattr(S, "kaggle_tmp_redirect", lambda *a, **k: ("model", None))
monkeypatch.setattr(S, "_gguf_conversion_directory", lambda directory: "work")
+ monkeypatch.setattr(S, "_gguf_conversion_is_staged", lambda directory: False)
monkeypatch.setattr(
S, "_filesystem_id", lambda path: devices.get(str(path), state["cache_device"])
)
@@ -3206,6 +3241,7 @@ class TestTheCacheIsChargedOnTheConversionFilesystem:
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, "_gguf_conversion_is_staged", lambda directory: False)
monkeypatch.setattr(S, "_hub_cache_directory", lambda: self.CACHE)
monkeypatch.setattr(S, "IS_KAGGLE_ENVIRONMENT", False)
monkeypatch.setattr(S, "IS_COLAB_ENVIRONMENT", False)
@@ -3306,6 +3342,7 @@ class TestACacheOnAnotherFilesystemIsNotChargedToTheOutputDisk:
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, "_gguf_conversion_is_staged", lambda directory: False)
monkeypatch.setattr(
S, "_filesystem_id", lambda path: devices.get(str(path), state["cache_device"])
)
diff --git a/tests/saving/test_gguf_intermediate_on_destination.py b/tests/saving/test_gguf_intermediate_on_destination.py
new file mode 100644
index 00000000000..972dfca6c0b
--- /dev/null
+++ b/tests/saving/test_gguf_intermediate_on_destination.py
@@ -0,0 +1,283 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""The intermediate GGUF is written on the destination filesystem, so placing it is a rename."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+
+import pytest
+
+save_mod = pytest.importorskip("unsloth.save", reason = "needs torch + unsloth_zoo")
+
+
+class _Converter:
+ """Writes where convert_to_gguf would: a bare name resolves against the CWD."""
+
+ def __init__(self, fail_after_write = False):
+ self.fail_after_write = fail_after_write
+ self.outfiles = []
+
+ def __call__(self, **kwargs):
+ model_name = kwargs["model_name"]
+ qtype = kwargs["quantization_type"]
+ if qtype == "None":
+ qtype = kwargs.get("model_dtype", "bf16")
+ out = model_name if model_name.endswith(".gguf") else f"{model_name}.{qtype.upper()}.gguf"
+ self.outfiles.append(os.path.abspath(out))
+ with open(out, "wb") as handle:
+ handle.write(b"GGUF" + b"\0" * 4096)
+ if self.fail_after_write:
+ raise RuntimeError("converter died mid-write")
+ return [out], False
+
+
+def _wire(monkeypatch, converter, quantized):
+ monkeypatch.setattr(save_mod, "check_llama_cpp", lambda: ("llama-quantize", "convert.py"))
+ monkeypatch.setattr(
+ save_mod,
+ "_download_convert_hf_to_gguf",
+ lambda: ("convert.py", {"LlamaForCausalLM"}, set()),
+ )
+ monkeypatch.setattr(save_mod, "use_local_gguf", contextlib.nullcontext)
+ monkeypatch.setattr(save_mod, "convert_to_gguf", converter)
+
+ def _quantize(input_gguf, output_gguf, quant_type, **kw):
+ quantized.append((input_gguf, output_gguf))
+ with open(output_gguf, "wb") as handle:
+ handle.write(b"GGUF")
+ return output_gguf
+
+ monkeypatch.setattr(save_mod, "quantize_gguf", _quantize)
+
+
+def _copies(monkeypatch):
+ calls = []
+ for name in ("copy2", "copyfile", "copy"):
+ real = getattr(save_mod.shutil, name)
+
+ def _spy(
+ *a,
+ _real = real,
+ _name = name,
+ **kw,
+ ):
+ calls.append(_name)
+ return _real(*a, **kw)
+
+ monkeypatch.setattr(save_mod.shutil, name, _spy)
+ return calls
+
+
+def _layout(tmp_path, monkeypatch):
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+ monkeypatch.chdir(cwd)
+ model_directory = tmp_path / "out" / "model"
+ model_directory.mkdir(parents = True)
+ return cwd, model_directory, str(model_directory) + "_gguf"
+
+
+def _save(model_directory, methods):
+ return save_mod.save_to_gguf(
+ model_name = "MyModel",
+ model_type = "llama",
+ model_dtype = "bfloat16",
+ model_directory = str(model_directory),
+ quantization_method = methods,
+ )
+
+
[email protected]("methods", [["q4_k_m"], ["q4_k_m", "q8_0"], ["bf16"]])
+def test_intermediate_is_written_inside_the_gguf_directory(monkeypatch, tmp_path, methods):
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ converter = _Converter()
+ quantized = []
+ _wire(monkeypatch, converter, quantized)
+ copies = _copies(monkeypatch)
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ files, _, _ = _save(model_directory, methods)
+
+ (outfile,) = converter.outfiles
+ assert os.path.dirname(os.path.dirname(outfile)) == os.path.abspath(gguf_directory)
+ assert sorted(os.listdir(gguf_directory)) == sorted(os.path.basename(f) for f in files)
+ assert os.path.basename(outfile) == "MyModel.BF16.gguf"
+ assert os.listdir(cwd) == []
+ assert copies == []
+ for source, _ in quantized:
+ assert source == os.path.join(gguf_directory, "MyModel.BF16.gguf")
+
+
+def test_a_failed_conversion_leaves_no_partial_file_anywhere(monkeypatch, tmp_path):
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ _wire(monkeypatch, _Converter(fail_after_write = True), [])
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ with pytest.raises(RuntimeError, match = "converter died"):
+ _save(model_directory, ["q4_k_m"])
+
+ assert os.listdir(cwd) == []
+ assert not os.path.exists(gguf_directory)
+
+
+def test_a_failed_conversion_keeps_an_existing_gguf_directory(monkeypatch, tmp_path):
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ os.makedirs(gguf_directory)
+ keep = os.path.join(gguf_directory, "earlier.Q8_0.gguf")
+ with open(keep, "wb") as handle:
+ handle.write(b"GGUF")
+ _wire(monkeypatch, _Converter(fail_after_write = True), [])
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ with pytest.raises(RuntimeError):
+ _save(model_directory, ["q4_k_m"])
+
+ assert os.listdir(gguf_directory) == ["earlier.Q8_0.gguf"]
+ assert os.listdir(cwd) == []
+
+
+def test_an_existing_output_of_the_same_name_is_replaced(monkeypatch, tmp_path):
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ os.makedirs(gguf_directory)
+ stale = os.path.join(gguf_directory, "MyModel.BF16.gguf")
+ with open(stale, "wb") as handle:
+ handle.write(b"stale")
+ _wire(monkeypatch, _Converter(), [])
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ _save(model_directory, ["bf16"])
+
+ with open(stale, "rb") as handle:
+ assert handle.read().startswith(b"GGUF")
+ assert os.listdir(gguf_directory) == ["MyModel.BF16.gguf"]
+
+
+def test_without_a_staging_folder_the_cwd_placement_is_kept(monkeypatch, tmp_path):
+ """An output folder that cannot hold the staging folder falls back to the old CWD write and move."""
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ converter = _Converter()
+ _wire(monkeypatch, converter, [])
+ monkeypatch.setattr(save_mod, "_gguf_conversion_staging", lambda directory: (None, False))
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ _save(model_directory, ["bf16"])
+
+ assert converter.outfiles == [os.path.join(str(cwd), "MyModel.BF16.gguf")]
+ assert os.listdir(gguf_directory) == ["MyModel.BF16.gguf"]
+ assert os.listdir(cwd) == []
+
+
+def test_place_gguf_output_falls_back_to_move_across_filesystems(monkeypatch, tmp_path):
+ src = tmp_path / "a.gguf"
+ src.write_bytes(b"GGUF")
+ dst = tmp_path / "b.gguf"
+
+ def _exdev(*a, **k):
+ raise OSError(18, "Invalid cross-device link")
+
+ moved = []
+ monkeypatch.setattr(save_mod.os, "replace", _exdev)
+ real_move = save_mod.shutil.move
+ monkeypatch.setattr(
+ save_mod.shutil, "move", lambda s, d: (moved.append((s, d)), real_move(s, d))[1]
+ )
+ save_mod._place_gguf_output(str(src), str(dst))
+ assert moved == [(str(src), str(dst))]
+ assert dst.read_bytes() == b"GGUF" and not src.exists()
+
+
+def _deep_layout(tmp_path, monkeypatch, total):
+ """Like `_layout`, with the model folder name padded so its `_gguf` path is `total` characters."""
+ cwd = tmp_path / "cwd"
+ cwd.mkdir()
+ monkeypatch.chdir(cwd)
+ parent = tmp_path / "out"
+ pad = total - len(str(parent / "m")) - len("_gguf")
+ assert pad > 0
+ model_directory = parent / ("m" + "x" * pad)
+ model_directory.mkdir(parents = True)
+ gguf_directory = str(model_directory) + "_gguf"
+ assert len(gguf_directory) == total
+ return cwd, model_directory, gguf_directory
+
+
[email protected]("staged", [True, False])
+def test_windows_path_limit_keeps_the_cwd_placement_near_max_path(monkeypatch, tmp_path, staged):
+ """The staging folder lengthens the intermediate's path; on Windows without long paths a destination near MAX_PATH must keep the old CWD write rather than fail inside the converter."""
+ # 150 leaves room for the staged name; 215 does not (215 + 31 + "/MyModel" + 40 > 259) though the final name still fits.
+ cwd, model_directory, gguf_directory = _deep_layout(
+ tmp_path, monkeypatch, 150 if staged else 215
+ )
+ assert len(os.path.join(gguf_directory, "MyModel.BF16-mmproj-00001-of-00002.gguf")) <= 259
+ converter = _Converter()
+ _wire(monkeypatch, converter, [])
+ monkeypatch.setattr(save_mod, "IS_WINDOWS", True)
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ _save(model_directory, ["bf16"])
+
+ (outfile,) = converter.outfiles
+ if staged:
+ assert os.path.dirname(os.path.dirname(outfile)) == os.path.abspath(gguf_directory)
+ else:
+ assert outfile == os.path.join(str(cwd), "MyModel.BF16.gguf")
+ assert os.listdir(gguf_directory) == ["MyModel.BF16.gguf"]
+ assert os.listdir(cwd) == []
+
+
+def test_projector_and_shards_are_all_placed_and_staging_removed(monkeypatch, tmp_path):
+ """A VLM conversion returns a sharded text model plus an mmproj file; every one lands in the output folder and the staging folder goes."""
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+ written = []
+
+ def _convert(**kwargs):
+ stem = kwargs["model_name"]
+ names = [
+ f"{stem}.BF16-00001-of-00002.gguf",
+ f"{stem}.BF16-00002-of-00002.gguf",
+ f"{stem}.BF16-mmproj.gguf",
+ ]
+ for name in names:
+ with open(name, "wb") as handle:
+ handle.write(b"GGUF")
+ written.extend(os.path.abspath(n) for n in names)
+ return names, True
+
+ _wire(monkeypatch, _convert, [])
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ files, _, _ = save_mod.save_to_gguf(
+ model_name = "MyModel",
+ model_type = "llama",
+ model_dtype = "bfloat16",
+ model_directory = str(model_directory),
+ quantization_method = ["bf16"],
+ is_vlm = True,
+ )
+
+ assert {os.path.dirname(os.path.dirname(f)) for f in written} == {
+ os.path.abspath(gguf_directory)
+ }
+ assert sorted(os.listdir(gguf_directory)) == sorted(os.path.basename(f) for f in written)
+ assert os.listdir(cwd) == []
+
+
+def test_interrupted_conversion_removes_the_staging_folder(monkeypatch, tmp_path):
+ cwd, model_directory, gguf_directory = _layout(tmp_path, monkeypatch)
+
+ def _interrupted(**kwargs):
+ with open(kwargs["model_name"] + ".BF16.gguf", "wb") as handle:
+ handle.write(b"GGUF")
+ raise KeyboardInterrupt
+
+ _wire(monkeypatch, _interrupted, [])
+ monkeypatch.setattr(save_mod.torch.cuda, "is_bf16_supported", lambda *a, **k: True)
+
+ with pytest.raises(KeyboardInterrupt):
+ _save(model_directory, ["q4_k_m"])
+
+ assert not os.path.exists(gguf_directory)
+ assert os.listdir(cwd) == []
diff --git a/tests/test_gguf_windows_export_routing.py b/tests/test_gguf_windows_export_routing.py
index 24425dc13b3..51a756095ce 100644
--- a/tests/test_gguf_windows_export_routing.py
+++ b/tests/test_gguf_windows_export_routing.py
@@ -72,6 +72,12 @@ class _Harness:
monkeypatch.setattr(save_mod, "convert_to_gguf", self._convert)
monkeypatch.setattr(save_mod, "quantize_gguf", self._quantize)
monkeypatch.setattr(save_mod, "os", _OsShim(flavour))
+ # The real staging folder comes from tempfile, which joins with the host os.path; keep it virtual.
+ monkeypatch.setattr(
+ save_mod,
+ "_gguf_conversion_staging",
+ lambda directory: (flavour.join(directory, ".unsloth_gguf_convert_t"), False),
+ )
def _scratch(self, virtual_path: str):
"""Materialise a virtual (possibly Windows) path as one real POSIX file."""
@@ -91,7 +97,9 @@ class _Harness:
final = model_name if model_name.endswith(".gguf") else f"{model_name}.{qtype.upper()}.gguf"
self.initial_names.append(final)
# save.py requires the returned paths to exist; the escape under test is at the quantize join.
- return [str(self._scratch(final))], False
+ real = self._scratch(final)
+ # Under the posixpath shim on a Windows host, a backslash path has no posix basename; "C:/..." still opens.
+ return [real.as_posix() if self.flavour is posixpath else str(real)], False
def _quantize(self, input_gguf, output_gguf, quant_type, **kw):
self.quantize_calls.append(
@@ -157,6 +165,8 @@ def test_derived_stem_keeps_quantized_gguf_inside_gguf_directory(monkeypatch, tm
for call in harness.quantize_calls:
assert ntpath.dirname(call["output"]) == expected_dir, call["output"]
assert not call["output"].startswith("D:"), call["output"]
+ # The intermediate is written on the destination volume, not the process CWD.
+ assert ntpath.dirname(ntpath.dirname(harness.initial_names[0])) == expected_dir
def test_legacy_stem_escaped_to_the_base_model_drive(monkeypatch, tmp_path):
diff --git a/unsloth/save.py b/unsloth/save.py
index 4e369a30010..a895dee57f5 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -2412,6 +2412,121 @@ def _choose_first_conversion(
return model_dtype
+def _convert_into_gguf_directory(
+ model_name,
+ model_directory,
+ model_dtype,
+ first_conversion,
+ first_conversion_dtype,
+ is_vlm,
+ is_gpt_oss,
+ print_output,
+ gguf_directory,
+ conversion_staging,
+):
+ """Convert to GGUF and place the files in `gguf_directory`; without a staging folder the converter writes to the CWD."""
+ print("Unsloth: Preparing converter script...")
+ with use_local_gguf():
+ converter_path, supported_text_archs, supported_vision_archs = (
+ _download_convert_hf_to_gguf()
+ )
+
+ print(f"Unsloth: [1] Converting model into {first_conversion_dtype} GGUF format.")
+ print(f"This might take 3 minutes...")
+
+ initial_files, is_vlm_update = convert_to_gguf(
+ model_name = (
+ model_name
+ if conversion_staging is None
+ else os.path.join(conversion_staging, model_name)
+ ),
+ input_folder = model_directory,
+ model_dtype = model_dtype,
+ quantization_type = first_conversion,
+ converter_location = converter_path,
+ supported_text_archs = supported_text_archs,
+ supported_vision_archs = supported_vision_archs,
+ is_vlm = is_vlm,
+ is_gpt_oss = is_gpt_oss,
+ max_shard_size = "50GB",
+ print_output = print_output,
+ )
+ for file in initial_files:
+ if not os.path.exists(file):
+ # Gated like the outer handler: disk advice is only right when disk is the problem, and a converter with no llama.cpp support fails here with space to spare.
+ if IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk(
+ RuntimeError(f"Conversion produced no output at {file}"),
+ os.path.dirname(file) or None,
+ ):
+ raise RuntimeError(
+ f"Unsloth: Conversion failed for {file}\n"
+ "You are in a Kaggle environment with limited disk space (20GB).\n"
+ "Try saving to /tmp for more space or use a smaller model.\n"
+ "Alternatively, save the 16bit model first, then convert manually."
+ )
+ else:
+ raise RuntimeError(
+ f"Unsloth: Conversion failed for {file}\nPlease check disk space and try again."
+ )
+
+ os.makedirs(gguf_directory, exist_ok = True)
+ moved_files = []
+ for fpath in initial_files:
+ dst = os.path.join(gguf_directory, os.path.basename(fpath))
+ _place_gguf_output(fpath, dst)
+ moved_files.append(dst)
+ return moved_files, is_vlm_update
+
+
+def _gguf_conversion_staging(gguf_directory):
+ """`(staging, created_gguf_directory)`: a hidden folder inside `gguf_directory` for the converter output, so placing it is a rename even when the CWD is on another filesystem, and a failed conversion is one rmtree. `(None, False)` on failure keeps the CWD placement."""
+ import tempfile
+
+ created = False
+ try:
+ if not os.path.isdir(gguf_directory):
+ os.makedirs(gguf_directory, exist_ok = True)
+ created = True
+ return tempfile.mkdtemp(prefix = ".unsloth_gguf_convert_", dir = gguf_directory), created
+ except Exception:
+ if created:
+ _remove_empty_directory(gguf_directory)
+ return None, False
+
+
+# MAX_PATH 260 incl. terminator without LongPathsEnabled; the converter appends at most `.BF16-mmproj-00001-of-00002.gguf` (32 chars).
+_WINDOWS_MAX_PATH_CHARS = 259
+_GGUF_CONVERTER_SUFFIX_CHARS = 40
+
+
+def _staged_conversion_fits_path_limit(staging, model_name):
+ """False on Windows when a converter output inside `staging` could pass MAX_PATH, so a deep destination keeps the CWD placement that worked before."""
+ if not IS_WINDOWS:
+ return True
+ try:
+ staged = os.path.abspath(os.path.join(staging, model_name))
+ except Exception:
+ return False
+ return len(staged) + _GGUF_CONVERTER_SUFFIX_CHARS <= _WINDOWS_MAX_PATH_CHARS
+
+
+def _remove_empty_directory(directory):
+ try:
+ os.rmdir(directory)
+ except OSError:
+ pass
+
+
+def _place_gguf_output(src, dst):
+ """`os.replace` is a rename that also overwrites on Windows; anything it refuses (cross-device, directory at `dst`, held file) falls back to `shutil.move`."""
+ if os.path.abspath(src) == os.path.abspath(dst):
+ return
+ try:
+ os.replace(src, dst)
+ except OSError:
+ shutil.move(src, dst)
+
+
def save_to_gguf(
model_name: str,
model_type: str,
@@ -2538,58 +2653,40 @@ def save_to_gguf(
print_output = print_output,
)
- print("Unsloth: Preparing converter script...")
- with use_local_gguf():
- converter_path, supported_text_archs, supported_vision_archs = (
- _download_convert_hf_to_gguf()
- )
-
- print(f"Unsloth: [1] Converting model into {first_conversion_dtype} GGUF format.")
- print(f"This might take 3 minutes...")
-
- initial_files, is_vlm_update = convert_to_gguf(
+ if gguf_directory is None:
+ gguf_directory = f"{model_directory}_gguf"
+ else:
+ gguf_directory = os.fspath(gguf_directory)
+ conversion_staging, created_gguf_directory = _gguf_conversion_staging(gguf_directory)
+ if conversion_staging is not None and not _staged_conversion_fits_path_limit(
+ conversion_staging, model_name
+ ):
+ shutil.rmtree(conversion_staging, ignore_errors = True)
+ if created_gguf_directory:
+ _remove_empty_directory(gguf_directory)
+ conversion_staging, created_gguf_directory = None, False
+ try:
+ initial_files, is_vlm_update = _convert_into_gguf_directory(
model_name = model_name,
- input_folder = model_directory,
+ model_directory = model_directory,
model_dtype = model_dtype,
- quantization_type = first_conversion,
- converter_location = converter_path,
- supported_text_archs = supported_text_archs,
- supported_vision_archs = supported_vision_archs,
+ first_conversion = first_conversion,
+ first_conversion_dtype = first_conversion_dtype,
is_vlm = is_vlm,
is_gpt_oss = is_gpt_oss,
- max_shard_size = "50GB",
print_output = print_output,
+ gguf_directory = gguf_directory,
+ conversion_staging = conversion_staging,
)
+ except BaseException:
+ if conversion_staging is not None:
+ shutil.rmtree(conversion_staging, ignore_errors = True)
+ if created_gguf_directory:
+ _remove_empty_directory(gguf_directory)
+ raise
+ if conversion_staging is not None:
+ shutil.rmtree(conversion_staging, ignore_errors = True)
is_vlm = is_vlm_update
- for file in initial_files:
- if not os.path.exists(file):
- # Gated like the outer handler: disk advice is only right when disk is the problem, and a converter with no llama.cpp support fails here with space to spare.
- if IS_KAGGLE_ENVIRONMENT and _gguf_failure_looks_like_disk(
- RuntimeError(f"Conversion produced no output at {file}"),
- os.path.dirname(file) or None,
- ):
- raise RuntimeError(
- f"Unsloth: Conversion failed for {file}\n"
- "You are in a Kaggle environment with limited disk space (20GB).\n"
- "Try saving to /tmp for more space or use a smaller model.\n"
- "Alternatively, save the 16bit model first, then convert manually."
- )
- else:
- raise RuntimeError(
- f"Unsloth: Conversion failed for {file}\nPlease check disk space and try again."
- )
-
- if gguf_directory is None:
- gguf_directory = f"{model_directory}_gguf"
- else:
- gguf_directory = os.fspath(gguf_directory)
- os.makedirs(gguf_directory, exist_ok = True)
- moved_files = []
- for fpath in initial_files:
- dst = os.path.join(gguf_directory, os.path.basename(fpath))
- shutil.move(fpath, dst)
- moved_files.append(dst)
- initial_files = moved_files
print(f"Unsloth: Initial conversion completed! Files: {initial_files}")
@@ -4080,7 +4177,7 @@ def _directory_is_writable(directory):
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, falling back to the input folder only when that CWD is unwritable; `save_to_gguf` then `shutil.move`s the file into the `_gguf` directory, which is a copy rather than a rename across filesystems. So on a Kaggle kernel the intermediate, two bytes per parameter and the largest single staging artefact, still lands in the 20GB /kaggle/working even after the export was 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."""
+ """Where an UNSTAGED intermediate GGUF is written: `convert_to_gguf` resolves a bare `--outfile` against the CWD, or the input folder when the CWD is unwritable. None when the CWD cannot be read, and then nothing is charged."""
try:
cwd = os.getcwd()
except Exception:
@@ -4088,6 +4185,22 @@ def _gguf_conversion_directory(model_directory):
return cwd if _directory_is_writable(cwd) else model_directory
+def _gguf_conversion_is_staged(gguf_directory):
+ """Mirrors `_gguf_conversion_staging`: True when the intermediate will be written inside `gguf_directory`, so the CWD is never charged for it. Windows stays False because its MAX_PATH guard can still fall back to the CWD."""
+ if IS_WINDOWS:
+ return False
+ try:
+ probe = os.path.abspath(os.fspath(gguf_directory))
+ while not os.path.isdir(probe):
+ parent = os.path.dirname(probe)
+ if parent == probe:
+ return False
+ probe = parent
+ except Exception:
+ return False
+ return _directory_is_writable(probe)
+
+
def _gguf_model_input_directory(
model,
save_directory,
@@ -4261,7 +4374,7 @@ def _preflight_gguf_disk(
# Ask the redirect for the same figure the refusal reads. need_with_cache is the aggregate, but a disposable merge is reclaimed before the quants, so a phased peak that fits in /kaggle/working was relocated. Read before any move, and it can only lower the ask.
phased_need = 0
- # The intermediate conversion is written to the process CWD, not into `save_directory` and not into the `_gguf` sibling, and only afterwards moved, so 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. When that working directory is on THIS filesystem the checkpoint and the conversion are on it together, and 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, and summing them charges the reserve on top of a conversion that does not exist while the guard runs, so a 60GB merge and a 60GB conversion on 122GB free clear both phases (63.2GB, then 120GB) while the sum asks 123.2GB and refuses.
+ # Single filesystem only: the merge and the conversion are two phases, so the peak is their max, not their sum (a 60GB merge and a 60GB conversion clear 122GB free; the sum asks 123.2GB).
if (
merge_is_disposable
and needs_merge
@@ -4307,9 +4420,12 @@ def _preflight_gguf_disk(
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, state_dict)
- )
+ if _gguf_conversion_is_staged(gguf_directory):
+ conversion_directory = gguf_directory
+ else:
+ conversion_directory = _gguf_conversion_directory(
+ _gguf_model_input_directory(model, save_directory, state_dict)
+ )
# Cleared when the cache shares a filesystem with room for the export but not a cached base too: dropping the optional half beats failing. The message travels with the flag, since more than one filesystem can set it and each has to name the one it measured.
sibling_prewarm_ok = True
@@ -4347,7 +4463,7 @@ def _preflight_gguf_disk(
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 sees. Riding on top of the reserved figure rather than beside it: 16GB checkpoint + 14GB cache on 30.5GB passes a max of 30GB and then the merge refuses under its own 5%. Added instead, this drops the pre-warm, not the export.
need_here_with_cache = max(need_here_with_cache, reserved + cache_here)
- # The intermediate conversion lands in the working directory before the move, so on THIS filesystem the checkpoint and conversion coexist and charging each alone lets 60GB + 60GB pass on 100GB. max, not +: they are two phases, and summing them refuses 122GB free that clears both.
+ # An unstaged intermediate on THIS filesystem coexists with the checkpoint. max, not +: they are two phases, and summing them refuses 122GB free that clears both.
if (
need_conversion > 0
and conversion_directory is not None
@@ -4393,7 +4509,7 @@ def _preflight_gguf_disk(
need_here = peak
need_here_with_cache = peak + cache_here
- # The intermediate conversion is written to the process CWD and only then moved, so when that CWD is its own filesystem nothing above has measured the disk the largest staging artefact lands on: on Kaggle, the 20GB working directory the redirect just left.
+ # An unstaged intermediate is written to the CWD and then moved; on its own filesystem (Kaggle's 20GB working directory after a /tmp redirect) nothing above measured it.
if (
need_conversion > 0
and conversion_directory is not None