Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: only clean up GGUF artifacts the export owns (#7940)
oobaboogae8fcbd68d1fa
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex a14a9a1dff7..a005fb11f7c 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -3,7 +3,6 @@"""Export backend - exports models in various formats."""-import globimport jsonimport structlogimport tempfile@@ -192,6 +191,26 @@ def _reported_gguf_files(result):return resolved or None+def _materialized_imatrix_path(model_dir, imatrix_file):+ """Where unsloth copies a `*.gguf_file` imatrix beside the model, else None.++ `_materialize_imatrix` drops that copy in the model directory, so the owned-root scan+ would otherwise relocate an importance matrix as if it were a converted model. Matching+ the full path, not the basename: an imatrix named after the quant would otherwise+ suppress the real output in `model_gguf/` as well.+ """+ if imatrix_file is True:+ name = "imatrix_unsloth.gguf" # the upstream imatrix_unsloth.gguf_file, renamed+ elif isinstance(imatrix_file, (str, os.PathLike)):+ base = os.path.basename(os.fspath(imatrix_file))+ if not base.endswith(".gguf_file"):+ return None+ name = base[: -len(".gguf_file")] + ".gguf"+ else:+ return None+ return Path(model_dir) / name++def _compressed_export_supported():"""True if the installed unsloth build can do FP8/NVFP4 compressed-tensors export."""try:@@ -1023,7 +1042,6 @@ class ExportBackend:imatrix_kw = {"imatrix_file": imatrix_file} if imatrix_file is not None else {}output_path: Optional[str] = None- model_tmp_to_cleanup: Optional[str] = Nonetry:# Normalize to a lowercased list so multiple quants come from one model load.if isinstance(quantization_method, (list, tuple)):@@ -1065,99 +1083,75 @@ class ExportBackend:# On WSL, patch out sudo check before llama.cpp build_apply_wsl_sudo_patch()- # convert_to_gguf writes output relative to cwd (repo root);- # snapshot existing .gguf so we can diff and relocate afterwards.- cwd = os.getcwd()- pre_existing_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf")))-- pre_existing_subs = {d.name for d in Path(abs_save_dir).iterdir() if d.is_dir()}-- # Avoid clobbering an existing user-owned model/ directory.- import uuid-- _model_tmp = os.path.join(abs_save_dir, f"_tmp_model_{uuid.uuid4().hex[:8]}")- model_tmp_to_cleanup = _model_tmp- _gguf_result = self.current_model.save_pretrained_gguf(- _model_tmp,- self.current_tokenizer,- quantization_method = quant_method,- **imatrix_kw,- )-- # Trust what unsloth reports over guessing: the heuristics below only- # check cwd, new subdirs of the save dir, and the checkpoint sibling,- # so anything written elsewhere was silently lost (#7897). Relocate- # first, before the flatten pass rmtree's the temp dir it lives in.- for src in _reported_gguf_files(_gguf_result) or []:- dest = os.path.join(abs_save_dir, os.path.basename(src))- if os.path.abspath(src) == os.path.abspath(dest):- continue- try:- shutil.move(src, dest)- except FileNotFoundError:- continue- logger.info(- f"Relocated GGUF (reported by unsloth): "- f"{os.path.basename(src)} → {abs_save_dir}/"+ # Keep all intermediates under an export-owned root.+ model_tmp_root = tempfile.mkdtemp(prefix = "_tmp_model_", dir = abs_save_dir)+ model_tmp_path = Path(model_tmp_root)+ _model_tmp = os.path.join(model_tmp_root, "model")+ # Needed by the cleanup below too, so resolve it before anything can raise.+ imatrix_path = _materialized_imatrix_path(_model_tmp, imatrix_file)+ try:+ result = self.current_model.save_pretrained_gguf(+ _model_tmp,+ self.current_tokenizer,+ quantization_method = quant_method,+ **imatrix_kw,)- # The Modelfile lands in the temp *_gguf dir, which the flatten pass- # deletes after moving only *.gguf.- _modelfile = (- _gguf_result.get("modelfile_location")- if isinstance(_gguf_result, dict)- else None- )- if (- isinstance(_modelfile, str)- and os.path.isfile(_modelfile)- and os.path.dirname(os.path.abspath(_modelfile)) != abs_save_dir- ):- try:- shutil.move(_modelfile, os.path.join(abs_save_dir, "Modelfile"))- logger.info(f"Relocated Modelfile → {abs_save_dir}/")- except OSError:- pass-- # Relocate the .gguf that convert_to_gguf wrote to cwd (repo root).- new_ggufs = set(glob.glob(os.path.join(cwd, "*.gguf"))) - pre_existing_ggufs- for src in sorted(new_ggufs):- dest = os.path.join(abs_save_dir, os.path.basename(src))- shutil.move(src, dest)- logger.info(f"Relocated GGUF: {os.path.basename(src)} → {abs_save_dir}/")-- # Flatten GGUF files from subdirs created during this export.- for sub in list(Path(abs_save_dir).iterdir()):- if not sub.is_dir():- continue- if sub.name in pre_existing_subs:- continue- # rglob: the rmtree below is unconditional, so a GGUF one level- # deeper (sharded output) would otherwise be destroyed.- for src in sorted(sub.rglob("*.gguf")):+ # Scan only the owned root; exact reported paths cover external outputs.+ reported = result if isinstance(result, dict) else {}+ produced = {p for p in model_tmp_path.rglob("*.gguf") if p.is_file()}+ produced.update(Path(f) for f in _reported_gguf_files(result) or [])+ produced = {p for p in produced if p != imatrix_path}+ modelfiles = {p for p in model_tmp_path.rglob("Modelfile") if p.is_file()}+ reported_modelfile = reported.get("modelfile_location")+ if reported_modelfile and Path(reported_modelfile).is_file():+ modelfiles.add(Path(os.path.abspath(os.fspath(reported_modelfile))))++ relocated_ggufs = []+ for src in sorted(produced):+ if src.is_symlink():+ raise RuntimeError(+ f"GGUF conversion produced a symlink, refusing to relocate it: {src}"+ )dest = os.path.join(abs_save_dir, src.name)shutil.move(str(src), dest)+ relocated_ggufs.append(dest)logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/")- shutil.rmtree(str(sub), ignore_errors = True)- logger.info(f"Cleaned up subdirectory: {sub.name}")-- # For non-PEFT models, save_pretrained_gguf leaves a *_gguf dir at- # the checkpoint path; relocate its GGUFs and clean it up.- if self.current_checkpoint:- ckpt = Path(self.current_checkpoint)- gguf_dir = ckpt.parent / f"{ckpt.name}_gguf"- if gguf_dir.is_dir() and gguf_dir.resolve() != Path(abs_save_dir).resolve():- for src in gguf_dir.glob("*.gguf"):- dest = os.path.join(abs_save_dir, src.name)- shutil.move(str(src), dest)- logger.info(f"Relocated GGUF: {src.name} → {abs_save_dir}/")- # Also relocate Ollama Modelfile if present- modelfile = gguf_dir / "Modelfile"- if modelfile.is_file():+ if not relocated_ggufs:+ raise RuntimeError(+ "GGUF conversion produced no files: no .gguf outputs for "+ f"{abs_save_dir}"+ )++ if modelfiles:+ modelfile = sorted(modelfiles)[0]+ if modelfile.is_symlink():+ raise RuntimeError(+ "GGUF conversion produced a symlinked Modelfile, "+ f"refusing to relocate it: {modelfile}"+ )+ # Optional artifact: unsloth generates it best-effort, so a locked or+ # read-only destination must not fail an export whose GGUFs all landed.+ try:shutil.move(str(modelfile), os.path.join(abs_save_dir, "Modelfile"))logger.info(f"Relocated Modelfile → {abs_save_dir}/")- shutil.rmtree(str(gguf_dir), ignore_errors = True)- logger.info(f"Cleaned up intermediate GGUF dir: {gguf_dir}")+ except OSError as exception:+ logger.warning(f"Could not relocate the Modelfile: {exception}")+ finally:+ # Preserve any GGUF that could not be relocated. The imatrix is an input,+ # so counting it would retain the merged checkpoint on every such export.+ unrelocated = []+ if model_tmp_path.is_dir():+ unrelocated = sorted(+ str(p) for p in model_tmp_path.rglob("*.gguf") if p != imatrix_path+ )+ if unrelocated:+ logger.error(+ "Kept GGUF files that could not be relocated: %s",+ ", ".join(unrelocated),+ )+ else:+ shutil.rmtree(model_tmp_root, ignore_errors = True)# iterdir, not glob.glob: glob hides dot-leading names, so an empty# model stem's ".Q4_K_M.gguf" got reported as "(none)".@@ -1173,7 +1167,7 @@ class ExportBackend:)if not final_ggufs:# Reporting success over an empty directory is what hid #7897.- shutil.rmtree(model_tmp_to_cleanup, ignore_errors = True)+ # The owned temp root is already gone: the finally above drops it.return (False,f"GGUF conversion reported success but wrote no .gguf file to "@@ -1213,8 +1207,6 @@ class ExportBackend:)except Exception as e:- if model_tmp_to_cleanup:- shutil.rmtree(model_tmp_to_cleanup, ignore_errors = True)logger.error(f"Error exporting GGUF model: {e}")import tracebackdiff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.pyindex d0f586e5c23..1687ffcfccc 100644--- a/studio/backend/tests/test_export_absolute_paths.py+++ b/studio/backend/tests/test_export_absolute_paths.py@@ -3,6 +3,7 @@import importlib.machineryimport importlib.util+import shutilimport sysimport typesfrom pathlib import Path@@ -285,7 +286,7 @@ def _install_export_backend_stubs(monkeypatch):utils_paths.resolve_output_dir = lambda value = None: Path(value or "outputs")-def test_gguf_export_cleans_temp_dir_when_post_processing_fails(tmp_path, monkeypatch):+def test_gguf_export_keeps_a_gguf_it_could_not_relocate(tmp_path, monkeypatch):_install_export_backend_stubs(monkeypatch)export_mod = _load_module("test_core_export_backend", "core/export/export.py", monkeypatch)@@ -302,9 +303,11 @@ def test_gguf_export_cleans_temp_dir_when_post_processing_fails(tmp_path, monkeyclass _Model:def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):- Path(model_save_path).mkdir(parents = True)+ Path(model_save_path).mkdir(parents = True, exist_ok = True)(Path(model_save_path) / "model.safetensors").write_bytes(b"weights")- (cwd / "converted.gguf").write_bytes(b"gguf")+ output_dir = Path(f"{model_save_path}_gguf")+ output_dir.mkdir(parents = True, exist_ok = True)+ (output_dir / "converted.gguf").write_bytes(b"gguf")backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)backend.current_model = _Model()@@ -316,6 +319,282 @@ def test_gguf_export_cleans_temp_dir_when_post_processing_fails(tmp_path, monkeyassert success is Falseassert "move failed" in messageassert output_path is None+ # Preserve a completed GGUF when relocation fails.+ roots = list(save_dir.glob("_tmp_model_*"))+ assert len(roots) == 1+ assert (roots[0] / "model_gguf" / "converted.gguf").read_bytes() == b"gguf"+++def test_gguf_export_fails_when_owned_output_has_no_gguf(tmp_path, monkeypatch):+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_empty_owned_output", "core/export/export.py", monkeypatch+ )++ save_dir = tmp_path / "export"+ checkpoint_gguf = tmp_path / "checkpoint_gguf"+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ checkpoint_gguf.mkdir()+ (checkpoint_gguf / "misdirected.gguf").write_bytes(b"gguf")++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = str(tmp_path / "checkpoint")++ success, message, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")++ assert success is False+ assert "produced no files" in message+ assert output_path is None+ assert (checkpoint_gguf / "misdirected.gguf").read_bytes() == b"gguf"+ assert not (save_dir / "export_metadata.json").exists()+ assert list(save_dir.glob("_tmp_model_*")) == []+++def _require_undeletable_dir_support(tmp_path):+ """Skip where directory mode bits cannot make cleanup fail."""+ probe = tmp_path / "_perm_probe"+ victim = probe / "victim"+ probe.mkdir()+ victim.write_bytes(b"x")+ probe.chmod(0o500)+ try:+ victim.unlink()+ except OSError:+ return+ finally:+ probe.chmod(0o700)+ shutil.rmtree(probe, ignore_errors = True)+ pytest.skip("this platform allows deleting files from a read-only directory")+++def test_gguf_export_survives_real_owned_temp_cleanup_failure(tmp_path, monkeypatch):+ _require_undeletable_dir_support(tmp_path)+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_cleanup_failure", "core/export/export.py", monkeypatch+ )++ save_dir = tmp_path / "export"+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)+ locked_dirs = []++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output_dir = Path(f"{model_save_path}_gguf")+ output_dir.mkdir(parents = True, exist_ok = True)+ (output_dir / "converted.gguf").write_bytes(b"gguf")+ # A read-only model directory makes the real cleanup fail.+ merged = Path(model_save_path)+ merged.mkdir()+ (merged / "model.safetensors").write_bytes(b"weights")+ merged.chmod(0o500)+ locked_dirs.append(merged)++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ try:+ success, message, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")+ finally:+ for locked in locked_dirs:+ locked.chmod(0o700)++ assert success is True, message+ assert output_path == str(save_dir.resolve())+ assert (save_dir / "converted.gguf").read_bytes() == b"gguf"+ # The removable output is gone, but the locked model directory remains.+ assert len(locked_dirs) == 1+ model_tmp_root = locked_dirs[0].parent+ assert not (model_tmp_root / "model_gguf").exists()+ assert (locked_dirs[0] / "model.safetensors").read_bytes() == b"weights"+ assert list(save_dir.glob("_tmp_model_*")) == [model_tmp_root]+++# Both PEFT and non-PEFT exports must preserve an existing checkpoint sibling.[email protected]("merges_into_model_dir", [False, True], ids = ["non_peft", "peft"])+def test_gguf_export_preserves_unowned_paths(tmp_path, monkeypatch, merges_into_model_dir):+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_owned_temp", "core/export/export.py", monkeypatch+ )++ cwd = tmp_path / "cwd"+ save_dir = tmp_path / "export"+ checkpoint = tmp_path / "Qwen3-8B"+ checkpoint_gguf = tmp_path / "Qwen3-8B_gguf"+ cwd.mkdir()+ checkpoint.mkdir()+ checkpoint_gguf.mkdir()+ notes = checkpoint_gguf / "notes.txt"+ imatrix = checkpoint_gguf / "imatrix.dat"+ old_gguf = checkpoint_gguf / "old.Q4_K_M.gguf"+ old_modelfile = checkpoint_gguf / "Modelfile"+ concurrent_dir = save_dir / "user-created"+ concurrent_cwd_gguf = cwd / "unrelated.gguf"+ notes.write_text("keep", encoding = "utf-8")+ imatrix.write_bytes(b"imatrix")+ old_gguf.write_bytes(b"old")+ old_modelfile.write_text("FROM old.Q4_K_M.gguf", encoding = "utf-8")+ monkeypatch.chdir(cwd)+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ if merges_into_model_dir:+ merged = Path(model_save_path)+ merged.mkdir()+ (merged / "model.safetensors").write_bytes(b"merged")+ output_dir = Path(f"{model_save_path}_gguf")+ output_dir.mkdir(parents = True, exist_ok = True)+ (output_dir / "new.Q4_K_M.gguf").write_bytes(b"new")+ (output_dir / "Modelfile").write_text("FROM new.Q4_K_M.gguf", encoding = "utf-8")+ concurrent_dir.mkdir()+ (concurrent_dir / "notes.txt").write_text("keep", encoding = "utf-8")+ concurrent_cwd_gguf.write_bytes(b"unrelated")+ # Reported files may also appear in the owned-root scan.+ return {+ "gguf_directory": str(output_dir),+ "gguf_files": [str(output_dir / "new.Q4_K_M.gguf")],+ "modelfile_location": str(output_dir / "Modelfile"),+ }++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = str(checkpoint)++ success, _, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")++ assert success is True+ assert output_path == str(save_dir.resolve())+ assert (save_dir / "new.Q4_K_M.gguf").read_bytes() == b"new"+ assert (save_dir / "Modelfile").read_text(encoding = "utf-8") == "FROM new.Q4_K_M.gguf"+ assert not (save_dir / "old.Q4_K_M.gguf").exists()+ assert notes.read_text(encoding = "utf-8") == "keep"+ assert imatrix.read_bytes() == b"imatrix"+ assert old_gguf.read_bytes() == b"old"+ assert old_modelfile.read_text(encoding = "utf-8") == "FROM old.Q4_K_M.gguf"+ assert (concurrent_dir / "notes.txt").read_text(encoding = "utf-8") == "keep"+ assert concurrent_cwd_gguf.read_bytes() == b"unrelated"+ assert list(save_dir.glob("_tmp_model_*")) == []+++def test_gguf_export_relocates_gguf_written_into_the_model_path(tmp_path, monkeypatch):+ # MLX writes into the save path and returns no manifest.+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_in_place_output", "core/export/export.py", monkeypatch+ )++ save_dir = tmp_path / "export"+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output_dir = Path(model_save_path)+ output_dir.mkdir(parents = True, exist_ok = True)+ (output_dir / "Qwen3-8B.Q4_K_M.gguf").write_bytes(b"converted")++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = str(tmp_path / "Qwen3-8B")++ success, message, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")++ assert success is True, message+ assert output_path == str(save_dir.resolve())+ assert (save_dir / "Qwen3-8B.Q4_K_M.gguf").read_bytes() == b"converted"+ assert list(save_dir.glob("_tmp_model_*")) == []+++def test_gguf_export_rejects_symlink_inside_its_owned_temp_tree(tmp_path, monkeypatch):+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_symlinked_output", "core/export/export.py", monkeypatch+ )++ save_dir = tmp_path / "export"+ user_owned_gguf = tmp_path / "user-owned.gguf"+ user_owned_gguf.write_bytes(b"keep")+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ output_dir = Path(f"{model_save_path}_gguf")+ output_dir.mkdir(parents = True)+ link = output_dir / "converted.gguf"+ try:+ link.symlink_to(user_owned_gguf)+ except OSError as exception:+ pytest.skip(f"symlinks unavailable: {exception}")+ return {"gguf_files": [str(link)]}++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = None++ success, message, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")++ assert success is False+ assert "symlink" in message+ assert output_path is None+ assert user_owned_gguf.read_bytes() == b"keep"+ assert not (save_dir / "converted.gguf").exists()+ roots = list(save_dir.glob("_tmp_model_*"))+ assert len(roots) == 1+ assert (roots[0] / "model_gguf" / "converted.gguf").is_symlink()+++def test_gguf_export_relocates_only_reported_files_from_outside_the_owned_root(+ tmp_path, monkeypatch+):+ # Relocate reported files without scanning their unowned directory.+ _install_export_backend_stubs(monkeypatch)+ export_mod = _load_module(+ "test_core_export_backend_unowned_report", "core/export/export.py", monkeypatch+ )++ save_dir = tmp_path / "export"+ checkpoint_gguf = tmp_path / "Qwen3-8B_gguf"+ checkpoint_gguf.mkdir()+ (checkpoint_gguf / "notes.txt").write_text("keep", encoding = "utf-8")+ (checkpoint_gguf / "old.Q8_0.gguf").write_bytes(b"old")+ monkeypatch.setattr(export_mod, "resolve_export_write_dir", lambda _value: save_dir)++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ (checkpoint_gguf / "new.Q4_K_M.gguf").write_bytes(b"new")+ (checkpoint_gguf / "Modelfile").write_text("FROM new.Q4_K_M.gguf", encoding = "utf-8")+ return {+ "gguf_directory": str(checkpoint_gguf),+ "gguf_files": [str(checkpoint_gguf / "new.Q4_K_M.gguf")],+ "modelfile_location": str(checkpoint_gguf / "Modelfile"),+ }++ backend = export_mod.ExportBackend.__new__(export_mod.ExportBackend)+ backend.current_model = _Model()+ backend.current_tokenizer = object()+ backend.current_checkpoint = str(tmp_path / "Qwen3-8B")++ success, message, output_path = backend.export_gguf(str(save_dir), "Q4_K_M")++ assert success is True, message+ assert output_path == str(save_dir.resolve())+ assert (save_dir / "new.Q4_K_M.gguf").read_bytes() == b"new"+ assert (save_dir / "Modelfile").read_text(encoding = "utf-8") == "FROM new.Q4_K_M.gguf"+ assert not (save_dir / "old.Q8_0.gguf").exists()+ assert checkpoint_gguf.is_dir()+ assert (checkpoint_gguf / "notes.txt").read_text(encoding = "utf-8") == "keep"+ assert (checkpoint_gguf / "old.Q8_0.gguf").read_bytes() == b"old"assert list(save_dir.glob("_tmp_model_*")) == []diff --git a/studio/backend/tests/test_export_gguf_discovery.py b/studio/backend/tests/test_export_gguf_discovery.pyindex bfddd294686..a8be7d8343a 100644--- a/studio/backend/tests/test_export_gguf_discovery.py+++ b/studio/backend/tests/test_export_gguf_discovery.py@@ -13,6 +13,7 @@ Reuses the harness in test_export_absolute_paths.py.from __future__ import annotations+import osimport sysfrom pathlib import Path@@ -286,10 +287,7 @@ def test_modelfile_is_relocated_not_deleted(monkeypatch, tmp_path):def test_stale_gguf_alone_does_not_fake_a_successful_export(monkeypatch, tmp_path):- """Documents current behaviour: the listing is directory-based, so a leftover- GGUF in the destination does count as success. Asserted so a future change is- deliberate.- """+ """A leftover destination artifact must not hide a conversion with no output."""class _Model:def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):@@ -300,8 +298,10 @@ def test_stale_gguf_alone_does_not_fake_a_successful_export(monkeypatch, tmp_patsave_dir.mkdir(parents = True, exist_ok = True)_gguf(save_dir / "OldRun.Q4_K_M.gguf")- success, _message, _p = backend.export_gguf(str(save_dir), "q5_k_m")- assert success is True+ success, message, output_path = backend.export_gguf(str(save_dir), "q5_k_m")+ assert success is False+ assert "produced no files" in message+ assert output_path is Nonedef test_cleanup_failure_does_not_lose_reported_files(monkeypatch, tmp_path):@@ -319,3 +319,108 @@ def test_cleanup_failure_does_not_lose_reported_files(monkeypatch, tmp_path):success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m")assert success is True, messageassert (save_dir / "MyModel.Q5_K_M.gguf").is_file()+++def test_materialized_imatrix_is_not_exported_as_a_model(monkeypatch, tmp_path):+ """unsloth copies a *.gguf_file imatrix next to the model as *.gguf; it is not an output."""++ class _Model:+ def save_pretrained_gguf(+ self,+ model_save_path,+ tokenizer,+ quantization_method,+ imatrix_file = None,+ ):+ # _materialize_imatrix copies into the model dir, renaming .gguf_file -> .gguf.+ _gguf(Path(model_save_path) / "imatrix_unsloth.gguf", b"IMATRIX")+ quant = _gguf(Path(f"{model_save_path}_gguf") / "MyModel.Q5_K_M.gguf")+ return {"gguf_files": [str(quant)]}++ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())++ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m", imatrix_file = True)++ assert success is True, message+ assert (save_dir / "MyModel.Q5_K_M.gguf").is_file()+ assert not (save_dir / "imatrix_unsloth.gguf").exists()+++def test_materialized_imatrix_does_not_block_temp_root_cleanup(monkeypatch, tmp_path):+ """The imatrix is not an unrelocated output, so it must not retain the merged checkpoint."""++ class _Model:+ def save_pretrained_gguf(+ self,+ model_save_path,+ tokenizer,+ quantization_method,+ imatrix_file = None,+ ):+ merged = Path(model_save_path)+ merged.mkdir(parents = True, exist_ok = True)+ (merged / "model.safetensors").write_bytes(b"a very large merged checkpoint")+ _gguf(merged / "imatrix_unsloth.gguf", b"IMATRIX")+ quant = _gguf(Path(f"{model_save_path}_gguf") / "MyModel.Q5_K_M.gguf")+ return {"gguf_files": [str(quant)]}++ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())++ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m", imatrix_file = True)++ assert success is True, message+ assert (save_dir / "MyModel.Q5_K_M.gguf").is_file()+ assert list(save_dir.glob("_tmp_model_*")) == []+++def test_imatrix_named_like_the_output_does_not_suppress_the_real_gguf(monkeypatch, tmp_path):+ """An imatrix whose derived name collides with the quant must not drop the quant too."""+ imatrix_src = _gguf(tmp_path / "MyModel.Q5_K_M.gguf_file", b"IMATRIX")++ class _Model:+ def save_pretrained_gguf(+ self,+ model_save_path,+ tokenizer,+ quantization_method,+ imatrix_file = None,+ ):+ _gguf(Path(model_save_path) / "MyModel.Q5_K_M.gguf", b"IMATRIX")+ quant = _gguf(Path(f"{model_save_path}_gguf") / "MyModel.Q5_K_M.gguf")+ return {"gguf_files": [str(quant)]}++ _m, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())++ success, message, _p = backend.export_gguf(+ str(save_dir), "q5_k_m", imatrix_file = str(imatrix_src)+ )++ assert success is True, message+ assert (save_dir / "MyModel.Q5_K_M.gguf").read_bytes() == b"GGUF"+ assert list(save_dir.glob("_tmp_model_*")) == []+++def test_modelfile_relocation_failure_does_not_fail_the_export(monkeypatch, tmp_path):+ """The Modelfile is optional, so a locked destination must not sink placed GGUFs."""++ class _Model:+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):+ out = Path(f"{model_save_path}_gguf")+ _gguf(out / "MyModel.Q5_K_M.gguf")+ (out / "Modelfile").write_text("FROM MyModel.Q5_K_M.gguf", encoding = "utf-8")++ export_mod, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, _Model())+ real_move = export_mod.shutil.move++ def _move(src, dst, *args, **kwargs):+ if os.path.basename(str(dst)) == "Modelfile":+ raise PermissionError("destination Modelfile is locked")+ return real_move(src, dst, *args, **kwargs)++ monkeypatch.setattr(export_mod.shutil, "move", _move)++ success, message, _p = backend.export_gguf(str(save_dir), "q5_k_m")++ assert success is True, message+ assert (save_dir / "MyModel.Q5_K_M.gguf").is_file()+ assert not (save_dir / "Modelfile").exists()diff --git a/tests/saving/test_export_dispatch.py b/tests/saving/test_export_dispatch.pyindex ad6d51e0b76..656d4ffbc5b 100644--- a/tests/saving/test_export_dispatch.py+++ b/tests/saving/test_export_dispatch.py@@ -9,6 +9,7 @@ regressions that pure AST checks cannot (e.g. wrong scheme/suffix/outtype passedfrom __future__ import annotationsimport inspect+import osimport pytest@@ -23,6 +24,16 @@ class _FakeModel:)()+class _FakeTokenizer:+ chat_template = None++ def __init__(self):+ self.saved_to = []++ def save_pretrained(self, path):+ self.saved_to.append(path)++# -- merged_* -> compressed-tensors dispatch ---------------------------------------------@@ -128,6 +139,57 @@ def test_gguf_lora_push_to_hub_is_rejected(tmp_path):)[email protected]("trailing_separator", [False, True])+def test_non_peft_gguf_uses_checkpoint_as_input_not_output(+ monkeypatch, tmp_path, trailing_separator+):+ checkpoint = tmp_path / "checkpoint"+ checkpoint.mkdir()+ requested = tmp_path / "export" / "model"+ requested.parent.mkdir()+ model = _FakeModel()+ model.config = type(+ "cfg",+ (),+ {+ "_name_or_path": str(checkpoint),+ "architectures": ["LlamaForCausalLM"],+ "model_type": "llama",+ },+ )()+ tokenizer = _FakeTokenizer()+ seen = {}++ monkeypatch.setattr(save_mod, "_is_vlm", lambda _model: False)+ monkeypatch.setattr(save_mod, "_is_gpt_oss", lambda _model: False)+ monkeypatch.setattr(save_mod, "fix_tokenizer_bos_token", lambda _tokenizer: (False, None))+ monkeypatch.setattr(save_mod, "_resolve_imatrix_file", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(save_mod, "dtype_from_config", lambda _config: save_mod.torch.float16)+ monkeypatch.setattr(save_mod, "create_ollama_modelfile", lambda *_args, **_kwargs: None)++ def _save_to_gguf(**kwargs):+ seen.update(kwargs)+ output = tmp_path / "export" / "model_gguf" / "model.Q8_0.gguf"+ output.parent.mkdir()+ output.write_bytes(b"GGUF")+ return [str(output)], True, False++ monkeypatch.setattr(save_mod, "save_to_gguf", _save_to_gguf)++ requested_arg = f"{requested}{os.sep}" if trailing_separator else str(requested)+ result = save_mod.unsloth_save_pretrained_gguf(+ model,+ requested_arg,+ tokenizer = tokenizer,+ quantization_method = "q8_0",+ )++ assert seen["model_directory"] == str(checkpoint)+ assert seen["gguf_directory"] == f"{requested}_gguf"+ assert result["gguf_directory"] == f"{requested}_gguf"+ assert tokenizer.saved_to == [str(checkpoint)]++# The above rejection points users at push_to_hub_gguf(save_method='lora'), so that path# has to work; it is only ever exercised here.diff --git a/tests/saving/test_gguf_single_pass_export.py b/tests/saving/test_gguf_single_pass_export.pyindex 296fb0d8cae..df803972a91 100644--- a/tests/saving/test_gguf_single_pass_export.py+++ b/tests/saving/test_gguf_single_pass_export.py@@ -145,6 +145,21 @@ def test_fast_quantized_alias_is_single_pass(monkeypatch, tmp_path):assert h.quantize_calls == []+def test_explicit_gguf_directory_does_not_reuse_model_sibling(monkeypatch, tmp_path):+ h = _Harness(monkeypatch, tmp_path)+ model_sibling = tmp_path / "model_dir_gguf"+ model_sibling.mkdir()+ notes = model_sibling / "notes.txt"+ notes.write_text("keep", encoding = "utf-8")+ output_dir = tmp_path / "owned_output"++ locations, _, _ = _run(tmp_path, ["q8_0"], gguf_directory = output_dir)++ assert [os.path.dirname(path) for path in locations] == [str(output_dir)]+ assert notes.read_text(encoding = "utf-8") == "keep"+ assert list(model_sibling.glob("*.gguf")) == []++def test_k_quant_keeps_two_pass(monkeypatch, tmp_path):h = _Harness(monkeypatch, tmp_path)locations, want_full_precision, _ = _run(tmp_path, ["q4_k_m"])diff --git a/unsloth/save.py b/unsloth/save.pyindex 33ec0badbe9..31e0049e85e 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -1864,12 +1864,14 @@ def save_to_gguf(is_vlm: bool = False,is_gpt_oss: bool = False,imatrix = None,+ gguf_directory: Optional[Union[str, os.PathLike]] = None,):"""Orchestrates the complete GGUF conversion process.Handles installation, conversion, and quantization.`imatrix` is a local importance-matrix path (already resolved); it is forwarded tollama-quantize and is required for the IQ low-bit quant types.+ `gguf_directory` can place outputs separately from the model input directory."""# print_output True only if UNSLOTH_ENABLE_LOGGING=1if os.environ.get("UNSLOTH_ENABLE_LOGGING", "0") == "1":@@ -2044,7 +2046,10 @@ def save_to_gguf()# Move initial GGUF files into a dedicated _gguf directory- gguf_directory = f"{model_directory}_gguf"+ 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:@@ -2999,6 +3004,7 @@ def unsloth_save_pretrained_gguf(raise ValueError("Unsloth: Saving to GGUF must have a tokenizer.")if isinstance(tokenizer, (PreTrainedTokenizerBase, ProcessorMixin)):tokenizer = patch_saving_functions(tokenizer)+ save_directory = os.path.normpath(os.fspath(save_directory))# save_method="lora" exports the adapter itself as a GGUF LoRA (not a merged model).if save_method is not None and str(save_method).lower() == "lora":@@ -3079,6 +3085,9 @@ def unsloth_save_pretrained_gguf(del arguments["is_processor"]del arguments["imatrix_file"] # only used by the gguf quantize step, not the 16bit merge+ # Preserve the requested output before reusing a non-PEFT checkpoint as input.+ gguf_directory = f"{save_directory}_gguf"+# Step 3: Fix tokenizer BOS token if neededif is_processor:fix_bos_token, old_chat_template = fix_tokenizer_bos_token(tokenizer.tokenizer)@@ -3207,6 +3216,7 @@ def unsloth_save_pretrained_gguf(is_vlm = is_vlm, # Pass VLM flagis_gpt_oss = is_gpt_oss, # Pass gpt_oss Flagimatrix = imatrix_path,+ gguf_directory = gguf_directory,)except Exception as e:if _gguf_child_was_oom_killed(e):@@ -3230,7 +3240,6 @@ def unsloth_save_pretrained_gguf(raise RuntimeError(f"Unsloth: GGUF conversion failed: {e}") from e# Step 9: Create Ollama modelfile- gguf_directory = f"{save_directory}_gguf"modelfile_location = Noneollama_success = Falseif all_file_locations: